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: 2015-12-16 09:58:02 -0800 (Wed, 16 Dec 2015) $'
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.ByteArrayOutputStream;
27
import java.io.File;
28
import java.io.FileNotFoundException;
29
import java.io.FileOutputStream;
30
import java.io.IOException;
31
import java.io.InputStream;
32
import java.io.OutputStream;
33
import java.io.OutputStreamWriter;
34
import java.io.Writer;
35
import java.math.BigInteger;
36
import java.sql.PreparedStatement;
37
import java.sql.ResultSet;
38
import java.sql.SQLException;
39
import java.util.ArrayList;
40
import java.util.Calendar;
41
import java.util.Date;
42
import java.util.Hashtable;
43
import java.util.List;
44
import java.util.Set;
45
import java.util.Timer;
46
import java.util.Vector;
47
import java.util.concurrent.locks.Lock;
48

    
49
import javax.servlet.http.HttpServletRequest;
50

    
51
import org.apache.commons.io.IOUtils;
52
import org.apache.log4j.Logger;
53
import org.dataone.client.v2.CNode;
54
import org.dataone.client.v2.itk.D1Client;
55
import org.dataone.client.v2.formats.ObjectFormatCache;
56
import org.dataone.configuration.Settings;
57
import org.dataone.service.exceptions.BaseException;
58
import org.dataone.service.exceptions.IdentifierNotUnique;
59
import org.dataone.service.exceptions.InsufficientResources;
60
import org.dataone.service.exceptions.InvalidRequest;
61
import org.dataone.service.exceptions.InvalidSystemMetadata;
62
import org.dataone.service.exceptions.InvalidToken;
63
import org.dataone.service.exceptions.NotAuthorized;
64
import org.dataone.service.exceptions.NotFound;
65
import org.dataone.service.exceptions.NotImplemented;
66
import org.dataone.service.exceptions.ServiceFailure;
67
import org.dataone.service.exceptions.UnsupportedType;
68
import org.dataone.service.types.v1.AccessRule;
69
import org.dataone.service.types.v1.DescribeResponse;
70
import org.dataone.service.types.v1.Group;
71
import org.dataone.service.types.v1.Identifier;
72
import org.dataone.service.types.v1.ObjectFormatIdentifier;
73
import org.dataone.service.types.v1.ObjectList;
74
import org.dataone.service.types.v2.Log;
75
import org.dataone.service.types.v2.Node;
76
import org.dataone.service.types.v2.OptionList;
77
import org.dataone.service.types.v1.Event;
78
import org.dataone.service.types.v1.NodeReference;
79
import org.dataone.service.types.v1.NodeType;
80
import org.dataone.service.types.v2.ObjectFormat;
81
import org.dataone.service.types.v1.Permission;
82
import org.dataone.service.types.v1.Replica;
83
import org.dataone.service.types.v1.Session;
84
import org.dataone.service.types.v1.Subject;
85
import org.dataone.service.types.v2.SystemMetadata;
86
import org.dataone.service.types.v1.util.AuthUtils;
87
import org.dataone.service.types.v1.util.ChecksumUtil;
88
import org.dataone.service.util.Constants;
89

    
90
import edu.ucsb.nceas.metacat.AccessionNumber;
91
import edu.ucsb.nceas.metacat.AccessionNumberException;
92
import edu.ucsb.nceas.metacat.DBTransform;
93
import edu.ucsb.nceas.metacat.DocumentImpl;
94
import edu.ucsb.nceas.metacat.EventLog;
95
import edu.ucsb.nceas.metacat.IdentifierManager;
96
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
97
import edu.ucsb.nceas.metacat.MetacatHandler;
98
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
99
import edu.ucsb.nceas.metacat.common.query.stream.ContentTypeByteArrayInputStream;
100
import edu.ucsb.nceas.metacat.database.DBConnection;
101
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
102
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
103
import edu.ucsb.nceas.metacat.index.MetacatSolrIndex;
104
import edu.ucsb.nceas.metacat.properties.PropertyService;
105
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
106
import edu.ucsb.nceas.metacat.util.SkinUtil;
107
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
108

    
109
public abstract class D1NodeService {
110
    
111
  public static final String DELETEDMESSAGE = "The object with the PID has been deleted from the node.";
112
    
113
  private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
114

    
115
  /** For logging the operations */
116
  protected HttpServletRequest request;
117
  
118
  /* reference to the metacat handler */
119
  protected MetacatHandler handler;
120
  
121
  /* parameters set in the incoming request */
122
  private Hashtable<String, String[]> params;
123
  
124
  /**
125
   * limit paged results sets to a configured maximum
126
   */
127
  protected static int MAXIMUM_DB_RECORD_COUNT = 7000;
128
  
129
  static {
130
		try {
131
			MAXIMUM_DB_RECORD_COUNT = Integer.valueOf(PropertyService.getProperty("database.webResultsetSize"));
132
		} catch (Exception e) {
133
			logMetacat.warn("Could not set MAXIMUM_DB_RECORD_COUNT", e);
134
		}
135
	}
136
  
137
  /**
138
   * out-of-band session object to be used when not passed in as a method parameter
139
   */
140
  protected Session session;
141

    
142
  /**
143
   * Constructor - used to set the metacatUrl from a subclass extending D1NodeService
144
   * 
145
   * @param metacatUrl - the URL of the metacat service, including the ending /d1
146
   */
147
  public D1NodeService(HttpServletRequest request) {
148
		this.request = request;
149
	}
150

    
151
  /**
152
   * retrieve the out-of-band session
153
   * @return
154
   */
155
  	public Session getSession() {
156
		return session;
157
	}
158
  	
159
  	/**
160
  	 * Set the out-of-band session
161
  	 * @param session
162
  	 */
163
	public void setSession(Session session) {
164
		this.session = session;
165
	}
166

    
167
  /**
168
   * This method provides a lighter weight mechanism than 
169
   * getSystemMetadata() for a client to determine basic 
170
   * properties of the referenced object.
171
   * 
172
   * @param session - the Session object containing the credentials for the Subject
173
   * @param pid - the identifier of the object to be described
174
   * 
175
   * @return describeResponse - A set of values providing a basic description 
176
   *                            of the object.
177
   * 
178
   * @throws InvalidToken
179
   * @throws ServiceFailure
180
   * @throws NotAuthorized
181
   * @throws NotFound
182
   * @throws NotImplemented
183
   * @throws InvalidRequest
184
   */
185
  public DescribeResponse describe(Session session, Identifier pid) 
186
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
187
      
188
      String serviceFailureCode = "4931";
189
      Identifier sid = getPIDForSID(pid, serviceFailureCode);
190
      if(sid != null) {
191
          pid = sid;
192
      }
193

    
194
    // get system metadata and construct the describe response
195
      SystemMetadata sysmeta = getSystemMetadata(session, pid);
196
      DescribeResponse describeResponse = 
197
      	new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(), 
198
      			sysmeta.getDateSysMetadataModified(),
199
      			sysmeta.getChecksum(), sysmeta.getSerialVersion());
200

    
201
      return describeResponse;
202

    
203
  }
204
  
205
  /**
206
   * Deletes an object from the Member Node, where the object is either a 
207
   * data object or a science metadata object.
208
   * 
209
   * @param session - the Session object containing the credentials for the Subject
210
   * @param pid - The object identifier to be deleted
211
   * 
212
   * @return pid - the identifier of the object used for the deletion
213
   * 
214
   * @throws InvalidToken
215
   * @throws ServiceFailure
216
   * @throws NotAuthorized
217
   * @throws NotFound
218
   * @throws NotImplemented
219
   * @throws InvalidRequest
220
   */
221
  public Identifier delete(Session session, Identifier pid) 
222
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
223
      
224
      String localId = null;
225
      if (session == null) {
226
      	throw new InvalidToken("1330", "No session has been provided");
227
      }
228
      // just for logging purposes
229
      String username = session.getSubject().getValue();
230

    
231
      // do we have a valid pid?
232
      if (pid == null || pid.getValue().trim().equals("")) {
233
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
234
      }
235

    
236
      // check for the existing identifier
237
      try {
238
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
239
      } catch (McdbDocNotFoundException e) {
240
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
241
      } catch (SQLException e) {
242
          throw new ServiceFailure("1350", "The object with the provided " + "identifier "+pid.getValue()+" couldn't be identified since "+e.getMessage());
243
      }
244
      
245
      try {
246
          // delete the document, as admin
247
          DocumentImpl.delete(localId, null, null, null, true);
248
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
249

    
250
          // archive it
251
          // DocumentImpl.delete() now sets this
252
          // see https://redmine.dataone.org/issues/3406
253
//          SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
254
//          sysMeta.setArchived(true);
255
//          sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
256
//          HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
257
          
258
      } catch (McdbDocNotFoundException e) {
259
          throw new NotFound("1340", "The provided identifier was invalid.");
260

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

    
264
      } catch (InsufficientKarmaException e) {
265
          if ( logMetacat.isDebugEnabled() ) {
266
              e.printStackTrace();
267
          }
268
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
269
      
270
      } catch (Exception e) { // for some reason DocumentImpl throws a general Exception
271
          throw new ServiceFailure("1350", "There was a problem deleting the object." + "The error message was: " + e.getMessage());
272
      }
273

    
274
      return pid;
275
  }
276
  
277
  /**
278
   * Low level, "are you alive" operation. A valid ping response is 
279
   * indicated by a HTTP status of 200.
280
   * 
281
   * @return true if the service is alive
282
   * 
283
   * @throws NotImplemented
284
   * @throws ServiceFailure
285
   * @throws InsufficientResources
286
   */
287
  public Date ping() 
288
      throws NotImplemented, ServiceFailure, InsufficientResources {
289

    
290
      // test if we can get a database connection
291
      int serialNumber = -1;
292
      DBConnection dbConn = null;
293
      try {
294
          dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
295
          serialNumber = dbConn.getCheckOutSerialNumber();
296
      } catch (SQLException e) {
297
      	ServiceFailure sf = new ServiceFailure("", e.getMessage());
298
      	sf.initCause(e);
299
          throw sf;
300
      } finally {
301
          // Return the database connection
302
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
303
      }
304

    
305
      return Calendar.getInstance().getTime();
306
  }
307
  
308
  /**
309
   * Adds a new object to the Node, where the object is either a data 
310
   * object or a science metadata object. This method is called by clients 
311
   * to create new data objects on Member Nodes or internally for Coordinating
312
   * Nodes
313
   * 
314
   * @param session - the Session object containing the credentials for the Subject
315
   * @param pid - The object identifier to be created
316
   * @param object - the object bytes
317
   * @param sysmeta - the system metadata that describes the object  
318
   * 
319
   * @return pid - the object identifier created
320
   * 
321
   * @throws InvalidToken
322
   * @throws ServiceFailure
323
   * @throws NotAuthorized
324
   * @throws IdentifierNotUnique
325
   * @throws UnsupportedType
326
   * @throws InsufficientResources
327
   * @throws InvalidSystemMetadata
328
   * @throws NotImplemented
329
   * @throws InvalidRequest
330
   */
331
  public Identifier create(Session session, Identifier pid, InputStream object,
332
    SystemMetadata sysmeta) 
333
    throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
334
    UnsupportedType, InsufficientResources, InvalidSystemMetadata, 
335
    NotImplemented, InvalidRequest {
336

    
337
    Identifier resultPid = null;
338
    String localId = null;
339
    boolean allowed = false;
340
    
341
    // check for null session
342
    if (session == null) {
343
    	throw new InvalidToken("4894", "Session is required to WRITE to the Node.");
344
    }
345
    Subject subject = session.getSubject();
346

    
347
    Subject publicSubject = new Subject();
348
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
349
	// be sure the user is authenticated for create()
350
    if (subject == null || subject.getValue() == null || 
351
        subject.equals(publicSubject) ) {
352
      throw new NotAuthorized("1100", "The provided identity does not have " +
353
        "permission to WRITE to the Node.");
354
      
355
    }
356
        
357
    // verify that pid == SystemMetadata.getIdentifier()
358
    logMetacat.debug("Comparing pid|sysmeta_pid: " + 
359
      pid.getValue() + "|" + sysmeta.getIdentifier().getValue());
360
    if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
361
        throw new InvalidSystemMetadata("1180", 
362
            "The supplied system metadata is invalid. " +
363
            "The identifier " + pid.getValue() + " does not match identifier" +
364
            "in the system metadata identified by " +
365
            sysmeta.getIdentifier().getValue() + ".");
366
        
367
    }
368
    
369

    
370
    logMetacat.debug("Checking if identifier exists: " + pid.getValue());
371
    // Check that the identifier does not already exist
372
    boolean idExists = false;
373
    try {
374
        idExists = IdentifierManager.getInstance().identifierExists(pid.getValue());
375
    } catch (SQLException e) {
376
        throw new ServiceFailure("1190", 
377
                                "The requested identifier " + pid.getValue() +
378
                                " couldn't be determined if it is unique since : "+e.getMessage());
379
    }
380
    if (idExists) {
381
	    	throw new IdentifierNotUnique("1120", 
382
			          "The requested identifier " + pid.getValue() +
383
			          " is already used by another object and" +
384
			          "therefore can not be used for this object. Clients should choose" +
385
			          "a new identifier that is unique and retry the operation or " +
386
			          "use CN.reserveIdentifier() to reserve one.");
387
    	
388
    }
389
    
390
    
391
    // TODO: this probably needs to be refined more
392
    try {
393
      allowed = isAuthorized(session, pid, Permission.WRITE);
394
            
395
    } catch (NotFound e) {
396
      // The identifier doesn't exist, writing should be fine.
397
      allowed = true;
398
    }
399
    
400
    if(!allowed) {
401
        throw new NotAuthorized("1100", "Provited Identity doesn't have the WRITE permission on the pid "+pid.getValue());
402
    }
403
    // verify checksum, only if we can reset the inputstream
404
    if (object.markSupported()) {
405
        logMetacat.debug("Checking checksum for: " + pid.getValue());
406
	    String checksumAlgorithm = sysmeta.getChecksum().getAlgorithm();
407
	    String checksumValue = sysmeta.getChecksum().getValue();
408
	    try {
409
			String computedChecksumValue = ChecksumUtil.checksum(object, checksumAlgorithm).getValue();
410
			// it's very important that we don't consume the stream
411
			object.reset();
412
			if (!computedChecksumValue.equals(checksumValue)) {
413
			    logMetacat.error("Checksum for " + pid.getValue() + " does not match system metadata, computed = " + computedChecksumValue );
414
				throw new InvalidSystemMetadata("4896", "Checksum given does not match that of the object");
415
			}
416
		} catch (Exception e) {
417
			String msg = "Error verifying checksum values";
418
	      	logMetacat.error(msg, e);
419
	        throw new ServiceFailure("1190", msg + ": " + e.getMessage());
420
		}
421
    } else {
422
    	logMetacat.warn("mark is not supported on the object's input stream - cannot verify checksum without consuming stream");
423
    }
424
    	
425
    // we have the go ahead
426
    //if ( allowed ) {
427
         
428
        // save the sysmeta
429
        try {
430
            // lock and unlock of the pid happens in the subclass
431
            HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
432
           
433
        
434
        } catch (Exception e) {
435
            logMetacat.error("Problem creating system metadata: " + pid.getValue(), e);
436
            throw new ServiceFailure("1190", e.getMessage());
437
        }
438
      
439
        logMetacat.debug("Allowed to insert: " + pid.getValue());
440

    
441
      // Science metadata (XML) or science data object?
442
      // TODO: there are cases where certain object formats are science metadata
443
      // but are not XML (netCDF ...).  Handle this.
444
      if ( isScienceMetadata(sysmeta) ) {
445
        
446
        // CASE METADATA:
447
      	//String objectAsXML = "";
448
        try {
449
	        //objectAsXML = IOUtils.toString(object, "UTF-8");
450
	        localId = insertOrUpdateDocument(object,"UTF-8", pid, session, "insert");
451
	        //localId = im.getLocalId(pid.getValue());
452

    
453
        } catch (IOException e) {
454
            removeSystemMeta(pid);
455
        	String msg = "The Node is unable to create the object. " +
456
          "There was a problem converting the object to XML";
457
        	logMetacat.info(msg);
458
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
459

    
460
        } catch (ServiceFailure e) {
461
            removeSystemMeta(pid);
462
            throw e;
463
        } catch (Exception e) {
464
            removeSystemMeta(pid);
465
            throw new ServiceFailure("1190", "The node is unable to create the object: " + e.getMessage());
466
        }
467
                    
468
      } else {
469
	        
470
	      // DEFAULT CASE: DATA (needs to be checked and completed)
471
          try {
472
              localId = insertDataObject(object, pid, session);
473
          } catch (ServiceFailure e) {
474
              removeSystemMeta(pid);
475
              throw e;
476
          } catch (Exception e) {
477
              removeSystemMeta(pid);
478
              throw new ServiceFailure("1190", "The node is unable to create the object: " + e.getMessage());
479
          }
480
	      
481
      }   
482
    
483
    //}
484

    
485
    logMetacat.debug("Done inserting new object: " + pid.getValue());
486
    
487
    // setting the resulting identifier failed
488
    if (localId == null ) {
489
        removeSystemMeta(pid);
490
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
491
    }
492
    
493
    try {
494
        // submit for indexing
495
        MetacatSolrIndex.getInstance().submit(sysmeta.getIdentifier(), sysmeta, null, true);
496
    } catch (Exception e) {
497
        logMetacat.warn("Couldn't create solr index for object "+pid.getValue());
498
    }
499

    
500
    resultPid = pid;
501
    
502
    logMetacat.debug("create() complete for object: " + pid.getValue());
503

    
504
    return resultPid;
505
  }
506
  
507
  /*
508
   * Roll-back method when inserting data object fails.
509
   */
510
  protected void removeSystemMeta(Identifier id){
511
      HazelcastService.getInstance().getSystemMetadataMap().remove(id);
512
  }
513
  
514
  /*
515
   * Roll-back method when inserting data object fails.
516
   */
517
  protected void removeSolrIndex(SystemMetadata sysMeta) {
518
      sysMeta.setSerialVersion(sysMeta.getSerialVersion().add(BigInteger.ONE));
519
      sysMeta.setArchived(true);
520
      sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
521
      try {
522
          MetacatSolrIndex.getInstance().submit(sysMeta.getIdentifier(), sysMeta, null, false);
523
      } catch (Exception e) {
524
          logMetacat.warn("Can't remove the solr index for pid "+sysMeta.getIdentifier().getValue());
525
      }
526
      
527
  }
528

    
529
  /**
530
   * Return the log records associated with a given event between the start and 
531
   * end dates listed given a particular Subject listed in the Session
532
   * 
533
   * @param session - the Session object containing the credentials for the Subject
534
   * @param fromDate - the start date of the desired log records
535
   * @param toDate - the end date of the desired log records
536
   * @param event - restrict log records of a specific event type
537
   * @param start - zero based offset from the first record in the 
538
   *                set of matching log records. Used to assist with 
539
   *                paging the response.
540
   * @param count - maximum number of log records to return in the response. 
541
   *                Used to assist with paging the response.
542
   * 
543
   * @return the desired log records
544
   * 
545
   * @throws InvalidToken
546
   * @throws ServiceFailure
547
   * @throws NotAuthorized
548
   * @throws InvalidRequest
549
   * @throws NotImplemented
550
   */
551
  public Log getLogRecords(Session session, Date fromDate, Date toDate, 
552
      String event, String pidFilter, Integer start, Integer count) throws InvalidToken, ServiceFailure,
553
      NotAuthorized, InvalidRequest, NotImplemented {
554

    
555
	  // only admin access to this method
556
	  // see https://redmine.dataone.org/issues/2855
557
	  if (!isAdminAuthorized(session)) {
558
		  throw new NotAuthorized("1460", "Only the CN or admin is allowed to harvest logs from this node");
559
	  }
560
    Log log = new Log();
561
    IdentifierManager im = IdentifierManager.getInstance();
562
    EventLog el = EventLog.getInstance();
563
    if ( fromDate == null ) {
564
      logMetacat.debug("setting fromdate from null");
565
      fromDate = new Date(1);
566
    }
567
    if ( toDate == null ) {
568
      logMetacat.debug("setting todate from null");
569
      toDate = new Date();
570
    }
571

    
572
    if ( start == null ) {
573
    	start = 0;	
574
    }
575
    
576
    if ( count == null ) {
577
    	count = 1000;
578
    }
579
    
580
    // safeguard against large requests
581
    if (count > MAXIMUM_DB_RECORD_COUNT) {
582
    	count = MAXIMUM_DB_RECORD_COUNT;
583
    }
584

    
585
    String[] filterDocid = null;
586
    if (pidFilter != null && !pidFilter.trim().equals("")) {
587
        //check if the given identifier is a sid. If it is sid, choose the current pid of the sid.
588
        Identifier pid = new Identifier();
589
        pid.setValue(pidFilter);
590
        String serviceFailureCode = "1490";
591
        Identifier sid = getPIDForSID(pid, serviceFailureCode);
592
        if(sid != null) {
593
            pid = sid;
594
        }
595
        pidFilter = pid.getValue();
596
		try {
597
	      String localId = im.getLocalId(pidFilter);
598
	      filterDocid = new String[] {localId};
599
	    } catch (Exception ex) { 
600
	    	String msg = "Could not find localId for given pidFilter '" + pidFilter + "'";
601
	        logMetacat.warn(msg, ex);
602
	        //throw new InvalidRequest("1480", msg);
603
	        return log; //return 0 record
604
	    }
605
    }
606
    
607
    logMetacat.debug("fromDate: " + fromDate);
608
    logMetacat.debug("toDate: " + toDate);
609

    
610
    log = el.getD1Report(null, null, filterDocid, event,
611
        new java.sql.Timestamp(fromDate.getTime()),
612
        new java.sql.Timestamp(toDate.getTime()), false, start, count);
613
    
614
    logMetacat.info("getLogRecords");
615
    return log;
616
  }
617
    
618
  /**
619
   * Return the object identified by the given object identifier
620
   * 
621
   * @param session - the Session object containing the credentials for the Subject
622
   * @param pid - the object identifier for the given object
623
   * 
624
   * TODO: The D1 Authorization API doesn't provide information on which 
625
   * authentication system the Subject belongs to, and so it's not possible to
626
   * discern which Person or Group is a valid KNB LDAP DN.  Fix this.
627
   * 
628
   * @return inputStream - the input stream of the given object
629
   * 
630
   * @throws InvalidToken
631
   * @throws ServiceFailure
632
   * @throws NotAuthorized
633
   * @throws InvalidRequest
634
   * @throws NotImplemented
635
   */
636
  public InputStream get(Session session, Identifier pid) 
637
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
638
    NotImplemented {
639
    
640
    String serviceFailureCode = "1030";
641
    Identifier sid = getPIDForSID(pid, serviceFailureCode);
642
    if(sid != null) {
643
        pid = sid;
644
    }
645
    
646
    InputStream inputStream = null; // bytes to be returned
647
    handler = new MetacatHandler(new Timer());
648
    boolean allowed = false;
649
    String localId; // the metacat docid for the pid
650
    
651
    // get the local docid from Metacat
652
    try {
653
      localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
654
    
655
    } catch (McdbDocNotFoundException e) {
656
      throw new NotFound("1020", "The object specified by " + 
657
                         pid.getValue() +
658
                         " does not exist at this node.");
659
    } catch (SQLException e) {
660
        throw new ServiceFailure("1030", "The object specified by "+ pid.getValue()+
661
                                  " couldn't be identified at this node since "+e.getMessage());
662
    }
663
    
664
    // check for authorization
665
    try {
666
		allowed = isAuthorized(session, pid, Permission.READ);
667
	} catch (InvalidRequest e) {
668
		throw new ServiceFailure("1030", e.getDescription());
669
	}
670
    
671
    // if the person is authorized, perform the read
672
    if (allowed) {
673
      try {
674
        inputStream = handler.read(localId);
675
      } catch (McdbDocNotFoundException de) {
676
          String error ="";
677
          if(EventLog.getInstance().isDeleted(localId)) {
678
                error=DELETEDMESSAGE;
679
          }
680
          throw new NotFound("1020", "The object specified by " + 
681
                           pid.getValue() +
682
                           " does not exist at this node. "+error);
683
      } catch (Exception e) {
684
        throw new ServiceFailure("1030", "The object specified by " + 
685
            pid.getValue() +
686
            " could not be returned due to error: " +
687
            e.getMessage()+". ");
688
      }
689
    }
690

    
691
    // if we fail to set the input stream
692
    if ( inputStream == null ) {
693
        String error ="";
694
        if(EventLog.getInstance().isDeleted(localId)) {
695
              error=DELETEDMESSAGE;
696
        }
697
        throw new NotFound("1020", "The object specified by " + 
698
                         pid.getValue() +
699
                         " does not exist at this node. "+error);
700
    }
701
    
702
	// log the read event
703
    String principal = Constants.SUBJECT_PUBLIC;
704
    if (session != null && session.getSubject() != null) {
705
    	principal = session.getSubject().getValue();
706
    }
707
    EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "read");
708
    
709
    return inputStream;
710
  }
711

    
712
  /**
713
   * Return the system metadata for a given object
714
   * 
715
   * @param session - the Session object containing the credentials for the Subject
716
   * @param pid - the object identifier for the given object
717
   * 
718
   * @return inputStream - the input stream of the given system metadata object
719
   * 
720
   * @throws InvalidToken
721
   * @throws ServiceFailure
722
   * @throws NotAuthorized
723
   * @throws NotFound
724
   * @throws InvalidRequest
725
   * @throws NotImplemented
726
   */
727
    public SystemMetadata getSystemMetadata(Session session, Identifier pid)
728
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
729
        NotImplemented {
730

    
731
        String serviceFailureCode = "1090";
732
        Identifier sid = getPIDForSID(pid, serviceFailureCode);
733
        if(sid != null) {
734
            pid = sid;
735
        }
736
        boolean isAuthorized = false;
737
        SystemMetadata systemMetadata = null;
738
        List<Replica> replicaList = null;
739
        NodeReference replicaNodeRef = null;
740
        List<Node> nodeListBySubject = null;
741
        Subject subject = null;
742
        
743
        if (session != null ) {
744
            subject = session.getSubject();
745
        }
746
        
747
        // check normal authorization
748
        BaseException originalAuthorizationException = null;
749
        if (!isAuthorized) {
750
            try {
751
                isAuthorized = isAuthorized(session, pid, Permission.READ);
752

    
753
            } catch (InvalidRequest e) {
754
                throw new ServiceFailure("1090", e.getDescription());
755
            } catch (NotAuthorized nae) {
756
            	// catch this for later
757
            	originalAuthorizationException = nae;
758
			}
759
        }
760
        
761
        // get the system metadata first because we need the replica list for auth
762
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
763
        
764
        // check the replica information to expand access to MNs that might need it
765
        if (!isAuthorized) {
766
        	
767
	        try {
768
	        	
769
	            // if MNs are listed as replicas, allow access
770
	            if ( systemMetadata != null ) {
771
	                replicaList = systemMetadata.getReplicaList();
772
	                // only check if there are in fact replicas listed
773
	                if ( replicaList != null ) {
774
	                    
775
	                    if ( subject != null ) {
776
	                        // get the list of nodes with a matching node subject
777
	                        try {
778
	                            nodeListBySubject = listNodesBySubject(session.getSubject());
779
	
780
	                        } catch (BaseException e) {
781
	                            // Unexpected error contacting the CN via D1Client
782
	                            String msg = "Caught an unexpected error while trying "
783
	                                    + "to potentially authorize system metadata access "
784
	                                    + "based on the session subject. The error was "
785
	                                    + e.getMessage();
786
	                            logMetacat.error(msg);
787
	                            if (logMetacat.isDebugEnabled()) {
788
	                                e.printStackTrace();
789
	
790
	                            }
791
	                            // isAuthorized is still false 
792
	                        }
793
	
794
	                    }
795
	                    if (nodeListBySubject != null) {
796
	                        // compare node ids to replica node ids
797
	                        outer: for (Replica replica : replicaList) {
798
	                            replicaNodeRef = replica.getReplicaMemberNode();
799
	
800
	                            for (Node node : nodeListBySubject) {
801
	                                if (node.getIdentifier().equals(replicaNodeRef)) {
802
	                                    // node id via session subject matches a replica node
803
	                                    isAuthorized = true;
804
	                                    break outer;
805
	                                }
806
	                            }
807
	                        }
808
	                    }
809
	                }
810
	            }
811
	            
812
	            // if we still aren't authorized, then we are done
813
	            if (!isAuthorized) {
814
	                throw new NotAuthorized("1400", Permission.READ
815
	                        + " not allowed on " + pid.getValue());
816
	            }
817

    
818
	        } catch (RuntimeException e) {
819
	        	e.printStackTrace();
820
	            // convert hazelcast RuntimeException to ServiceFailure
821
	            throw new ServiceFailure("1090", "Unexpected error getting system metadata for: " + 
822
	                pid.getValue());	
823
	        }
824
	        
825
        }
826
        
827
        // It wasn't in the map
828
        if ( systemMetadata == null ) {
829
            String error ="";
830
            String localId = null;
831
            try {
832
                localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
833
              
834
             } catch (Exception e) {
835
                logMetacat.warn("Couldn't find the local id for the pid "+pid.getValue());
836
            }
837
            
838
            if(localId != null && EventLog.getInstance().isDeleted(localId)) {
839
                error = DELETEDMESSAGE;
840
            } else if (localId == null && EventLog.getInstance().isDeleted(pid.getValue())) {
841
                error = DELETEDMESSAGE;
842
            }
843
            throw new NotFound("1420", "No record found for: " + pid.getValue()+". "+error);
844
        }
845
        
846
        return systemMetadata;
847
    }
848
     
849
    
850
    /**
851
     * Test if the specified session represents the authoritative member node for the
852
     * given object specified by the identifier. According the the DataONE documentation, 
853
     * the authoritative member node has all the rights of the *rightsHolder*.
854
     * @param session - the Session object containing the credentials for the Subject
855
     * @param pid - the Identifier of the data object
856
     * @return true if the session represents the authoritative mn.
857
     * @throws ServiceFailure 
858
     * @throws NotImplemented 
859
     */
860
    public boolean isAuthoritativeMNodeAdmin(Session session, Identifier pid) {
861
        boolean allowed = false;
862
        //check the parameters
863
        if(session == null) {
864
            logMetacat.debug("D1NodeService.isAuthoritativeMNodeAdmin - the session object is null and return false.");
865
            return allowed;
866
        } else if (pid == null || pid.getValue() == null || pid.getValue().trim().equals("")) {
867
            logMetacat.debug("D1NodeService.isAuthoritativeMNodeAdmin - the Identifier object is null (not being specified) and return false.");
868
            return allowed;
869
        }
870
        
871
        //Get the subject from the session
872
        Subject subject = session.getSubject();
873
        if(subject != null) {
874
            //Get the authoritative member node info from the system metadata
875
            SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
876
            if(sysMeta != null) {
877
                NodeReference authoritativeMNode = sysMeta.getAuthoritativeMemberNode();
878
                if(authoritativeMNode != null) {
879
                        CNode cn = null;
880
                        try {
881
                            cn = D1Client.getCN();
882
                        } catch (BaseException e) {
883
                            logMetacat.error("D1NodeService.isAuthoritativeMNodeAdmin - couldn't connect to the CN since "+
884
                                            e.getDescription()+ ". The false value will be returned for the AuthoritativeMNodeAdmin.");
885
                            return allowed;
886
                        }
887
                        
888
                        if(cn != null) {
889
                            List<Node> nodes = null;
890
                            try {
891
                                nodes = cn.listNodes().getNodeList();
892
                            } catch (NotImplemented e) {
893
                                logMetacat.error("D1NodeService.isAuthoritativeMNodeAdmin - couldn't get the member nodes list from the CN since "+e.getDescription()+ 
894
                                                ". The false value will be returned for the AuthoritativeMNodeAdmin.");
895
                                return allowed;
896
                            } catch (ServiceFailure ee) {
897
                                logMetacat.error("D1NodeService.isAuthoritativeMNodeAdmin - couldn't get the member nodes list from the CN since "+ee.getDescription()+ 
898
                                                ". The false value will be returned for the AuthoritativeMNodeAdmin.");
899
                                return allowed;
900
                            }
901
                            if(nodes != null) {
902
                                for(Node node : nodes) {
903
                                    //find the authoritative node and get its subjects
904
                                    if (node.getType() == NodeType.MN && node.getIdentifier() != null && node.getIdentifier().equals(authoritativeMNode)) {
905
                                        List<Subject> nodeSubjects = node.getSubjectList();
906
                                        if(nodeSubjects != null) {
907
                                            // check if the session subject is in the node subject list
908
                                            for (Subject nodeSubject : nodeSubjects) {
909
                                                logMetacat.debug("D1NodeService.isAuthoritativeMNodeAdmin(), comparing subjects: " +
910
                                                    nodeSubject.getValue() + " and " + subject.getValue());
911
                                                if ( nodeSubject != null && nodeSubject.equals(subject) ) {
912
                                                    allowed = true; // subject of session == target node subject
913
                                                    break;
914
                                                }
915
                                            }              
916
                                        }
917
                                      
918
                                    }
919
                                }
920
                            }
921
                        }
922
                }
923
            }
924
        }
925
        return allowed;
926
    }
927
    
928
    
929
  /**
930
   * Test if the user identified by the provided token has administrative authorization 
931
   * 
932
   * @param session - the Session object containing the credentials for the Subject
933
   * 
934
   * @return true if the user is admin (mn itself or a cn )
935
   * 
936
   * @throws ServiceFailure
937
   * @throws InvalidToken
938
   * @throws NotFound
939
   * @throws NotAuthorized
940
   * @throws NotImplemented
941
   */
942
  public boolean isAdminAuthorized(Session session) 
943
      throws ServiceFailure, InvalidToken, NotAuthorized,
944
      NotImplemented {
945

    
946
      boolean allowed = false;
947
      
948
      // must have a session in order to check admin 
949
      if (session == null) {
950
         logMetacat.debug("In isAdminAuthorized(), session is null ");
951
         return false;
952
      }
953
      
954
      logMetacat.debug("In isAdminAuthorized(), checking CN or MN authorization for " +
955
           session.getSubject().getValue());
956
      
957
      // check if this is the node calling itself (MN)
958
      try {
959
          allowed = isNodeAdmin(session);
960
      } catch (Exception e) {
961
          logMetacat.warn("We can't determine if the session is a node subject. But we will contiune to check if it is a cn subject.");
962
      }
963
      
964
      
965
      // check the CN list
966
      if (!allowed) {
967
	      allowed = isCNAdmin(session);
968
      }
969
      
970
      return allowed;
971
  }
972
  
973
  /*
974
   * Determine if the specified session is a CN or not. Return true if it is; otherwise false.
975
   */
976
  protected boolean isCNAdmin (Session session) {
977
      boolean allowed = false;
978
      List<Node> nodes = null;
979
      logMetacat.debug("D1NodeService.isCNAdmin - the beginning");
980
      try {
981
          // are we allowed to do this? only CNs are allowed
982
          CNode cn = D1Client.getCN();
983
          logMetacat.debug("D1NodeService.isCNAdmin - after getting the cn.");
984
          nodes = cn.listNodes().getNodeList();
985
          logMetacat.debug("D1NodeService.isCNAdmin - after getting the node list.");
986
      }
987
      catch (Throwable e) {
988
          logMetacat.warn("Couldn't get the node list from the cn since "+e.getMessage()+". So we can't determine if the subject is a CN.");
989
          return false;  
990
      }
991
          
992
      if ( nodes == null ) {
993
          return false;
994
          //throw new ServiceFailure("4852", "Couldn't get node list.");
995
      }
996
      
997
      // find the node in the node list
998
      for ( Node node : nodes ) {
999
          
1000
          NodeReference nodeReference = node.getIdentifier();
1001
          logMetacat.debug("In isCNAdmin(), Node reference is: " + nodeReference.getValue());
1002
          
1003
          Subject subject = session.getSubject();
1004
          
1005
          if (node.getType() == NodeType.CN) {
1006
              List<Subject> nodeSubjects = node.getSubjectList();
1007
              
1008
              // check if the session subject is in the node subject list
1009
              for (Subject nodeSubject : nodeSubjects) {
1010
                  logMetacat.debug("In isCNAdmin(), comparing subjects: " +
1011
                      nodeSubject.getValue() + " and " + subject.getValue());
1012
                  if ( nodeSubject.equals(subject) ) {
1013
                      allowed = true; // subject of session == target node subject
1014
                      break;
1015
                      
1016
                  }
1017
              }              
1018
          }
1019
      }
1020
      logMetacat.debug("D1NodeService.isCNAdmin. Is it a cn admin? "+allowed);
1021
      return allowed;
1022
  }
1023
  
1024
  /**
1025
   * Test if the user identified by the provided token has administrative authorization 
1026
   * on this node because they are calling themselves
1027
   * 
1028
   * @param session - the Session object containing the credentials for the Subject
1029
   * 
1030
   * @return true if the user is this node
1031
   * @throws ServiceFailure 
1032
   * @throws NotImplemented 
1033
   */
1034
  public boolean isNodeAdmin(Session session) throws NotImplemented, ServiceFailure {
1035

    
1036
      boolean allowed = false;
1037
      
1038
      // must have a session in order to check admin 
1039
      if (session == null) {
1040
         logMetacat.debug("In isNodeAdmin(), session is null ");
1041
         return false;
1042
      }
1043
      
1044
      logMetacat.debug("In isNodeAdmin(), MN authorization for " +
1045
           session.getSubject().getValue());
1046
      
1047
      Node node = MNodeService.getInstance(request).getCapabilities();
1048
      NodeReference nodeReference = node.getIdentifier();
1049
      logMetacat.debug("In isNodeAdmin(), Node reference is: " + nodeReference.getValue());
1050
      
1051
      Subject subject = session.getSubject();
1052
      
1053
      if (node.getType() == NodeType.MN) {
1054
          List<Subject> nodeSubjects = node.getSubjectList();
1055
          
1056
          // check if the session subject is in the node subject list
1057
          for (Subject nodeSubject : nodeSubjects) {
1058
              logMetacat.debug("In isNodeAdmin(), comparing subjects: " +
1059
                  nodeSubject.getValue() + " and " + subject.getValue());
1060
              if ( nodeSubject.equals(subject) ) {
1061
                  allowed = true; // subject of session == this node's subect
1062
                  break;
1063
              }
1064
          }              
1065
      }
1066
      logMetacat.debug("In is NodeAdmin method. Is this a node admin? "+allowed);
1067
      return allowed;
1068
  }
1069
  
1070
  /**
1071
   * Test if the user identified by the provided token has authorization 
1072
   * for the operation on the specified object.
1073
   * Allowed subjects include:
1074
   * 1. CNs
1075
   * 2. Authoritative node
1076
   * 3. Owner of the object
1077
   * 4. Users with the specified permission in the access rules.
1078
   * 
1079
   * @param session - the Session object containing the credentials for the Subject
1080
   * @param pid - The identifer of the resource for which access is being checked
1081
   * @param operation - The type of operation which is being requested for the given pid
1082
   *
1083
   * @return true if the operation is allowed
1084
   * 
1085
   * @throws ServiceFailure
1086
   * @throws InvalidToken
1087
   * @throws NotFound
1088
   * @throws NotAuthorized
1089
   * @throws NotImplemented
1090
   * @throws InvalidRequest
1091
   */
1092
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
1093
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
1094
    NotImplemented, InvalidRequest {
1095

    
1096
    boolean allowed = false;
1097
    
1098
    if (permission == null) {
1099
    	throw new InvalidRequest("1761", "Permission was not provided or is invalid");
1100
    }
1101
    
1102
    // always allow CN access
1103
    if ( isAdminAuthorized(session) ) {
1104
        allowed = true;
1105
        return allowed;
1106
        
1107
    }
1108
    
1109
    String serviceFailureCode = "1760";
1110
    Identifier sid = getPIDForSID(pid, serviceFailureCode);
1111
    if(sid != null) {
1112
        pid = sid;
1113
    }
1114
    
1115
    // the authoritative member node of the pid always has the access as well.
1116
    if (isAuthoritativeMNodeAdmin(session, pid)) {
1117
        allowed = true;
1118
        return allowed;
1119
    }
1120
    
1121
    //is it the owner of the object or the access rules allow the user?
1122
    allowed = userHasPermission(session,  pid, permission );
1123
    
1124
    // throw or return?
1125
    if (!allowed) {
1126
     // track the identities we have checked against
1127
      StringBuffer includedSubjects = new StringBuffer();
1128
      Set<Subject> subjects = AuthUtils.authorizedClientSubjects(session);
1129
      for (Subject s: subjects) {
1130
             includedSubjects.append(s.getValue() + "; ");
1131
        }    
1132
      throw new NotAuthorized("1820", permission + " not allowed on " + pid.getValue() + " for subject[s]: " + includedSubjects.toString() );
1133
    }
1134
    
1135
    return allowed;
1136
    
1137
  }
1138
  
1139
  
1140
  /*
1141
   * Determine if a user has the permission to perform the specified permission.
1142
   * 1. Owner can have any permission.
1143
   * 2. Access table allow the user has the permission
1144
   */
1145
  public static boolean userHasPermission(Session userSession, Identifier pid, Permission permission ) throws NotFound{
1146
      boolean allowed = false;
1147
      // permissions are hierarchical
1148
      List<Permission> expandedPermissions = null;
1149
      // get the subject[s] from the session
1150
      //defer to the shared util for recursively compiling the subjects   
1151
      Set<Subject> subjects = AuthUtils.authorizedClientSubjects(userSession);
1152
          
1153
      // get the system metadata
1154
      String pidStr = pid.getValue();
1155
      SystemMetadata systemMetadata = null;
1156
      try {
1157
          systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1158

    
1159
      } catch (Exception e) {
1160
          // convert Hazelcast RuntimeException to NotFound
1161
          logMetacat.error("An error occurred while getting system metadata for identifier " +
1162
              pid.getValue() + ". The error message was: " + e.getMessage());
1163
          throw new NotFound("1800", "No record found for " + pidStr);
1164
          
1165
      } 
1166
      
1167
      // throw not found if it was not found
1168
      if (systemMetadata == null) {
1169
          String localId = null;
1170
          String error = "No system metadata could be found for given PID: " + pidStr;
1171
          try {
1172
              localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1173
            
1174
           } catch (Exception e) {
1175
              logMetacat.warn("Couldn't find the local id for the pid "+pidStr);
1176
          }
1177
          
1178
          if(localId != null && EventLog.getInstance().isDeleted(localId)) {
1179
              error = error + ". "+DELETEDMESSAGE;
1180
          } else if (localId == null && EventLog.getInstance().isDeleted(pid.getValue())) {
1181
              error = error + ". "+DELETEDMESSAGE;
1182
          }
1183
          throw new NotFound("1800", error);
1184
      }
1185
          
1186
      // do we own it?
1187
      for (Subject s: subjects) {
1188
        logMetacat.debug("Comparing \t" + 
1189
                         systemMetadata.getRightsHolder().getValue() +
1190
                         " \tagainst \t" + s.getValue());
1191
          //includedSubjects.append(s.getValue() + "; ");
1192
          allowed = systemMetadata.getRightsHolder().equals(s);
1193
          if (allowed) {
1194
              return allowed;
1195
          }
1196
      }    
1197
      
1198
      // otherwise check the access rules
1199
      try {
1200
          List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
1201
          search: // label break
1202
          for (AccessRule accessRule: allows) {
1203
            for (Subject s: subjects) {
1204
              logMetacat.debug("Checking allow access rule for subject: " + s.getValue());
1205
              if (accessRule.getSubjectList().contains(s)) {
1206
                  logMetacat.debug("Access rule contains subject: " + s.getValue());
1207
                  for (Permission p: accessRule.getPermissionList()) {
1208
                      logMetacat.debug("Checking permission: " + p.xmlValue());
1209
                      expandedPermissions = expandPermissions(p);
1210
                      allowed = expandedPermissions.contains(permission);
1211
                      if (allowed) {
1212
                          logMetacat.info("Permission granted: " + p.xmlValue() + " to " + s.getValue());
1213
                          break search; //label break
1214
                      }
1215
                  }
1216
                  
1217
              }
1218
            }
1219
          }
1220
      } catch (Exception e) {
1221
          // catch all for errors - safe side should be to deny the access
1222
          logMetacat.error("Problem checking authorization - defaulting to deny", e);
1223
          allowed = false;
1224
        
1225
      }
1226
      return allowed;
1227
  }
1228
  /*
1229
   * parse a logEntry and get the relevant field from it
1230
   * 
1231
   * @param fieldname
1232
   * @param entry
1233
   * @return
1234
   */
1235
  private String getLogEntryField(String fieldname, String entry) {
1236
    String begin = "<" + fieldname + ">";
1237
    String end = "</" + fieldname + ">";
1238
    // logMetacat.debug("looking for " + begin + " and " + end +
1239
    // " in entry " + entry);
1240
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
1241
        .indexOf(end));
1242
    logMetacat.debug("entry " + fieldname + " : " + s);
1243
    return s;
1244
  }
1245

    
1246
  /** 
1247
   * Determine if a given object should be treated as an XML science metadata
1248
   * object. 
1249
   * 
1250
   * @param sysmeta - the SystemMetadata describing the object
1251
   * @return true if the object should be treated as science metadata
1252
   */
1253
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
1254
    
1255
    ObjectFormat objectFormat = null;
1256
    boolean isScienceMetadata = false;
1257
    
1258
    try {
1259
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
1260
      if ( objectFormat.getFormatType().equals("METADATA") ) {
1261
      	isScienceMetadata = true;
1262
      	
1263
      }
1264
      
1265
       
1266
    } catch (ServiceFailure e) {
1267
      logMetacat.debug("There was a problem determining if the object identified by" + 
1268
          sysmeta.getIdentifier().getValue() + 
1269
          " is science metadata: " + e.getMessage());
1270
    
1271
    } catch (NotFound e) {
1272
      logMetacat.debug("There was a problem determining if the object identified by" + 
1273
          sysmeta.getIdentifier().getValue() + 
1274
          " is science metadata: " + e.getMessage());
1275
    
1276
    }
1277
    
1278
    return isScienceMetadata;
1279

    
1280
  }
1281
  
1282
  /**
1283
   * Check fro whitespace in the given pid.
1284
   * null pids are also invalid by default
1285
   * @param pid
1286
   * @return
1287
   */
1288
  public static boolean isValidIdentifier(Identifier pid) {
1289
	  if (pid != null && pid.getValue() != null && pid.getValue().length() > 0) {
1290
		  return !pid.getValue().matches(".*\\s+.*");
1291
	  } 
1292
	  return false;
1293
  }
1294
  
1295
  
1296
  /**
1297
   * Insert or update an XML document into Metacat
1298
   * 
1299
   * @param xml - the XML document to insert or update
1300
   * @param pid - the identifier to be used for the resulting object
1301
   * 
1302
   * @return localId - the resulting docid of the document created or updated
1303
   * 
1304
   */
1305
  public String insertOrUpdateDocument(InputStream xml, String encoding,  Identifier pid, 
1306
    Session session, String insertOrUpdate) 
1307
    throws ServiceFailure, IOException {
1308
    
1309
  	logMetacat.debug("Starting to insert xml document...");
1310
    IdentifierManager im = IdentifierManager.getInstance();
1311

    
1312
    // generate pid/localId pair for sysmeta
1313
    String localId = null;
1314
    byte[] xmlBytes  = IOUtils.toByteArray(xml);
1315
    String xmlStr = new String(xmlBytes, encoding);
1316
    if(insertOrUpdate.equals("insert")) {
1317
      localId = im.generateLocalId(pid.getValue(), 1);
1318
      
1319
    } else {
1320
      //localid should already exist in the identifier table, so just find it
1321
      try {
1322
        logMetacat.debug("Updating pid " + pid.getValue());
1323
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
1324
        
1325
        localId = im.getLocalId(pid.getValue());
1326
        
1327
        logMetacat.debug("localId: " + localId);
1328
        //increment the revision
1329
        String docid = localId.substring(0, localId.lastIndexOf("."));
1330
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1331
        int rev = new Integer(revS).intValue();
1332
        rev++;
1333
        docid = docid + "." + rev;
1334
        localId = docid;
1335
        logMetacat.debug("incremented localId: " + localId);
1336
      
1337
      } catch(McdbDocNotFoundException e) {
1338
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
1339
            "pid " + pid.getValue() + 
1340
            " should have been in the identifier table, but it wasn't: " + 
1341
            e.getMessage());
1342
      
1343
      } catch (SQLException e) {
1344
          throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument() -"+
1345
                     " couldn't identify if the pid "+pid.getValue()+" is in the identifier table since "+e.getMessage());
1346
      }
1347
      
1348
    }
1349

    
1350
    params = new Hashtable<String, String[]>();
1351
    String[] action = new String[1];
1352
    action[0] = insertOrUpdate;
1353
    params.put("action", action);
1354
    String[] docid = new String[1];
1355
    docid[0] = localId;
1356
    params.put("docid", docid);
1357
    String[] doctext = new String[1];
1358
    doctext[0] = xmlStr;
1359
    params.put("doctext", doctext);
1360
    
1361
    String username = Constants.SUBJECT_PUBLIC;
1362
    String[] groupnames = null;
1363
    if (session != null ) {
1364
    	username = session.getSubject().getValue();
1365
    	if (session.getSubjectInfo() != null) {
1366
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
1367
    		if (groupList != null) {
1368
    			groupnames = new String[groupList.size()];
1369
    			for (int i = 0; i < groupList.size(); i++ ) {
1370
    				groupnames[i] = groupList.get(i).getGroupName();
1371
    			}
1372
    		}
1373
    	}
1374
    }
1375
    
1376
    // do the insert or update action
1377
    handler = new MetacatHandler(new Timer());
1378
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null, 
1379
                        null, params, username, groupnames, false, false, xmlBytes);
1380
    
1381
    if(result.indexOf("<error>") != -1) {
1382
    	String detailCode = "";
1383
    	if ( insertOrUpdate.equals("insert") ) {
1384
    		// make sure to remove the mapping so that subsequent attempts do not fail with IdentifierNotUnique
1385
    		im.removeMapping(pid.getValue(), localId);
1386
    		detailCode = "1190";
1387
    		
1388
    	} else if ( insertOrUpdate.equals("update") ) {
1389
    		detailCode = "1310";
1390
    		
1391
    	}
1392
        throw new ServiceFailure(detailCode, 
1393
          "Error inserting or updating document: " + result);
1394
    }
1395
    logMetacat.debug("Finsished inserting xml document with id " + localId);
1396
    
1397
    return localId;
1398
  }
1399
  
1400
  /**
1401
   * Insert a data document
1402
   * 
1403
   * @param object
1404
   * @param pid
1405
   * @param sessionData
1406
   * @throws ServiceFailure
1407
   * @returns localId of the data object inserted
1408
   */
1409
  public String insertDataObject(InputStream object, Identifier pid, 
1410
          Session session) throws ServiceFailure {
1411
      
1412
    String username = Constants.SUBJECT_PUBLIC;
1413
    String[] groupnames = null;
1414
    if (session != null ) {
1415
    	username = session.getSubject().getValue();
1416
    	if (session.getSubjectInfo() != null) {
1417
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
1418
    		if (groupList != null) {
1419
    			groupnames = new String[groupList.size()];
1420
    			for (int i = 0; i < groupList.size(); i++ ) {
1421
    				groupnames[i] = groupList.get(i).getGroupName();
1422
    			}
1423
    		}
1424
    	}
1425
    }
1426
  
1427
    // generate pid/localId pair for object
1428
    logMetacat.debug("Generating a pid/localId mapping");
1429
    IdentifierManager im = IdentifierManager.getInstance();
1430
    String localId = im.generateLocalId(pid.getValue(), 1);
1431
  
1432
    // Save the data file to disk using "localId" as the name
1433
    String datafilepath = null;
1434
	try {
1435
		datafilepath = PropertyService.getProperty("application.datafilepath");
1436
	} catch (PropertyNotFoundException e) {
1437
		ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
1438
		sf.initCause(e);
1439
		throw sf;
1440
	}
1441
    boolean locked = false;
1442
	try {
1443
		locked = DocumentImpl.getDataFileLockGrant(localId);
1444
	} catch (Exception e) {
1445
		ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1446
		sf.initCause(e);
1447
		throw sf;
1448
	}
1449

    
1450
    logMetacat.debug("Case DATA: starting to write to disk.");
1451
	if (locked) {
1452

    
1453
          File dataDirectory = new File(datafilepath);
1454
          dataDirectory.mkdirs();
1455
  
1456
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1457
  
1458
          // TODO: Check that the file size matches SystemMetadata
1459
          // long size = newFile.length();
1460
          // if (size == 0) {
1461
          //     throw new IOException("Uploaded file is 0 bytes!");
1462
          // }
1463
  
1464
          // Register the file in the database (which generates an exception
1465
          // if the localId is not acceptable or other untoward things happen
1466
          try {
1467
            logMetacat.debug("Registering document...");
1468
            DocumentImpl.registerDocument(localId, "BIN", localId,
1469
                    username, groupnames);
1470
            logMetacat.debug("Registration step completed.");
1471
            
1472
          } catch (SQLException e) {
1473
            //newFile.delete();
1474
            logMetacat.debug("SQLE: " + e.getMessage());
1475
            e.printStackTrace(System.out);
1476
            throw new ServiceFailure("1190", "Registration failed: " + 
1477
            		e.getMessage());
1478
            
1479
          } catch (AccessionNumberException e) {
1480
            //newFile.delete();
1481
            logMetacat.debug("ANE: " + e.getMessage());
1482
            e.printStackTrace(System.out);
1483
            throw new ServiceFailure("1190", "Registration failed: " + 
1484
            	e.getMessage());
1485
            
1486
          } catch (Exception e) {
1487
            //newFile.delete();
1488
            logMetacat.debug("Exception: " + e.getMessage());
1489
            e.printStackTrace(System.out);
1490
            throw new ServiceFailure("1190", "Registration failed: " + 
1491
            	e.getMessage());
1492
          }
1493
  
1494
          logMetacat.debug("Logging the creation event.");
1495
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1496
  
1497
          // Schedule replication for this data file, the "insert" action is important here!
1498
          logMetacat.debug("Scheduling replication.");
1499
          ForceReplicationHandler frh = new ForceReplicationHandler(localId, "insert", false, null);
1500
      }
1501
      
1502
      return localId;
1503
    
1504
  }
1505

    
1506
  /**
1507
   * Insert a systemMetadata document and return its localId
1508
   */
1509
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1510
      throws ServiceFailure {
1511
      
1512
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1513
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1514
      logMetacat.debug("Inserting new system metadata with modified date " + 
1515
          sysmeta.getDateSysMetadataModified());
1516
      
1517
      //insert the system metadata
1518
      try {
1519
        // note: the calling subclass handles the map hazelcast lock/unlock
1520
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1521
      	// submit for indexing
1522
        MetacatSolrIndex.getInstance().submit(sysmeta.getIdentifier(), sysmeta, null, true);
1523
      } catch (Exception e) {
1524
          throw new ServiceFailure("1190", e.getMessage());
1525
          
1526
	    }  
1527
  }
1528
  
1529
  /**
1530
   * Retrieve the list of objects present on the MN that match the calling parameters
1531
   * 
1532
   * @param session - the Session object containing the credentials for the Subject
1533
   * @param startTime - Specifies the beginning of the time range from which 
1534
   *                    to return object (>=)
1535
   * @param endTime - Specifies the beginning of the time range from which 
1536
   *                  to return object (>=)
1537
   * @param objectFormat - Restrict results to the specified object format
1538
   * @param replicaStatus - Indicates if replicated objects should be returned in the list
1539
   * @param start - The zero-based index of the first value, relative to the 
1540
   *                first record of the resultset that matches the parameters.
1541
   * @param count - The maximum number of entries that should be returned in 
1542
   *                the response. The Member Node may return less entries 
1543
   *                than specified in this value.
1544
   * 
1545
   * @return objectList - the list of objects matching the criteria
1546
   * 
1547
   * @throws InvalidToken
1548
   * @throws ServiceFailure
1549
   * @throws NotAuthorized
1550
   * @throws InvalidRequest
1551
   * @throws NotImplemented
1552
   */
1553
  public ObjectList listObjects(Session session, Date startTime, Date endTime, ObjectFormatIdentifier objectFormatId, Identifier identifier, NodeReference nodeId, Integer start,
1554
          Integer count) throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken {
1555

    
1556
      ObjectList objectList = null;
1557

    
1558
      try {
1559
          // safeguard against large requests
1560
          if (count == null || count > MAXIMUM_DB_RECORD_COUNT) {
1561
              count = MAXIMUM_DB_RECORD_COUNT;
1562
          }
1563
          boolean isSid = false;
1564
          if(identifier != null) {
1565
              isSid = IdentifierManager.getInstance().systemMetadataSIDExists(identifier);
1566
          }
1567
          objectList = IdentifierManager.getInstance().querySystemMetadata(startTime, endTime, objectFormatId, nodeId, start, count, identifier, isSid);
1568
      } catch (Exception e) {
1569
          throw new ServiceFailure("1580", "Error querying system metadata: " + e.getMessage());
1570
      }
1571

    
1572
      return objectList;
1573
  }
1574

    
1575

    
1576
  /**
1577
   * Update a systemMetadata document
1578
   * 
1579
   * @param sysMeta - the system metadata object in the system to update
1580
   */
1581
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1582
        throws ServiceFailure {
1583
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1584
        try {
1585
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1586
            boolean needUpdateModificationDate = true;
1587
            updateSystemMetadataWithoutLock(sysMeta, needUpdateModificationDate);
1588
        } catch (Exception e) {
1589
            throw new ServiceFailure("4862", e.getMessage());
1590
        } finally {
1591
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1592

    
1593
        }
1594

    
1595
    }
1596
    
1597
    /**
1598
     * Update system metadata without locking the system metadata in hazelcast server. So the caller should lock it first. 
1599
     * @param sysMeta
1600
     * @param needUpdateModificationDate
1601
     * @throws ServiceFailure
1602
     */
1603
    private void updateSystemMetadataWithoutLock(SystemMetadata sysMeta, boolean needUpdateModificationDate) throws ServiceFailure {
1604
        logMetacat.debug("D1NodeService.updateSystemMetadataWithoutLock() called.");
1605
        if(needUpdateModificationDate) {
1606
            logMetacat.debug("D1NodeService.updateSystemMetadataWithoutLock() - update the modification date.");
1607
            sysMeta.setDateSysMetadataModified(new Date());
1608
        }
1609
        
1610
        // submit for indexing
1611
        try {
1612
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1613
            MetacatSolrIndex.getInstance().submit(sysMeta.getIdentifier(), sysMeta, null, true);
1614
        } catch (Exception e) {
1615
            throw new ServiceFailure("4862", e.getMessage());
1616
            //logMetacat.warn("D1NodeService.updateSystemMetadataWithoutLock - we can't submit the change of the system metadata to the solr index since "+e.getMessage());
1617
        }
1618
    }
1619
    
1620
    /**
1621
     * Update the system metadata of the specified pid. The caller of this method should lock the system metadata in hazelcast server.
1622
     * @param session - the identity of the client which calls the method
1623
     * @param pid - the identifier of the object which will be updated
1624
     * @param sysmeta - the new system metadata  
1625
     * @return
1626
     * @throws NotImplemented
1627
     * @throws NotAuthorized
1628
     * @throws ServiceFailure
1629
     * @throws InvalidRequest
1630
     * @throws InvalidSystemMetadata
1631
     * @throws InvalidToken
1632
     */
1633
	protected boolean updateSystemMetadata(Session session, Identifier pid,
1634
			SystemMetadata sysmeta, boolean needUpdateModificationDate, SystemMetadata currentSysmeta, boolean fromCN) throws NotImplemented, NotAuthorized,
1635
			ServiceFailure, InvalidRequest, InvalidSystemMetadata, InvalidToken {
1636
		
1637
	  // The lock to be used for this identifier
1638
      Lock lock = null;
1639
     
1640
      // verify that guid == SystemMetadata.getIdentifier()
1641
      logMetacat.debug("Comparing guid|sysmeta_guid: " + pid.getValue() + 
1642
          "|" + sysmeta.getIdentifier().getValue());
1643
      
1644
      if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
1645
          throw new InvalidRequest("4863", 
1646
              "The identifier in method call (" + pid.getValue() + 
1647
              ") does not match identifier in system metadata (" +
1648
              sysmeta.getIdentifier().getValue() + ").");
1649
      }
1650
      //compare serial version.
1651
      
1652
      //check the sid
1653
      //SystemMetadata currentSysmeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1654
      logMetacat.debug("The current dateUploaded is ============"+currentSysmeta.getDateUploaded());
1655
      logMetacat.debug("the dateUploaded in the new system metadata is "+sysmeta.getDateUploaded());
1656
      logMetacat.debug("The current dateUploaded is (by time) ============"+currentSysmeta.getDateUploaded().getTime());
1657
      logMetacat.debug("the dateUploaded in the new system metadata is (by time) "+sysmeta.getDateUploaded().getTime());
1658
      if(currentSysmeta == null ) {
1659
          //do we need throw an exception?
1660
          logMetacat.warn("D1NodeService.updateSystemMetadata: Currently there is no system metadata in this node associated with the pid "+pid.getValue());
1661
      } else {
1662
          
1663
          /*BigInteger newVersion = sysmeta.getSerialVersion();
1664
          if(newVersion == null) {
1665
              throw new InvalidRequest("4869", "The serial version can't be null in the new system metadata");
1666
          }
1667
          BigInteger currentVersion = currentSysmeta.getSerialVersion();
1668
          if(currentVersion != null && newVersion.compareTo(currentVersion) <= 0) {
1669
              throw new InvalidRequest("4869", "The serial version in the new system metadata is "+newVersion.toString()+
1670
                      " which is less than or equals the previous version "+currentVersion.toString()+". This is illegal in the updateSystemMetadata method.");
1671
          }*/
1672
          Identifier currentSid = currentSysmeta.getSeriesId();
1673
          if(currentSid != null) {
1674
              logMetacat.debug("In the branch that the sid is not null in the current system metadata and the current sid is "+currentSid.getValue());
1675
              //new sid must match the current sid
1676
              Identifier newSid = sysmeta.getSeriesId();
1677
              if (!isValidIdentifier(newSid)) {
1678
                  throw new InvalidRequest("4869", "The series id in the system metadata is invalid in the request.");
1679
              } else {
1680
                  if(!newSid.getValue().equals(currentSid.getValue())) {
1681
                      throw new InvalidRequest("4869", "The series id "+newSid.getValue() +" in the system metadata doesn't match the current sid "+currentSid.getValue());
1682
                  }
1683
              }
1684
          } else {
1685
              //current system metadata doesn't have a sid. So we can have those scenarios
1686
              //1. The new sid may be null as well
1687
              //2. If the new sid does exist, it may be an identifier which hasn't bee used.
1688
              //3. If the new sid does exist, it may be an sid which equals the SID it obsoletes
1689
              //4. If the new sid does exist, it may be an sid which equauls the SID it was obsoleted by
1690
              Identifier newSid = sysmeta.getSeriesId();
1691
              if(newSid != null) {
1692
                  //It matches the rules of the checkSidInModifyingSystemMetadata
1693
                  checkSidInModifyingSystemMetadata(sysmeta, "4956", "4868");
1694
              }
1695
          }
1696
          checkModifiedImmutableFields(currentSysmeta, sysmeta);
1697
          checkOneTimeSettableSysmMetaFields(currentSysmeta, sysmeta);
1698
          if(currentSysmeta.getObsoletes() == null && sysmeta.getObsoletes() != null) {
1699
              //we are setting a value to the obsoletes field, so we should make sure if there is not object obsoletes the value
1700
              String obsoletes = existsInObsoletes(sysmeta.getObsoletes());
1701
              if( obsoletes != null) {
1702
                  throw new InvalidSystemMetadata("4956", "There is an object with id "+obsoletes +
1703
                          " already obsoletes the pid "+sysmeta.getObsoletes().getValue() +". You can't set the object "+pid.getValue()+" to obsolete the pid "+sysmeta.getObsoletes().getValue()+" again.");
1704
              }
1705
          }
1706
          
1707
          if(currentSysmeta.getObsoletedBy() == null && sysmeta.getObsoletedBy() != null) {
1708
              //we are setting a value to the obsoletedBy field, so we should make sure that the no another object obsoletes the pid we are updating. 
1709
              String obsoletedBy = existsInObsoletedBy(sysmeta.getObsoletedBy());
1710
              if( obsoletedBy != null) {
1711
                  throw new InvalidSystemMetadata("4956", "There is an object with id "+obsoletedBy +
1712
                          " already is obsoleted by the pid "+sysmeta.getObsoletedBy().getValue() +". You can't set the pid "+pid.getValue()+" to be obsoleted by the pid "+sysmeta.getObsoletedBy().getValue()+" again.");
1713
              }
1714
          }
1715
      }
1716
      
1717
      // do the actual update
1718
      if(sysmeta.getArchived() != null && sysmeta.getArchived() == true && 
1719
                 ((currentSysmeta.getArchived() != null && currentSysmeta.getArchived() == false ) || currentSysmeta.getArchived() == null)) {
1720
          boolean logArchive = false;//we log it as the update system metadata event. So don't log it again.
1721
          if(fromCN) {
1722
              logMetacat.debug("D1Node.update - this is to archive a cn object "+pid.getValue());
1723
              try {
1724
                  archiveCNObject(logArchive, session, pid, sysmeta, needUpdateModificationDate);
1725
              } catch (NotFound e) {
1726
                  throw new InvalidRequest("4869", "Can't find the pid "+pid.getValue()+" for archive.");
1727
              }
1728
          } else {
1729
              logMetacat.debug("D1Node.update - this is to archive a MN object "+pid.getValue());
1730
              try {
1731
                  archiveObject(logArchive, session, pid, sysmeta, needUpdateModificationDate);
1732
              } catch (NotFound e) {
1733
                  throw new InvalidRequest("4869", "Can't find the pid "+pid.getValue()+" for archive.");
1734
              }
1735
          }
1736
      } else {
1737
          logMetacat.debug("D1Node.update - regularly update the system metadata of the pid "+pid.getValue());
1738
          updateSystemMetadataWithoutLock(sysmeta, needUpdateModificationDate);
1739
      }
1740

    
1741
      try {
1742
    	  String localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1743
    	  EventLog.getInstance().log(request.getRemoteAddr(), 
1744
    	          request.getHeader("User-Agent"), session.getSubject().getValue(), 
1745
    	          localId, "updateSystemMetadata");
1746
      } catch (McdbDocNotFoundException e) {
1747
    	  // do nothing, no localId to log with
1748
    	  logMetacat.warn("Could not log 'updateSystemMetadata' event because no localId was found for pid: " + pid.getValue());
1749
      } catch (SQLException e) {
1750
          logMetacat.warn("Could not log 'updateSystemMetadata' event because the localId couldn't be identified for the pid: " + pid.getValue());
1751
      }
1752
      return true;
1753
	}
1754
	
1755
	
1756
	/*
1757
	 * Check if the newMeta modifies an immutable field. 
1758
	 */
1759
	private void checkModifiedImmutableFields(SystemMetadata orgMeta, SystemMetadata newMeta) throws InvalidRequest{
1760
	    logMetacat.debug("in the start of the checkModifiedImmutableFields method");
1761
	    if(orgMeta != null && newMeta != null) {
1762
	        logMetacat.debug("in the checkModifiedImmutableFields method when the org and new system metadata is not null");
1763
	        if(newMeta.getIdentifier() == null) {
1764
	            throw new InvalidRequest("4869", "The new version of the system metadata is invalid since the identifier is null");
1765
	        }
1766
	        if(!orgMeta.getIdentifier().equals(newMeta.getIdentifier())) {
1767
	            throw new InvalidRequest("4869","The request is trying to modify an immutable field in the SystemMeta: the new system meta's identifier "+newMeta.getIdentifier().getValue()+" is "+
1768
	                  "different to the orginal one "+orgMeta.getIdentifier().getValue());
1769
	        }
1770
	        if(newMeta.getSize() == null) {
1771
	            throw new InvalidRequest("4869", "The new version of the system metadata is invalid since the size is null");
1772
	        }
1773
	        if(!orgMeta.getSize().equals(newMeta.getSize())) {
1774
	            throw new InvalidRequest("4869", "The request is trying to modify an immutable field in the SystemMeta: the new system meta's size "+newMeta.getSize().longValue()+" is "+
1775
	                      "different to the orginal one "+orgMeta.getSize().longValue());
1776
	        }
1777
	        if(newMeta.getChecksum()!= null && orgMeta.getChecksum() != null && !orgMeta.getChecksum().getValue().equals(newMeta.getChecksum().getValue())) {
1778
	            logMetacat.error("The request is trying to modify an immutable field in the SystemMeta: the new system meta's checksum "+newMeta.getChecksum().getValue()+" is "+
1779
                        "different to the orginal one "+orgMeta.getChecksum().getValue());
1780
	            throw new InvalidRequest("4869", "The request is trying to modify an immutable field in the SystemMeta: the new system meta's checksum "+newMeta.getChecksum().getValue()+" is "+
1781
                        "different to the orginal one "+orgMeta.getChecksum().getValue());
1782
	        }
1783
	        if(orgMeta.getSubmitter() != null) {
1784
	            logMetacat.debug("in the checkModifiedImmutableFields method and orgMeta.getSubmitter is not null and the orginal submiter is "+orgMeta.getSubmitter().getValue());
1785
	        }
1786
	        
1787
	        if(newMeta.getSubmitter() != null) {
1788
                logMetacat.debug("in the checkModifiedImmutableFields method and newMeta.getSubmitter is not null and the submiter in the new system metadata is "+newMeta.getSubmitter().getValue());
1789
            }
1790
	        if(orgMeta.getSubmitter() != null && newMeta.getSubmitter() != null && !orgMeta.getSubmitter().equals(newMeta.getSubmitter())) {
1791
	            throw new InvalidRequest("4869", "The request is trying to modify an immutable field in the SystemMeta: the new system meta's submitter "+newMeta.getSubmitter().getValue()+" is "+
1792
                        "different to the orginal one "+orgMeta.getSubmitter().getValue());
1793
	        }
1794
	        
1795
	        if(orgMeta.getDateUploaded() != null && newMeta.getDateUploaded() != null && orgMeta.getDateUploaded().getTime() != newMeta.getDateUploaded().getTime()) {
1796
	            throw new InvalidRequest("4869", "The request is trying to modify an immutable field in the SystemMeta: the new system meta's date of uploaded "+newMeta.getDateUploaded()+" is "+
1797
                        "different to the orginal one "+orgMeta.getDateUploaded());
1798
	        }
1799
	        
1800
	        if(orgMeta.getOriginMemberNode() != null && newMeta.getOriginMemberNode() != null && !orgMeta.getOriginMemberNode().equals(newMeta.getOriginMemberNode())) {
1801
	            throw new InvalidRequest("4869", "The request is trying to modify an immutable field in the SystemMeta: the new system meta's orginal member node  "+newMeta.getOriginMemberNode().getValue()+" is "+
1802
                        "different to the orginal one "+orgMeta.getOriginMemberNode().getValue());
1803
	        }
1804
	        
1805
	        if (orgMeta.getOriginMemberNode() != null && newMeta.getOriginMemberNode() == null ) {
1806
	            throw new InvalidRequest("4869", "The request is trying to modify an immutable field in the SystemMeta: the new system meta's orginal member node is null and it "+" is "+
1807
                        "different to the orginal one "+orgMeta.getOriginMemberNode().getValue());
1808
	        }
1809
	        
1810
	        if(orgMeta.getSeriesId() != null && newMeta.getSeriesId() != null && !orgMeta.getSeriesId().equals(newMeta.getSeriesId())) {
1811
                throw new InvalidRequest("4869", "The request is trying to modify an immutable field in the SystemMeta: the new system meta's series id  "+newMeta.getSeriesId().getValue()+" is "+
1812
                        "different to the orginal one "+orgMeta.getSeriesId().getValue());
1813
            }
1814
	        
1815
	    }
1816
	}
1817
	
1818
	/*
1819
	 * Some fields in the system metadata, such as obsoletes or obsoletedBy can be set only once. 
1820
	 * After set, they are not allowed to be changed.
1821
	 */
1822
	private void checkOneTimeSettableSysmMetaFields(SystemMetadata orgMeta, SystemMetadata newMeta) throws InvalidRequest {
1823
	    if(orgMeta.getObsoletedBy() != null ) {
1824
	        if(newMeta.getObsoletedBy() == null || !orgMeta.getObsoletedBy().equals(newMeta.getObsoletedBy())) {
1825
	            throw new InvalidRequest("4869", "The request is trying to reset the obsoletedBy field in the system metadata of the object "
1826
	                    + orgMeta.getIdentifier().getValue() +". This is illegal since the obsoletedBy filed is set, you can't change it again.");
1827
	        }
1828
        }
1829
	    if(orgMeta.getObsoletes() != null) {
1830
	        if(newMeta.getObsoletes() == null || !orgMeta.getObsoletes().equals(newMeta.getObsoletes())) {
1831
	            throw new InvalidRequest("4869", "The request is trying to reset the obsoletes field in the system metadata of the object"+
1832
	               orgMeta.getIdentifier().getValue()+". This is illegal since the obsoletes filed is set, you can't change it again.");
1833
	        }
1834
	    }
1835
	}
1836
  
1837
  /**
1838
   * Given a Permission, returns a list of all permissions that it encompasses
1839
   * Permissions are hierarchical so that WRITE also allows READ.
1840
   * @param permission
1841
   * @return list of included Permissions for the given permission
1842
   */
1843
  protected static List<Permission> expandPermissions(Permission permission) {
1844
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1845
	    if (permission.equals(Permission.READ)) {
1846
	    	expandedPermissions.add(Permission.READ);
1847
	    }
1848
	    if (permission.equals(Permission.WRITE)) {
1849
	    	expandedPermissions.add(Permission.READ);
1850
	    	expandedPermissions.add(Permission.WRITE);
1851
	    }
1852
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1853
	    	expandedPermissions.add(Permission.READ);
1854
	    	expandedPermissions.add(Permission.WRITE);
1855
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1856
	    }
1857
	    return expandedPermissions;
1858
  }
1859

    
1860
  /*
1861
   * Write a stream to a file
1862
   * 
1863
   * @param dir - the directory to write to
1864
   * @param fileName - the file name to write to
1865
   * @param data - the object bytes as an input stream
1866
   * 
1867
   * @return newFile - the new file created
1868
   * 
1869
   * @throws ServiceFailure
1870
   */
1871
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1872
    throws ServiceFailure {
1873
    
1874
    File newFile = new File(dir, fileName);
1875
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1876

    
1877
    try {
1878
        if (newFile.createNewFile()) {
1879
          // write data stream to desired file
1880
          OutputStream os = new FileOutputStream(newFile);
1881
          long length = IOUtils.copyLarge(data, os);
1882
          os.flush();
1883
          os.close();
1884
        } else {
1885
          logMetacat.debug("File creation failed, or file already exists.");
1886
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1887
        }
1888
    } catch (FileNotFoundException e) {
1889
      logMetacat.debug("FNF: " + e.getMessage());
1890
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1891
                + e.getMessage());
1892
    } catch (IOException e) {
1893
      logMetacat.debug("IOE: " + e.getMessage());
1894
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1895
                + " " + e.getMessage());
1896
    }
1897

    
1898
    return newFile;
1899
  }
1900

    
1901
  /*
1902
   * Returns a list of nodes that have been registered with the DataONE infrastructure
1903
   * that match the given session subject
1904
   * @return nodes - List of nodes from the registry with a matching session subject
1905
   * 
1906
   * @throws ServiceFailure
1907
   * @throws NotImplemented
1908
   */
1909
  protected List<Node> listNodesBySubject(Subject subject) 
1910
      throws ServiceFailure, NotImplemented {
1911
      List<Node> nodeList = new ArrayList<Node>();
1912
      
1913
      CNode cn = D1Client.getCN();
1914
      List<Node> nodes = cn.listNodes().getNodeList();
1915
      
1916
      // find the node in the node list
1917
      for ( Node node : nodes ) {
1918
          
1919
          List<Subject> nodeSubjects = node.getSubjectList();
1920
          if (nodeSubjects != null) {    
1921
	          // check if the session subject is in the node subject list
1922
	          for (Subject nodeSubject : nodeSubjects) {
1923
	              if ( nodeSubject.equals(subject) ) { // subject of session == node subject
1924
	                  nodeList.add(node);  
1925
	              }                              
1926
	          }
1927
          }
1928
      }
1929
      
1930
      return nodeList;
1931
      
1932
  }
1933

    
1934
  /**
1935
   * Archives an object, where the object is either a 
1936
   * data object or a science metadata object.
1937
   * Note: it doesn't check the authorization; it doesn't lock the system metadata;it only accept pid.
1938
   * @param session - the Session object containing the credentials for the Subject
1939
   * @param pid - The object identifier to be archived
1940
   * 
1941
   * @return pid - the identifier of the object used for the archiving
1942
   * 
1943
   * @throws InvalidToken
1944
   * @throws ServiceFailure
1945
   * @throws NotAuthorized
1946
   * @throws NotFound
1947
   * @throws NotImplemented
1948
   * @throws InvalidRequest
1949
   */
1950
  protected Identifier archiveObject(boolean log, Session session, Identifier pid, SystemMetadata sysMeta, boolean needModifyDate) 
1951
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1952

    
1953
      String localId = null;
1954
      boolean allowed = false;
1955
      String username = Constants.SUBJECT_PUBLIC;
1956
      if (session == null) {
1957
      	throw new InvalidToken("1330", "No session has been provided");
1958
      } else {
1959
          username = session.getSubject().getValue();
1960
      }
1961
      // do we have a valid pid?
1962
      if (pid == null || pid.getValue().trim().equals("")) {
1963
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
1964
      }
1965
      
1966
      if(sysMeta == null) {
1967
          throw new NotFound("2911", "There is no system metadata associated with "+pid.getValue());
1968
      }
1969
      
1970
      // check for the existing identifier
1971
      try {
1972
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1973
      } catch (McdbDocNotFoundException e) {
1974
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
1975
      } catch (SQLException e) {
1976
          throw new ServiceFailure("1350", "The object with the provided identifier "+pid.getValue()+" couldn't be identified since "+e.getMessage());
1977
      }
1978

    
1979

    
1980
          try {
1981
              // archive the document
1982
              DocumentImpl.delete(localId, null, null, null, false);
1983
              if(log) {
1984
                   try {
1985
                      EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
1986
                   } catch (Exception e) {
1987
                      logMetacat.warn("D1NodeService.archiveObject - can't log the delete event since "+e.getMessage());
1988
                   }
1989
              }
1990
             
1991
              
1992
              // archive it
1993
              sysMeta.setArchived(true);
1994
              if(needModifyDate) {
1995
                  sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1996
                  sysMeta.setSerialVersion(sysMeta.getSerialVersion().add(BigInteger.ONE));
1997
              }
1998
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
1999
              
2000
              // submit for indexing
2001
              // DocumentImpl call above should do this.
2002
              // see: https://projects.ecoinformatics.org/ecoinfo/issues/6030
2003
              //HazelcastService.getInstance().getIndexQueue().add(sysMeta);
2004
              
2005
          } catch (McdbDocNotFoundException e) {
2006
              throw new NotFound("1340", "The provided identifier was invalid.");
2007

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

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

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

    
2018

    
2019
      return pid;
2020
  }
2021
  
2022
  /**
2023
   * Archive a object on cn and notify the replica. This method doesn't lock the system metadata map. The caller should lock it.
2024
   * This method doesn't check the authorization; this method only accept a pid.
2025
   * It wouldn't notify the replca that the system metadata has been changed.
2026
   * @param session
2027
   * @param pid
2028
   * @param sysMeta
2029
   * @param notifyReplica
2030
   * @return
2031
   * @throws InvalidToken
2032
   * @throws ServiceFailure
2033
   * @throws NotAuthorized
2034
   * @throws NotFound
2035
   * @throws NotImplemented
2036
   */
2037
  protected void archiveCNObject(boolean log, Session session, Identifier pid, SystemMetadata sysMeta, boolean needModifyDate) 
2038
          throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
2039

    
2040
          String localId = null; // The corresponding docid for this pid
2041
          
2042
          // Check for the existing identifier
2043
          try {
2044
              localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
2045
              archiveObject(log, session, pid, sysMeta, needModifyDate);
2046
          
2047
          } catch (McdbDocNotFoundException e) {
2048
              // This object is not registered in the identifier table. Assume it is of formatType DATA,
2049
              // and set the archive flag. (i.e. the *object* doesn't exist on the CN)
2050
              
2051
              try {
2052
                  if ( sysMeta != null ) {
2053
                    sysMeta.setArchived(true);
2054
                    if (needModifyDate) {
2055
                        sysMeta.setSerialVersion(sysMeta.getSerialVersion().add(BigInteger.ONE));
2056
                        sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
2057
                    }
2058
                    HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
2059
                      
2060
                  } else {
2061
                      throw new ServiceFailure("4972", "Couldn't archive the object " + pid.getValue() +
2062
                          ". Couldn't obtain the system metadata record.");
2063
                      
2064
                  }
2065
                  
2066
              } catch (RuntimeException re) {
2067
                  throw new ServiceFailure("4972", "Couldn't archive " + pid.getValue() + 
2068
                      ". The error message was: " + re.getMessage());
2069
                  
2070
              } 
2071

    
2072
          } catch (SQLException e) {
2073
              throw new ServiceFailure("4972", "Couldn't archive the object " + pid.getValue() +
2074
                      ". The local id of the object with the identifier can't be identified since "+e.getMessage());
2075
          }
2076
          
2077
    }
2078
  
2079
  
2080
  /**
2081
   * A utility method for v1 api to check the specified identifier exists as a pid
2082
   * @param identifier  the specified identifier
2083
   * @param serviceFailureCode  the detail error code for the service failure exception
2084
   * @param noFoundCode  the detail error code for the not found exception
2085
   * @throws ServiceFailure
2086
   * @throws NotFound
2087
   */
2088
  public void checkV1SystemMetaPidExist(Identifier identifier, String serviceFailureCode, String serviceFailureMessage,  
2089
          String noFoundCode, String notFoundMessage) throws ServiceFailure, NotFound {
2090
      boolean exists = false;
2091
      try {
2092
          exists = IdentifierManager.getInstance().systemMetadataPIDExists(identifier);
2093
      } catch (SQLException e) {
2094
          throw new ServiceFailure(serviceFailureCode, serviceFailureMessage+" since "+e.getMessage());
2095
      }
2096
      if(!exists) {
2097
         //the v1 method only handles a pid. so it should throw a not-found exception.
2098
          // check if the pid was deleted.
2099
          try {
2100
              String localId = IdentifierManager.getInstance().getLocalId(identifier.getValue());
2101
              if(EventLog.getInstance().isDeleted(localId)) {
2102
                  notFoundMessage=notFoundMessage+" "+DELETEDMESSAGE;
2103
              } 
2104
            } catch (Exception e) {
2105
              logMetacat.info("Couldn't determine if the not-found identifier "+identifier.getValue()+" was deleted since "+e.getMessage());
2106
            }
2107
            throw new NotFound(noFoundCode, notFoundMessage);
2108
      }
2109
  }
2110
  
2111
  /**
2112
   * Utility method to get the PID for an SID. If the specified identifier is not an SID
2113
   * , null will be returned.
2114
   * @param sid  the specified sid
2115
   * @param serviceFailureCode  the detail error code for the service failure exception
2116
   * @return the pid for the sid. If the specified identifier is not an SID, null will be returned.
2117
   * @throws ServiceFailure
2118
   */
2119
  protected Identifier getPIDForSID(Identifier sid, String serviceFailureCode) throws ServiceFailure {
2120
      Identifier id = null;
2121
      String serviceFailureMessage = "The PID "+" couldn't be identified for the sid " + sid.getValue();
2122
      try {
2123
          //determine if the given pid is a sid or not.
2124
          if(IdentifierManager.getInstance().systemMetadataSIDExists(sid)) {
2125
              try {
2126
                  //set the header pid for the sid if the identifier is a sid.
2127
                  id = IdentifierManager.getInstance().getHeadPID(sid);
2128
              } catch (SQLException sqle) {
2129
                  throw new ServiceFailure(serviceFailureCode, serviceFailureMessage+" since "+sqle.getMessage());
2130
              }
2131
              
2132
          }
2133
      } catch (SQLException e) {
2134
          throw new ServiceFailure(serviceFailureCode, serviceFailureMessage + " since "+e.getMessage());
2135
      }
2136
      return id;
2137
  }
2138

    
2139
  /*
2140
   * Determine if the sid is legitimate in CN.create and CN.registerSystemMetadata methods. It also is used as a part of rules of the updateSystemMetadata method. Here are the rules:
2141
   * A. If the sysmeta doesn't have an SID, nothing needs to be checked for the SID.
2142
   * B. If the sysmeta does have an SID, it may be an identifier which doesn't exist in the system.
2143
   * C. If the sysmeta does have an SID and it exists as an SID in the system, those scenarios are acceptable:
2144
   *    i. The sysmeta has an obsoletes field, the SID has the same value as the SID of the system metadata of the obsoleting pid.
2145
   *    ii. The sysmeta has an obsoletedBy field, the SID has the same value as the SID of the system metadata of the obsoletedBy pid. 
2146
   */
2147
  protected boolean checkSidInModifyingSystemMetadata(SystemMetadata sysmeta, String invalidSystemMetadataCode, String serviceFailureCode) throws InvalidSystemMetadata, ServiceFailure{
2148
      boolean pass = false;
2149
      if(sysmeta == null) {
2150
          throw new InvalidSystemMetadata(invalidSystemMetadataCode, "The system metadata is null in the request.");
2151
      }
2152
      Identifier sid = sysmeta.getSeriesId();
2153
      if(sid != null) {
2154
          // the series id exists
2155
          if (!isValidIdentifier(sid)) {
2156
              throw new InvalidSystemMetadata(invalidSystemMetadataCode, "The series id in the system metadata is invalid in the request.");
2157
          }
2158
          Identifier pid = sysmeta.getIdentifier();
2159
          if (!isValidIdentifier(pid)) {
2160
              throw new InvalidSystemMetadata(invalidSystemMetadataCode, "The pid in the system metadata is invalid in the request.");
2161
          }
2162
          //the series id equals the pid (new pid hasn't been registered in the system, so IdentifierManager.getInstance().identifierExists method can't exclude this scenario )
2163
          if(sid.getValue().equals(pid.getValue())) {
2164
              throw new InvalidSystemMetadata(invalidSystemMetadataCode, "The series id "+sid.getValue()+" in the system metadata shouldn't have the same value of the pid.");
2165
          }
2166
          try {
2167
              if (IdentifierManager.getInstance().identifierExists(sid.getValue())) {
2168
                  //the sid exists in system
2169
                  if(sysmeta.getObsoletes() != null) {
2170
                      SystemMetadata obsoletesSysmeta = HazelcastService.getInstance().getSystemMetadataMap().get(sysmeta.getObsoletes());
2171
                      if(obsoletesSysmeta != null) {
2172
                          Identifier obsoletesSid = obsoletesSysmeta.getSeriesId();
2173
                          if(obsoletesSid != null && obsoletesSid.getValue() != null && !obsoletesSid.getValue().trim().equals("")) {
2174
                              if(sid.getValue().equals(obsoletesSid.getValue())) {
2175
                                  pass = true;// the i of rule C
2176
                              }
2177
                          }
2178
                      } else {
2179
                           logMetacat.warn("D1NodeService.checkSidInModifyingSystemMetacat - Can't find the system metadata for the pid "+sysmeta.getObsoletes().getValue()+
2180
                                                                         " which is the value of the obsoletes. So we can't check if the sid " +sid.getValue()+" is legitimate ");
2181
                      }
2182
                  }
2183
                  if(!pass) {
2184
                      // the sid doesn't match the sid of the obsoleting identifier. So we check the obsoletedBy
2185
                      if(sysmeta.getObsoletedBy() != null) {
2186
                          SystemMetadata obsoletedBySysmeta = HazelcastService.getInstance().getSystemMetadataMap().get(sysmeta.getObsoletedBy());
2187
                          if(obsoletedBySysmeta != null) {
2188
                              Identifier obsoletedBySid = obsoletedBySysmeta.getSeriesId();
2189
                              if(obsoletedBySid != null && obsoletedBySid.getValue() != null && !obsoletedBySid.getValue().trim().equals("")) {
2190
                                  if(sid.getValue().equals(obsoletedBySid.getValue())) {
2191
                                      pass = true;// the ii of the rule C
2192
                                  }
2193
                              }
2194
                          } else {
2195
                              logMetacat.warn("D1NodeService.checkSidInModifyingSystemMetacat - Can't find the system metadata for the pid "+sysmeta.getObsoletes().getValue() 
2196
                                                                            +" which is the value of the obsoletedBy. So we can't check if the sid "+sid.getValue()+" is legitimate.");
2197
                          }
2198
                      }
2199
                  }
2200
                  if(!pass) {
2201
                      throw new InvalidSystemMetadata(invalidSystemMetadataCode, "The series id "+sid.getValue()+
2202
                              " in the system metadata exists in the system. And it doesn't match either previous object's sid or the next object's sid.");
2203
                  }
2204
              } else {
2205
                  pass = true; //Rule B
2206
              }
2207
          } catch (SQLException e) {
2208
              throw new ServiceFailure(serviceFailureCode, "Can't determine if the sid in the system metadata is unique or not since "+e.getMessage());
2209
          }
2210
          
2211
      } else {
2212
          //no sid. Rule A.
2213
          pass = true;
2214
      }
2215
      return pass;
2216
      
2217
  }
2218
  
2219
  //@Override
2220
  public OptionList listViews(Session arg0) throws InvalidToken,
2221
          ServiceFailure, NotAuthorized, InvalidRequest, NotImplemented {
2222
      OptionList views = new OptionList();
2223
      views.setKey("views");
2224
      views.setDescription("List of views for objects on the node");
2225
      Vector<String> skinNames = null;
2226
      try {
2227
          skinNames = SkinUtil.getSkinNames();
2228
      } catch (PropertyNotFoundException e) {
2229
          throw new ServiceFailure("2841", e.getMessage());
2230
      }
2231
      for (String skinName: skinNames) {
2232
          views.addOption(skinName);
2233
      }
2234
      return views;
2235
  }
2236
  
2237
  public OptionList listViews() throws InvalidToken,
2238
  ServiceFailure, NotAuthorized, InvalidRequest, NotImplemented { 
2239
      return listViews(null);
2240
  }
2241

    
2242
  //@Override
2243
  public InputStream view(Session session, String format, Identifier pid)
2244
          throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest,
2245
          NotImplemented, NotFound {
2246
      InputStream resultInputStream = null;
2247
      
2248
      String serviceFailureCode = "2831";
2249
      Identifier sid = getPIDForSID(pid, serviceFailureCode);
2250
      if(sid != null) {
2251
          pid = sid;
2252
      }
2253
      
2254
      SystemMetadata sysMeta = this.getSystemMetadata(session, pid);
2255
      InputStream object = this.get(session, pid);
2256

    
2257
      try {
2258
          // can only transform metadata, really
2259
          ObjectFormat objectFormat = ObjectFormatCache.getInstance().getFormat(sysMeta.getFormatId());
2260
          if (objectFormat.getFormatType().equals("METADATA")) {
2261
              // transform
2262
              DBTransform transformer = new DBTransform();
2263
              String documentContent = IOUtils.toString(object, "UTF-8");
2264
              String sourceType = objectFormat.getFormatId().getValue();
2265
              String targetType = "-//W3C//HTML//EN";
2266
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
2267
              Writer writer = new OutputStreamWriter(baos , "UTF-8");
2268
              // TODO: include more params?
2269
              Hashtable<String, String[]> params = new Hashtable<String, String[]>();
2270
              String localId = null;
2271
              try {
2272
                  localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
2273
              } catch (McdbDocNotFoundException e) {
2274
                  throw new NotFound("1020", e.getMessage());
2275
              }
2276
              params.put("qformat", new String[] {format});               
2277
              params.put("docid", new String[] {localId});
2278
              params.put("pid", new String[] {pid.getValue()});
2279
              transformer.transformXMLDocument(
2280
                      documentContent , 
2281
                      sourceType, 
2282
                      targetType , 
2283
                      format, 
2284
                      writer, 
2285
                      params, 
2286
                      null //sessionid
2287
                      );
2288
              
2289
              // finally, get the HTML back
2290
              resultInputStream = new ContentTypeByteArrayInputStream(baos.toByteArray());
2291
              ((ContentTypeByteArrayInputStream) resultInputStream).setContentType("text/html");
2292
  
2293
          } else {
2294
              // just return the raw bytes
2295
              resultInputStream = object;
2296
          }
2297
      } catch (IOException e) {
2298
          // report as service failure
2299
          ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2300
          sf.initCause(e);
2301
          throw sf;
2302
      } catch (PropertyNotFoundException e) {
2303
          // report as service failure
2304
          ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2305
          sf.initCause(e);
2306
          throw sf;
2307
      } catch (SQLException e) {
2308
          // report as service failure
2309
          ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2310
          sf.initCause(e);
2311
          throw sf;
2312
      } catch (ClassNotFoundException e) {
2313
          // report as service failure
2314
          ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2315
          sf.initCause(e);
2316
          throw sf;
2317
      }
2318
      
2319
      return resultInputStream;
2320
  } 
2321
  
2322
  /*
2323
   * Determine if the given identifier exists in the obsoletes field in the system metadata table.
2324
   * If the return value is not null, the given identifier exists in the given cloumn. The return value is 
2325
   * the guid of the first row.
2326
   */
2327
  protected String existsInObsoletes(Identifier id) throws InvalidRequest, ServiceFailure{
2328
      String guid = existsInFields("obsoletes", id);
2329
      return guid;
2330
  }
2331
  
2332
  /*
2333
   * Determine if the given identifier exists in the obsoletes field in the system metadata table.
2334
   * If the return value is not null, the given identifier exists in the given cloumn. The return value is 
2335
   * the guid of the first row.
2336
   */
2337
  protected String existsInObsoletedBy(Identifier id) throws InvalidRequest, ServiceFailure{
2338
      String guid = existsInFields("obsoleted_by", id);
2339
      return guid;
2340
  }
2341

    
2342
  /*
2343
   * Determine if the given identifier exists in the given column in the system metadata table. 
2344
   * If the return value is not null, the given identifier exists in the given cloumn. The return value is 
2345
   * the guid of the first row.
2346
   */
2347
  private String existsInFields(String column, Identifier id) throws InvalidRequest, ServiceFailure {
2348
      String guid = null;
2349
      if(id == null ) {
2350
          throw new InvalidRequest("4863", "The given identifier is null and we can't determine if the guid exists in the field "+column+" in the systemmetadata table");
2351
      }
2352
      String sql = "SELECT guid FROM systemmetadata WHERE "+column+" = ?";
2353
      int serialNumber = -1;
2354
      DBConnection dbConn = null;
2355
      PreparedStatement stmt = null;
2356
      ResultSet result = null;
2357
      try {
2358
          dbConn = 
2359
                  DBConnectionPool.getDBConnection("D1NodeService.existsInFields");
2360
          serialNumber = dbConn.getCheckOutSerialNumber();
2361
          stmt = dbConn.prepareStatement(sql);
2362
          stmt.setString(1, id.getValue());
2363
          result = stmt.executeQuery();
2364
          if(result.next()) {
2365
              guid = result.getString(1);
2366
          }
2367
          stmt.close();
2368
      } catch (SQLException e) {
2369
          e.printStackTrace();
2370
          throw new ServiceFailure("4862","We can't determine if the id "+id.getValue()+" exists in field "+column+" in the systemmetadata table since "+e.getMessage());
2371
      } finally {
2372
          // Return database connection to the pool
2373
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2374
          if(stmt != null) {
2375
              try {
2376
                  stmt.close();
2377
              } catch (SQLException e) {
2378
                  logMetacat.warn("We can close the PreparedStatment in D1NodeService.existsInFields since "+e.getMessage());
2379
              }
2380
          }
2381
          
2382
      }
2383
      return guid;
2384
      
2385
  }
2386
}
(2-2/8)