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-12-29 17:06:30 -0800 (Mon, 29 Dec 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
  public static final String DELETEDMESSAGE = "The object with the PID has been deleted from the node.";
97
  
98
  private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
99

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

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

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

    
152
  /**
153
   * This method provides a lighter weight mechanism than 
154
   * getSystemMetadata() for a client to determine basic 
155
   * properties of the referenced object.
156
   * 
157
   * @param session - the Session object containing the credentials for the Subject
158
   * @param pid - the identifier of the object to be described
159
   * 
160
   * @return describeResponse - A set of values providing a basic description 
161
   *                            of the object.
162
   * 
163
   * @throws InvalidToken
164
   * @throws ServiceFailure
165
   * @throws NotAuthorized
166
   * @throws NotFound
167
   * @throws NotImplemented
168
   * @throws InvalidRequest
169
   */
170
  public DescribeResponse describe(Session session, Identifier pid) 
171
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
172
      
173
      String serviceFailureCode = "4931";
174
      Identifier sid = getPIDForSID(pid, serviceFailureCode);
175
      if(sid != null) {
176
          pid = sid;
177
      }
178

    
179
    // get system metadata and construct the describe response
180
      SystemMetadata sysmeta = getSystemMetadata(session, pid);
181
      DescribeResponse describeResponse = 
182
      	new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(), 
183
      			sysmeta.getDateSysMetadataModified(),
184
      			sysmeta.getChecksum(), sysmeta.getSerialVersion());
185

    
186
      return describeResponse;
187

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

    
209
      String localId = null;
210
      if (session == null) {
211
      	throw new InvalidToken("1330", "No session has been provided");
212
      }
213
      // just for logging purposes
214
      String username = session.getSubject().getValue();
215

    
216
      // do we have a valid pid?
217
      if (pid == null || pid.getValue().trim().equals("")) {
218
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
219
      }
220

    
221
      // check for the existing identifier
222
      try {
223
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
224
      } catch (McdbDocNotFoundException e) {
225
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
226
      } catch (SQLException e) {
227
          throw new ServiceFailure("1350", "The object with the provided " + "identifier "+pid.getValue()+" couldn't be identified since "+e.getMessage());
228
      }
229
      
230
      try {
231
          // delete the document, as admin
232
          DocumentImpl.delete(localId, null, null, null, true);
233
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
234

    
235
          // archive it
236
          // DocumentImpl.delete() now sets this
237
          // see https://redmine.dataone.org/issues/3406
238
//          SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
239
//          sysMeta.setArchived(true);
240
//          sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
241
//          HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
242
          
243
      } catch (McdbDocNotFoundException e) {
244
          throw new NotFound("1340", "The provided identifier was invalid.");
245

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

    
249
      } catch (InsufficientKarmaException e) {
250
          if ( logMetacat.isDebugEnabled() ) {
251
              e.printStackTrace();
252
          }
253
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
254
      
255
      } catch (Exception e) { // for some reason DocumentImpl throws a general Exception
256
          throw new ServiceFailure("1350", "There was a problem deleting the object." + "The error message was: " + e.getMessage());
257
      }
258

    
259
      return pid;
260
  }
261
  
262
  /**
263
   * Low level, "are you alive" operation. A valid ping response is 
264
   * indicated by a HTTP status of 200.
265
   * 
266
   * @return true if the service is alive
267
   * 
268
   * @throws NotImplemented
269
   * @throws ServiceFailure
270
   * @throws InsufficientResources
271
   */
272
  public Date ping() 
273
      throws NotImplemented, ServiceFailure, InsufficientResources {
274

    
275
      // test if we can get a database connection
276
      int serialNumber = -1;
277
      DBConnection dbConn = null;
278
      try {
279
          dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
280
          serialNumber = dbConn.getCheckOutSerialNumber();
281
      } catch (SQLException e) {
282
      	ServiceFailure sf = new ServiceFailure("", e.getMessage());
283
      	sf.initCause(e);
284
          throw sf;
285
      } finally {
286
          // Return the database connection
287
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
288
      }
289

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

    
322
    Identifier resultPid = null;
323
    String localId = null;
324
    boolean allowed = false;
325
    
326
    // check for null session
327
    if (session == null) {
328
    	throw new InvalidToken("4894", "Session is required to WRITE to the Node.");
329
    }
330
    Subject subject = session.getSubject();
331

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

    
360
    logMetacat.debug("Checking if identifier exists: " + pid.getValue());
361
    // Check that the identifier does not already exist
362
    boolean idExists = false;
363
    try {
364
        idExists = IdentifierManager.getInstance().identifierExists(pid.getValue());
365
    } catch (SQLException e) {
366
        throw new ServiceFailure("1190", 
367
                                "The requested identifier " + pid.getValue() +
368
                                " couldn't be determined if it is unique since : "+e.getMessage());
369
    }
370
    if (idExists) {
371
	    	throw new IdentifierNotUnique("1120", 
372
			          "The requested identifier " + pid.getValue() +
373
			          " is already used by another object and" +
374
			          "therefore can not be used for this object. Clients should choose" +
375
			          "a new identifier that is unique and retry the operation or " +
376
			          "use CN.reserveIdentifier() to reserve one.");
377
    	
378
    }
379
    
380
    // verify the sid in the system metadata
381
    Identifier sid = sysmeta.getSeriesId();
382
    if(sid != null) {
383
        if (!isValidIdentifier(sid)) {
384
            throw new InvalidSystemMetadata("1180", "The provided series id is invalid.");
385
        }
386
        try {
387
            idExists = IdentifierManager.getInstance().identifierExists(sid.getValue());
388
        } catch (SQLException e) {
389
            throw new ServiceFailure("1190", 
390
                                    "The series identifier " + sid.getValue() +
391
                                    " in the system metadata couldn't be determined if it is unique since : "+e.getMessage());
392
        }
393
        if (idExists) {
394
                throw new InvalidSystemMetadata("1180", 
395
                          "The series identifier " + sid.getValue() +
396
                          " is already used by another object and" +
397
                          "therefore can not be used for this object. Clients should choose" +
398
                          "a new identifier that is unique and retry the operation or " +
399
                          "use CN.reserveIdentifier() to reserve one.");
400
            
401
        }
402
    }
403
    
404
    // TODO: this probably needs to be refined more
405
    try {
406
      allowed = isAuthorized(session, pid, Permission.WRITE);
407
            
408
    } catch (NotFound e) {
409
      // The identifier doesn't exist, writing should be fine.
410
      allowed = true;
411
    }
412
    
413
    // verify checksum, only if we can reset the inputstream
414
    if (object.markSupported()) {
415
        logMetacat.debug("Checking checksum for: " + pid.getValue());
416
	    String checksumAlgorithm = sysmeta.getChecksum().getAlgorithm();
417
	    String checksumValue = sysmeta.getChecksum().getValue();
418
	    try {
419
			String computedChecksumValue = ChecksumUtil.checksum(object, checksumAlgorithm).getValue();
420
			// it's very important that we don't consume the stream
421
			object.reset();
422
			if (!computedChecksumValue.equals(checksumValue)) {
423
			    logMetacat.error("Checksum for " + pid.getValue() + " does not match system metadata, computed = " + computedChecksumValue );
424
				throw new InvalidSystemMetadata("4896", "Checksum given does not match that of the object");
425
			}
426
		} catch (Exception e) {
427
			String msg = "Error verifying checksum values";
428
	      	logMetacat.error(msg, e);
429
	        throw new ServiceFailure("1190", msg + ": " + e.getMessage());
430
		}
431
    } else {
432
    	logMetacat.warn("mark is not supported on the object's input stream - cannot verify checksum without consuming stream");
433
    }
434
    	
435
    // we have the go ahead
436
    if ( allowed ) {
437
      
438
        logMetacat.debug("Allowed to insert: " + pid.getValue());
439

    
440
      // Science metadata (XML) or science data object?
441
      // TODO: there are cases where certain object formats are science metadata
442
      // but are not XML (netCDF ...).  Handle this.
443
      if ( isScienceMetadata(sysmeta) ) {
444
        
445
        // CASE METADATA:
446
      	//String objectAsXML = "";
447
        try {
448
	        //objectAsXML = IOUtils.toString(object, "UTF-8");
449
	        localId = insertOrUpdateDocument(object,"UTF-8", pid, session, "insert");
450
	        //localId = im.getLocalId(pid.getValue());
451

    
452
        } catch (IOException e) {
453
        	String msg = "The Node is unable to create the object. " +
454
          "There was a problem converting the object to XML";
455
        	logMetacat.info(msg);
456
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
457

    
458
        }
459
                    
460
      } else {
461
	        
462
	      // DEFAULT CASE: DATA (needs to be checked and completed)
463
	      localId = insertDataObject(object, pid, session);
464
      }   
465
    
466
    }
467

    
468
    logMetacat.debug("Done inserting new object: " + pid.getValue());
469
    
470
    // save the sysmeta
471
    try {
472
    	// lock and unlock of the pid happens in the subclass
473
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
474
    	// submit for indexing
475
        MetacatSolrIndex.getInstance().submit(sysmeta.getIdentifier(), sysmeta, null, true);
476
        
477
    } catch (Exception e) {
478
    	logMetacat.error("Problem creating system metadata: " + pid.getValue(), e);
479
        throw new ServiceFailure("1190", e.getMessage());
480
	}
481
    
482
    // setting the resulting identifier failed
483
    if (localId == null ) {
484
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
485
    }
486

    
487
    resultPid = pid;
488
    
489
    logMetacat.debug("create() complete for object: " + pid.getValue());
490

    
491
    return resultPid;
492
  }
493

    
494
  /**
495
   * Return the log records associated with a given event between the start and 
496
   * end dates listed given a particular Subject listed in the Session
497
   * 
498
   * @param session - the Session object containing the credentials for the Subject
499
   * @param fromDate - the start date of the desired log records
500
   * @param toDate - the end date of the desired log records
501
   * @param event - restrict log records of a specific event type
502
   * @param start - zero based offset from the first record in the 
503
   *                set of matching log records. Used to assist with 
504
   *                paging the response.
505
   * @param count - maximum number of log records to return in the response. 
506
   *                Used to assist with paging the response.
507
   * 
508
   * @return the desired log records
509
   * 
510
   * @throws InvalidToken
511
   * @throws ServiceFailure
512
   * @throws NotAuthorized
513
   * @throws InvalidRequest
514
   * @throws NotImplemented
515
   */
516
  public Log getLogRecords(Session session, Date fromDate, Date toDate, 
517
      String event, String pidFilter, Integer start, Integer count) throws InvalidToken, ServiceFailure,
518
      NotAuthorized, InvalidRequest, NotImplemented {
519

    
520
	  // only admin access to this method
521
	  // see https://redmine.dataone.org/issues/2855
522
	  if (!isAdminAuthorized(session)) {
523
		  throw new NotAuthorized("1460", "Only the CN or admin is allowed to harvest logs from this node");
524
	  }
525
	  
526
    IdentifierManager im = IdentifierManager.getInstance();
527
    EventLog el = EventLog.getInstance();
528
    if ( fromDate == null ) {
529
      logMetacat.debug("setting fromdate from null");
530
      fromDate = new Date(1);
531
    }
532
    if ( toDate == null ) {
533
      logMetacat.debug("setting todate from null");
534
      toDate = new Date();
535
    }
536

    
537
    if ( start == null ) {
538
    	start = 0;	
539
    }
540
    
541
    if ( count == null ) {
542
    	count = 1000;
543
    }
544
    
545
    // safeguard against large requests
546
    if (count > MAXIMUM_DB_RECORD_COUNT) {
547
    	count = MAXIMUM_DB_RECORD_COUNT;
548
    }
549

    
550
    String[] filterDocid = null;
551
    if (pidFilter != null) {
552
		try {
553
	      String localId = im.getLocalId(pidFilter);
554
	      filterDocid = new String[] {localId};
555
	    } catch (Exception ex) { 
556
	    	String msg = "Could not find localId for given pidFilter '" + pidFilter + "'";
557
	        logMetacat.warn(msg, ex);
558
	        //throw new InvalidRequest("1480", msg);
559
	    }
560
    }
561
    
562
    logMetacat.debug("fromDate: " + fromDate);
563
    logMetacat.debug("toDate: " + toDate);
564

    
565
    Log log = el.getD1Report(null, null, filterDocid, event,
566
        new java.sql.Timestamp(fromDate.getTime()),
567
        new java.sql.Timestamp(toDate.getTime()), false, start, count);
568
    
569
    logMetacat.info("getLogRecords");
570
    return log;
571
  }
572
    
573
  /**
574
   * Return the object identified by the given object identifier
575
   * 
576
   * @param session - the Session object containing the credentials for the Subject
577
   * @param pid - the object identifier for the given object
578
   * 
579
   * TODO: The D1 Authorization API doesn't provide information on which 
580
   * authentication system the Subject belongs to, and so it's not possible to
581
   * discern which Person or Group is a valid KNB LDAP DN.  Fix this.
582
   * 
583
   * @return inputStream - the input stream of the given object
584
   * 
585
   * @throws InvalidToken
586
   * @throws ServiceFailure
587
   * @throws NotAuthorized
588
   * @throws InvalidRequest
589
   * @throws NotImplemented
590
   */
591
  public InputStream get(Session session, Identifier pid) 
592
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
593
    NotImplemented {
594
    
595
    String serviceFailureCode = "1030";
596
    Identifier sid = getPIDForSID(pid, serviceFailureCode);
597
    if(sid != null) {
598
        pid = sid;
599
    }
600
    
601
    InputStream inputStream = null; // bytes to be returned
602
    handler = new MetacatHandler(new Timer());
603
    boolean allowed = false;
604
    String localId; // the metacat docid for the pid
605
    
606
    // get the local docid from Metacat
607
    try {
608
      localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
609
    
610
    } catch (McdbDocNotFoundException e) {
611
      throw new NotFound("1020", "The object specified by " + 
612
                         pid.getValue() +
613
                         " does not exist at this node.");
614
    } catch (SQLException e) {
615
        throw new ServiceFailure("1030", "The object specified by "+ pid.getValue()+
616
                                  " couldn't be identified at this node since "+e.getMessage());
617
    }
618
    
619
    // check for authorization
620
    try {
621
		allowed = isAuthorized(session, pid, Permission.READ);
622
	} catch (InvalidRequest e) {
623
		throw new ServiceFailure("1030", e.getDescription());
624
	}
625
    
626
    // if the person is authorized, perform the read
627
    if (allowed) {
628
      try {
629
        inputStream = handler.read(localId);
630
      } catch (McdbDocNotFoundException de) {
631
          String error ="";
632
          if(EventLog.getInstance().isDeleted(localId)) {
633
                error=DELETEDMESSAGE;
634
          }
635
          throw new NotFound("1020", "The object specified by " + 
636
                           pid.getValue() +
637
                           " does not exist at this node. "+error);
638
      } catch (Exception e) {
639
        throw new ServiceFailure("1030", "The object specified by " + 
640
            pid.getValue() +
641
            " could not be returned due to error: " +
642
            e.getMessage()+". ");
643
      }
644
    }
645

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

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

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

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

    
773
	        } catch (RuntimeException e) {
774
	        	e.printStackTrace();
775
	            // convert hazelcast RuntimeException to ServiceFailure
776
	            throw new ServiceFailure("1090", "Unexpected error getting system metadata for: " + 
777
	                pid.getValue());	
778
	        }
779
	        
780
        }
781
        
782
        // It wasn't in the map
783
        if ( systemMetadata == null ) {
784
            String error ="";
785
            String localId = null;
786
            try {
787
                localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
788
              
789
             } catch (Exception e) {
790
                logMetacat.warn("Couldn't find the local id for the pid "+pid.getValue());
791
            }
792
            
793
            if(localId != null && EventLog.getInstance().isDeleted(localId)) {
794
                error = DELETEDMESSAGE;
795
            } else if (localId == null && EventLog.getInstance().isDeleted(pid.getValue())) {
796
                error = DELETEDMESSAGE;
797
            }
798
            throw new NotFound("1420", "No record found for: " + pid.getValue()+". "+error);
799
        }
800
        
801
        return systemMetadata;
802
    }
803
     
804
    
805
    /**
806
     * Test if the specified session represents the authoritative member node for the
807
     * given object specified by the identifier. According the the DataONE documentation, 
808
     * the authoritative member node has all the rights of the *rightsHolder*.
809
     * @param session - the Session object containing the credentials for the Subject
810
     * @param pid - the Identifier of the data object
811
     * @return true if the session represents the authoritative mn.
812
     * @throws ServiceFailure 
813
     * @throws NotImplemented 
814
     */
815
    public boolean isAuthoritativeMNodeAdmin(Session session, Identifier pid) {
816
        boolean allowed = false;
817
        //check the parameters
818
        if(session == null) {
819
            logMetacat.debug("D1NodeService.isAuthoritativeMNodeAdmin - the session object is null and return false.");
820
            return allowed;
821
        } else if (pid == null || pid.getValue() == null || pid.getValue().trim().equals("")) {
822
            logMetacat.debug("D1NodeService.isAuthoritativeMNodeAdmin - the Identifier object is null (not being specified) and return false.");
823
            return allowed;
824
        }
825
        
826
        //Get the subject from the session
827
        Subject subject = session.getSubject();
828
        if(subject != null) {
829
            //Get the authoritative member node info from the system metadata
830
            SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
831
            if(sysMeta != null) {
832
                NodeReference authoritativeMNode = sysMeta.getAuthoritativeMemberNode();
833
                if(authoritativeMNode != null) {
834
                        CNode cn = null;
835
                        try {
836
                            cn = D1Client.getCN();
837
                        } catch (BaseException e) {
838
                            logMetacat.error("D1NodeService.isAuthoritativeMNodeAdmin - couldn't connect to the CN since "+
839
                                            e.getDescription()+ ". The false value will be returned for the AuthoritativeMNodeAdmin.");
840
                            return allowed;
841
                        }
842
                        
843
                        if(cn != null) {
844
                            List<Node> nodes = null;
845
                            try {
846
                                nodes = cn.listNodes().getNodeList();
847
                            } catch (NotImplemented e) {
848
                                logMetacat.error("D1NodeService.isAuthoritativeMNodeAdmin - couldn't get the member nodes list from the CN since "+e.getDescription()+ 
849
                                                ". The false value will be returned for the AuthoritativeMNodeAdmin.");
850
                                return allowed;
851
                            } catch (ServiceFailure ee) {
852
                                logMetacat.error("D1NodeService.isAuthoritativeMNodeAdmin - couldn't get the member nodes list from the CN since "+ee.getDescription()+ 
853
                                                ". The false value will be returned for the AuthoritativeMNodeAdmin.");
854
                                return allowed;
855
                            }
856
                            if(nodes != null) {
857
                                for(Node node : nodes) {
858
                                    //find the authoritative node and get its subjects
859
                                    if (node.getType() == NodeType.MN && node.getIdentifier() != null && node.getIdentifier().equals(authoritativeMNode)) {
860
                                        List<Subject> nodeSubjects = node.getSubjectList();
861
                                        if(nodeSubjects != null) {
862
                                            // check if the session subject is in the node subject list
863
                                            for (Subject nodeSubject : nodeSubjects) {
864
                                                logMetacat.debug("D1NodeService.isAuthoritativeMNodeAdmin(), comparing subjects: " +
865
                                                    nodeSubject.getValue() + " and " + subject.getValue());
866
                                                if ( nodeSubject != null && nodeSubject.equals(subject) ) {
867
                                                    allowed = true; // subject of session == target node subject
868
                                                    break;
869
                                                }
870
                                            }              
871
                                        }
872
                                      
873
                                    }
874
                                }
875
                            }
876
                        }
877
                }
878
            }
879
        }
880
        return allowed;
881
    }
882
    
883
    
884
  /**
885
   * Test if the user identified by the provided token has administrative authorization 
886
   * 
887
   * @param session - the Session object containing the credentials for the Subject
888
   * 
889
   * @return true if the user is admin
890
   * 
891
   * @throws ServiceFailure
892
   * @throws InvalidToken
893
   * @throws NotFound
894
   * @throws NotAuthorized
895
   * @throws NotImplemented
896
   */
897
  public boolean isAdminAuthorized(Session session) 
898
      throws ServiceFailure, InvalidToken, NotAuthorized,
899
      NotImplemented {
900

    
901
      boolean allowed = false;
902
      
903
      // must have a session in order to check admin 
904
      if (session == null) {
905
         logMetacat.debug("In isAdminAuthorized(), session is null ");
906
         return false;
907
      }
908
      
909
      logMetacat.debug("In isAdminAuthorized(), checking CN or MN authorization for " +
910
           session.getSubject().getValue());
911
      
912
      // check if this is the node calling itself (MN)
913
      allowed = isNodeAdmin(session);
914
      
915
      // check the CN list
916
      if (!allowed) {
917
	      List<Node> nodes = null;
918

    
919
    	  try {
920
		      // are we allowed to do this? only CNs are allowed
921
		      CNode cn = D1Client.getCN();
922
		      nodes = cn.listNodes().getNodeList();
923
    	  }
924
	      catch (Throwable e) {
925
	    	  logMetacat.warn(e.getMessage());
926
	    	  return false;  
927
	      }
928
		      
929
	      if ( nodes == null ) {
930
	    	  return false;
931
	          //throw new ServiceFailure("4852", "Couldn't get node list.");
932
	      }
933
	      
934
	      // find the node in the node list
935
	      for ( Node node : nodes ) {
936
	          
937
	          NodeReference nodeReference = node.getIdentifier();
938
	          logMetacat.debug("In isAdminAuthorized(), Node reference is: " + nodeReference.getValue());
939
	          
940
	          Subject subject = session.getSubject();
941
	          
942
	          if (node.getType() == NodeType.CN) {
943
	              List<Subject> nodeSubjects = node.getSubjectList();
944
	              
945
	              // check if the session subject is in the node subject list
946
	              for (Subject nodeSubject : nodeSubjects) {
947
	                  logMetacat.debug("In isAdminAuthorized(), comparing subjects: " +
948
	                      nodeSubject.getValue() + " and " + subject.getValue());
949
	                  if ( nodeSubject.equals(subject) ) {
950
	                      allowed = true; // subject of session == target node subject
951
	                      break;
952
	                      
953
	                  }
954
	              }              
955
	          }
956
	      }
957
      }
958
      
959
      return allowed;
960
  }
961
  
962
  /**
963
   * Test if the user identified by the provided token has administrative authorization 
964
   * on this node because they are calling themselves
965
   * 
966
   * @param session - the Session object containing the credentials for the Subject
967
   * 
968
   * @return true if the user is this node
969
   * @throws ServiceFailure 
970
   * @throws NotImplemented 
971
   */
972
  public boolean isNodeAdmin(Session session) throws NotImplemented, ServiceFailure {
973

    
974
      boolean allowed = false;
975
      
976
      // must have a session in order to check admin 
977
      if (session == null) {
978
         logMetacat.debug("In isNodeAdmin(), session is null ");
979
         return false;
980
      }
981
      
982
      logMetacat.debug("In isNodeAdmin(), MN authorization for " +
983
           session.getSubject().getValue());
984
      
985
      Node node = MNodeService.getInstance(request).getCapabilities();
986
      NodeReference nodeReference = node.getIdentifier();
987
      logMetacat.debug("In isNodeAdmin(), Node reference is: " + nodeReference.getValue());
988
      
989
      Subject subject = session.getSubject();
990
      
991
      if (node.getType() == NodeType.MN) {
992
          List<Subject> nodeSubjects = node.getSubjectList();
993
          
994
          // check if the session subject is in the node subject list
995
          for (Subject nodeSubject : nodeSubjects) {
996
              logMetacat.debug("In isNodeAdmin(), comparing subjects: " +
997
                  nodeSubject.getValue() + " and " + subject.getValue());
998
              if ( nodeSubject.equals(subject) ) {
999
                  allowed = true; // subject of session == this node's subect
1000
                  break;
1001
              }
1002
          }              
1003
      }
1004
      
1005
      return allowed;
1006
  }
1007
  
1008
  /**
1009
   * Test if the user identified by the provided token has authorization 
1010
   * for the operation on the specified object.
1011
   * 
1012
   * @param session - the Session object containing the credentials for the Subject
1013
   * @param pid - The identifer of the resource for which access is being checked
1014
   * @param operation - The type of operation which is being requested for the given pid
1015
   *
1016
   * @return true if the operation is allowed
1017
   * 
1018
   * @throws ServiceFailure
1019
   * @throws InvalidToken
1020
   * @throws NotFound
1021
   * @throws NotAuthorized
1022
   * @throws NotImplemented
1023
   * @throws InvalidRequest
1024
   */
1025
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
1026
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
1027
    NotImplemented, InvalidRequest {
1028

    
1029
    boolean allowed = false;
1030
    
1031
    if (permission == null) {
1032
    	throw new InvalidRequest("1761", "Permission was not provided or is invalid");
1033
    }
1034
    
1035
    // permissions are hierarchical
1036
    List<Permission> expandedPermissions = null;
1037
    
1038
    // always allow CN access
1039
    if ( isAdminAuthorized(session) ) {
1040
        allowed = true;
1041
        return allowed;
1042
        
1043
    }
1044
    
1045
    // the authoritative member node of the pid always has the access as well.
1046
    if (isAuthoritativeMNodeAdmin(session, pid)) {
1047
        allowed = true;
1048
        return allowed;
1049
    }
1050
    
1051
    // get the subject[s] from the session
1052
	//defer to the shared util for recursively compiling the subjects	
1053
	Set<Subject> subjects = AuthUtils.authorizedClientSubjects(session);
1054
    
1055
	// track the identities we have checked against
1056
	StringBuffer includedSubjects = new StringBuffer();
1057
    	
1058
    // get the system metadata
1059
    String pidStr = pid.getValue();
1060
    SystemMetadata systemMetadata = null;
1061
    try {
1062
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1063

    
1064
    } catch (Exception e) {
1065
        // convert Hazelcast RuntimeException to NotFound
1066
        logMetacat.error("An error occurred while getting system metadata for identifier " +
1067
            pid.getValue() + ". The error message was: " + e.getMessage());
1068
        throw new NotFound("1800", "No record found for " + pidStr);
1069
        
1070
    } 
1071
    
1072
    // throw not found if it was not found
1073
    if (systemMetadata == null) {
1074
        String localId = null;
1075
        String error = "No system metadata could be found for given PID: " + pidStr;
1076
        try {
1077
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1078
          
1079
         } catch (Exception e) {
1080
            logMetacat.warn("Couldn't find the local id for the pid "+pidStr);
1081
        }
1082
        
1083
        if(localId != null && EventLog.getInstance().isDeleted(localId)) {
1084
            error = error + ". "+DELETEDMESSAGE;
1085
        } else if (localId == null && EventLog.getInstance().isDeleted(pid.getValue())) {
1086
            error = error + ". "+DELETEDMESSAGE;
1087
        }
1088
        throw new NotFound("1800", error);
1089
    }
1090
	    
1091
    // do we own it?
1092
    for (Subject s: subjects) {
1093
      logMetacat.debug("Comparing \t" + 
1094
                       systemMetadata.getRightsHolder().getValue() +
1095
                       " \tagainst \t" + s.getValue());
1096
      	includedSubjects.append(s.getValue() + "; ");
1097
    	allowed = systemMetadata.getRightsHolder().equals(s);
1098
    	if (allowed) {
1099
    		return allowed;
1100
    	}
1101
    }    
1102
    
1103
    // otherwise check the access rules
1104
    try {
1105
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
1106
	    search: // label break
1107
	    for (AccessRule accessRule: allows) {
1108
	      for (Subject s: subjects) {
1109
	        logMetacat.debug("Checking allow access rule for subject: " + s.getValue());
1110
	        if (accessRule.getSubjectList().contains(s)) {
1111
	        	logMetacat.debug("Access rule contains subject: " + s.getValue());
1112
	        	for (Permission p: accessRule.getPermissionList()) {
1113
		        	logMetacat.debug("Checking permission: " + p.xmlValue());
1114
	        		expandedPermissions = expandPermissions(p);
1115
	        		allowed = expandedPermissions.contains(permission);
1116
	        		if (allowed) {
1117
			        	logMetacat.info("Permission granted: " + p.xmlValue() + " to " + s.getValue());
1118
	        			break search; //label break
1119
	        		}
1120
	        	}
1121
        		
1122
	        }
1123
	      }
1124
	    }
1125
    } catch (Exception e) {
1126
    	// catch all for errors - safe side should be to deny the access
1127
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
1128
		allowed = false;
1129
	  
1130
    }
1131
    
1132
    // throw or return?
1133
    if (!allowed) {
1134
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr + " for subject[s]: " + includedSubjects.toString() );
1135
    }
1136
    
1137
    return allowed;
1138
    
1139
  }
1140
  
1141
  /*
1142
   * parse a logEntry and get the relevant field from it
1143
   * 
1144
   * @param fieldname
1145
   * @param entry
1146
   * @return
1147
   */
1148
  private String getLogEntryField(String fieldname, String entry) {
1149
    String begin = "<" + fieldname + ">";
1150
    String end = "</" + fieldname + ">";
1151
    // logMetacat.debug("looking for " + begin + " and " + end +
1152
    // " in entry " + entry);
1153
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
1154
        .indexOf(end));
1155
    logMetacat.debug("entry " + fieldname + " : " + s);
1156
    return s;
1157
  }
1158

    
1159
  /** 
1160
   * Determine if a given object should be treated as an XML science metadata
1161
   * object. 
1162
   * 
1163
   * @param sysmeta - the SystemMetadata describing the object
1164
   * @return true if the object should be treated as science metadata
1165
   */
1166
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
1167
    
1168
    ObjectFormat objectFormat = null;
1169
    boolean isScienceMetadata = false;
1170
    
1171
    try {
1172
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
1173
      if ( objectFormat.getFormatType().equals("METADATA") ) {
1174
      	isScienceMetadata = true;
1175
      	
1176
      }
1177
      
1178
       
1179
    } catch (ServiceFailure e) {
1180
      logMetacat.debug("There was a problem determining if the object identified by" + 
1181
          sysmeta.getIdentifier().getValue() + 
1182
          " is science metadata: " + e.getMessage());
1183
    
1184
    } catch (NotFound e) {
1185
      logMetacat.debug("There was a problem determining if the object identified by" + 
1186
          sysmeta.getIdentifier().getValue() + 
1187
          " is science metadata: " + e.getMessage());
1188
    
1189
    }
1190
    
1191
    return isScienceMetadata;
1192

    
1193
  }
1194
  
1195
  /**
1196
   * Check fro whitespace in the given pid.
1197
   * null pids are also invalid by default
1198
   * @param pid
1199
   * @return
1200
   */
1201
  public static boolean isValidIdentifier(Identifier pid) {
1202
	  if (pid != null && pid.getValue() != null && pid.getValue().length() > 0) {
1203
		  return !pid.getValue().matches(".*\\s+.*");
1204
	  } 
1205
	  return false;
1206
  }
1207
  
1208
  
1209
  /**
1210
   * Insert or update an XML document into Metacat
1211
   * 
1212
   * @param xml - the XML document to insert or update
1213
   * @param pid - the identifier to be used for the resulting object
1214
   * 
1215
   * @return localId - the resulting docid of the document created or updated
1216
   * 
1217
   */
1218
  public String insertOrUpdateDocument(InputStream xml, String encoding,  Identifier pid, 
1219
    Session session, String insertOrUpdate) 
1220
    throws ServiceFailure, IOException {
1221
    
1222
  	logMetacat.debug("Starting to insert xml document...");
1223
    IdentifierManager im = IdentifierManager.getInstance();
1224

    
1225
    // generate pid/localId pair for sysmeta
1226
    String localId = null;
1227
    byte[] xmlBytes  = IOUtils.toByteArray(xml);
1228
    String xmlStr = new String(xmlBytes, encoding);
1229
    if(insertOrUpdate.equals("insert")) {
1230
      localId = im.generateLocalId(pid.getValue(), 1);
1231
      
1232
    } else {
1233
      //localid should already exist in the identifier table, so just find it
1234
      try {
1235
        logMetacat.debug("Updating pid " + pid.getValue());
1236
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
1237
        
1238
        localId = im.getLocalId(pid.getValue());
1239
        
1240
        logMetacat.debug("localId: " + localId);
1241
        //increment the revision
1242
        String docid = localId.substring(0, localId.lastIndexOf("."));
1243
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1244
        int rev = new Integer(revS).intValue();
1245
        rev++;
1246
        docid = docid + "." + rev;
1247
        localId = docid;
1248
        logMetacat.debug("incremented localId: " + localId);
1249
      
1250
      } catch(McdbDocNotFoundException e) {
1251
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
1252
            "pid " + pid.getValue() + 
1253
            " should have been in the identifier table, but it wasn't: " + 
1254
            e.getMessage());
1255
      
1256
      } catch (SQLException e) {
1257
          throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument() -"+
1258
                     " couldn't identify if the pid "+pid.getValue()+" is in the identifier table since "+e.getMessage());
1259
      }
1260
      
1261
    }
1262

    
1263
    params = new Hashtable<String, String[]>();
1264
    String[] action = new String[1];
1265
    action[0] = insertOrUpdate;
1266
    params.put("action", action);
1267
    String[] docid = new String[1];
1268
    docid[0] = localId;
1269
    params.put("docid", docid);
1270
    String[] doctext = new String[1];
1271
    doctext[0] = xmlStr;
1272
    params.put("doctext", doctext);
1273
    
1274
    String username = Constants.SUBJECT_PUBLIC;
1275
    String[] groupnames = null;
1276
    if (session != null ) {
1277
    	username = session.getSubject().getValue();
1278
    	if (session.getSubjectInfo() != null) {
1279
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
1280
    		if (groupList != null) {
1281
    			groupnames = new String[groupList.size()];
1282
    			for (int i = 0; i < groupList.size(); i++ ) {
1283
    				groupnames[i] = groupList.get(i).getGroupName();
1284
    			}
1285
    		}
1286
    	}
1287
    }
1288
    
1289
    // do the insert or update action
1290
    handler = new MetacatHandler(new Timer());
1291
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null, 
1292
                        null, params, username, groupnames, false, false, xmlBytes);
1293
    
1294
    if(result.indexOf("<error>") != -1) {
1295
    	String detailCode = "";
1296
    	if ( insertOrUpdate.equals("insert") ) {
1297
    		// make sure to remove the mapping so that subsequent attempts do not fail with IdentifierNotUnique
1298
    		im.removeMapping(pid.getValue(), localId);
1299
    		detailCode = "1190";
1300
    		
1301
    	} else if ( insertOrUpdate.equals("update") ) {
1302
    		detailCode = "1310";
1303
    		
1304
    	}
1305
        throw new ServiceFailure(detailCode, 
1306
          "Error inserting or updating document: " + result);
1307
    }
1308
    logMetacat.debug("Finsished inserting xml document with id " + localId);
1309
    
1310
    return localId;
1311
  }
1312
  
1313
  /**
1314
   * Insert a data document
1315
   * 
1316
   * @param object
1317
   * @param pid
1318
   * @param sessionData
1319
   * @throws ServiceFailure
1320
   * @returns localId of the data object inserted
1321
   */
1322
  public String insertDataObject(InputStream object, Identifier pid, 
1323
          Session session) throws ServiceFailure {
1324
      
1325
    String username = Constants.SUBJECT_PUBLIC;
1326
    String[] groupnames = null;
1327
    if (session != null ) {
1328
    	username = session.getSubject().getValue();
1329
    	if (session.getSubjectInfo() != null) {
1330
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
1331
    		if (groupList != null) {
1332
    			groupnames = new String[groupList.size()];
1333
    			for (int i = 0; i < groupList.size(); i++ ) {
1334
    				groupnames[i] = groupList.get(i).getGroupName();
1335
    			}
1336
    		}
1337
    	}
1338
    }
1339
  
1340
    // generate pid/localId pair for object
1341
    logMetacat.debug("Generating a pid/localId mapping");
1342
    IdentifierManager im = IdentifierManager.getInstance();
1343
    String localId = im.generateLocalId(pid.getValue(), 1);
1344
  
1345
    // Save the data file to disk using "localId" as the name
1346
    String datafilepath = null;
1347
	try {
1348
		datafilepath = PropertyService.getProperty("application.datafilepath");
1349
	} catch (PropertyNotFoundException e) {
1350
		ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
1351
		sf.initCause(e);
1352
		throw sf;
1353
	}
1354
    boolean locked = false;
1355
	try {
1356
		locked = DocumentImpl.getDataFileLockGrant(localId);
1357
	} catch (Exception e) {
1358
		ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1359
		sf.initCause(e);
1360
		throw sf;
1361
	}
1362

    
1363
    logMetacat.debug("Case DATA: starting to write to disk.");
1364
	if (locked) {
1365

    
1366
          File dataDirectory = new File(datafilepath);
1367
          dataDirectory.mkdirs();
1368
  
1369
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1370
  
1371
          // TODO: Check that the file size matches SystemMetadata
1372
          // long size = newFile.length();
1373
          // if (size == 0) {
1374
          //     throw new IOException("Uploaded file is 0 bytes!");
1375
          // }
1376
  
1377
          // Register the file in the database (which generates an exception
1378
          // if the localId is not acceptable or other untoward things happen
1379
          try {
1380
            logMetacat.debug("Registering document...");
1381
            DocumentImpl.registerDocument(localId, "BIN", localId,
1382
                    username, groupnames);
1383
            logMetacat.debug("Registration step completed.");
1384
            
1385
          } catch (SQLException e) {
1386
            //newFile.delete();
1387
            logMetacat.debug("SQLE: " + e.getMessage());
1388
            e.printStackTrace(System.out);
1389
            throw new ServiceFailure("1190", "Registration failed: " + 
1390
            		e.getMessage());
1391
            
1392
          } catch (AccessionNumberException e) {
1393
            //newFile.delete();
1394
            logMetacat.debug("ANE: " + e.getMessage());
1395
            e.printStackTrace(System.out);
1396
            throw new ServiceFailure("1190", "Registration failed: " + 
1397
            	e.getMessage());
1398
            
1399
          } catch (Exception e) {
1400
            //newFile.delete();
1401
            logMetacat.debug("Exception: " + e.getMessage());
1402
            e.printStackTrace(System.out);
1403
            throw new ServiceFailure("1190", "Registration failed: " + 
1404
            	e.getMessage());
1405
          }
1406
  
1407
          logMetacat.debug("Logging the creation event.");
1408
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1409
  
1410
          // Schedule replication for this data file, the "insert" action is important here!
1411
          logMetacat.debug("Scheduling replication.");
1412
          ForceReplicationHandler frh = new ForceReplicationHandler(localId, "insert", false, null);
1413
      }
1414
      
1415
      return localId;
1416
    
1417
  }
1418

    
1419
  /**
1420
   * Insert a systemMetadata document and return its localId
1421
   */
1422
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1423
      throws ServiceFailure {
1424
      
1425
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1426
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1427
      logMetacat.debug("Inserting new system metadata with modified date " + 
1428
          sysmeta.getDateSysMetadataModified());
1429
      
1430
      //insert the system metadata
1431
      try {
1432
        // note: the calling subclass handles the map hazelcast lock/unlock
1433
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1434
      	// submit for indexing
1435
        MetacatSolrIndex.getInstance().submit(sysmeta.getIdentifier(), sysmeta, null, true);
1436
      } catch (Exception e) {
1437
          throw new ServiceFailure("1190", e.getMessage());
1438
          
1439
	    }  
1440
  }
1441

    
1442
  /**
1443
   * Update a systemMetadata document
1444
   * 
1445
   * @param sysMeta - the system metadata object in the system to update
1446
   */
1447
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1448
        throws ServiceFailure {
1449

    
1450
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1451
        sysMeta.setDateSysMetadataModified(new Date());
1452
        try {
1453
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1454
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1455
            // submit for indexing
1456
            MetacatSolrIndex.getInstance().submit(sysMeta.getIdentifier(), sysMeta, null, true);
1457
        } catch (Exception e) {
1458
            throw new ServiceFailure("4862", e.getMessage());
1459

    
1460
        } finally {
1461
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1462

    
1463
        }
1464

    
1465
    }
1466
    
1467
	public boolean updateSystemMetadata(Session session, Identifier pid,
1468
			SystemMetadata sysmeta) throws NotImplemented, NotAuthorized,
1469
			ServiceFailure, InvalidRequest, InvalidSystemMetadata, InvalidToken {
1470
		
1471
		// The lock to be used for this identifier
1472
      Lock lock = null;
1473

    
1474
      // TODO: control who can call this?
1475
      if (session == null) {
1476
          //TODO: many of the thrown exceptions do not use the correct error codes
1477
          //check these against the docs and correct them
1478
          throw new NotAuthorized("4861", "No Session - could not authorize for registration." +
1479
                  "  If you are not logged in, please do so and retry the request.");
1480
      }
1481
      
1482
      // verify that guid == SystemMetadata.getIdentifier()
1483
      logMetacat.debug("Comparing guid|sysmeta_guid: " + pid.getValue() + 
1484
          "|" + sysmeta.getIdentifier().getValue());
1485
      
1486
      if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
1487
          throw new InvalidRequest("4863", 
1488
              "The identifier in method call (" + pid.getValue() + 
1489
              ") does not match identifier in system metadata (" +
1490
              sysmeta.getIdentifier().getValue() + ").");
1491
      }
1492

    
1493
      // do the actual update
1494
      this.updateSystemMetadata(sysmeta);
1495
      
1496
      try {
1497
    	  String localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1498
    	  EventLog.getInstance().log(request.getRemoteAddr(), 
1499
    	          request.getHeader("User-Agent"), session.getSubject().getValue(), 
1500
    	          localId, "updateSystemMetadata");
1501
      } catch (McdbDocNotFoundException e) {
1502
    	  // do nothing, no localId to log with
1503
    	  logMetacat.warn("Could not log 'updateSystemMetadata' event because no localId was found for pid: " + pid.getValue());
1504
      } catch (SQLException e) {
1505
          logMetacat.warn("Could not log 'updateSystemMetadata' event because the localId couldn't be identified for the pid: " + pid.getValue());
1506
      }
1507
      
1508
      return true;
1509
	}
1510
  
1511
  /**
1512
   * Given a Permission, returns a list of all permissions that it encompasses
1513
   * Permissions are hierarchical so that WRITE also allows READ.
1514
   * @param permission
1515
   * @return list of included Permissions for the given permission
1516
   */
1517
  protected List<Permission> expandPermissions(Permission permission) {
1518
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1519
	    if (permission.equals(Permission.READ)) {
1520
	    	expandedPermissions.add(Permission.READ);
1521
	    }
1522
	    if (permission.equals(Permission.WRITE)) {
1523
	    	expandedPermissions.add(Permission.READ);
1524
	    	expandedPermissions.add(Permission.WRITE);
1525
	    }
1526
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1527
	    	expandedPermissions.add(Permission.READ);
1528
	    	expandedPermissions.add(Permission.WRITE);
1529
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1530
	    }
1531
	    return expandedPermissions;
1532
  }
1533

    
1534
  /*
1535
   * Write a stream to a file
1536
   * 
1537
   * @param dir - the directory to write to
1538
   * @param fileName - the file name to write to
1539
   * @param data - the object bytes as an input stream
1540
   * 
1541
   * @return newFile - the new file created
1542
   * 
1543
   * @throws ServiceFailure
1544
   */
1545
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1546
    throws ServiceFailure {
1547
    
1548
    File newFile = new File(dir, fileName);
1549
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1550

    
1551
    try {
1552
        if (newFile.createNewFile()) {
1553
          // write data stream to desired file
1554
          OutputStream os = new FileOutputStream(newFile);
1555
          long length = IOUtils.copyLarge(data, os);
1556
          os.flush();
1557
          os.close();
1558
        } else {
1559
          logMetacat.debug("File creation failed, or file already exists.");
1560
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1561
        }
1562
    } catch (FileNotFoundException e) {
1563
      logMetacat.debug("FNF: " + e.getMessage());
1564
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1565
                + e.getMessage());
1566
    } catch (IOException e) {
1567
      logMetacat.debug("IOE: " + e.getMessage());
1568
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1569
                + " " + e.getMessage());
1570
    }
1571

    
1572
    return newFile;
1573
  }
1574

    
1575
  /*
1576
   * Returns a list of nodes that have been registered with the DataONE infrastructure
1577
   * that match the given session subject
1578
   * @return nodes - List of nodes from the registry with a matching session subject
1579
   * 
1580
   * @throws ServiceFailure
1581
   * @throws NotImplemented
1582
   */
1583
  protected List<Node> listNodesBySubject(Subject subject) 
1584
      throws ServiceFailure, NotImplemented {
1585
      List<Node> nodeList = new ArrayList<Node>();
1586
      
1587
      CNode cn = D1Client.getCN();
1588
      List<Node> nodes = cn.listNodes().getNodeList();
1589
      
1590
      // find the node in the node list
1591
      for ( Node node : nodes ) {
1592
          
1593
          List<Subject> nodeSubjects = node.getSubjectList();
1594
          if (nodeSubjects != null) {    
1595
	          // check if the session subject is in the node subject list
1596
	          for (Subject nodeSubject : nodeSubjects) {
1597
	              if ( nodeSubject.equals(subject) ) { // subject of session == node subject
1598
	                  nodeList.add(node);  
1599
	              }                              
1600
	          }
1601
          }
1602
      }
1603
      
1604
      return nodeList;
1605
      
1606
  }
1607

    
1608
  /**
1609
   * Archives an object, where the object is either a 
1610
   * data object or a science metadata object.
1611
   * 
1612
   * @param session - the Session object containing the credentials for the Subject
1613
   * @param pid - The object identifier to be archived
1614
   * 
1615
   * @return pid - the identifier of the object used for the archiving
1616
   * 
1617
   * @throws InvalidToken
1618
   * @throws ServiceFailure
1619
   * @throws NotAuthorized
1620
   * @throws NotFound
1621
   * @throws NotImplemented
1622
   * @throws InvalidRequest
1623
   */
1624
  public Identifier archive(Session session, Identifier pid) 
1625
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1626

    
1627
      String localId = null;
1628
      boolean allowed = false;
1629
      String username = Constants.SUBJECT_PUBLIC;
1630
      String[] groupnames = null;
1631
      if (session == null) {
1632
      	throw new InvalidToken("1330", "No session has been provided");
1633
      } else {
1634
          username = session.getSubject().getValue();
1635
          if (session.getSubjectInfo() != null) {
1636
              List<Group> groupList = session.getSubjectInfo().getGroupList();
1637
              if (groupList != null) {
1638
                  groupnames = new String[groupList.size()];
1639
                  for (int i = 0; i < groupList.size(); i++) {
1640
                      groupnames[i] = groupList.get(i).getGroupName();
1641
                  }
1642
              }
1643
          }
1644
      }
1645

    
1646
      // do we have a valid pid?
1647
      if (pid == null || pid.getValue().trim().equals("")) {
1648
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
1649
      }
1650

    
1651
      // check for the existing identifier
1652
      try {
1653
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1654
      } catch (McdbDocNotFoundException e) {
1655
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
1656
      } catch (SQLException e) {
1657
          throw new ServiceFailure("1350", "The object with the provided identifier "+pid.getValue()+" couldn't be identified since "+e.getMessage());
1658
      }
1659

    
1660
      // does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
1661
      try {
1662
			allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
1663
		} catch (InvalidRequest e) {
1664
          throw new ServiceFailure("1350", e.getDescription());
1665
		}
1666
          
1667

    
1668
      if (allowed) {
1669
          try {
1670
              // archive the document
1671
              DocumentImpl.delete(localId, null, null, null, false);
1672
              EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
1673

    
1674
              // archive it
1675
              SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1676
              sysMeta.setArchived(true);
1677
              sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1678
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
1679
              // submit for indexing
1680
              // DocumentImpl call above should do this.
1681
              // see: https://projects.ecoinformatics.org/ecoinfo/issues/6030
1682
              //HazelcastService.getInstance().getIndexQueue().add(sysMeta);
1683
              
1684
          } catch (McdbDocNotFoundException e) {
1685
              throw new NotFound("1340", "The provided identifier was invalid.");
1686

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

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

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

    
1697
      } else {
1698
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
1699
      }
1700

    
1701
      return pid;
1702
  }
1703
  
1704
  
1705
  /**
1706
   * A utility method for v1 api to check the specified identifier exists as a pid
1707
   * @param identifier  the specified identifier
1708
   * @param serviceFailureCode  the detail error code for the service failure exception
1709
   * @param noFoundCode  the detail error code for the not found exception
1710
   * @throws ServiceFailure
1711
   * @throws NotFound
1712
   */
1713
  public void checkV1SystemMetaPidExist(Identifier identifier, String serviceFailureCode, String serviceFailureMessage,  
1714
          String noFoundCode, String notFoundMessage) throws ServiceFailure, NotFound {
1715
      boolean exists = false;
1716
      try {
1717
          exists = IdentifierManager.getInstance().systemMetadataPIDExists(identifier);
1718
      } catch (SQLException e) {
1719
          throw new ServiceFailure(serviceFailureCode, serviceFailureMessage+" since "+e.getMessage());
1720
      }
1721
      if(!exists) {
1722
         //the v1 method only handles a pid. so it should throw a not-found exception.
1723
          // check if the pid was deleted.
1724
          try {
1725
              String localId = IdentifierManager.getInstance().getLocalId(identifier.getValue());
1726
              if(EventLog.getInstance().isDeleted(localId)) {
1727
                  notFoundMessage=notFoundMessage+" "+DELETEDMESSAGE;
1728
              } 
1729
            } catch (Exception e) {
1730
              logMetacat.info("Couldn't determine if the not-found identifier "+identifier.getValue()+" was deleted since "+e.getMessage());
1731
            }
1732
            throw new NotFound(noFoundCode, notFoundMessage);
1733
      }
1734
  }
1735
  
1736
  /**
1737
   * Utility method to get the PID for an SID. If the specified identifier is not an SID
1738
   * , null will be returned.
1739
   * @param sid  the specified sid
1740
   * @param serviceFailureCode  the detail error code for the service failure exception
1741
   * @return the pid for the sid. If the specified identifier is not an SID, null will be returned.
1742
   * @throws ServiceFailure
1743
   */
1744
  protected Identifier getPIDForSID(Identifier sid, String serviceFailureCode) throws ServiceFailure {
1745
      Identifier id = null;
1746
      String serviceFailureMessage = "The PID "+" couldn't be identified for the sid " + sid.getValue();
1747
      try {
1748
          //determine if the given pid is a sid or not.
1749
          if(IdentifierManager.getInstance().systemMetadataSIDExists(sid)) {
1750
              try {
1751
                  //set the header pid for the sid if the identifier is a sid.
1752
                  id = IdentifierManager.getInstance().getHeadPID(sid);
1753
              } catch (SQLException sqle) {
1754
                  throw new ServiceFailure(serviceFailureCode, serviceFailureMessage+" since "+sqle.getMessage());
1755
              }
1756
              
1757
          }
1758
      } catch (SQLException e) {
1759
          throw new ServiceFailure(serviceFailureCode, serviceFailureMessage + " since "+e.getMessage());
1760
      }
1761
      return id;
1762
  }
1763

    
1764

    
1765
}
(2-2/7)