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.util.Date;
27
import java.util.List;
28
import java.util.Set;
29

    
30
import org.apache.log4j.Logger;
31
import org.dataone.client.CNode;
32
import org.dataone.client.D1Client;
33
import org.dataone.service.cn.v1.CNAuthorization;
34
import org.dataone.service.cn.v1.CNCore;
35
import org.dataone.service.cn.v1.CNRead;
36
import org.dataone.service.cn.v1.CNReplication;
37
import org.dataone.service.exceptions.IdentifierNotUnique;
38
import org.dataone.service.exceptions.InsufficientResources;
39
import org.dataone.service.exceptions.InvalidRequest;
40
import org.dataone.service.exceptions.InvalidSystemMetadata;
41
import org.dataone.service.exceptions.InvalidToken;
42
import org.dataone.service.exceptions.NotAuthorized;
43
import org.dataone.service.exceptions.NotFound;
44
import org.dataone.service.exceptions.NotImplemented;
45
import org.dataone.service.exceptions.ServiceFailure;
46
import org.dataone.service.types.v1.Checksum;
47
import org.dataone.service.types.v1.Identifier;
48
import org.dataone.service.types.v1.Node;
49
import org.dataone.service.types.v1.NodeList;
50
import org.dataone.service.types.v1.NodeReference;
51
import org.dataone.service.types.v1.ObjectFormat;
52
import org.dataone.service.types.v1.ObjectFormatIdentifier;
53
import org.dataone.service.types.v1.ObjectFormatList;
54
import org.dataone.service.types.v1.ObjectList;
55
import org.dataone.service.types.v1.ObjectLocationList;
56
import org.dataone.service.types.v1.Permission;
57
import org.dataone.service.types.v1.Replica;
58
import org.dataone.service.types.v1.ReplicationPolicy;
59
import org.dataone.service.types.v1.ReplicationStatus;
60
import org.dataone.service.types.v1.Session;
61
import org.dataone.service.types.v1.Subject;
62
import org.dataone.service.types.v1.SystemMetadata;
63

    
64
import com.hazelcast.query.SqlPredicate;
65

    
66
import edu.ucsb.nceas.metacat.EventLog;
67
import edu.ucsb.nceas.metacat.IdentifierManager;
68
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
69
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
70

    
71
/**
72
 * Represents Metacat's implementation of the DataONE Coordinating Node 
73
 * service API. Methods implement the various CN* interfaces, and methods common
74
 * to both Member Node and Coordinating Node interfaces are found in the
75
 * D1NodeService super class.
76
 *
77
 */
78
public class CNodeService extends D1NodeService implements CNAuthorization,
79
    CNCore, CNRead, CNReplication {
80

    
81
  /* the instance of the CNodeService object */
82
  private static CNodeService instance = null;
83

    
84
  /* the logger instance */
85
  private Logger logMetacat = null;
86

    
87
  /**
88
   * singleton accessor
89
   */
90
  public static CNodeService getInstance() { 
91
    if (instance == null) {
92
    
93
      instance = new CNodeService();
94
      
95
    }
96
  
97
    return instance;
98
  }
99
  
100
  /**
101
   * Constructor, private for singleton access
102
   */
103
  private CNodeService() {
104
    super();
105
    logMetacat = Logger.getLogger(CNodeService.class);
106
        
107
  }
108
    
109
  /**
110
   * Set the replication policy for an object given the object identifier
111
   * 
112
   * @param session - the Session object containing the credentials for the Subject
113
   * @param pid - the object identifier for the given object
114
   * @param policy - the replication policy to be applied
115
   * 
116
   * @return true or false
117
   * 
118
   * @throws NotImplemented
119
   * @throws NotAuthorized
120
   * @throws ServiceFailure
121
   * @throws InvalidRequest
122
   * 
123
   */
124
  @Override
125
  public boolean setReplicationPolicy(Session session, Identifier pid,
126
    ReplicationPolicy policy) 
127
    throws NotImplemented, NotFound, NotAuthorized, ServiceFailure, InvalidRequest, InvalidToken {
128

    
129
    // get the subject
130
    Subject subject = session.getSubject();
131
    // get the system metadata
132
    String guid = pid.getValue();
133
    
134
    // are we allowed to do this?
135
    if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
136
      throw new NotAuthorized("4881", Permission.CHANGE_PERMISSION + " not allowed by " + subject.getValue() + " on " + guid);  
137
    }
138
    
139
    SystemMetadata systemMetadata = null;
140
    try {
141
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(guid);
142
    } catch (McdbDocNotFoundException e) {
143
      throw new NotFound("4884", "No record found for: " + guid);
144
    }
145
        
146
    // set the new policy
147
    systemMetadata.setReplicationPolicy(policy);
148
    
149
    // update the metadata
150
    try {
151
	    HazelcastService.getInstance().getSystemMetadataMap().lock(systemMetadata.getIdentifier());
152
	    HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
153
	    HazelcastService.getInstance().getSystemMetadataMap().unlock(systemMetadata.getIdentifier());
154
    } catch (Exception e) {
155
		throw new ServiceFailure("4882", e.getMessage());
156
	} finally {
157
	    HazelcastService.getInstance().getSystemMetadataMap().unlock(systemMetadata.getIdentifier());
158
	}
159
    
160
    return true;
161
  }
162

    
163
  /**
164
   * Set the replication status for an object given the object identifier
165
   * 
166
   * @param session - the Session object containing the credentials for the Subject
167
   * @param pid - the object identifier for the given object
168
   * @param status - the replication status to be applied
169
   * 
170
   * @return true or false
171
   * 
172
   * @throws NotImplemented
173
   * @throws NotAuthorized
174
   * @throws ServiceFailure
175
   * @throws InvalidRequest
176
   * @throws InvalidToken
177
   * @throws NotFound
178
   * 
179
   */
180
  @Override
181
  public boolean setReplicationStatus(Session session, Identifier pid,
182
    NodeReference targetNode, ReplicationStatus status) 
183
    throws ServiceFailure, NotImplemented, InvalidToken, NotAuthorized, 
184
    InvalidRequest, NotFound {
185

    
186
    // get the subject
187
    Subject subject = session.getSubject();
188
    // get the system metadata
189
    String guid = pid.getValue();
190
    
191
    // are we allowed to do this?
192
    if (!isAuthorized(session, pid, Permission.WRITE)) {
193
      throw new NotAuthorized("4720", Permission.WRITE + " not allowed by " + subject.getValue() + " on " + guid);  
194
    }
195
    
196
    SystemMetadata systemMetadata = null;
197
    try {
198
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(guid);
199
    } catch (McdbDocNotFoundException e) {
200
      throw new NotFound("4740", "No record found for: " + guid);
201
    }
202
        
203
    // set the status for each replica
204
    // TODO: should this method select a certain replica?
205
    List<Replica> replicas = systemMetadata.getReplicaList();
206
    for (Replica replica: replicas) {
207
      replica.setReplicationStatus(status);
208
    }
209
    
210
    // [re]set the list -- redundant?
211
    systemMetadata.setReplicaList(replicas);
212
    
213
    // update the metadata
214
    try {
215
	    HazelcastService.getInstance().getSystemMetadataMap().lock(systemMetadata.getIdentifier());
216
	    HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
217
	    HazelcastService.getInstance().getSystemMetadataMap().unlock(systemMetadata.getIdentifier());
218
    } catch (Exception e) {
219
		throw new ServiceFailure("4700", e.getMessage());
220
	} finally {
221
	    HazelcastService.getInstance().getSystemMetadataMap().unlock(systemMetadata.getIdentifier());
222
	}
223
	
224
    return true;
225
  }
226

    
227
  /**
228
   * Test that the specified relationship between pidOfSubject and pidOfObject exists
229
   * 
230
   * @param session - the Session object containing the credentials for the Subject
231
   * @param node - the node information for the given node be modified
232
   * 
233
   * @return true if the relationship exists
234
   * 
235
   * @throws InvalidToken
236
   * @throws ServiceFailure
237
   * @throws NotAuthorized
238
   * @throws NotFound
239
   * @throws InvalidRequest
240
   * @throws NotImplemented
241
   */
242
  @Override
243
  public boolean assertRelation(Session session, Identifier pidOfSubject, 
244
    String relationship, Identifier pidOfObject) 
245
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
246
    InvalidRequest, NotImplemented {
247
    
248
    
249
    // get the system metadata
250
    String guid1 = pidOfSubject.getValue();
251
    // are we allowed to do this?
252
    if (!isAuthorized(session, pidOfSubject, Permission.READ)) {
253
      throw new NotAuthorized("4881", Permission.READ + " not allowed on " + guid1);  
254
    }
255
    
256
    SystemMetadata systemMetadata = null;
257
    try {
258
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(guid1);
259
    } catch (McdbDocNotFoundException e) {
260
      throw new NotFound("4884", "No record found for: " + guid1);
261
    }
262
        
263
    // check relationships
264
    // TODO: use ORE map
265
    if (relationship.equalsIgnoreCase("describes")) {
266
      
267
    }
268
    if (relationship.equalsIgnoreCase("describedBy")) {
269
      
270
    }
271
    if (relationship.equalsIgnoreCase("derivedFrom")) {
272
      
273
    }
274
    if (relationship.equalsIgnoreCase("obsoletes")) {
275
      Identifier pid = systemMetadata.getObsoletes();
276
      if (pid.getValue().equals(pidOfObject.getValue())) {
277
        return true;
278
      }
279
      //return systemMetadata.getObsoleteList().contains(pidOfObject);
280
    }
281
    if (relationship.equalsIgnoreCase("obsoletedBy")) {
282
      Identifier pid = systemMetadata.getObsoletedBy();
283
      if (pid.getValue().equals(pidOfObject.getValue())) {
284
        return true;
285
      }
286
      //return systemMetadata.getObsoletedByList().contains(pidOfObject);
287
    }
288

    
289
    return false;
290
  }
291
  
292
  /**
293
   * Return the checksum of the object given the identifier 
294
   * 
295
   * @param session - the Session object containing the credentials for the Subject
296
   * @param pid - the object identifier for the given object
297
   * 
298
   * @return checksum - the checksum of the object
299
   * 
300
   * @throws InvalidToken
301
   * @throws ServiceFailure
302
   * @throws NotAuthorized
303
   * @throws NotFound
304
   * @throws InvalidRequest
305
   * @throws NotImplemented
306
   */
307
  @Override
308
  public Checksum getChecksum(Session session, Identifier pid)
309
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
310
    InvalidRequest, NotImplemented {
311
    
312
    if (!isAuthorized(session, pid, Permission.READ)) {
313
      throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());  
314
    }
315
    SystemMetadata systemMetadata = null;
316
    try {
317
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
318
    } catch (McdbDocNotFoundException e) {
319
      throw new NotFound("1420", "No record found for: " + pid.getValue());
320
    }
321
    Checksum checksum = systemMetadata.getChecksum();
322
    
323
    return checksum;
324
  }
325

    
326
  /**
327
   * Resolve the location of a given object
328
   * 
329
   * @param session - the Session object containing the credentials for the Subject
330
   * @param pid - the object identifier for the given object
331
   * 
332
   * @return objectLocationList - the list of nodes known to contain the object
333
   * 
334
   * @throws InvalidRequest
335
   * @throws InvalidToken
336
   * @throws ServiceFailure
337
   * @throws NotAuthorized
338
   * @throws NotFound
339
   * @throws NotImplemented
340
   */
341
  @Override
342
  public ObjectLocationList resolve(Session session, Identifier pid)
343
    throws InvalidRequest, InvalidToken, ServiceFailure, NotAuthorized,
344
    NotFound, NotImplemented {
345

    
346
    throw new NotImplemented("4131", "resolve not implemented");
347

    
348
  }
349

    
350
  /**
351
   * Search the metadata catalog for identifiers that match the criteria
352
   * 
353
   * @param session - the Session object containing the credentials for the Subject
354
   * @param queryType - An identifier for the type of query expression 
355
   *                    provided in the query
356
   * @param query -  The criteria for matching the characteristics of the 
357
   *                 metadata objects of interest
358
   * 
359
   * @return objectList - the list of objects matching the criteria
360
   * 
361
   * @throws InvalidToken
362
   * @throws ServiceFailure
363
   * @throws NotAuthorized
364
   * @throws InvalidRequest
365
   * @throws NotImplemented
366
   */
367
  @Override
368
  public ObjectList search(Session session, String queryType, String query)
369
    throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest,
370
    NotImplemented {
371

    
372
    ObjectList objectList = null;
373
    try {
374
        objectList = 
375
          IdentifierManager.getInstance().querySystemMetadata(
376
              null, //startTime, 
377
              null, //endTime,
378
              null, //objectFormat, 
379
              false, //replicaStatus, 
380
              0, //start, 
381
              -1 //count
382
              );
383
        
384
    } catch (Exception e) {
385
      throw new ServiceFailure("4310", "Error querying system metadata: " + e.getMessage());
386
    }
387

    
388
      return objectList;
389
      
390
    //throw new NotImplemented("4281", "search not implemented");
391
    
392
    // the code block below is from an older implementation
393
    
394
    /*  This block commented out because of the EcoGrid circular dependency.
395
         *  For now, query will not be supported until the circularity can be
396
         *  resolved, probably by moving the ecogrid query syntax transformers
397
         *  directly into the Metacat codebase.  MBJ 2010-02-03
398
         
399
        try {
400
            EcogridQueryParser parser = new EcogridQueryParser(request
401
                    .getReader());
402
            parser.parseXML();
403
            QueryType queryType = parser.getEcogridQuery();
404
            EcogridJavaToMetacatJavaQueryTransformer queryTransformer = 
405
                new EcogridJavaToMetacatJavaQueryTransformer();
406
            QuerySpecification metacatQuery = queryTransformer
407
                    .transform(queryType);
408

    
409
            DBQuery metacat = new DBQuery();
410

    
411
            boolean useXMLIndex = (new Boolean(PropertyService
412
                    .getProperty("database.usexmlindex"))).booleanValue();
413
            String xmlquery = "query"; // we don't care the query in resultset,
414
            // the query can be anything
415
            PrintWriter out = null; // we don't want metacat result, so set out null
416

    
417
            // parameter: queryspecification, user, group, usingIndexOrNot
418
            StringBuffer result = metacat.createResultDocument(xmlquery,
419
                    metacatQuery, out, username, groupNames, useXMLIndex);
420

    
421
            // create result set transfer       
422
            String saxparser = PropertyService.getProperty("xml.saxparser");
423
            MetacatResultsetParser metacatResultsetParser = new MetacatResultsetParser(
424
                    new StringReader(result.toString()), saxparser, queryType
425
                            .getNamespace().get_value());
426
            ResultsetType records = metacatResultsetParser.getEcogridResult();
427

    
428
            System.out
429
                    .println(EcogridResultsetTransformer.toXMLString(records));
430
            response.setContentType("text/xml");
431
            out = response.getWriter();
432
            out.print(EcogridResultsetTransformer.toXMLString(records));
433

    
434
        } catch (Exception e) {
435
            e.printStackTrace();
436
        }*/
437
    
438

    
439
  }
440
  
441
  /**
442
   * Returns the object format registered in the DataONE Object Format 
443
   * Vocabulary for the given format identifier
444
   * 
445
   * @param fmtid - the identifier of the format requested
446
   * 
447
   * @return objectFormat - the object format requested
448
   * 
449
   * @throws InvalidRequest
450
   * @throws ServiceFailure
451
   * @throws NotFound
452
   * @throws InsufficientResources
453
   * @throws NotImplemented
454
   */
455
  @Override
456
  public ObjectFormat getFormat(ObjectFormatIdentifier fmtid)
457
    throws InvalidRequest, ServiceFailure, NotFound, InsufficientResources,
458
    NotImplemented {
459
     
460
      return ObjectFormatService.getInstance().getFormat(fmtid);
461
      
462
  }
463

    
464
  /**
465
   * Returns a list of all object formats registered in the DataONE Object 
466
   * Format Vocabulary
467
    * 
468
   * @return objectFormatList - The list of object formats registered in 
469
   *                            the DataONE Object Format Vocabulary
470
   * 
471
   * @throws InvalidRequest
472
   * @throws ServiceFailure
473
   * @throws NotImplemented
474
   * @throws NotFound
475
   * @throws InsufficientResources
476
   */
477
  @Override
478
  public ObjectFormatList listFormats() 
479
    throws InvalidRequest, ServiceFailure, NotFound, InsufficientResources, 
480
    NotImplemented {
481

    
482
    return ObjectFormatService.getInstance().listFormats();
483
  }
484

    
485
  /**
486
   * Returns a list of nodes that have been registered with the DataONE infrastructure
487
    * 
488
   * @return nodeList - List of nodes from the registry
489
   * 
490
   * @throws ServiceFailure
491
   * @throws NotImplemented
492
   */
493
  @Override
494
  public NodeList listNodes() 
495
    throws NotImplemented, ServiceFailure {
496

    
497
    throw new NotImplemented("4800", "listNodes not implemented");
498
  }
499

    
500
  /**
501
   * Provides a mechanism for adding system metadata independently of its 
502
   * associated object, such as when adding system metadata for data objects.
503
    * 
504
   * @param session - the Session object containing the credentials for the Subject
505
   * @param pid - The identifier of the object to register the system metadata against
506
   * @param sysmeta - The system metadata to be registered
507
   * 
508
   * @return true if the registration succeeds
509
   * 
510
   * @throws NotImplemented
511
   * @throws NotAuthorized
512
   * @throws ServiceFailure
513
   * @throws InvalidRequest
514
   * @throws InvalidSystemMetadata
515
   */
516
  @Override
517
  public Identifier registerSystemMetadata(Session session, Identifier guid,
518
    SystemMetadata sysmeta) 
519
    throws NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest, 
520
    InvalidSystemMetadata {
521

    
522
    // TODO: control who can call this?
523
        if (session == null) {
524
            //TODO: many of the thrown exceptions do not use the correct error codes
525
            //check these against the docs and correct them
526
            throw new NotAuthorized("4861", "No Session - could not authorize for registration." +
527
                    "  If you are not logged in, please do so and retry the request.");
528
        }
529
        
530
        // verify that guid == SystemMetadata.getIdentifier()
531
        logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
532
        if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
533
            throw new InvalidRequest("4863", 
534
                "GUID in method call (" + guid.getValue() + ") does not match GUID in system metadata (" +
535
                sysmeta.getIdentifier().getValue() + ").");
536
        }
537

    
538
        logMetacat.debug("Checking if identifier exists...");
539
        // Check that the identifier does not already exist
540
        if (IdentifierManager.getInstance().identifierExists(guid.getValue())) {
541
            throw new InvalidRequest("4863", 
542
                "GUID is already in use by an existing object.");
543
      
544
        }
545

    
546
        // insert the system metadata into the object store
547
        logMetacat.debug("Starting to insert SystemMetadata...");
548
        sysmeta.setDateSysMetadataModified(new Date());
549
        try {
550
          HazelcastService.getInstance().getSystemMetadataMap().lock(sysmeta.getIdentifier());
551
          HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
552
          HazelcastService.getInstance().getSystemMetadataMap().unlock(sysmeta.getIdentifier());
553
        } catch (Exception e) {
554
            throw new ServiceFailure("4862", "Error inserting system metadata: " + e.getClass() + ": " + e.getMessage());
555
        } finally {
556
          HazelcastService.getInstance().getSystemMetadataMap().unlock(sysmeta.getIdentifier());
557

    
558
        }
559
        
560
        logMetacat.debug("Returning from registerSystemMetadata");
561
        EventLog.getInstance().log(null, session.getSubject().getValue(), guid.getValue(), "registerSystemMetadata");
562
        return guid;
563
  }
564

    
565
  /**
566
   * Provides a mechanism for updating system metadata independently of its 
567
   * associated object
568
    * 
569
   * @param session - the Session object containing the credentials for the Subject
570
   * @param pid - The identifier of the system metadata
571
   * @param sysmeta - The system metadata to be registered
572
   * 
573
   * @return true if the update succeeds
574
   * 
575
   * @throws NotImplemented
576
   * @throws NotAuthorized
577
   * @throws ServiceFailure
578
   * @throws InvalidRequest
579
   * @throws InvalidSystemMetadata
580
   * @throws NotFound
581
   */
582
  @Override
583
  public boolean updateSystemMetadata(Session session, Identifier guid,
584
    SystemMetadata sysmeta) 
585
    throws NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest, 
586
    InvalidSystemMetadata, NotFound {
587

    
588
    // TODO: control who can call this?
589
        if (session == null) {
590
            //TODO: many of the thrown exceptions do not use the correct error codes
591
            //check these against the docs and correct them
592
            throw new NotAuthorized("4861", "No Session - could not authorize for update." +
593
                    "  If you are not logged in, please do so and retry the request.");
594
        }
595
        
596
        // verify that guid == SystemMetadata.getIdentifier()
597
        logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
598
        if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
599
            throw new InvalidRequest("4863", 
600
                "GUID in method call (" + guid.getValue() + ") does not match GUID in system metadata (" +
601
                sysmeta.getIdentifier().getValue() + ").");
602
        }
603

    
604
        logMetacat.debug("Checking if identifier exists...");
605
        // Check that the identifier exists
606
        if (!IdentifierManager.getInstance().identifierExists(guid.getValue())) {
607
            throw new NotFound("000", 
608
                "GUID does not exist");
609
        }
610

    
611
        // update the system metadata into the object store
612
        logMetacat.debug("Starting to update SystemMetadata...");
613
        sysmeta.setDateSysMetadataModified(new Date());
614
        
615
        // update system metadata
616
        try {
617
    	    HazelcastService.getInstance().getSystemMetadataMap().lock(sysmeta.getIdentifier());
618
    	    HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
619
    	    HazelcastService.getInstance().getSystemMetadataMap().unlock(sysmeta.getIdentifier());
620
        } catch (Exception e) {
621
    		throw new ServiceFailure("4852", e.getMessage());
622
    	} finally {
623
    	    HazelcastService.getInstance().getSystemMetadataMap().unlock(sysmeta.getIdentifier());
624
    	}
625
        
626
        logMetacat.debug("Returning from updateSystemMetadata");
627
        EventLog.getInstance().log(null, session.getSubject().getValue(), guid.getValue(), "updateSystemMetadata");
628
        return true;
629
  }
630
  
631
  /**
632
   * Given an optional scope and format, reserves and returns an identifier 
633
   * within that scope and format that is unique and will not be 
634
   * used by any other sessions. 
635
    * 
636
   * @param session - the Session object containing the credentials for the Subject
637
   * @param pid - The identifier of the object to register the system metadata against
638
   * @param scope - An optional string to be used to qualify the scope of 
639
   *                the identifier namespace, which is applied differently 
640
   *                depending on the format requested. If scope is not 
641
   *                supplied, a default scope will be used.
642
   * @param format - The optional name of the identifier format to be used, 
643
   *                  drawn from a DataONE-specific vocabulary of identifier 
644
   *                 format names, including several common syntaxes such 
645
   *                 as DOI, LSID, UUID, and LSRN, among others. If the 
646
   *                 format is not supplied by the caller, the CN service 
647
   *                 will use a default identifier format, which may change 
648
   *                 over time.
649
   * 
650
   * @return true if the registration succeeds
651
   * 
652
   * @throws InvalidToken
653
   * @throws ServiceFailure
654
   * @throws NotAuthorized
655
   * @throws IdentifierNotUnique
656
   * @throws NotImplemented
657
   */
658
  @Override
659
  public boolean reserveIdentifier(Session session, Identifier pid)
660
  throws InvalidToken, ServiceFailure,
661
        NotAuthorized, IdentifierNotUnique, NotImplemented, InvalidRequest {
662

    
663
    throw new NotImplemented("4191", "reserveIdentifier not implemented on this node");
664
  }
665
  
666
  @Override
667
  public Identifier generateIdentifier(Session session, String scheme, String fragment)
668
  throws InvalidToken, ServiceFailure,
669
        NotAuthorized, NotImplemented, InvalidRequest {
670
    throw new NotImplemented("4191", "generateIdentifier not implemented on this node");
671
  }
672
  
673
  /**
674
    * Checks whether the pid is reserved by the subject in the session param
675
    * If the reservation is held on the pid by the subject, we return true.
676
    * 
677
   * @param session - the Session object containing the Subject
678
   * @param pid - The identifier to check
679
   * 
680
   * @return true if the reservation exists for the subject/pid
681
   * 
682
   * @throws InvalidToken
683
   * @throws ServiceFailure
684
   * @throws NotFound - when the pid is not found (in use or in reservation)
685
   * @throws NotAuthorized - when the subject does not hold a reservation on the pid
686
   * @throws IdentifierNotUnique - when the pid is in use
687
   * @throws NotImplemented
688
   */
689

    
690
  @Override
691
  public boolean hasReservation(Session session, Identifier pid) 
692
      throws InvalidToken, ServiceFailure, NotFound, NotAuthorized, IdentifierNotUnique, 
693
      NotImplemented, InvalidRequest {
694
  
695
      throw new NotImplemented("4191", "hasReservation not implemented on this node");
696
  }
697

    
698
  /**
699
   * Changes ownership (RightsHolder) of the specified object to the 
700
   * subject specified by userId
701
    * 
702
   * @param session - the Session object containing the credentials for the Subject
703
   * @param pid - Identifier of the object to be modified
704
   * @param userId - The subject that will be taking ownership of the specified object.
705
   *
706
   * @return pid - the identifier of the modified object
707
   * 
708
   * @throws ServiceFailure
709
   * @throws InvalidToken
710
   * @throws NotFound
711
   * @throws NotAuthorized
712
   * @throws NotImplemented
713
   * @throws InvalidRequest
714
   */  
715
  @Override
716
  public Identifier setOwner(Session session, Identifier pid, Subject userId)
717
    throws InvalidToken, ServiceFailure, NotFound, NotAuthorized,
718
    NotImplemented, InvalidRequest {
719
    
720
    // get the subject
721
    Subject subject = session.getSubject();
722
    // get the system metadata
723
    String guid = pid.getValue();
724
    
725
    // are we allowed to do this?
726
    if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
727
      throw new NotAuthorized("4440", "not allowed by " + subject.getValue() + " on " + guid);  
728
    }
729
    
730
    SystemMetadata systemMetadata = null;
731
    try {
732
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(guid);
733
    } catch (McdbDocNotFoundException e) {
734
      throw new NotFound("4460", "No record found for: " + guid);
735
    }
736
        
737
    // set the new rights holder
738
    systemMetadata.setRightsHolder(userId);
739
    
740
    // update the metadata
741
    try {
742
	    HazelcastService.getInstance().getSystemMetadataMap().lock(systemMetadata.getIdentifier());
743
	    HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
744
	    HazelcastService.getInstance().getSystemMetadataMap().unlock(systemMetadata.getIdentifier());
745
    } catch (Exception e) {
746
		throw new ServiceFailure("4490", e.getMessage());
747
	} finally {
748
	    HazelcastService.getInstance().getSystemMetadataMap().unlock(systemMetadata.getIdentifier());
749
	}
750
    
751
    return pid;
752
  }
753

    
754
  /**
755
   * Verify that a replication task is authorized by comparing the target node's
756
   * Subject (from the X.509 certificate-derived Session) with the list of 
757
   * subjects in the known, pending replication tasks map.
758
   * 
759
   * @param originatingNodeSession - Session information that contains the 
760
   *                                 identity of the calling user
761
   * @param targetNodeSubject - Subject identifying the target node
762
   * @param pid - the identifier of the object to be replicated
763
   * @param replicatePermission - the execute permission to be granted
764
   * 
765
   * @throws ServiceFailure
766
   * @throws NotImplemented
767
   * @throws InvalidToken
768
   * @throws NotAuthorized
769
   * @throws InvalidRequest
770
   * @throws NotFound
771
   */
772
  @Override
773
  public boolean isNodeAuthorized(Session originatingNodeSession, 
774
    Subject targetNodeSubject, Identifier pid, Permission replicatePermission) 
775
    throws NotImplemented, NotAuthorized, InvalidToken, ServiceFailure, 
776
    NotFound, InvalidRequest {
777

    
778
	  boolean isAllowed = false;
779
	  SystemMetadata sysmeta = null;
780
    NodeReference targetNode = null;
781
    
782
	  try {
783
	    // get the target node reference from the nodes list
784
	    CNode cn = D1Client.getCN();
785
	    List<Node> nodes = (List<Node>) cn.listNodes();
786

    
787
	    for ( Node node : nodes ) {
788
	        Subject nodeSubject = node.getSubject(0);
789
	        if (nodeSubject.getValue().equals(targetNodeSubject)) {
790
	            targetNode = node.getIdentifier();
791
	            
792
	        }
793
	    }
794
	    
795

    
796
	    //lock, get, and unlock the pid
797
	    HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
798
	    sysmeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
799
	    HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
800
	    List<Replica> replicaList = sysmeta.getReplicaList();
801
	    
802
        // find the replica with the status set to 'requested'
803
        for (Replica replica : replicaList) {
804
            ReplicationStatus status = replica.getReplicationStatus();
805
            NodeReference listedNode = replica.getReplicaMemberNode();
806
            if (listedNode.equals(targetNode)
807
                    && status.equals(ReplicationStatus.REQUESTED)) {
808
                isAllowed = true;
809
                break;
810

    
811
            }
812
        }
813

    
814
	  } catch(Exception e) {
815
	    // Catch Hazelcast RuntimeExceptions
816
	    
817
	  } finally {
818
	    // always unlock the pid
819
      HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
820

    
821
	  }
822
	    
823
	  return isAllowed;
824
    
825
  }
826

    
827
}
(1-1/6)