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-31 17:36:28 -0700 (Fri, 31 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
  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
    // get system metadata and construct the describe response
174
      SystemMetadata sysmeta = getSystemMetadata(session, pid);
175
      DescribeResponse describeResponse = 
176
      	new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(), 
177
      			sysmeta.getDateSysMetadataModified(),
178
      			sysmeta.getChecksum(), sysmeta.getSerialVersion());
179

    
180
      return describeResponse;
181

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
450
    return resultPid;
451
  }
452

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

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

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

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

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

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

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

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

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

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

    
836
      boolean allowed = false;
837
      
838
      // must have a session in order to check admin 
839
      if (session == null) {
840
         logMetacat.debug("In isAdminAuthorized(), session is null ");
841
         return false;
842
      }
843
      
844
      logMetacat.debug("In isAdminAuthorized(), checking CN or MN authorization for " +
845
           session.getSubject().getValue());
846
      
847
      // check if this is the node calling itself (MN)
848
      allowed = isNodeAdmin(session);
849
      
850
      // check the CN list
851
      if (!allowed) {
852
	      List<Node> nodes = null;
853

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

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

    
964
    boolean allowed = false;
965
    
966
    if (permission == null) {
967
    	throw new InvalidRequest("1761", "Permission was not provided or is invalid");
968
    }
969
    
970
    // permissions are hierarchical
971
    List<Permission> expandedPermissions = null;
972
    
973
    // always allow CN access
974
    if ( isAdminAuthorized(session) ) {
975
        allowed = true;
976
        return allowed;
977
        
978
    }
979
    
980
    // the authoritative member node of the pid always has the access as well.
981
    if (isAuthoritativeMNodeAdmin(session, pid)) {
982
        allowed = true;
983
        return allowed;
984
    }
985
    
986
    // get the subject[s] from the session
987
	//defer to the shared util for recursively compiling the subjects	
988
	Set<Subject> subjects = AuthUtils.authorizedClientSubjects(session);
989
    
990
	// track the identities we have checked against
991
	StringBuffer includedSubjects = new StringBuffer();
992
    	
993
    // get the system metadata
994
    String pidStr = pid.getValue();
995
    SystemMetadata systemMetadata = null;
996
    try {
997
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
998

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

    
1092
  /** 
1093
   * Determine if a given object should be treated as an XML science metadata
1094
   * object. 
1095
   * 
1096
   * @param sysmeta - the SystemMetadata describing the object
1097
   * @return true if the object should be treated as science metadata
1098
   */
1099
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
1100
    
1101
    ObjectFormat objectFormat = null;
1102
    boolean isScienceMetadata = false;
1103
    
1104
    try {
1105
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
1106
      if ( objectFormat.getFormatType().equals("METADATA") ) {
1107
      	isScienceMetadata = true;
1108
      	
1109
      }
1110
      
1111
       
1112
    } catch (ServiceFailure e) {
1113
      logMetacat.debug("There was a problem determining if the object identified by" + 
1114
          sysmeta.getIdentifier().getValue() + 
1115
          " is science metadata: " + e.getMessage());
1116
    
1117
    } catch (NotFound e) {
1118
      logMetacat.debug("There was a problem determining if the object identified by" + 
1119
          sysmeta.getIdentifier().getValue() + 
1120
          " is science metadata: " + e.getMessage());
1121
    
1122
    }
1123
    
1124
    return isScienceMetadata;
1125

    
1126
  }
1127
  
1128
  /**
1129
   * Check fro whitespace in the given pid.
1130
   * null pids are also invalid by default
1131
   * @param pid
1132
   * @return
1133
   */
1134
  public static boolean isValidIdentifier(Identifier pid) {
1135
	  if (pid != null && pid.getValue() != null && pid.getValue().length() > 0) {
1136
		  return !pid.getValue().matches(".*\\s+.*");
1137
	  } 
1138
	  return false;
1139
  }
1140
  
1141
  
1142
  /**
1143
   * Insert or update an XML document into Metacat
1144
   * 
1145
   * @param xml - the XML document to insert or update
1146
   * @param pid - the identifier to be used for the resulting object
1147
   * 
1148
   * @return localId - the resulting docid of the document created or updated
1149
   * 
1150
   */
1151
  public String insertOrUpdateDocument(InputStream xml, String encoding,  Identifier pid, 
1152
    Session session, String insertOrUpdate) 
1153
    throws ServiceFailure, IOException {
1154
    
1155
  	logMetacat.debug("Starting to insert xml document...");
1156
    IdentifierManager im = IdentifierManager.getInstance();
1157

    
1158
    // generate pid/localId pair for sysmeta
1159
    String localId = null;
1160
    byte[] xmlBytes  = IOUtils.toByteArray(xml);
1161
    String xmlStr = new String(xmlBytes, encoding);
1162
    if(insertOrUpdate.equals("insert")) {
1163
      localId = im.generateLocalId(pid.getValue(), 1);
1164
      
1165
    } else {
1166
      //localid should already exist in the identifier table, so just find it
1167
      try {
1168
        logMetacat.debug("Updating pid " + pid.getValue());
1169
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
1170
        
1171
        localId = im.getLocalId(pid.getValue());
1172
        
1173
        logMetacat.debug("localId: " + localId);
1174
        //increment the revision
1175
        String docid = localId.substring(0, localId.lastIndexOf("."));
1176
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1177
        int rev = new Integer(revS).intValue();
1178
        rev++;
1179
        docid = docid + "." + rev;
1180
        localId = docid;
1181
        logMetacat.debug("incremented localId: " + localId);
1182
      
1183
      } catch(McdbDocNotFoundException e) {
1184
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
1185
            "pid " + pid.getValue() + 
1186
            " should have been in the identifier table, but it wasn't: " + 
1187
            e.getMessage());
1188
      
1189
      }
1190
      
1191
    }
1192

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

    
1293
    logMetacat.debug("Case DATA: starting to write to disk.");
1294
	if (locked) {
1295

    
1296
          File dataDirectory = new File(datafilepath);
1297
          dataDirectory.mkdirs();
1298
  
1299
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1300
  
1301
          // TODO: Check that the file size matches SystemMetadata
1302
          // long size = newFile.length();
1303
          // if (size == 0) {
1304
          //     throw new IOException("Uploaded file is 0 bytes!");
1305
          // }
1306
  
1307
          // Register the file in the database (which generates an exception
1308
          // if the localId is not acceptable or other untoward things happen
1309
          try {
1310
            logMetacat.debug("Registering document...");
1311
            DocumentImpl.registerDocument(localId, "BIN", localId,
1312
                    username, groupnames);
1313
            logMetacat.debug("Registration step completed.");
1314
            
1315
          } catch (SQLException e) {
1316
            //newFile.delete();
1317
            logMetacat.debug("SQLE: " + e.getMessage());
1318
            e.printStackTrace(System.out);
1319
            throw new ServiceFailure("1190", "Registration failed: " + 
1320
            		e.getMessage());
1321
            
1322
          } catch (AccessionNumberException e) {
1323
            //newFile.delete();
1324
            logMetacat.debug("ANE: " + e.getMessage());
1325
            e.printStackTrace(System.out);
1326
            throw new ServiceFailure("1190", "Registration failed: " + 
1327
            	e.getMessage());
1328
            
1329
          } catch (Exception e) {
1330
            //newFile.delete();
1331
            logMetacat.debug("Exception: " + e.getMessage());
1332
            e.printStackTrace(System.out);
1333
            throw new ServiceFailure("1190", "Registration failed: " + 
1334
            	e.getMessage());
1335
          }
1336
  
1337
          logMetacat.debug("Logging the creation event.");
1338
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1339
  
1340
          // Schedule replication for this data file, the "insert" action is important here!
1341
          logMetacat.debug("Scheduling replication.");
1342
          ForceReplicationHandler frh = new ForceReplicationHandler(localId, "insert", false, null);
1343
      }
1344
      
1345
      return localId;
1346
    
1347
  }
1348

    
1349
  /**
1350
   * Insert a systemMetadata document and return its localId
1351
   */
1352
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1353
      throws ServiceFailure {
1354
      
1355
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1356
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1357
      logMetacat.debug("Inserting new system metadata with modified date " + 
1358
          sysmeta.getDateSysMetadataModified());
1359
      
1360
      //insert the system metadata
1361
      try {
1362
        // note: the calling subclass handles the map hazelcast lock/unlock
1363
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1364
      	// submit for indexing
1365
        MetacatSolrIndex.getInstance().submit(sysmeta.getIdentifier(), sysmeta, null, true);
1366
      } catch (Exception e) {
1367
          throw new ServiceFailure("1190", e.getMessage());
1368
          
1369
	    }  
1370
  }
1371

    
1372
  /**
1373
   * Update a systemMetadata document
1374
   * 
1375
   * @param sysMeta - the system metadata object in the system to update
1376
   */
1377
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1378
        throws ServiceFailure {
1379

    
1380
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1381
        sysMeta.setDateSysMetadataModified(new Date());
1382
        try {
1383
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1384
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1385
            // submit for indexing
1386
            MetacatSolrIndex.getInstance().submit(sysMeta.getIdentifier(), sysMeta, null, true);
1387
        } catch (Exception e) {
1388
            throw new ServiceFailure("4862", e.getMessage());
1389

    
1390
        } finally {
1391
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1392

    
1393
        }
1394

    
1395
    }
1396
    
1397
	public boolean updateSystemMetadata(Session session, Identifier pid,
1398
			SystemMetadata sysmeta) throws NotImplemented, NotAuthorized,
1399
			ServiceFailure, InvalidRequest, InvalidSystemMetadata, InvalidToken {
1400
		
1401
		// The lock to be used for this identifier
1402
      Lock lock = null;
1403

    
1404
      // TODO: control who can call this?
1405
      if (session == null) {
1406
          //TODO: many of the thrown exceptions do not use the correct error codes
1407
          //check these against the docs and correct them
1408
          throw new NotAuthorized("4861", "No Session - could not authorize for registration." +
1409
                  "  If you are not logged in, please do so and retry the request.");
1410
      }
1411
      
1412
      // verify that guid == SystemMetadata.getIdentifier()
1413
      logMetacat.debug("Comparing guid|sysmeta_guid: " + pid.getValue() + 
1414
          "|" + sysmeta.getIdentifier().getValue());
1415
      
1416
      if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
1417
          throw new InvalidRequest("4863", 
1418
              "The identifier in method call (" + pid.getValue() + 
1419
              ") does not match identifier in system metadata (" +
1420
              sysmeta.getIdentifier().getValue() + ").");
1421
      }
1422

    
1423
      // do the actual update
1424
      this.updateSystemMetadata(sysmeta);
1425
      
1426
      try {
1427
    	  String localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1428
    	  EventLog.getInstance().log(request.getRemoteAddr(), 
1429
    	          request.getHeader("User-Agent"), session.getSubject().getValue(), 
1430
    	          localId, "updateSystemMetadata");
1431
      } catch (McdbDocNotFoundException e) {
1432
    	  // do nothing, no localId to log with
1433
    	  logMetacat.warn("Could not log 'updateSystemMetadata' event because no localId was found for pid: " + pid.getValue());
1434
      }
1435
      
1436
      return true;
1437
	}
1438
  
1439
  /**
1440
   * Given a Permission, returns a list of all permissions that it encompasses
1441
   * Permissions are hierarchical so that WRITE also allows READ.
1442
   * @param permission
1443
   * @return list of included Permissions for the given permission
1444
   */
1445
  protected List<Permission> expandPermissions(Permission permission) {
1446
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1447
	    if (permission.equals(Permission.READ)) {
1448
	    	expandedPermissions.add(Permission.READ);
1449
	    }
1450
	    if (permission.equals(Permission.WRITE)) {
1451
	    	expandedPermissions.add(Permission.READ);
1452
	    	expandedPermissions.add(Permission.WRITE);
1453
	    }
1454
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1455
	    	expandedPermissions.add(Permission.READ);
1456
	    	expandedPermissions.add(Permission.WRITE);
1457
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1458
	    }
1459
	    return expandedPermissions;
1460
  }
1461

    
1462
  /*
1463
   * Write a stream to a file
1464
   * 
1465
   * @param dir - the directory to write to
1466
   * @param fileName - the file name to write to
1467
   * @param data - the object bytes as an input stream
1468
   * 
1469
   * @return newFile - the new file created
1470
   * 
1471
   * @throws ServiceFailure
1472
   */
1473
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1474
    throws ServiceFailure {
1475
    
1476
    File newFile = new File(dir, fileName);
1477
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1478

    
1479
    try {
1480
        if (newFile.createNewFile()) {
1481
          // write data stream to desired file
1482
          OutputStream os = new FileOutputStream(newFile);
1483
          long length = IOUtils.copyLarge(data, os);
1484
          os.flush();
1485
          os.close();
1486
        } else {
1487
          logMetacat.debug("File creation failed, or file already exists.");
1488
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1489
        }
1490
    } catch (FileNotFoundException e) {
1491
      logMetacat.debug("FNF: " + e.getMessage());
1492
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1493
                + e.getMessage());
1494
    } catch (IOException e) {
1495
      logMetacat.debug("IOE: " + e.getMessage());
1496
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1497
                + " " + e.getMessage());
1498
    }
1499

    
1500
    return newFile;
1501
  }
1502

    
1503
  /*
1504
   * Returns a list of nodes that have been registered with the DataONE infrastructure
1505
   * that match the given session subject
1506
   * @return nodes - List of nodes from the registry with a matching session subject
1507
   * 
1508
   * @throws ServiceFailure
1509
   * @throws NotImplemented
1510
   */
1511
  protected List<Node> listNodesBySubject(Subject subject) 
1512
      throws ServiceFailure, NotImplemented {
1513
      List<Node> nodeList = new ArrayList<Node>();
1514
      
1515
      CNode cn = D1Client.getCN();
1516
      List<Node> nodes = cn.listNodes().getNodeList();
1517
      
1518
      // find the node in the node list
1519
      for ( Node node : nodes ) {
1520
          
1521
          List<Subject> nodeSubjects = node.getSubjectList();
1522
          if (nodeSubjects != null) {    
1523
	          // check if the session subject is in the node subject list
1524
	          for (Subject nodeSubject : nodeSubjects) {
1525
	              if ( nodeSubject.equals(subject) ) { // subject of session == node subject
1526
	                  nodeList.add(node);  
1527
	              }                              
1528
	          }
1529
          }
1530
      }
1531
      
1532
      return nodeList;
1533
      
1534
  }
1535

    
1536
  /**
1537
   * Archives an object, where the object is either a 
1538
   * data object or a science metadata object.
1539
   * 
1540
   * @param session - the Session object containing the credentials for the Subject
1541
   * @param pid - The object identifier to be archived
1542
   * 
1543
   * @return pid - the identifier of the object used for the archiving
1544
   * 
1545
   * @throws InvalidToken
1546
   * @throws ServiceFailure
1547
   * @throws NotAuthorized
1548
   * @throws NotFound
1549
   * @throws NotImplemented
1550
   * @throws InvalidRequest
1551
   */
1552
  public Identifier archive(Session session, Identifier pid) 
1553
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1554

    
1555
      String localId = null;
1556
      boolean allowed = false;
1557
      String username = Constants.SUBJECT_PUBLIC;
1558
      String[] groupnames = null;
1559
      if (session == null) {
1560
      	throw new InvalidToken("1330", "No session has been provided");
1561
      } else {
1562
          username = session.getSubject().getValue();
1563
          if (session.getSubjectInfo() != null) {
1564
              List<Group> groupList = session.getSubjectInfo().getGroupList();
1565
              if (groupList != null) {
1566
                  groupnames = new String[groupList.size()];
1567
                  for (int i = 0; i < groupList.size(); i++) {
1568
                      groupnames[i] = groupList.get(i).getGroupName();
1569
                  }
1570
              }
1571
          }
1572
      }
1573

    
1574
      // do we have a valid pid?
1575
      if (pid == null || pid.getValue().trim().equals("")) {
1576
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
1577
      }
1578

    
1579
      // check for the existing identifier
1580
      try {
1581
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1582
      } catch (McdbDocNotFoundException e) {
1583
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
1584
      }
1585

    
1586
      // does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
1587
      try {
1588
			allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
1589
		} catch (InvalidRequest e) {
1590
          throw new ServiceFailure("1350", e.getDescription());
1591
		}
1592
          
1593

    
1594
      if (allowed) {
1595
          try {
1596
              // archive the document
1597
              DocumentImpl.delete(localId, null, null, null, false);
1598
              EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
1599

    
1600
              // archive it
1601
              SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1602
              sysMeta.setArchived(true);
1603
              sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1604
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
1605
              // submit for indexing
1606
              // DocumentImpl call above should do this.
1607
              // see: https://projects.ecoinformatics.org/ecoinfo/issues/6030
1608
              //HazelcastService.getInstance().getIndexQueue().add(sysMeta);
1609
              
1610
          } catch (McdbDocNotFoundException e) {
1611
              throw new NotFound("1340", "The provided identifier was invalid.");
1612

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

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

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

    
1623
      } else {
1624
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
1625
      }
1626

    
1627
      return pid;
1628
  }
1629

    
1630

    
1631
}
(2-2/7)