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-26 12:08:30 -0700 (Thu, 26 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
      // check if this is the node calling itself (MN)
711
      allowed = isNodeAdmin(session);
712
      
713
      // check the CN list
714
      if (!allowed) {
715
	      // are we allowed to do this? only CNs are allowed
716
	      CNode cn = D1Client.getCN();
717
	      List<Node> nodes = cn.listNodes().getNodeList();
718
	      
719
	      if ( nodes == null ) {
720
	          throw new ServiceFailure("4852", "Couldn't get node list.");
721
	  
722
	      }
723
	      
724
	      // find the node in the node list
725
	      for ( Node node : nodes ) {
726
	          
727
	          NodeReference nodeReference = node.getIdentifier();
728
	          logMetacat.debug("In isAdminAuthorized(), Node reference is: " + nodeReference.getValue());
729
	          
730
	          Subject subject = session.getSubject();
731
	          
732
	          if (node.getType() == NodeType.CN) {
733
	              List<Subject> nodeSubjects = node.getSubjectList();
734
	              
735
	              // check if the session subject is in the node subject list
736
	              for (Subject nodeSubject : nodeSubjects) {
737
	                  logMetacat.debug("In isAdminAuthorized(), comparing subjects: " +
738
	                      nodeSubject.getValue() + " and " + subject.getValue());
739
	                  if ( nodeSubject.equals(subject) ) {
740
	                      allowed = true; // subject of session == target node subject
741
	                      break;
742
	                      
743
	                  }
744
	              }              
745
	          }
746
	      }
747
      }
748
      
749
      return allowed;
750
  }
751
  
752
  /**
753
   * Test if the user identified by the provided token has administrative authorization 
754
   * on this node because they are calling themselves
755
   * 
756
   * @param session - the Session object containing the credentials for the Subject
757
   * 
758
   * @return true if the user is this node
759
   * @throws ServiceFailure 
760
   * @throws NotImplemented 
761
   */
762
  public boolean isNodeAdmin(Session session) throws NotImplemented, ServiceFailure {
763

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

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

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

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

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

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

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

    
1125
    logMetacat.debug("Case DATA: starting to write to disk.");
1126
	if (locked) {
1127

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

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

    
1204
  /**
1205
   * Update a systemMetadata document
1206
   * 
1207
   * @param sysMeta - the system metadata object in the system to update
1208
   */
1209
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1210
        throws ServiceFailure {
1211

    
1212
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1213
        sysMeta.setDateSysMetadataModified(new Date());
1214
        try {
1215
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1216
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1217

    
1218
        } catch (Exception e) {
1219
            throw new ServiceFailure("4862", e.getMessage());
1220

    
1221
        } finally {
1222
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1223

    
1224
        }
1225

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

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

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

    
1289
    return newFile;
1290
  }
1291

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

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

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

    
1363
      // do we have a valid pid?
1364
      if (pid == null || pid.getValue().trim().equals("")) {
1365
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
1366
      }
1367

    
1368
      // check for the existing identifier
1369
      try {
1370
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1371
      } catch (McdbDocNotFoundException e) {
1372
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
1373
      }
1374

    
1375
      // does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
1376
      try {
1377
			allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
1378
		} catch (InvalidRequest e) {
1379
          throw new ServiceFailure("1350", e.getDescription());
1380
		}
1381
          
1382

    
1383
      if (allowed) {
1384
          try {
1385
              // archive the document
1386
              DocumentImpl.delete(localId, null, null, null, false);
1387
              EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
1388

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

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

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

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

    
1408
      } else {
1409
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
1410
      }
1411

    
1412
      return pid;
1413
  }
1414
  
1415
  public Identifier archive(Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1416
	  return archive(null, pid);
1417
  }
1418

    
1419

    
1420
}
(2-2/5)