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.InputStream;
27
import java.math.BigInteger;
28
import java.util.ArrayList;
29
import java.util.Calendar;
30
import java.util.Date;
31
import java.util.List;
32
import java.util.concurrent.locks.Lock;
33

    
34
import javax.servlet.http.HttpServletRequest;
35

    
36
import org.apache.log4j.Logger;
37
import org.dataone.client.CNode;
38
import org.dataone.client.D1Client;
39
import org.dataone.service.cn.v1.CNAuthorization;
40
import org.dataone.service.cn.v1.CNCore;
41
import org.dataone.service.cn.v1.CNRead;
42
import org.dataone.service.cn.v1.CNReplication;
43
import org.dataone.service.exceptions.BaseException;
44
import org.dataone.service.exceptions.IdentifierNotUnique;
45
import org.dataone.service.exceptions.InsufficientResources;
46
import org.dataone.service.exceptions.InvalidRequest;
47
import org.dataone.service.exceptions.InvalidSystemMetadata;
48
import org.dataone.service.exceptions.InvalidToken;
49
import org.dataone.service.exceptions.NotAuthorized;
50
import org.dataone.service.exceptions.NotFound;
51
import org.dataone.service.exceptions.NotImplemented;
52
import org.dataone.service.exceptions.ServiceFailure;
53
import org.dataone.service.exceptions.UnsupportedType;
54
import org.dataone.service.exceptions.VersionMismatch;
55
import org.dataone.service.types.v1.AccessPolicy;
56
import org.dataone.service.types.v1.Checksum;
57
import org.dataone.service.types.v1.ChecksumAlgorithmList;
58
import org.dataone.service.types.v1.Identifier;
59
import org.dataone.service.types.v1.Node;
60
import org.dataone.service.types.v1.NodeList;
61
import org.dataone.service.types.v1.NodeReference;
62
import org.dataone.service.types.v1.NodeType;
63
import org.dataone.service.types.v1.ObjectFormat;
64
import org.dataone.service.types.v1.ObjectFormatIdentifier;
65
import org.dataone.service.types.v1.ObjectFormatList;
66
import org.dataone.service.types.v1.ObjectList;
67
import org.dataone.service.types.v1.ObjectLocationList;
68
import org.dataone.service.types.v1.Permission;
69
import org.dataone.service.types.v1.Replica;
70
import org.dataone.service.types.v1.ReplicationPolicy;
71
import org.dataone.service.types.v1.ReplicationStatus;
72
import org.dataone.service.types.v1.Session;
73
import org.dataone.service.types.v1.Subject;
74
import org.dataone.service.types.v1.SystemMetadata;
75
import org.dataone.service.types.v1.util.ServiceMethodRestrictionUtil;
76

    
77
import edu.ucsb.nceas.metacat.EventLog;
78
import edu.ucsb.nceas.metacat.IdentifierManager;
79
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
80

    
81
/**
82
 * Represents Metacat's implementation of the DataONE Coordinating Node 
83
 * service API. Methods implement the various CN* interfaces, and methods common
84
 * to both Member Node and Coordinating Node interfaces are found in the
85
 * D1NodeService super class.
86
 *
87
 */
88
public class CNodeService extends D1NodeService implements CNAuthorization,
89
    CNCore, CNRead, CNReplication {
90

    
91
  /* the logger instance */
92
  private Logger logMetacat = null;
93

    
94
  /**
95
   * singleton accessor
96
   */
97
  public static CNodeService getInstance(HttpServletRequest request) { 
98
    return new CNodeService(request);
99
  }
100
  
101
  /**
102
   * Constructor, private for singleton access
103
   */
104
  private CNodeService(HttpServletRequest request) {
105
    super(request);
106
    logMetacat = Logger.getLogger(CNodeService.class);
107
        
108
  }
109
    
110
  /**
111
   * Set the replication policy for an object given the object identifier
112
   * 
113
   * @param session - the Session object containing the credentials for the Subject
114
   * @param pid - the object identifier for the given object
115
   * @param policy - the replication policy to be applied
116
   * 
117
   * @return true or false
118
   * 
119
   * @throws NotImplemented
120
   * @throws NotAuthorized
121
   * @throws ServiceFailure
122
   * @throws InvalidRequest
123
   * @throws VersionMismatch
124
   * 
125
   */
126
  @Override
127
  public boolean setReplicationPolicy(Session session, Identifier pid,
128
      ReplicationPolicy policy, long serialVersion) 
129
      throws NotImplemented, NotFound, NotAuthorized, ServiceFailure, 
130
      InvalidRequest, InvalidToken, VersionMismatch {
131
      
132
      // The lock to be used for this identifier
133
      Lock lock = null;
134
      
135
      // get the subject
136
      Subject subject = session.getSubject();
137
      
138
      // are we allowed to do this?
139
      if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
140
          throw new NotAuthorized("4881", Permission.CHANGE_PERMISSION
141
                  + " not allowed by " + subject.getValue() + " on "
142
                  + pid.getValue());
143
          
144
      }
145
      
146
      SystemMetadata systemMetadata = null;
147
      try {
148
          lock = HazelcastService.getInstance().getLock(pid.getValue());
149
          lock.lock();
150
          logMetacat.debug("Locked identifier " + pid.getValue());
151

    
152
          try {
153
              if ( HazelcastService.getInstance().getSystemMetadataMap().containsKey(pid) ) {
154
                  systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
155
                  
156
              }
157
              
158
              // did we get it correctly?
159
              if ( systemMetadata == null ) {
160
                  throw new NotFound("4884", "Couldn't find an object identified by " + pid.getValue());
161
                  
162
              }
163

    
164
              // does the request have the most current system metadata?
165
              if ( systemMetadata.getSerialVersion().longValue() != serialVersion ) {
166
                 String msg = "The requested system metadata version number " + 
167
                     serialVersion + " differs from the current version at " +
168
                     systemMetadata.getSerialVersion().longValue() +
169
                     ". Please get the latest copy in order to modify it.";
170
                 throw new VersionMismatch("4886", msg);
171
                 
172
              }
173
              
174
          } catch (RuntimeException e) { // Catch is generic since HZ throws RuntimeException
175
              throw new NotFound("4884", "No record found for: " + pid.getValue());
176
            
177
          }
178
          
179
          // set the new policy
180
          systemMetadata.setReplicationPolicy(policy);
181
          
182
          // update the metadata
183
          try {
184
              systemMetadata.setSerialVersion(systemMetadata.getSerialVersion().add(BigInteger.ONE));
185
              systemMetadata.setDateSysMetadataModified(Calendar.getInstance().getTime());
186
              HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
187
            
188
          } catch (RuntimeException e) {
189
              throw new ServiceFailure("4882", e.getMessage());
190
          
191
          }
192
          
193
      } catch (RuntimeException e) {
194
          throw new ServiceFailure("4882", e.getMessage());
195
          
196
      } finally {
197
          lock.unlock();
198
          logMetacat.debug("Unlocked identifier " + pid.getValue());
199
          
200
      }
201
    
202
      return true;
203
  }
204

    
205
  /**
206
   * Deletes the replica from the given Member Node
207
   * NOTE: MN.delete() may be an "archive" operation. TBD.
208
   * @param session
209
   * @param pid
210
   * @param nodeId
211
   * @param serialVersion
212
   * @return
213
   * @throws InvalidToken
214
   * @throws ServiceFailure
215
   * @throws NotAuthorized
216
   * @throws NotFound
217
   * @throws NotImplemented
218
   * @throws VersionMismatch
219
   */
220
  @Override
221
  public boolean deleteReplicationMetadata(Session session, Identifier pid, NodeReference nodeId, long serialVersion) 
222
  	throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, VersionMismatch {
223
	  
224
	  	// The lock to be used for this identifier
225
		Lock lock = null;
226

    
227
		// get the subject
228
		Subject subject = session.getSubject();
229

    
230
		// are we allowed to do this?
231
		boolean isAuthorized = false;
232
		try {
233
			isAuthorized = isAuthorized(session, pid, Permission.WRITE);
234
		} catch (InvalidRequest e) {
235
			throw new ServiceFailure("4882", e.getDescription());
236
		}
237
		if (!isAuthorized) {
238
			throw new NotAuthorized("4881", Permission.WRITE
239
					+ " not allowed by " + subject.getValue() + " on "
240
					+ pid.getValue());
241

    
242
		}
243

    
244
		SystemMetadata systemMetadata = null;
245
		try {
246
			lock = HazelcastService.getInstance().getLock(pid.getValue());
247
			lock.lock();
248
			logMetacat.debug("Locked identifier " + pid.getValue());
249

    
250
			try {
251
				if (HazelcastService.getInstance().getSystemMetadataMap().containsKey(pid)) {
252
					systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
253
				}
254

    
255
				// did we get it correctly?
256
				if (systemMetadata == null) {
257
					throw new NotFound("4884", "Couldn't find an object identified by " + pid.getValue());
258
				}
259

    
260
				// does the request have the most current system metadata?
261
				if (systemMetadata.getSerialVersion().longValue() != serialVersion) {
262
					String msg = "The requested system metadata version number "
263
							+ serialVersion
264
							+ " differs from the current version at "
265
							+ systemMetadata.getSerialVersion().longValue()
266
							+ ". Please get the latest copy in order to modify it.";
267
					throw new VersionMismatch("4886", msg);
268

    
269
				}
270

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

    
274
			}
275
			  
276
			// check permissions
277
			// TODO: is this necessary?
278
			List<Node> nodeList = D1Client.getCN().listNodes().getNodeList();
279
			boolean isAllowed = ServiceMethodRestrictionUtil.isMethodAllowed(session.getSubject(), nodeList, "CNReplication", "deleteReplicationMetadata");
280
			if (isAllowed) {
281
				throw new NotAuthorized("4881", "Caller is not authorized to deleteReplicationMetadata");
282
			}
283
			  
284
			// delete the replica from the given node
285
			D1Client.getMN(nodeId).delete(session, pid);
286
			  
287
			// reflect that change in the system metadata
288
			List<Replica> updatedReplicas = new ArrayList<Replica>(systemMetadata.getReplicaList());
289
			for (Replica r: systemMetadata.getReplicaList()) {
290
				  if (r.getReplicaMemberNode().equals(nodeId)) {
291
					  updatedReplicas.remove(r);
292
					  break;
293
				  }
294
			}
295
			systemMetadata.setReplicaList(updatedReplicas);
296

    
297
			// update the metadata
298
			try {
299
				systemMetadata.setSerialVersion(systemMetadata.getSerialVersion().add(BigInteger.ONE));
300
				systemMetadata.setDateSysMetadataModified(Calendar.getInstance().getTime());
301
				HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
302
			} catch (RuntimeException e) {
303
				throw new ServiceFailure("4882", e.getMessage());
304
			}
305

    
306
		} catch (RuntimeException e) {
307
			throw new ServiceFailure("4882", e.getMessage());
308
		} finally {
309
			lock.unlock();
310
			logMetacat.debug("Unlocked identifier " + pid.getValue());
311
		}
312

    
313
		return true;	  
314
	  
315
  }
316
  
317
  /**
318
   * Set the obsoletedBy attribute in System Metadata
319
   * @param session
320
   * @param pid
321
   * @param obsoletedByPid
322
   * @param serialVersion
323
   * @return
324
   * @throws NotImplemented
325
   * @throws NotFound
326
   * @throws NotAuthorized
327
   * @throws ServiceFailure
328
   * @throws InvalidRequest
329
   * @throws InvalidToken
330
   * @throws VersionMismatch
331
   */
332
  @Override
333
  public boolean setObsoletedBy(Session session, Identifier pid,
334
			Identifier obsoletedByPid, long serialVersion)
335
			throws NotImplemented, NotFound, NotAuthorized, ServiceFailure,
336
			InvalidRequest, InvalidToken, VersionMismatch {
337

    
338
		// The lock to be used for this identifier
339
		Lock lock = null;
340

    
341
		// get the subject
342
		Subject subject = session.getSubject();
343

    
344
		// are we allowed to do this?
345
		if (!isAuthorized(session, pid, Permission.WRITE)) {
346
			throw new NotAuthorized("4881", Permission.WRITE
347
					+ " not allowed by " + subject.getValue() + " on "
348
					+ pid.getValue());
349

    
350
		}
351

    
352

    
353
		SystemMetadata systemMetadata = null;
354
		try {
355
			lock = HazelcastService.getInstance().getLock(pid.getValue());
356
			lock.lock();
357
			logMetacat.debug("Locked identifier " + pid.getValue());
358

    
359
			try {
360
				if (HazelcastService.getInstance().getSystemMetadataMap().containsKey(pid)) {
361
					systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
362
				}
363

    
364
				// did we get it correctly?
365
				if (systemMetadata == null) {
366
					throw new NotFound("4884", "Couldn't find an object identified by " + pid.getValue());
367
				}
368

    
369
				// does the request have the most current system metadata?
370
				if (systemMetadata.getSerialVersion().longValue() != serialVersion) {
371
					String msg = "The requested system metadata version number "
372
							+ serialVersion
373
							+ " differs from the current version at "
374
							+ systemMetadata.getSerialVersion().longValue()
375
							+ ". Please get the latest copy in order to modify it.";
376
					throw new VersionMismatch("4886", msg);
377

    
378
				}
379

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

    
383
			}
384

    
385
			// set the new policy
386
			systemMetadata.setObsoletedBy(obsoletedByPid);
387

    
388
			// update the metadata
389
			try {
390
				systemMetadata.setSerialVersion(systemMetadata.getSerialVersion().add(BigInteger.ONE));
391
				systemMetadata.setDateSysMetadataModified(Calendar.getInstance().getTime());
392
				HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
393
			} catch (RuntimeException e) {
394
				throw new ServiceFailure("4882", e.getMessage());
395
			}
396

    
397
		} catch (RuntimeException e) {
398
			throw new ServiceFailure("4882", e.getMessage());
399
		} finally {
400
			lock.unlock();
401
			logMetacat.debug("Unlocked identifier " + pid.getValue());
402
		}
403

    
404
		return true;
405
	}
406
  
407
  
408
  /**
409
   * Set the replication status for an object given the object identifier
410
   * 
411
   * @param session - the Session object containing the credentials for the Subject
412
   * @param pid - the object identifier for the given object
413
   * @param status - the replication status to be applied
414
   * 
415
   * @return true or false
416
   * 
417
   * @throws NotImplemented
418
   * @throws NotAuthorized
419
   * @throws ServiceFailure
420
   * @throws InvalidRequest
421
   * @throws InvalidToken
422
   * @throws NotFound
423
   * 
424
   */
425
  @Override
426
  public boolean setReplicationStatus(Session session, Identifier pid,
427
      NodeReference targetNode, ReplicationStatus status, BaseException failure) 
428
      throws ServiceFailure, NotImplemented, InvalidToken, NotAuthorized, 
429
      InvalidRequest, NotFound {
430
	  
431
	  // cannot be called by public
432
	  if (session == null) {
433
		  throw new NotAuthorized("4720", "Session cannot be null");
434
	  }
435
      
436
      // The lock to be used for this identifier
437
      Lock lock = null;
438
      
439
      boolean allowed = false;
440
      int replicaEntryIndex = -1;
441
      List<Replica> replicas = null;
442
      // get the subject
443
      Subject subject = session.getSubject();
444
      logMetacat.debug("ReplicationStatus for identifier " + pid.getValue() +
445
          " is " + status.toString());
446
      
447
      SystemMetadata systemMetadata = null;
448

    
449
      try {
450
          lock = HazelcastService.getInstance().getLock(pid.getValue());
451
          lock.lock();
452
          logMetacat.debug("Locked identifier " + pid.getValue());
453

    
454
          try {      
455
              systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
456

    
457
              // did we get it correctly?
458
              if ( systemMetadata == null ) {
459
                  logMetacat.debug("systemMetadata is null for " + pid.getValue());
460
                  throw new NotFound("4740", "Couldn't find an object identified by " + pid.getValue());
461
                  
462
              }
463
              replicas = systemMetadata.getReplicaList();
464
              int count = 0;
465
              
466
              // was there a failure? log it
467
              if ( failure != null && status == ReplicationStatus.FAILED ) {
468
                 String msg = "The replication request of the object identified by " + 
469
                     pid.getValue() + " failed.  The error message was " +
470
                     failure.getMessage() + ".";
471
              }
472
              
473
              if (replicas.size() > 0 && replicas != null) {
474
                  // find the target replica index in the replica list
475
                  for (Replica replica : replicas) {
476
                      String replicaNodeStr = replica.getReplicaMemberNode()
477
                              .getValue();
478
                      String targetNodeStr = targetNode.getValue();
479
                      logMetacat.debug("Comparing " + replicaNodeStr + " to "
480
                              + targetNodeStr);
481
                  
482
                      if (replicaNodeStr.equals(targetNodeStr)) {
483
                          replicaEntryIndex = count;
484
                          logMetacat.debug("replica entry index is: "
485
                                  + replicaEntryIndex);
486
                          break;
487
                      }
488
                      count++;
489
                  
490
                  }
491
              }
492
              // are we allowed to do this? only CNs and target MNs are allowed
493
              CNode cn = D1Client.getCN();
494
              List<Node> nodes = cn.listNodes().getNodeList();
495
              
496
              // find the node in the node list
497
              for ( Node node : nodes ) {
498
                  
499
                  NodeReference nodeReference = node.getIdentifier();
500
                  logMetacat.debug("In setReplicationStatus(), Node reference is: " + nodeReference.getValue());
501
                  
502
                  // allow target MN certs and CN certs
503
                  if (targetNode.getValue().equals(nodeReference.getValue()) ||
504
                      node.getType() == NodeType.CN) {
505
                      List<Subject> nodeSubjects = node.getSubjectList();
506
                      
507
                      // check if the session subject is in the node subject list
508
                      for (Subject nodeSubject : nodeSubjects) {
509
                          if ( nodeSubject.equals(subject) ) {
510
                              allowed = true; // subject of session == target node subject
511
                              break;
512
                              
513
                          }
514
                      }                 
515
                  }
516
              }
517

    
518
              if ( !isAuthorized(session, pid, Permission.WRITE) ) {
519
                  if (!allowed) {
520
                    String msg = "The subject identified by "
521
                            + subject.getValue()
522
                            + " does not have permission to set the replication status for "
523
                            + "the replica identified by "
524
                            + targetNode.getValue() + ".";
525
                    logMetacat.info(msg);
526
                    throw new NotAuthorized("4720", msg);
527
                }
528
                  
529
              }
530
              
531

    
532
          } catch (RuntimeException e) { // Catch is generic since HZ throws RuntimeException
533
            throw new NotFound("4740", "No record found for: " + pid.getValue() +
534
                " : " + e.getMessage());
535
            
536
          }
537
          
538
          Replica targetReplica = new Replica();
539
          // set the status for the replica
540
          if ( replicaEntryIndex != -1 ) {
541
              targetReplica = replicas.get(replicaEntryIndex);
542
              targetReplica.setReplicationStatus(status);
543
              logMetacat.debug("Set the replication status for " + 
544
                  targetReplica.getReplicaMemberNode().getValue() + " to " +
545
                  targetReplica.getReplicationStatus());
546
              
547
          } else {
548
              // this is a new entry, create it
549
              targetReplica.setReplicaMemberNode(targetNode);
550
              targetReplica.setReplicationStatus(status);
551
              targetReplica.setReplicaVerified(Calendar.getInstance().getTime());
552
              replicas.add(targetReplica);
553
              
554
          }
555
          
556
          systemMetadata.setReplicaList(replicas);
557
                
558
          // update the metadata
559
          try {
560
              systemMetadata.setSerialVersion(systemMetadata.getSerialVersion().add(BigInteger.ONE));
561
              systemMetadata.setDateSysMetadataModified(Calendar.getInstance().getTime());
562
              HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
563
              
564
              if ( status == ReplicationStatus.FAILED && failure != null ) {
565
                  logMetacat.warn("Replication failed for identifier " + pid.getValue() +
566
                      " on target node " + targetNode + ". The exception was: " +
567
                      failure.getMessage());
568
              }
569
          } catch (RuntimeException e) {
570
              throw new ServiceFailure("4700", e.getMessage());
571
          
572
          }
573
          
574
    } catch (RuntimeException e) {
575
        String msg = "There was a RuntimeException getting the lock for " +
576
            pid.getValue();
577
        logMetacat.info(msg);
578
        
579
    } finally {
580
        lock.unlock();
581
        logMetacat.debug("Unlocked identifier " + pid.getValue());
582
        
583
    }
584
      
585
      return true;
586
  }
587
  
588
  /**
589
   * Return the checksum of the object given the identifier 
590
   * 
591
   * @param session - the Session object containing the credentials for the Subject
592
   * @param pid - the object identifier for the given object
593
   * 
594
   * @return checksum - the checksum of the object
595
   * 
596
   * @throws InvalidToken
597
   * @throws ServiceFailure
598
   * @throws NotAuthorized
599
   * @throws NotFound
600
   * @throws NotImplemented
601
   */
602
  @Override
603
  public Checksum getChecksum(Session session, Identifier pid)
604
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
605
    NotImplemented {
606
    
607
	boolean isAuthorized = false;
608
	try {
609
		isAuthorized = isAuthorized(session, pid, Permission.READ);
610
	} catch (InvalidRequest e) {
611
		throw new ServiceFailure("1410", e.getDescription());
612
	}  
613
    if (!isAuthorized) {
614
        throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());  
615
    }
616
    
617
    SystemMetadata systemMetadata = null;
618
    Checksum checksum = null;
619
    
620
    try {
621
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);        
622

    
623
        if (systemMetadata == null ) {
624
            throw new NotFound("1420", "Couldn't find an object identified by " + pid.getValue());
625
        }
626
        checksum = systemMetadata.getChecksum();
627
        
628
    } catch (RuntimeException e) {
629
        throw new ServiceFailure("1410", "An error occurred getting the checksum for " + 
630
            pid.getValue() + ". The error message was: " + e.getMessage());
631
      
632
    }
633
    
634
    return checksum;
635
  }
636

    
637
  /**
638
   * Resolve the location of a given object
639
   * 
640
   * @param session - the Session object containing the credentials for the Subject
641
   * @param pid - the object identifier for the given object
642
   * 
643
   * @return objectLocationList - the list of nodes known to contain the object
644
   * 
645
   * @throws InvalidToken
646
   * @throws ServiceFailure
647
   * @throws NotAuthorized
648
   * @throws NotFound
649
   * @throws NotImplemented
650
   */
651
  @Override
652
  public ObjectLocationList resolve(Session session, Identifier pid)
653
    throws InvalidToken, ServiceFailure, NotAuthorized,
654
    NotFound, NotImplemented {
655

    
656
    throw new NotImplemented("4131", "resolve not implemented");
657

    
658
  }
659

    
660
  /**
661
   * Search the metadata catalog for identifiers that match the criteria
662
   * 
663
   * @param session - the Session object containing the credentials for the Subject
664
   * @param queryType - An identifier for the type of query expression 
665
   *                    provided in the query
666
   * @param query -  The criteria for matching the characteristics of the 
667
   *                 metadata objects of interest
668
   * 
669
   * @return objectList - the list of objects matching the criteria
670
   * 
671
   * @throws InvalidToken
672
   * @throws ServiceFailure
673
   * @throws NotAuthorized
674
   * @throws InvalidRequest
675
   * @throws NotImplemented
676
   */
677
  @Override
678
  public ObjectList search(Session session, String queryType, String query)
679
    throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest,
680
    NotImplemented {
681

    
682
    ObjectList objectList = null;
683
    try {
684
        objectList = 
685
          IdentifierManager.getInstance().querySystemMetadata(
686
              null, //startTime, 
687
              null, //endTime,
688
              null, //objectFormat, 
689
              false, //replicaStatus, 
690
              0, //start, 
691
              -1 //count
692
              );
693
        
694
    } catch (Exception e) {
695
      throw new ServiceFailure("4310", "Error querying system metadata: " + e.getMessage());
696
    }
697

    
698
      return objectList;
699
      
700
    //throw new NotImplemented("4281", "search not implemented");
701
    
702
    // the code block below is from an older implementation
703
    
704
    /*  This block commented out because of the EcoGrid circular dependency.
705
         *  For now, query will not be supported until the circularity can be
706
         *  resolved, probably by moving the ecogrid query syntax transformers
707
         *  directly into the Metacat codebase.  MBJ 2010-02-03
708
         
709
        try {
710
            EcogridQueryParser parser = new EcogridQueryParser(request
711
                    .getReader());
712
            parser.parseXML();
713
            QueryType queryType = parser.getEcogridQuery();
714
            EcogridJavaToMetacatJavaQueryTransformer queryTransformer = 
715
                new EcogridJavaToMetacatJavaQueryTransformer();
716
            QuerySpecification metacatQuery = queryTransformer
717
                    .transform(queryType);
718

    
719
            DBQuery metacat = new DBQuery();
720

    
721
            boolean useXMLIndex = (new Boolean(PropertyService
722
                    .getProperty("database.usexmlindex"))).booleanValue();
723
            String xmlquery = "query"; // we don't care the query in resultset,
724
            // the query can be anything
725
            PrintWriter out = null; // we don't want metacat result, so set out null
726

    
727
            // parameter: queryspecification, user, group, usingIndexOrNot
728
            StringBuffer result = metacat.createResultDocument(xmlquery,
729
                    metacatQuery, out, username, groupNames, useXMLIndex);
730

    
731
            // create result set transfer       
732
            String saxparser = PropertyService.getProperty("xml.saxparser");
733
            MetacatResultsetParser metacatResultsetParser = new MetacatResultsetParser(
734
                    new StringReader(result.toString()), saxparser, queryType
735
                            .getNamespace().get_value());
736
            ResultsetType records = metacatResultsetParser.getEcogridResult();
737

    
738
            System.out
739
                    .println(EcogridResultsetTransformer.toXMLString(records));
740
            response.setContentType("text/xml");
741
            out = response.getWriter();
742
            out.print(EcogridResultsetTransformer.toXMLString(records));
743

    
744
        } catch (Exception e) {
745
            e.printStackTrace();
746
        }*/
747
    
748

    
749
  }
750
  
751
  /**
752
   * Returns the object format registered in the DataONE Object Format 
753
   * Vocabulary for the given format identifier
754
   * 
755
   * @param fmtid - the identifier of the format requested
756
   * 
757
   * @return objectFormat - the object format requested
758
   * 
759
   * @throws ServiceFailure
760
   * @throws NotFound
761
   * @throws InsufficientResources
762
   * @throws NotImplemented
763
   */
764
  @Override
765
  public ObjectFormat getFormat(ObjectFormatIdentifier fmtid)
766
    throws ServiceFailure, NotFound, NotImplemented {
767
     
768
      return ObjectFormatService.getInstance().getFormat(fmtid);
769
      
770
  }
771

    
772
  /**
773
   * Returns a list of all object formats registered in the DataONE Object 
774
   * Format Vocabulary
775
    * 
776
   * @return objectFormatList - The list of object formats registered in 
777
   *                            the DataONE Object Format Vocabulary
778
   * 
779
   * @throws ServiceFailure
780
   * @throws NotImplemented
781
   * @throws InsufficientResources
782
   */
783
  @Override
784
  public ObjectFormatList listFormats() 
785
    throws ServiceFailure, NotImplemented {
786

    
787
    return ObjectFormatService.getInstance().listFormats();
788
  }
789

    
790
  /**
791
   * Returns a list of nodes that have been registered with the DataONE infrastructure
792
    * 
793
   * @return nodeList - List of nodes from the registry
794
   * 
795
   * @throws ServiceFailure
796
   * @throws NotImplemented
797
   */
798
  @Override
799
  public NodeList listNodes() 
800
    throws NotImplemented, ServiceFailure {
801

    
802
    throw new NotImplemented("4800", "listNodes not implemented");
803
  }
804

    
805
  /**
806
   * Provides a mechanism for adding system metadata independently of its 
807
   * associated object, such as when adding system metadata for data objects.
808
    * 
809
   * @param session - the Session object containing the credentials for the Subject
810
   * @param pid - The identifier of the object to register the system metadata against
811
   * @param sysmeta - The system metadata to be registered
812
   * 
813
   * @return true if the registration succeeds
814
   * 
815
   * @throws NotImplemented
816
   * @throws NotAuthorized
817
   * @throws ServiceFailure
818
   * @throws InvalidRequest
819
   * @throws InvalidSystemMetadata
820
   */
821
  @Override
822
  public Identifier registerSystemMetadata(Session session, Identifier pid,
823
      SystemMetadata sysmeta) 
824
      throws NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest, 
825
      InvalidSystemMetadata {
826

    
827
      // The lock to be used for this identifier
828
      Lock lock = null;
829

    
830
      // TODO: control who can call this?
831
      if (session == null) {
832
          //TODO: many of the thrown exceptions do not use the correct error codes
833
          //check these against the docs and correct them
834
          throw new NotAuthorized("4861", "No Session - could not authorize for registration." +
835
                  "  If you are not logged in, please do so and retry the request.");
836
      }
837
      
838
      // verify that guid == SystemMetadata.getIdentifier()
839
      logMetacat.debug("Comparing guid|sysmeta_guid: " + pid.getValue() + 
840
          "|" + sysmeta.getIdentifier().getValue());
841
      if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
842
          throw new InvalidRequest("4863", 
843
              "The identifier in method call (" + pid.getValue() + 
844
              ") does not match identifier in system metadata (" +
845
              sysmeta.getIdentifier().getValue() + ").");
846
      }
847

    
848
      try {
849
          lock = HazelcastService.getInstance().getLock(sysmeta.getIdentifier().getValue());
850
          lock.lock();
851
          logMetacat.debug("Locked identifier " + pid.getValue());
852
          logMetacat.debug("Checking if identifier exists...");
853
          // Check that the identifier does not already exist
854
          if (HazelcastService.getInstance().getSystemMetadataMap().containsKey(pid)) {
855
              throw new InvalidRequest("4863", 
856
                  "The identifier is already in use by an existing object.");
857
          
858
          }
859
          
860
          // insert the system metadata into the object store
861
          logMetacat.debug("Starting to insert SystemMetadata...");
862
          try {
863
              sysmeta.setSerialVersion(BigInteger.ONE);
864
              sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
865
              HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
866
              
867
          } catch (RuntimeException e) {
868
            logMetacat.error("Problem registering system metadata: " + pid.getValue(), e);
869
              throw new ServiceFailure("4862", "Error inserting system metadata: " + 
870
                  e.getClass() + ": " + e.getMessage());
871
              
872
          }
873
          
874
      } catch (RuntimeException e) {
875
          throw new ServiceFailure("4862", "Error inserting system metadata: " + 
876
                  e.getClass() + ": " + e.getMessage());
877
          
878
      }  finally {
879
          lock.unlock();
880
          logMetacat.debug("Unlocked identifier " + pid.getValue());
881
          
882
      }
883

    
884
      
885
      logMetacat.debug("Returning from registerSystemMetadata");
886
      EventLog.getInstance().log(request.getRemoteAddr(), 
887
          request.getHeader("User-Agent"), session.getSubject().getValue(), 
888
          pid.getValue(), "registerSystemMetadata");
889
      return pid;
890
  }
891
  
892
  /**
893
   * Given an optional scope and format, reserves and returns an identifier 
894
   * within that scope and format that is unique and will not be 
895
   * used by any other sessions. 
896
    * 
897
   * @param session - the Session object containing the credentials for the Subject
898
   * @param pid - The identifier of the object to register the system metadata against
899
   * @param scope - An optional string to be used to qualify the scope of 
900
   *                the identifier namespace, which is applied differently 
901
   *                depending on the format requested. If scope is not 
902
   *                supplied, a default scope will be used.
903
   * @param format - The optional name of the identifier format to be used, 
904
   *                  drawn from a DataONE-specific vocabulary of identifier 
905
   *                 format names, including several common syntaxes such 
906
   *                 as DOI, LSID, UUID, and LSRN, among others. If the 
907
   *                 format is not supplied by the caller, the CN service 
908
   *                 will use a default identifier format, which may change 
909
   *                 over time.
910
   * 
911
   * @return true if the registration succeeds
912
   * 
913
   * @throws InvalidToken
914
   * @throws ServiceFailure
915
   * @throws NotAuthorized
916
   * @throws IdentifierNotUnique
917
   * @throws NotImplemented
918
   */
919
  @Override
920
  public Identifier reserveIdentifier(Session session, Identifier pid)
921
  throws InvalidToken, ServiceFailure,
922
        NotAuthorized, IdentifierNotUnique, NotImplemented, InvalidRequest {
923

    
924
    throw new NotImplemented("4191", "reserveIdentifier not implemented on this node");
925
  }
926
  
927
  @Override
928
  public Identifier generateIdentifier(Session session, String scheme, String fragment)
929
  throws InvalidToken, ServiceFailure,
930
        NotAuthorized, NotImplemented, InvalidRequest {
931
    throw new NotImplemented("4191", "generateIdentifier not implemented on this node");
932
  }
933
  
934
  /**
935
    * Checks whether the pid is reserved by the subject in the session param
936
    * If the reservation is held on the pid by the subject, we return true.
937
    * 
938
   * @param session - the Session object containing the Subject
939
   * @param pid - The identifier to check
940
   * 
941
   * @return true if the reservation exists for the subject/pid
942
   * 
943
   * @throws InvalidToken
944
   * @throws ServiceFailure
945
   * @throws NotFound - when the pid is not found (in use or in reservation)
946
   * @throws NotAuthorized - when the subject does not hold a reservation on the pid
947
   * @throws IdentifierNotUnique - when the pid is in use
948
   * @throws NotImplemented
949
   */
950

    
951
  @Override
952
  public boolean hasReservation(Session session, Subject subject, Identifier pid) 
953
      throws InvalidToken, ServiceFailure, NotFound, NotAuthorized, IdentifierNotUnique, 
954
      NotImplemented, InvalidRequest {
955
  
956
      throw new NotImplemented("4191", "hasReservation not implemented on this node");
957
  }
958

    
959
  /**
960
   * Changes ownership (RightsHolder) of the specified object to the 
961
   * subject specified by userId
962
    * 
963
   * @param session - the Session object containing the credentials for the Subject
964
   * @param pid - Identifier of the object to be modified
965
   * @param userId - The subject that will be taking ownership of the specified object.
966
   *
967
   * @return pid - the identifier of the modified object
968
   * 
969
   * @throws ServiceFailure
970
   * @throws InvalidToken
971
   * @throws NotFound
972
   * @throws NotAuthorized
973
   * @throws NotImplemented
974
   * @throws InvalidRequest
975
   */  
976
  @Override
977
  public Identifier setRightsHolder(Session session, Identifier pid, Subject userId,
978
      long serialVersion)
979
      throws InvalidToken, ServiceFailure, NotFound, NotAuthorized,
980
      NotImplemented, InvalidRequest, VersionMismatch {
981
      
982
      // The lock to be used for this identifier
983
      Lock lock = null;
984

    
985
      // get the subject
986
      Subject subject = session.getSubject();
987
      
988
      // are we allowed to do this?
989
      if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
990
          throw new NotAuthorized("4440", "not allowed by "
991
                  + subject.getValue() + " on " + pid.getValue());
992
          
993
      }
994
      
995
      SystemMetadata systemMetadata = null;
996
      try {
997
          lock = HazelcastService.getInstance().getLock(pid.getValue());
998
          logMetacat.debug("Locked identifier " + pid.getValue());
999

    
1000
          try {
1001
              systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1002
              
1003
              // does the request have the most current system metadata?
1004
              if ( systemMetadata.getSerialVersion().longValue() != serialVersion ) {
1005
                 String msg = "The requested system metadata version number " + 
1006
                     serialVersion + " differs from the current version at " +
1007
                     systemMetadata.getSerialVersion().longValue() +
1008
                     ". Please get the latest copy in order to modify it.";
1009
                 throw new VersionMismatch("4443", msg);
1010
              }
1011
              
1012
          } catch (RuntimeException e) { // Catch is generic since HZ throws RuntimeException
1013
              throw new NotFound("4460", "No record found for: " + pid.getValue());
1014
              
1015
          }
1016
              
1017
          // set the new rights holder
1018
          systemMetadata.setRightsHolder(userId);
1019
          
1020
          // update the metadata
1021
          try {
1022
              systemMetadata.setSerialVersion(systemMetadata.getSerialVersion().add(BigInteger.ONE));
1023
              systemMetadata.setDateSysMetadataModified(Calendar.getInstance().getTime());
1024
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, systemMetadata);
1025
              
1026
          } catch (RuntimeException e) {
1027
              throw new ServiceFailure("4490", e.getMessage());
1028
          
1029
          }
1030
          
1031
      } catch (RuntimeException e) {
1032
          throw new ServiceFailure("4490", e.getMessage());
1033
          
1034
      } finally {
1035
          lock.unlock();
1036
          logMetacat.debug("Unlocked identifier " + pid.getValue());
1037
      
1038
      }
1039
      
1040
      return pid;
1041
  }
1042

    
1043
  /**
1044
   * Verify that a replication task is authorized by comparing the target node's
1045
   * Subject (from the X.509 certificate-derived Session) with the list of 
1046
   * subjects in the known, pending replication tasks map.
1047
   * 
1048
   * @param originatingNodeSession - Session information that contains the 
1049
   *                                 identity of the calling user
1050
   * @param targetNodeSubject - Subject identifying the target node
1051
   * @param pid - the identifier of the object to be replicated
1052
   * @param replicatePermission - the execute permission to be granted
1053
   * 
1054
   * @throws ServiceFailure
1055
   * @throws NotImplemented
1056
   * @throws InvalidToken
1057
   * @throws NotAuthorized
1058
   * @throws InvalidRequest
1059
   * @throws NotFound
1060
   */
1061
  @Override
1062
  public boolean isNodeAuthorized(Session originatingNodeSession, 
1063
    Subject targetNodeSubject, Identifier pid) 
1064
    throws NotImplemented, NotAuthorized, InvalidToken, ServiceFailure, 
1065
    NotFound, InvalidRequest {
1066
    
1067
    boolean isAllowed = false;
1068
    SystemMetadata sysmeta = null;
1069
    NodeReference targetNode = null;
1070
    
1071
    try {
1072
      // get the target node reference from the nodes list
1073
      CNode cn = D1Client.getCN();
1074
      List<Node> nodes = cn.listNodes().getNodeList();
1075
      
1076
      if ( nodes != null ) {
1077
        for (Node node : nodes) {
1078
            
1079
            for (Subject nodeSubject : node.getSubjectList()) {
1080
                
1081
                if ( nodeSubject.equals(targetNodeSubject) ) {
1082
                    targetNode = node.getIdentifier();
1083
                    logMetacat.debug("targetNode is : " + targetNode.getValue());
1084
                    break;
1085
                }
1086
            }
1087
            
1088
            if ( targetNode != null) { break; }
1089
        }
1090
        
1091
      } else {
1092
          String msg = "Couldn't get the node list from the CN";
1093
          logMetacat.debug(msg);
1094
          throw new ServiceFailure("4872", msg);
1095
          
1096
      }
1097
      
1098
      // can't find a node listed with the given subject
1099
      if ( targetNode == null ) {
1100
          String msg = "There is no Member Node registered with a node subject " +
1101
              "matching " + targetNodeSubject.getValue();
1102
          logMetacat.info(msg);
1103
          throw new NotAuthorized("4871", msg);
1104
          
1105
      }
1106
      
1107
      logMetacat.debug("Getting system metadata for identifier " + pid.getValue());
1108
      
1109
      sysmeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1110

    
1111
      if ( sysmeta != null ) {
1112
          
1113
          List<Replica> replicaList = sysmeta.getReplicaList();
1114
          
1115
          if ( replicaList != null ) {
1116
              
1117
              // find the replica with the status set to 'requested'
1118
              for (Replica replica : replicaList) {
1119
                  ReplicationStatus status = replica.getReplicationStatus();
1120
                  NodeReference listedNode = replica.getReplicaMemberNode();
1121
                  if ( listedNode != null && targetNode != null ) {
1122
                      logMetacat.debug("Comparing " + listedNode.getValue()
1123
                              + " to " + targetNode.getValue());
1124
                      
1125
                      if (listedNode.getValue().equals(targetNode.getValue())
1126
                              && status.equals(ReplicationStatus.REQUESTED)) {
1127
                          isAllowed = true;
1128
                          break;
1129

    
1130
                      }
1131
                  }
1132
              }
1133
          }
1134
          logMetacat.debug("The " + targetNode.getValue() + " is allowed " +
1135
              "to replicate: " + isAllowed + " for " + pid.getValue());
1136

    
1137
          
1138
      } else {
1139
          logMetacat.debug("System metadata for identifier " + pid.getValue() +
1140
          " is null.");          
1141
          throw new NotFound("4874", "Couldn't find an object identified by " + pid.getValue());
1142
          
1143
      }
1144

    
1145
    } catch (RuntimeException e) {
1146
    	  ServiceFailure sf = new ServiceFailure("4872", 
1147
                "Runtime Exception: Couldn't determine if node is allowed: " + 
1148
                e.getCause().getMessage());
1149
    	  sf.initCause(e);
1150
        throw sf;
1151
        
1152
    }
1153
      
1154
    return isAllowed;
1155
    
1156
  }
1157

    
1158
  /**
1159
   * Adds a new object to the Node, where the object is a science metadata object.
1160
   * 
1161
   * @param session - the Session object containing the credentials for the Subject
1162
   * @param pid - The object identifier to be created
1163
   * @param object - the object bytes
1164
   * @param sysmeta - the system metadata that describes the object  
1165
   * 
1166
   * @return pid - the object identifier created
1167
   * 
1168
   * @throws InvalidToken
1169
   * @throws ServiceFailure
1170
   * @throws NotAuthorized
1171
   * @throws IdentifierNotUnique
1172
   * @throws UnsupportedType
1173
   * @throws InsufficientResources
1174
   * @throws InvalidSystemMetadata
1175
   * @throws NotImplemented
1176
   * @throws InvalidRequest
1177
   */
1178
  public Identifier create(Session session, Identifier pid, InputStream object,
1179
    SystemMetadata sysmeta) 
1180
    throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
1181
    UnsupportedType, InsufficientResources, InvalidSystemMetadata, 
1182
    NotImplemented, InvalidRequest {
1183
                  
1184
      // The lock to be used for this identifier
1185
      Lock lock = null;
1186

    
1187
      try {
1188
          lock = HazelcastService.getInstance().getLock(pid.getValue());
1189
          // are we allowed?
1190
          boolean isAllowed = false;
1191
          CNode cn = D1Client.getCN();
1192
          NodeList nodeList = cn.listNodes();
1193
          
1194
          for (Node node : nodeList.getNodeList()) {
1195
              if ( node.getType().equals(NodeType.CN) ) {
1196
                  
1197
                  List<Subject> subjects = node.getSubjectList();
1198
                  for (Subject subject : subjects) {
1199
                     if (subject.equals(session.getSubject())) {
1200
                         isAllowed = true;
1201
                         break;
1202
                     }
1203
                  }
1204
              } else {
1205
                  
1206
              }
1207
          }
1208

    
1209
          // proceed if we're called by a CN
1210
          if ( isAllowed ) {
1211
              // create the coordinating node version of the document      
1212
              lock.lock();
1213
              logMetacat.debug("Locked identifier " + pid.getValue());
1214
              sysmeta.setSerialVersion(BigInteger.ONE);
1215
              sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1216
              sysmeta.setArchived(false); // this is a create op, not update
1217
              
1218
              // the CN should have set the origin and authoritative member node fields
1219
              try {
1220
                  sysmeta.getOriginMemberNode().getValue();
1221
                  sysmeta.getAuthoritativeMemberNode().getValue();
1222
                  
1223
              } catch (NullPointerException npe) {
1224
                  throw new InvalidSystemMetadata("4896", 
1225
                      "Both the origin and authoritative member node identifiers need to be set.");
1226
                  
1227
              }
1228
              pid = super.create(session, pid, object, sysmeta);
1229

    
1230
          } else {
1231
              String msg = "The subject listed as " + session.getSubject().getValue() + 
1232
                  " isn't allowed to call create() on a Coordinating Node.";
1233
              logMetacat.info(msg);
1234
              throw new NotAuthorized("1100", msg);
1235
          }
1236
          
1237
      } catch (RuntimeException e) {
1238
          // Convert Hazelcast runtime exceptions to service failures
1239
          String msg = "There was a problem creating the object identified by " +
1240
              pid.getValue() + ". There error message was: " + e.getMessage();
1241
          throw new ServiceFailure("4893", msg);
1242
          
1243
      } finally {
1244
    	  if (lock != null) {
1245
	          lock.unlock();
1246
	          logMetacat.debug("Unlocked identifier " + pid.getValue());
1247
    	  }
1248
      }
1249
      
1250
      return pid;
1251

    
1252
  }
1253

    
1254
  /**
1255
   * Set access for a given object using the object identifier and a Subject
1256
   * under a given Session.
1257
   * 
1258
   * @param session - the Session object containing the credentials for the Subject
1259
   * @param pid - the object identifier for the given object to apply the policy
1260
   * @param policy - the access policy to be applied
1261
   * 
1262
   * @return true if the application of the policy succeeds
1263
   * @throws InvalidToken
1264
   * @throws ServiceFailure
1265
   * @throws NotFound
1266
   * @throws NotAuthorized
1267
   * @throws NotImplemented
1268
   * @throws InvalidRequest
1269
   */
1270
  public boolean setAccessPolicy(Session session, Identifier pid, 
1271
      AccessPolicy accessPolicy, long serialVersion) 
1272
      throws InvalidToken, ServiceFailure, NotFound, NotAuthorized, 
1273
      NotImplemented, InvalidRequest, VersionMismatch {
1274
      
1275
      // The lock to be used for this identifier
1276
      Lock lock = null;
1277
      SystemMetadata systemMetadata = null;
1278
      
1279
      boolean success = false;
1280
      
1281
      // get the subject
1282
      Subject subject = session.getSubject();
1283
      
1284
      // are we allowed to do this?
1285
      if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
1286
          throw new NotAuthorized("4420", "not allowed by "
1287
                  + subject.getValue() + " on " + pid.getValue());
1288
      }
1289
      
1290
      try {
1291
          lock = HazelcastService.getInstance().getLock(pid.getValue());
1292
          lock.lock();
1293
          logMetacat.debug("Locked identifier " + pid.getValue());
1294

    
1295
          try {
1296
              systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1297

    
1298
              if ( systemMetadata == null ) {
1299
                  throw new NotFound("4400", "Couldn't find an object identified by " + pid.getValue());
1300
                  
1301
              }
1302
              // does the request have the most current system metadata?
1303
              if ( systemMetadata.getSerialVersion().longValue() != serialVersion ) {
1304
                 String msg = "The requested system metadata version number " + 
1305
                     serialVersion + " differs from the current version at " +
1306
                     systemMetadata.getSerialVersion().longValue() +
1307
                     ". Please get the latest copy in order to modify it.";
1308
                 throw new VersionMismatch("4402", msg);
1309
                 
1310
              }
1311
              
1312
          } catch (RuntimeException e) {
1313
              // convert Hazelcast RuntimeException to NotFound
1314
              throw new NotFound("4400", "No record found for: " + pid);
1315
            
1316
          }
1317
              
1318
          // set the access policy
1319
          systemMetadata.setAccessPolicy(accessPolicy);
1320
          
1321
          // update the system metadata
1322
          try {
1323
              systemMetadata.setSerialVersion(systemMetadata.getSerialVersion().add(BigInteger.ONE));
1324
              systemMetadata.setDateSysMetadataModified(Calendar.getInstance().getTime());
1325
              HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
1326
            
1327
          } catch (RuntimeException e) {
1328
              // convert Hazelcast RuntimeException to ServiceFailure
1329
              throw new ServiceFailure("4430", e.getMessage());
1330
            
1331
          }
1332
          
1333
      } catch (RuntimeException e) {
1334
          throw new ServiceFailure("4430", e.getMessage());
1335
          
1336
      } finally {
1337
          lock.unlock();
1338
          logMetacat.debug("Unlocked identifier " + pid.getValue());
1339
        
1340
      }
1341

    
1342
    
1343
    // TODO: how do we know if the map was persisted?
1344
    success = true;
1345
    
1346
    return success;
1347
  }
1348

    
1349
  /**
1350
   * Full replacement of replication metadata in the system metadata for the 
1351
   * specified object, changes date system metadata modified
1352
   * 
1353
   * @param session - the Session object containing the credentials for the Subject
1354
   * @param pid - the object identifier for the given object to apply the policy
1355
   * @param replica - the replica to be updated
1356
   * @return
1357
   * @throws NotImplemented
1358
   * @throws NotAuthorized
1359
   * @throws ServiceFailure
1360
   * @throws InvalidRequest
1361
   * @throws NotFound
1362
   * @throws VersionMismatch
1363
   */
1364
  @Override
1365
  public boolean updateReplicationMetadata(Session session, Identifier pid,
1366
      Replica replica, long serialVersion) 
1367
      throws NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest,
1368
      NotFound, VersionMismatch {
1369
      
1370
      // The lock to be used for this identifier
1371
      Lock lock = null;
1372
      
1373
      // get the subject
1374
      Subject subject = session.getSubject();
1375
      
1376
      // are we allowed to do this?
1377
      try {
1378

    
1379
          // what is the controlling permission?
1380
          if (!isAuthorized(session, pid, Permission.WRITE)) {
1381
              throw new NotAuthorized("4851", "not allowed by "
1382
                      + subject.getValue() + " on " + pid.getValue());
1383
          }
1384

    
1385
        
1386
      } catch (InvalidToken e) {
1387
          throw new NotAuthorized("4851", "not allowed by " + subject.getValue() + 
1388
                  " on " + pid.getValue());  
1389
          
1390
      }
1391

    
1392
      SystemMetadata systemMetadata = null;
1393
      try {
1394
          lock = HazelcastService.getInstance().getLock(pid.getValue());
1395
          lock.lock();
1396
          logMetacat.debug("Locked identifier " + pid.getValue());
1397

    
1398
          try {      
1399
              systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1400

    
1401
              // does the request have the most current system metadata?
1402
              if ( systemMetadata.getSerialVersion().longValue() != serialVersion ) {
1403
                 String msg = "The requested system metadata version number " + 
1404
                     serialVersion + " differs from the current version at " +
1405
                     systemMetadata.getSerialVersion().longValue() +
1406
                     ". Please get the latest copy in order to modify it.";
1407
                 throw new VersionMismatch("4855", msg);
1408
              }
1409
              
1410
          } catch (RuntimeException e) { // Catch is generic since HZ throws RuntimeException
1411
              throw new NotFound("4854", "No record found for: " + pid.getValue() +
1412
                  " : " + e.getMessage());
1413
            
1414
          }
1415
              
1416
          // set the status for the replica
1417
          List<Replica> replicas = systemMetadata.getReplicaList();
1418
          NodeReference replicaNode = replica.getReplicaMemberNode();
1419
          int index = 0;
1420
          for (Replica listedReplica: replicas) {
1421
              
1422
              // remove the replica that we are replacing
1423
              if ( replicaNode.getValue().equals(listedReplica.getReplicaMemberNode().getValue())) {
1424
                  replicas.remove(index);
1425
                  break;
1426
                  
1427
              }
1428
              index++;
1429
          }
1430
          
1431
          // add the new replica item
1432
          replicas.add(replica);
1433
          systemMetadata.setReplicaList(replicas);
1434
          
1435
          // update the metadata
1436
          try {
1437
              systemMetadata.setSerialVersion(systemMetadata.getSerialVersion().add(BigInteger.ONE));
1438
              systemMetadata.setDateSysMetadataModified(Calendar.getInstance().getTime());
1439
              HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
1440
            
1441
          } catch (RuntimeException e) {
1442
              logMetacat.info("Unknown RuntimeException thrown: " + e.getCause().getMessage());
1443
              throw new ServiceFailure("4852", e.getMessage());
1444
          
1445
          }
1446
          
1447
      } catch (RuntimeException e) {
1448
          logMetacat.info("Unknown RuntimeException thrown: " + e.getCause().getMessage());
1449
          throw new ServiceFailure("4852", e.getMessage());
1450
      
1451
      } finally {
1452
          lock.unlock();
1453
          logMetacat.debug("Unlocked identifier " + pid.getValue());
1454
          
1455
      }
1456
    
1457
      return true;
1458
      
1459
  }
1460
  
1461
  /**
1462
   * 
1463
   */
1464
  @Override
1465
  public ObjectList listObjects(Session session, Date startTime, 
1466
      Date endTime, ObjectFormatIdentifier formatid, Boolean replicaStatus,
1467
      Integer start, Integer count)
1468
      throws InvalidRequest, InvalidToken, NotAuthorized, NotImplemented,
1469
      ServiceFailure {
1470
      
1471
      ObjectList objectList = null;
1472
        try {
1473
            objectList = IdentifierManager.getInstance().querySystemMetadata(startTime, endTime, formatid, replicaStatus, start, count);
1474
        } catch (Exception e) {
1475
            throw new ServiceFailure("1580", "Error querying system metadata: " + e.getMessage());
1476
        }
1477

    
1478
        return objectList;
1479
  }
1480

    
1481
  
1482
 	/**
1483
 	 * Returns a list of checksum algorithms that are supported by DataONE.
1484
 	 * @return cal  the list of checksum algorithms
1485
 	 * 
1486
 	 * @throws ServiceFailure
1487
 	 * @throws NotImplemented
1488
 	 */
1489
  @Override
1490
  public ChecksumAlgorithmList listChecksumAlgorithms()
1491
			throws ServiceFailure, NotImplemented {
1492
		ChecksumAlgorithmList cal = new ChecksumAlgorithmList();
1493
		cal.addAlgorithm("MD5");
1494
		cal.addAlgorithm("SHA-1");
1495
		return cal;
1496
		
1497
	}
1498
    
1499
}
(1-1/5)