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-17 11:09:51 -0700 (Tue, 17 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 the pid is valid format
301
    if (isValidIdentifier(pid)) {
302
    	throw new InvalidRequest("1202", "The provided identifier is invalid.");
303
    }
304
    
305
    // verify that pid == SystemMetadata.getIdentifier()
306
    logMetacat.debug("Comparing pid|sysmeta_pid: " + 
307
      pid.getValue() + "|" + sysmeta.getIdentifier().getValue());
308
    if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
309
        throw new InvalidSystemMetadata("1180", 
310
            "The supplied system metadata is invalid. " +
311
            "The identifier " + pid.getValue() + " does not match identifier" +
312
            "in the system metadata identified by " +
313
            sysmeta.getIdentifier().getValue() + ".");
314
        
315
    }
316

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

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

    
377
        } catch (IOException e) {
378
        	String msg = "The Node is unable to create the object. " +
379
          "There was a problem converting the object to XML";
380
        	logMetacat.info(msg);
381
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
382

    
383
        }
384
                    
385
      } else {
386
	        
387
	      // DEFAULT CASE: DATA (needs to be checked and completed)
388
	      localId = insertDataObject(object, pid, session);
389
      }   
390
    
391
    }
392

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

    
410
    resultPid = pid;
411
    
412
    logMetacat.debug("create() complete for object: " + pid.getValue());
413

    
414
    return resultPid;
415
  }
416

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

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

    
460
    if ( start == null ) {
461
    	start = 0;	
462
    }
463
    
464
    if ( count == null ) {
465
    	count = 1000;
466
    }
467

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

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

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

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

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

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

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

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

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

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

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

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

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

    
954
  }
955
  
956
  /**
957
   * Check fro whitespace in the given pid.
958
   * null pids are also invalid by default
959
   * @param pid
960
   * @return
961
   */
962
  public static boolean isValidIdentifier(Identifier pid) {
963
	  if (pid != null && pid.getValue() != null && pid.getValue().length() > 0) {
964
		  return !pid.getValue().matches("\\s");
965
	  } 
966
	  return false;
967
  }
968
  
969
  
970
  /**
971
   * Insert or update an XML document into Metacat
972
   * 
973
   * @param xml - the XML document to insert or update
974
   * @param pid - the identifier to be used for the resulting object
975
   * 
976
   * @return localId - the resulting docid of the document created or updated
977
   * 
978
   */
979
  public String insertOrUpdateDocument(String xml, Identifier pid, 
980
    Session session, String insertOrUpdate) 
981
    throws ServiceFailure {
982
    
983
  	logMetacat.debug("Starting to insert xml document...");
984
    IdentifierManager im = IdentifierManager.getInstance();
985

    
986
    // generate pid/localId pair for sysmeta
987
    String localId = null;
988
    
989
    if(insertOrUpdate.equals("insert")) {
990
      localId = im.generateLocalId(pid.getValue(), 1);
991
      
992
    } else {
993
      //localid should already exist in the identifier table, so just find it
994
      try {
995
        logMetacat.debug("Updating pid " + pid.getValue());
996
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
997
        
998
        localId = im.getLocalId(pid.getValue());
999
        
1000
        logMetacat.debug("localId: " + localId);
1001
        //increment the revision
1002
        String docid = localId.substring(0, localId.lastIndexOf("."));
1003
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1004
        int rev = new Integer(revS).intValue();
1005
        rev++;
1006
        docid = docid + "." + rev;
1007
        localId = docid;
1008
        logMetacat.debug("incremented localId: " + localId);
1009
      
1010
      } catch(McdbDocNotFoundException e) {
1011
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
1012
            "pid " + pid.getValue() + 
1013
            " should have been in the identifier table, but it wasn't: " + 
1014
            e.getMessage());
1015
      
1016
      }
1017
      
1018
    }
1019

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

    
1120
    logMetacat.debug("Case DATA: starting to write to disk.");
1121
	if (locked) {
1122

    
1123
          File dataDirectory = new File(datafilepath);
1124
          dataDirectory.mkdirs();
1125
  
1126
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1127
  
1128
          // TODO: Check that the file size matches SystemMetadata
1129
          // long size = newFile.length();
1130
          // if (size == 0) {
1131
          //     throw new IOException("Uploaded file is 0 bytes!");
1132
          // }
1133
  
1134
          // Register the file in the database (which generates an exception
1135
          // if the localId is not acceptable or other untoward things happen
1136
          try {
1137
            logMetacat.debug("Registering document...");
1138
            DocumentImpl.registerDocument(localId, "BIN", localId,
1139
                    username, groupnames);
1140
            logMetacat.debug("Registration step completed.");
1141
            
1142
          } catch (SQLException e) {
1143
            //newFile.delete();
1144
            logMetacat.debug("SQLE: " + e.getMessage());
1145
            e.printStackTrace(System.out);
1146
            throw new ServiceFailure("1190", "Registration failed: " + 
1147
            		e.getMessage());
1148
            
1149
          } catch (AccessionNumberException e) {
1150
            //newFile.delete();
1151
            logMetacat.debug("ANE: " + e.getMessage());
1152
            e.printStackTrace(System.out);
1153
            throw new ServiceFailure("1190", "Registration failed: " + 
1154
            	e.getMessage());
1155
            
1156
          } catch (Exception e) {
1157
            //newFile.delete();
1158
            logMetacat.debug("Exception: " + e.getMessage());
1159
            e.printStackTrace(System.out);
1160
            throw new ServiceFailure("1190", "Registration failed: " + 
1161
            	e.getMessage());
1162
          }
1163
  
1164
          logMetacat.debug("Logging the creation event.");
1165
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1166
  
1167
          // Schedule replication for this data file
1168
          logMetacat.debug("Scheduling replication.");
1169
          ForceReplicationHandler frh = new ForceReplicationHandler(
1170
            localId, "create", false, null);
1171
      }
1172
      
1173
      return localId;
1174
    
1175
  }
1176

    
1177
  /**
1178
   * Insert a systemMetadata document and return its localId
1179
   */
1180
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1181
      throws ServiceFailure {
1182
      
1183
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1184
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1185
      logMetacat.debug("Inserting new system metadata with modified date " + 
1186
          sysmeta.getDateSysMetadataModified());
1187
      
1188
      //insert the system metadata
1189
      try {
1190
        // note: the calling subclass handles the map hazelcast lock/unlock
1191
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1192
      	
1193
      } catch (Exception e) {
1194
          throw new ServiceFailure("1190", e.getMessage());
1195
          
1196
	    }  
1197
  }
1198

    
1199
  /**
1200
   * Update a systemMetadata document
1201
   * 
1202
   * @param sysMeta - the system metadata object in the system to update
1203
   */
1204
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1205
        throws ServiceFailure {
1206

    
1207
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1208
        sysMeta.setDateSysMetadataModified(new Date());
1209
        try {
1210
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1211
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1212

    
1213
        } catch (Exception e) {
1214
            throw new ServiceFailure("4862", e.getMessage());
1215

    
1216
        } finally {
1217
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1218

    
1219
        }
1220

    
1221
    }
1222
  
1223
  /**
1224
   * Given a Permission, returns a list of all permissions that it encompasses
1225
   * Permissions are hierarchical so that WRITE also allows READ.
1226
   * @param permission
1227
   * @return list of included Permissions for the given permission
1228
   */
1229
  protected List<Permission> expandPermissions(Permission permission) {
1230
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1231
	    if (permission.equals(Permission.READ)) {
1232
	    	expandedPermissions.add(Permission.READ);
1233
	    }
1234
	    if (permission.equals(Permission.WRITE)) {
1235
	    	expandedPermissions.add(Permission.READ);
1236
	    	expandedPermissions.add(Permission.WRITE);
1237
	    }
1238
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1239
	    	expandedPermissions.add(Permission.READ);
1240
	    	expandedPermissions.add(Permission.WRITE);
1241
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1242
	    }
1243
	    return expandedPermissions;
1244
  }
1245

    
1246
  /*
1247
   * Write a stream to a file
1248
   * 
1249
   * @param dir - the directory to write to
1250
   * @param fileName - the file name to write to
1251
   * @param data - the object bytes as an input stream
1252
   * 
1253
   * @return newFile - the new file created
1254
   * 
1255
   * @throws ServiceFailure
1256
   */
1257
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1258
    throws ServiceFailure {
1259
    
1260
    File newFile = new File(dir, fileName);
1261
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1262

    
1263
    try {
1264
        if (newFile.createNewFile()) {
1265
          // write data stream to desired file
1266
          OutputStream os = new FileOutputStream(newFile);
1267
          long length = IOUtils.copyLarge(data, os);
1268
          os.flush();
1269
          os.close();
1270
        } else {
1271
          logMetacat.debug("File creation failed, or file already exists.");
1272
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1273
        }
1274
    } catch (FileNotFoundException e) {
1275
      logMetacat.debug("FNF: " + e.getMessage());
1276
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1277
                + e.getMessage());
1278
    } catch (IOException e) {
1279
      logMetacat.debug("IOE: " + e.getMessage());
1280
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1281
                + " " + e.getMessage());
1282
    }
1283

    
1284
    return newFile;
1285
  }
1286

    
1287
  /*
1288
   * Returns a list of nodes that have been registered with the DataONE infrastructure
1289
   * that match the given session subject
1290
   * @return nodes - List of nodes from the registry with a matching session subject
1291
   * 
1292
   * @throws ServiceFailure
1293
   * @throws NotImplemented
1294
   */
1295
  protected List<Node> listNodesBySubject(Subject subject) 
1296
      throws ServiceFailure, NotImplemented {
1297
      List<Node> nodeList = new ArrayList<Node>();
1298
      
1299
      CNode cn = D1Client.getCN();
1300
      List<Node> nodes = cn.listNodes().getNodeList();
1301
      
1302
      // find the node in the node list
1303
      for ( Node node : nodes ) {
1304
          
1305
          List<Subject> nodeSubjects = node.getSubjectList();
1306
          if (nodeSubjects != null) {    
1307
	          // check if the session subject is in the node subject list
1308
	          for (Subject nodeSubject : nodeSubjects) {
1309
	              if ( nodeSubject.equals(subject) ) { // subject of session == node subject
1310
	                  nodeList.add(node);  
1311
	              }                              
1312
	          }
1313
          }
1314
      }
1315
      
1316
      return nodeList;
1317
      
1318
  }
1319

    
1320
  /**
1321
   * Archives an object, where the object is either a 
1322
   * data object or a science metadata object.
1323
   * 
1324
   * @param session - the Session object containing the credentials for the Subject
1325
   * @param pid - The object identifier to be archived
1326
   * 
1327
   * @return pid - the identifier of the object used for the archiving
1328
   * 
1329
   * @throws InvalidToken
1330
   * @throws ServiceFailure
1331
   * @throws NotAuthorized
1332
   * @throws NotFound
1333
   * @throws NotImplemented
1334
   * @throws InvalidRequest
1335
   */
1336
  public Identifier archive(Session session, Identifier pid) 
1337
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1338

    
1339
      String localId = null;
1340
      boolean allowed = false;
1341
      String username = Constants.SUBJECT_PUBLIC;
1342
      String[] groupnames = null;
1343
      if (session == null) {
1344
      	throw new InvalidToken("1330", "No session has been provided");
1345
      } else {
1346
          username = session.getSubject().getValue();
1347
          if (session.getSubjectInfo() != null) {
1348
              List<Group> groupList = session.getSubjectInfo().getGroupList();
1349
              if (groupList != null) {
1350
                  groupnames = new String[groupList.size()];
1351
                  for (int i = 0; i > groupList.size(); i++) {
1352
                      groupnames[i] = groupList.get(i).getGroupName();
1353
                  }
1354
              }
1355
          }
1356
      }
1357

    
1358
      // do we have a valid pid?
1359
      if (pid == null || pid.getValue().trim().equals("")) {
1360
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
1361
      }
1362

    
1363
      // check for the existing identifier
1364
      try {
1365
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1366
      } catch (McdbDocNotFoundException e) {
1367
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
1368
      }
1369

    
1370
      // does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
1371
      try {
1372
			allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
1373
		} catch (InvalidRequest e) {
1374
          throw new ServiceFailure("1350", e.getDescription());
1375
		}
1376
          
1377

    
1378
      if (allowed) {
1379
          try {
1380
              // archive the document
1381
              DocumentImpl.delete(localId, null, null, null, false);
1382
              EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
1383

    
1384
              // archive it
1385
              SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1386
              sysMeta.setArchived(true);
1387
              sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1388
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
1389
              
1390
          } catch (McdbDocNotFoundException e) {
1391
              throw new NotFound("1340", "The provided identifier was invalid.");
1392

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

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

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

    
1403
      } else {
1404
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
1405
      }
1406

    
1407
      return pid;
1408
  }
1409
  
1410
  public Identifier archive(Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1411
	  return archive(null, pid);
1412
  }
1413

    
1414

    
1415
}
(2-2/5)