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-11-07 14:53:33 -0800 (Wed, 07 Nov 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
   * out-of-band session object to be used when not passed in as a method parameter
113
   */
114
  protected Session session;
115

    
116
  /**
117
   * Constructor - used to set the metacatUrl from a subclass extending D1NodeService
118
   * 
119
   * @param metacatUrl - the URL of the metacat service, including the ending /d1
120
   */
121
  public D1NodeService(HttpServletRequest request) {
122
		this.request = request;
123
	}
124

    
125
  /**
126
   * retrieve the out-of-band session
127
   * @return
128
   */
129
  	public Session getSession() {
130
		return session;
131
	}
132
  	
133
  	/**
134
  	 * Set the out-of-band session
135
  	 * @param session
136
  	 */
137
	public void setSession(Session session) {
138
		this.session = session;
139
	}
140

    
141
  /**
142
   * This method provides a lighter weight mechanism than 
143
   * getSystemMetadata() for a client to determine basic 
144
   * properties of the referenced object.
145
   * 
146
   * @param session - the Session object containing the credentials for the Subject
147
   * @param pid - the identifier of the object to be described
148
   * 
149
   * @return describeResponse - A set of values providing a basic description 
150
   *                            of the object.
151
   * 
152
   * @throws InvalidToken
153
   * @throws ServiceFailure
154
   * @throws NotAuthorized
155
   * @throws NotFound
156
   * @throws NotImplemented
157
   * @throws InvalidRequest
158
   */
159
  public DescribeResponse describe(Session session, Identifier pid) 
160
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
161

    
162
    // get system metadata and construct the describe response
163
      SystemMetadata sysmeta = getSystemMetadata(session, pid);
164
      DescribeResponse describeResponse = 
165
      	new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(), 
166
      			sysmeta.getDateSysMetadataModified(),
167
      			sysmeta.getChecksum(), sysmeta.getSerialVersion());
168

    
169
      return describeResponse;
170

    
171
  }
172
  
173
  /**
174
   * Deletes an object from the Member Node, where the object is either a 
175
   * data object or a science metadata object.
176
   * 
177
   * @param session - the Session object containing the credentials for the Subject
178
   * @param pid - The object identifier to be deleted
179
   * 
180
   * @return pid - the identifier of the object used for the deletion
181
   * 
182
   * @throws InvalidToken
183
   * @throws ServiceFailure
184
   * @throws NotAuthorized
185
   * @throws NotFound
186
   * @throws NotImplemented
187
   * @throws InvalidRequest
188
   */
189
  public Identifier delete(Session session, Identifier pid) 
190
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
191

    
192
      String localId = null;
193
      if (session == null) {
194
      	throw new InvalidToken("1330", "No session has been provided");
195
      }
196
      // just for logging purposes
197
      String username = session.getSubject().getValue();
198

    
199
      // do we have a valid pid?
200
      if (pid == null || pid.getValue().trim().equals("")) {
201
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
202
      }
203

    
204
      // check for the existing identifier
205
      try {
206
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
207
      } catch (McdbDocNotFoundException e) {
208
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
209
      }
210
      
211
      try {
212
          // delete the document, as admin
213
          DocumentImpl.delete(localId, null, null, null, true);
214
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
215

    
216
          // archive it
217
          SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
218
          sysMeta.setArchived(true);
219
          sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
220
          HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
221
          
222
      } catch (McdbDocNotFoundException e) {
223
          throw new NotFound("1340", "The provided identifier was invalid.");
224

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

    
228
      } catch (InsufficientKarmaException e) {
229
          if ( logMetacat.isDebugEnabled() ) {
230
              e.printStackTrace();
231
          }
232
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
233
      
234
      } catch (Exception e) { // for some reason DocumentImpl throws a general Exception
235
          throw new ServiceFailure("1350", "There was a problem deleting the object." + "The error message was: " + e.getMessage());
236
      }
237

    
238
      return pid;
239
  }
240
  
241
  /**
242
   * Low level, "are you alive" operation. A valid ping response is 
243
   * indicated by a HTTP status of 200.
244
   * 
245
   * @return true if the service is alive
246
   * 
247
   * @throws NotImplemented
248
   * @throws ServiceFailure
249
   * @throws InsufficientResources
250
   */
251
  public Date ping() 
252
      throws NotImplemented, ServiceFailure, InsufficientResources {
253

    
254
      // test if we can get a database connection
255
      int serialNumber = -1;
256
      DBConnection dbConn = null;
257
      try {
258
          dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
259
          serialNumber = dbConn.getCheckOutSerialNumber();
260
      } catch (SQLException e) {
261
      	ServiceFailure sf = new ServiceFailure("", e.getMessage());
262
      	sf.initCause(e);
263
          throw sf;
264
      } finally {
265
          // Return the database connection
266
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
267
      }
268

    
269
      return Calendar.getInstance().getTime();
270
  }
271
  
272
  /**
273
   * Adds a new object to the Node, where the object is either a data 
274
   * object or a science metadata object. This method is called by clients 
275
   * to create new data objects on Member Nodes or internally for Coordinating
276
   * Nodes
277
   * 
278
   * @param session - the Session object containing the credentials for the Subject
279
   * @param pid - The object identifier to be created
280
   * @param object - the object bytes
281
   * @param sysmeta - the system metadata that describes the object  
282
   * 
283
   * @return pid - the object identifier created
284
   * 
285
   * @throws InvalidToken
286
   * @throws ServiceFailure
287
   * @throws NotAuthorized
288
   * @throws IdentifierNotUnique
289
   * @throws UnsupportedType
290
   * @throws InsufficientResources
291
   * @throws InvalidSystemMetadata
292
   * @throws NotImplemented
293
   * @throws InvalidRequest
294
   */
295
  public Identifier create(Session session, Identifier pid, InputStream object,
296
    SystemMetadata sysmeta) 
297
    throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
298
    UnsupportedType, InsufficientResources, InvalidSystemMetadata, 
299
    NotImplemented, InvalidRequest {
300

    
301
    Identifier resultPid = null;
302
    String localId = null;
303
    boolean allowed = false;
304
    
305
    // check for null session
306
    if (session == null) {
307
    	throw new InvalidToken("4894", "Session is required to WRITE to the Node.");
308
    }
309
    Subject subject = session.getSubject();
310

    
311
    Subject publicSubject = new Subject();
312
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
313
	// be sure the user is authenticated for create()
314
    if (subject == null || subject.getValue() == null || 
315
        subject.equals(publicSubject) ) {
316
      throw new NotAuthorized("1100", "The provided identity does not have " +
317
        "permission to WRITE to the Node.");
318
      
319
    }
320
    
321
    // verify the pid is valid format
322
    if (!isValidIdentifier(pid)) {
323
    	throw new InvalidRequest("1202", "The provided identifier is invalid.");
324
    }
325
    
326
    // verify that pid == SystemMetadata.getIdentifier()
327
    logMetacat.debug("Comparing pid|sysmeta_pid: " + 
328
      pid.getValue() + "|" + sysmeta.getIdentifier().getValue());
329
    if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
330
        throw new InvalidSystemMetadata("1180", 
331
            "The supplied system metadata is invalid. " +
332
            "The identifier " + pid.getValue() + " does not match identifier" +
333
            "in the system metadata identified by " +
334
            sysmeta.getIdentifier().getValue() + ".");
335
        
336
    }
337

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

    
386
      // Science metadata (XML) or science data object?
387
      // TODO: there are cases where certain object formats are science metadata
388
      // but are not XML (netCDF ...).  Handle this.
389
      if ( isScienceMetadata(sysmeta) ) {
390
        
391
        // CASE METADATA:
392
      	String objectAsXML = "";
393
        try {
394
	        objectAsXML = IOUtils.toString(object, "UTF-8");
395
	        localId = insertOrUpdateDocument(objectAsXML, pid, session, "insert");
396
	        //localId = im.getLocalId(pid.getValue());
397

    
398
        } catch (IOException e) {
399
        	String msg = "The Node is unable to create the object. " +
400
          "There was a problem converting the object to XML";
401
        	logMetacat.info(msg);
402
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
403

    
404
        }
405
                    
406
      } else {
407
	        
408
	      // DEFAULT CASE: DATA (needs to be checked and completed)
409
	      localId = insertDataObject(object, pid, session);
410
      }   
411
    
412
    }
413

    
414
    logMetacat.debug("Done inserting new object: " + pid.getValue());
415
    
416
    // save the sysmeta
417
    try {
418
      // lock and unlock of the pid happens in the subclass
419
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
420
    	
421
    } catch (Exception e) {
422
    	logMetacat.error("Problem creating system metadata: " + pid.getValue(), e);
423
        throw new ServiceFailure("1190", e.getMessage());
424
	}
425
    
426
    // setting the resulting identifier failed
427
    if (localId == null ) {
428
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
429
    }
430

    
431
    resultPid = pid;
432
    
433
    logMetacat.debug("create() complete for object: " + pid.getValue());
434

    
435
    return resultPid;
436
  }
437

    
438
  /**
439
   * Return the log records associated with a given event between the start and 
440
   * end dates listed given a particular Subject listed in the Session
441
   * 
442
   * @param session - the Session object containing the credentials for the Subject
443
   * @param fromDate - the start date of the desired log records
444
   * @param toDate - the end date of the desired log records
445
   * @param event - restrict log records of a specific event type
446
   * @param start - zero based offset from the first record in the 
447
   *                set of matching log records. Used to assist with 
448
   *                paging the response.
449
   * @param count - maximum number of log records to return in the response. 
450
   *                Used to assist with paging the response.
451
   * 
452
   * @return the desired log records
453
   * 
454
   * @throws InvalidToken
455
   * @throws ServiceFailure
456
   * @throws NotAuthorized
457
   * @throws InvalidRequest
458
   * @throws NotImplemented
459
   */
460
  public Log getLogRecords(Session session, Date fromDate, Date toDate, 
461
      Event event, String pidFilter, Integer start, Integer count) throws InvalidToken, ServiceFailure,
462
      NotAuthorized, InvalidRequest, NotImplemented {
463

    
464
	  // only admin access to this method
465
	  // see https://redmine.dataone.org/issues/2855
466
	  if (!isAdminAuthorized(session)) {
467
		  throw new NotAuthorized("1460", "Only the CN or admin is allowed to harvest logs from this node");
468
	  }
469
	  
470
    IdentifierManager im = IdentifierManager.getInstance();
471
    EventLog el = EventLog.getInstance();
472
    if ( fromDate == null ) {
473
      logMetacat.debug("setting fromdate from null");
474
      fromDate = new Date(1);
475
    }
476
    if ( toDate == null ) {
477
      logMetacat.debug("setting todate from null");
478
      toDate = new Date();
479
    }
480

    
481
    if ( start == null ) {
482
    	start = 0;	
483
    }
484
    
485
    if ( count == null ) {
486
    	count = 1000;
487
    }
488

    
489
    String[] filterDocid = null;
490
    if (pidFilter != null) {
491
		try {
492
	      String localId = im.getLocalId(pidFilter);
493
	      filterDocid = new String[] {localId};
494
	    } catch (Exception ex) { 
495
	    	String msg = "Could not find localId for given pidFilter '" + pidFilter + "'";
496
	        logMetacat.warn(msg, ex);
497
	        //throw new InvalidRequest("1480", msg);
498
	    }
499
    }
500
    
501
    logMetacat.debug("fromDate: " + fromDate);
502
    logMetacat.debug("toDate: " + toDate);
503

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

    
568
    // if we fail to set the input stream
569
    if ( inputStream == null ) {
570
      throw new NotFound("1020", "The object specified by " + 
571
                         pid.getValue() +
572
                         "does not exist at this node.");
573
    }
574
    
575
	// log the read event
576
    String principal = Constants.SUBJECT_PUBLIC;
577
    if (session != null && session.getSubject() != null) {
578
    	principal = session.getSubject().getValue();
579
    }
580
    EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "read");
581
    
582
    return inputStream;
583
  }
584

    
585
  /**
586
   * Return the system metadata for a given object
587
   * 
588
   * @param session - the Session object containing the credentials for the Subject
589
   * @param pid - the object identifier for the given object
590
   * 
591
   * @return inputStream - the input stream of the given system metadata object
592
   * 
593
   * @throws InvalidToken
594
   * @throws ServiceFailure
595
   * @throws NotAuthorized
596
   * @throws NotFound
597
   * @throws InvalidRequest
598
   * @throws NotImplemented
599
   */
600
    public SystemMetadata getSystemMetadata(Session session, Identifier pid)
601
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
602
        NotImplemented {
603

    
604
        boolean isAuthorized = false;
605
        SystemMetadata systemMetadata = null;
606
        List<Replica> replicaList = null;
607
        NodeReference replicaNodeRef = null;
608
        List<Node> nodeListBySubject = null;
609
        Subject subject = null;
610
        
611
        if (session != null ) {
612
            subject = session.getSubject();
613
        }
614
        
615
        // check normal authorization
616
        BaseException originalAuthorizationException = null;
617
        if (!isAuthorized) {
618
            try {
619
                isAuthorized = isAuthorized(session, pid, Permission.READ);
620

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

    
686
	        } catch (RuntimeException e) {
687
	        	e.printStackTrace();
688
	            // convert hazelcast RuntimeException to ServiceFailure
689
	            throw new ServiceFailure("1090", "Unexpected error getting system metadata for: " + 
690
	                pid.getValue());	
691
	        }
692
	        
693
        }
694
        
695
        // It wasn't in the map
696
        if ( systemMetadata == null ) {
697
            throw new NotFound("1420", "No record found for: " + pid.getValue());
698
        }
699
        
700
        return systemMetadata;
701
    }
702
     
703
  /**
704
   * Test if the user identified by the provided token has administrative authorization 
705
   * 
706
   * @param session - the Session object containing the credentials for the Subject
707
   * 
708
   * @return true if the user is admin
709
   * 
710
   * @throws ServiceFailure
711
   * @throws InvalidToken
712
   * @throws NotFound
713
   * @throws NotAuthorized
714
   * @throws NotImplemented
715
   */
716
  public boolean isAdminAuthorized(Session session) 
717
      throws ServiceFailure, InvalidToken, NotAuthorized,
718
      NotImplemented {
719

    
720
      boolean allowed = false;
721
      
722
      // must have a session in order to check admin 
723
      if (session == null) {
724
         logMetacat.debug("In isAdminAuthorized(), session is null ");
725
         return false;
726
      }
727
      
728
      logMetacat.debug("In isAdminAuthorized(), checking CN or MN authorization for " +
729
           session.getSubject().getValue());
730
      
731
      // check if this is the node calling itself (MN)
732
      allowed = isNodeAdmin(session);
733
      
734
      // check the CN list
735
      if (!allowed) {
736
	      // are we allowed to do this? only CNs are allowed
737
	      CNode cn = D1Client.getCN();
738
	      List<Node> nodes = cn.listNodes().getNodeList();
739
	      
740
	      if ( nodes == null ) {
741
	          throw new ServiceFailure("4852", "Couldn't get node list.");
742
	  
743
	      }
744
	      
745
	      // find the node in the node list
746
	      for ( Node node : nodes ) {
747
	          
748
	          NodeReference nodeReference = node.getIdentifier();
749
	          logMetacat.debug("In isAdminAuthorized(), Node reference is: " + nodeReference.getValue());
750
	          
751
	          Subject subject = session.getSubject();
752
	          
753
	          if (node.getType() == NodeType.CN) {
754
	              List<Subject> nodeSubjects = node.getSubjectList();
755
	              
756
	              // check if the session subject is in the node subject list
757
	              for (Subject nodeSubject : nodeSubjects) {
758
	                  logMetacat.debug("In isAdminAuthorized(), comparing subjects: " +
759
	                      nodeSubject.getValue() + " and " + subject.getValue());
760
	                  if ( nodeSubject.equals(subject) ) {
761
	                      allowed = true; // subject of session == target node subject
762
	                      break;
763
	                      
764
	                  }
765
	              }              
766
	          }
767
	      }
768
      }
769
      
770
      return allowed;
771
  }
772
  
773
  /**
774
   * Test if the user identified by the provided token has administrative authorization 
775
   * on this node because they are calling themselves
776
   * 
777
   * @param session - the Session object containing the credentials for the Subject
778
   * 
779
   * @return true if the user is this node
780
   * @throws ServiceFailure 
781
   * @throws NotImplemented 
782
   */
783
  public boolean isNodeAdmin(Session session) throws NotImplemented, ServiceFailure {
784

    
785
      boolean allowed = false;
786
      
787
      // must have a session in order to check admin 
788
      if (session == null) {
789
         logMetacat.debug("In isNodeAdmin(), session is null ");
790
         return false;
791
      }
792
      
793
      logMetacat.debug("In isNodeAdmin(), MN authorization for " +
794
           session.getSubject().getValue());
795
      
796
      Node node = MNodeService.getInstance(request).getCapabilities();
797
      NodeReference nodeReference = node.getIdentifier();
798
      logMetacat.debug("In isNodeAdmin(), Node reference is: " + nodeReference.getValue());
799
      
800
      Subject subject = session.getSubject();
801
      
802
      if (node.getType() == NodeType.MN) {
803
          List<Subject> nodeSubjects = node.getSubjectList();
804
          
805
          // check if the session subject is in the node subject list
806
          for (Subject nodeSubject : nodeSubjects) {
807
              logMetacat.debug("In isNodeAdmin(), comparing subjects: " +
808
                  nodeSubject.getValue() + " and " + subject.getValue());
809
              if ( nodeSubject.equals(subject) ) {
810
                  allowed = true; // subject of session == this node's subect
811
                  break;
812
              }
813
          }              
814
      }
815
      
816
      return allowed;
817
  }
818
  
819
  /**
820
   * Test if the user identified by the provided token has authorization 
821
   * for the operation on the specified object.
822
   * 
823
   * @param session - the Session object containing the credentials for the Subject
824
   * @param pid - The identifer of the resource for which access is being checked
825
   * @param operation - The type of operation which is being requested for the given pid
826
   *
827
   * @return true if the operation is allowed
828
   * 
829
   * @throws ServiceFailure
830
   * @throws InvalidToken
831
   * @throws NotFound
832
   * @throws NotAuthorized
833
   * @throws NotImplemented
834
   * @throws InvalidRequest
835
   */
836
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
837
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
838
    NotImplemented, InvalidRequest {
839

    
840
    boolean allowed = false;
841
    
842
    if (permission == null) {
843
    	throw new InvalidRequest("1761", "Permission was not provided or is invalid");
844
    }
845
    
846
    // permissions are hierarchical
847
    List<Permission> expandedPermissions = null;
848
    
849
    // always allow CN access
850
    if ( isAdminAuthorized(session) ) {
851
        allowed = true;
852
        return allowed;
853
        
854
    }
855
    
856
    // get the subject[s] from the session
857
	//defer to the shared util for recursively compiling the subjects	
858
	Set<Subject> subjects = AuthUtils.authorizedClientSubjects(session);
859
    
860
	// track the identities we have checked against
861
	StringBuffer includedSubjects = new StringBuffer();
862
    	
863
    // get the system metadata
864
    String pidStr = pid.getValue();
865
    SystemMetadata systemMetadata = null;
866
    try {
867
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
868

    
869
    } catch (Exception e) {
870
        // convert Hazelcast RuntimeException to NotFound
871
        logMetacat.error("An error occurred while getting system metadata for identifier " +
872
            pid.getValue() + ". The error message was: " + e.getMessage());
873
        throw new NotFound("1800", "No record found for " + pidStr);
874
        
875
    } 
876
    
877
    // throw not found if it was not found
878
    if (systemMetadata == null) {
879
    	throw new NotFound("1800", "No system metadata could be found for given PID: " + pidStr);
880
    }
881
	    
882
    // do we own it?
883
    for (Subject s: subjects) {
884
      logMetacat.debug("Comparing \t" + 
885
                       systemMetadata.getRightsHolder().getValue() +
886
                       " \tagainst \t" + s.getValue());
887
      	includedSubjects.append(s.getValue() + "; ");
888
    	allowed = systemMetadata.getRightsHolder().equals(s);
889
    	if (allowed) {
890
    		return allowed;
891
    	}
892
    }    
893
    
894
    // otherwise check the access rules
895
    try {
896
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
897
	    search: // label break
898
	    for (AccessRule accessRule: allows) {
899
	      for (Subject s: subjects) {
900
	        logMetacat.debug("Checking allow access rule for subject: " + s.getValue());
901
	        if (accessRule.getSubjectList().contains(s)) {
902
	        	logMetacat.debug("Access rule contains subject: " + s.getValue());
903
	        	for (Permission p: accessRule.getPermissionList()) {
904
		        	logMetacat.debug("Checking permission: " + p.xmlValue());
905
	        		expandedPermissions = expandPermissions(p);
906
	        		allowed = expandedPermissions.contains(permission);
907
	        		if (allowed) {
908
			        	logMetacat.info("Permission granted: " + p.xmlValue() + " to " + s.getValue());
909
	        			break search; //label break
910
	        		}
911
	        	}
912
        		
913
	        }
914
	      }
915
	    }
916
    } catch (Exception e) {
917
    	// catch all for errors - safe side should be to deny the access
918
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
919
		allowed = false;
920
	  
921
    }
922
    
923
    // throw or return?
924
    if (!allowed) {
925
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr + " for subject[s]: " + includedSubjects.toString() );
926
    }
927
    
928
    return allowed;
929
    
930
  }
931
  
932
  /*
933
   * parse a logEntry and get the relevant field from it
934
   * 
935
   * @param fieldname
936
   * @param entry
937
   * @return
938
   */
939
  private String getLogEntryField(String fieldname, String entry) {
940
    String begin = "<" + fieldname + ">";
941
    String end = "</" + fieldname + ">";
942
    // logMetacat.debug("looking for " + begin + " and " + end +
943
    // " in entry " + entry);
944
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
945
        .indexOf(end));
946
    logMetacat.debug("entry " + fieldname + " : " + s);
947
    return s;
948
  }
949

    
950
  /** 
951
   * Determine if a given object should be treated as an XML science metadata
952
   * object. 
953
   * 
954
   * @param sysmeta - the SystemMetadata describing the object
955
   * @return true if the object should be treated as science metadata
956
   */
957
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
958
    
959
    ObjectFormat objectFormat = null;
960
    boolean isScienceMetadata = false;
961
    
962
    try {
963
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
964
      if ( objectFormat.getFormatType().equals("METADATA") ) {
965
      	isScienceMetadata = true;
966
      	
967
      }
968
      
969
       
970
    } catch (ServiceFailure e) {
971
      logMetacat.debug("There was a problem determining if the object identified by" + 
972
          sysmeta.getIdentifier().getValue() + 
973
          " is science metadata: " + e.getMessage());
974
    
975
    } catch (NotFound e) {
976
      logMetacat.debug("There was a problem determining if the object identified by" + 
977
          sysmeta.getIdentifier().getValue() + 
978
          " is science metadata: " + e.getMessage());
979
    
980
    }
981
    
982
    return isScienceMetadata;
983

    
984
  }
985
  
986
  /**
987
   * Check fro whitespace in the given pid.
988
   * null pids are also invalid by default
989
   * @param pid
990
   * @return
991
   */
992
  public static boolean isValidIdentifier(Identifier pid) {
993
	  if (pid != null && pid.getValue() != null && pid.getValue().length() > 0) {
994
		  return !pid.getValue().matches("\\s");
995
	  } 
996
	  return false;
997
  }
998
  
999
  
1000
  /**
1001
   * Insert or update an XML document into Metacat
1002
   * 
1003
   * @param xml - the XML document to insert or update
1004
   * @param pid - the identifier to be used for the resulting object
1005
   * 
1006
   * @return localId - the resulting docid of the document created or updated
1007
   * 
1008
   */
1009
  public String insertOrUpdateDocument(String xml, Identifier pid, 
1010
    Session session, String insertOrUpdate) 
1011
    throws ServiceFailure {
1012
    
1013
  	logMetacat.debug("Starting to insert xml document...");
1014
    IdentifierManager im = IdentifierManager.getInstance();
1015

    
1016
    // generate pid/localId pair for sysmeta
1017
    String localId = null;
1018
    
1019
    if(insertOrUpdate.equals("insert")) {
1020
      localId = im.generateLocalId(pid.getValue(), 1);
1021
      
1022
    } else {
1023
      //localid should already exist in the identifier table, so just find it
1024
      try {
1025
        logMetacat.debug("Updating pid " + pid.getValue());
1026
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
1027
        
1028
        localId = im.getLocalId(pid.getValue());
1029
        
1030
        logMetacat.debug("localId: " + localId);
1031
        //increment the revision
1032
        String docid = localId.substring(0, localId.lastIndexOf("."));
1033
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1034
        int rev = new Integer(revS).intValue();
1035
        rev++;
1036
        docid = docid + "." + rev;
1037
        localId = docid;
1038
        logMetacat.debug("incremented localId: " + localId);
1039
      
1040
      } catch(McdbDocNotFoundException e) {
1041
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
1042
            "pid " + pid.getValue() + 
1043
            " should have been in the identifier table, but it wasn't: " + 
1044
            e.getMessage());
1045
      
1046
      }
1047
      
1048
    }
1049

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

    
1150
    logMetacat.debug("Case DATA: starting to write to disk.");
1151
	if (locked) {
1152

    
1153
          File dataDirectory = new File(datafilepath);
1154
          dataDirectory.mkdirs();
1155
  
1156
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1157
  
1158
          // TODO: Check that the file size matches SystemMetadata
1159
          // long size = newFile.length();
1160
          // if (size == 0) {
1161
          //     throw new IOException("Uploaded file is 0 bytes!");
1162
          // }
1163
  
1164
          // Register the file in the database (which generates an exception
1165
          // if the localId is not acceptable or other untoward things happen
1166
          try {
1167
            logMetacat.debug("Registering document...");
1168
            DocumentImpl.registerDocument(localId, "BIN", localId,
1169
                    username, groupnames);
1170
            logMetacat.debug("Registration step completed.");
1171
            
1172
          } catch (SQLException e) {
1173
            //newFile.delete();
1174
            logMetacat.debug("SQLE: " + e.getMessage());
1175
            e.printStackTrace(System.out);
1176
            throw new ServiceFailure("1190", "Registration failed: " + 
1177
            		e.getMessage());
1178
            
1179
          } catch (AccessionNumberException e) {
1180
            //newFile.delete();
1181
            logMetacat.debug("ANE: " + e.getMessage());
1182
            e.printStackTrace(System.out);
1183
            throw new ServiceFailure("1190", "Registration failed: " + 
1184
            	e.getMessage());
1185
            
1186
          } catch (Exception e) {
1187
            //newFile.delete();
1188
            logMetacat.debug("Exception: " + e.getMessage());
1189
            e.printStackTrace(System.out);
1190
            throw new ServiceFailure("1190", "Registration failed: " + 
1191
            	e.getMessage());
1192
          }
1193
  
1194
          logMetacat.debug("Logging the creation event.");
1195
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1196
  
1197
          // Schedule replication for this data file, the "insert" action is important here!
1198
          logMetacat.debug("Scheduling replication.");
1199
          ForceReplicationHandler frh = new ForceReplicationHandler(localId, "insert", false, null);
1200
      }
1201
      
1202
      return localId;
1203
    
1204
  }
1205

    
1206
  /**
1207
   * Insert a systemMetadata document and return its localId
1208
   */
1209
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1210
      throws ServiceFailure {
1211
      
1212
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1213
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1214
      logMetacat.debug("Inserting new system metadata with modified date " + 
1215
          sysmeta.getDateSysMetadataModified());
1216
      
1217
      //insert the system metadata
1218
      try {
1219
        // note: the calling subclass handles the map hazelcast lock/unlock
1220
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1221
      	
1222
      } catch (Exception e) {
1223
          throw new ServiceFailure("1190", e.getMessage());
1224
          
1225
	    }  
1226
  }
1227

    
1228
  /**
1229
   * Update a systemMetadata document
1230
   * 
1231
   * @param sysMeta - the system metadata object in the system to update
1232
   */
1233
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1234
        throws ServiceFailure {
1235

    
1236
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1237
        sysMeta.setDateSysMetadataModified(new Date());
1238
        try {
1239
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1240
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1241

    
1242
        } catch (Exception e) {
1243
            throw new ServiceFailure("4862", e.getMessage());
1244

    
1245
        } finally {
1246
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1247

    
1248
        }
1249

    
1250
    }
1251
  
1252
  /**
1253
   * Given a Permission, returns a list of all permissions that it encompasses
1254
   * Permissions are hierarchical so that WRITE also allows READ.
1255
   * @param permission
1256
   * @return list of included Permissions for the given permission
1257
   */
1258
  protected List<Permission> expandPermissions(Permission permission) {
1259
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1260
	    if (permission.equals(Permission.READ)) {
1261
	    	expandedPermissions.add(Permission.READ);
1262
	    }
1263
	    if (permission.equals(Permission.WRITE)) {
1264
	    	expandedPermissions.add(Permission.READ);
1265
	    	expandedPermissions.add(Permission.WRITE);
1266
	    }
1267
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1268
	    	expandedPermissions.add(Permission.READ);
1269
	    	expandedPermissions.add(Permission.WRITE);
1270
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1271
	    }
1272
	    return expandedPermissions;
1273
  }
1274

    
1275
  /*
1276
   * Write a stream to a file
1277
   * 
1278
   * @param dir - the directory to write to
1279
   * @param fileName - the file name to write to
1280
   * @param data - the object bytes as an input stream
1281
   * 
1282
   * @return newFile - the new file created
1283
   * 
1284
   * @throws ServiceFailure
1285
   */
1286
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1287
    throws ServiceFailure {
1288
    
1289
    File newFile = new File(dir, fileName);
1290
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1291

    
1292
    try {
1293
        if (newFile.createNewFile()) {
1294
          // write data stream to desired file
1295
          OutputStream os = new FileOutputStream(newFile);
1296
          long length = IOUtils.copyLarge(data, os);
1297
          os.flush();
1298
          os.close();
1299
        } else {
1300
          logMetacat.debug("File creation failed, or file already exists.");
1301
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1302
        }
1303
    } catch (FileNotFoundException e) {
1304
      logMetacat.debug("FNF: " + e.getMessage());
1305
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1306
                + e.getMessage());
1307
    } catch (IOException e) {
1308
      logMetacat.debug("IOE: " + e.getMessage());
1309
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1310
                + " " + e.getMessage());
1311
    }
1312

    
1313
    return newFile;
1314
  }
1315

    
1316
  /*
1317
   * Returns a list of nodes that have been registered with the DataONE infrastructure
1318
   * that match the given session subject
1319
   * @return nodes - List of nodes from the registry with a matching session subject
1320
   * 
1321
   * @throws ServiceFailure
1322
   * @throws NotImplemented
1323
   */
1324
  protected List<Node> listNodesBySubject(Subject subject) 
1325
      throws ServiceFailure, NotImplemented {
1326
      List<Node> nodeList = new ArrayList<Node>();
1327
      
1328
      CNode cn = D1Client.getCN();
1329
      List<Node> nodes = cn.listNodes().getNodeList();
1330
      
1331
      // find the node in the node list
1332
      for ( Node node : nodes ) {
1333
          
1334
          List<Subject> nodeSubjects = node.getSubjectList();
1335
          if (nodeSubjects != null) {    
1336
	          // check if the session subject is in the node subject list
1337
	          for (Subject nodeSubject : nodeSubjects) {
1338
	              if ( nodeSubject.equals(subject) ) { // subject of session == node subject
1339
	                  nodeList.add(node);  
1340
	              }                              
1341
	          }
1342
          }
1343
      }
1344
      
1345
      return nodeList;
1346
      
1347
  }
1348

    
1349
  /**
1350
   * Archives an object, where the object is either a 
1351
   * data object or a science metadata object.
1352
   * 
1353
   * @param session - the Session object containing the credentials for the Subject
1354
   * @param pid - The object identifier to be archived
1355
   * 
1356
   * @return pid - the identifier of the object used for the archiving
1357
   * 
1358
   * @throws InvalidToken
1359
   * @throws ServiceFailure
1360
   * @throws NotAuthorized
1361
   * @throws NotFound
1362
   * @throws NotImplemented
1363
   * @throws InvalidRequest
1364
   */
1365
  public Identifier archive(Session session, Identifier pid) 
1366
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1367

    
1368
      String localId = null;
1369
      boolean allowed = false;
1370
      String username = Constants.SUBJECT_PUBLIC;
1371
      String[] groupnames = null;
1372
      if (session == null) {
1373
      	throw new InvalidToken("1330", "No session has been provided");
1374
      } else {
1375
          username = session.getSubject().getValue();
1376
          if (session.getSubjectInfo() != null) {
1377
              List<Group> groupList = session.getSubjectInfo().getGroupList();
1378
              if (groupList != null) {
1379
                  groupnames = new String[groupList.size()];
1380
                  for (int i = 0; i > groupList.size(); i++) {
1381
                      groupnames[i] = groupList.get(i).getGroupName();
1382
                  }
1383
              }
1384
          }
1385
      }
1386

    
1387
      // do we have a valid pid?
1388
      if (pid == null || pid.getValue().trim().equals("")) {
1389
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
1390
      }
1391

    
1392
      // check for the existing identifier
1393
      try {
1394
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1395
      } catch (McdbDocNotFoundException e) {
1396
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
1397
      }
1398

    
1399
      // does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
1400
      try {
1401
			allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
1402
		} catch (InvalidRequest e) {
1403
          throw new ServiceFailure("1350", e.getDescription());
1404
		}
1405
          
1406

    
1407
      if (allowed) {
1408
          try {
1409
              // archive the document
1410
              DocumentImpl.delete(localId, null, null, null, false);
1411
              EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
1412

    
1413
              // archive it
1414
              SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1415
              sysMeta.setArchived(true);
1416
              sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1417
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
1418
              
1419
          } catch (McdbDocNotFoundException e) {
1420
              throw new NotFound("1340", "The provided identifier was invalid.");
1421

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

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

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

    
1432
      } else {
1433
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
1434
      }
1435

    
1436
      return pid;
1437
  }
1438
  
1439
  public Identifier archive(Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1440
	  return archive(null, pid);
1441
  }
1442

    
1443

    
1444
}
(2-2/5)