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

    
407
      // Science metadata (XML) or science data object?
408
      // TODO: there are cases where certain object formats are science metadata
409
      // but are not XML (netCDF ...).  Handle this.
410
      if ( isScienceMetadata(sysmeta) ) {
411
        
412
        // CASE METADATA:
413
      	//String objectAsXML = "";
414
        try {
415
	        //objectAsXML = IOUtils.toString(object, "UTF-8");
416
	        localId = insertOrUpdateDocument(object,"UTF-8", pid, session, "insert");
417
	        //localId = im.getLocalId(pid.getValue());
418

    
419
        } catch (IOException e) {
420
        	String msg = "The Node is unable to create the object. " +
421
          "There was a problem converting the object to XML";
422
        	logMetacat.info(msg);
423
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
424

    
425
        }
426
                    
427
      } else {
428
	        
429
	      // DEFAULT CASE: DATA (needs to be checked and completed)
430
	      localId = insertDataObject(object, pid, session);
431
      }   
432
    
433
    }
434

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

    
454
    resultPid = pid;
455
    
456
    logMetacat.debug("create() complete for object: " + pid.getValue());
457

    
458
    return resultPid;
459
  }
460

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

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

    
504
    if ( start == null ) {
505
    	start = 0;	
506
    }
507
    
508
    if ( count == null ) {
509
    	count = 1000;
510
    }
511
    
512
    // safeguard against large requests
513
    if (count > MAXIMUM_DB_RECORD_COUNT) {
514
    	count = MAXIMUM_DB_RECORD_COUNT;
515
    }
516

    
517
    String[] filterDocid = null;
518
    if (pidFilter != null) {
519
		try {
520
	      String localId = im.getLocalId(pidFilter);
521
	      filterDocid = new String[] {localId};
522
	    } catch (Exception ex) { 
523
	    	String msg = "Could not find localId for given pidFilter '" + pidFilter + "'";
524
	        logMetacat.warn(msg, ex);
525
	        //throw new InvalidRequest("1480", msg);
526
	    }
527
    }
528
    
529
    logMetacat.debug("fromDate: " + fromDate);
530
    logMetacat.debug("toDate: " + toDate);
531

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

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

    
617
  /**
618
   * Return the system metadata for a given object
619
   * 
620
   * @param session - the Session object containing the credentials for the Subject
621
   * @param pid - the object identifier for the given object
622
   * 
623
   * @return inputStream - the input stream of the given system metadata object
624
   * 
625
   * @throws InvalidToken
626
   * @throws ServiceFailure
627
   * @throws NotAuthorized
628
   * @throws NotFound
629
   * @throws InvalidRequest
630
   * @throws NotImplemented
631
   */
632
    public SystemMetadata getSystemMetadata(Session session, Identifier pid)
633
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
634
        NotImplemented {
635

    
636
        boolean isAuthorized = false;
637
        SystemMetadata systemMetadata = null;
638
        List<Replica> replicaList = null;
639
        NodeReference replicaNodeRef = null;
640
        List<Node> nodeListBySubject = null;
641
        Subject subject = null;
642
        
643
        if (session != null ) {
644
            subject = session.getSubject();
645
        }
646
        
647
        // check normal authorization
648
        BaseException originalAuthorizationException = null;
649
        if (!isAuthorized) {
650
            try {
651
                isAuthorized = isAuthorized(session, pid, Permission.READ);
652

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

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

    
846
      boolean allowed = false;
847
      
848
      // must have a session in order to check admin 
849
      if (session == null) {
850
         logMetacat.debug("In isAdminAuthorized(), session is null ");
851
         return false;
852
      }
853
      
854
      logMetacat.debug("In isAdminAuthorized(), checking CN or MN authorization for " +
855
           session.getSubject().getValue());
856
      
857
      // check if this is the node calling itself (MN)
858
      allowed = isNodeAdmin(session);
859
      
860
      // check the CN list
861
      if (!allowed) {
862
	      List<Node> nodes = null;
863

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

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

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

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

    
1104
  /** 
1105
   * Determine if a given object should be treated as an XML science metadata
1106
   * object. 
1107
   * 
1108
   * @param sysmeta - the SystemMetadata describing the object
1109
   * @return true if the object should be treated as science metadata
1110
   */
1111
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
1112
    
1113
    ObjectFormat objectFormat = null;
1114
    boolean isScienceMetadata = false;
1115
    
1116
    try {
1117
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
1118
      if ( objectFormat.getFormatType().equals("METADATA") ) {
1119
      	isScienceMetadata = true;
1120
      	
1121
      }
1122
      
1123
       
1124
    } catch (ServiceFailure e) {
1125
      logMetacat.debug("There was a problem determining if the object identified by" + 
1126
          sysmeta.getIdentifier().getValue() + 
1127
          " is science metadata: " + e.getMessage());
1128
    
1129
    } catch (NotFound e) {
1130
      logMetacat.debug("There was a problem determining if the object identified by" + 
1131
          sysmeta.getIdentifier().getValue() + 
1132
          " is science metadata: " + e.getMessage());
1133
    
1134
    }
1135
    
1136
    return isScienceMetadata;
1137

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

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

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

    
1305
    logMetacat.debug("Case DATA: starting to write to disk.");
1306
	if (locked) {
1307

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

    
1361
  /**
1362
   * Insert a systemMetadata document and return its localId
1363
   */
1364
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1365
      throws ServiceFailure {
1366
      
1367
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1368
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1369
      logMetacat.debug("Inserting new system metadata with modified date " + 
1370
          sysmeta.getDateSysMetadataModified());
1371
      
1372
      //insert the system metadata
1373
      try {
1374
        // note: the calling subclass handles the map hazelcast lock/unlock
1375
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1376
      	// submit for indexing
1377
        MetacatSolrIndex.getInstance().submit(sysmeta.getIdentifier(), sysmeta, null, true);
1378
      } catch (Exception e) {
1379
          throw new ServiceFailure("1190", e.getMessage());
1380
          
1381
	    }  
1382
  }
1383

    
1384
  /**
1385
   * Update a systemMetadata document
1386
   * 
1387
   * @param sysMeta - the system metadata object in the system to update
1388
   */
1389
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1390
        throws ServiceFailure {
1391

    
1392
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1393
        sysMeta.setDateSysMetadataModified(new Date());
1394
        try {
1395
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1396
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1397
            // submit for indexing
1398
            MetacatSolrIndex.getInstance().submit(sysMeta.getIdentifier(), sysMeta, null, true);
1399
        } catch (Exception e) {
1400
            throw new ServiceFailure("4862", e.getMessage());
1401

    
1402
        } finally {
1403
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1404

    
1405
        }
1406

    
1407
    }
1408
    
1409
	public boolean updateSystemMetadata(Session session, Identifier pid,
1410
			SystemMetadata sysmeta) throws NotImplemented, NotAuthorized,
1411
			ServiceFailure, InvalidRequest, InvalidSystemMetadata, InvalidToken {
1412
		
1413
		// The lock to be used for this identifier
1414
      Lock lock = null;
1415

    
1416
      // TODO: control who can call this?
1417
      if (session == null) {
1418
          //TODO: many of the thrown exceptions do not use the correct error codes
1419
          //check these against the docs and correct them
1420
          throw new NotAuthorized("4861", "No Session - could not authorize for registration." +
1421
                  "  If you are not logged in, please do so and retry the request.");
1422
      }
1423
      
1424
      // verify that guid == SystemMetadata.getIdentifier()
1425
      logMetacat.debug("Comparing guid|sysmeta_guid: " + pid.getValue() + 
1426
          "|" + sysmeta.getIdentifier().getValue());
1427
      
1428
      if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
1429
          throw new InvalidRequest("4863", 
1430
              "The identifier in method call (" + pid.getValue() + 
1431
              ") does not match identifier in system metadata (" +
1432
              sysmeta.getIdentifier().getValue() + ").");
1433
      }
1434

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

    
1474
  /*
1475
   * Write a stream to a file
1476
   * 
1477
   * @param dir - the directory to write to
1478
   * @param fileName - the file name to write to
1479
   * @param data - the object bytes as an input stream
1480
   * 
1481
   * @return newFile - the new file created
1482
   * 
1483
   * @throws ServiceFailure
1484
   */
1485
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1486
    throws ServiceFailure {
1487
    
1488
    File newFile = new File(dir, fileName);
1489
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1490

    
1491
    try {
1492
        if (newFile.createNewFile()) {
1493
          // write data stream to desired file
1494
          OutputStream os = new FileOutputStream(newFile);
1495
          long length = IOUtils.copyLarge(data, os);
1496
          os.flush();
1497
          os.close();
1498
        } else {
1499
          logMetacat.debug("File creation failed, or file already exists.");
1500
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1501
        }
1502
    } catch (FileNotFoundException e) {
1503
      logMetacat.debug("FNF: " + e.getMessage());
1504
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1505
                + e.getMessage());
1506
    } catch (IOException e) {
1507
      logMetacat.debug("IOE: " + e.getMessage());
1508
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1509
                + " " + e.getMessage());
1510
    }
1511

    
1512
    return newFile;
1513
  }
1514

    
1515
  /*
1516
   * Returns a list of nodes that have been registered with the DataONE infrastructure
1517
   * that match the given session subject
1518
   * @return nodes - List of nodes from the registry with a matching session subject
1519
   * 
1520
   * @throws ServiceFailure
1521
   * @throws NotImplemented
1522
   */
1523
  protected List<Node> listNodesBySubject(Subject subject) 
1524
      throws ServiceFailure, NotImplemented {
1525
      List<Node> nodeList = new ArrayList<Node>();
1526
      
1527
      CNode cn = D1Client.getCN();
1528
      List<Node> nodes = cn.listNodes().getNodeList();
1529
      
1530
      // find the node in the node list
1531
      for ( Node node : nodes ) {
1532
          
1533
          List<Subject> nodeSubjects = node.getSubjectList();
1534
          if (nodeSubjects != null) {    
1535
	          // check if the session subject is in the node subject list
1536
	          for (Subject nodeSubject : nodeSubjects) {
1537
	              if ( nodeSubject.equals(subject) ) { // subject of session == node subject
1538
	                  nodeList.add(node);  
1539
	              }                              
1540
	          }
1541
          }
1542
      }
1543
      
1544
      return nodeList;
1545
      
1546
  }
1547

    
1548
  /**
1549
   * Archives an object, where the object is either a 
1550
   * data object or a science metadata object.
1551
   * 
1552
   * @param session - the Session object containing the credentials for the Subject
1553
   * @param pid - The object identifier to be archived
1554
   * 
1555
   * @return pid - the identifier of the object used for the archiving
1556
   * 
1557
   * @throws InvalidToken
1558
   * @throws ServiceFailure
1559
   * @throws NotAuthorized
1560
   * @throws NotFound
1561
   * @throws NotImplemented
1562
   * @throws InvalidRequest
1563
   */
1564
  public Identifier archive(Session session, Identifier pid) 
1565
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1566

    
1567
      String localId = null;
1568
      boolean allowed = false;
1569
      String username = Constants.SUBJECT_PUBLIC;
1570
      String[] groupnames = null;
1571
      if (session == null) {
1572
      	throw new InvalidToken("1330", "No session has been provided");
1573
      } else {
1574
          username = session.getSubject().getValue();
1575
          if (session.getSubjectInfo() != null) {
1576
              List<Group> groupList = session.getSubjectInfo().getGroupList();
1577
              if (groupList != null) {
1578
                  groupnames = new String[groupList.size()];
1579
                  for (int i = 0; i < groupList.size(); i++) {
1580
                      groupnames[i] = groupList.get(i).getGroupName();
1581
                  }
1582
              }
1583
          }
1584
      }
1585

    
1586
      // do we have a valid pid?
1587
      if (pid == null || pid.getValue().trim().equals("")) {
1588
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
1589
      }
1590

    
1591
      // check for the existing identifier
1592
      try {
1593
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1594
      } catch (McdbDocNotFoundException e) {
1595
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
1596
      }
1597

    
1598
      // does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
1599
      try {
1600
			allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
1601
		} catch (InvalidRequest e) {
1602
          throw new ServiceFailure("1350", e.getDescription());
1603
		}
1604
          
1605

    
1606
      if (allowed) {
1607
          try {
1608
              // archive the document
1609
              DocumentImpl.delete(localId, null, null, null, false);
1610
              EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
1611

    
1612
              // archive it
1613
              SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1614
              sysMeta.setArchived(true);
1615
              sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1616
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
1617
              // submit for indexing
1618
              // DocumentImpl call above should do this.
1619
              // see: https://projects.ecoinformatics.org/ecoinfo/issues/6030
1620
              //HazelcastService.getInstance().getIndexQueue().add(sysMeta);
1621
              
1622
          } catch (McdbDocNotFoundException e) {
1623
              throw new NotFound("1340", "The provided identifier was invalid.");
1624

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

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

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

    
1635
      } else {
1636
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
1637
      }
1638

    
1639
      return pid;
1640
  }
1641

    
1642

    
1643
}
(2-2/7)