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: leinfelder $'
7
 *     '$Date: 2012-07-02 12:06:42 -0700 (Mon, 02 Jul 2012) $'
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.Arrays;
35
import java.util.Calendar;
36
import java.util.Date;
37
import java.util.Hashtable;
38
import java.util.List;
39
import java.util.Set;
40
import java.util.Timer;
41
import java.util.Vector;
42

    
43
import javax.servlet.http.HttpServletRequest;
44

    
45

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

    
83
import edu.ucsb.nceas.metacat.AccessionNumberException;
84
import edu.ucsb.nceas.metacat.DocumentImpl;
85
import edu.ucsb.nceas.metacat.EventLog;
86
import edu.ucsb.nceas.metacat.IdentifierManager;
87
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
88
import edu.ucsb.nceas.metacat.MetacatHandler;
89
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
90
import edu.ucsb.nceas.metacat.database.DBConnection;
91
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
92
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
93
import edu.ucsb.nceas.metacat.properties.PropertyService;
94
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
95
import edu.ucsb.nceas.metacat.util.DocumentUtil;
96
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
97

    
98
public abstract class D1NodeService {
99
  
100
  private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
101

    
102
  /** For logging the operations */
103
  protected HttpServletRequest request;
104
  
105
  /* reference to the metacat handler */
106
  protected MetacatHandler handler;
107
  
108
  /* parameters set in the incoming request */
109
  private Hashtable<String, String[]> params;
110

    
111
  /**
112
   * Constructor - used to set the metacatUrl from a subclass extending D1NodeService
113
   * 
114
   * @param metacatUrl - the URL of the metacat service, including the ending /d1
115
   */
116
  public D1NodeService(HttpServletRequest request) {
117
		this.request = request;
118
	}
119
  
120
  /**
121
   * This method provides a lighter weight mechanism than 
122
   * getSystemMetadata() for a client to determine basic 
123
   * properties of the referenced object.
124
   * 
125
   * @param session - the Session object containing the credentials for the Subject
126
   * @param pid - the identifier of the object to be described
127
   * 
128
   * @return describeResponse - A set of values providing a basic description 
129
   *                            of the object.
130
   * 
131
   * @throws InvalidToken
132
   * @throws ServiceFailure
133
   * @throws NotAuthorized
134
   * @throws NotFound
135
   * @throws NotImplemented
136
   * @throws InvalidRequest
137
   */
138
  public DescribeResponse describe(Session session, Identifier pid) 
139
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
140

    
141
    // get system metadata and construct the describe response
142
      SystemMetadata sysmeta = getSystemMetadata(session, pid);
143
      DescribeResponse describeResponse = 
144
      	new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(), 
145
      			sysmeta.getDateSysMetadataModified(),
146
      			sysmeta.getChecksum(), sysmeta.getSerialVersion());
147

    
148
      return describeResponse;
149

    
150
  }
151
  
152
  /**
153
   * Deletes an object from the Member Node, where the object is either a 
154
   * data object or a science metadata object.
155
   * 
156
   * @param session - the Session object containing the credentials for the Subject
157
   * @param pid - The object identifier to be deleted
158
   * 
159
   * @return pid - the identifier of the object used for the deletion
160
   * 
161
   * @throws InvalidToken
162
   * @throws ServiceFailure
163
   * @throws NotAuthorized
164
   * @throws NotFound
165
   * @throws NotImplemented
166
   * @throws InvalidRequest
167
   */
168
  public Identifier delete(Session session, Identifier pid) 
169
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
170

    
171
      String localId = null;
172
      if (session == null) {
173
      	throw new InvalidToken("1330", "No session has been provided");
174
      }
175
      // just for logging purposes
176
      String username = session.getSubject().getValue();
177

    
178
      // do we have a valid pid?
179
      if (pid == null || pid.getValue().trim().equals("")) {
180
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
181
      }
182

    
183
      // check for the existing identifier
184
      try {
185
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
186
      } catch (McdbDocNotFoundException e) {
187
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
188
      }
189
      
190
      try {
191
          // delete the document, as admin
192
          DocumentImpl.delete(localId, null, null, null, true);
193
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
194

    
195
          // archive it
196
          SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
197
          sysMeta.setArchived(true);
198
          sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
199
          HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
200
          
201
      } catch (McdbDocNotFoundException e) {
202
          throw new NotFound("1340", "The provided identifier was invalid.");
203

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

    
207
      } catch (InsufficientKarmaException e) {
208
          if ( logMetacat.isDebugEnabled() ) {
209
              e.printStackTrace();
210
          }
211
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
212
      
213
      } catch (Exception e) { // for some reason DocumentImpl throws a general Exception
214
          throw new ServiceFailure("1350", "There was a problem deleting the object." + "The error message was: " + e.getMessage());
215
      }
216

    
217
      return pid;
218
  }
219
  
220
  /**
221
   * Low level, "are you alive" operation. A valid ping response is 
222
   * indicated by a HTTP status of 200.
223
   * 
224
   * @return true if the service is alive
225
   * 
226
   * @throws NotImplemented
227
   * @throws ServiceFailure
228
   * @throws InsufficientResources
229
   */
230
  public Date ping() 
231
      throws NotImplemented, ServiceFailure, InsufficientResources {
232

    
233
      // test if we can get a database connection
234
      int serialNumber = -1;
235
      DBConnection dbConn = null;
236
      try {
237
          dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
238
          serialNumber = dbConn.getCheckOutSerialNumber();
239
      } catch (SQLException e) {
240
      	ServiceFailure sf = new ServiceFailure("", e.getMessage());
241
      	sf.initCause(e);
242
          throw sf;
243
      } finally {
244
          // Return the database connection
245
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
246
      }
247

    
248
      return Calendar.getInstance().getTime();
249
  }
250
  
251
  /**
252
   * Adds a new object to the Node, where the object is either a data 
253
   * object or a science metadata object. This method is called by clients 
254
   * to create new data objects on Member Nodes or internally for Coordinating
255
   * Nodes
256
   * 
257
   * @param session - the Session object containing the credentials for the Subject
258
   * @param pid - The object identifier to be created
259
   * @param object - the object bytes
260
   * @param sysmeta - the system metadata that describes the object  
261
   * 
262
   * @return pid - the object identifier created
263
   * 
264
   * @throws InvalidToken
265
   * @throws ServiceFailure
266
   * @throws NotAuthorized
267
   * @throws IdentifierNotUnique
268
   * @throws UnsupportedType
269
   * @throws InsufficientResources
270
   * @throws InvalidSystemMetadata
271
   * @throws NotImplemented
272
   * @throws InvalidRequest
273
   */
274
  public Identifier create(Session session, Identifier pid, InputStream object,
275
    SystemMetadata sysmeta) 
276
    throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
277
    UnsupportedType, InsufficientResources, InvalidSystemMetadata, 
278
    NotImplemented, InvalidRequest {
279

    
280
    Identifier resultPid = null;
281
    String localId = null;
282
    boolean allowed = false;
283
    
284
    // check for null session
285
    if (session == null) {
286
    	throw new InvalidToken("4894", "Session is required to WRITE to the Node.");
287
    }
288
    Subject subject = session.getSubject();
289

    
290
    Subject publicSubject = new Subject();
291
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
292
	// be sure the user is authenticated for create()
293
    if (subject == null || subject.getValue() == null || 
294
        subject.equals(publicSubject) ) {
295
      throw new NotAuthorized("1100", "The provided identity does not have " +
296
        "permission to WRITE to the Node.");
297
      
298
    }
299
    
300
    // verify that pid == SystemMetadata.getIdentifier()
301
    logMetacat.debug("Comparing pid|sysmeta_pid: " + 
302
      pid.getValue() + "|" + sysmeta.getIdentifier().getValue());
303
    if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
304
        throw new InvalidSystemMetadata("1180", 
305
            "The supplied system metadata is invalid. " +
306
            "The identifier " + pid.getValue() + " does not match identifier" +
307
            "in the system metadata identified by " +
308
            sysmeta.getIdentifier().getValue() + ".");
309
        
310
    }
311

    
312
    logMetacat.debug("Checking if identifier exists: " + pid.getValue());
313
    // Check that the identifier does not already exist
314
    if (IdentifierManager.getInstance().identifierExists(pid.getValue())) {
315
	    	throw new IdentifierNotUnique("1120", 
316
			          "The requested identifier " + pid.getValue() +
317
			          " is already used by another object and" +
318
			          "therefore can not be used for this object. Clients should choose" +
319
			          "a new identifier that is unique and retry the operation or " +
320
			          "use CN.reserveIdentifier() to reserve one.");
321
    	
322
    }
323
    
324
    // TODO: this probably needs to be refined more
325
    try {
326
      allowed = isAuthorized(session, pid, Permission.WRITE);
327
            
328
    } catch (NotFound e) {
329
      // The identifier doesn't exist, writing should be fine.
330
      allowed = true;
331
    }
332
    
333
    // verify checksum, only if we can reset the inputstream
334
    if (object.markSupported()) {
335
        logMetacat.debug("Checking checksum for: " + pid.getValue());
336
	    String checksumAlgorithm = sysmeta.getChecksum().getAlgorithm();
337
	    String checksumValue = sysmeta.getChecksum().getValue();
338
	    try {
339
			String computedChecksumValue = ChecksumUtil.checksum(object, checksumAlgorithm).getValue();
340
			// it's very important that we don't consume the stream
341
			object.reset();
342
			if (!computedChecksumValue.equals(checksumValue)) {
343
			    logMetacat.error("Checksum for " + pid.getValue() + " does not match system metadata, computed = " + computedChecksumValue );
344
				throw new InvalidSystemMetadata("4896", "Checksum given does not match that of the object");
345
			}
346
		} catch (Exception e) {
347
			String msg = "Error verifying checksum values";
348
	      	logMetacat.error(msg, e);
349
	        throw new ServiceFailure("1190", msg + ": " + e.getMessage());
350
		}
351
    } else {
352
    	logMetacat.warn("mark is not supported on the object's input stream - cannot verify checksum without consuming stream");
353
    }
354
    	
355
    // we have the go ahead
356
    if ( allowed ) {
357
      
358
        logMetacat.debug("Allowed to insert: " + pid.getValue());
359

    
360
      // Science metadata (XML) or science data object?
361
      // TODO: there are cases where certain object formats are science metadata
362
      // but are not XML (netCDF ...).  Handle this.
363
      if ( isScienceMetadata(sysmeta) ) {
364
        
365
        // CASE METADATA:
366
      	String objectAsXML = "";
367
        try {
368
	        objectAsXML = IOUtils.toString(object, "UTF-8");
369
	        localId = insertOrUpdateDocument(objectAsXML, pid, session, "insert");
370
	        //localId = im.getLocalId(pid.getValue());
371

    
372
        } catch (IOException e) {
373
        	String msg = "The Node is unable to create the object. " +
374
          "There was a problem converting the object to XML";
375
        	logMetacat.info(msg);
376
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
377

    
378
        }
379
                    
380
      } else {
381
	        
382
	      // DEFAULT CASE: DATA (needs to be checked and completed)
383
	      localId = insertDataObject(object, pid, session);
384
      }   
385
    
386
    }
387

    
388
    logMetacat.debug("Done inserting new object: " + pid.getValue());
389
    
390
    // save the sysmeta
391
    try {
392
      // lock and unlock of the pid happens in the subclass
393
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
394
    	
395
    } catch (Exception e) {
396
    	logMetacat.error("Problem creating system metadata: " + pid.getValue(), e);
397
        throw new ServiceFailure("1190", e.getMessage());
398
	}
399
    
400
    // setting the resulting identifier failed
401
    if (localId == null ) {
402
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
403
    }
404

    
405
    resultPid = pid;
406
    
407
    logMetacat.debug("create() complete for object: " + pid.getValue());
408

    
409
    return resultPid;
410
  }
411

    
412
  /**
413
   * Return the log records associated with a given event between the start and 
414
   * end dates listed given a particular Subject listed in the Session
415
   * 
416
   * @param session - the Session object containing the credentials for the Subject
417
   * @param fromDate - the start date of the desired log records
418
   * @param toDate - the end date of the desired log records
419
   * @param event - restrict log records of a specific event type
420
   * @param start - zero based offset from the first record in the 
421
   *                set of matching log records. Used to assist with 
422
   *                paging the response.
423
   * @param count - maximum number of log records to return in the response. 
424
   *                Used to assist with paging the response.
425
   * 
426
   * @return the desired log records
427
   * 
428
   * @throws InvalidToken
429
   * @throws ServiceFailure
430
   * @throws NotAuthorized
431
   * @throws InvalidRequest
432
   * @throws NotImplemented
433
   */
434
  public Log getLogRecords(Session session, Date fromDate, Date toDate, 
435
      Event event, String pidFilter, Integer start, Integer count) throws InvalidToken, ServiceFailure,
436
      NotAuthorized, InvalidRequest, NotImplemented {
437

    
438
	  // only admin access to this method
439
	  // see https://redmine.dataone.org/issues/2855
440
	  if (!isAdminAuthorized(session)) {
441
		  throw new NotAuthorized("1460", "Only the CN or admin is allowed to harvest logs from this node");
442
	  }
443
	  
444
    IdentifierManager im = IdentifierManager.getInstance();
445
    EventLog el = EventLog.getInstance();
446
    if ( fromDate == null ) {
447
      logMetacat.debug("setting fromdate from null");
448
      fromDate = new Date(1);
449
    }
450
    if ( toDate == null ) {
451
      logMetacat.debug("setting todate from null");
452
      toDate = new Date();
453
    }
454

    
455
    if ( start == null ) {
456
    	start = 0;	
457
    }
458
    
459
    if ( count == null ) {
460
    	count = 1000;
461
    }
462

    
463
    String[] filterDocid = null;
464
    if (pidFilter != null) {
465
		try {
466
	      String localId = im.getLocalId(pidFilter);
467
	      filterDocid = new String[] {localId};
468
	    } catch (Exception ex) { 
469
	    	String msg = "Could not find localId for given pidFilter '" + pidFilter + "'";
470
	        logMetacat.warn(msg, ex);
471
	        //throw new InvalidRequest("1480", msg);
472
	    }
473
    }
474
    
475
    logMetacat.debug("fromDate: " + fromDate);
476
    logMetacat.debug("toDate: " + toDate);
477

    
478
    Log log = el.getD1Report(null, null, filterDocid, event,
479
        new java.sql.Timestamp(fromDate.getTime()),
480
        new java.sql.Timestamp(toDate.getTime()), false, start, count);
481
    
482
    logMetacat.info("getLogRecords");
483
    return log;
484
  }
485
    
486
  /**
487
   * Return the object identified by the given object identifier
488
   * 
489
   * @param session - the Session object containing the credentials for the Subject
490
   * @param pid - the object identifier for the given object
491
   * 
492
   * TODO: The D1 Authorization API doesn't provide information on which 
493
   * authentication system the Subject belongs to, and so it's not possible to
494
   * discern which Person or Group is a valid KNB LDAP DN.  Fix this.
495
   * 
496
   * @return inputStream - the input stream of the given object
497
   * 
498
   * @throws InvalidToken
499
   * @throws ServiceFailure
500
   * @throws NotAuthorized
501
   * @throws InvalidRequest
502
   * @throws NotImplemented
503
   */
504
  public InputStream get(Session session, Identifier pid) 
505
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
506
    NotImplemented {
507
    
508
    InputStream inputStream = null; // bytes to be returned
509
    handler = new MetacatHandler(new Timer());
510
    boolean allowed = false;
511
    String localId; // the metacat docid for the pid
512
    
513
    // get the local docid from Metacat
514
    try {
515
      localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
516
    
517
    } catch (McdbDocNotFoundException e) {
518
      throw new NotFound("1020", "The object specified by " + 
519
                         pid.getValue() +
520
                         " does not exist at this node.");
521
    }
522
    
523
    // check for authorization
524
    try {
525
		allowed = isAuthorized(session, pid, Permission.READ);
526
	} catch (InvalidRequest e) {
527
		throw new ServiceFailure("1030", e.getDescription());
528
	}
529
    
530
    // if the person is authorized, perform the read
531
    if (allowed) {
532
      try {
533
        inputStream = handler.read(localId);
534
      } catch (Exception e) {
535
        throw new NotFound("1020", "The object specified by " + 
536
            pid.getValue() +
537
            "could not be returned due to error: " +
538
            e.getMessage());
539
      }
540
    }
541

    
542
    // if we fail to set the input stream
543
    if ( inputStream == null ) {
544
      throw new NotFound("1020", "The object specified by " + 
545
                         pid.getValue() +
546
                         "does not exist at this node.");
547
    }
548
    
549
	// log the read event
550
    String principal = Constants.SUBJECT_PUBLIC;
551
    if (session != null && session.getSubject() != null) {
552
    	principal = session.getSubject().getValue();
553
    }
554
    EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "read");
555
    
556
    return inputStream;
557
  }
558

    
559
  /**
560
   * Return the system metadata for a given object
561
   * 
562
   * @param session - the Session object containing the credentials for the Subject
563
   * @param pid - the object identifier for the given object
564
   * 
565
   * @return inputStream - the input stream of the given system metadata object
566
   * 
567
   * @throws InvalidToken
568
   * @throws ServiceFailure
569
   * @throws NotAuthorized
570
   * @throws NotFound
571
   * @throws InvalidRequest
572
   * @throws NotImplemented
573
   */
574
    public SystemMetadata getSystemMetadata(Session session, Identifier pid)
575
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
576
        NotImplemented {
577

    
578
        boolean isAuthorized = false;
579
        SystemMetadata systemMetadata = null;
580
        List<Replica> replicaList = null;
581
        NodeReference replicaNodeRef = null;
582
        List<Node> nodeListBySubject = null;
583
        Subject subject = null;
584
        
585
        if (session != null ) {
586
            subject = session.getSubject();
587
        }
588
        
589
        // check normal authorization
590
        BaseException originalAuthorizationException = null;
591
        if (!isAuthorized) {
592
            try {
593
                isAuthorized = isAuthorized(session, pid, Permission.READ);
594

    
595
            } catch (InvalidRequest e) {
596
                throw new ServiceFailure("1090", e.getDescription());
597
            } catch (NotAuthorized nae) {
598
            	// catch this for later
599
            	originalAuthorizationException = nae;
600
			}
601
        }
602
        
603
        // get the system metadata first because we need the replica list for auth
604
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
605
        
606
        // check the replica information to expand access to MNs that might need it
607
        if (!isAuthorized) {
608
        	
609
	        try {
610
	        	
611
	            // if MNs are listed as replicas, allow access
612
	            if ( systemMetadata != null ) {
613
	                replicaList = systemMetadata.getReplicaList();
614
	                // only check if there are in fact replicas listed
615
	                if ( replicaList != null ) {
616
	                    
617
	                    if ( subject != null ) {
618
	                        // get the list of nodes with a matching node subject
619
	                        try {
620
	                            nodeListBySubject = listNodesBySubject(session.getSubject());
621
	
622
	                        } catch (BaseException e) {
623
	                            // Unexpected error contacting the CN via D1Client
624
	                            String msg = "Caught an unexpected error while trying "
625
	                                    + "to potentially authorize system metadata access "
626
	                                    + "based on the session subject. The error was "
627
	                                    + e.getMessage();
628
	                            logMetacat.error(msg);
629
	                            if (logMetacat.isDebugEnabled()) {
630
	                                e.printStackTrace();
631
	
632
	                            }
633
	                            // isAuthorized is still false 
634
	                        }
635
	
636
	                    }
637
	                    if (nodeListBySubject != null) {
638
	                        // compare node ids to replica node ids
639
	                        outer: for (Replica replica : replicaList) {
640
	                            replicaNodeRef = replica.getReplicaMemberNode();
641
	
642
	                            for (Node node : nodeListBySubject) {
643
	                                if (node.getIdentifier().equals(replicaNodeRef)) {
644
	                                    // node id via session subject matches a replica node
645
	                                    isAuthorized = true;
646
	                                    break outer;
647
	                                }
648
	                            }
649
	                        }
650
	                    }
651
	                }
652
	            }
653
	            
654
	            // if we still aren't authorized, then we are done
655
	            if (!isAuthorized) {
656
	                throw new NotAuthorized("1400", Permission.READ
657
	                        + " not allowed on " + pid.getValue());
658
	            }
659

    
660
	        } catch (RuntimeException e) {
661
	        	e.printStackTrace();
662
	            // convert hazelcast RuntimeException to ServiceFailure
663
	            throw new ServiceFailure("1090", "Unexpected error getting system metadata for: " + 
664
	                pid.getValue());	
665
	        }
666
	        
667
        }
668
        
669
        // It wasn't in the map
670
        if ( systemMetadata == null ) {
671
            throw new NotFound("1420", "No record found for: " + pid.getValue());
672
        }
673
        
674
        return systemMetadata;
675
    }
676
     
677
  /**
678
   * Test if the user identified by the provided token has administrative authorization 
679
   * 
680
   * @param session - the Session object containing the credentials for the Subject
681
   * 
682
   * @return true if the user is admin
683
   * 
684
   * @throws ServiceFailure
685
   * @throws InvalidToken
686
   * @throws NotFound
687
   * @throws NotAuthorized
688
   * @throws NotImplemented
689
   */
690
  public boolean isAdminAuthorized(Session session) 
691
      throws ServiceFailure, InvalidToken, NotAuthorized,
692
      NotImplemented {
693

    
694
      boolean allowed = false;
695
      
696
      // must have a session in order to check admin 
697
      if (session == null) {
698
         logMetacat.debug("In isAdminAuthorized(), session is null ");
699
         return false;
700
      }
701
      
702
      logMetacat.debug("In isAdminAuthorized(), checking CN or MN authorization for " +
703
           session.getSubject().getValue());
704
      
705
      // are we allowed to do this? only CNs are allowed
706
      CNode cn = D1Client.getCN();
707
      List<Node> nodes = cn.listNodes().getNodeList();
708
      
709
      if ( nodes == null ) {
710
          throw new ServiceFailure("4852", "Couldn't get node list.");
711
  
712
      }
713
      
714
      // find the node in the node list
715
      for ( Node node : nodes ) {
716
          
717
          NodeReference nodeReference = node.getIdentifier();
718
          logMetacat.debug("In isAdminAuthorized(), Node reference is: " + nodeReference.getValue());
719
          
720
          Subject subject = session.getSubject();
721
          
722
          if (node.getType() == NodeType.CN) {
723
              List<Subject> nodeSubjects = node.getSubjectList();
724
              
725
              // check if the session subject is in the node subject list
726
              for (Subject nodeSubject : nodeSubjects) {
727
                  logMetacat.debug("In isAdminAuthorized(), comparing subjects: " +
728
                      nodeSubject.getValue() + " and " + subject.getValue());
729
                  if ( nodeSubject.equals(subject) ) {
730
                      allowed = true; // subject of session == target node subject
731
                      break;
732
                      
733
                  }
734
              }              
735
          }
736
      }
737

    
738
      
739
      return allowed;
740
  }
741
  
742
  /**
743
   * Test if the user identified by the provided token has administrative authorization 
744
   * on this node because they are calling themselves
745
   * 
746
   * @param session - the Session object containing the credentials for the Subject
747
   * 
748
   * @return true if the user is this node
749
   * @throws ServiceFailure 
750
   * @throws NotImplemented 
751
   */
752
  public boolean isNodeAdmin(Session session) throws NotImplemented, ServiceFailure {
753

    
754
      boolean allowed = false;
755
      
756
      // must have a session in order to check admin 
757
      if (session == null) {
758
         logMetacat.debug("In isNodeAdmin(), session is null ");
759
         return false;
760
      }
761
      
762
      logMetacat.debug("In isNodeAdmin(), MN authorization for " +
763
           session.getSubject().getValue());
764
      
765
      Node node = MNodeService.getInstance(request).getCapabilities();
766
      NodeReference nodeReference = node.getIdentifier();
767
      logMetacat.debug("In isNodeAdmin(), Node reference is: " + nodeReference.getValue());
768
      
769
      Subject subject = session.getSubject();
770
      
771
      if (node.getType() == NodeType.MN) {
772
          List<Subject> nodeSubjects = node.getSubjectList();
773
          
774
          // check if the session subject is in the node subject list
775
          for (Subject nodeSubject : nodeSubjects) {
776
              logMetacat.debug("In isNodeAdmin(), comparing subjects: " +
777
                  nodeSubject.getValue() + " and " + subject.getValue());
778
              if ( nodeSubject.equals(subject) ) {
779
                  allowed = true; // subject of session == this node's subect
780
                  break;
781
              }
782
          }              
783
      }
784
      
785
      return allowed;
786
  }
787
  
788
  /**
789
   * Test if the user identified by the provided token has authorization 
790
   * for the operation on the specified object.
791
   * 
792
   * @param session - the Session object containing the credentials for the Subject
793
   * @param pid - The identifer of the resource for which access is being checked
794
   * @param operation - The type of operation which is being requested for the given pid
795
   *
796
   * @return true if the operation is allowed
797
   * 
798
   * @throws ServiceFailure
799
   * @throws InvalidToken
800
   * @throws NotFound
801
   * @throws NotAuthorized
802
   * @throws NotImplemented
803
   * @throws InvalidRequest
804
   */
805
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
806
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
807
    NotImplemented, InvalidRequest {
808

    
809
    boolean allowed = false;
810
    
811
    if (permission == null) {
812
    	throw new InvalidRequest("1761", "Permission was not provided or is invalid");
813
    }
814
    
815
    // permissions are hierarchical
816
    List<Permission> expandedPermissions = null;
817
    
818
    // always allow CN access
819
    if ( isAdminAuthorized(session) ) {
820
        allowed = true;
821
        return allowed;
822
        
823
    }
824
    
825
    // get the subject[s] from the session
826
	//defer to the shared util for recursively compiling the subjects	
827
	Set<Subject> subjects = AuthUtils.authorizedClientSubjects(session);
828
    
829
    // get the system metadata
830
    String pidStr = pid.getValue();
831
    SystemMetadata systemMetadata = null;
832
    try {
833
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
834

    
835
    } catch (Exception e) {
836
        // convert Hazelcast RuntimeException to NotFound
837
        logMetacat.error("An error occurred while getting system metadata for identifier " +
838
            pid.getValue() + ". The error message was: " + e.getMessage());
839
        throw new NotFound("1800", "No record found for " + pidStr);
840
        
841
    } 
842
    
843
    // throw not found if it was not found
844
    if (systemMetadata == null) {
845
    	throw new NotFound("1800", "No system metadata could be found for given PID: " + pidStr);
846
    }
847
	    
848
    // do we own it?
849
    for (Subject s: subjects) {
850
      logMetacat.debug("Comparing \t" + 
851
                       systemMetadata.getRightsHolder().getValue() +
852
                       " \tagainst \t" + s.getValue());
853
    	allowed = systemMetadata.getRightsHolder().equals(s);
854
    	if (allowed) {
855
    		return allowed;
856
    	}
857
    }    
858
    
859
    // otherwise check the access rules
860
    try {
861
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
862
	    search: // label break
863
	    for (AccessRule accessRule: allows) {
864
	      for (Subject s: subjects) {
865
	        logMetacat.debug("Checking allow access rule for subject: " + s.getValue());
866
	        if (accessRule.getSubjectList().contains(s)) {
867
	        	logMetacat.debug("Access rule contains subject: " + s.getValue());
868
	        	for (Permission p: accessRule.getPermissionList()) {
869
		        	logMetacat.debug("Checking permission: " + p.xmlValue());
870
	        		expandedPermissions = expandPermissions(p);
871
	        		allowed = expandedPermissions.contains(permission);
872
	        		if (allowed) {
873
			        	logMetacat.info("Permission granted: " + p.xmlValue() + " to " + s.getValue());
874
	        			break search; //label break
875
	        		}
876
	        	}
877
        		
878
	        }
879
	      }
880
	    }
881
    } catch (Exception e) {
882
    	// catch all for errors - safe side should be to deny the access
883
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
884
		allowed = false;
885
	  
886
    }
887
    
888
    // throw or return?
889
    if (!allowed) {
890
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
891
    }
892
    
893
    return allowed;
894
    
895
  }
896
  
897
  /*
898
   * parse a logEntry and get the relevant field from it
899
   * 
900
   * @param fieldname
901
   * @param entry
902
   * @return
903
   */
904
  private String getLogEntryField(String fieldname, String entry) {
905
    String begin = "<" + fieldname + ">";
906
    String end = "</" + fieldname + ">";
907
    // logMetacat.debug("looking for " + begin + " and " + end +
908
    // " in entry " + entry);
909
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
910
        .indexOf(end));
911
    logMetacat.debug("entry " + fieldname + " : " + s);
912
    return s;
913
  }
914

    
915
  /** 
916
   * Determine if a given object should be treated as an XML science metadata
917
   * object. 
918
   * 
919
   * @param sysmeta - the SystemMetadata describing the object
920
   * @return true if the object should be treated as science metadata
921
   */
922
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
923
    
924
    ObjectFormat objectFormat = null;
925
    boolean isScienceMetadata = false;
926
    
927
    try {
928
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
929
      if ( objectFormat.getFormatType().equals("METADATA") ) {
930
      	isScienceMetadata = true;
931
      	
932
      }
933
      
934
       
935
    } catch (ServiceFailure e) {
936
      logMetacat.debug("There was a problem determining if the object identified by" + 
937
          sysmeta.getIdentifier().getValue() + 
938
          " is science metadata: " + e.getMessage());
939
    
940
    } catch (NotFound e) {
941
      logMetacat.debug("There was a problem determining if the object identified by" + 
942
          sysmeta.getIdentifier().getValue() + 
943
          " is science metadata: " + e.getMessage());
944
    
945
    }
946
    
947
    return isScienceMetadata;
948

    
949
  }
950
  
951
  /**
952
   * Insert or update an XML document into Metacat
953
   * 
954
   * @param xml - the XML document to insert or update
955
   * @param pid - the identifier to be used for the resulting object
956
   * 
957
   * @return localId - the resulting docid of the document created or updated
958
   * 
959
   */
960
  public String insertOrUpdateDocument(String xml, Identifier pid, 
961
    Session session, String insertOrUpdate) 
962
    throws ServiceFailure {
963
    
964
  	logMetacat.debug("Starting to insert xml document...");
965
    IdentifierManager im = IdentifierManager.getInstance();
966

    
967
    // generate pid/localId pair for sysmeta
968
    String localId = null;
969
    
970
    if(insertOrUpdate.equals("insert")) {
971
      localId = im.generateLocalId(pid.getValue(), 1);
972
      
973
    } else {
974
      //localid should already exist in the identifier table, so just find it
975
      try {
976
        logMetacat.debug("Updating pid " + pid.getValue());
977
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
978
        
979
        localId = im.getLocalId(pid.getValue());
980
        
981
        logMetacat.debug("localId: " + localId);
982
        //increment the revision
983
        String docid = localId.substring(0, localId.lastIndexOf("."));
984
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
985
        int rev = new Integer(revS).intValue();
986
        rev++;
987
        docid = docid + "." + rev;
988
        localId = docid;
989
        logMetacat.debug("incremented localId: " + localId);
990
      
991
      } catch(McdbDocNotFoundException e) {
992
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
993
            "pid " + pid.getValue() + 
994
            " should have been in the identifier table, but it wasn't: " + 
995
            e.getMessage());
996
      
997
      }
998
      
999
    }
1000

    
1001
    params = new Hashtable<String, String[]>();
1002
    String[] action = new String[1];
1003
    action[0] = insertOrUpdate;
1004
    params.put("action", action);
1005
    String[] docid = new String[1];
1006
    docid[0] = localId;
1007
    params.put("docid", docid);
1008
    String[] doctext = new String[1];
1009
    doctext[0] = xml;
1010
    params.put("doctext", doctext);
1011
    
1012
    String username = Constants.SUBJECT_PUBLIC;
1013
    String[] groupnames = null;
1014
    if (session != null ) {
1015
    	username = session.getSubject().getValue();
1016
    	if (session.getSubjectInfo() != null) {
1017
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
1018
    		if (groupList != null) {
1019
    			groupnames = new String[groupList.size()];
1020
    			for (int i = 0; i > groupList.size(); i++ ) {
1021
    				groupnames[i] = groupList.get(i).getGroupName();
1022
    			}
1023
    		}
1024
    	}
1025
    }
1026
    
1027
    // do the insert or update action
1028
    handler = new MetacatHandler(new Timer());
1029
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null, 
1030
                        null, params, username, groupnames, false, false);
1031
    
1032
    if(result.indexOf("<error>") != -1) {
1033
    	String detailCode = "";
1034
    	if ( insertOrUpdate.equals("insert") ) {
1035
    		// make sure to remove the mapping so that subsequent attempts do not fail with IdentifierNotUnique
1036
    		im.removeMapping(pid.getValue(), localId);
1037
    		detailCode = "1190";
1038
    		
1039
    	} else if ( insertOrUpdate.equals("update") ) {
1040
    		detailCode = "1310";
1041
    		
1042
    	}
1043
        throw new ServiceFailure(detailCode, 
1044
          "Error inserting or updating document: " + result);
1045
    }
1046
    logMetacat.debug("Finsished inserting xml document with id " + localId);
1047
    
1048
    return localId;
1049
  }
1050
  
1051
  /**
1052
   * Insert a data document
1053
   * 
1054
   * @param object
1055
   * @param pid
1056
   * @param sessionData
1057
   * @throws ServiceFailure
1058
   * @returns localId of the data object inserted
1059
   */
1060
  public String insertDataObject(InputStream object, Identifier pid, 
1061
          Session session) throws ServiceFailure {
1062
      
1063
    String username = Constants.SUBJECT_PUBLIC;
1064
    String[] groupnames = null;
1065
    if (session != null ) {
1066
    	username = session.getSubject().getValue();
1067
    	if (session.getSubjectInfo() != null) {
1068
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
1069
    		if (groupList != null) {
1070
    			groupnames = new String[groupList.size()];
1071
    			for (int i = 0; i > groupList.size(); i++ ) {
1072
    				groupnames[i] = groupList.get(i).getGroupName();
1073
    			}
1074
    		}
1075
    	}
1076
    }
1077
  
1078
    // generate pid/localId pair for object
1079
    logMetacat.debug("Generating a pid/localId mapping");
1080
    IdentifierManager im = IdentifierManager.getInstance();
1081
    String localId = im.generateLocalId(pid.getValue(), 1);
1082
  
1083
    // Save the data file to disk using "localId" as the name
1084
    String datafilepath = null;
1085
	try {
1086
		datafilepath = PropertyService.getProperty("application.datafilepath");
1087
	} catch (PropertyNotFoundException e) {
1088
		ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
1089
		sf.initCause(e);
1090
		throw sf;
1091
	}
1092
    boolean locked = false;
1093
	try {
1094
		locked = DocumentImpl.getDataFileLockGrant(localId);
1095
	} catch (Exception e) {
1096
		ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1097
		sf.initCause(e);
1098
		throw sf;
1099
	}
1100

    
1101
    logMetacat.debug("Case DATA: starting to write to disk.");
1102
	if (locked) {
1103

    
1104
          File dataDirectory = new File(datafilepath);
1105
          dataDirectory.mkdirs();
1106
  
1107
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1108
  
1109
          // TODO: Check that the file size matches SystemMetadata
1110
          // long size = newFile.length();
1111
          // if (size == 0) {
1112
          //     throw new IOException("Uploaded file is 0 bytes!");
1113
          // }
1114
  
1115
          // Register the file in the database (which generates an exception
1116
          // if the localId is not acceptable or other untoward things happen
1117
          try {
1118
            logMetacat.debug("Registering document...");
1119
            DocumentImpl.registerDocument(localId, "BIN", localId,
1120
                    username, groupnames);
1121
            logMetacat.debug("Registration step completed.");
1122
            
1123
          } catch (SQLException e) {
1124
            //newFile.delete();
1125
            logMetacat.debug("SQLE: " + e.getMessage());
1126
            e.printStackTrace(System.out);
1127
            throw new ServiceFailure("1190", "Registration failed: " + 
1128
            		e.getMessage());
1129
            
1130
          } catch (AccessionNumberException e) {
1131
            //newFile.delete();
1132
            logMetacat.debug("ANE: " + e.getMessage());
1133
            e.printStackTrace(System.out);
1134
            throw new ServiceFailure("1190", "Registration failed: " + 
1135
            	e.getMessage());
1136
            
1137
          } catch (Exception e) {
1138
            //newFile.delete();
1139
            logMetacat.debug("Exception: " + e.getMessage());
1140
            e.printStackTrace(System.out);
1141
            throw new ServiceFailure("1190", "Registration failed: " + 
1142
            	e.getMessage());
1143
          }
1144
  
1145
          logMetacat.debug("Logging the creation event.");
1146
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1147
  
1148
          // Schedule replication for this data file
1149
          logMetacat.debug("Scheduling replication.");
1150
          ForceReplicationHandler frh = new ForceReplicationHandler(
1151
            localId, "create", false, null);
1152
      }
1153
      
1154
      return localId;
1155
    
1156
  }
1157

    
1158
  /**
1159
   * Insert a systemMetadata document and return its localId
1160
   */
1161
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1162
      throws ServiceFailure {
1163
      
1164
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1165
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1166
      logMetacat.debug("Inserting new system metadata with modified date " + 
1167
          sysmeta.getDateSysMetadataModified());
1168
      
1169
      //insert the system metadata
1170
      try {
1171
        // note: the calling subclass handles the map hazelcast lock/unlock
1172
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1173
      	
1174
      } catch (Exception e) {
1175
          throw new ServiceFailure("1190", e.getMessage());
1176
          
1177
	    }  
1178
  }
1179

    
1180
  /**
1181
   * Update a systemMetadata document
1182
   * 
1183
   * @param sysMeta - the system metadata object in the system to update
1184
   */
1185
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1186
        throws ServiceFailure {
1187

    
1188
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1189
        sysMeta.setDateSysMetadataModified(new Date());
1190
        try {
1191
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1192
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1193

    
1194
        } catch (Exception e) {
1195
            throw new ServiceFailure("4862", e.getMessage());
1196

    
1197
        } finally {
1198
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1199

    
1200
        }
1201

    
1202
    }
1203
  
1204
  /**
1205
   * Given a Permission, returns a list of all permissions that it encompasses
1206
   * Permissions are hierarchical so that WRITE also allows READ.
1207
   * @param permission
1208
   * @return list of included Permissions for the given permission
1209
   */
1210
  protected List<Permission> expandPermissions(Permission permission) {
1211
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1212
	    if (permission.equals(Permission.READ)) {
1213
	    	expandedPermissions.add(Permission.READ);
1214
	    }
1215
	    if (permission.equals(Permission.WRITE)) {
1216
	    	expandedPermissions.add(Permission.READ);
1217
	    	expandedPermissions.add(Permission.WRITE);
1218
	    }
1219
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1220
	    	expandedPermissions.add(Permission.READ);
1221
	    	expandedPermissions.add(Permission.WRITE);
1222
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1223
	    }
1224
	    return expandedPermissions;
1225
  }
1226

    
1227
  /*
1228
   * Write a stream to a file
1229
   * 
1230
   * @param dir - the directory to write to
1231
   * @param fileName - the file name to write to
1232
   * @param data - the object bytes as an input stream
1233
   * 
1234
   * @return newFile - the new file created
1235
   * 
1236
   * @throws ServiceFailure
1237
   */
1238
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1239
    throws ServiceFailure {
1240
    
1241
    File newFile = new File(dir, fileName);
1242
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1243

    
1244
    try {
1245
        if (newFile.createNewFile()) {
1246
          // write data stream to desired file
1247
          OutputStream os = new FileOutputStream(newFile);
1248
          long length = IOUtils.copyLarge(data, os);
1249
          os.flush();
1250
          os.close();
1251
        } else {
1252
          logMetacat.debug("File creation failed, or file already exists.");
1253
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1254
        }
1255
    } catch (FileNotFoundException e) {
1256
      logMetacat.debug("FNF: " + e.getMessage());
1257
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1258
                + e.getMessage());
1259
    } catch (IOException e) {
1260
      logMetacat.debug("IOE: " + e.getMessage());
1261
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1262
                + " " + e.getMessage());
1263
    }
1264

    
1265
    return newFile;
1266
  }
1267

    
1268
  /*
1269
   * Returns a list of nodes that have been registered with the DataONE infrastructure
1270
   * that match the given session subject
1271
   * @return nodes - List of nodes from the registry with a matching session subject
1272
   * 
1273
   * @throws ServiceFailure
1274
   * @throws NotImplemented
1275
   */
1276
  protected List<Node> listNodesBySubject(Subject subject) 
1277
      throws ServiceFailure, NotImplemented {
1278
      List<Node> nodeList = new ArrayList<Node>();
1279
      
1280
      CNode cn = D1Client.getCN();
1281
      List<Node> nodes = cn.listNodes().getNodeList();
1282
      
1283
      // find the node in the node list
1284
      for ( Node node : nodes ) {
1285
          
1286
          List<Subject> nodeSubjects = node.getSubjectList();
1287
          if (nodeSubjects != null) {    
1288
	          // check if the session subject is in the node subject list
1289
	          for (Subject nodeSubject : nodeSubjects) {
1290
	              if ( nodeSubject.equals(subject) ) { // subject of session == node subject
1291
	                  nodeList.add(node);  
1292
	              }                              
1293
	          }
1294
          }
1295
      }
1296
      
1297
      return nodeList;
1298
      
1299
  }
1300

    
1301
  /**
1302
   * Archives an object, where the object is either a 
1303
   * data object or a science metadata object.
1304
   * 
1305
   * @param session - the Session object containing the credentials for the Subject
1306
   * @param pid - The object identifier to be archived
1307
   * 
1308
   * @return pid - the identifier of the object used for the archiving
1309
   * 
1310
   * @throws InvalidToken
1311
   * @throws ServiceFailure
1312
   * @throws NotAuthorized
1313
   * @throws NotFound
1314
   * @throws NotImplemented
1315
   * @throws InvalidRequest
1316
   */
1317
  public Identifier archive(Session session, Identifier pid) 
1318
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1319

    
1320
      String localId = null;
1321
      boolean allowed = false;
1322
      String username = Constants.SUBJECT_PUBLIC;
1323
      String[] groupnames = null;
1324
      if (session == null) {
1325
      	throw new InvalidToken("1330", "No session has been provided");
1326
      } else {
1327
          username = session.getSubject().getValue();
1328
          if (session.getSubjectInfo() != null) {
1329
              List<Group> groupList = session.getSubjectInfo().getGroupList();
1330
              if (groupList != null) {
1331
                  groupnames = new String[groupList.size()];
1332
                  for (int i = 0; i > groupList.size(); i++) {
1333
                      groupnames[i] = groupList.get(i).getGroupName();
1334
                  }
1335
              }
1336
          }
1337
      }
1338

    
1339
      // do we have a valid pid?
1340
      if (pid == null || pid.getValue().trim().equals("")) {
1341
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
1342
      }
1343

    
1344
      // check for the existing identifier
1345
      try {
1346
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1347
      } catch (McdbDocNotFoundException e) {
1348
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
1349
      }
1350

    
1351
      // does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
1352
      try {
1353
			allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
1354
		} catch (InvalidRequest e) {
1355
          throw new ServiceFailure("1350", e.getDescription());
1356
		}
1357
          
1358

    
1359
      if (allowed) {
1360
          try {
1361
              // archive the document
1362
              DocumentImpl.delete(localId, null, null, null, false);
1363
              EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
1364

    
1365
              // archive it
1366
              SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1367
              sysMeta.setArchived(true);
1368
              sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1369
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
1370
              
1371
          } catch (McdbDocNotFoundException e) {
1372
              throw new NotFound("1340", "The provided identifier was invalid.");
1373

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

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

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

    
1384
      } else {
1385
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
1386
      }
1387

    
1388
      return pid;
1389
  }
1390
  
1391
  public Identifier archive(Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1392
	  return archive(null, pid);
1393
  }
1394

    
1395

    
1396
}
(2-2/5)