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.ByteArrayInputStream;
27
import java.io.ByteArrayOutputStream;
28
import java.io.File;
29
import java.io.FileInputStream;
30
import java.io.FileOutputStream;
31
import java.io.IOException;
32
import java.io.InputStream;
33
import java.io.InputStreamReader;
34
import java.io.OutputStreamWriter;
35
import java.io.StringReader;
36
import java.io.UnsupportedEncodingException;
37
import java.io.Writer;
38
import java.math.BigInteger;
39
import java.net.URISyntaxException;
40
import java.nio.charset.Charset;
41
import java.security.NoSuchAlgorithmException;
42
import java.sql.SQLException;
43
import java.util.ArrayList;
44
import java.util.Calendar;
45
import java.util.Date;
46
import java.util.HashMap;
47
import java.util.HashSet;
48
import java.util.Hashtable;
49
import java.util.List;
50
import java.util.Map;
51
import java.util.Set;
52
import java.util.Timer;
53
import java.util.UUID;
54
import java.util.Vector;
55

    
56
import javax.servlet.http.HttpServletRequest;
57
import javax.xml.transform.Result;
58
import javax.xml.transform.Source;
59
import javax.xml.transform.TransformerException;
60
import javax.xml.transform.TransformerFactory;
61
import javax.xml.transform.dom.DOMSource;
62
import javax.xml.transform.stream.StreamResult;
63

    
64
import org.apache.commons.io.IOUtils;
65
import org.apache.log4j.Logger;
66
import org.dataone.client.v2.CNode;
67
import org.dataone.client.v2.itk.D1Client;
68
import org.dataone.client.v2.MNode;
69
import org.dataone.client.v2.formats.ObjectFormatCache;
70
import org.dataone.client.auth.CertificateManager;
71
import org.dataone.client.v2.formats.ObjectFormatInfo;
72
import org.dataone.configuration.Settings;
73
import org.dataone.ore.ResourceMapFactory;
74
import org.dataone.service.exceptions.BaseException;
75
import org.dataone.service.exceptions.IdentifierNotUnique;
76
import org.dataone.service.exceptions.InsufficientResources;
77
import org.dataone.service.exceptions.InvalidRequest;
78
import org.dataone.service.exceptions.InvalidSystemMetadata;
79
import org.dataone.service.exceptions.InvalidToken;
80
import org.dataone.service.exceptions.NotAuthorized;
81
import org.dataone.service.exceptions.NotFound;
82
import org.dataone.service.exceptions.NotImplemented;
83
import org.dataone.service.exceptions.ServiceFailure;
84
import org.dataone.service.exceptions.SynchronizationFailed;
85
import org.dataone.service.exceptions.UnsupportedType;
86
import org.dataone.service.mn.tier1.v2.MNCore;
87
import org.dataone.service.mn.tier1.v2.MNRead;
88
import org.dataone.service.mn.tier2.v2.MNAuthorization;
89
import org.dataone.service.mn.tier3.v2.MNStorage;
90
import org.dataone.service.mn.tier4.v2.MNReplication;
91
import org.dataone.service.mn.v2.MNPackage;
92
import org.dataone.service.mn.v2.MNQuery;
93
import org.dataone.service.mn.v2.MNView;
94
import org.dataone.service.types.v1.AccessRule;
95
import org.dataone.service.types.v1.Checksum;
96
import org.dataone.service.types.v1.DescribeResponse;
97
import org.dataone.service.types.v1.Event;
98
import org.dataone.service.types.v1.Identifier;
99
import org.dataone.service.types.v2.Log;
100
import org.dataone.service.types.v2.LogEntry;
101
import org.dataone.service.types.v2.OptionList;
102
import org.dataone.service.types.v1.MonitorInfo;
103
import org.dataone.service.types.v1.MonitorList;
104
import org.dataone.service.types.v2.Node;
105
import org.dataone.service.types.v2.NodeList;
106
import org.dataone.service.types.v1.NodeReference;
107
import org.dataone.service.types.v1.NodeState;
108
import org.dataone.service.types.v1.NodeType;
109
import org.dataone.service.types.v2.ObjectFormat;
110
import org.dataone.service.types.v1.Group;
111
import org.dataone.service.types.v1.ObjectFormatIdentifier;
112
import org.dataone.service.types.v1.ObjectList;
113
import org.dataone.service.types.v1.Permission;
114
import org.dataone.service.types.v1.Ping;
115
import org.dataone.service.types.v1.Replica;
116
import org.dataone.service.types.v1.ReplicationStatus;
117
import org.dataone.service.types.v1.Schedule;
118
import org.dataone.service.types.v1.Service;
119
import org.dataone.service.types.v1.Services;
120
import org.dataone.service.types.v1.Session;
121
import org.dataone.service.types.v1.Subject;
122
import org.dataone.service.types.v1.Synchronization;
123
import org.dataone.service.types.v2.SystemMetadata;
124
import org.dataone.service.types.v1.util.AuthUtils;
125
import org.dataone.service.types.v1.util.ChecksumUtil;
126
import org.dataone.service.types.v1_1.QueryEngineDescription;
127
import org.dataone.service.types.v1_1.QueryEngineList;
128
import org.dataone.service.types.v1_1.QueryField;
129
import org.dataone.service.util.Constants;
130
import org.dataone.service.util.TypeMarshaller;
131
import org.dspace.foresite.OREException;
132
import org.dspace.foresite.OREParserException;
133
import org.dspace.foresite.ORESerialiserException;
134
import org.dspace.foresite.ResourceMap;
135
import org.ecoinformatics.datamanager.parser.DataPackage;
136
import org.ecoinformatics.datamanager.parser.Entity;
137
import org.ecoinformatics.datamanager.parser.generic.DataPackageParserInterface;
138
import org.ecoinformatics.datamanager.parser.generic.Eml200DataPackageParser;
139
import org.w3c.dom.Document;
140

    
141
import edu.ucsb.nceas.ezid.EZIDException;
142
import edu.ucsb.nceas.metacat.DBQuery;
143
import edu.ucsb.nceas.metacat.DBTransform;
144
import edu.ucsb.nceas.metacat.EventLog;
145
import edu.ucsb.nceas.metacat.IdentifierManager;
146
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
147
import edu.ucsb.nceas.metacat.MetaCatServlet;
148
import edu.ucsb.nceas.metacat.MetacatHandler;
149
import edu.ucsb.nceas.metacat.ReadOnlyChecker;
150
import edu.ucsb.nceas.metacat.common.query.EnabledQueryEngines;
151
import edu.ucsb.nceas.metacat.common.query.stream.ContentTypeByteArrayInputStream;
152
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
153
import edu.ucsb.nceas.metacat.index.MetacatSolrEngineDescriptionHandler;
154
import edu.ucsb.nceas.metacat.index.MetacatSolrIndex;
155
import edu.ucsb.nceas.metacat.properties.PropertyService;
156
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
157
import edu.ucsb.nceas.metacat.util.DeleteOnCloseFileInputStream;
158
import edu.ucsb.nceas.metacat.util.DocumentUtil;
159
import edu.ucsb.nceas.metacat.util.SkinUtil;
160
import edu.ucsb.nceas.metacat.util.SystemUtil;
161
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
162
import edu.ucsb.nceas.utilities.XMLUtilities;
163
import edu.ucsb.nceas.utilities.export.HtmlToPdf;
164
import gov.loc.repository.bagit.Bag;
165
import gov.loc.repository.bagit.BagFactory;
166
import gov.loc.repository.bagit.writer.impl.ZipWriter;
167

    
168
/**
169
 * Represents Metacat's implementation of the DataONE Member Node 
170
 * service API. Methods implement the various MN* interfaces, and methods common
171
 * to both Member Node and Coordinating Node interfaces are found in the
172
 * D1NodeService base class.
173
 * 
174
 * Implements:
175
 * MNCore.ping()
176
 * MNCore.getLogRecords()
177
 * MNCore.getObjectStatistics()
178
 * MNCore.getOperationStatistics()
179
 * MNCore.getStatus()
180
 * MNCore.getCapabilities()
181
 * MNRead.get()
182
 * MNRead.getSystemMetadata()
183
 * MNRead.describe()
184
 * MNRead.getChecksum()
185
 * MNRead.listObjects()
186
 * MNRead.synchronizationFailed()
187
 * MNAuthorization.isAuthorized()
188
 * MNAuthorization.setAccessPolicy()
189
 * MNStorage.create()
190
 * MNStorage.update()
191
 * MNStorage.delete()
192
 * MNStorage.updateSystemMetadata()
193
 * MNReplication.replicate()
194
 * 
195
 */
196
public class MNodeService extends D1NodeService 
197
    implements MNAuthorization, MNCore, MNRead, MNReplication, MNStorage, MNQuery, MNView, MNPackage {
198

    
199
    //private static final String PATHQUERY = "pathquery";
200
	public static final String UUID_SCHEME = "UUID";
201
	public static final String DOI_SCHEME = "DOI";
202
	private static final String UUID_PREFIX = "urn:uuid:";
203
	
204
	private static String XPATH_EML_ID = "/eml:eml/@packageId";
205

    
206
	/* the logger instance */
207
    private Logger logMetacat = null;
208
    
209
    /* A reference to a remote Memeber Node */
210
    //private MNode mn;
211
    
212
    /* A reference to a Coordinating Node */
213
    private CNode cn;
214

    
215

    
216
    /**
217
     * Singleton accessor to get an instance of MNodeService.
218
     * 
219
     * @return instance - the instance of MNodeService
220
     */
221
    public static MNodeService getInstance(HttpServletRequest request) {
222
        return new MNodeService(request);
223
    }
224

    
225
    /**
226
     * Constructor, private for singleton access
227
     */
228
    private MNodeService(HttpServletRequest request) {
229
        super(request);
230
        logMetacat = Logger.getLogger(MNodeService.class);
231
        
232
        // set the Member Node certificate file location
233
        CertificateManager.getInstance().setCertificateLocation(Settings.getConfiguration().getString("D1Client.certificate.file"));
234
    }
235

    
236
    /**
237
     * Deletes an object from the Member Node, where the object is either a 
238
     * data object or a science metadata object.
239
     * 
240
     * @param session - the Session object containing the credentials for the Subject
241
     * @param pid - The object identifier to be deleted
242
     * 
243
     * @return pid - the identifier of the object used for the deletion
244
     * 
245
     * @throws InvalidToken
246
     * @throws ServiceFailure
247
     * @throws NotAuthorized
248
     * @throws NotFound
249
     * @throws NotImplemented
250
     * @throws InvalidRequest
251
     */
252
    @Override
253
    public Identifier delete(Session session, Identifier pid) 
254
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
255

    
256
        if(isReadOnlyMode()) {
257
            throw new ServiceFailure("2902", ReadOnlyChecker.DATAONEERROR);
258
        }
259
    	// only admin of  the MN or the CN is allowed a full delete
260
        boolean allowed = false;
261
        allowed = isAdminAuthorized(session);
262
        
263
        String serviceFailureCode = "2902";
264
        Identifier sid = getPIDForSID(pid, serviceFailureCode);
265
        if(sid != null) {
266
            pid = sid;
267
        }
268
        
269
        //check if it is the authoritative member node
270
        if(!allowed) {
271
            allowed = isAuthoritativeMNodeAdmin(session, pid);
272
        }
273
        
274
        if (!allowed) { 
275
            throw new NotAuthorized("1320", "The provided identity does not have " + "permission to delete objects on the Node.");
276
        }
277
    	
278
    	// defer to superclass implementation
279
        return super.delete(session, pid);
280
    }
281

    
282
    /**
283
     * Updates an existing object by creating a new object identified by 
284
     * newPid on the Member Node which explicitly obsoletes the object 
285
     * identified by pid through appropriate changes to the SystemMetadata 
286
     * of pid and newPid
287
     * 
288
     * @param session - the Session object containing the credentials for the Subject
289
     * @param pid - The identifier of the object to be updated
290
     * @param object - the new object bytes
291
     * @param sysmeta - the new system metadata describing the object
292
     * 
293
     * @return newPid - the identifier of the new object
294
     * 
295
     * @throws InvalidToken
296
     * @throws ServiceFailure
297
     * @throws NotAuthorized
298
     * @throws NotFound
299
     * @throws NotImplemented
300
     * @throws IdentifierNotUnique
301
     * @throws UnsupportedType
302
     * @throws InsufficientResources
303
     * @throws InvalidSystemMetadata
304
     * @throws InvalidRequest
305
     */
306
    @Override
307
    public Identifier update(Session session, Identifier pid, InputStream object, 
308
        Identifier newPid, SystemMetadata sysmeta) 
309
        throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
310
        UnsupportedType, InsufficientResources, NotFound, 
311
        InvalidSystemMetadata, NotImplemented, InvalidRequest {
312
        
313
        if(isReadOnlyMode()) {
314
            throw new ServiceFailure("1310", ReadOnlyChecker.DATAONEERROR);
315
        }
316

    
317
        //transform a sid to a pid if it is applicable
318
        String serviceFailureCode = "1310";
319
        Identifier sid = getPIDForSID(pid, serviceFailureCode);
320
        if(sid != null) {
321
            pid = sid;
322
        }
323
        
324
        String localId = null;
325
        boolean allowed = false;
326
        boolean isScienceMetadata = false;
327
        
328
        if (session == null) {
329
        	throw new InvalidToken("1210", "No session has been provided");
330
        }
331
        Subject subject = session.getSubject();
332

    
333
        // verify the pid is valid format
334
        if (!isValidIdentifier(pid)) {
335
        	throw new InvalidRequest("1202", "The provided identifier is invalid.");
336
        }
337
        
338
        // verify the new pid is valid format
339
        if (!isValidIdentifier(newPid)) {
340
            throw new InvalidRequest("1202", "The provided identifier is invalid.");
341
        }
342
        
343
        // make sure that the newPid doesn't exists
344
        boolean idExists = true;
345
        try {
346
            idExists = IdentifierManager.getInstance().identifierExists(newPid.getValue());
347
        } catch (SQLException e) {
348
            throw new ServiceFailure("1310", 
349
                                    "The requested identifier " + newPid.getValue() +
350
                                    " couldn't be determined if it is unique since : "+e.getMessage());
351
        }
352
        if (idExists) {
353
                throw new IdentifierNotUnique("1220", 
354
                          "The requested identifier " + newPid.getValue() +
355
                          " is already used by another object and" +
356
                          "therefore can not be used for this object. Clients should choose" +
357
                          "a new identifier that is unique and retry the operation or " +
358
                          "use CN.reserveIdentifier() to reserve one.");
359
            
360
        }
361
        
362
       
363

    
364
        // check for the existing identifier
365
        try {
366
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
367
            
368
        } catch (McdbDocNotFoundException e) {
369
            throw new InvalidRequest("1202", "The object with the provided " + 
370
                "identifier was not found.");
371
            
372
        } catch (SQLException ee) {
373
            throw new ServiceFailure("1310", "The object with the provided " + 
374
                    "identifier "+pid.getValue()+" can't be identified since - "+ee.getMessage());
375
        }
376
        
377
        // set the originating node
378
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
379
        sysmeta.setOriginMemberNode(originMemberNode);
380
        
381
        // set the submitter to match the certificate
382
        sysmeta.setSubmitter(subject);
383
        // set the dates
384
        Date now = Calendar.getInstance().getTime();
385
        sysmeta.setDateSysMetadataModified(now);
386
        sysmeta.setDateUploaded(now);
387
        
388
        // make sure serial version is set to something
389
        BigInteger serialVersion = sysmeta.getSerialVersion();
390
        if (serialVersion == null) {
391
        	sysmeta.setSerialVersion(BigInteger.ZERO);
392
        }
393

    
394
        // does the subject have WRITE ( == update) priveleges on the pid?
395
        //allowed = isAuthorized(session, pid, Permission.WRITE);
396
        //CN having the permission is allowed; user with the write permission and calling on the authoritative node is allowed.
397
        allowed = allowUpdating(session, pid, Permission.WRITE);
398
        if (allowed) {
399
        	
400
        	// check quality of SM
401
        	if (sysmeta.getObsoletedBy() != null) {
402
        		throw new InvalidSystemMetadata("1300", "Cannot include obsoletedBy when updating object");
403
        	}
404
        	if (sysmeta.getObsoletes() != null && !sysmeta.getObsoletes().getValue().equals(pid.getValue())) {
405
        		throw new InvalidSystemMetadata("1300", "The identifier provided in obsoletes does not match old Identifier");
406
        	}
407

    
408
            // get the existing system metadata for the object
409
            SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
410
            //System.out.println("the archive is "+existingSysMeta.getArchived());
411
            //Base on documentation, we can't update an archived object:
412
            //The update operation MUST fail with Exceptions.InvalidRequest on objects that have the Types.SystemMetadata.archived property set to true.
413
            if(existingSysMeta.getArchived() != null && existingSysMeta.getArchived()) {
414
                throw new InvalidRequest("1202","An archived object"+pid.getValue()+" can't be updated");
415
            }
416

    
417
            // check for previous update
418
            // see: https://redmine.dataone.org/issues/3336
419
            Identifier existingObsoletedBy = existingSysMeta.getObsoletedBy();
420
            if (existingObsoletedBy != null) {
421
            	throw new InvalidRequest("1202", 
422
            			"The previous identifier has already been made obsolete by: " + existingObsoletedBy.getValue());
423
            }
424
            //check the sid in the system metadata. If it exists, it should be non-exist or match the old sid in the previous system metadata.
425
            Identifier sidInSys = sysmeta.getSeriesId();
426
            if(sidInSys != null) {
427
                if (!isValidIdentifier(sidInSys)) {
428
                    throw new InvalidSystemMetadata("1300", "The provided series id in the system metadata is invalid.");
429
                }
430
                Identifier previousSid = existingSysMeta.getSeriesId();
431
                if(previousSid != null) {
432
                    // there is a previous sid, if the new sid doesn't match it, the new sid should be non-existing.
433
                    if(!sidInSys.getValue().equals(previousSid.getValue())) {
434
                        try {
435
                            idExists = IdentifierManager.getInstance().identifierExists(sidInSys.getValue());
436
                        } catch (SQLException e) {
437
                            throw new ServiceFailure("1310", 
438
                                                    "The requested identifier " + sidInSys.getValue() +
439
                                                    " couldn't be determined if it is unique since : "+e.getMessage());
440
                        }
441
                        if(idExists) {
442
                            throw new InvalidSystemMetadata("1300", "The series id "+sidInSys.getValue()+" in the system metadata doesn't match the previous series id "
443
                                                            +previousSid.getValue()+", so it should NOT exist. However, it was used by another object.");
444
                        }
445
                    }
446
                } else {
447
                    // there is no previous sid, the new sid should be non-existing.
448
                    try {
449
                        idExists = IdentifierManager.getInstance().identifierExists(sidInSys.getValue());
450
                    } catch (SQLException e) {
451
                        throw new ServiceFailure("1310", 
452
                                                "The requested identifier " + sidInSys.getValue() +
453
                                                " couldn't be determined if it is unique since : "+e.getMessage());
454
                    }
455
                    if(idExists) {
456
                        throw new InvalidSystemMetadata("1300", "The series id "+sidInSys.getValue()+" in the system metadata should NOT exist since the previous series id is null."
457
                                                        +"However, it was used by another object.");
458
                    }
459
                }
460
                //the series id equals the pid (new pid hasn't been registered in the system, so IdentifierManager.getInstance().identifierExists method can't exclude this scenario)
461
                if(sidInSys.getValue().equals(newPid.getValue())) {
462
                    throw new InvalidSystemMetadata("1300", "The series id "+sidInSys.getValue()+" in the system metadata shouldn't have the same value of the pid.");
463
                }
464
            }
465

    
466
            isScienceMetadata = isScienceMetadata(sysmeta);
467

    
468
            // do we have XML metadata or a data object?
469
            if (isScienceMetadata) {
470

    
471
                // update the science metadata XML document
472
                // TODO: handle non-XML metadata/data documents (like netCDF)
473
                // TODO: don't put objects into memory using stream to string
474
                //String objectAsXML = "";
475
                try {
476
                    //objectAsXML = IOUtils.toString(object, "UTF-8");
477
                	
478
                    localId = insertOrUpdateDocument(object, "UTF-8", pid, session, "update");
479
                    
480
                    // register the newPid and the generated localId
481
                    if (newPid != null) {
482
                        IdentifierManager.getInstance().createMapping(newPid.getValue(), localId);
483
                    }
484

    
485
                } catch (IOException e) {
486
                    String msg = "The Node is unable to create the object. " + "There was a problem converting the object to XML";
487
                    logMetacat.info(msg);
488
                    throw new ServiceFailure("1310", msg + ": " + e.getMessage());
489

    
490
                }
491

    
492
            } else {
493

    
494
                // update the data object
495
                localId = insertDataObject(object, newPid, session);
496

    
497
            }
498
            
499
            // add the newPid to the obsoletedBy list for the existing sysmeta
500
            existingSysMeta.setObsoletedBy(newPid);
501
            //increase version
502
            BigInteger current = existingSysMeta.getSerialVersion();
503
            //System.out.println("the current version is "+current);
504
            current = current.add(BigInteger.ONE);
505
            //System.out.println("the new current version is "+current);
506
            existingSysMeta.setSerialVersion(current);
507
            // then update the existing system metadata
508
            updateSystemMetadata(existingSysMeta);
509

    
510
            // prep the new system metadata, add pid to the affected lists
511
            sysmeta.setObsoletes(pid);
512
            //sysmeta.addDerivedFrom(pid);
513

    
514
            // and insert the new system metadata
515
            insertSystemMetadata(sysmeta);
516

    
517
            // log the update event
518
            EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), subject.getValue(), localId, Event.UPDATE.toString());
519
            
520
            // attempt to register the identifier - it checks if it is a doi
521
            try {
522
    			DOIService.getInstance().registerDOI(sysmeta);
523
    		} catch (Exception e) {
524
                throw new ServiceFailure("1190", "Could not register DOI: " + e.getMessage());
525
    		}
526

    
527
        } else {
528
            throw new NotAuthorized("1200", "The provided identity does not have " + "permission to UPDATE the object identified by " + pid.getValue()
529
                    + " on the Member Node.");
530
        }
531

    
532
        return newPid;
533
    }
534

    
535
    public Identifier create(Session session, Identifier pid, InputStream object, SystemMetadata sysmeta) throws InvalidToken, ServiceFailure, NotAuthorized,
536
            IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, InvalidRequest {
537

    
538
        if(isReadOnlyMode()) {
539
            throw new ServiceFailure("1190", ReadOnlyChecker.DATAONEERROR);
540
        }
541
        // check for null session
542
        if (session == null) {
543
          throw new InvalidToken("1110", "Session is required to WRITE to the Node.");
544
        }
545
        // verify the pid is valid format
546
        if (!isValidIdentifier(pid)) {
547
            throw new InvalidRequest("1102", "The provided identifier is invalid.");
548
        }
549
        // set the submitter to match the certificate
550
        sysmeta.setSubmitter(session.getSubject());
551
        // set the originating node
552
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
553
        sysmeta.setOriginMemberNode(originMemberNode);
554
        sysmeta.setArchived(false);
555

    
556
        // set the dates
557
        Date now = Calendar.getInstance().getTime();
558
        sysmeta.setDateSysMetadataModified(now);
559
        sysmeta.setDateUploaded(now);
560
        
561
        // set the serial version
562
        sysmeta.setSerialVersion(BigInteger.ZERO);
563

    
564
        // check that we are not attempting to subvert versioning
565
        if (sysmeta.getObsoletes() != null && sysmeta.getObsoletes().getValue() != null) {
566
            throw new InvalidSystemMetadata("1180", 
567
              "The supplied system metadata is invalid. " +
568
              "The obsoletes field cannot have a value when creating entries.");
569
        }
570
        
571
        if (sysmeta.getObsoletedBy() != null && sysmeta.getObsoletedBy().getValue() != null) {
572
            throw new InvalidSystemMetadata("1180", 
573
              "The supplied system metadata is invalid. " +
574
              "The obsoletedBy field cannot have a value when creating entries.");
575
        }
576
        
577
        // verify the sid in the system metadata
578
        Identifier sid = sysmeta.getSeriesId();
579
        boolean idExists = false;
580
        if(sid != null) {
581
            if (!isValidIdentifier(sid)) {
582
                throw new InvalidSystemMetadata("1180", "The provided series id is invalid.");
583
            }
584
            try {
585
                idExists = IdentifierManager.getInstance().identifierExists(sid.getValue());
586
            } catch (SQLException e) {
587
                throw new ServiceFailure("1190", 
588
                                        "The series identifier " + sid.getValue() +
589
                                        " in the system metadata couldn't be determined if it is unique since : "+e.getMessage());
590
            }
591
            if (idExists) {
592
                    throw new InvalidSystemMetadata("1180", 
593
                              "The series identifier " + sid.getValue() +
594
                              " is already used by another object and" +
595
                              "therefore can not be used for this object. Clients should choose" +
596
                              "a new identifier that is unique and retry the operation or " +
597
                              "use CN.reserveIdentifier() to reserve one.");
598
                
599
            }
600
            //the series id equals the pid (new pid hasn't been registered in the system, so IdentifierManager.getInstance().identifierExists method can't exclude this scenario )
601
            if(sid.getValue().equals(pid.getValue())) {
602
                throw new InvalidSystemMetadata("1180", "The series id "+sid.getValue()+" in the system metadata shouldn't have the same value of the pid.");
603
            }
604
        }
605

    
606
        // call the shared impl
607
        Identifier resultPid = super.create(session, pid, object, sysmeta);
608
        
609
        // attempt to register the identifier - it checks if it is a doi
610
        try {
611
			DOIService.getInstance().registerDOI(sysmeta);
612
		} catch (Exception e) {
613
			ServiceFailure sf = new ServiceFailure("1190", "Could not register DOI: " + e.getMessage());
614
			sf.initCause(e);
615
            throw sf;
616
		}
617
        
618
        // return 
619
		return resultPid ;
620
    }
621

    
622
    /**
623
     * Called by a Coordinating Node to request that the Member Node create a 
624
     * copy of the specified object by retrieving it from another Member 
625
     * Node and storing it locally so that it can be made accessible to 
626
     * the DataONE system.
627
     * 
628
     * @param session - the Session object containing the credentials for the Subject
629
     * @param sysmeta - Copy of the CN held system metadata for the object
630
     * @param sourceNode - A reference to node from which the content should be 
631
     *                     retrieved. The reference should be resolved by 
632
     *                     checking the CN node registry.
633
     * 
634
     * @return true if the replication succeeds
635
     * 
636
     * @throws ServiceFailure
637
     * @throws NotAuthorized
638
     * @throws NotImplemented
639
     * @throws UnsupportedType
640
     * @throws InsufficientResources
641
     * @throws InvalidRequest
642
     */
643
    @Override
644
    public boolean replicate(Session session, SystemMetadata sysmeta,
645
            NodeReference sourceNode) throws NotImplemented, ServiceFailure,
646
            NotAuthorized, InvalidRequest, InsufficientResources,
647
            UnsupportedType {
648
        /*if(isReadOnlyMode()) {
649
            throw new InvalidRequest("2153", "The Metacat member node is on the read-only mode and your request can't be fulfiled. Please try again later.");
650
        }*/
651

    
652
        if (session != null && sysmeta != null && sourceNode != null) {
653
            logMetacat.info("MNodeService.replicate() called with parameters: \n" +
654
                            "\tSession.Subject      = "                           +
655
                            session.getSubject().getValue() + "\n"                +
656
                            "\tidentifier           = "                           + 
657
                            sysmeta.getIdentifier().getValue()                    +
658
                            "\n" + "\tSource NodeReference ="                     +
659
                            sourceNode.getValue());
660
        }
661
        boolean result = false;
662
        String nodeIdStr = null;
663
        NodeReference nodeId = null;
664

    
665
        // get the referenced object
666
        Identifier pid = sysmeta.getIdentifier();
667
        // verify the pid is valid format
668
        if (!isValidIdentifier(pid)) {
669
            throw new InvalidRequest("2153", "The provided identifier in the system metadata is invalid.");
670
        }
671

    
672
        // get from the membernode
673
        // TODO: switch credentials for the server retrieval?
674
        this.cn = D1Client.getCN();
675
        InputStream object = null;
676
        Session thisNodeSession = null;
677
        SystemMetadata localSystemMetadata = null;
678
        BaseException failure = null;
679
        String localId = null;
680
        
681
        // TODO: check credentials
682
        // cannot be called by public
683
        if (session == null || session.getSubject() == null) {
684
            String msg = "No session was provided to replicate identifier " +
685
            sysmeta.getIdentifier().getValue();
686
            logMetacat.error(msg);
687
            throw new NotAuthorized("2152", msg);
688
            
689
        }
690

    
691

    
692
        // get the local node id
693
        try {
694
            nodeIdStr = PropertyService.getProperty("dataone.nodeId");
695
            nodeId = new NodeReference();
696
            nodeId.setValue(nodeIdStr);
697

    
698
        } catch (PropertyNotFoundException e1) {
699
            String msg = "Couldn't get dataone.nodeId property: " + e1.getMessage();
700
            failure = new ServiceFailure("2151", msg);
701
            //setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
702
            logMetacat.error(msg);
703
            //return true;
704
            throw new ServiceFailure("2151", msg);
705

    
706
        }
707
        
708

    
709
        try {
710
            // do we already have a replica?
711
            try {
712
                localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
713
                // if we have a local id, get the local object
714
                try {
715
                    object = MetacatHandler.read(localId);
716
                } catch (Exception e) {
717
                	// NOTE: we may already know about this ID because it could be a data file described by a metadata file
718
                	// https://redmine.dataone.org/issues/2572
719
                	// TODO: fix this so that we don't prevent ourselves from getting replicas
720
                	
721
                    // let the CN know that the replication failed
722
                	logMetacat.warn("Object content not found on this node despite having localId: " + localId);
723
                	String msg = "Can't read the object bytes properly, replica is invalid.";
724
                    ServiceFailure serviceFailure = new ServiceFailure("2151", msg);
725
                    setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, serviceFailure);
726
                    logMetacat.warn(msg);
727
                    throw serviceFailure;
728
                    
729
                }
730

    
731
            } catch (McdbDocNotFoundException e) {
732
                logMetacat.info("No replica found. Continuing.");
733
                
734
            } catch (SQLException ee) {
735
                throw new ServiceFailure("2151", "Couldn't identify the local id of the object with the specified identifier "
736
                                        +pid.getValue()+" since - "+ee.getMessage());
737
            }
738
            
739
            // no local replica, get a replica
740
            if ( object == null ) {
741
                /*boolean success = true;
742
                try {
743
                    //use the v2 ping api to connect the source node
744
                    mn.ping();
745
                } catch (Exception e) {
746
                    success = false;
747
                }*/
748
                D1NodeVersionChecker checker = new D1NodeVersionChecker(sourceNode);
749
                String nodeVersion = checker.getVersion("MNRead");
750
                if(nodeVersion != null && nodeVersion.equals(D1NodeVersionChecker.V1)) {
751
                    //The source node is a v1 node, we use the v1 api
752
                    org.dataone.client.v1.MNode mNodeV1 =  org.dataone.client.v1.itk.D1Client.getMN(sourceNode);
753
                    object = mNodeV1.getReplica(thisNodeSession, pid);
754
                } else if (nodeVersion != null && nodeVersion.equals(D1NodeVersionChecker.V2)){
755
                 // session should be null to use the default certificate
756
                    // location set in the Certificate manager
757
                    MNode mn = D1Client.getMN(sourceNode);
758
                    object = mn.getReplica(thisNodeSession, pid);
759
                } else {
760
                    throw new ServiceFailure("2151", "The version of MNRead service is "+nodeVersion+" in the source node "+sourceNode.getValue()+" and it is supported. Please check the information in the cn");
761
                }
762
                
763
                logMetacat.info("MNodeService.getReplica() called for identifier "
764
                                + pid.getValue());
765

    
766
            }
767

    
768
        } catch (InvalidToken e) {            
769
            String msg = "Could not retrieve object to replicate (InvalidToken): "+ e.getMessage();
770
            failure = new ServiceFailure("2151", msg);
771
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
772
            logMetacat.error(msg);
773
            throw new ServiceFailure("2151", msg);
774

    
775
        } catch (NotFound e) {
776
            String msg = "Could not retrieve object to replicate (NotFound): "+ e.getMessage();
777
            failure = new ServiceFailure("2151", msg);
778
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
779
            logMetacat.error(msg);
780
            throw new ServiceFailure("2151", msg);
781

    
782
        } catch (NotAuthorized e) {
783
            String msg = "Could not retrieve object to replicate (NotAuthorized): "+ e.getMessage();
784
            failure = new ServiceFailure("2151", msg);
785
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
786
            logMetacat.error(msg);
787
            throw new ServiceFailure("2151", msg);
788
        } catch (NotImplemented e) {
789
            String msg = "Could not retrieve object to replicate (mn.getReplica NotImplemented): "+ e.getMessage();
790
            failure = new ServiceFailure("2151", msg);
791
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
792
            logMetacat.error(msg);
793
            throw new ServiceFailure("2151", msg);
794
        } catch (ServiceFailure e) {
795
            String msg = "Could not retrieve object to replicate (ServiceFailure): "+ e.getMessage();
796
            failure = new ServiceFailure("2151", msg);
797
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
798
            logMetacat.error(msg);
799
            throw new ServiceFailure("2151", msg);
800
        } catch (InsufficientResources e) {
801
            String msg = "Could not retrieve object to replicate (InsufficientResources): "+ e.getMessage();
802
            failure = new ServiceFailure("2151", msg);
803
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
804
            logMetacat.error(msg);
805
            throw new ServiceFailure("2151", msg);
806
        }
807

    
808
        // verify checksum on the object, if supported
809
        if (object.markSupported()) {
810
            Checksum givenChecksum = sysmeta.getChecksum();
811
            Checksum computedChecksum = null;
812
            try {
813
                computedChecksum = ChecksumUtil.checksum(object, givenChecksum.getAlgorithm());
814
                object.reset();
815

    
816
            } catch (Exception e) {
817
                String msg = "Error computing checksum on replica: " + e.getMessage();
818
                logMetacat.error(msg);
819
                ServiceFailure sf = new ServiceFailure("2151", msg);
820
                sf.initCause(e);
821
                setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, sf);
822
                throw sf;
823
            }
824
            if (!givenChecksum.getValue().equals(computedChecksum.getValue())) {
825
                logMetacat.error("Given    checksum for " + pid.getValue() + 
826
                    "is " + givenChecksum.getValue());
827
                logMetacat.error("Computed checksum for " + pid.getValue() + 
828
                    "is " + computedChecksum.getValue());
829
                String msg = "Computed checksum does not match declared checksum";
830
                failure = new ServiceFailure("2151", msg);
831
                setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
832
                throw new ServiceFailure("2151", msg);
833
            }
834
        }
835

    
836
        // add it to local store
837
        Identifier retPid;
838
        try {
839
            // skip the MN.create -- this mutates the system metadata and we don't want it to
840
            if ( localId == null ) {
841
                // TODO: this will fail if we already "know" about the identifier
842
            	// FIXME: see https://redmine.dataone.org/issues/2572
843
                retPid = super.create(session, pid, object, sysmeta);
844
                result = (retPid.getValue().equals(pid.getValue()));
845
            }
846
            
847
        } catch (Exception e) {
848
            String msg = "Could not save object to local store (" + e.getClass().getName() + "): " + e.getMessage();
849
            failure = new ServiceFailure("2151", msg);
850
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
851
            logMetacat.error(msg);
852
            throw new ServiceFailure("2151", msg);
853
            
854
        }
855

    
856
        // finish by setting the replication status
857
        setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.COMPLETED, null);
858
        return result;
859

    
860
    }
861
    
862
    /*
863
     * If the given node supports v2 replication.
864
     */
865
    private boolean supportV2Replication(Node node) throws InvalidRequest {
866
        return supportVersionReplication(node, "v2");
867
    }
868
    
869
    /*
870
     * If the given node support the the given version replication. Return true if it does.
871
     */
872
    private boolean supportVersionReplication(Node node, String version) throws InvalidRequest{
873
        boolean support = false;
874
        if(node == null) {
875
            throw new InvalidRequest("2153", "There is no capacity information about the node in the replicate.");
876
        } else {
877
            Services services = node.getServices();
878
            if(services == null) {
879
                throw new InvalidRequest("2153", "Can't get replica from a node which doesn't have the replicate service.");
880
            } else {
881
               List<Service> list = services.getServiceList();
882
               if(list == null) {
883
                   throw new InvalidRequest("2153", "Can't get replica from a node which doesn't have the replicate service.");
884
               } else {
885
                   for(Service service : list) {
886
                       if(service != null && service.getName() != null && service.getName().equals("MNReplication") && 
887
                               service.getVersion() != null && service.getVersion().equalsIgnoreCase(version) && service.getAvailable() == true ) {
888
                           support = true;
889
                           
890
                       }
891
                   }
892
               }
893
            }
894
        }
895
        return support;
896
    }
897

    
898
    /**
899
     * Return the object identified by the given object identifier
900
     * 
901
     * @param session - the Session object containing the credentials for the Subject
902
     * @param pid - the object identifier for the given object
903
     * 
904
     * @return inputStream - the input stream of the given object
905
     * 
906
     * @throws InvalidToken
907
     * @throws ServiceFailure
908
     * @throws NotAuthorized
909
     * @throws InvalidRequest
910
     * @throws NotImplemented
911
     */
912
    @Override
913
    public InputStream get(Session session, Identifier pid) 
914
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
915

    
916
        return super.get(session, pid);
917

    
918
    }
919

    
920
    /**
921
     * Returns a Checksum for the specified object using an accepted hashing algorithm
922
     * 
923
     * @param session - the Session object containing the credentials for the Subject
924
     * @param pid - the object identifier for the given object
925
     * @param algorithm -  the name of an algorithm that will be used to compute 
926
     *                     a checksum of the bytes of the object
927
     * 
928
     * @return checksum - the checksum of the given object
929
     * 
930
     * @throws InvalidToken
931
     * @throws ServiceFailure
932
     * @throws NotAuthorized
933
     * @throws NotFound
934
     * @throws InvalidRequest
935
     * @throws NotImplemented
936
     */
937
    @Override
938
    public Checksum getChecksum(Session session, Identifier pid, String algorithm) 
939
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
940
        InvalidRequest, NotImplemented {
941

    
942
        Checksum checksum = null;
943
        String serviceFailure = "1410";
944
        String notFound = "1420";
945
        //Checkum only handles the pid, not sid
946
        checkV1SystemMetaPidExist(pid, serviceFailure, "The checksum for the object specified by "+pid.getValue()+" couldn't be returned ",  notFound, 
947
                "The object specified by "+pid.getValue()+" does not exist at this node.");
948
        InputStream inputStream = get(session, pid);
949

    
950
        try {
951
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
952

    
953
        } catch (NoSuchAlgorithmException e) {
954
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
955
                    + e.getMessage());
956
        } catch (IOException e) {
957
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
958
                    + e.getMessage());
959
        }
960

    
961
        if (checksum == null) {
962
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
963
        }
964

    
965
        return checksum;
966
    }
967

    
968
    /**
969
     * Return the system metadata for a given object
970
     * 
971
     * @param session - the Session object containing the credentials for the Subject
972
     * @param pid - the object identifier for the given object
973
     * 
974
     * @return inputStream - the input stream of the given system metadata object
975
     * 
976
     * @throws InvalidToken
977
     * @throws ServiceFailure
978
     * @throws NotAuthorized
979
     * @throws NotFound
980
     * @throws InvalidRequest
981
     * @throws NotImplemented
982
     */
983
    @Override
984
    public SystemMetadata getSystemMetadata(Session session, Identifier pid) 
985
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
986
        NotImplemented {
987

    
988
        return super.getSystemMetadata(session, pid);
989
    }
990

    
991
    /**
992
     * Retrieve the list of objects present on the MN that match the calling parameters
993
     * 
994
     * @param session - the Session object containing the credentials for the Subject
995
     * @param startTime - Specifies the beginning of the time range from which 
996
     *                    to return object (>=)
997
     * @param endTime - Specifies the beginning of the time range from which 
998
     *                  to return object (>=)
999
     * @param objectFormat - Restrict results to the specified object format
1000
     * @param replicaStatus - Indicates if replicated objects should be returned in the list
1001
     * @param start - The zero-based index of the first value, relative to the 
1002
     *                first record of the resultset that matches the parameters.
1003
     * @param count - The maximum number of entries that should be returned in 
1004
     *                the response. The Member Node may return less entries 
1005
     *                than specified in this value.
1006
     * 
1007
     * @return objectList - the list of objects matching the criteria
1008
     * 
1009
     * @throws InvalidToken
1010
     * @throws ServiceFailure
1011
     * @throws NotAuthorized
1012
     * @throws InvalidRequest
1013
     * @throws NotImplemented
1014
     */
1015
    @Override
1016
    public ObjectList listObjects(Session session, Date startTime, Date endTime, ObjectFormatIdentifier objectFormatId, Identifier identifier, Boolean replicaStatus, Integer start,
1017
            Integer count) throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken {
1018
        NodeReference nodeId = null;
1019
        if(!replicaStatus) {
1020
            //not include those objects whose authoritative node is not this mn
1021
            nodeId = new NodeReference();
1022
            try {
1023
                String currentNodeId = PropertyService.getInstance().getProperty("dataone.nodeId"); // return only pids for which this mn
1024
                nodeId.setValue(currentNodeId);
1025
            } catch(Exception e) {
1026
                throw new ServiceFailure("1580", e.getMessage());
1027
            }
1028
        }
1029
        return super.listObjects(session, startTime, endTime, objectFormatId, identifier, nodeId, start, count);
1030
    }
1031

    
1032
    /**
1033
     * Return a description of the node's capabilities and services.
1034
     * 
1035
     * @return node - the technical capabilities of the Member Node
1036
     * 
1037
     * @throws ServiceFailure
1038
     * @throws NotAuthorized
1039
     * @throws InvalidRequest
1040
     * @throws NotImplemented
1041
     */
1042
    @Override
1043
    public Node getCapabilities() 
1044
        throws NotImplemented, ServiceFailure {
1045

    
1046
        String nodeName = null;
1047
        String nodeId = null;
1048
        String subject = null;
1049
        String contactSubject = null;
1050
        String nodeDesc = null;
1051
        String nodeTypeString = null;
1052
        NodeType nodeType = null;
1053
        List<String> mnCoreServiceVersions = null;
1054
        List<String> mnReadServiceVersions = null;
1055
        List<String> mnAuthorizationServiceVersions = null;
1056
        List<String> mnStorageServiceVersions = null;
1057
        List<String> mnReplicationServiceVersions = null;
1058

    
1059
        boolean nodeSynchronize = false;
1060
        boolean nodeReplicate = false;
1061
        List<String> mnCoreServiceAvailables = null;
1062
        List<String> mnReadServiceAvailables = null;
1063
        List<String> mnAuthorizationServiceAvailables = null;
1064
        List<String> mnStorageServiceAvailables = null;
1065
        List<String> mnReplicationServiceAvailables = null;
1066

    
1067
        try {
1068
            // get the properties of the node based on configuration information
1069
            nodeName = Settings.getConfiguration().getString("dataone.nodeName");
1070
            nodeId = Settings.getConfiguration().getString("dataone.nodeId");
1071
            subject = Settings.getConfiguration().getString("dataone.subject");
1072
            contactSubject = Settings.getConfiguration().getString("dataone.contactSubject");
1073
            nodeDesc = Settings.getConfiguration().getString("dataone.nodeDescription");
1074
            nodeTypeString = Settings.getConfiguration().getString("dataone.nodeType");
1075
            nodeType = NodeType.convert(nodeTypeString);
1076
            nodeSynchronize = new Boolean(Settings.getConfiguration().getString("dataone.nodeSynchronize")).booleanValue();
1077
            nodeReplicate = new Boolean(Settings.getConfiguration().getString("dataone.nodeReplicate")).booleanValue();
1078

    
1079
            // Set the properties of the node based on configuration information and
1080
            // calls to current status methods
1081
            String serviceName = SystemUtil.getSecureContextURL() + "/" + PropertyService.getProperty("dataone.serviceName");
1082
            Node node = new Node();
1083
            node.setBaseURL(serviceName + "/" + nodeTypeString);
1084
            node.setDescription(nodeDesc);
1085

    
1086
            // set the node's health information
1087
            node.setState(NodeState.UP);
1088
            
1089
            // set the ping response to the current value
1090
            Ping canPing = new Ping();
1091
            canPing.setSuccess(false);
1092
            try {
1093
            	Date pingDate = ping();
1094
                canPing.setSuccess(pingDate != null);
1095
            } catch (BaseException e) {
1096
                e.printStackTrace();
1097
                // guess it can't be pinged
1098
            }
1099
            
1100
            node.setPing(canPing);
1101

    
1102
            NodeReference identifier = new NodeReference();
1103
            identifier.setValue(nodeId);
1104
            node.setIdentifier(identifier);
1105
            Subject s = new Subject();
1106
            s.setValue(subject);
1107
            node.addSubject(s);
1108
            Subject contact = new Subject();
1109
            contact.setValue(contactSubject);
1110
            node.addContactSubject(contact);
1111
            node.setName(nodeName);
1112
            node.setReplicate(nodeReplicate);
1113
            node.setSynchronize(nodeSynchronize);
1114

    
1115
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
1116
            Services services = new Services();
1117

    
1118
            mnCoreServiceVersions = Settings.getConfiguration().getList("dataone.mnCore.serviceVersion");
1119
            mnCoreServiceAvailables = Settings.getConfiguration().getList("dataone.mnCore.serviceAvailable");
1120
            if(mnCoreServiceVersions != null && mnCoreServiceAvailables != null && mnCoreServiceVersions.size() == mnCoreServiceAvailables.size()) {
1121
                for(int i=0; i<mnCoreServiceVersions.size(); i++) {
1122
                    String version = mnCoreServiceVersions.get(i);
1123
                    boolean available = new Boolean(mnCoreServiceAvailables.get(i)).booleanValue();
1124
                    Service sMNCore = new Service();
1125
                    sMNCore.setName("MNCore");
1126
                    sMNCore.setVersion(version);
1127
                    sMNCore.setAvailable(available);
1128
                    services.addService(sMNCore);
1129
                }
1130
            }
1131
            
1132
            mnReadServiceVersions = Settings.getConfiguration().getList("dataone.mnRead.serviceVersion");
1133
            mnReadServiceAvailables = Settings.getConfiguration().getList("dataone.mnRead.serviceAvailable");
1134
            if(mnReadServiceVersions != null && mnReadServiceAvailables != null && mnReadServiceVersions.size()==mnReadServiceAvailables.size()) {
1135
                for(int i=0; i<mnReadServiceVersions.size(); i++) {
1136
                    String version = mnReadServiceVersions.get(i);
1137
                    boolean available = new Boolean(mnReadServiceAvailables.get(i)).booleanValue();
1138
                    Service sMNRead = new Service();
1139
                    sMNRead.setName("MNRead");
1140
                    sMNRead.setVersion(version);
1141
                    sMNRead.setAvailable(available);
1142
                    services.addService(sMNRead);
1143
                }
1144
            }
1145
           
1146
            mnAuthorizationServiceVersions = Settings.getConfiguration().getList("dataone.mnAuthorization.serviceVersion");
1147
            mnAuthorizationServiceAvailables = Settings.getConfiguration().getList("dataone.mnAuthorization.serviceAvailable");
1148
            if(mnAuthorizationServiceVersions != null && mnAuthorizationServiceAvailables != null && mnAuthorizationServiceVersions.size()==mnAuthorizationServiceAvailables.size()) {
1149
                for(int i=0; i<mnAuthorizationServiceVersions.size(); i++) {
1150
                    String version = mnAuthorizationServiceVersions.get(i);
1151
                    boolean available = new Boolean(mnAuthorizationServiceAvailables.get(i)).booleanValue();
1152
                    Service sMNAuthorization = new Service();
1153
                    sMNAuthorization.setName("MNAuthorization");
1154
                    sMNAuthorization.setVersion(version);
1155
                    sMNAuthorization.setAvailable(available);
1156
                    services.addService(sMNAuthorization);
1157
                }
1158
            }
1159
           
1160
            mnStorageServiceVersions = Settings.getConfiguration().getList("dataone.mnStorage.serviceVersion");
1161
            mnStorageServiceAvailables = Settings.getConfiguration().getList("dataone.mnStorage.serviceAvailable");
1162
            if(mnStorageServiceVersions != null && mnStorageServiceAvailables != null && mnStorageServiceVersions.size() == mnStorageServiceAvailables.size()) {
1163
                for(int i=0; i<mnStorageServiceVersions.size(); i++) {
1164
                    String version = mnStorageServiceVersions.get(i);
1165
                    boolean available = new Boolean(mnStorageServiceAvailables.get(i)).booleanValue();
1166
                    Service sMNStorage = new Service();
1167
                    sMNStorage.setName("MNStorage");
1168
                    sMNStorage.setVersion(version);
1169
                    sMNStorage.setAvailable(available);
1170
                    services.addService(sMNStorage);
1171
                }
1172
            }
1173
            
1174
            mnReplicationServiceVersions = Settings.getConfiguration().getList("dataone.mnReplication.serviceVersion");
1175
            mnReplicationServiceAvailables = Settings.getConfiguration().getList("dataone.mnReplication.serviceAvailable");
1176
            if(mnReplicationServiceVersions != null && mnReplicationServiceAvailables != null && mnReplicationServiceVersions.size() == mnReplicationServiceAvailables.size()) {
1177
                for (int i=0; i<mnReplicationServiceVersions.size(); i++) {
1178
                    String version = mnReplicationServiceVersions.get(i);
1179
                    boolean available = new Boolean(mnReplicationServiceAvailables.get(i)).booleanValue();
1180
                    Service sMNReplication = new Service();
1181
                    sMNReplication.setName("MNReplication");
1182
                    sMNReplication.setVersion(version);
1183
                    sMNReplication.setAvailable(available);
1184
                    services.addService(sMNReplication);
1185
                }
1186
            }
1187
            
1188
            node.setServices(services);
1189

    
1190
            // Set the schedule for synchronization
1191
            Synchronization synchronization = new Synchronization();
1192
            Schedule schedule = new Schedule();
1193
            Date now = new Date();
1194
            schedule.setYear(PropertyService.getProperty("dataone.nodeSynchronization.schedule.year"));
1195
            schedule.setMon(PropertyService.getProperty("dataone.nodeSynchronization.schedule.mon"));
1196
            schedule.setMday(PropertyService.getProperty("dataone.nodeSynchronization.schedule.mday"));
1197
            schedule.setWday(PropertyService.getProperty("dataone.nodeSynchronization.schedule.wday"));
1198
            schedule.setHour(PropertyService.getProperty("dataone.nodeSynchronization.schedule.hour"));
1199
            schedule.setMin(PropertyService.getProperty("dataone.nodeSynchronization.schedule.min"));
1200
            schedule.setSec(PropertyService.getProperty("dataone.nodeSynchronization.schedule.sec"));
1201
            synchronization.setSchedule(schedule);
1202
            synchronization.setLastHarvested(now);
1203
            synchronization.setLastCompleteHarvest(now);
1204
            node.setSynchronization(synchronization);
1205

    
1206
            node.setType(nodeType);
1207
            return node;
1208

    
1209
        } catch (PropertyNotFoundException pnfe) {
1210
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
1211
            logMetacat.error(msg);
1212
            throw new ServiceFailure("2162", msg);
1213
        }
1214
    }
1215

    
1216
    
1217

    
1218
    /**
1219
     * A callback method used by a CN to indicate to a MN that it cannot 
1220
     * complete synchronization of the science metadata identified by pid.  Log
1221
     * the event in the metacat event log.
1222
     * 
1223
     * @param session
1224
     * @param syncFailed
1225
     * 
1226
     * @throws ServiceFailure
1227
     * @throws NotAuthorized
1228
     * @throws NotImplemented
1229
     */
1230
    @Override
1231
    public boolean synchronizationFailed(Session session, SynchronizationFailed syncFailed) 
1232
        throws NotImplemented, ServiceFailure, NotAuthorized {
1233

    
1234
        String localId;
1235
        Identifier pid;
1236
        if ( syncFailed.getPid() != null ) {
1237
            pid = new Identifier();
1238
            pid.setValue(syncFailed.getPid());
1239
            boolean allowed;
1240
            
1241
            //are we allowed? only CNs
1242
            try {
1243
                allowed = isAdminAuthorized(session);
1244
                if ( !allowed ){
1245
                    throw new NotAuthorized("2162", 
1246
                            "Not allowed to call synchronizationFailed() on this node.");
1247
                }
1248
            } catch (InvalidToken e) {
1249
                throw new NotAuthorized("2162", 
1250
                        "Not allowed to call synchronizationFailed() on this node.");
1251

    
1252
            }
1253
            
1254
        } else {
1255
            throw new ServiceFailure("2161", "The identifier cannot be null.");
1256

    
1257
        }
1258
        
1259
        try {
1260
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1261
        } catch (McdbDocNotFoundException e) {
1262
            throw new ServiceFailure("2161", "The identifier specified by " + 
1263
                    syncFailed.getPid() + " was not found on this node.");
1264

    
1265
        } catch (SQLException e) {
1266
            throw new ServiceFailure("2161", "Couldn't identify the local id of the identifier specified by " + 
1267
                    syncFailed.getPid() + " since "+e.getMessage());
1268
        }
1269
        // TODO: update the CN URL below when the CNRead.SynchronizationFailed
1270
        // method is changed to include the URL as a parameter
1271
        logMetacat.warn("Synchronization for the object identified by " + 
1272
                pid.getValue() + " failed from " + syncFailed.getNodeId() + 
1273
                " with message: " + syncFailed.getDescription() + 
1274
                ". Logging the event to the Metacat EventLog as a 'syncFailed' event.");
1275
        // TODO: use the event type enum when the SYNCHRONIZATION_FAILED event is added
1276
        String principal = Constants.SUBJECT_PUBLIC;
1277
        if (session != null && session.getSubject() != null) {
1278
          principal = session.getSubject().getValue();
1279
        }
1280
        try {
1281
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "synchronization_failed");
1282
        } catch (Exception e) {
1283
            throw new ServiceFailure("2161", "Could not log the error for: " + pid.getValue());
1284
        }
1285
        //EventLog.getInstance().log("CN URL WILL GO HERE", 
1286
        //  session.getSubject().getValue(), localId, Event.SYNCHRONIZATION_FAILED);
1287
        return true;
1288

    
1289
    }
1290

    
1291
    /**
1292
     * Essentially a get() but with different logging behavior
1293
     */
1294
    @Override
1295
    public InputStream getReplica(Session session, Identifier pid) 
1296
        throws NotAuthorized, NotImplemented, ServiceFailure, InvalidToken, NotFound {
1297

    
1298
        logMetacat.info("MNodeService.getReplica() called.");
1299

    
1300
        // cannot be called by public
1301
        if (session == null) {
1302
        	throw new InvalidToken("2183", "No session was provided.");
1303
        }
1304
        
1305
        logMetacat.info("MNodeService.getReplica() called with parameters: \n" +
1306
             "\tSession.Subject      = " + session.getSubject().getValue() + "\n" +
1307
             "\tIdentifier           = " + pid.getValue());
1308

    
1309
        InputStream inputStream = null; // bytes to be returned
1310
        handler = new MetacatHandler(new Timer());
1311
        boolean allowed = false;
1312
        String localId; // the metacat docid for the pid
1313

    
1314
        // get the local docid from Metacat
1315
        try {
1316
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1317
        } catch (McdbDocNotFoundException e) {
1318
            throw new NotFound("2185", "The object specified by " + 
1319
                    pid.getValue() + " does not exist at this node.");
1320
            
1321
        } catch (SQLException e) {
1322
            throw new ServiceFailure("2181", "The local id of the object specified by " + 
1323
                    pid.getValue() + " couldn't be identified since "+e.getMessage());
1324
        }
1325

    
1326
        Subject targetNodeSubject = session.getSubject();
1327

    
1328
        // check for authorization to replicate, null session to act as this source MN
1329
        try {
1330
            allowed = D1Client.getCN().isNodeAuthorized(null, targetNodeSubject, pid);
1331
        } catch (InvalidToken e1) {
1332
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
1333
                + e1.getMessage());
1334
            
1335
        } catch (NotFound e1) {
1336
            throw new NotFound("2185", "Could not find the object "+pid.getValue()+" in this node - " 
1337
                    + e1.getMessage());
1338

    
1339
        } catch (InvalidRequest e1) {
1340
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
1341
                    + e1.getMessage());
1342

    
1343
        }
1344

    
1345
        logMetacat.info("Called D1Client.isNodeAuthorized(). Allowed = " + allowed +
1346
            " for identifier " + pid.getValue());
1347

    
1348
        // if the person is authorized, perform the read
1349
        if (allowed) {
1350
            try {
1351
                inputStream = MetacatHandler.read(localId);
1352
            } catch (Exception e) {
1353
                throw new ServiceFailure("2181", "The object specified by " + 
1354
                    pid.getValue() + "could not be returned due to error: " + e.getMessage());
1355
            }
1356
        } else {
1357
            throw new NotAuthorized("2182", "The pid "+pid.getValue()+" is not authorized to be read by the client.");
1358
        }
1359

    
1360
        // if we fail to set the input stream
1361
        if (inputStream == null) {
1362
            throw new ServiceFailure("2181", "The object specified by " + 
1363
                pid.getValue() + " can't be returned from the node.");
1364
        }
1365

    
1366
        // log the replica event
1367
        String principal = null;
1368
        if (session.getSubject() != null) {
1369
            principal = session.getSubject().getValue();
1370
        }
1371
        EventLog.getInstance().log(request.getRemoteAddr(), 
1372
            request.getHeader("User-Agent"), principal, localId, "replicate");
1373

    
1374
        return inputStream;
1375
    }
1376
    
1377
    /**
1378
     * A method to notify the Member Node that the authoritative copy of 
1379
     * system metadata on the Coordinating Nodes has changed.
1380
     *
1381
     * @param session   Session information that contains the identity of the 
1382
     *                  calling user as retrieved from the X.509 certificate 
1383
     *                  which must be traceable to the CILogon service.
1384
     * @param serialVersion   The serialVersion of the system metadata
1385
     * @param dateSysMetaLastModified  The time stamp for when the system metadata was changed
1386
     * @throws NotImplemented
1387
     * @throws ServiceFailure
1388
     * @throws NotAuthorized
1389
     * @throws InvalidRequest
1390
     * @throws InvalidToken
1391
     */
1392
    public boolean systemMetadataChanged(Session session, Identifier pid,
1393
        long serialVersion, Date dateSysMetaLastModified) 
1394
        throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest,
1395
        InvalidToken {
1396
        boolean needCheckAuthoriativeNode = true; 
1397
        return systemMetadataChanged(needCheckAuthoriativeNode, session, pid,serialVersion, dateSysMetaLastModified);
1398
    }
1399

    
1400
    /**
1401
     * A method to notify the Member Node that the authoritative copy of 
1402
     * system metadata on the Coordinating Nodes has changed.
1403
     * @param needCheckAuthoriativeNode  this is for the dataone version 2. In the
1404
     * version 2, there are two scenarios:
1405
     * 1. If the node is the authoritative node, it only accepts serial version and replica list.
1406
     * 2. If the node is a replica, it accepts everything.
1407
     * For the v1, api, the parameter should be false. 
1408
     * @param session   Session information that contains the identity of the 
1409
     *                  calling user as retrieved from the X.509 certificate 
1410
     *                  which must be traceable to the CILogon service.
1411
     * @param serialVersion   The serialVersion of the system metadata
1412
     * @param dateSysMetaLastModified  The time stamp for when the system metadata was changed
1413
     * @throws NotImplemented
1414
     * @throws ServiceFailure
1415
     * @throws NotAuthorized
1416
     * @throws InvalidRequest
1417
     * @throws InvalidToken
1418
     */
1419
    public boolean systemMetadataChanged(boolean needCheckAuthoriativeNode, Session session, Identifier pid,
1420
        long serialVersion, Date dateSysMetaLastModified) 
1421
        throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest,
1422
        InvalidToken {
1423
        
1424
        /*if(isReadOnlyMode()) {
1425
            throw new InvalidRequest("1334", "The Metacat member node is on the read-only mode and your request can't be fulfiled. Please try again later.");
1426
        }*/
1427
        // cannot be called by public
1428
        if (session == null) {
1429
        	throw new InvalidToken("1332", "No session was provided.");
1430
        }
1431

    
1432
        String serviceFailureCode = "1333";
1433
        Identifier sid = getPIDForSID(pid, serviceFailureCode);
1434
        if(sid != null) {
1435
            pid = sid;
1436
        }
1437
        
1438
        SystemMetadata currentLocalSysMeta = null;
1439
        SystemMetadata newSysMeta = null;
1440
        CNode cn = D1Client.getCN();
1441
        NodeList nodeList = null;
1442
        Subject callingSubject = null;
1443
        boolean allowed = false;
1444
        
1445
        // are we allowed to call this?
1446
        callingSubject = session.getSubject();
1447
        nodeList = cn.listNodes();
1448
        
1449
        for(Node node : nodeList.getNodeList()) {
1450
            // must be a CN
1451
            if ( node.getType().equals(NodeType.CN)) {
1452
               List<Subject> subjectList = node.getSubjectList();
1453
               // the calling subject must be in the subject list
1454
               if ( subjectList.contains(callingSubject)) {
1455
                   allowed = true;
1456
                   
1457
               }
1458
               
1459
            }
1460
        }
1461
        
1462
        if (!allowed ) {
1463
            String msg = "The subject identified by " + callingSubject.getValue() +
1464
              " is not authorized to call this service.";
1465
            throw new NotAuthorized("1331", msg);
1466
            
1467
        }
1468
        try {
1469
            HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
1470
        
1471
            // compare what we have locally to what is sent in the change notification
1472
            try {
1473
                currentLocalSysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1474
                 
1475
            } catch (RuntimeException e) {
1476
                String msg = "SystemMetadata for pid " + pid.getValue() +
1477
                  " couldn't be updated because it couldn't be found locally: " +
1478
                  e.getMessage();
1479
                logMetacat.error(msg);
1480
                ServiceFailure sf = new ServiceFailure("1333", msg);
1481
                sf.initCause(e);
1482
                throw sf; 
1483
            }
1484
            
1485
            if(currentLocalSysMeta == null) {
1486
                throw new InvalidRequest("1334", "We can't find the system metadata in the node for the id "+pid.getValue());
1487
            }
1488
            if (currentLocalSysMeta.getSerialVersion().longValue() <= serialVersion ) {
1489
                try {
1490
                    newSysMeta = cn.getSystemMetadata(null, pid);
1491
                } catch (NotFound e) {
1492
                    // huh? you just said you had it
1493
                	String msg = "On updating the local copy of system metadata " + 
1494
                    "for pid " + pid.getValue() +", the CN reports it is not found." +
1495
                    " The error message was: " + e.getMessage();
1496
                    logMetacat.error(msg);
1497
                    //ServiceFailure sf = new ServiceFailure("1333", msg);
1498
                    InvalidRequest sf = new InvalidRequest("1334", msg);
1499
                    sf.initCause(e);
1500
                    throw sf;
1501
                }
1502
                
1503
                //check about the sid in the system metadata
1504
                Identifier newSID = newSysMeta.getSeriesId();
1505
                if(newSID != null) {
1506
                    if (!isValidIdentifier(newSID)) {
1507
                        throw new InvalidRequest("1334", "The series identifier in the new system metadata is invalid.");
1508
                    }
1509
                    Identifier currentSID = currentLocalSysMeta.getSeriesId();
1510
                    if( currentSID != null && currentSID.getValue() != null) {
1511
                        if(!newSID.getValue().equals(currentSID.getValue())) {
1512
                            //newSID doesn't match the currentSID. The newSID shouldn't be used.
1513
                            try {
1514
                                if(IdentifierManager.getInstance().identifierExists(newSID.getValue())) {
1515
                                    throw new InvalidRequest("1334", "The series identifier "+newSID.getValue()+" in the new system metadata has been used by another object.");
1516
                                }
1517
                            } catch (SQLException sql) {
1518
                                throw new ServiceFailure("1333", "Couldn't determine if the SID "+newSID.getValue()+" in the system metadata exists in the node since "+sql.getMessage());
1519
                            }
1520
                            
1521
                        }
1522
                    } else {
1523
                        //newSID shouldn't be used
1524
                        try {
1525
                            if(IdentifierManager.getInstance().identifierExists(newSID.getValue())) {
1526
                                throw new InvalidRequest("1334", "The series identifier "+newSID.getValue()+" in the new system metadata has been used by another object.");
1527
                            }
1528
                        } catch (SQLException sql) {
1529
                            throw new ServiceFailure("1333", "Couldn't determine if the SID "+newSID.getValue()+" in the system metadata exists in the node since "+sql.getMessage());
1530
                        }
1531
                    }
1532
                }
1533
                // update the local copy of system metadata for the pid
1534
                try {
1535
                    if(needCheckAuthoriativeNode) {
1536
                        //this is for the v2 api.
1537
                        if(isAuthoritativeNode(pid)) {
1538
                            //this is the authoritative node, so we only accept replica and serial version
1539
                            logMetacat.debug("MNodeService.systemMetadataChanged - this is the authoritative node for the pid "+pid.getValue());
1540
                            List<Replica> replicas = newSysMeta.getReplicaList();
1541
                            newSysMeta = currentLocalSysMeta;
1542
                            newSysMeta.setSerialVersion(new BigInteger((new Long(serialVersion)).toString()));
1543
                            newSysMeta.setReplicaList(replicas);
1544
                        } else {
1545
                            //we need to archive the object in the replica node
1546
                            logMetacat.debug("MNodeService.systemMetadataChanged - this is NOT the authoritative node for the pid "+pid.getValue());
1547
                            logMetacat.debug("MNodeService.systemMetadataChanged - the new value of archive is "+newSysMeta.getArchived()+" for the pid "+pid.getValue());
1548
                            logMetacat.debug("MNodeService.systemMetadataChanged - the local value of archive is "+currentLocalSysMeta.getArchived()+" for the pid "+pid.getValue());
1549
                            if (newSysMeta.getArchived() != null && newSysMeta.getArchived() == true  && 
1550
                                    ((currentLocalSysMeta.getArchived() != null && currentLocalSysMeta.getArchived() == false ) || currentLocalSysMeta.getArchived() == null)){
1551
                                logMetacat.debug("MNodeService.systemMetadataChanged - start to archive object "+pid.getValue());
1552
                                boolean logArchive = false;
1553
                                boolean needUpdateModificationDate = false;
1554
                                try {
1555
                                    archiveObject(logArchive, session, pid, newSysMeta, needUpdateModificationDate);
1556
                                } catch (NotFound e) {
1557
                                    throw new InvalidRequest("1334", "Can't find the pid "+pid.getValue()+" for archive.");
1558
                                }
1559
                                
1560
                            } else if((newSysMeta.getArchived() == null || newSysMeta.getArchived() == false) && (currentLocalSysMeta.getArchived() != null && currentLocalSysMeta.getArchived() == true )) {
1561
                                throw new InvalidRequest("1334", "The pid "+pid.getValue()+" has been archived and it can't be reset to false.");
1562
                            }
1563
                        }
1564
                    }
1565
                    HazelcastService.getInstance().getSystemMetadataMap().put(newSysMeta.getIdentifier(), newSysMeta);
1566
                    logMetacat.info("Updated local copy of system metadata for pid " +
1567
                        pid.getValue() + " after change notification from the CN.");
1568
                    
1569
                    // TODO: consider inspecting the change for archive
1570
                    // see: https://projects.ecoinformatics.org/ecoinfo/issues/6417
1571
    //                if (newSysMeta.getArchived() != null && newSysMeta.getArchived().booleanValue()) {
1572
    //                	try {
1573
    //						this.archive(session, newSysMeta.getIdentifier());
1574
    //					} catch (NotFound e) {
1575
    //						// do we care? nothing to do about it now
1576
    //						logMetacat.error(e.getMessage(), e);
1577
    //					}
1578
    //                }
1579
                    
1580
                } catch (RuntimeException e) {
1581
                    String msg = "SystemMetadata for pid " + pid.getValue() +
1582
                      " couldn't be updated: " +
1583
                      e.getMessage();
1584
                    logMetacat.error(msg);
1585
                    ServiceFailure sf = new ServiceFailure("1333", msg);
1586
                    sf.initCause(e);
1587
                    throw sf;
1588
                }
1589
                
1590
                try {
1591
                    String localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1592
                    EventLog.getInstance().log(request.getRemoteAddr(), 
1593
                            request.getHeader("User-Agent"), session.getSubject().getValue(), 
1594
                            localId, "updateSystemMetadata");
1595
                } catch (Exception e) {
1596
                    // do nothing, no localId to log with
1597
                    logMetacat.warn("MNodeService.systemMetadataChanged - Could not log 'updateSystemMetadata' event because no localId was found for pid: " + pid.getValue());
1598
                } 
1599
                
1600
               
1601
            }
1602
        } finally {
1603
            HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
1604
        }
1605
        
1606
        if (currentLocalSysMeta.getSerialVersion().longValue() <= serialVersion ) {
1607
            // attempt to re-register the identifier (it checks if it is a doi)
1608
            try {
1609
                DOIService.getInstance().registerDOI(newSysMeta);
1610
            } catch (Exception e) {
1611
                logMetacat.warn("Could not [re]register DOI: " + e.getMessage(), e);
1612
            }
1613
            
1614
            // submit for indexing
1615
            try {
1616
                MetacatSolrIndex.getInstance().submit(newSysMeta.getIdentifier(), newSysMeta, null, true);
1617
            } catch (Exception e) {
1618
                logMetacat.error("Could not submit changed systemMetadata for indexing, pid: " + newSysMeta.getIdentifier().getValue(), e);
1619
            }
1620
        }
1621
        
1622
        return true;
1623
        
1624
    }
1625
    
1626
    /*
1627
     * Set the replication status for the object on the Coordinating Node
1628
     * 
1629
     * @param session - the session for the this target node
1630
     * @param pid - the identifier of the object being updated
1631
     * @param nodeId - the identifier of this target node
1632
     * @param status - the replication status to set
1633
     * @param failure - the exception to include, if any
1634
     */
1635
    private void setReplicationStatus(Session session, Identifier pid, 
1636
        NodeReference nodeId, ReplicationStatus status, BaseException failure) 
1637
        throws ServiceFailure, NotImplemented, NotAuthorized, 
1638
        InvalidRequest {
1639
        
1640
        // call the CN as the MN to set the replication status
1641
        try {
1642
            this.cn = D1Client.getCN();
1643
            this.cn.setReplicationStatus(session, pid, nodeId,
1644
                    status, failure);
1645
            
1646
        } catch (InvalidToken e) {
1647
        	String msg = "Could not set the replication status for " + pid.getValue() + " on the CN (InvalidToken): " + e.getMessage();
1648
            logMetacat.error(msg);
1649
        	throw new ServiceFailure("2151",
1650
                    msg);
1651
            
1652
        } catch (NotFound e) {
1653
        	String msg = "Could not set the replication status for " + pid.getValue() + " on the CN (NotFound): " + e.getMessage();
1654
            logMetacat.error(msg);
1655
        	throw new ServiceFailure("2151",
1656
                    msg);
1657
            
1658
        }
1659
    }
1660
    
1661
    private SystemMetadata makePublicIfNot(SystemMetadata sysmeta, Identifier pid) throws ServiceFailure, InvalidToken, NotFound, NotImplemented, InvalidRequest {
1662
    	// check if it is publicly readable
1663
		boolean isPublic = false;
1664
		Subject publicSubject = new Subject();
1665
		publicSubject.setValue(Constants.SUBJECT_PUBLIC);
1666
		Session publicSession = new Session();
1667
		publicSession.setSubject(publicSubject);
1668
		AccessRule publicRule = new AccessRule();
1669
		publicRule.addPermission(Permission.READ);
1670
		publicRule.addSubject(publicSubject);
1671
		
1672
		// see if we need to add the rule
1673
		try {
1674
			isPublic = this.isAuthorized(publicSession, pid, Permission.READ);
1675
		} catch (NotAuthorized na) {
1676
			// well, certainly not authorized for public read!
1677
		}
1678
		if (!isPublic) {
1679
			sysmeta.getAccessPolicy().addAllow(publicRule);
1680
		}
1681
		
1682
		return sysmeta;
1683
    }
1684

    
1685
	@Override
1686
	public Identifier generateIdentifier(Session session, String scheme, String fragment)
1687
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1688
			InvalidRequest {
1689
		
1690
		// check for null session
1691
        if (session == null) {
1692
          throw new InvalidToken("2190", "Session is required to generate an Identifier at this Node.");
1693
        }
1694
		
1695
		Identifier identifier = new Identifier();
1696
		
1697
		// handle different schemes
1698
		if (scheme.equalsIgnoreCase(UUID_SCHEME)) {
1699
			// UUID
1700
			UUID uuid = UUID.randomUUID();
1701
            identifier.setValue(UUID_PREFIX + uuid.toString());
1702
		} else if (scheme.equalsIgnoreCase(DOI_SCHEME)) {
1703
			// generate a DOI
1704
			try {
1705
				identifier = DOIService.getInstance().generateDOI();
1706
			} catch (EZIDException e) {
1707
				ServiceFailure sf = new ServiceFailure("2191", "Could not generate DOI: " + e.getMessage());
1708
				sf.initCause(e);
1709
				throw sf;
1710
			}
1711
		} else {
1712
			// default if we don't know the scheme
1713
			if (fragment != null) {
1714
				// for now, just autogen with fragment
1715
				String autogenId = DocumentUtil.generateDocumentId(fragment, 0);
1716
				identifier.setValue(autogenId);			
1717
			} else {
1718
				// autogen with no fragment
1719
				String autogenId = DocumentUtil.generateDocumentId(0);
1720
				identifier.setValue(autogenId);
1721
			}
1722
		}
1723
		
1724
		// TODO: reserve the identifier with the CN. We can only do this when
1725
		// 1) the MN is part of a CN cluster
1726
		// 2) the request is from an authenticated user
1727
		
1728
		return identifier;
1729
	}
1730

    
1731
	
1732

    
1733
	@Override
1734
	public QueryEngineDescription getQueryEngineDescription(Session session, String engine)
1735
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1736
			NotFound {
1737
	    if(engine != null && engine.equals(EnabledQueryEngines.PATHQUERYENGINE)) {
1738
	        if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.PATHQUERYENGINE)) {
1739
                throw new NotImplemented("0000", "MNodeService.query - the query engine "+engine +" hasn't been implemented or has been disabled.");
1740
            }
1741
	        QueryEngineDescription qed = new QueryEngineDescription();
1742
	        qed.setName(EnabledQueryEngines.PATHQUERYENGINE);
1743
	        qed.setQueryEngineVersion("1.0");
1744
	        qed.addAdditionalInfo("This is the traditional structured query for Metacat");
1745
	        Vector<String> pathsForIndexing = null;
1746
	        try {
1747
	            pathsForIndexing = SystemUtil.getPathsForIndexing();
1748
	        } catch (MetacatUtilException e) {
1749
	            logMetacat.warn("Could not get index paths", e);
1750
	        }
1751
	        for (String fieldName: pathsForIndexing) {
1752
	            QueryField field = new QueryField();
1753
	            field.addDescription("Indexed field for path '" + fieldName + "'");
1754
	            field.setName(fieldName);
1755
	            field.setReturnable(true);
1756
	            field.setSearchable(true);
1757
	            field.setSortable(false);
1758
	            // TODO: determine type and multivaluedness
1759
	            field.setType(String.class.getName());
1760
	            //field.setMultivalued(true);
1761
	            qed.addQueryField(field);
1762
	        }
1763
	        return qed;
1764
	    } else if (engine != null && engine.equals(EnabledQueryEngines.SOLRENGINE)) {
1765
	        if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.SOLRENGINE)) {
1766
                throw new NotImplemented("0000", "MNodeService.getQueryEngineDescription - the query engine "+engine +" hasn't been implemented or has been disabled.");
1767
            }
1768
	        try {
1769
	            QueryEngineDescription qed = MetacatSolrEngineDescriptionHandler.getInstance().getQueryEngineDescritpion();
1770
	            return qed;
1771
	        } catch (Exception e) {
1772
	            e.printStackTrace();
1773
	            throw new ServiceFailure("Solr server error", e.getMessage());
1774
	        }
1775
	    } else {
1776
	        throw new NotFound("404", "The Metacat member node can't find the query engine - "+engine);
1777
	    }
1778
		
1779
	}
1780

    
1781
	@Override
1782
	public QueryEngineList listQueryEngines(Session session) throws InvalidToken,
1783
			ServiceFailure, NotAuthorized, NotImplemented {
1784
		QueryEngineList qel = new QueryEngineList();
1785
		//qel.addQueryEngine(EnabledQueryEngines.PATHQUERYENGINE);
1786
		//qel.addQueryEngine(EnabledQueryEngines.SOLRENGINE);
1787
		List<String> enables = EnabledQueryEngines.getInstance().getEnabled();
1788
		for(String name : enables) {
1789
		    qel.addQueryEngine(name);
1790
		}
1791
		return qel;
1792
	}
1793

    
1794
	@Override
1795
	public InputStream query(Session session, String engine, String query) throws InvalidToken,
1796
			ServiceFailure, NotAuthorized, InvalidRequest, NotImplemented,
1797
			NotFound {
1798
	    String user = Constants.SUBJECT_PUBLIC;
1799
        String[] groups= null;
1800
        Set<Subject> subjects = null;
1801
        if (session != null) {
1802
            user = session.getSubject().getValue();
1803
            subjects = AuthUtils.authorizedClientSubjects(session);
1804
            if (subjects != null) {
1805
                List<String> groupList = new ArrayList<String>();
1806
                for (Subject subject: subjects) {
1807
                    groupList.add(subject.getValue());
1808
                }
1809
                groups = groupList.toArray(new String[0]);
1810
            }
1811
        } else {
1812
            //add the public user subject to the set 
1813
            Subject subject = new Subject();
1814
            subject.setValue(Constants.SUBJECT_PUBLIC);
1815
            subjects = new HashSet<Subject>();
1816
            subjects.add(subject);
1817
        }
1818
        //System.out.println("====== user is "+user);
1819
        //System.out.println("====== groups are "+groups);
1820
		if (engine != null && engine.equals(EnabledQueryEngines.PATHQUERYENGINE)) {
1821
		    if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.PATHQUERYENGINE)) {
1822
                throw new NotImplemented("0000", "MNodeService.query - the query engine "+engine +" hasn't been implemented or has been disabled.");
1823
            }
1824
			try {
1825
				DBQuery queryobj = new DBQuery();
1826
				
1827
				String results = queryobj.performPathquery(query, user, groups);
1828
				ContentTypeByteArrayInputStream ctbais = new ContentTypeByteArrayInputStream(results.getBytes(MetaCatServlet.DEFAULT_ENCODING));
1829
				ctbais.setContentType("text/xml");
1830
				return ctbais;
1831

    
1832
			} catch (Exception e) {
1833
				throw new ServiceFailure("Pathquery error", e.getMessage());
1834
			}
1835
			
1836
		} else if (engine != null && engine.equals(EnabledQueryEngines.SOLRENGINE)) {
1837
		    if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.SOLRENGINE)) {
1838
		        throw new NotImplemented("0000", "MNodeService.query - the query engine "+engine +" hasn't been implemented or has been disabled.");
1839
		    }
1840
		    logMetacat.info("The query is ==================================== \n"+query);
1841
		    try {
1842
		        
1843
                return MetacatSolrIndex.getInstance().query(query, subjects);
1844
            } catch (Exception e) {
1845
                // TODO Auto-generated catch block
1846
                throw new ServiceFailure("Solr server error", e.getMessage());
1847
            } 
1848
		}
1849
		return null;
1850
	}
1851
	
1852
	/**
1853
	 * Given an existing Science Metadata PID, this method mints a DOI
1854
	 * and updates the original object "publishing" the update with the DOI.
1855
	 * This includes updating the ORE map that describes the Science Metadata+data.
1856
	 * TODO: ensure all referenced objects allow public read
1857
	 * 
1858
	 * @see https://projects.ecoinformatics.org/ecoinfo/issues/6014
1859
	 * 
1860
	 * @param originalIdentifier
1861
	 * @param request
1862
	 * @throws InvalidRequest 
1863
	 * @throws NotImplemented 
1864
	 * @throws NotAuthorized 
1865
	 * @throws ServiceFailure 
1866
	 * @throws InvalidToken 
1867
	 * @throws NotFound
1868
	 * @throws InvalidSystemMetadata 
1869
	 * @throws InsufficientResources 
1870
	 * @throws UnsupportedType 
1871
	 * @throws IdentifierNotUnique 
1872
	 */
1873
	public Identifier publish(Session session, Identifier originalIdentifier) throws InvalidToken, 
1874
	ServiceFailure, NotAuthorized, NotImplemented, InvalidRequest, NotFound, IdentifierNotUnique, 
1875
	UnsupportedType, InsufficientResources, InvalidSystemMetadata, IOException {
1876
		
1877
	    String serviceFailureCode = "1030";
1878
	    Identifier sid = getPIDForSID(originalIdentifier, serviceFailureCode);
1879
	    if(sid != null) {
1880
	        originalIdentifier = sid;
1881
	    }
1882
		// get the original SM
1883
		SystemMetadata originalSystemMetadata = this.getSystemMetadata(session, originalIdentifier);
1884

    
1885
		// make copy of it using the marshaller to ensure DEEP copy
1886
		SystemMetadata sysmeta = null;
1887
		try {
1888
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
1889
			TypeMarshaller.marshalTypeToOutputStream(originalSystemMetadata, baos);
1890
			sysmeta = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class, new ByteArrayInputStream(baos.toByteArray()));
1891
		} catch (Exception e) {
1892
			// report as service failure
1893
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1894
			sf.initCause(e);
1895
			throw sf;
1896
		}
1897

    
1898
		// mint a DOI for the new revision
1899
		Identifier newIdentifier = this.generateIdentifier(session, MNodeService.DOI_SCHEME, null);
1900
				
1901
		// set new metadata values
1902
		sysmeta.setIdentifier(newIdentifier);
1903
		sysmeta.setObsoletes(originalIdentifier);
1904
		sysmeta.setObsoletedBy(null);
1905
		
1906
		// ensure it is publicly readable
1907
		sysmeta = makePublicIfNot(sysmeta, originalIdentifier);
1908
		
1909
		//Get the bytes
1910
		InputStream inputStream = null;		
1911
		boolean isScienceMetadata = isScienceMetadata(sysmeta);
1912
		//If it's a science metadata doc, we want to update the packageId first
1913
		if(isScienceMetadata){
1914
			InputStream originalObject = this.get(session, originalIdentifier);
1915
			
1916
			//Edit the science metadata with the new package Id (EML)
1917
			inputStream = editScienceMetadata(session, originalObject, originalIdentifier, newIdentifier);
1918
		}
1919
		else{
1920
			inputStream = this.get(session, originalIdentifier);
1921
		}
1922
		
1923
		// update the object
1924
		this.update(session, originalIdentifier, inputStream, newIdentifier, sysmeta);
1925
		
1926
		// update ORE that references the scimeta
1927
		// first try the naive method, then check the SOLR index
1928
		try {
1929
			String localId = IdentifierManager.getInstance().getLocalId(originalIdentifier.getValue());
1930
			
1931
			Identifier potentialOreIdentifier = new Identifier();
1932
			potentialOreIdentifier.setValue(SystemMetadataFactory.RESOURCE_MAP_PREFIX + localId);
1933
			
1934
			InputStream oreInputStream = null;
1935
			try {
1936
				oreInputStream = this.get(session, potentialOreIdentifier);
1937
			} catch (NotFound nf) {
1938
				// this is probably okay for many sci meta data docs
1939
				logMetacat.warn("No potential ORE map found for: " + potentialOreIdentifier.getValue());
1940
				// try the SOLR index
1941
				List<Identifier> potentialOreIdentifiers = this.lookupOreFor(originalIdentifier, false);
1942
				if (potentialOreIdentifiers != null) {
1943
					potentialOreIdentifier = potentialOreIdentifiers.get(0);
1944
					try {
1945
						oreInputStream = this.get(session, potentialOreIdentifier);
1946
					} catch (NotFound nf2) {
1947
						// this is probably okay for many sci meta data docs
1948
						logMetacat.warn("No potential ORE map found for: " + potentialOreIdentifier.getValue());
1949
					}
1950
				}
1951
			}
1952
			if (oreInputStream != null) {
1953
				Identifier newOreIdentifier = MNodeService.getInstance(request).generateIdentifier(session, MNodeService.UUID_SCHEME, null);
1954
	
1955
				Map<Identifier, Map<Identifier, List<Identifier>>> resourceMapStructure = ResourceMapFactory.getInstance().parseResourceMap(oreInputStream);
1956
				Map<Identifier, List<Identifier>> sciMetaMap = resourceMapStructure.get(potentialOreIdentifier);
1957
				List<Identifier> dataIdentifiers = sciMetaMap.get(originalIdentifier);
1958
					
1959
				// reconstruct the ORE with the new identifiers
1960
				sciMetaMap.remove(originalIdentifier);
1961
				sciMetaMap.put(newIdentifier, dataIdentifiers);
1962
				
1963
				ResourceMap resourceMap = ResourceMapFactory.getInstance().createResourceMap(newOreIdentifier, sciMetaMap);
1964
				String resourceMapString = ResourceMapFactory.getInstance().serializeResourceMap(resourceMap);
1965
				
1966
				// get the original ORE SM and update the values
1967
				SystemMetadata originalOreSysMeta = this.getSystemMetadata(session, potentialOreIdentifier);
1968
				SystemMetadata oreSysMeta = new SystemMetadata();
1969
				try {
1970
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
1971
					TypeMarshaller.marshalTypeToOutputStream(originalOreSysMeta, baos);
1972
					oreSysMeta = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class, new ByteArrayInputStream(baos.toByteArray()));
1973
				} catch (Exception e) {
1974
					// report as service failure
1975
					ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1976
					sf.initCause(e);
1977
					throw sf;
1978
				}
1979

    
1980
				oreSysMeta.setIdentifier(newOreIdentifier);
1981
				oreSysMeta.setObsoletes(potentialOreIdentifier);
1982
				oreSysMeta.setObsoletedBy(null);
1983
				oreSysMeta.setSize(BigInteger.valueOf(resourceMapString.getBytes("UTF-8").length));
1984
				oreSysMeta.setChecksum(ChecksumUtil.checksum(resourceMapString.getBytes("UTF-8"), oreSysMeta.getChecksum().getAlgorithm()));
1985
				
1986
				// ensure ORE is publicly readable
1987
				oreSysMeta = makePublicIfNot(oreSysMeta, potentialOreIdentifier);
1988
				
1989
				// ensure all data objects allow public read
1990
				List<String> pidsToSync = new ArrayList<String>();
1991
				for (Identifier dataId: dataIdentifiers) {
1992
					SystemMetadata dataSysMeta = this.getSystemMetadata(session, dataId);
1993
					dataSysMeta = makePublicIfNot(dataSysMeta, dataId);
1994
					this.updateSystemMetadata(dataSysMeta);
1995
					pidsToSync.add(dataId.getValue());
1996
				}
1997
				SyncAccessPolicy sap = new SyncAccessPolicy();
1998
				try {
1999
					sap.sync(pidsToSync);
2000
				} catch (Exception e) {
2001
					// ignore
2002
					logMetacat.warn("Error attempting to sync access for data objects when publishing package");
2003
				}
2004
				
2005
				// save the updated ORE
2006
				this.update(
2007
						session, 
2008
						potentialOreIdentifier, 
2009
						new ByteArrayInputStream(resourceMapString.getBytes("UTF-8")), 
2010
						newOreIdentifier, 
2011
						oreSysMeta);
2012
				
2013
			} else {
2014
				// create a new ORE for them
2015
				// https://projects.ecoinformatics.org/ecoinfo/issues/6194
2016
				try {
2017
					// find the local id for the NEW package.
2018
					String newLocalId = IdentifierManager.getInstance().getLocalId(newIdentifier.getValue());
2019
	
2020
					@SuppressWarnings("unused")
2021
					SystemMetadata extraSysMeta = SystemMetadataFactory.createSystemMetadata(newLocalId, true, false);
2022
					// should be done generating the ORE here, and the same permissions were used from the metadata object
2023
					
2024
				} catch (Exception e) {
2025
					// oops, guess there was a problem - no package for you
2026
					logMetacat.error("Could not generate new ORE for published object: " + newIdentifier.getValue(), e);
2027
				}
2028
			}
2029
		} catch (McdbDocNotFoundException e) {
2030
			// report as service failure
2031
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2032
			sf.initCause(e);
2033
			throw sf;
2034
		} catch (UnsupportedEncodingException e) {
2035
			// report as service failure
2036
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2037
			sf.initCause(e);
2038
			throw sf;
2039
		} catch (OREException e) {
2040
			// report as service failure
2041
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2042
			sf.initCause(e);
2043
			throw sf;
2044
		} catch (URISyntaxException e) {
2045
			// report as service failure
2046
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2047
			sf.initCause(e);
2048
			throw sf;
2049
		} catch (OREParserException e) {
2050
			// report as service failure
2051
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2052
			sf.initCause(e);
2053
			throw sf;
2054
		} catch (ORESerialiserException e) {
2055
			// report as service failure
2056
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2057
			sf.initCause(e);
2058
			throw sf;
2059
		} catch (NoSuchAlgorithmException e) {
2060
			// report as service failure
2061
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2062
			sf.initCause(e);
2063
			throw sf;
2064
		} catch (SQLException e) {
2065
            // report as service failure
2066
            ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2067
            sf.initCause(e);
2068
            throw sf;
2069
        }
2070
		
2071
		return newIdentifier;
2072
	}
2073
	
2074
	/**
2075
	   * Update a science metadata document with its new Identifier  
2076
	   * 
2077
	   * @param session - the Session object containing the credentials for the Subject
2078
	   * @param object - the InputStream for the XML object to be edited
2079
	   * @param pid - the Identifier of the XML object to be updated
2080
	   * @param newPid = the new Identifier to give to the modified XML doc
2081
	   * 
2082
	   * @return newObject - The InputStream for the modified XML object
2083
	   * 
2084
	   * @throws ServiceFailure
2085
	   * @throws IOException
2086
	   * @throws UnsupportedEncodingException
2087
	   * @throws InvalidToken
2088
	   * @throws NotAuthorized
2089
	   * @throws NotFound
2090
	   * @throws NotImplemented
2091
	   */
2092
	  public InputStream editScienceMetadata(Session session, InputStream object, Identifier pid, Identifier newPid)
2093
	  	throws ServiceFailure, IOException, UnsupportedEncodingException, InvalidToken, NotAuthorized, NotFound, NotImplemented {
2094
	    
2095
		logMetacat.debug("D1NodeService.editScienceMetadata() called.");
2096
		
2097
		 InputStream newObject = null;
2098
		
2099
	    try{   	
2100
	    	//Get the root node of the XML document
2101
	    	byte[] xmlBytes  = IOUtils.toByteArray(object);
2102
	        String xmlStr = new String(xmlBytes, "UTF-8");
2103
	        
2104
	    	Document doc = XMLUtilities.getXMLReaderAsDOMDocument(new StringReader(xmlStr));
2105
		    org.w3c.dom.Node docNode = doc.getDocumentElement();
2106

    
2107
		    //Get the system metadata for this object
2108
		    SystemMetadata sysMeta = null;
2109
		    try{
2110
		    	sysMeta = getSystemMetadata(session, pid);
2111
		    } catch(NotAuthorized e){
2112
		    	throw new ServiceFailure("1030", "D1NodeService.editScienceMetadata(): " + 
2113
		    			"This session is not authorized to access the system metadata for " +
2114
		    			pid.getValue() + " : " + e.getMessage());
2115
		    } catch(NotFound e){
2116
		    	throw new ServiceFailure("1030", "D1NodeService.editScienceMetadata(): " + 
2117
		    			"Could not find the system metadata for " +
2118
		    			pid.getValue() + " : " + e.getMessage());
2119
		    }
2120
		    
2121
		    //Get the formatId
2122
	        ObjectFormatIdentifier objFormatId = sysMeta.getFormatId();
2123
	        String formatId = objFormatId.getValue();
2124
	        
2125
	    	//For all EML formats
2126
	        if(formatId.indexOf("eml") == 0){
2127
	        	//Update or add the id attribute
2128
	    	    XMLUtilities.addAttributeNodeToDOMTree(docNode, XPATH_EML_ID, newPid.getValue());
2129
	        }
2130

    
2131
	        //The modified object InputStream
2132
		    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
2133
		    Source xmlSource = new DOMSource(docNode);
2134
		    Result outputTarget = new StreamResult(outputStream);
2135
		    TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
2136
		    newObject = new ByteArrayInputStream(outputStream.toByteArray());
2137
		    
2138
	    } catch(TransformerException e) {
2139
	    	throw new ServiceFailure("1030", "MNNodeService.editScienceMetadata(): " +
2140
	                "Could not update the ID in the XML document for " +
2141
	                "pid " + pid.getValue() +" : " + e.getMessage());
2142
	    } catch(IOException e){
2143
	    	throw new ServiceFailure("1030", "MNNodeService.editScienceMetadata(): " +
2144
	                "Could not update the ID in the XML document for " +
2145
	                "pid " + pid.getValue() +" : " + e.getMessage());
2146
	    }
2147
	    
2148
	    return newObject;
2149
	  }
2150
	
2151
	/**
2152
	 * Determines if we already have registered an ORE map for this package
2153
	 * NOTE: uses a solr query to locate OREs for the object
2154
	 * @param guid of the EML/packaging object
2155
	 * @return list of resource map identifiers for the given pid
2156
	 */
2157
	public List<Identifier> lookupOreFor(Identifier guid, boolean includeObsolete) {
2158
		// Search for the ORE if we can find it
2159
		String pid = guid.getValue();
2160
		List<Identifier> retList = null;
2161
		try {
2162
			String query = "fl=id,resourceMap&wt=xml&q=-obsoletedBy:[* TO *]+resourceMap:[* TO *]+id:\"" + pid + "\"";
2163
			if (includeObsolete) {
2164
				query = "fl=id,resourceMap&wt=xml&q=resourceMap:[* TO *]+id:\"" + pid + "\"";
2165
			}
2166
			
2167
			InputStream results = this.query(null, "solr", query);
2168
			org.w3c.dom.Node rootNode = XMLUtilities.getXMLReaderAsDOMTreeRootNode(new InputStreamReader(results, "UTF-8"));
2169
			//String resultString = XMLUtilities.getDOMTreeAsString(rootNode);
2170
			org.w3c.dom.NodeList nodeList = XMLUtilities.getNodeListWithXPath(rootNode, "//arr[@name=\"resourceMap\"]/str");
2171
			if (nodeList != null && nodeList.getLength() > 0) {
2172
				retList = new ArrayList<Identifier>();
2173
				for (int i = 0; i < nodeList.getLength(); i++) {
2174
					String found = nodeList.item(i).getFirstChild().getNodeValue();
2175
					Identifier oreId = new Identifier();
2176
					oreId.setValue(found);
2177
					retList.add(oreId);
2178
				}
2179
			}
2180
		} catch (Exception e) {
2181
			logMetacat.error("Error checking for resourceMap[s] on pid " + pid + ". " + e.getMessage(), e);
2182
		}
2183
		
2184
		return retList;
2185
	}
2186
	
2187

    
2188
	@Override
2189
	public InputStream getPackage(Session session, ObjectFormatIdentifier formatId,
2190
			Identifier pid) throws InvalidToken, ServiceFailure,
2191
			NotAuthorized, InvalidRequest, NotImplemented, NotFound {
2192
	    if(formatId == null) {
2193
	        throw new InvalidRequest("2873", "The format type can't be null in the getpackage method.");
2194
	    } else if(!formatId.getValue().equals("application/bagit-097")) {
2195
	        throw new NotImplemented("", "The format "+formatId.getValue()+" is not supported in the getpackage method");
2196
	    }
2197
	    String serviceFailureCode = "2871";
2198
	    Identifier sid = getPIDForSID(pid, serviceFailureCode);
2199
	    if(sid != null) {
2200
	        pid = sid;
2201
	    }
2202
		InputStream bagInputStream = null;
2203
		BagFactory bagFactory = new BagFactory();
2204
		Bag bag = bagFactory.createBag();
2205
		
2206
		// track the temp files we use so we can delete them when finished
2207
		List<File> tempFiles = new ArrayList<File>();
2208
		
2209
		// the pids to include in the package
2210
		List<Identifier> packagePids = new ArrayList<Identifier>();
2211
		
2212
		// catch non-D1 service errors and throw as ServiceFailures
2213
		try {
2214
			//Create a map of dataone ids and file names
2215
			Map<Identifier, String> fileNames = new HashMap<Identifier, String>();
2216
			
2217
			// track the pid-to-file mapping
2218
			StringBuffer pidMapping = new StringBuffer();
2219
			
2220
			// find the package contents
2221
			SystemMetadata sysMeta = this.getSystemMetadata(session, pid);
2222
			if (ObjectFormatCache.getInstance().getFormat(sysMeta.getFormatId()).getFormatType().equals("RESOURCE")) {
2223
				//Get the resource map as a map of Identifiers
2224
				InputStream oreInputStream = this.get(session, pid);
2225
				Map<Identifier, Map<Identifier, List<Identifier>>> resourceMapStructure = ResourceMapFactory.getInstance().parseResourceMap(oreInputStream);
2226
				packagePids.addAll(resourceMapStructure.keySet());
2227
				//Loop through each object in this resource map
2228
				for (Map<Identifier, List<Identifier>> entries: resourceMapStructure.values()) {
2229
					//Loop through each metadata object in this entry
2230
					Set<Identifier> metadataIdentifiers = entries.keySet();
2231
					for(Identifier metadataID: metadataIdentifiers){
2232
						try{
2233
							//Get the system metadata for this metadata object
2234
							SystemMetadata metadataSysMeta = this.getSystemMetadata(session, metadataID);
2235
							
2236
							// include user-friendly metadata
2237
							if (ObjectFormatCache.getInstance().getFormat(metadataSysMeta.getFormatId()).getFormatType().equals("METADATA")) {
2238
								InputStream metadataStream = this.get(session, metadataID);
2239
							
2240
								try {
2241
									// transform
2242
						            String format = "default";
2243

    
2244
									DBTransform transformer = new DBTransform();
2245
						            String documentContent = IOUtils.toString(metadataStream, "UTF-8");
2246
						            String sourceType = metadataSysMeta.getFormatId().getValue();
2247
						            String targetType = "-//W3C//HTML//EN";
2248
						            ByteArrayOutputStream baos = new ByteArrayOutputStream();
2249
						            Writer writer = new OutputStreamWriter(baos , "UTF-8");
2250
						            // TODO: include more params?
2251
						            Hashtable<String, String[]> params = new Hashtable<String, String[]>();
2252
						            String localId = null;
2253
									try {
2254
										localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
2255
									} catch (McdbDocNotFoundException e) {
2256
										throw new NotFound("1020", e.getMessage());
2257
									}
2258
									params.put("qformat", new String[] {format});	            
2259
						            params.put("docid", new String[] {localId});
2260
						            params.put("pid", new String[] {pid.getValue()});
2261
						            params.put("displaymodule", new String[] {"printall"});
2262
						            
2263
						            transformer.transformXMLDocument(
2264
						                    documentContent , 
2265
						                    sourceType, 
2266
						                    targetType , 
2267
						                    format, 
2268
						                    writer, 
2269
						                    params, 
2270
						                    null //sessionid
2271
						                    );
2272
						            
2273
						            // finally, get the HTML back
2274
						            ContentTypeByteArrayInputStream resultInputStream = new ContentTypeByteArrayInputStream(baos.toByteArray());
2275
						            
2276
						            // write to temp file with correct css path
2277
						            File tmpDir = File.createTempFile("package_", "_dir");
2278
						            tmpDir.delete();
2279
						            tmpDir.mkdir();
2280
						            File htmlFile = File.createTempFile("metadata", ".html", tmpDir);
2281
						            File cssDir = new File(tmpDir, format);
2282
						            cssDir.mkdir();
2283
						            File cssFile = new File(tmpDir, format + "/" + format + ".css");
2284
						            String pdfFileName = metadataID.getValue().replaceAll("[^a-zA-Z0-9\\-\\.]", "_") + "-METADATA.pdf";
2285
						            File pdfFile = new File(tmpDir, pdfFileName);
2286
						            //File pdfFile = File.createTempFile("metadata", ".pdf", tmpDir);
2287
						            
2288
						            // put the CSS file in place for the html to find it
2289
						            String originalCssPath = SystemUtil.getContextDir() + "/style/skins/" + format + "/" + format + ".css";
2290
						            IOUtils.copy(new FileInputStream(originalCssPath), new FileOutputStream(cssFile));
2291
						            
2292
						            // write the HTML file
2293
						            IOUtils.copy(resultInputStream, new FileOutputStream(htmlFile));
2294
						            
2295
						            // convert to PDF
2296
						            HtmlToPdf.export(htmlFile.getAbsolutePath(), pdfFile.getAbsolutePath());
2297
						            
2298
						            //add to the package
2299
						            bag.addFileToPayload(pdfFile);
2300
									pidMapping.append(metadataID.getValue() + " (pdf)" +  "\t" + "data/" + pdfFile.getName() + "\n");
2301
						            
2302
						            // mark for clean up after we are done
2303
									htmlFile.delete();
2304
									cssFile.delete();
2305
									cssDir.delete();
2306
						            tempFiles.add(tmpDir);
2307
									tempFiles.add(pdfFile); // delete this first later on
2308
						            
2309
								} catch (Exception e) {
2310
									logMetacat.warn("Could not transform metadata", e);
2311
								}
2312
							}
2313

    
2314
							
2315
							//If this is in eml format, extract the filename and GUID from each entity in its package
2316
							if (metadataSysMeta.getFormatId().getValue().startsWith("eml://")) {
2317
								//Get the package
2318
								DataPackageParserInterface parser = new Eml200DataPackageParser();
2319
								InputStream emlStream = this.get(session, metadataID);
2320
								parser.parse(emlStream);
2321
								DataPackage dataPackage = parser.getDataPackage();
2322
								
2323
								//Get all the entities in this package and loop through each to extract its ID and file name
2324
								Entity[] entities = dataPackage.getEntityList();
2325
								for(Entity entity: entities){
2326
									try{
2327
										//Get the file name from the metadata
2328
										String fileNameFromMetadata = entity.getName();
2329
										
2330
										//Get the ecogrid URL from the metadata
2331
										String ecogridIdentifier = entity.getEntityIdentifier();
2332
										//Parse the ecogrid URL to get the local id
2333
										String idFromMetadata = DocumentUtil.getAccessionNumberFromEcogridIdentifier(ecogridIdentifier);
2334
										
2335
										//Get the docid and rev pair
2336
										String docid = DocumentUtil.getDocIdFromString(idFromMetadata);
2337
										String rev = DocumentUtil.getRevisionStringFromString(idFromMetadata);
2338
										
2339
										//Get the GUID
2340
										String guid = IdentifierManager.getInstance().getGUID(docid, Integer.valueOf(rev));
2341
										Identifier dataIdentifier = new Identifier();
2342
										dataIdentifier.setValue(guid);
2343
										
2344
										//Add the GUID to our GUID & file name map
2345
										fileNames.put(dataIdentifier, fileNameFromMetadata);
2346
									}
2347
									catch(Exception e){
2348
										//Prevent just one entity error
2349
										e.printStackTrace();
2350
										logMetacat.debug(e.getMessage(), e);
2351
									}
2352
								}
2353
							}
2354
						}
2355
						catch(Exception e){
2356
							//Catch errors that would prevent package download
2357
							logMetacat.debug(e.toString());
2358
						}
2359
					}
2360
					packagePids.addAll(entries.keySet());
2361
					for (List<Identifier> dataPids: entries.values()) {
2362
						packagePids.addAll(dataPids);
2363
					}
2364
				}
2365
			} else {
2366
				// just the lone pid in this package
2367
				packagePids.add(pid);
2368
			}
2369
			
2370
			//Create a temp file, then delete it and make a directory with that name
2371
			File tempDir = File.createTempFile("temp", Long.toString(System.nanoTime()));
2372
			tempDir.delete();
2373
			tempDir = new File(tempDir.getPath() + "_dir");
2374
			tempDir.mkdir();			
2375
			tempFiles.add(tempDir);
2376
			File pidMappingFile = new File(tempDir, "pid-mapping.txt");
2377
			
2378
			// loop through the package contents
2379
			for (Identifier entryPid: packagePids) {
2380
				//Get the system metadata for each item
2381
				SystemMetadata entrySysMeta = this.getSystemMetadata(session, entryPid);					
2382
				
2383
				String objectFormatType = ObjectFormatCache.getInstance().getFormat(entrySysMeta.getFormatId()).getFormatType();
2384
				String fileName = null;
2385
				
2386
				//TODO: Be more specific of what characters to replace. Make sure periods arent replaced for the filename from metadata
2387
				//Our default file name is just the ID + format type (e.g. walker.1.1-DATA)
2388
				fileName = entryPid.getValue().replaceAll("[^a-zA-Z0-9\\-\\.]", "_") + "-" + objectFormatType;
2389

    
2390
				if(fileNames.containsKey(entryPid)){
2391
					//Let's use the file name and extension from the metadata is we have it
2392
					fileName = entryPid.getValue().replaceAll("[^a-zA-Z0-9\\-\\.]", "_") + "-" + fileNames.get(entryPid).replaceAll("[^a-zA-Z0-9\\-\\.]", "_");
2393
				}
2394
				else{
2395
					//If we couldn't find a given file name, use the system metadata extension
2396
					String extension = ObjectFormatInfo.instance().getExtension(entrySysMeta.getFormatId().getValue());
2397
					fileName += extension;
2398
				}
2399
				
2400
		        //Create a new file for this item and add to the list
2401
				File tempFile = new File(tempDir, fileName);
2402
				tempFiles.add(tempFile);
2403
				
2404
				InputStream entryInputStream = this.get(session, entryPid);			
2405
				IOUtils.copy(entryInputStream, new FileOutputStream(tempFile));
2406
				bag.addFileToPayload(tempFile);
2407
				pidMapping.append(entryPid.getValue() + "\t" + "data/" + tempFile.getName() + "\n");
2408
			}
2409
			
2410
			//add the the pid to data file map
2411
			IOUtils.write(pidMapping.toString(), new FileOutputStream(pidMappingFile));
2412
			bag.addFileAsTag(pidMappingFile);
2413
			tempFiles.add(pidMappingFile);
2414
			
2415
			bag = bag.makeComplete();
2416
			
2417
			///Now create the zip file
2418
			//Use the pid as the file name prefix, replacing all non-word characters
2419
			String zipName = pid.getValue().replaceAll("\\W", "_");
2420
			
2421
			File bagFile = new File(tempDir, zipName+".zip");
2422
			
2423
			bag.setFile(bagFile);
2424
			ZipWriter zipWriter = new ZipWriter(bagFactory);
2425
			bag.write(zipWriter, bagFile);
2426
			bagFile = bag.getFile();
2427
			// use custom FIS that will delete the file when closed
2428
			bagInputStream = new DeleteOnCloseFileInputStream(bagFile);
2429
			// also mark for deletion on shutdown in case the stream is never closed
2430
			bagFile.deleteOnExit();
2431
			tempFiles.add(bagFile);
2432
			
2433
			// clean up other temp files
2434
			for (int i=tempFiles.size()-1; i>=0; i--){
2435
				tempFiles.get(i).delete();
2436
			}
2437
			
2438
		} catch (IOException e) {
2439
			// report as service failure
2440
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2441
			sf.initCause(e);
2442
			throw sf;
2443
		} catch (OREException e) {
2444
			// report as service failure
2445
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2446
			sf.initCause(e);
2447
			throw sf;
2448
		} catch (URISyntaxException e) {
2449
			// report as service failure
2450
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2451
			sf.initCause(e);
2452
			throw sf;
2453
		} catch (OREParserException e) {
2454
			// report as service failure
2455
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2456
			sf.initCause(e);
2457
			throw sf;
2458
		}
2459
		
2460
		return bagInputStream;
2461
	}
2462
	
2463
	 /**
2464
	   * Archives an object, where the object is either a 
2465
	   * data object or a science metadata object.
2466
	   * 
2467
	   * @param session - the Session object containing the credentials for the Subject
2468
	   * @param pid - The object identifier to be archived
2469
	   * 
2470
	   * @return pid - the identifier of the object used for the archiving
2471
	   * 
2472
	   * @throws InvalidToken
2473
	   * @throws ServiceFailure
2474
	   * @throws NotAuthorized
2475
	   * @throws NotFound
2476
	   * @throws NotImplemented
2477
	   * @throws InvalidRequest
2478
	   */
2479
	  public Identifier archive(Session session, Identifier pid) 
2480
	      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
2481
	      if(isReadOnlyMode()) {
2482
	            throw new ServiceFailure("2912", ReadOnlyChecker.DATAONEERROR);
2483
	        }
2484
	      boolean allowed = false;
2485
	      // do we have a valid pid?
2486
	      if (pid == null || pid.getValue().trim().equals("")) {
2487
	          throw new ServiceFailure("1350", "The provided identifier was invalid.");
2488
	      }
2489
	      
2490
	      String serviceFailureCode = "1350";
2491
	      Identifier sid = getPIDForSID(pid, serviceFailureCode);
2492
	      if(sid != null) {
2493
	          pid = sid;
2494
	      }
2495
	      // does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
2496
	      try {
2497
	            allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
2498
	        } catch (InvalidRequest e) {
2499
	          throw new ServiceFailure("1350", e.getDescription());
2500
	        } 
2501

    
2502
	      if (allowed) {
2503
	         try {
2504
	             HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
2505
	             logMetacat.debug("MNodeService.archive - lock the identifier "+pid.getValue()+" in the system metadata map.");
2506
	             SystemMetadata sysmeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
2507
	             boolean needModifyDate = true;
2508
	             boolean logArchive = true;
2509
	             super.archiveObject(logArchive, session, pid, sysmeta, needModifyDate); 
2510
	         } finally {
2511
	             HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
2512
	             logMetacat.debug("MNodeService.archive - unlock the identifier "+pid.getValue()+" in the system metadata map.");
2513
	         }
2514
	        
2515

    
2516
	      } else {
2517
	          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
2518
	      }
2519

    
2520
	      return pid;
2521
	  }
2522
    
2523
	/**
2524
	 * Update the system metadata of the specified pid.
2525
	 */
2526
	@Override
2527
	public boolean updateSystemMetadata(Session session, Identifier pid,
2528
            SystemMetadata sysmeta) throws NotImplemented, NotAuthorized,
2529
            ServiceFailure, InvalidRequest, InvalidSystemMetadata, InvalidToken {
2530
	  
2531
	  if(isReadOnlyMode()) {
2532
            throw new ServiceFailure("4868",  ReadOnlyChecker.DATAONEERROR);
2533
      }
2534
	 if(sysmeta == null) {
2535
	     throw  new InvalidRequest("4869", "The system metadata object should NOT be null in the updateSystemMetadata request.");
2536
	 }
2537
	 if(pid == null || pid.getValue() == null) {
2538
         throw new InvalidRequest("4869", "Please specify the id in the updateSystemMetadata request ") ;
2539
     }
2540

    
2541
     if (session == null) {
2542
         //TODO: many of the thrown exceptions do not use the correct error codes
2543
         //check these against the docs and correct them
2544
         throw new NotAuthorized("4861", "No Session - could not authorize for updating system metadata." +
2545
                 "  If you are not logged in, please do so and retry the request.");
2546
     } else {
2547
         try {
2548
             //Following session can do the change:
2549
           //- Authoritative Member Node (we can use isNodeAdmin since we checked isAuthoritativeNode )
2550
             //- Owner of object (coved by the userHasPermission method)
2551
             //- user subjects with the change permission
2552
             //Note: Coordinating Node can not because MN is authoritative
2553
             /*if(!isAuthoritativeNode(pid)) {
2554
                throw  new InvalidRequest("4863", "Client can only call updateSystemMetadata request on the authoritative memember node.");
2555
             }
2556
             if(!isNodeAdmin(session) && !userHasPermission(session, pid, Permission.CHANGE_PERMISSION)) {
2557
                 throw new NotAuthorized("4861", "The client -"+ session.getSubject().getValue()+ "is not authorized for updating the system metadata of the object "+pid.getValue());
2558
             }*/
2559
             if(!allowUpdating(session, pid, Permission.CHANGE_PERMISSION)) {
2560
                 throw new NotAuthorized("4861", "The client -"+ session.getSubject().getValue()+ "is not authorized for updating the system metadata of the object "+pid.getValue());
2561
             }
2562
         } catch (NotFound e) {
2563
             throw new InvalidRequest("4869", "Can't determine if the client has the permission to update the system metacat of the object with id "+pid.getValue()+" since "+e.getDescription());
2564
         }
2565
         
2566
     }
2567
      //update the system metadata locally
2568
      boolean success = false;
2569
      try {
2570
          HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
2571
          SystemMetadata currentSysmeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
2572
          if(currentSysmeta == null) {
2573
              throw  new InvalidRequest("4869", "We can't find the current system metadata on the member node for the id "+pid.getValue());
2574
          }
2575
          Date currentModiDate = currentSysmeta.getDateSysMetadataModified();
2576
          Date commingModiDate = sysmeta.getDateSysMetadataModified();
2577
          if(commingModiDate == null) {
2578
              throw  new InvalidRequest("4869", "The system metadata modification date can't be null.");
2579
          }
2580
          if(currentModiDate != null && commingModiDate.getTime() != currentModiDate.getTime()) {
2581
              throw new InvalidRequest("4869", "Your system metadata modification date is "+commingModiDate.toString()+
2582
                      ". It doesn't match our current system metadata modification date in the member node - "+currentModiDate.toString()+
2583
                      ". Please check if you have got the newest version of the system metadata before the modification.");
2584
          }
2585
          boolean needUpdateModificationDate = true;
2586
          boolean fromCN = false;
2587
          success = updateSystemMetadata(session, pid, sysmeta, needUpdateModificationDate, currentSysmeta, fromCN);
2588
      } finally {
2589
          HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
2590
      }
2591
      
2592
      if(success) {
2593
          //TODO
2594
          //notify the cns the synchornize the new system metadata.
2595
          this.cn = D1Client.getCN();
2596
          try {
2597
              if(this.cn == null)  {
2598
                  logMetacat.warn("updateSystemMetadata - can't get the instance of the CN. So the system metadata in CN can't be updated.");
2599
              } else {
2600
                  this.cn.synchronize(null, pid);
2601
              }
2602
          } catch (BaseException e) {
2603
              e.printStackTrace();
2604
              logMetacat.error("It is a DataONEBaseException and its detail code is "+e.getDetail_code() +" and its code is "+e.getCode());
2605
              logMetacat.error("Can't update the systemmetadata of pid "+pid.getValue()+" in CNs since "+e.getMessage());
2606
          } catch (Exception e) {
2607
              e.printStackTrace();
2608
              logMetacat.error("Can't update the systemmetadata of pid "+pid.getValue()+" in CNs since "+e.getMessage());
2609
          }
2610
          
2611
          // attempt to re-register the identifier (it checks if it is a doi)
2612
          try {
2613
        	  DOIService.getInstance().registerDOI(sysmeta);
2614
          } catch (Exception e) {
2615
  			logMetacat.warn("Could not [re]register DOI: " + e.getMessage(), e);
2616
          }
2617
      }
2618
      return success;
2619
    }
2620
	
2621
	/*
2622
     * Determine if the current node is the authoritative node for the given pid.
2623
     */
2624
    protected boolean isAuthoritativeNode(Identifier pid) throws InvalidRequest {
2625
        boolean isAuthoritativeNode = false;
2626
        if(pid != null && pid.getValue() != null) {
2627
            SystemMetadata sys = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
2628
            if(sys != null) {
2629
                NodeReference node = sys.getAuthoritativeMemberNode();
2630
                if(node != null) {
2631
                    String nodeValue = node.getValue();
2632
                    logMetacat.debug("The authoritative node for id "+pid.getValue()+" is "+nodeValue);
2633
                    //System.out.println("The authoritative node for id "+pid.getValue()+" is "+nodeValue);
2634
                    String currentNodeId = Settings.getConfiguration().getString("dataone.nodeId");
2635
                    logMetacat.debug("The node id in metacat.properties is "+currentNodeId);
2636
                    //System.out.println("The node id in metacat.properties is "+currentNodeId);
2637
                    if(currentNodeId != null && !currentNodeId.trim().equals("") && currentNodeId.equals(nodeValue)) {
2638
                        logMetacat.debug("They are matching");
2639
                        //System.out.println("They are matching");
2640
                        isAuthoritativeNode = true;
2641
                    }
2642
                } else {
2643
                    throw new InvalidRequest("4869", "Coudn't find the authoritative member node in the system metadata associated with the pid "+pid.getValue());
2644
                }
2645
            } else {
2646
                throw new InvalidRequest("4869", "Coudn't find the system metadata associated with the pid "+pid.getValue());
2647
            }
2648
        } else {
2649
            throw new InvalidRequest("4869", "The request pid is null");
2650
        }
2651
        return isAuthoritativeNode;
2652
    }
2653
    
2654
    /*
2655
     * Rules are:
2656
     * 1. If the session has an cn object, it is allowed.
2657
     * 2. If it is not a cn object, the client should have approperate permission and it should also happen on the authorative node.
2658
     */
2659
    private boolean allowUpdating(Session session, Identifier pid, Permission permission) throws NotAuthorized, NotFound, InvalidRequest {
2660
        boolean allow = false;
2661
        if(isCNAdmin (session)) {
2662
            allow = true;
2663
        } else {
2664
            if(isAuthoritativeNode(pid)) {
2665
                if(userHasPermission(session, pid, permission)) {
2666
                    allow = true;
2667
                } else {
2668
                    allow = false;
2669
                }
2670
            } else {
2671
                throw new NotAuthorized("4861", "Client can only call the request on the authoritative memember node.");
2672
            }
2673
        }
2674
        return allow;
2675
        
2676
    }
2677
    
2678
    /**
2679
     * Check if the metacat is in the read-only mode.
2680
     * @return true if it is; otherwise false.
2681
     */
2682
    protected boolean isReadOnlyMode() {
2683
        boolean readOnly = false;
2684
        ReadOnlyChecker checker = new ReadOnlyChecker();
2685
        readOnly = checker.isReadOnly();
2686
        return readOnly;
2687
    }
2688
    
2689
}
(5-5/8)