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:  $'
7
 *     '$Date:  $'
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.IOException;
27
import java.io.InputStream;
28
import java.io.PipedInputStream;
29
import java.io.PipedOutputStream;
30
import java.lang.reflect.InvocationTargetException;
31
import java.math.BigInteger;
32
import java.sql.SQLException;
33
import java.util.ArrayList;
34
import java.util.Calendar;
35
import java.util.Date;
36
import java.util.List;
37
import java.util.concurrent.locks.Lock;
38

    
39
import javax.servlet.http.HttpServletRequest;
40

    
41
import org.apache.commons.beanutils.BeanUtils;
42
import org.apache.log4j.Logger;
43
import org.dataone.client.v2.CNode;
44
import org.dataone.client.v2.MNode;
45
import org.dataone.client.v2.itk.D1Client;
46
import org.dataone.service.cn.v2.CNAuthorization;
47
import org.dataone.service.cn.v2.CNCore;
48
import org.dataone.service.cn.v2.CNRead;
49
import org.dataone.service.cn.v2.CNReplication;
50
import org.dataone.service.cn.v2.CNView;
51
import org.dataone.service.exceptions.BaseException;
52
import org.dataone.service.exceptions.IdentifierNotUnique;
53
import org.dataone.service.exceptions.InsufficientResources;
54
import org.dataone.service.exceptions.InvalidRequest;
55
import org.dataone.service.exceptions.InvalidSystemMetadata;
56
import org.dataone.service.exceptions.InvalidToken;
57
import org.dataone.service.exceptions.NotAuthorized;
58
import org.dataone.service.exceptions.NotFound;
59
import org.dataone.service.exceptions.NotImplemented;
60
import org.dataone.service.exceptions.ServiceFailure;
61
import org.dataone.service.exceptions.UnsupportedType;
62
import org.dataone.service.exceptions.VersionMismatch;
63
import org.dataone.service.types.v1.AccessPolicy;
64
import org.dataone.service.types.v1.Checksum;
65
import org.dataone.service.types.v1.ChecksumAlgorithmList;
66
import org.dataone.service.types.v1.Event;
67
import org.dataone.service.types.v1.Identifier;
68
import org.dataone.service.types.v1.NodeReference;
69
import org.dataone.service.types.v1.NodeType;
70
import org.dataone.service.types.v1.ObjectFormatIdentifier;
71
import org.dataone.service.types.v1.ObjectList;
72
import org.dataone.service.types.v1.ObjectLocationList;
73
import org.dataone.service.types.v1.Permission;
74
import org.dataone.service.types.v1.Replica;
75
import org.dataone.service.types.v1.ReplicationPolicy;
76
import org.dataone.service.types.v1.ReplicationStatus;
77
import org.dataone.service.types.v1.Session;
78
import org.dataone.service.types.v1.Subject;
79
import org.dataone.service.types.v1_1.QueryEngineDescription;
80
import org.dataone.service.types.v1_1.QueryEngineList;
81
import org.dataone.service.types.v2.Node;
82
import org.dataone.service.types.v2.NodeList;
83
import org.dataone.service.types.v2.ObjectFormat;
84
import org.dataone.service.types.v2.ObjectFormatList;
85
import org.dataone.service.types.v2.SystemMetadata;
86
import org.dataone.service.types.v2.util.ServiceMethodRestrictionUtil;
87
import org.dataone.service.util.TypeMarshaller;
88
import org.jibx.runtime.JiBXException;
89

    
90
import edu.ucsb.nceas.metacat.DBUtil;
91
import edu.ucsb.nceas.metacat.EventLog;
92
import edu.ucsb.nceas.metacat.IdentifierManager;
93
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
94
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
95
import edu.ucsb.nceas.metacat.properties.PropertyService;
96
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
97

    
98
/**
99
 * Represents Metacat's implementation of the DataONE Coordinating Node 
100
 * service API. Methods implement the various CN* interfaces, and methods common
101
 * to both Member Node and Coordinating Node interfaces are found in the
102
 * D1NodeService super class.
103
 *
104
 */
105
public class CNodeService extends D1NodeService implements CNAuthorization,
106
    CNCore, CNRead, CNReplication, CNView {
107

    
108
  /* the logger instance */
109
  private Logger logMetacat = null;
110
  public final static String V2V1MISSMATCH = "The Coordinating Node is not authorized to make systemMetadata changes on this object. Please make changes directly on the authoritative Member Node.";
111

    
112
  /**
113
   * singleton accessor
114
   */
115
  public static CNodeService getInstance(HttpServletRequest request) { 
116
    return new CNodeService(request);
117
  }
118
  
119
  /**
120
   * Constructor, private for singleton access
121
   */
122
  private CNodeService(HttpServletRequest request) {
123
    super(request);
124
    logMetacat = Logger.getLogger(CNodeService.class);
125
        
126
  }
127
    
128
  /**
129
   * Set the replication policy for an object given the object identifier
130
   * It only is applied to objects whose authoritative mn is a v1 node.
131
   * @param session - the Session object containing the credentials for the Subject
132
   * @param pid - the object identifier for the given object
133
   * @param policy - the replication policy to be applied
134
   * 
135
   * @return true or false
136
   * 
137
   * @throws NotImplemented
138
   * @throws NotAuthorized
139
   * @throws ServiceFailure
140
   * @throws InvalidRequest
141
   * @throws VersionMismatch
142
   * 
143
   */
144
  @Override
145
  public boolean setReplicationPolicy(Session session, Identifier pid,
146
      ReplicationPolicy policy, long serialVersion) 
147
      throws NotImplemented, NotFound, NotAuthorized, ServiceFailure, 
148
      InvalidRequest, InvalidToken, VersionMismatch {
149
      
150
      // do we have a valid pid?
151
      if (pid == null || pid.getValue().trim().equals("")) {
152
          throw new InvalidRequest("4883", "The provided identifier was invalid.");
153
          
154
      }
155
      
156
      //only allow pid to be passed
157
      String serviceFailure = "4882";
158
      String notFound = "4884";
159
      checkV1SystemMetaPidExist(pid, serviceFailure, "The object for given PID "+pid.getValue()+" couldn't be identified if it exists",  notFound, 
160
              "No object could be found for given PID: "+pid.getValue());
161
      
162
      /*String serviceFailureCode = "4882";
163
      Identifier sid = getPIDForSID(pid, serviceFailureCode);
164
      if(sid != null) {
165
          pid = sid;
166
      }*/
167
      // The lock to be used for this identifier
168
      Lock lock = null;
169
      
170
      // get the subject
171
      Subject subject = session.getSubject();
172
      
173
      // are we allowed to do this?
174
      if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
175
          throw new NotAuthorized("4881", Permission.CHANGE_PERMISSION
176
                  + " not allowed by " + subject.getValue() + " on "
177
                  + pid.getValue());
178
          
179
      }
180
      
181
      SystemMetadata systemMetadata = null;
182
      try {
183
          lock = HazelcastService.getInstance().getLock(pid.getValue());
184
          lock.lock();
185
          logMetacat.debug("Locked identifier " + pid.getValue());
186

    
187
          try {
188
              if ( HazelcastService.getInstance().getSystemMetadataMap().containsKey(pid) ) {
189
                  systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
190
                  
191
              }
192
              
193
              // did we get it correctly?
194
              if ( systemMetadata == null ) {
195
                  throw new NotFound("4884", "Couldn't find an object identified by " + pid.getValue());
196
                  
197
              }
198
              D1NodeVersionChecker checker = new D1NodeVersionChecker(systemMetadata.getAuthoritativeMemberNode());
199
              String version = checker.getVersion("MNStorage");
200
              if(version == null) {
201
                  throw new ServiceFailure("4882", "Couldn't determine the version of the MNStorge for the "+pid.getValue());
202
              } else if (version.equalsIgnoreCase(D1NodeVersionChecker.V2)) {
203
                  //we don't apply this method to an object whose authoritative node is v2
204
                  throw new NotAuthorized("4881", V2V1MISSMATCH);
205
              } else if (!version.equalsIgnoreCase(D1NodeVersionChecker.V1)) {
206
                  //we don't understand this version (it is not v1 or v2)
207
                  throw new InvalidRequest("4883", "The version of the MNStorage is "+version+" for the authoritative member node of the object "+pid.getValue()+". We don't support it.");
208
              }
209
              // does the request have the most current system metadata?
210
              if ( systemMetadata.getSerialVersion().longValue() != serialVersion ) {
211
                 String msg = "The requested system metadata version number " + 
212
                     serialVersion + " differs from the current version at " +
213
                     systemMetadata.getSerialVersion().longValue() +
214
                     ". Please get the latest copy in order to modify it.";
215
                 throw new VersionMismatch("4886", msg);
216
                 
217
              }
218
              
219
          } catch (RuntimeException e) { // Catch is generic since HZ throws RuntimeException
220
              throw new NotFound("4884", "No record found for: " + pid.getValue());
221
            
222
          }
223
          
224
          // set the new policy
225
          systemMetadata.setReplicationPolicy(policy);
226
          
227
          // update the metadata
228
          try {
229
              systemMetadata.setSerialVersion(systemMetadata.getSerialVersion().add(BigInteger.ONE));
230
              systemMetadata.setDateSysMetadataModified(Calendar.getInstance().getTime());
231
              HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
232
              notifyReplicaNodes(systemMetadata);
233
              
234
          } catch (RuntimeException e) {
235
              throw new ServiceFailure("4882", e.getMessage());
236
          
237
          }
238
          
239
      } catch (RuntimeException e) {
240
          throw new ServiceFailure("4882", e.getMessage());
241
          
242
      } finally {
243
          lock.unlock();
244
          logMetacat.debug("Unlocked identifier " + pid.getValue());
245
          
246
      }
247
    
248
      return true;
249
  }
250

    
251
  /**
252
   * Deletes the replica from the given Member Node
253
   * NOTE: MN.delete() may be an "archive" operation. TBD.
254
   * @param session
255
   * @param pid
256
   * @param nodeId
257
   * @param serialVersion
258
   * @return
259
   * @throws InvalidToken
260
   * @throws ServiceFailure
261
   * @throws NotAuthorized
262
   * @throws NotFound
263
   * @throws NotImplemented
264
   * @throws VersionMismatch
265
   */
266
  @Override
267
  public boolean deleteReplicationMetadata(Session session, Identifier pid, NodeReference nodeId, long serialVersion) 
268
  	throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, VersionMismatch {
269
	  
270
	  	// The lock to be used for this identifier
271
		Lock lock = null;
272

    
273
		// get the subject
274
		Subject subject = session.getSubject();
275

    
276
		// are we allowed to do this?
277
		/*boolean isAuthorized = false;
278
		try {
279
			isAuthorized = isAuthorized(session, pid, Permission.WRITE);
280
		} catch (InvalidRequest e) {
281
			throw new ServiceFailure("4882", e.getDescription());
282
		}
283
		if (!isAuthorized) {
284
			throw new NotAuthorized("4881", Permission.WRITE
285
					+ " not allowed by " + subject.getValue() + " on "
286
					+ pid.getValue());
287

    
288
		}*/
289
		if(session == null) {
290
		    throw new NotAuthorized("4882", "Session cannot be null. It is not authorized for deleting the replication metadata of the object "+pid.getValue());
291
		} else {
292
		    if(!isCNAdmin(session)) {
293
		        throw new NotAuthorized("4882", "The client -"+ session.getSubject().getValue()+ "is not a CN and is not authorized for deleting the replication metadata of the object "+pid.getValue());
294
		    }
295
		}
296

    
297
		SystemMetadata systemMetadata = null;
298
		try {
299
			lock = HazelcastService.getInstance().getLock(pid.getValue());
300
			lock.lock();
301
			logMetacat.debug("Locked identifier " + pid.getValue());
302

    
303
			try {
304
				if (HazelcastService.getInstance().getSystemMetadataMap().containsKey(pid)) {
305
					systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
306
				}
307

    
308
				// did we get it correctly?
309
				if (systemMetadata == null) {
310
					throw new NotFound("4884", "Couldn't find an object identified by " + pid.getValue());
311
				}
312

    
313
				// does the request have the most current system metadata?
314
				if (systemMetadata.getSerialVersion().longValue() != serialVersion) {
315
					String msg = "The requested system metadata version number "
316
							+ serialVersion
317
							+ " differs from the current version at "
318
							+ systemMetadata.getSerialVersion().longValue()
319
							+ ". Please get the latest copy in order to modify it.";
320
					throw new VersionMismatch("4886", msg);
321

    
322
				}
323

    
324
			} catch (RuntimeException e) { // Catch is generic since HZ throws RuntimeException
325
				throw new NotFound("4884", "No record found for: " + pid.getValue());
326

    
327
			}
328
			  
329
			// check permissions
330
			// TODO: is this necessary?
331
			/*List<Node> nodeList = D1Client.getCN().listNodes().getNodeList();
332
			boolean isAllowed = ServiceMethodRestrictionUtil.isMethodAllowed(session.getSubject(), nodeList, "CNReplication", "deleteReplicationMetadata");
333
			if (!isAllowed) {
334
				throw new NotAuthorized("4881", "Caller is not authorized to deleteReplicationMetadata");
335
			}*/
336
			  
337
			// delete the replica from the given node
338
			// CSJ: use CN.delete() to truly delete a replica, semantically
339
			// deleteReplicaMetadata() only modifies the sytem metadata entry.
340
			//D1Client.getMN(nodeId).delete(session, pid);
341
			  
342
			// reflect that change in the system metadata
343
			List<Replica> updatedReplicas = new ArrayList<Replica>(systemMetadata.getReplicaList());
344
			for (Replica r: systemMetadata.getReplicaList()) {
345
				  if (r.getReplicaMemberNode().equals(nodeId)) {
346
					  updatedReplicas.remove(r);
347
					  break;
348
				  }
349
			}
350
			systemMetadata.setReplicaList(updatedReplicas);
351

    
352
			// update the metadata
353
			try {
354
				systemMetadata.setSerialVersion(systemMetadata.getSerialVersion().add(BigInteger.ONE));
355
				systemMetadata.setDateSysMetadataModified(Calendar.getInstance().getTime());
356
				HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
357
			} catch (RuntimeException e) {
358
				throw new ServiceFailure("4882", e.getMessage());
359
			}
360

    
361
		} catch (RuntimeException e) {
362
			throw new ServiceFailure("4882", e.getMessage());
363
		} finally {
364
			lock.unlock();
365
			logMetacat.debug("Unlocked identifier " + pid.getValue());
366
		}
367

    
368
		return true;	  
369
	  
370
  }
371
  
372
  /**
373
   * Deletes an object from the Coordinating Node
374
   * 
375
   * @param session - the Session object containing the credentials for the Subject
376
   * @param pid - The object identifier to be deleted
377
   * 
378
   * @return pid - the identifier of the object used for the deletion
379
   * 
380
   * @throws InvalidToken
381
   * @throws ServiceFailure
382
   * @throws NotAuthorized
383
   * @throws NotFound
384
   * @throws NotImplemented
385
   * @throws InvalidRequest
386
   */
387
  @Override
388
  public Identifier delete(Session session, Identifier pid) 
389
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
390
      
391
      String localId = null;      // The corresponding docid for this pid
392
	  Lock lock = null;           // The lock to be used for this identifier
393
      CNode cn = null;            // a reference to the CN to get the node list    
394
      NodeType nodeType = null;   // the nodeType of the replica node being contacted
395
      List<Node> nodeList = null; // the list of nodes in this CN environment
396

    
397
      // check for a valid session
398
      if (session == null) {
399
        	throw new InvalidToken("4963", "No session has been provided");
400
        	
401
      }
402

    
403
      // do we have a valid pid?
404
      if (pid == null || pid.getValue().trim().equals("")) {
405
          throw new ServiceFailure("4960", "The provided identifier was invalid.");
406
          
407
      }
408
      
409
      String serviceFailureCode = "4962";
410
      Identifier sid = getPIDForSID(pid, serviceFailureCode);
411
      if(sid != null) {
412
          pid = sid;
413
      }
414

    
415
	  // check that it is CN/admin
416
	  boolean allowed = isAdminAuthorized(session);
417
	  
418
	  // additional check if it is the authoritative node if it is not the admin
419
      if(!allowed) {
420
          allowed = isAuthoritativeMNodeAdmin(session, pid);
421
          
422
      }
423
	  
424
	  if (!allowed) {
425
		  String msg = "The subject " + session.getSubject().getValue() + 
426
			  " is not allowed to call delete() on a Coordinating Node.";
427
		  logMetacat.info(msg);
428
		  throw new NotAuthorized("4960", msg);
429
		  
430
	  }
431
	  
432
	  // Don't defer to superclass implementation without a locally registered identifier
433
	  SystemMetadata systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
434
      // Check for the existing identifier
435
      try {
436
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
437
          super.delete(session, pid);
438
          
439
      } catch (McdbDocNotFoundException e) {
440
          // This object is not registered in the identifier table. Assume it is of formatType DATA,
441
    	  // and set the archive flag. (i.e. the *object* doesn't exist on the CN)
442
    	  
443
          try {
444
  			  lock = HazelcastService.getInstance().getLock(pid.getValue());
445
  			  lock.lock();
446
  			  logMetacat.debug("Locked identifier " + pid.getValue());
447

    
448
			  SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
449
			  if ( sysMeta != null ) {
450
				/*sysMeta.setSerialVersion(sysMeta.getSerialVersion().add(BigInteger.ONE));
451
				sysMeta.setArchived(true);
452
				sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
453
				HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);*/
454
			    //move the systemmetadata object from the map and delete the records in the systemmetadata database table
455
	            //since this is cn, we don't need worry about the mn solr index.
456
	            HazelcastService.getInstance().getSystemMetadataMap().remove(pid);
457
	            HazelcastService.getInstance().getIdentifiers().remove(pid);
458
	            String username = session.getSubject().getValue();//just for logging purpose
459
                //since data objects were not registered in the identifier table, we use pid as the docid
460
                EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, pid.getValue(), Event.DELETE.xmlValue());
461
				
462
			  } else {
463
				  throw new ServiceFailure("4962", "Couldn't delete the object " + pid.getValue() +
464
					  ". Couldn't obtain the system metadata record.");
465
				  
466
			  }
467
			  
468
		  } catch (RuntimeException re) {
469
			  throw new ServiceFailure("4962", "Couldn't delete " + pid.getValue() + 
470
				  ". The error message was: " + re.getMessage());
471
			  
472
		  } finally {
473
			  lock.unlock();
474
			  logMetacat.debug("Unlocked identifier " + pid.getValue());
475

    
476
		  }
477

    
478
          // NOTE: cannot log the delete without localId
479
//          EventLog.getInstance().log(request.getRemoteAddr(), 
480
//                  request.getHeader("User-Agent"), session.getSubject().getValue(), 
481
//                  pid.getValue(), Event.DELETE.xmlValue());
482

    
483
      } catch (SQLException e) {
484
          throw new ServiceFailure("4962", "Couldn't delete " + pid.getValue() + 
485
                  ". The local id of the object with the identifier can't be identified since " + e.getMessage());
486
      }
487

    
488
      // get the node list
489
      try {
490
          cn = D1Client.getCN();
491
          nodeList = cn.listNodes().getNodeList();
492
          
493
      } catch (Exception e) { // handle BaseException and other I/O issues
494
          
495
          // swallow errors since the call is not critical
496
          logMetacat.error("Can't inform MNs of the deletion of " + pid.getValue() + 
497
              " due to communication issues with the CN: " + e.getMessage());
498
          
499
      }
500

    
501
	  // notify the replicas
502
	  if (systemMetadata.getReplicaList() != null) {
503
		  for (Replica replica: systemMetadata.getReplicaList()) {
504
			  NodeReference replicaNode = replica.getReplicaMemberNode();
505
			  try {
506
                  if (nodeList != null) {
507
                      // find the node type
508
                      for (Node node : nodeList) {
509
                          if ( node.getIdentifier().getValue().equals(replicaNode.getValue()) ) {
510
                              nodeType = node.getType();
511
                              break;
512
              
513
                          }
514
                      }
515
                  }
516
                  
517
                  // only send call MN.delete() to avoid an infinite loop with the CN
518
                  if (nodeType != null && nodeType == NodeType.MN) {
519
				      Identifier mnRetId = D1Client.getMN(replicaNode).delete(null, pid);
520
                  }
521
                  
522
			  } catch (Exception e) {
523
				  // all we can really do is log errors and carry on with life
524
				  logMetacat.error("Error deleting pid: " +  pid.getValue() + 
525
					  " from replica MN: " + replicaNode.getValue(), e);
526
			}
527
			  
528
		  }
529
	  }
530
	  
531
	  return pid;
532
      
533
  }
534
  
535
  /**
536
   * Archives an object from the Coordinating Node
537
   * 
538
   * @param session - the Session object containing the credentials for the Subject
539
   * @param pid - The object identifier to be deleted
540
   * 
541
   * @return pid - the identifier of the object used for the deletion
542
   * 
543
   * @throws InvalidToken
544
   * @throws ServiceFailure
545
   * @throws NotAuthorized
546
   * @throws NotFound
547
   * @throws NotImplemented
548
   * @throws InvalidRequest
549
   */
550
  @Override
551
  public Identifier archive(Session session, Identifier pid) 
552
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
553

    
554
      String localId = null; // The corresponding docid for this pid
555
	  Lock lock = null;      // The lock to be used for this identifier
556
      CNode cn = null;            // a reference to the CN to get the node list    
557
      NodeType nodeType = null;   // the nodeType of the replica node being contacted
558
      List<Node> nodeList = null; // the list of nodes in this CN environment
559
      
560

    
561
      // check for a valid session
562
      if (session == null) {
563
        	throw new InvalidToken("4973", "No session has been provided");
564
        	
565
      }
566

    
567
      // do we have a valid pid?
568
      if (pid == null || pid.getValue().trim().equals("")) {
569
          throw new ServiceFailure("4972", "The provided identifier was invalid.");
570
          
571
      }
572

    
573
	  // check that it is CN/admin
574
	  boolean allowed = isAdminAuthorized(session);
575
	  
576
	  String serviceFailureCode = "4972";
577
	  Identifier sid = getPIDForSID(pid, serviceFailureCode);
578
	  if(sid != null) {
579
	        pid = sid;
580
	  }
581
	  
582
	  //check if it is the authoritative member node
583
	  if(!allowed) {
584
	      allowed = isAuthoritativeMNodeAdmin(session, pid);
585
	  }
586
	  
587
	  if (!allowed) {
588
		  String msg = "The subject " + session.getSubject().getValue() + 
589
				  " is not allowed to call archive() on a Coordinating Node.";
590
		  logMetacat.info(msg);
591
		  throw new NotAuthorized("4970", msg);
592
	  }
593
	  
594
      try {
595
          HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
596
          logMetacat.debug("CNodeService.archive - lock the system metadata for "+pid.getValue());
597
          SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
598
          boolean needModifyDate = true;
599
          archiveCNObjectWithNotificationReplica(session, pid, sysMeta, needModifyDate);
600
      
601
      } finally {
602
          HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
603
          logMetacat.debug("CNodeService.archive - unlock the system metadata for "+pid.getValue());
604
      }
605

    
606
	  return pid;
607
      
608
  }
609
  
610
  
611
  /**
612
   * Archive a object on cn and notify the replica. This method doesn't lock the system metadata map. The caller should lock it.
613
   * This method doesn't check the authorization; this method only accept a pid.
614
   * @param session
615
   * @param pid
616
   * @param sysMeta
617
   * @param notifyReplica
618
   * @return
619
   * @throws InvalidToken
620
   * @throws ServiceFailure
621
   * @throws NotAuthorized
622
   * @throws NotFound
623
   * @throws NotImplemented
624
   */
625
  private Identifier archiveCNObjectWithNotificationReplica(Session session, Identifier pid, SystemMetadata sysMeta, boolean needModifyDate) 
626
                  throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
627
          archiveCNObject(session, pid, sysMeta, needModifyDate);
628
          // notify the replicas
629
          notifyReplicaNodes(sysMeta);
630
          return pid;
631
    }
632
  
633
  
634
  
635
  /**
636
   * Set the obsoletedBy attribute in System Metadata
637
   * @param session
638
   * @param pid
639
   * @param obsoletedByPid
640
   * @param serialVersion
641
   * @return
642
   * @throws NotImplemented
643
   * @throws NotFound
644
   * @throws NotAuthorized
645
   * @throws ServiceFailure
646
   * @throws InvalidRequest
647
   * @throws InvalidToken
648
   * @throws VersionMismatch
649
   */
650
  @Override
651
  public boolean setObsoletedBy(Session session, Identifier pid,
652
			Identifier obsoletedByPid, long serialVersion)
653
			throws NotImplemented, NotFound, NotAuthorized, ServiceFailure,
654
			InvalidRequest, InvalidToken, VersionMismatch {
655
      
656
      // do we have a valid pid?
657
      if (pid == null || pid.getValue().trim().equals("")) {
658
          throw new InvalidRequest("4942", "The provided identifier was invalid.");
659
          
660
      }
661
      
662
      /*String serviceFailureCode = "4941";
663
      Identifier sid = getPIDForSID(pid, serviceFailureCode);
664
      if(sid != null) {
665
          pid = sid;
666
      }*/
667
      
668
      // do we have a valid pid?
669
      if (obsoletedByPid == null || obsoletedByPid.getValue().trim().equals("")) {
670
          throw new InvalidRequest("4942", "The provided obsoletedByPid was invalid.");
671
          
672
      }
673
      
674
      try {
675
          if(IdentifierManager.getInstance().systemMetadataSIDExists(obsoletedByPid)) {
676
              throw new InvalidRequest("4942", "The provided obsoletedByPid "+obsoletedByPid.getValue()+" is an existing SID. However, it must NOT be an SID.");
677
          }
678
      } catch (SQLException ee) {
679
          throw new ServiceFailure("4941", "Couldn't determine if the obsoletedByPid "+obsoletedByPid.getValue()+" is an SID or not. The id shouldn't be an SID.");
680
      }
681
      
682

    
683
		// The lock to be used for this identifier
684
		Lock lock = null;
685

    
686
		// get the subject
687
		Subject subject = session.getSubject();
688

    
689
		// are we allowed to do this?
690
		if (!isAuthorized(session, pid, Permission.WRITE)) {
691
			throw new NotAuthorized("4881", Permission.WRITE
692
					+ " not allowed by " + subject.getValue() + " on "
693
					+ pid.getValue());
694

    
695
		}
696

    
697

    
698
		SystemMetadata systemMetadata = null;
699
		try {
700
			lock = HazelcastService.getInstance().getLock(pid.getValue());
701
			lock.lock();
702
			logMetacat.debug("Locked identifier " + pid.getValue());
703

    
704
			try {
705
				if (HazelcastService.getInstance().getSystemMetadataMap().containsKey(pid)) {
706
					systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
707
				}
708

    
709
				// did we get it correctly?
710
				if (systemMetadata == null) {
711
					throw new NotFound("4884", "Couldn't find an object identified by " + pid.getValue());
712
				}
713

    
714
				// does the request have the most current system metadata?
715
				if (systemMetadata.getSerialVersion().longValue() != serialVersion) {
716
					String msg = "The requested system metadata version number "
717
							+ serialVersion
718
							+ " differs from the current version at "
719
							+ systemMetadata.getSerialVersion().longValue()
720
							+ ". Please get the latest copy in order to modify it.";
721
					throw new VersionMismatch("4886", msg);
722

    
723
				}
724

    
725
			} catch (RuntimeException e) { // Catch is generic since HZ throws RuntimeException
726
				throw new NotFound("4884", "No record found for: " + pid.getValue());
727

    
728
			}
729

    
730
			// set the new policy
731
			systemMetadata.setObsoletedBy(obsoletedByPid);
732

    
733
			// update the metadata
734
			try {
735
				systemMetadata.setSerialVersion(systemMetadata.getSerialVersion().add(BigInteger.ONE));
736
				systemMetadata.setDateSysMetadataModified(Calendar.getInstance().getTime());
737
				HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
738
			} catch (RuntimeException e) {
739
				throw new ServiceFailure("4882", e.getMessage());
740
			}
741

    
742
		} catch (RuntimeException e) {
743
			throw new ServiceFailure("4882", e.getMessage());
744
		} finally {
745
			lock.unlock();
746
			logMetacat.debug("Unlocked identifier " + pid.getValue());
747
		}
748

    
749
		return true;
750
	}
751
  
752
  
753
  /**
754
   * Set the replication status for an object given the object identifier
755
   * 
756
   * @param session - the Session object containing the credentials for the Subject
757
   * @param pid - the object identifier for the given object
758
   * @param status - the replication status to be applied
759
   * 
760
   * @return true or false
761
   * 
762
   * @throws NotImplemented
763
   * @throws NotAuthorized
764
   * @throws ServiceFailure
765
   * @throws InvalidRequest
766
   * @throws InvalidToken
767
   * @throws NotFound
768
   * 
769
   */
770
  @Override
771
  public boolean setReplicationStatus(Session session, Identifier pid,
772
      NodeReference targetNode, ReplicationStatus status, BaseException failure) 
773
      throws ServiceFailure, NotImplemented, InvalidToken, NotAuthorized, 
774
      InvalidRequest, NotFound {
775
	  
776
	  // cannot be called by public
777
	  if (session == null) {
778
		  throw new NotAuthorized("4720", "Session cannot be null");
779
	  } 
780
	  
781
	  /*else {
782
	      if(!isCNAdmin(session)) {
783
              throw new NotAuthorized("4720", "The client -"+ session.getSubject().getValue()+ "is not a CN and is not authorized for setting the replication status of the object "+pid.getValue());
784
        }
785
	  }*/
786
	  
787
	// do we have a valid pid?
788
      if (pid == null || pid.getValue().trim().equals("")) {
789
          throw new InvalidRequest("4730", "The provided identifier was invalid.");
790
          
791
      }
792
      
793
      /*String serviceFailureCode = "4700";
794
      Identifier sid = getPIDForSID(pid, serviceFailureCode);
795
      if(sid != null) {
796
          pid = sid;
797
      }*/
798
      
799
      // The lock to be used for this identifier
800
      Lock lock = null;
801
      
802
      boolean allowed = false;
803
      int replicaEntryIndex = -1;
804
      List<Replica> replicas = null;
805
      // get the subject
806
      Subject subject = session.getSubject();
807
      logMetacat.debug("ReplicationStatus for identifier " + pid.getValue() +
808
          " is " + status.toString());
809
      
810
      SystemMetadata systemMetadata = null;
811

    
812
      try {
813
          lock = HazelcastService.getInstance().getLock(pid.getValue());
814
          lock.lock();
815
          logMetacat.debug("Locked identifier " + pid.getValue());
816

    
817
          try {      
818
              systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
819

    
820
              // did we get it correctly?
821
              if ( systemMetadata == null ) {
822
                  logMetacat.debug("systemMetadata is null for " + pid.getValue());
823
                  throw new NotFound("4740", "Couldn't find an object identified by " + pid.getValue());
824
                  
825
              }
826
              replicas = systemMetadata.getReplicaList();
827
              int count = 0;
828
              
829
              // was there a failure? log it
830
              if ( failure != null && status.equals(ReplicationStatus.FAILED) ) {
831
                 String msg = "The replication request of the object identified by " + 
832
                     pid.getValue() + " failed.  The error message was " +
833
                     failure.getMessage() + ".";
834
                 logMetacat.error(msg);
835
              }
836
              
837
              if (replicas.size() > 0 && replicas != null) {
838
                  // find the target replica index in the replica list
839
                  for (Replica replica : replicas) {
840
                      String replicaNodeStr = replica.getReplicaMemberNode().getValue();
841
                      String targetNodeStr = targetNode.getValue();
842
                      logMetacat.debug("Comparing " + replicaNodeStr + " to " + targetNodeStr);
843
                  
844
                      if (replicaNodeStr.equals(targetNodeStr)) {
845
                          replicaEntryIndex = count;
846
                          logMetacat.debug("replica entry index is: "
847
                                  + replicaEntryIndex);
848
                          break;
849
                      }
850
                      count++;
851
                  
852
                  }
853
              }
854
              // are we allowed to do this? only CNs and target MNs are allowed
855
              CNode cn = D1Client.getCN();
856
              List<Node> nodes = cn.listNodes().getNodeList();
857
              
858
              // find the node in the node list
859
              for ( Node node : nodes ) {
860
                  
861
                  NodeReference nodeReference = node.getIdentifier();
862
                  logMetacat.debug("In setReplicationStatus(), Node reference is: " + 
863
                      nodeReference.getValue());
864
                  
865
                  // allow target MN certs
866
                  if ( targetNode.getValue().equals(nodeReference.getValue() ) &&
867
                      node.getType().equals(NodeType.MN)) {
868
                      List<Subject> nodeSubjects = node.getSubjectList();
869
                      
870
                      // check if the session subject is in the node subject list
871
                      for (Subject nodeSubject : nodeSubjects) {
872
                          logMetacat.debug("In setReplicationStatus(), comparing subjects: " +
873
                                  nodeSubject.getValue() + " and " + subject.getValue());
874
                          if ( nodeSubject.equals(subject) ) { // subject of session == target node subject
875
                              
876
                              // lastly limit to COMPLETED, INVALIDATED,
877
                              // and FAILED status updates from MNs only
878
                              if ( status.equals(ReplicationStatus.COMPLETED) ||
879
                                   status.equals(ReplicationStatus.INVALIDATED) ||
880
                                   status.equals(ReplicationStatus.FAILED)) {
881
                                  allowed = true;
882
                                  break;
883
                                  
884
                              }                              
885
                          }
886
                      }                 
887
                  }
888
              }
889

    
890
              if ( !allowed ) {
891
                  //check for CN admin access
892
                  //allowed = isAuthorized(session, pid, Permission.WRITE);
893
                  allowed = isCNAdmin(session);
894
                  
895
              }              
896
              
897
              if ( !allowed ) {
898
                  String msg = "The subject identified by "
899
                          + subject.getValue()
900
                          + " is not a CN or MN, and does not have permission to set the replication status for "
901
                          + "the replica identified by "
902
                          + targetNode.getValue() + ".";
903
                  logMetacat.info(msg);
904
                  throw new NotAuthorized("4720", msg);
905
                  
906
              }
907

    
908
          } catch (RuntimeException e) { // Catch is generic since HZ throws RuntimeException
909
            throw new NotFound("4740", "No record found for: " + pid.getValue() +
910
                " : " + e.getMessage());
911
            
912
          }
913
          
914
          Replica targetReplica = new Replica();
915
          // set the status for the replica
916
          if ( replicaEntryIndex != -1 ) {
917
              targetReplica = replicas.get(replicaEntryIndex);
918
              
919
              // don't allow status to change from COMPLETED to anything other
920
              // than INVALIDATED: prevents overwrites from race conditions
921
              if ( targetReplica.getReplicationStatus().equals(ReplicationStatus.COMPLETED) &&
922
            	   !status.equals(ReplicationStatus.INVALIDATED)) {
923
            	  throw new InvalidRequest("4730", "Status state change from " +
924
            			  targetReplica.getReplicationStatus() + " to " +
925
            			  status.toString() + "is prohibited for identifier " +
926
            			  pid.getValue() + " and target node " + 
927
            			  targetReplica.getReplicaMemberNode().getValue());
928
              }
929
              
930
              if(targetReplica.getReplicationStatus().equals(status)) {
931
                  //There is no change in the status, we do nothing.
932
                  return true;
933
              }
934
              
935
              targetReplica.setReplicationStatus(status);
936
              
937
              logMetacat.debug("Set the replication status for " + 
938
                  targetReplica.getReplicaMemberNode().getValue() + " to " +
939
                  targetReplica.getReplicationStatus() + " for identifier " +
940
                  pid.getValue());
941
              
942
          } else {
943
              // this is a new entry, create it
944
              targetReplica.setReplicaMemberNode(targetNode);
945
              targetReplica.setReplicationStatus(status);
946
              targetReplica.setReplicaVerified(Calendar.getInstance().getTime());
947
              replicas.add(targetReplica);
948
              
949
          }
950
          
951
          systemMetadata.setReplicaList(replicas);
952
                
953
          // update the metadata
954
          try {
955
              systemMetadata.setSerialVersion(systemMetadata.getSerialVersion().add(BigInteger.ONE));
956
              // Based on CN behavior discussion 9/16/15, we no longer want to 
957
              // update the modified date for changes to the replica list
958
              //systemMetadata.setDateSysMetadataModified(Calendar.getInstance().getTime());
959
              HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
960

    
961
              if ( !status.equals(ReplicationStatus.QUEUED) && 
962
            	   !status.equals(ReplicationStatus.REQUESTED)) {
963
                  
964
                logMetacat.trace("METRICS:\tREPLICATION:\tEND REQUEST:\tPID:\t" + pid.getValue() + 
965
                          "\tNODE:\t" + targetNode.getValue() + 
966
                          "\tSIZE:\t" + systemMetadata.getSize().intValue());
967
                
968
                logMetacat.trace("METRICS:\tREPLICATION:\t" + status.toString().toUpperCase() +
969
                          "\tPID:\t"  + pid.getValue() + 
970
                          "\tNODE:\t" + targetNode.getValue() + 
971
                          "\tSIZE:\t" + systemMetadata.getSize().intValue());
972
              }
973

    
974
              if ( status.equals(ReplicationStatus.FAILED) && failure != null ) {
975
                  logMetacat.warn("Replication failed for identifier " + pid.getValue() +
976
                      " on target node " + targetNode + ". The exception was: " +
977
                      failure.getMessage());
978
              }
979
              
980
			  // update the replica nodes about the completed replica when complete
981
              if (status.equals(ReplicationStatus.COMPLETED)) {
982
				notifyReplicaNodes(systemMetadata);
983
			}
984
          
985
          } catch (RuntimeException e) {
986
              throw new ServiceFailure("4700", e.getMessage());
987
          
988
          }
989
          
990
    } catch (RuntimeException e) {
991
        String msg = "There was a RuntimeException getting the lock for " +
992
            pid.getValue();
993
        logMetacat.info(msg);
994
        
995
    } finally {
996
        lock.unlock();
997
        logMetacat.debug("Unlocked identifier " + pid.getValue());
998
        
999
    }
1000
      
1001
      return true;
1002
  }
1003
  
1004
/**
1005
   * Return the checksum of the object given the identifier 
1006
   * 
1007
   * @param session - the Session object containing the credentials for the Subject
1008
   * @param pid - the object identifier for the given object
1009
   * 
1010
   * @return checksum - the checksum of the object
1011
   * 
1012
   * @throws InvalidToken
1013
   * @throws ServiceFailure
1014
   * @throws NotAuthorized
1015
   * @throws NotFound
1016
   * @throws NotImplemented
1017
   */
1018
  @Override
1019
  public Checksum getChecksum(Session session, Identifier pid)
1020
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1021
    NotImplemented {
1022
    
1023
	boolean isAuthorized = false;
1024
	try {
1025
		isAuthorized = isAuthorized(session, pid, Permission.READ);
1026
	} catch (InvalidRequest e) {
1027
		throw new ServiceFailure("1410", e.getDescription());
1028
	}  
1029
    if (!isAuthorized) {
1030
        throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());  
1031
    }
1032
    
1033
    SystemMetadata systemMetadata = null;
1034
    Checksum checksum = null;
1035
    
1036
    try {
1037
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);        
1038

    
1039
        if (systemMetadata == null ) {
1040
            String error ="";
1041
            String localId = null;
1042
            try {
1043
                localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1044
              
1045
             } catch (Exception e) {
1046
                logMetacat.warn("Couldn't find the local id for the pid "+pid.getValue());
1047
            }
1048
            
1049
            if(localId != null && EventLog.getInstance().isDeleted(localId)) {
1050
                error = DELETEDMESSAGE;
1051
            } else if (localId == null && EventLog.getInstance().isDeleted(pid.getValue())) {
1052
                error = DELETEDMESSAGE;
1053
            }
1054
            throw new NotFound("1420", "Couldn't find an object identified by " + pid.getValue()+". "+error);
1055
        }
1056
        checksum = systemMetadata.getChecksum();
1057
        
1058
    } catch (RuntimeException e) {
1059
        throw new ServiceFailure("1410", "An error occurred getting the checksum for " + 
1060
            pid.getValue() + ". The error message was: " + e.getMessage());
1061
      
1062
    }
1063
    
1064
    return checksum;
1065
  }
1066

    
1067
  /**
1068
   * Resolve the location of a given object
1069
   * 
1070
   * @param session - the Session object containing the credentials for the Subject
1071
   * @param pid - the object identifier for the given object
1072
   * 
1073
   * @return objectLocationList - the list of nodes known to contain the object
1074
   * 
1075
   * @throws InvalidToken
1076
   * @throws ServiceFailure
1077
   * @throws NotAuthorized
1078
   * @throws NotFound
1079
   * @throws NotImplemented
1080
   */
1081
  @Override
1082
  public ObjectLocationList resolve(Session session, Identifier pid)
1083
    throws InvalidToken, ServiceFailure, NotAuthorized,
1084
    NotFound, NotImplemented {
1085

    
1086
    throw new NotImplemented("4131", "resolve not implemented");
1087

    
1088
  }
1089

    
1090
  /**
1091
   * Metacat does not implement this method at the CN level
1092
   */
1093
  @Override
1094
  public ObjectList search(Session session, String queryType, String query)
1095
    throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest,
1096
    NotImplemented {
1097

    
1098
		  throw new NotImplemented("4281", "Metacat does not implement CN.search");
1099
	  
1100
//    ObjectList objectList = null;
1101
//    try {
1102
//        objectList = 
1103
//          IdentifierManager.getInstance().querySystemMetadata(
1104
//              null, //startTime, 
1105
//              null, //endTime,
1106
//              null, //objectFormat, 
1107
//              false, //replicaStatus, 
1108
//              0, //start, 
1109
//              1000 //count
1110
//              );
1111
//        
1112
//    } catch (Exception e) {
1113
//      throw new ServiceFailure("4310", "Error querying system metadata: " + e.getMessage());
1114
//    }
1115
//
1116
//      return objectList;
1117
		  
1118
  }
1119
  
1120
  /**
1121
   * Returns the object format registered in the DataONE Object Format 
1122
   * Vocabulary for the given format identifier
1123
   * 
1124
   * @param fmtid - the identifier of the format requested
1125
   * 
1126
   * @return objectFormat - the object format requested
1127
   * 
1128
   * @throws ServiceFailure
1129
   * @throws NotFound
1130
   * @throws InsufficientResources
1131
   * @throws NotImplemented
1132
   */
1133
  @Override
1134
  public ObjectFormat getFormat(ObjectFormatIdentifier fmtid)
1135
    throws ServiceFailure, NotFound, NotImplemented {
1136
     
1137
      return ObjectFormatService.getInstance().getFormat(fmtid);
1138
      
1139
  }
1140

    
1141
    @Override
1142
    public ObjectFormatIdentifier addFormat(Session session, ObjectFormatIdentifier formatId, ObjectFormat format)
1143
            throws ServiceFailure, NotFound, NotImplemented, NotAuthorized, InvalidToken {
1144

    
1145
        logMetacat.debug("CNodeService.addFormat() called.\n" + 
1146
                "format ID: " + format.getFormatId() + "\n" + 
1147
                "format name: " + format.getFormatName() + "\n" + 
1148
                "format type: " + format.getFormatType() );
1149
        
1150
        // FIXME remove:
1151
        if (true)
1152
            throw new NotImplemented("0000", "Implementation underway... Will need testing too...");
1153
        
1154
        if (!isAdminAuthorized(session))
1155
            throw new NotAuthorized("0000", "Not authorized to call addFormat()");
1156

    
1157
        String separator = ".";
1158
        try {
1159
            separator = PropertyService.getProperty("document.accNumSeparator");
1160
        } catch (PropertyNotFoundException e) {
1161
            logMetacat.warn("Unable to find property \"document.accNumSeparator\"\n" + e.getMessage());
1162
        }
1163

    
1164
        // find pids of last and next ObjectFormatList
1165
        String OBJECT_FORMAT_DOCID = ObjectFormatService.OBJECT_FORMAT_DOCID;
1166
        int lastRev = -1;
1167
        try {
1168
            lastRev = DBUtil.getLatestRevisionInDocumentTable(OBJECT_FORMAT_DOCID);
1169
        } catch (SQLException e) {
1170
            throw new ServiceFailure("0000", "Unable to locate last revision of the object format list.\n" + e.getMessage());
1171
        }
1172
        int nextRev = lastRev + 1;
1173
        String lastDocID = OBJECT_FORMAT_DOCID + separator + lastRev;
1174
        String nextDocID = OBJECT_FORMAT_DOCID + separator + nextRev;
1175
        
1176
        Identifier lastPid = new Identifier();
1177
        lastPid.setValue(lastDocID);
1178
        Identifier nextPid = new Identifier();
1179
        nextPid.setValue(nextDocID);
1180
        
1181
        logMetacat.debug("Last ObjectFormatList document ID: " + lastDocID + "\n" 
1182
                + "Next ObjectFormatList document ID: " + nextDocID);
1183
        
1184
        // add new format to the current ObjectFormatList
1185
        ObjectFormatList objectFormatList = ObjectFormatService.getInstance().listFormats();
1186
        List<ObjectFormat> innerList = objectFormatList.getObjectFormatList();
1187
        innerList.add(format);
1188

    
1189
        // get existing (last) sysmeta and make a copy
1190
        SystemMetadata lastSysmeta = getSystemMetadata(session, lastPid);
1191
        SystemMetadata nextSysmeta = new SystemMetadata();
1192
        try {
1193
            BeanUtils.copyProperties(nextSysmeta, lastSysmeta);
1194
        } catch (IllegalAccessException | InvocationTargetException e) {
1195
            throw new ServiceFailure("0000", "Unable to create system metadata for updated object format list.\n" + e.getMessage());
1196
        }
1197
        
1198
        // create the new object format list, and update the old sysmeta with obsoletedBy
1199
        createNewObjectFormatList(session, lastPid, nextPid, objectFormatList, nextSysmeta);
1200
        updateOldObjectFormatList(session, lastPid, nextPid, lastSysmeta);
1201
        
1202
        // TODO add to ObjectFormatService local cache?
1203
        
1204
        return formatId;
1205
    }
1206

    
1207
    /**
1208
     * Creates the object for the next / updated version of the ObjectFormatList.
1209
     * 
1210
     * @param session
1211
     * @param lastPid
1212
     * @param nextPid
1213
     * @param objectFormatList
1214
     * @param lastSysmeta
1215
     */
1216
    private void createNewObjectFormatList(Session session, Identifier lastPid, Identifier nextPid,
1217
            ObjectFormatList objectFormatList, SystemMetadata lastSysmeta) 
1218
                    throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented {
1219
        
1220
        PipedInputStream is = new PipedInputStream();
1221
        PipedOutputStream os = null;
1222
        
1223
        try {
1224
            os = new PipedOutputStream(is);
1225
            TypeMarshaller.marshalTypeToOutputStream(objectFormatList, os);
1226
        } catch (JiBXException | IOException e) {
1227
            throw new ServiceFailure("0000", "Unable to marshal object format list.\n" + e.getMessage());
1228
        } finally {
1229
            try {
1230
                os.flush();
1231
                os.close();
1232
            } catch (IOException ioe) {
1233
                throw new ServiceFailure("0000", "Unable to marshal object format list.\n" + ioe.getMessage());
1234
            }
1235
        }
1236
        
1237
        BigInteger docSize = lastSysmeta.getSize();
1238
        try {
1239
            docSize = BigInteger.valueOf(is.available());
1240
        } catch (IOException e) {
1241
            logMetacat.warn("Unable to set an accurate size for the new object format list.", e);
1242
        }
1243
        
1244
        lastSysmeta.setIdentifier(nextPid);
1245
        lastSysmeta.setObsoletes(lastPid);
1246
        lastSysmeta.setSize(docSize); 
1247
        lastSysmeta.setSubmitter(session.getSubject());
1248
        lastSysmeta.setDateUploaded(new Date());
1249
        
1250
        // create new object format list
1251
        try {
1252
            create(session, nextPid, is, lastSysmeta);
1253
        } catch (IdentifierNotUnique | UnsupportedType | InsufficientResources
1254
                | InvalidSystemMetadata | InvalidRequest e) {
1255
            throw new ServiceFailure("0000", "Unable to create() new object format list" + e.getMessage());
1256
        }
1257
    }
1258
  
1259
    /**
1260
     * Updates the SystemMetadata for the old version of the ObjectFormatList
1261
     * by setting the obsoletedBy value to the pid of the new version of the 
1262
     * ObjectFormatList.
1263
     * 
1264
     * @param session
1265
     * @param lastPid
1266
     * @param obsoletedByPid
1267
     * @param lastSysmeta
1268
     * @throws ServiceFailure
1269
     */
1270
    private void updateOldObjectFormatList(Session session, Identifier lastPid, Identifier obsoletedByPid, SystemMetadata lastSysmeta) 
1271
            throws ServiceFailure {
1272
        
1273
        lastSysmeta.setObsoletedBy(obsoletedByPid);
1274
        
1275
        try {
1276
            this.updateSystemMetadata(session, lastPid, lastSysmeta);
1277
        } catch (NotImplemented | NotAuthorized | ServiceFailure | InvalidRequest
1278
                | InvalidSystemMetadata | InvalidToken e) {
1279
            throw new ServiceFailure("0000", "Unable to update metadata of old object format list.\n" + e.getMessage());
1280
        }
1281
    }
1282
  /**
1283
   * Returns a list of all object formats registered in the DataONE Object 
1284
   * Format Vocabulary
1285
    * 
1286
   * @return objectFormatList - The list of object formats registered in 
1287
   *                            the DataONE Object Format Vocabulary
1288
   * 
1289
   * @throws ServiceFailure
1290
   * @throws NotImplemented
1291
   * @throws InsufficientResources
1292
   */
1293
  @Override
1294
  public ObjectFormatList listFormats() 
1295
    throws ServiceFailure, NotImplemented {
1296

    
1297
    return ObjectFormatService.getInstance().listFormats();
1298
  }
1299

    
1300
  /**
1301
   * Returns a list of nodes that have been registered with the DataONE infrastructure
1302
    * 
1303
   * @return nodeList - List of nodes from the registry
1304
   * 
1305
   * @throws ServiceFailure
1306
   * @throws NotImplemented
1307
   */
1308
  @Override
1309
  public NodeList listNodes() 
1310
    throws NotImplemented, ServiceFailure {
1311

    
1312
    throw new NotImplemented("4800", "listNodes not implemented");
1313
  }
1314

    
1315
  /**
1316
   * Provides a mechanism for adding system metadata independently of its 
1317
   * associated object, such as when adding system metadata for data objects.
1318
    * 
1319
   * @param session - the Session object containing the credentials for the Subject
1320
   * @param pid - The identifier of the object to register the system metadata against
1321
   * @param sysmeta - The system metadata to be registered
1322
   * 
1323
   * @return true if the registration succeeds
1324
   * 
1325
   * @throws NotImplemented
1326
   * @throws NotAuthorized
1327
   * @throws ServiceFailure
1328
   * @throws InvalidRequest
1329
   * @throws InvalidSystemMetadata
1330
   */
1331
  @Override
1332
  public Identifier registerSystemMetadata(Session session, Identifier pid,
1333
      SystemMetadata sysmeta) 
1334
      throws NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest, 
1335
      InvalidSystemMetadata {
1336

    
1337
      // The lock to be used for this identifier
1338
      Lock lock = null;
1339

    
1340
      // TODO: control who can call this?
1341
      if (session == null) {
1342
          //TODO: many of the thrown exceptions do not use the correct error codes
1343
          //check these against the docs and correct them
1344
          throw new NotAuthorized("4861", "No Session - could not authorize for registration." +
1345
                  "  If you are not logged in, please do so and retry the request.");
1346
      } else {
1347
          //only CN is allwoed
1348
          if(!isCNAdmin(session)) {
1349
                throw new NotAuthorized("4861", "The client -"+ session.getSubject().getValue()+ "is not a CN and is not authorized for registering the system metadata of the object "+pid.getValue());
1350
          }
1351
      }
1352
      // the identifier can't be an SID
1353
      try {
1354
          if(IdentifierManager.getInstance().systemMetadataSIDExists(pid)) {
1355
              throw new InvalidRequest("4863", "The provided identifier "+pid.getValue()+" is a series id which is not allowed.");
1356
          }
1357
      } catch (SQLException sqle) {
1358
          throw new ServiceFailure("4862", "Couldn't determine if the pid "+pid.getValue()+" is a series id since "+sqle.getMessage());
1359
      }
1360
      
1361
      // verify that guid == SystemMetadata.getIdentifier()
1362
      logMetacat.debug("Comparing guid|sysmeta_guid: " + pid.getValue() + 
1363
          "|" + sysmeta.getIdentifier().getValue());
1364
      if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
1365
          throw new InvalidRequest("4863", 
1366
              "The identifier in method call (" + pid.getValue() + 
1367
              ") does not match identifier in system metadata (" +
1368
              sysmeta.getIdentifier().getValue() + ").");
1369
      }
1370
      
1371
      //check if the sid is legitimate in the system metadata
1372
      //checkSidInModifyingSystemMetadata(sysmeta, "4864", "4862");
1373
      Identifier sid = sysmeta.getSeriesId();
1374
      if(sid != null) {
1375
          if (!isValidIdentifier(sid)) {
1376
              throw new InvalidRequest("4863", "The series id in the system metadata is invalid in the request.");
1377
          }
1378
      }
1379

    
1380
      try {
1381
          lock = HazelcastService.getInstance().getLock(sysmeta.getIdentifier().getValue());
1382
          lock.lock();
1383
          logMetacat.debug("Locked identifier " + pid.getValue());
1384
          logMetacat.debug("Checking if identifier exists...");
1385
          // Check that the identifier does not already exist
1386
          if (HazelcastService.getInstance().getSystemMetadataMap().containsKey(pid)) {
1387
              throw new InvalidRequest("4863", 
1388
                  "The identifier is already in use by an existing object.");
1389
          
1390
          }
1391
          
1392
          // insert the system metadata into the object store
1393
          logMetacat.debug("Starting to insert SystemMetadata...");
1394
          try {
1395
              sysmeta.setSerialVersion(BigInteger.ONE);
1396
              sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1397
              HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1398
              
1399
          } catch (RuntimeException e) {
1400
            logMetacat.error("Problem registering system metadata: " + pid.getValue(), e);
1401
              throw new ServiceFailure("4862", "Error inserting system metadata: " + 
1402
                  e.getClass() + ": " + e.getMessage());
1403
              
1404
          }
1405
          
1406
      } catch (RuntimeException e) {
1407
          throw new ServiceFailure("4862", "Error inserting system metadata: " + 
1408
                  e.getClass() + ": " + e.getMessage());
1409
          
1410
      }  finally {
1411
          lock.unlock();
1412
          logMetacat.debug("Unlocked identifier " + pid.getValue());
1413
          
1414
      }
1415

    
1416
      
1417
      logMetacat.debug("Returning from registerSystemMetadata");
1418
      
1419
      try {
1420
    	  String localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1421
    	  EventLog.getInstance().log(request.getRemoteAddr(), 
1422
    	          request.getHeader("User-Agent"), session.getSubject().getValue(), 
1423
    	          localId, "registerSystemMetadata");
1424
      } catch (McdbDocNotFoundException e) {
1425
    	  // do nothing, no localId to log with
1426
    	  logMetacat.warn("Could not log 'registerSystemMetadata' event because no localId was found for pid: " + pid.getValue());
1427
      } catch (SQLException ee) {
1428
          // do nothing, no localId to log with
1429
          logMetacat.warn("Could not log 'registerSystemMetadata' event because the localId couldn't be identified for pid: " + pid.getValue());
1430
      }
1431
      
1432
      
1433
      return pid;
1434
  }
1435
  
1436
  /**
1437
   * Given an optional scope and format, reserves and returns an identifier 
1438
   * within that scope and format that is unique and will not be 
1439
   * used by any other sessions. 
1440
    * 
1441
   * @param session - the Session object containing the credentials for the Subject
1442
   * @param pid - The identifier of the object to register the system metadata against
1443
   * @param scope - An optional string to be used to qualify the scope of 
1444
   *                the identifier namespace, which is applied differently 
1445
   *                depending on the format requested. If scope is not 
1446
   *                supplied, a default scope will be used.
1447
   * @param format - The optional name of the identifier format to be used, 
1448
   *                  drawn from a DataONE-specific vocabulary of identifier 
1449
   *                 format names, including several common syntaxes such 
1450
   *                 as DOI, LSID, UUID, and LSRN, among others. If the 
1451
   *                 format is not supplied by the caller, the CN service 
1452
   *                 will use a default identifier format, which may change 
1453
   *                 over time.
1454
   * 
1455
   * @return true if the registration succeeds
1456
   * 
1457
   * @throws InvalidToken
1458
   * @throws ServiceFailure
1459
   * @throws NotAuthorized
1460
   * @throws IdentifierNotUnique
1461
   * @throws NotImplemented
1462
   */
1463
  @Override
1464
  public Identifier reserveIdentifier(Session session, Identifier pid)
1465
  throws InvalidToken, ServiceFailure,
1466
        NotAuthorized, IdentifierNotUnique, NotImplemented, InvalidRequest {
1467

    
1468
    throw new NotImplemented("4191", "reserveIdentifier not implemented on this node");
1469
  }
1470
  
1471
  @Override
1472
  public Identifier generateIdentifier(Session session, String scheme, String fragment)
1473
  throws InvalidToken, ServiceFailure,
1474
        NotAuthorized, NotImplemented, InvalidRequest {
1475
    throw new NotImplemented("4191", "generateIdentifier not implemented on this node");
1476
  }
1477
  
1478
  /**
1479
    * Checks whether the pid is reserved by the subject in the session param
1480
    * If the reservation is held on the pid by the subject, we return true.
1481
    * 
1482
   * @param session - the Session object containing the Subject
1483
   * @param pid - The identifier to check
1484
   * 
1485
   * @return true if the reservation exists for the subject/pid
1486
   * 
1487
   * @throws InvalidToken
1488
   * @throws ServiceFailure
1489
   * @throws NotFound - when the pid is not found (in use or in reservation)
1490
   * @throws NotAuthorized - when the subject does not hold a reservation on the pid
1491
   * @throws IdentifierNotUnique - when the pid is in use
1492
   * @throws NotImplemented
1493
   */
1494

    
1495
  @Override
1496
  public boolean hasReservation(Session session, Subject subject, Identifier pid) 
1497
      throws InvalidToken, ServiceFailure, NotFound, NotAuthorized, IdentifierNotUnique, 
1498
      NotImplemented, InvalidRequest {
1499
  
1500
      throw new NotImplemented("4191", "hasReservation not implemented on this node");
1501
  }
1502

    
1503
  /**
1504
   * Changes ownership (RightsHolder) of the specified object to the 
1505
   * subject specified by userId
1506
    * 
1507
   * @param session - the Session object containing the credentials for the Subject
1508
   * @param pid - Identifier of the object to be modified
1509
   * @param userId - The subject that will be taking ownership of the specified object.
1510
   *
1511
   * @return pid - the identifier of the modified object
1512
   * 
1513
   * @throws ServiceFailure
1514
   * @throws InvalidToken
1515
   * @throws NotFound
1516
   * @throws NotAuthorized
1517
   * @throws NotImplemented
1518
   * @throws InvalidRequest
1519
   */  
1520
  @Override
1521
  public Identifier setRightsHolder(Session session, Identifier pid, Subject userId,
1522
      long serialVersion)
1523
      throws InvalidToken, ServiceFailure, NotFound, NotAuthorized,
1524
      NotImplemented, InvalidRequest, VersionMismatch {
1525
      
1526
      // The lock to be used for this identifier
1527
      Lock lock = null;
1528

    
1529
      // get the subject
1530
      Subject subject = session.getSubject();
1531
      
1532
      String serviceFailureCode = "4490";
1533
      Identifier sid = getPIDForSID(pid, serviceFailureCode);
1534
      if(sid != null) {
1535
          pid = sid;
1536
      }
1537
      
1538
      // are we allowed to do this?
1539
      if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
1540
          throw new NotAuthorized("4440", "not allowed by "
1541
                  + subject.getValue() + " on " + pid.getValue());
1542
          
1543
      }
1544
      
1545
      SystemMetadata systemMetadata = null;
1546
      try {
1547
          lock = HazelcastService.getInstance().getLock(pid.getValue());
1548
          lock.lock();
1549
          logMetacat.debug("Locked identifier " + pid.getValue());
1550

    
1551
          try {
1552
              systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1553
              
1554
              // does the request have the most current system metadata?
1555
              if ( systemMetadata.getSerialVersion().longValue() != serialVersion ) {
1556
                 String msg = "The requested system metadata version number " + 
1557
                     serialVersion + " differs from the current version at " +
1558
                     systemMetadata.getSerialVersion().longValue() +
1559
                     ". Please get the latest copy in order to modify it.";
1560
                 throw new VersionMismatch("4443", msg);
1561
              }
1562
              
1563
          } catch (RuntimeException e) { // Catch is generic since HZ throws RuntimeException
1564
              throw new NotFound("4460", "No record found for: " + pid.getValue());
1565
              
1566
          }
1567
              
1568
          // set the new rights holder
1569
          systemMetadata.setRightsHolder(userId);
1570
          
1571
          // update the metadata
1572
          try {
1573
              systemMetadata.setSerialVersion(systemMetadata.getSerialVersion().add(BigInteger.ONE));
1574
              systemMetadata.setDateSysMetadataModified(Calendar.getInstance().getTime());
1575
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, systemMetadata);
1576
              notifyReplicaNodes(systemMetadata);
1577
              
1578
          } catch (RuntimeException e) {
1579
              throw new ServiceFailure("4490", e.getMessage());
1580
          
1581
          }
1582
          
1583
      } catch (RuntimeException e) {
1584
          throw new ServiceFailure("4490", e.getMessage());
1585
          
1586
      } finally {
1587
          lock.unlock();
1588
          logMetacat.debug("Unlocked identifier " + pid.getValue());
1589
      
1590
      }
1591
      
1592
      return pid;
1593
  }
1594

    
1595
  /**
1596
   * Verify that a replication task is authorized by comparing the target node's
1597
   * Subject (from the X.509 certificate-derived Session) with the list of 
1598
   * subjects in the known, pending replication tasks map.
1599
   * 
1600
   * @param originatingNodeSession - Session information that contains the 
1601
   *                                 identity of the calling user
1602
   * @param targetNodeSubject - Subject identifying the target node
1603
   * @param pid - the identifier of the object to be replicated
1604
   * @param replicatePermission - the execute permission to be granted
1605
   * 
1606
   * @throws ServiceFailure
1607
   * @throws NotImplemented
1608
   * @throws InvalidToken
1609
   * @throws NotAuthorized
1610
   * @throws InvalidRequest
1611
   * @throws NotFound
1612
   */
1613
  @Override
1614
  public boolean isNodeAuthorized(Session originatingNodeSession, 
1615
    Subject targetNodeSubject, Identifier pid) 
1616
    throws NotImplemented, NotAuthorized, InvalidToken, ServiceFailure, 
1617
    NotFound, InvalidRequest {
1618
    
1619
    boolean isAllowed = false;
1620
    SystemMetadata sysmeta = null;
1621
    NodeReference targetNode = null;
1622
    
1623
    try {
1624
      // get the target node reference from the nodes list
1625
      CNode cn = D1Client.getCN();
1626
      List<Node> nodes = cn.listNodes().getNodeList();
1627
      
1628
      if ( nodes != null ) {
1629
        for (Node node : nodes) {
1630
            
1631
        	if (node.getSubjectList() != null) {
1632
        		
1633
	            for (Subject nodeSubject : node.getSubjectList()) {
1634
	            	
1635
	                if ( nodeSubject.equals(targetNodeSubject) ) {
1636
	                    targetNode = node.getIdentifier();
1637
	                    logMetacat.debug("targetNode is : " + targetNode.getValue());
1638
	                    break;
1639
	                }
1640
	            }
1641
        	}
1642
            
1643
            if ( targetNode != null) { break; }
1644
        }
1645
        
1646
      } else {
1647
          String msg = "Couldn't get the node list from the CN";
1648
          logMetacat.debug(msg);
1649
          throw new ServiceFailure("4872", msg);
1650
          
1651
      }
1652
      
1653
      // can't find a node listed with the given subject
1654
      if ( targetNode == null ) {
1655
          String msg = "There is no Member Node registered with a node subject " +
1656
              "matching " + targetNodeSubject.getValue();
1657
          logMetacat.info(msg);
1658
          throw new NotAuthorized("4871", msg);
1659
          
1660
      }
1661
      
1662
      logMetacat.debug("Getting system metadata for identifier " + pid.getValue());
1663
      
1664
      sysmeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1665

    
1666
      if ( sysmeta != null ) {
1667
          
1668
          List<Replica> replicaList = sysmeta.getReplicaList();
1669
          
1670
          if ( replicaList != null ) {
1671
              
1672
              // find the replica with the status set to 'requested'
1673
              for (Replica replica : replicaList) {
1674
                  ReplicationStatus status = replica.getReplicationStatus();
1675
                  NodeReference listedNode = replica.getReplicaMemberNode();
1676
                  if ( listedNode != null && targetNode != null ) {
1677
                      logMetacat.debug("Comparing " + listedNode.getValue()
1678
                              + " to " + targetNode.getValue());
1679
                      
1680
                      if (listedNode.getValue().equals(targetNode.getValue())
1681
                              && status.equals(ReplicationStatus.REQUESTED)) {
1682
                          isAllowed = true;
1683
                          break;
1684

    
1685
                      }
1686
                  }
1687
              }
1688
          }
1689
          logMetacat.debug("The " + targetNode.getValue() + " is allowed " +
1690
              "to replicate: " + isAllowed + " for " + pid.getValue());
1691

    
1692
          
1693
      } else {
1694
          logMetacat.debug("System metadata for identifier " + pid.getValue() +
1695
          " is null.");
1696
          String error ="";
1697
          String localId = null;
1698
          try {
1699
              localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1700
            
1701
           } catch (Exception e) {
1702
              logMetacat.warn("Couldn't find the local id for the pid "+pid.getValue());
1703
          }
1704
          
1705
          if(localId != null && EventLog.getInstance().isDeleted(localId)) {
1706
              error = DELETEDMESSAGE;
1707
          } else if (localId == null && EventLog.getInstance().isDeleted(pid.getValue())) {
1708
              error = DELETEDMESSAGE;
1709
          }
1710
          throw new NotFound("4874", "Couldn't find an object identified by " + pid.getValue()+". "+error);
1711
          
1712
      }
1713

    
1714
    } catch (RuntimeException e) {
1715
    	  ServiceFailure sf = new ServiceFailure("4872", 
1716
                "Runtime Exception: Couldn't determine if node is allowed: " + 
1717
                e.getMessage());
1718
    	  sf.initCause(e);
1719
        throw sf;
1720
        
1721
    }
1722
      
1723
    return isAllowed;
1724
    
1725
  }
1726

    
1727
  /**
1728
   * Adds a new object to the Node, where the object is a science metadata object.
1729
   * 
1730
   * @param session - the Session object containing the credentials for the Subject
1731
   * @param pid - The object identifier to be created
1732
   * @param object - the object bytes
1733
   * @param sysmeta - the system metadata that describes the object  
1734
   * 
1735
   * @return pid - the object identifier created
1736
   * 
1737
   * @throws InvalidToken
1738
   * @throws ServiceFailure
1739
   * @throws NotAuthorized
1740
   * @throws IdentifierNotUnique
1741
   * @throws UnsupportedType
1742
   * @throws InsufficientResources
1743
   * @throws InvalidSystemMetadata
1744
   * @throws NotImplemented
1745
   * @throws InvalidRequest
1746
   */
1747
  public Identifier create(Session session, Identifier pid, InputStream object,
1748
    SystemMetadata sysmeta) 
1749
    throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
1750
    UnsupportedType, InsufficientResources, InvalidSystemMetadata, 
1751
    NotImplemented, InvalidRequest {
1752
       
1753
   // verify the pid is valid format
1754
      if (!isValidIdentifier(pid)) {
1755
          throw new InvalidRequest("4891", "The provided identifier is invalid.");
1756
      }
1757
      // The lock to be used for this identifier
1758
      Lock lock = null;
1759

    
1760
      try {
1761
          lock = HazelcastService.getInstance().getLock(pid.getValue());
1762
          lock.lock();
1763
          // are we allowed?
1764
          boolean isAllowed = false;
1765
          isAllowed = isAdminAuthorized(session);
1766
          
1767
          // additional check if it is the authoritative node if it is not the admin
1768
          if(!isAllowed) {
1769
              isAllowed = isAuthoritativeMNodeAdmin(session, pid);
1770
          }
1771

    
1772
          // proceed if we're called by a CN
1773
          if ( isAllowed ) {
1774
              //check if the series id is legitimate. It uses the same rules of the method registerSystemMetadata
1775
              //checkSidInModifyingSystemMetadata(sysmeta, "4896", "4893");
1776
              Identifier sid = sysmeta.getSeriesId();
1777
              if(sid != null) {
1778
                  if (!isValidIdentifier(sid)) {
1779
                      throw new InvalidRequest("4891", "The series id in the system metadata is invalid in the request.");
1780
                  }
1781
              }
1782
              // create the coordinating node version of the document      
1783
              logMetacat.debug("Locked identifier " + pid.getValue());
1784
              sysmeta.setSerialVersion(BigInteger.ONE);
1785
              sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1786
              //sysmeta.setArchived(false); // this is a create op, not update
1787
              
1788
              // the CN should have set the origin and authoritative member node fields
1789
              try {
1790
                  sysmeta.getOriginMemberNode().getValue();
1791
                  sysmeta.getAuthoritativeMemberNode().getValue();
1792
                  
1793
              } catch (NullPointerException npe) {
1794
                  throw new InvalidSystemMetadata("4896", 
1795
                      "Both the origin and authoritative member node identifiers need to be set.");
1796
                  
1797
              }
1798
              pid = super.create(session, pid, object, sysmeta);
1799

    
1800
          } else {
1801
              String msg = "The subject listed as " + session.getSubject().getValue() + 
1802
                  " isn't allowed to call create() on a Coordinating Node.";
1803
              logMetacat.info(msg);
1804
              throw new NotAuthorized("1100", msg);
1805
          }
1806
          
1807
      } catch (RuntimeException e) {
1808
          // Convert Hazelcast runtime exceptions to service failures
1809
          String msg = "There was a problem creating the object identified by " +
1810
              pid.getValue() + ". There error message was: " + e.getMessage();
1811
          throw new ServiceFailure("4893", msg);
1812
          
1813
      } finally {
1814
    	  if (lock != null) {
1815
	          lock.unlock();
1816
	          logMetacat.debug("Unlocked identifier " + pid.getValue());
1817
    	  }
1818
      }
1819
      
1820
      return pid;
1821

    
1822
  }
1823

    
1824
  /**
1825
   * Set access for a given object using the object identifier and a Subject
1826
   * under a given Session.
1827
   * This method only applies the objects whose authoritative mn is a v1 node.
1828
   * @param session - the Session object containing the credentials for the Subject
1829
   * @param pid - the object identifier for the given object to apply the policy
1830
   * @param policy - the access policy to be applied
1831
   * 
1832
   * @return true if the application of the policy succeeds
1833
   * @throws InvalidToken
1834
   * @throws ServiceFailure
1835
   * @throws NotFound
1836
   * @throws NotAuthorized
1837
   * @throws NotImplemented
1838
   * @throws InvalidRequest
1839
   */
1840
  public boolean setAccessPolicy(Session session, Identifier pid, 
1841
      AccessPolicy accessPolicy, long serialVersion) 
1842
      throws InvalidToken, ServiceFailure, NotFound, NotAuthorized, 
1843
      NotImplemented, InvalidRequest, VersionMismatch {
1844
      
1845
   // do we have a valid pid?
1846
      if (pid == null || pid.getValue().trim().equals("")) {
1847
          throw new InvalidRequest("4402", "The provided identifier was invalid.");
1848
          
1849
      }
1850
      
1851
      String serviceFailureCode = "4430";
1852
      Identifier sid = getPIDForSID(pid, serviceFailureCode);
1853
      if(sid != null) {
1854
          pid = sid;
1855
      }
1856
      // The lock to be used for this identifier
1857
      Lock lock = null;
1858
      SystemMetadata systemMetadata = null;
1859
      
1860
      boolean success = false;
1861
      
1862
      // get the subject
1863
      Subject subject = session.getSubject();
1864
      
1865
      // are we allowed to do this?
1866
      if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
1867
          throw new NotAuthorized("4420", "not allowed by "
1868
                  + subject.getValue() + " on " + pid.getValue());
1869
      }
1870
      
1871
      try {
1872
          lock = HazelcastService.getInstance().getLock(pid.getValue());
1873
          lock.lock();
1874
          logMetacat.debug("Locked identifier " + pid.getValue());
1875

    
1876
          try {
1877
              systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1878

    
1879
              if ( systemMetadata == null ) {
1880
                  throw new NotFound("4400", "Couldn't find an object identified by " + pid.getValue());
1881
                  
1882
              }
1883
              // does the request have the most current system metadata?
1884
              if ( systemMetadata.getSerialVersion().longValue() != serialVersion ) {
1885
                 String msg = "The requested system metadata version number " + 
1886
                     serialVersion + " differs from the current version at " +
1887
                     systemMetadata.getSerialVersion().longValue() +
1888
                     ". Please get the latest copy in order to modify it.";
1889
                 throw new VersionMismatch("4402", msg);
1890
                 
1891
              }
1892
              
1893
              D1NodeVersionChecker checker = new D1NodeVersionChecker(systemMetadata.getAuthoritativeMemberNode());
1894
              String version = checker.getVersion("MNStorage");
1895
              if(version == null) {
1896
                  throw new ServiceFailure("4430", "Couldn't determine the version of the MNStorge for the "+pid.getValue());
1897
              } else if (version.equalsIgnoreCase(D1NodeVersionChecker.V2)) {
1898
                  //we don't apply this method to an object whose authoritative node is v2
1899
                  throw new NotAuthorized("4420", V2V1MISSMATCH);
1900
              } else if (!version.equalsIgnoreCase(D1NodeVersionChecker.V1)) {
1901
                  //we don't understand this version (it is not v1 or v2)
1902
                  throw new InvalidRequest("4402", "The version of the MNStorage is "+version+" for the authoritative member node of the object "+pid.getValue()+". We don't support it.");
1903
              }
1904
              
1905
          } catch (RuntimeException e) {
1906
              // convert Hazelcast RuntimeException to NotFound
1907
              throw new NotFound("4400", "No record found for: " + pid);
1908
            
1909
          }
1910
              
1911
          // set the access policy
1912
          systemMetadata.setAccessPolicy(accessPolicy);
1913
          
1914
          // update the system metadata
1915
          try {
1916
              systemMetadata.setSerialVersion(systemMetadata.getSerialVersion().add(BigInteger.ONE));
1917
              systemMetadata.setDateSysMetadataModified(Calendar.getInstance().getTime());
1918
              HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
1919
              notifyReplicaNodes(systemMetadata);
1920
              
1921
          } catch (RuntimeException e) {
1922
              // convert Hazelcast RuntimeException to ServiceFailure
1923
              throw new ServiceFailure("4430", e.getMessage());
1924
            
1925
          }
1926
          
1927
      } catch (RuntimeException e) {
1928
          throw new ServiceFailure("4430", e.getMessage());
1929
          
1930
      } finally {
1931
          lock.unlock();
1932
          logMetacat.debug("Unlocked identifier " + pid.getValue());
1933
        
1934
      }
1935

    
1936
    
1937
    // TODO: how do we know if the map was persisted?
1938
    success = true;
1939
    
1940
    return success;
1941
  }
1942

    
1943
  /**
1944
   * Full replacement of replication metadata in the system metadata for the 
1945
   * specified object, changes date system metadata modified
1946
   * 
1947
   * @param session - the Session object containing the credentials for the Subject
1948
   * @param pid - the object identifier for the given object to apply the policy
1949
   * @param replica - the replica to be updated
1950
   * @return
1951
   * @throws NotImplemented
1952
   * @throws NotAuthorized
1953
   * @throws ServiceFailure
1954
   * @throws InvalidRequest
1955
   * @throws NotFound
1956
   * @throws VersionMismatch
1957
   */
1958
  @Override
1959
  public boolean updateReplicationMetadata(Session session, Identifier pid,
1960
      Replica replica, long serialVersion) 
1961
      throws NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest,
1962
      NotFound, VersionMismatch {
1963
      
1964
      // The lock to be used for this identifier
1965
      Lock lock = null;
1966
      
1967
      // get the subject
1968
      Subject subject = session.getSubject();
1969
      
1970
      // are we allowed to do this?
1971
      if(session == null) {
1972
          throw new NotAuthorized("4851", "Session cannot be null. It is not authorized for updating the replication metadata of the object "+pid.getValue());
1973
      } else {
1974
          if(!isCNAdmin(session)) {
1975
              throw new NotAuthorized("4851", "The client -"+ session.getSubject().getValue()+ "is not a CN and is not authorized for updating the replication metadata of the object "+pid.getValue());
1976
        }
1977
      }
1978
      /*try {
1979

    
1980
          // what is the controlling permission?
1981
          if (!isAuthorized(session, pid, Permission.WRITE)) {
1982
              throw new NotAuthorized("4851", "not allowed by "
1983
                      + subject.getValue() + " on " + pid.getValue());
1984
          }
1985

    
1986
        
1987
      } catch (InvalidToken e) {
1988
          throw new NotAuthorized("4851", "not allowed by " + subject.getValue() + 
1989
                  " on " + pid.getValue());  
1990
          
1991
      }*/
1992

    
1993
      SystemMetadata systemMetadata = null;
1994
      try {
1995
          lock = HazelcastService.getInstance().getLock(pid.getValue());
1996
          lock.lock();
1997
          logMetacat.debug("Locked identifier " + pid.getValue());
1998

    
1999
          try {      
2000
              systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
2001

    
2002
              // does the request have the most current system metadata?
2003
              if ( systemMetadata.getSerialVersion().longValue() != serialVersion ) {
2004
                 String msg = "The requested system metadata version number " + 
2005
                     serialVersion + " differs from the current version at " +
2006
                     systemMetadata.getSerialVersion().longValue() +
2007
                     ". Please get the latest copy in order to modify it.";
2008
                 throw new VersionMismatch("4855", msg);
2009
              }
2010
              
2011
          } catch (RuntimeException e) { // Catch is generic since HZ throws RuntimeException
2012
              throw new NotFound("4854", "No record found for: " + pid.getValue() +
2013
                  " : " + e.getMessage());
2014
            
2015
          }
2016
              
2017
          // set the status for the replica
2018
          List<Replica> replicas = systemMetadata.getReplicaList();
2019
          NodeReference replicaNode = replica.getReplicaMemberNode();
2020
          ReplicationStatus replicaStatus = replica.getReplicationStatus();
2021
          int index = 0;
2022
          for (Replica listedReplica: replicas) {
2023
              
2024
              // remove the replica that we are replacing
2025
              if ( replicaNode.getValue().equals(listedReplica.getReplicaMemberNode().getValue())) {
2026
                      // don't allow status to change from COMPLETED to anything other
2027
                      // than INVALIDATED: prevents overwrites from race conditions
2028
                	  if ( !listedReplica.getReplicationStatus().equals(replicaStatus) && 
2029
                	       listedReplica.getReplicationStatus().equals(ReplicationStatus.COMPLETED) &&
2030
            		       !replicaStatus.equals(ReplicationStatus.INVALIDATED) ) {
2031
                	  throw new InvalidRequest("4853", "Status state change from " +
2032
                			  listedReplica.getReplicationStatus() + " to " +
2033
                			  replicaStatus.toString() + "is prohibited for identifier " +
2034
                			  pid.getValue() + " and target node " + 
2035
                			  listedReplica.getReplicaMemberNode().getValue());
2036

    
2037
            	  }
2038
                  replicas.remove(index);
2039
                  break;
2040
                  
2041
              }
2042
              index++;
2043
          }
2044
          
2045
          // add the new replica item
2046
          replicas.add(replica);
2047
          systemMetadata.setReplicaList(replicas);
2048
          
2049
          // update the metadata
2050
          try {
2051
              systemMetadata.setSerialVersion(systemMetadata.getSerialVersion().add(BigInteger.ONE));
2052
              // Based on CN behavior discussion 9/16/15, we no longer want to 
2053
              // update the modified date for changes to the replica list
2054
              //systemMetadata.setDateSysMetadataModified(Calendar.getInstance().getTime());
2055
              HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
2056
              
2057
              // inform replica nodes of the change if the status is complete
2058
              if ( replicaStatus.equals(ReplicationStatus.COMPLETED) ) {
2059
            	  notifyReplicaNodes(systemMetadata);
2060
            	  
2061
              }
2062
          } catch (RuntimeException e) {
2063
              logMetacat.info("Unknown RuntimeException thrown: " + e.getCause().getMessage());
2064
              throw new ServiceFailure("4852", e.getMessage());
2065
          
2066
          }
2067
          
2068
      } catch (RuntimeException e) {
2069
          logMetacat.info("Unknown RuntimeException thrown: " + e.getCause().getMessage());
2070
          throw new ServiceFailure("4852", e.getMessage());
2071
      
2072
      } finally {
2073
          lock.unlock();
2074
          logMetacat.debug("Unlocked identifier " + pid.getValue());
2075
          
2076
      }
2077
    
2078
      return true;
2079
      
2080
  }
2081
  
2082
  /**
2083
   * 
2084
   */
2085
  @Override
2086
  public ObjectList listObjects(Session session, Date startTime, 
2087
      Date endTime, ObjectFormatIdentifier formatid, NodeReference nodeId,Identifier identifier,
2088
      Integer start, Integer count)
2089
      throws InvalidRequest, InvalidToken, NotAuthorized, NotImplemented,
2090
      ServiceFailure {
2091

    
2092
      return super.listObjects(session, startTime, endTime, formatid, identifier, nodeId, start, count);
2093
  }
2094

    
2095
  
2096
 	/**
2097
 	 * Returns a list of checksum algorithms that are supported by DataONE.
2098
 	 * @return cal  the list of checksum algorithms
2099
 	 * 
2100
 	 * @throws ServiceFailure
2101
 	 * @throws NotImplemented
2102
 	 */
2103
  @Override
2104
  public ChecksumAlgorithmList listChecksumAlgorithms()
2105
			throws ServiceFailure, NotImplemented {
2106
		ChecksumAlgorithmList cal = new ChecksumAlgorithmList();
2107
		cal.addAlgorithm("MD5");
2108
		cal.addAlgorithm("SHA-1");
2109
		return cal;
2110
		
2111
	}
2112

    
2113
  /**
2114
   * Notify replica Member Nodes of system metadata changes for a given pid
2115
   * 
2116
   * @param currentSystemMetadata - the up to date system metadata
2117
   */
2118
  public void notifyReplicaNodes(SystemMetadata currentSystemMetadata) {
2119
      
2120
      Session session = null;
2121
      List<Replica> replicaList = currentSystemMetadata.getReplicaList();
2122
      //MNode mn = null;
2123
      NodeReference replicaNodeRef = null;
2124
      CNode cn = null;
2125
      NodeType nodeType = null;
2126
      List<Node> nodeList = null;
2127
      
2128
      try {
2129
          cn = D1Client.getCN();
2130
          nodeList = cn.listNodes().getNodeList();
2131
          
2132
      } catch (Exception e) { // handle BaseException and other I/O issues
2133
          
2134
          // swallow errors since the call is not critical
2135
          logMetacat.error("Can't inform MNs of system metadata changes due " +
2136
              "to communication issues with the CN: " + e.getMessage());
2137
          
2138
      }
2139
      
2140
      if ( replicaList != null ) {
2141
          
2142
          // iterate through the replicas and inform  MN replica nodes
2143
          for (Replica replica : replicaList) {
2144
              String replicationVersion = null;
2145
              replicaNodeRef = replica.getReplicaMemberNode();
2146
              try {
2147
                  if (nodeList != null) {
2148
                      // find the node type
2149
                      for (Node node : nodeList) {
2150
                          if ( node.getIdentifier().getValue().equals(replicaNodeRef.getValue()) ) {
2151
                              nodeType = node.getType();
2152
                              D1NodeVersionChecker checker = new D1NodeVersionChecker(replicaNodeRef);
2153
                              replicationVersion = checker.getVersion("MNRead");
2154
                              break;
2155
              
2156
                          }
2157
                      }
2158
                  }
2159
              
2160
                  // notify only MNs
2161
                  if (replicationVersion != null && nodeType != null && nodeType == NodeType.MN) {
2162
                      if(replicationVersion.equalsIgnoreCase(D1NodeVersionChecker.V2)) {
2163
                          //connect to a v2 mn
2164
                          MNode mn = D1Client.getMN(replicaNodeRef);
2165
                          mn.systemMetadataChanged(session, 
2166
                              currentSystemMetadata.getIdentifier(), 
2167
                              currentSystemMetadata.getSerialVersion().longValue(),
2168
                              currentSystemMetadata.getDateSysMetadataModified());
2169
                      } else if (replicationVersion.equalsIgnoreCase(D1NodeVersionChecker.V1)) {
2170
                          //connect to a v1 mn
2171
                          org.dataone.client.v1.MNode mn = org.dataone.client.v1.itk.D1Client.getMN(replicaNodeRef);
2172
                          mn.systemMetadataChanged(session, 
2173
                                  currentSystemMetadata.getIdentifier(), 
2174
                                  currentSystemMetadata.getSerialVersion().longValue(),
2175
                                  currentSystemMetadata.getDateSysMetadataModified());
2176
                      }
2177
                      
2178
                  }
2179
              
2180
              } catch (Exception e) { // handle BaseException and other I/O issues
2181
              
2182
                  // swallow errors since the call is not critical
2183
                  logMetacat.error("Can't inform "
2184
                          + replicaNodeRef.getValue()
2185
                          + " of system metadata changes due "
2186
                          + "to communication issues with the CN: "
2187
                          + e.getMessage());
2188
              
2189
              }
2190
          }
2191
      }
2192
  }
2193
  
2194
  /**
2195
   * Update the system metadata of the specified pid.
2196
   * Note: the serial version and the replica list in the new system metadata will be ignored and the old values will be kept.
2197
   */
2198
  @Override
2199
  public boolean updateSystemMetadata(Session session, Identifier pid,
2200
          SystemMetadata sysmeta) throws NotImplemented, NotAuthorized,
2201
          ServiceFailure, InvalidRequest, InvalidSystemMetadata, InvalidToken {
2202
   if(sysmeta == null) {
2203
       throw  new InvalidRequest("4863", "The system metadata object should NOT be null in the updateSystemMetadata request.");
2204
   }
2205
   if(pid == null || pid.getValue() == null) {
2206
       throw new InvalidRequest("4863", "Please specify the id in the updateSystemMetadata request ") ;
2207
   }
2208

    
2209
   if (session == null) {
2210
       //TODO: many of the thrown exceptions do not use the correct error codes
2211
       //check these against the docs and correct them
2212
       throw new NotAuthorized("4861", "No Session - could not authorize for updating system metadata." +
2213
               "  If you are not logged in, please do so and retry the request.");
2214
   } else {
2215
         //only CN is allwoed
2216
         if(!isCNAdmin(session)) {
2217
               throw new NotAuthorized("4861", "The client -"+ session.getSubject().getValue()+ "is not authorized for updating the system metadata of the object "+pid.getValue());
2218
         }
2219
   }
2220

    
2221
    //update the system metadata locally
2222
    boolean success = false;
2223
    try {
2224
        HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
2225
        SystemMetadata currentSysmeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
2226
       
2227
        if(currentSysmeta == null) {
2228
            throw  new InvalidRequest("4863", "We can't find the current system metadata on the member node for the id "+pid.getValue());
2229
        }
2230
        // CN will ignore the comming serial version and replica list fields from the mn node. 
2231
        BigInteger currentSerialVersion = currentSysmeta.getSerialVersion();
2232
        sysmeta.setSerialVersion(currentSerialVersion);
2233
        List<Replica> replicas = currentSysmeta.getReplicaList();
2234
        sysmeta.setReplicaList(replicas);
2235
        boolean needUpdateModificationDate = false;//cn doesn't need to change the modification date.
2236
        boolean fromCN = true;
2237
        success = updateSystemMetadata(session, pid, sysmeta, needUpdateModificationDate, currentSysmeta, fromCN);
2238
    } finally {
2239
        HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
2240
    }
2241
    return success;
2242
  }
2243
  
2244
    @Override
2245
    public boolean synchronize(Session session, Identifier pid) throws NotAuthorized, InvalidRequest, NotImplemented{
2246
        throw new NotImplemented("0000", "CN query services are not implemented in Metacat.");
2247

    
2248
    }
2249

    
2250
	@Override
2251
	public QueryEngineDescription getQueryEngineDescription(Session session,
2252
			String queryEngine) throws InvalidToken, ServiceFailure, NotAuthorized,
2253
			NotImplemented, NotFound {
2254
		throw new NotImplemented("0000", "CN query services are not implemented in Metacat.");
2255

    
2256
	}
2257
	
2258
	@Override
2259
	public QueryEngineList listQueryEngines(Session session) throws InvalidToken,
2260
			ServiceFailure, NotAuthorized, NotImplemented {
2261
		throw new NotImplemented("0000", "CN query services are not implemented in Metacat.");
2262

    
2263
	}
2264
	
2265
	@Override
2266
	public InputStream query(Session session, String queryEngine, String query)
2267
			throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest,
2268
			NotImplemented, NotFound {
2269
		throw new NotImplemented("0000", "CN query services are not implemented in Metacat.");
2270

    
2271
	}
2272
	
2273
	@Override
2274
	public Node getCapabilities() throws NotImplemented, ServiceFailure {
2275
		throw new NotImplemented("0000", "The CN capabilities are not stored in Metacat.");
2276
	}
2277

    
2278
}
(1-1/8)