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
import java.util.concurrent.ExecutorService;
56
import java.util.concurrent.Executors;
57

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

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

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

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

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

    
209
	/* the logger instance */
210
    private Logger logMetacat = null;
211
    
212
    /* A reference to a remote Memeber Node */
213
    //private MNode mn;
214
    
215
    /* A reference to a Coordinating Node */
216
    private CNode cn;
217
    
218
    // shared executor
219
    private static ExecutorService executor = null;
220

    
221
    static {
222
        // use a shared executor service with nThreads == one less than available processors
223
        int availableProcessors = Runtime.getRuntime().availableProcessors();
224
        int nThreads = availableProcessors * 1;
225
        nThreads--;
226
        nThreads = Math.max(1, nThreads);
227
        executor = Executors.newFixedThreadPool(nThreads);  
228
    }
229

    
230

    
231
    /**
232
     * Singleton accessor to get an instance of MNodeService.
233
     * 
234
     * @return instance - the instance of MNodeService
235
     */
236
    public static MNodeService getInstance(HttpServletRequest request) {
237
        return new MNodeService(request);
238
    }
239

    
240
    /**
241
     * Constructor, private for singleton access
242
     */
243
    private MNodeService(HttpServletRequest request) {
244
        super(request);
245
        logMetacat = Logger.getLogger(MNodeService.class);
246
        
247
        // set the Member Node certificate file location
248
        CertificateManager.getInstance().setCertificateLocation(Settings.getConfiguration().getString("D1Client.certificate.file"));
249
    }
250

    
251
    /**
252
     * Deletes an object from the Member Node, where the object is either a 
253
     * data object or a science metadata object.
254
     * 
255
     * @param session - the Session object containing the credentials for the Subject
256
     * @param pid - The object identifier to be deleted
257
     * 
258
     * @return pid - the identifier of the object used for the deletion
259
     * 
260
     * @throws InvalidToken
261
     * @throws ServiceFailure
262
     * @throws NotAuthorized
263
     * @throws NotFound
264
     * @throws NotImplemented
265
     * @throws InvalidRequest
266
     */
267
    @Override
268
    public Identifier delete(Session session, Identifier pid) 
269
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
270

    
271
        if(isReadOnlyMode()) {
272
            throw new ServiceFailure("2902", ReadOnlyChecker.DATAONEERROR);
273
        }
274
    	// only admin of  the MN or the CN is allowed a full delete
275
        boolean allowed = false;
276
        allowed = isAdminAuthorized(session);
277
        
278
        String serviceFailureCode = "2902";
279
        Identifier sid = getPIDForSID(pid, serviceFailureCode);
280
        if(sid != null) {
281
            pid = sid;
282
        }
283
        
284
        //check if it is the authoritative member node
285
        if(!allowed) {
286
            allowed = isAuthoritativeMNodeAdmin(session, pid);
287
        }
288
        
289
        if (!allowed) { 
290
            throw new NotAuthorized("1320", "The provided identity does not have " + "permission to delete objects on the Node.");
291
        }
292
    	
293
    	// defer to superclass implementation
294
        return super.delete(session, pid);
295
    }
296

    
297
    /**
298
     * Updates an existing object by creating a new object identified by 
299
     * newPid on the Member Node which explicitly obsoletes the object 
300
     * identified by pid through appropriate changes to the SystemMetadata 
301
     * of pid and newPid
302
     * 
303
     * @param session - the Session object containing the credentials for the Subject
304
     * @param pid - The identifier of the object to be updated
305
     * @param object - the new object bytes
306
     * @param sysmeta - the new system metadata describing the object
307
     * 
308
     * @return newPid - the identifier of the new object
309
     * 
310
     * @throws InvalidToken
311
     * @throws ServiceFailure
312
     * @throws NotAuthorized
313
     * @throws NotFound
314
     * @throws NotImplemented
315
     * @throws IdentifierNotUnique
316
     * @throws UnsupportedType
317
     * @throws InsufficientResources
318
     * @throws InvalidSystemMetadata
319
     * @throws InvalidRequest
320
     */
321
    @Override
322
    public Identifier update(Session session, Identifier pid, InputStream object, 
323
        Identifier newPid, SystemMetadata sysmeta) 
324
        throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
325
        UnsupportedType, InsufficientResources, NotFound, 
326
        InvalidSystemMetadata, NotImplemented, InvalidRequest {
327
        
328
        if(isReadOnlyMode()) {
329
            throw new ServiceFailure("1310", ReadOnlyChecker.DATAONEERROR);
330
        }
331

    
332
        //transform a sid to a pid if it is applicable
333
        String serviceFailureCode = "1310";
334
        Identifier sid = getPIDForSID(pid, serviceFailureCode);
335
        if(sid != null) {
336
            pid = sid;
337
        }
338
        
339
        String localId = null;
340
        boolean allowed = false;
341
        boolean isScienceMetadata = false;
342
        
343
        if (session == null) {
344
        	throw new InvalidToken("1210", "No session has been provided");
345
        }
346
        Subject subject = session.getSubject();
347

    
348
        // verify the pid is valid format
349
        if (!isValidIdentifier(pid)) {
350
        	throw new InvalidRequest("1202", "The provided identifier is invalid.");
351
        }
352
        
353
        // verify the new pid is valid format
354
        if (!isValidIdentifier(newPid)) {
355
            throw new InvalidRequest("1202", "The provided identifier is invalid.");
356
        }
357
        
358
        // make sure that the newPid doesn't exists
359
        boolean idExists = true;
360
        try {
361
            idExists = IdentifierManager.getInstance().identifierExists(newPid.getValue());
362
        } catch (SQLException e) {
363
            throw new ServiceFailure("1310", 
364
                                    "The requested identifier " + newPid.getValue() +
365
                                    " couldn't be determined if it is unique since : "+e.getMessage());
366
        }
367
        if (idExists) {
368
                throw new IdentifierNotUnique("1220", 
369
                          "The requested identifier " + newPid.getValue() +
370
                          " is already used by another object and" +
371
                          "therefore can not be used for this object. Clients should choose" +
372
                          "a new identifier that is unique and retry the operation or " +
373
                          "use CN.reserveIdentifier() to reserve one.");
374
            
375
        }
376
        
377
       
378

    
379
        // check for the existing identifier
380
        try {
381
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
382
            
383
        } catch (McdbDocNotFoundException e) {
384
            throw new InvalidRequest("1202", "The object with the provided " + 
385
                "identifier was not found.");
386
            
387
        } catch (SQLException ee) {
388
            throw new ServiceFailure("1310", "The object with the provided " + 
389
                    "identifier "+pid.getValue()+" can't be identified since - "+ee.getMessage());
390
        }
391
        
392
        // set the originating node
393
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
394
        sysmeta.setOriginMemberNode(originMemberNode);
395
        
396
        // set the submitter to match the certificate
397
        sysmeta.setSubmitter(subject);
398
        // set the dates
399
        Date now = Calendar.getInstance().getTime();
400
        sysmeta.setDateSysMetadataModified(now);
401
        sysmeta.setDateUploaded(now);
402
        
403
        // make sure serial version is set to something
404
        BigInteger serialVersion = sysmeta.getSerialVersion();
405
        if (serialVersion == null) {
406
        	sysmeta.setSerialVersion(BigInteger.ZERO);
407
        }
408

    
409
        // does the subject have WRITE ( == update) priveleges on the pid?
410
        //allowed = isAuthorized(session, pid, Permission.WRITE);
411
        //CN having the permission is allowed; user with the write permission and calling on the authoritative node is allowed.
412
        try {
413
            allowed = allowUpdating(session, pid, Permission.WRITE);
414
        }   catch (NotFound e) {
415
            throw new NotFound("1280", "Can't determine if the client has the permission to update the object with id "+pid.getValue()+" since "+e.getDescription());
416
        } catch(ServiceFailure e) {
417
            throw new ServiceFailure("1310", "Can't determine if the client has the permission to update the object with id "+pid.getValue()+" since "+e.getDescription());
418
        } catch(NotAuthorized e) {
419
            throw new NotAuthorized("1200", "Can't determine if the client has the permission to update the object with id "+pid.getValue()+" since "+e.getDescription());
420
        } catch(NotImplemented e) {
421
            throw new NotImplemented("1201","Can't determine if the client has the permission to update he object with id "+pid.getValue()+" since "+e.getDescription());
422
        } catch(InvalidRequest e) {
423
            throw new InvalidRequest("1202", "Can't determine if the client has the permission to update the object with id "+pid.getValue()+" since "+e.getDescription());
424
        } catch(InvalidToken e) {
425
            throw new InvalidToken("1210", "Can't determine if the client has the permission to update the object with id "+pid.getValue()+" since "+e.getDescription());
426
        }
427
        
428
        if (allowed) {
429
        	
430
        	// check quality of SM
431
        	if (sysmeta.getObsoletedBy() != null) {
432
        		throw new InvalidSystemMetadata("1300", "Cannot include obsoletedBy when updating object");
433
        	}
434
        	if (sysmeta.getObsoletes() != null && !sysmeta.getObsoletes().getValue().equals(pid.getValue())) {
435
        		throw new InvalidSystemMetadata("1300", "The identifier provided in obsoletes does not match old Identifier");
436
        	}
437

    
438
            // get the existing system metadata for the object
439
            SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
440
            //System.out.println("the archive is "+existingSysMeta.getArchived());
441
            //Base on documentation, we can't update an archived object:
442
            //The update operation MUST fail with Exceptions.InvalidRequest on objects that have the Types.SystemMetadata.archived property set to true.
443
            if(existingSysMeta.getArchived() != null && existingSysMeta.getArchived()) {
444
                throw new InvalidRequest("1202","An archived object"+pid.getValue()+" can't be updated");
445
            }
446

    
447
            // check for previous update
448
            // see: https://redmine.dataone.org/issues/3336
449
            Identifier existingObsoletedBy = existingSysMeta.getObsoletedBy();
450
            if (existingObsoletedBy != null) {
451
            	throw new InvalidRequest("1202", 
452
            			"The previous identifier has already been made obsolete by: " + existingObsoletedBy.getValue());
453
            }
454
            //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.
455
            Identifier sidInSys = sysmeta.getSeriesId();
456
            if(sidInSys != null) {
457
                if (!isValidIdentifier(sidInSys)) {
458
                    throw new InvalidSystemMetadata("1300", "The provided series id in the system metadata is invalid.");
459
                }
460
                Identifier previousSid = existingSysMeta.getSeriesId();
461
                if(previousSid != null) {
462
                    // there is a previous sid, if the new sid doesn't match it, the new sid should be non-existing.
463
                    if(!sidInSys.getValue().equals(previousSid.getValue())) {
464
                        try {
465
                            idExists = IdentifierManager.getInstance().identifierExists(sidInSys.getValue());
466
                        } catch (SQLException e) {
467
                            throw new ServiceFailure("1310", 
468
                                                    "The requested identifier " + sidInSys.getValue() +
469
                                                    " couldn't be determined if it is unique since : "+e.getMessage());
470
                        }
471
                        if(idExists) {
472
                            throw new InvalidSystemMetadata("1300", "The series id "+sidInSys.getValue()+" in the system metadata doesn't match the previous series id "
473
                                                            +previousSid.getValue()+", so it should NOT exist. However, it was used by another object.");
474
                        }
475
                    }
476
                } else {
477
                    // there is no previous sid, the new sid should be non-existing.
478
                    try {
479
                        idExists = IdentifierManager.getInstance().identifierExists(sidInSys.getValue());
480
                    } catch (SQLException e) {
481
                        throw new ServiceFailure("1310", 
482
                                                "The requested identifier " + sidInSys.getValue() +
483
                                                " couldn't be determined if it is unique since : "+e.getMessage());
484
                    }
485
                    if(idExists) {
486
                        throw new InvalidSystemMetadata("1300", "The series id "+sidInSys.getValue()+" in the system metadata should NOT exist since the previous series id is null."
487
                                                        +"However, it was used by another object.");
488
                    }
489
                }
490
                //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)
491
                if(sidInSys.getValue().equals(newPid.getValue())) {
492
                    throw new InvalidSystemMetadata("1300", "The series id "+sidInSys.getValue()+" in the system metadata shouldn't have the same value of the pid.");
493
                }
494
            }
495

    
496
            isScienceMetadata = isScienceMetadata(sysmeta);
497

    
498
            // do we have XML metadata or a data object?
499
            if (isScienceMetadata) {
500

    
501
                // update the science metadata XML document
502
                // TODO: handle non-XML metadata/data documents (like netCDF)
503
                // TODO: don't put objects into memory using stream to string
504
                //String objectAsXML = "";
505
                try {
506
                    //objectAsXML = IOUtils.toString(object, "UTF-8");
507
                	String formatId = null;
508
                	if(sysmeta.getFormatId() != null) {
509
                	    formatId = sysmeta.getFormatId().getValue();
510
                	}
511
                    localId = insertOrUpdateDocument(object, "UTF-8", pid, session, "update", formatId);
512
                    
513
                    // register the newPid and the generated localId
514
                    if (newPid != null) {
515
                        IdentifierManager.getInstance().createMapping(newPid.getValue(), localId);
516
                    }
517

    
518
                } catch (IOException e) {
519
                    String msg = "The Node is unable to create the object. " + "There was a problem converting the object to XML";
520
                    logMetacat.info(msg);
521
                    throw new ServiceFailure("1310", msg + ": " + e.getMessage());
522

    
523
                }
524

    
525
            } else {
526

    
527
                // update the data object
528
                localId = insertDataObject(object, newPid, session);
529

    
530
            }
531
            
532
            // add the newPid to the obsoletedBy list for the existing sysmeta
533
            existingSysMeta.setObsoletedBy(newPid);
534
            //increase version
535
            BigInteger current = existingSysMeta.getSerialVersion();
536
            //System.out.println("the current version is "+current);
537
            current = current.add(BigInteger.ONE);
538
            //System.out.println("the new current version is "+current);
539
            existingSysMeta.setSerialVersion(current);
540
            // then update the existing system metadata
541
            updateSystemMetadata(existingSysMeta);
542

    
543
            // prep the new system metadata, add pid to the affected lists
544
            sysmeta.setObsoletes(pid);
545
            //sysmeta.addDerivedFrom(pid);
546

    
547
            // and insert the new system metadata
548
            insertSystemMetadata(sysmeta);
549

    
550
            // log the update event
551
            EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), subject.getValue(), localId, Event.UPDATE.toString());
552
            
553
            // attempt to register the identifier - it checks if it is a doi
554
            try {
555
    			DOIService.getInstance().registerDOI(sysmeta);
556
    		} catch (Exception e) {
557
                throw new ServiceFailure("1190", "Could not register DOI: " + e.getMessage());
558
    		}
559

    
560
        } else {
561
            throw new NotAuthorized("1200", "The provided identity does not have " + "permission to UPDATE the object identified by " + pid.getValue()
562
                    + " on the Member Node.");
563
        }
564

    
565
        return newPid;
566
    }
567

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

    
571
        if(isReadOnlyMode()) {
572
            throw new ServiceFailure("1190", ReadOnlyChecker.DATAONEERROR);
573
        }
574
        // check for null session
575
        if (session == null) {
576
          throw new InvalidToken("1110", "Session is required to WRITE to the Node.");
577
        }
578
        // verify the pid is valid format
579
        if (!isValidIdentifier(pid)) {
580
            throw new InvalidRequest("1102", "The provided identifier is invalid.");
581
        }
582
        // set the submitter to match the certificate
583
        sysmeta.setSubmitter(session.getSubject());
584
        // set the originating node
585
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
586
        sysmeta.setOriginMemberNode(originMemberNode);
587
        
588
        // if no authoritative MN, set it to the same
589
        if (sysmeta.getAuthoritativeMemberNode() == null) {
590
        	sysmeta.setAuthoritativeMemberNode(originMemberNode);
591
        }
592
        
593
        sysmeta.setArchived(false);
594

    
595
        // set the dates
596
        Date now = Calendar.getInstance().getTime();
597
        sysmeta.setDateSysMetadataModified(now);
598
        sysmeta.setDateUploaded(now);
599
        
600
        // set the serial version
601
        sysmeta.setSerialVersion(BigInteger.ZERO);
602

    
603
        // check that we are not attempting to subvert versioning
604
        if (sysmeta.getObsoletes() != null && sysmeta.getObsoletes().getValue() != null) {
605
            throw new InvalidSystemMetadata("1180", 
606
              "The supplied system metadata is invalid. " +
607
              "The obsoletes field cannot have a value when creating entries.");
608
        }
609
        
610
        if (sysmeta.getObsoletedBy() != null && sysmeta.getObsoletedBy().getValue() != null) {
611
            throw new InvalidSystemMetadata("1180", 
612
              "The supplied system metadata is invalid. " +
613
              "The obsoletedBy field cannot have a value when creating entries.");
614
        }
615
        
616
        // verify the sid in the system metadata
617
        Identifier sid = sysmeta.getSeriesId();
618
        boolean idExists = false;
619
        if(sid != null) {
620
            if (!isValidIdentifier(sid)) {
621
                throw new InvalidSystemMetadata("1180", "The provided series id is invalid.");
622
            }
623
            try {
624
                idExists = IdentifierManager.getInstance().identifierExists(sid.getValue());
625
            } catch (SQLException e) {
626
                throw new ServiceFailure("1190", 
627
                                        "The series identifier " + sid.getValue() +
628
                                        " in the system metadata couldn't be determined if it is unique since : "+e.getMessage());
629
            }
630
            if (idExists) {
631
                    throw new InvalidSystemMetadata("1180", 
632
                              "The series identifier " + sid.getValue() +
633
                              " is already used by another object and" +
634
                              "therefore can not be used for this object. Clients should choose" +
635
                              "a new identifier that is unique and retry the operation or " +
636
                              "use CN.reserveIdentifier() to reserve one.");
637
                
638
            }
639
            //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 )
640
            if(sid.getValue().equals(pid.getValue())) {
641
                throw new InvalidSystemMetadata("1180", "The series id "+sid.getValue()+" in the system metadata shouldn't have the same value of the pid.");
642
            }
643
        }
644

    
645
        // call the shared impl
646
        Identifier resultPid = super.create(session, pid, object, sysmeta);
647
        
648
        // attempt to register the identifier - it checks if it is a doi
649
        try {
650
			DOIService.getInstance().registerDOI(sysmeta);
651
		} catch (Exception e) {
652
			ServiceFailure sf = new ServiceFailure("1190", "Could not register DOI: " + e.getMessage());
653
			sf.initCause(e);
654
            throw sf;
655
		}
656
        
657
        // return 
658
		return resultPid ;
659
    }
660

    
661
    /**
662
     * Called by a Coordinating Node to request that the Member Node create a 
663
     * copy of the specified object by retrieving it from another Member 
664
     * Node and storing it locally so that it can be made accessible to 
665
     * the DataONE system.
666
     * 
667
     * @param session - the Session object containing the credentials for the Subject
668
     * @param sysmeta - Copy of the CN held system metadata for the object
669
     * @param sourceNode - A reference to node from which the content should be 
670
     *                     retrieved. The reference should be resolved by 
671
     *                     checking the CN node registry.
672
     * 
673
     * @return true if the replication succeeds
674
     * 
675
     * @throws ServiceFailure
676
     * @throws NotAuthorized
677
     * @throws NotImplemented
678
     * @throws UnsupportedType
679
     * @throws InsufficientResources
680
     * @throws InvalidRequest
681
     */
682
    @Override
683
    public boolean replicate(Session session, SystemMetadata sysmeta,
684
            NodeReference sourceNode) throws NotImplemented, ServiceFailure,
685
            NotAuthorized, InvalidRequest, InsufficientResources,
686
            UnsupportedType {
687
        /*if(isReadOnlyMode()) {
688
            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.");
689
        }*/
690

    
691
        if (session != null && sysmeta != null && sourceNode != null) {
692
            logMetacat.info("MNodeService.replicate() called with parameters: \n" +
693
                            "\tSession.Subject      = "                           +
694
                            session.getSubject().getValue() + "\n"                +
695
                            "\tidentifier           = "                           + 
696
                            sysmeta.getIdentifier().getValue()                    +
697
                            "\n" + "\tSource NodeReference ="                     +
698
                            sourceNode.getValue());
699
        }
700
        boolean result = false;
701
        String nodeIdStr = null;
702
        NodeReference nodeId = null;
703

    
704
        // get the referenced object
705
        Identifier pid = sysmeta.getIdentifier();
706
        // verify the pid is valid format
707
        if (!isValidIdentifier(pid)) {
708
            throw new InvalidRequest("2153", "The provided identifier in the system metadata is invalid.");
709
        }
710

    
711
        // get from the membernode
712
        // TODO: switch credentials for the server retrieval?
713
        this.cn = D1Client.getCN();
714
        InputStream object = null;
715
        Session thisNodeSession = null;
716
        SystemMetadata localSystemMetadata = null;
717
        BaseException failure = null;
718
        String localId = null;
719
        
720
        // TODO: check credentials
721
        // cannot be called by public
722
        if (session == null || session.getSubject() == null) {
723
            String msg = "No session was provided to replicate identifier " +
724
            sysmeta.getIdentifier().getValue();
725
            logMetacat.error(msg);
726
            throw new NotAuthorized("2152", msg);
727
            
728
        }
729

    
730

    
731
        // get the local node id
732
        try {
733
            nodeIdStr = PropertyService.getProperty("dataone.nodeId");
734
            nodeId = new NodeReference();
735
            nodeId.setValue(nodeIdStr);
736

    
737
        } catch (PropertyNotFoundException e1) {
738
            String msg = "Couldn't get dataone.nodeId property: " + e1.getMessage();
739
            failure = new ServiceFailure("2151", msg);
740
            //setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
741
            logMetacat.error(msg);
742
            //return true;
743
            throw new ServiceFailure("2151", msg);
744

    
745
        }
746
        
747
        try {
748
            try {
749
                // do we already have a replica?
750
                try {
751
                    localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
752
                    // if we have a local id, get the local object
753
                    try {
754
                        object = MetacatHandler.read(localId);
755
                    } catch (Exception e) {
756
                        // NOTE: we may already know about this ID because it could be a data file described by a metadata file
757
                        // https://redmine.dataone.org/issues/2572
758
                        // TODO: fix this so that we don't prevent ourselves from getting replicas
759
                        
760
                        // let the CN know that the replication failed
761
                        logMetacat.warn("Object content not found on this node despite having localId: " + localId);
762
                        String msg = "Can't read the object bytes properly, replica is invalid.";
763
                        ServiceFailure serviceFailure = new ServiceFailure("2151", msg);
764
                        setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, serviceFailure);
765
                        logMetacat.warn(msg);
766
                        throw serviceFailure;
767
                        
768
                    }
769

    
770
                } catch (McdbDocNotFoundException e) {
771
                    logMetacat.info("No replica found. Continuing.");
772
                    
773
                } catch (SQLException ee) {
774
                    throw new ServiceFailure("2151", "Couldn't identify the local id of the object with the specified identifier "
775
                                            +pid.getValue()+" since - "+ee.getMessage());
776
                }
777
                
778
                // no local replica, get a replica
779
                if ( object == null ) {
780
                    /*boolean success = true;
781
                    try {
782
                        //use the v2 ping api to connect the source node
783
                        mn.ping();
784
                    } catch (Exception e) {
785
                        success = false;
786
                    }*/
787
                    D1NodeVersionChecker checker = new D1NodeVersionChecker(sourceNode);
788
                    String nodeVersion = checker.getVersion("MNRead");
789
                    if(nodeVersion != null && nodeVersion.equals(D1NodeVersionChecker.V1)) {
790
                        //The source node is a v1 node, we use the v1 api
791
                        org.dataone.client.v1.MNode mNodeV1 =  org.dataone.client.v1.itk.D1Client.getMN(sourceNode);
792
                        object = mNodeV1.getReplica(thisNodeSession, pid);
793
                    } else if (nodeVersion != null && nodeVersion.equals(D1NodeVersionChecker.V2)){
794
                     // session should be null to use the default certificate
795
                        // location set in the Certificate manager
796
                        MNode mn = D1Client.getMN(sourceNode);
797
                        object = mn.getReplica(thisNodeSession, pid);
798
                    } else {
799
                        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");
800
                    }
801
                    
802
                    logMetacat.info("MNodeService.getReplica() called for identifier "
803
                                    + pid.getValue());
804

    
805
                }
806

    
807
            } catch (InvalidToken e) {            
808
                String msg = "Could not retrieve object to replicate (InvalidToken): "+ e.getMessage();
809
                failure = new ServiceFailure("2151", msg);
810
                setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
811
                logMetacat.error(msg);
812
                throw new ServiceFailure("2151", msg);
813

    
814
            } catch (NotFound e) {
815
                String msg = "Could not retrieve object to replicate (NotFound): "+ e.getMessage();
816
                failure = new ServiceFailure("2151", msg);
817
                setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
818
                logMetacat.error(msg);
819
                throw new ServiceFailure("2151", msg);
820

    
821
            } catch (NotAuthorized e) {
822
                String msg = "Could not retrieve object to replicate (NotAuthorized): "+ e.getMessage();
823
                failure = new ServiceFailure("2151", msg);
824
                setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
825
                logMetacat.error(msg);
826
                throw new ServiceFailure("2151", msg);
827
            } catch (NotImplemented e) {
828
                String msg = "Could not retrieve object to replicate (mn.getReplica NotImplemented): "+ e.getMessage();
829
                failure = new ServiceFailure("2151", msg);
830
                setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
831
                logMetacat.error(msg);
832
                throw new ServiceFailure("2151", msg);
833
            } catch (ServiceFailure e) {
834
                String msg = "Could not retrieve object to replicate (ServiceFailure): "+ e.getMessage();
835
                failure = new ServiceFailure("2151", msg);
836
                setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
837
                logMetacat.error(msg);
838
                throw new ServiceFailure("2151", msg);
839
            } catch (InsufficientResources e) {
840
                String msg = "Could not retrieve object to replicate (InsufficientResources): "+ e.getMessage();
841
                failure = new ServiceFailure("2151", msg);
842
                setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
843
                logMetacat.error(msg);
844
                throw new ServiceFailure("2151", msg);
845
            }
846

    
847
            // verify checksum on the object, if supported
848
            if (object.markSupported()) {
849
                Checksum givenChecksum = sysmeta.getChecksum();
850
                Checksum computedChecksum = null;
851
                try {
852
                    computedChecksum = ChecksumUtil.checksum(object, givenChecksum.getAlgorithm());
853
                    object.reset();
854

    
855
                } catch (Exception e) {
856
                    String msg = "Error computing checksum on replica: " + e.getMessage();
857
                    logMetacat.error(msg);
858
                    ServiceFailure sf = new ServiceFailure("2151", msg);
859
                    sf.initCause(e);
860
                    setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, sf);
861
                    throw sf;
862
                }
863
                if (!givenChecksum.getValue().equals(computedChecksum.getValue())) {
864
                    logMetacat.error("Given    checksum for " + pid.getValue() + 
865
                        "is " + givenChecksum.getValue());
866
                    logMetacat.error("Computed checksum for " + pid.getValue() + 
867
                        "is " + computedChecksum.getValue());
868
                    String msg = "Computed checksum does not match declared checksum";
869
                    failure = new ServiceFailure("2151", msg);
870
                    setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
871
                    throw new ServiceFailure("2151", msg);
872
                }
873
            }
874

    
875
            // add it to local store
876
            Identifier retPid;
877
            try {
878
                // skip the MN.create -- this mutates the system metadata and we don't want it to
879
                if ( localId == null ) {
880
                    // TODO: this will fail if we already "know" about the identifier
881
                    // FIXME: see https://redmine.dataone.org/issues/2572
882
                    retPid = super.create(session, pid, object, sysmeta);
883
                    result = (retPid.getValue().equals(pid.getValue()));
884
                }
885
                
886
            } catch (Exception e) {
887
                String msg = "Could not save object to local store (" + e.getClass().getName() + "): " + e.getMessage();
888
                failure = new ServiceFailure("2151", msg);
889
                setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
890
                logMetacat.error(msg);
891
                throw new ServiceFailure("2151", msg);
892
                
893
            }
894
        } finally {
895
            IOUtils.closeQuietly(object);
896
        }
897
        
898

    
899
        // finish by setting the replication status
900
        setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.COMPLETED, null);
901
        return result;
902

    
903
    }
904
    
905
    /*
906
     * If the given node supports v2 replication.
907
     */
908
    private boolean supportV2Replication(Node node) throws InvalidRequest {
909
        return supportVersionReplication(node, "v2");
910
    }
911
    
912
    /*
913
     * If the given node support the the given version replication. Return true if it does.
914
     */
915
    private boolean supportVersionReplication(Node node, String version) throws InvalidRequest{
916
        boolean support = false;
917
        if(node == null) {
918
            throw new InvalidRequest("2153", "There is no capacity information about the node in the replicate.");
919
        } else {
920
            Services services = node.getServices();
921
            if(services == null) {
922
                throw new InvalidRequest("2153", "Can't get replica from a node which doesn't have the replicate service.");
923
            } else {
924
               List<Service> list = services.getServiceList();
925
               if(list == null) {
926
                   throw new InvalidRequest("2153", "Can't get replica from a node which doesn't have the replicate service.");
927
               } else {
928
                   for(Service service : list) {
929
                       if(service != null && service.getName() != null && service.getName().equals("MNReplication") && 
930
                               service.getVersion() != null && service.getVersion().equalsIgnoreCase(version) && service.getAvailable() == true ) {
931
                           support = true;
932
                           
933
                       }
934
                   }
935
               }
936
            }
937
        }
938
        return support;
939
    }
940

    
941
    /**
942
     * Return the object identified by the given object identifier
943
     * 
944
     * @param session - the Session object containing the credentials for the Subject
945
     * @param pid - the object identifier for the given object
946
     * 
947
     * @return inputStream - the input stream of the given object
948
     * 
949
     * @throws InvalidToken
950
     * @throws ServiceFailure
951
     * @throws NotAuthorized
952
     * @throws InvalidRequest
953
     * @throws NotImplemented
954
     */
955
    @Override
956
    public InputStream get(Session session, Identifier pid) 
957
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
958

    
959
        return super.get(session, pid);
960

    
961
    }
962

    
963
    /**
964
     * Returns a Checksum for the specified object using an accepted hashing algorithm
965
     * 
966
     * @param session - the Session object containing the credentials for the Subject
967
     * @param pid - the object identifier for the given object
968
     * @param algorithm -  the name of an algorithm that will be used to compute 
969
     *                     a checksum of the bytes of the object
970
     * 
971
     * @return checksum - the checksum of the given object
972
     * 
973
     * @throws InvalidToken
974
     * @throws ServiceFailure
975
     * @throws NotAuthorized
976
     * @throws NotFound
977
     * @throws InvalidRequest
978
     * @throws NotImplemented
979
     */
980
    @Override
981
    public Checksum getChecksum(Session session, Identifier pid, String algorithm) 
982
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
983
        InvalidRequest, NotImplemented {
984

    
985
        Checksum checksum = null;
986
        String serviceFailure = "1410";
987
        String notFound = "1420";
988
        //Checkum only handles the pid, not sid
989
        checkV1SystemMetaPidExist(pid, serviceFailure, "The checksum for the object specified by "+pid.getValue()+" couldn't be returned ",  notFound, 
990
                "The object specified by "+pid.getValue()+" does not exist at this node.");
991
        InputStream inputStream = get(session, pid);
992

    
993
        try {
994
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
995

    
996
        } catch (NoSuchAlgorithmException e) {
997
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
998
                    + e.getMessage());
999
        } catch (IOException e) {
1000
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
1001
                    + e.getMessage());
1002
        }
1003

    
1004
        if (checksum == null) {
1005
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
1006
        }
1007

    
1008
        return checksum;
1009
    }
1010

    
1011
    /**
1012
     * Return the system metadata for a given object
1013
     * 
1014
     * @param session - the Session object containing the credentials for the Subject
1015
     * @param pid - the object identifier for the given object
1016
     * 
1017
     * @return inputStream - the input stream of the given system metadata object
1018
     * 
1019
     * @throws InvalidToken
1020
     * @throws ServiceFailure
1021
     * @throws NotAuthorized
1022
     * @throws NotFound
1023
     * @throws InvalidRequest
1024
     * @throws NotImplemented
1025
     */
1026
    @Override
1027
    public SystemMetadata getSystemMetadata(Session session, Identifier pid) 
1028
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
1029
        NotImplemented {
1030

    
1031
        return super.getSystemMetadata(session, pid);
1032
    }
1033

    
1034
    /**
1035
     * Retrieve the list of objects present on the MN that match the calling parameters
1036
     * 
1037
     * @param session - the Session object containing the credentials for the Subject
1038
     * @param startTime - Specifies the beginning of the time range from which 
1039
     *                    to return object (>=)
1040
     * @param endTime - Specifies the beginning of the time range from which 
1041
     *                  to return object (>=)
1042
     * @param objectFormat - Restrict results to the specified object format
1043
     * @param replicaStatus - Indicates if replicated objects should be returned in the list
1044
     * @param start - The zero-based index of the first value, relative to the 
1045
     *                first record of the resultset that matches the parameters.
1046
     * @param count - The maximum number of entries that should be returned in 
1047
     *                the response. The Member Node may return less entries 
1048
     *                than specified in this value.
1049
     * 
1050
     * @return objectList - the list of objects matching the criteria
1051
     * 
1052
     * @throws InvalidToken
1053
     * @throws ServiceFailure
1054
     * @throws NotAuthorized
1055
     * @throws InvalidRequest
1056
     * @throws NotImplemented
1057
     */
1058
    @Override
1059
    public ObjectList listObjects(Session session, Date startTime, Date endTime, ObjectFormatIdentifier objectFormatId, Identifier identifier, Boolean replicaStatus, Integer start,
1060
            Integer count) throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken {
1061
        NodeReference nodeId = null;
1062
        if(!replicaStatus) {
1063
            //not include those objects whose authoritative node is not this mn
1064
            nodeId = new NodeReference();
1065
            try {
1066
                String currentNodeId = PropertyService.getInstance().getProperty("dataone.nodeId"); // return only pids for which this mn
1067
                nodeId.setValue(currentNodeId);
1068
            } catch(Exception e) {
1069
                throw new ServiceFailure("1580", e.getMessage());
1070
            }
1071
        }
1072
        return super.listObjects(session, startTime, endTime, objectFormatId, identifier, nodeId, start, count);
1073
    }
1074

    
1075
    /**
1076
     * Return a description of the node's capabilities and services.
1077
     * 
1078
     * @return node - the technical capabilities of the Member Node
1079
     * 
1080
     * @throws ServiceFailure
1081
     * @throws NotAuthorized
1082
     * @throws InvalidRequest
1083
     * @throws NotImplemented
1084
     */
1085
    @Override
1086
    public Node getCapabilities() 
1087
        throws NotImplemented, ServiceFailure {
1088

    
1089
        String nodeName = null;
1090
        String nodeId = null;
1091
        String subject = null;
1092
        String contactSubject = null;
1093
        String nodeDesc = null;
1094
        String nodeTypeString = null;
1095
        NodeType nodeType = null;
1096
        List<String> mnCoreServiceVersions = null;
1097
        List<String> mnReadServiceVersions = null;
1098
        List<String> mnAuthorizationServiceVersions = null;
1099
        List<String> mnStorageServiceVersions = null;
1100
        List<String> mnReplicationServiceVersions = null;
1101

    
1102
        boolean nodeSynchronize = false;
1103
        boolean nodeReplicate = false;
1104
        List<String> mnCoreServiceAvailables = null;
1105
        List<String> mnReadServiceAvailables = null;
1106
        List<String> mnAuthorizationServiceAvailables = null;
1107
        List<String> mnStorageServiceAvailables = null;
1108
        List<String> mnReplicationServiceAvailables = null;
1109

    
1110
        try {
1111
            // get the properties of the node based on configuration information
1112
            nodeName = Settings.getConfiguration().getString("dataone.nodeName");
1113
            nodeId = Settings.getConfiguration().getString("dataone.nodeId");
1114
            subject = Settings.getConfiguration().getString("dataone.subject");
1115
            contactSubject = Settings.getConfiguration().getString("dataone.contactSubject");
1116
            nodeDesc = Settings.getConfiguration().getString("dataone.nodeDescription");
1117
            nodeTypeString = Settings.getConfiguration().getString("dataone.nodeType");
1118
            nodeType = NodeType.convert(nodeTypeString);
1119
            nodeSynchronize = new Boolean(Settings.getConfiguration().getString("dataone.nodeSynchronize")).booleanValue();
1120
            nodeReplicate = new Boolean(Settings.getConfiguration().getString("dataone.nodeReplicate")).booleanValue();
1121

    
1122
            // Set the properties of the node based on configuration information and
1123
            // calls to current status methods
1124
            String serviceName = SystemUtil.getContextURL() + "/" + PropertyService.getProperty("dataone.serviceName");
1125
            Node node = new Node();
1126
            node.setBaseURL(serviceName + "/" + nodeTypeString);
1127
            node.setDescription(nodeDesc);
1128

    
1129
            // set the node's health information
1130
            node.setState(NodeState.UP);
1131
            
1132
            // set the ping response to the current value
1133
            Ping canPing = new Ping();
1134
            canPing.setSuccess(false);
1135
            try {
1136
            	Date pingDate = ping();
1137
                canPing.setSuccess(pingDate != null);
1138
            } catch (BaseException e) {
1139
                e.printStackTrace();
1140
                // guess it can't be pinged
1141
            }
1142
            
1143
            node.setPing(canPing);
1144

    
1145
            NodeReference identifier = new NodeReference();
1146
            identifier.setValue(nodeId);
1147
            node.setIdentifier(identifier);
1148
            Subject s = new Subject();
1149
            s.setValue(subject);
1150
            node.addSubject(s);
1151
            Subject contact = new Subject();
1152
            contact.setValue(contactSubject);
1153
            node.addContactSubject(contact);
1154
            node.setName(nodeName);
1155
            node.setReplicate(nodeReplicate);
1156
            node.setSynchronize(nodeSynchronize);
1157

    
1158
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
1159
            Services services = new Services();
1160

    
1161
            mnCoreServiceVersions = Settings.getConfiguration().getList("dataone.mnCore.serviceVersion");
1162
            mnCoreServiceAvailables = Settings.getConfiguration().getList("dataone.mnCore.serviceAvailable");
1163
            if(mnCoreServiceVersions != null && mnCoreServiceAvailables != null && mnCoreServiceVersions.size() == mnCoreServiceAvailables.size()) {
1164
                for(int i=0; i<mnCoreServiceVersions.size(); i++) {
1165
                    String version = mnCoreServiceVersions.get(i);
1166
                    boolean available = new Boolean(mnCoreServiceAvailables.get(i)).booleanValue();
1167
                    Service sMNCore = new Service();
1168
                    sMNCore.setName("MNCore");
1169
                    sMNCore.setVersion(version);
1170
                    sMNCore.setAvailable(available);
1171
                    services.addService(sMNCore);
1172
                }
1173
            }
1174
            
1175
            mnReadServiceVersions = Settings.getConfiguration().getList("dataone.mnRead.serviceVersion");
1176
            mnReadServiceAvailables = Settings.getConfiguration().getList("dataone.mnRead.serviceAvailable");
1177
            if(mnReadServiceVersions != null && mnReadServiceAvailables != null && mnReadServiceVersions.size()==mnReadServiceAvailables.size()) {
1178
                for(int i=0; i<mnReadServiceVersions.size(); i++) {
1179
                    String version = mnReadServiceVersions.get(i);
1180
                    boolean available = new Boolean(mnReadServiceAvailables.get(i)).booleanValue();
1181
                    Service sMNRead = new Service();
1182
                    sMNRead.setName("MNRead");
1183
                    sMNRead.setVersion(version);
1184
                    sMNRead.setAvailable(available);
1185
                    services.addService(sMNRead);
1186
                }
1187
            }
1188
           
1189
            mnAuthorizationServiceVersions = Settings.getConfiguration().getList("dataone.mnAuthorization.serviceVersion");
1190
            mnAuthorizationServiceAvailables = Settings.getConfiguration().getList("dataone.mnAuthorization.serviceAvailable");
1191
            if(mnAuthorizationServiceVersions != null && mnAuthorizationServiceAvailables != null && mnAuthorizationServiceVersions.size()==mnAuthorizationServiceAvailables.size()) {
1192
                for(int i=0; i<mnAuthorizationServiceVersions.size(); i++) {
1193
                    String version = mnAuthorizationServiceVersions.get(i);
1194
                    boolean available = new Boolean(mnAuthorizationServiceAvailables.get(i)).booleanValue();
1195
                    Service sMNAuthorization = new Service();
1196
                    sMNAuthorization.setName("MNAuthorization");
1197
                    sMNAuthorization.setVersion(version);
1198
                    sMNAuthorization.setAvailable(available);
1199
                    services.addService(sMNAuthorization);
1200
                }
1201
            }
1202
           
1203
            mnStorageServiceVersions = Settings.getConfiguration().getList("dataone.mnStorage.serviceVersion");
1204
            mnStorageServiceAvailables = Settings.getConfiguration().getList("dataone.mnStorage.serviceAvailable");
1205
            if(mnStorageServiceVersions != null && mnStorageServiceAvailables != null && mnStorageServiceVersions.size() == mnStorageServiceAvailables.size()) {
1206
                for(int i=0; i<mnStorageServiceVersions.size(); i++) {
1207
                    String version = mnStorageServiceVersions.get(i);
1208
                    boolean available = new Boolean(mnStorageServiceAvailables.get(i)).booleanValue();
1209
                    Service sMNStorage = new Service();
1210
                    sMNStorage.setName("MNStorage");
1211
                    sMNStorage.setVersion(version);
1212
                    sMNStorage.setAvailable(available);
1213
                    services.addService(sMNStorage);
1214
                }
1215
            }
1216
            
1217
            mnReplicationServiceVersions = Settings.getConfiguration().getList("dataone.mnReplication.serviceVersion");
1218
            mnReplicationServiceAvailables = Settings.getConfiguration().getList("dataone.mnReplication.serviceAvailable");
1219
            if(mnReplicationServiceVersions != null && mnReplicationServiceAvailables != null && mnReplicationServiceVersions.size() == mnReplicationServiceAvailables.size()) {
1220
                for (int i=0; i<mnReplicationServiceVersions.size(); i++) {
1221
                    String version = mnReplicationServiceVersions.get(i);
1222
                    boolean available = new Boolean(mnReplicationServiceAvailables.get(i)).booleanValue();
1223
                    Service sMNReplication = new Service();
1224
                    sMNReplication.setName("MNReplication");
1225
                    sMNReplication.setVersion(version);
1226
                    sMNReplication.setAvailable(available);
1227
                    services.addService(sMNReplication);
1228
                }
1229
            }
1230
            
1231
            node.setServices(services);
1232

    
1233
            // Set the schedule for synchronization
1234
            Synchronization synchronization = new Synchronization();
1235
            Schedule schedule = new Schedule();
1236
            Date now = new Date();
1237
            schedule.setYear(PropertyService.getProperty("dataone.nodeSynchronization.schedule.year"));
1238
            schedule.setMon(PropertyService.getProperty("dataone.nodeSynchronization.schedule.mon"));
1239
            schedule.setMday(PropertyService.getProperty("dataone.nodeSynchronization.schedule.mday"));
1240
            schedule.setWday(PropertyService.getProperty("dataone.nodeSynchronization.schedule.wday"));
1241
            schedule.setHour(PropertyService.getProperty("dataone.nodeSynchronization.schedule.hour"));
1242
            schedule.setMin(PropertyService.getProperty("dataone.nodeSynchronization.schedule.min"));
1243
            schedule.setSec(PropertyService.getProperty("dataone.nodeSynchronization.schedule.sec"));
1244
            synchronization.setSchedule(schedule);
1245
            synchronization.setLastHarvested(now);
1246
            synchronization.setLastCompleteHarvest(now);
1247
            node.setSynchronization(synchronization);
1248

    
1249
            node.setType(nodeType);
1250
            return node;
1251

    
1252
        } catch (PropertyNotFoundException pnfe) {
1253
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
1254
            logMetacat.error(msg);
1255
            throw new ServiceFailure("2162", msg);
1256
        }
1257
    }
1258

    
1259
    
1260

    
1261
    /**
1262
     * A callback method used by a CN to indicate to a MN that it cannot 
1263
     * complete synchronization of the science metadata identified by pid.  Log
1264
     * the event in the metacat event log.
1265
     * 
1266
     * @param session
1267
     * @param syncFailed
1268
     * 
1269
     * @throws ServiceFailure
1270
     * @throws NotAuthorized
1271
     * @throws NotImplemented
1272
     */
1273
    @Override
1274
    public boolean synchronizationFailed(Session session, SynchronizationFailed syncFailed) 
1275
        throws NotImplemented, ServiceFailure, NotAuthorized {
1276

    
1277
        String localId;
1278
        Identifier pid;
1279
        if ( syncFailed.getPid() != null ) {
1280
            pid = new Identifier();
1281
            pid.setValue(syncFailed.getPid());
1282
            boolean allowed;
1283
            
1284
            //are we allowed? only CNs
1285
            try {
1286
                allowed = isAdminAuthorized(session);
1287
                if ( !allowed ){
1288
                    throw new NotAuthorized("2162", 
1289
                            "Not allowed to call synchronizationFailed() on this node.");
1290
                }
1291
            } catch (InvalidToken e) {
1292
                throw new NotAuthorized("2162", 
1293
                        "Not allowed to call synchronizationFailed() on this node.");
1294

    
1295
            }
1296
            
1297
        } else {
1298
            throw new ServiceFailure("2161", "The identifier cannot be null.");
1299

    
1300
        }
1301
        
1302
        try {
1303
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1304
        } catch (McdbDocNotFoundException e) {
1305
            throw new ServiceFailure("2161", "The identifier specified by " + 
1306
                    syncFailed.getPid() + " was not found on this node.");
1307

    
1308
        } catch (SQLException e) {
1309
            throw new ServiceFailure("2161", "Couldn't identify the local id of the identifier specified by " + 
1310
                    syncFailed.getPid() + " since "+e.getMessage());
1311
        }
1312
        // TODO: update the CN URL below when the CNRead.SynchronizationFailed
1313
        // method is changed to include the URL as a parameter
1314
        logMetacat.warn("Synchronization for the object identified by " + 
1315
                pid.getValue() + " failed from " + syncFailed.getNodeId() + 
1316
                " with message: " + syncFailed.getDescription() + 
1317
                ". Logging the event to the Metacat EventLog as a 'syncFailed' event.");
1318
        // TODO: use the event type enum when the SYNCHRONIZATION_FAILED event is added
1319
        String principal = Constants.SUBJECT_PUBLIC;
1320
        if (session != null && session.getSubject() != null) {
1321
          principal = session.getSubject().getValue();
1322
        }
1323
        try {
1324
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "synchronization_failed");
1325
        } catch (Exception e) {
1326
            throw new ServiceFailure("2161", "Could not log the error for: " + pid.getValue());
1327
        }
1328
        //EventLog.getInstance().log("CN URL WILL GO HERE", 
1329
        //  session.getSubject().getValue(), localId, Event.SYNCHRONIZATION_FAILED);
1330
        return true;
1331

    
1332
    }
1333

    
1334
    /**
1335
     * Essentially a get() but with different logging behavior
1336
     */
1337
    @Override
1338
    public InputStream getReplica(Session session, Identifier pid) 
1339
        throws NotAuthorized, NotImplemented, ServiceFailure, InvalidToken, NotFound {
1340

    
1341
        logMetacat.info("MNodeService.getReplica() called.");
1342

    
1343
        // cannot be called by public
1344
        if (session == null) {
1345
        	throw new InvalidToken("2183", "No session was provided.");
1346
        }
1347
        
1348
        logMetacat.info("MNodeService.getReplica() called with parameters: \n" +
1349
             "\tSession.Subject      = " + session.getSubject().getValue() + "\n" +
1350
             "\tIdentifier           = " + pid.getValue());
1351

    
1352
        InputStream inputStream = null; // bytes to be returned
1353
        handler = new MetacatHandler(new Timer());
1354
        boolean allowed = false;
1355
        String localId; // the metacat docid for the pid
1356

    
1357
        // get the local docid from Metacat
1358
        try {
1359
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1360
        } catch (McdbDocNotFoundException e) {
1361
            throw new NotFound("2185", "The object specified by " + 
1362
                    pid.getValue() + " does not exist at this node.");
1363
            
1364
        } catch (SQLException e) {
1365
            throw new ServiceFailure("2181", "The local id of the object specified by " + 
1366
                    pid.getValue() + " couldn't be identified since "+e.getMessage());
1367
        }
1368

    
1369
        Subject targetNodeSubject = session.getSubject();
1370

    
1371
        // check for authorization to replicate, null session to act as this source MN
1372
        try {
1373
            allowed = D1Client.getCN().isNodeAuthorized(null, targetNodeSubject, pid);
1374
        } catch (InvalidToken e1) {
1375
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
1376
                + e1.getMessage());
1377
            
1378
        } catch (NotFound e1) {
1379
            throw new NotFound("2185", "Could not find the object "+pid.getValue()+" in this node - " 
1380
                    + e1.getMessage());
1381

    
1382
        } catch (InvalidRequest e1) {
1383
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
1384
                    + e1.getMessage());
1385

    
1386
        }
1387

    
1388
        logMetacat.info("Called D1Client.isNodeAuthorized(). Allowed = " + allowed +
1389
            " for identifier " + pid.getValue());
1390

    
1391
        // if the person is authorized, perform the read
1392
        if (allowed) {
1393
            try {
1394
                inputStream = MetacatHandler.read(localId);
1395
            } catch (Exception e) {
1396
                throw new ServiceFailure("2181", "The object specified by " + 
1397
                    pid.getValue() + "could not be returned due to error: " + e.getMessage());
1398
            }
1399
        } else {
1400
            throw new NotAuthorized("2182", "The pid "+pid.getValue()+" is not authorized to be read by the client.");
1401
        }
1402

    
1403
        // if we fail to set the input stream
1404
        if (inputStream == null) {
1405
            throw new ServiceFailure("2181", "The object specified by " + 
1406
                pid.getValue() + " can't be returned from the node.");
1407
        }
1408

    
1409
        // log the replica event
1410
        String principal = null;
1411
        if (session.getSubject() != null) {
1412
            principal = session.getSubject().getValue();
1413
        }
1414
        EventLog.getInstance().log(request.getRemoteAddr(), 
1415
            request.getHeader("User-Agent"), principal, localId, "replicate");
1416

    
1417
        return inputStream;
1418
    }
1419
    
1420
    /**
1421
     * A method to notify the Member Node that the authoritative copy of 
1422
     * system metadata on the Coordinating Nodes has changed.
1423
     *
1424
     * @param session   Session information that contains the identity of the 
1425
     *                  calling user as retrieved from the X.509 certificate 
1426
     *                  which must be traceable to the CILogon service.
1427
     * @param serialVersion   The serialVersion of the system metadata
1428
     * @param dateSysMetaLastModified  The time stamp for when the system metadata was changed
1429
     * @throws NotImplemented
1430
     * @throws ServiceFailure
1431
     * @throws NotAuthorized
1432
     * @throws InvalidRequest
1433
     * @throws InvalidToken
1434
     */
1435
    public boolean systemMetadataChanged(Session session, Identifier pid,
1436
        long serialVersion, Date dateSysMetaLastModified) 
1437
        throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest,
1438
        InvalidToken {
1439
        boolean needCheckAuthoriativeNode = true; 
1440
        return systemMetadataChanged(needCheckAuthoriativeNode, session, pid,serialVersion, dateSysMetaLastModified);
1441
    }
1442

    
1443
    /**
1444
     * A method to notify the Member Node that the authoritative copy of 
1445
     * system metadata on the Coordinating Nodes has changed.
1446
     * @param needCheckAuthoriativeNode  this is for the dataone version 2. In the
1447
     * version 2, there are two scenarios:
1448
     * 1. If the node is the authoritative node, it only accepts serial version and replica list.
1449
     * 2. If the node is a replica, it accepts everything.
1450
     * For the v1, api, the parameter should be false. 
1451
     * @param session   Session information that contains the identity of the 
1452
     *                  calling user as retrieved from the X.509 certificate 
1453
     *                  which must be traceable to the CILogon service.
1454
     * @param serialVersion   The serialVersion of the system metadata
1455
     * @param dateSysMetaLastModified  The time stamp for when the system metadata was changed
1456
     * @throws NotImplemented
1457
     * @throws ServiceFailure
1458
     * @throws NotAuthorized
1459
     * @throws InvalidRequest
1460
     * @throws InvalidToken
1461
     */
1462
    public boolean systemMetadataChanged(boolean needCheckAuthoriativeNode, Session session, Identifier pid,
1463
        long serialVersion, Date dateSysMetaLastModified) 
1464
        throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest,
1465
        InvalidToken {
1466
        
1467
        /*if(isReadOnlyMode()) {
1468
            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.");
1469
        }*/
1470
        // cannot be called by public
1471
        if (session == null) {
1472
        	throw new InvalidToken("1332", "No session was provided.");
1473
        }
1474

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

    
1728
	@Override
1729
	public Identifier generateIdentifier(Session session, String scheme, String fragment)
1730
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1731
			InvalidRequest {
1732
		
1733
		// check for null session
1734
        if (session == null) {
1735
          throw new InvalidToken("2190", "Session is required to generate an Identifier at this Node.");
1736
        }
1737
		
1738
		Identifier identifier = new Identifier();
1739
		
1740
		// handle different schemes
1741
		if (scheme.equalsIgnoreCase(UUID_SCHEME)) {
1742
			// UUID
1743
			UUID uuid = UUID.randomUUID();
1744
            identifier.setValue(UUID_PREFIX + uuid.toString());
1745
		} else if (scheme.equalsIgnoreCase(DOI_SCHEME)) {
1746
			// generate a DOI
1747
			try {
1748
				identifier = DOIService.getInstance().generateDOI();
1749
			} catch (EZIDException e) {
1750
				ServiceFailure sf = new ServiceFailure("2191", "Could not generate DOI: " + e.getMessage());
1751
				sf.initCause(e);
1752
				throw sf;
1753
			}
1754
		} else {
1755
			// default if we don't know the scheme
1756
			if (fragment != null) {
1757
				// for now, just autogen with fragment
1758
				String autogenId = DocumentUtil.generateDocumentId(fragment, 0);
1759
				identifier.setValue(autogenId);			
1760
			} else {
1761
				// autogen with no fragment
1762
				String autogenId = DocumentUtil.generateDocumentId(0);
1763
				identifier.setValue(autogenId);
1764
			}
1765
		}
1766
		
1767
		// TODO: reserve the identifier with the CN. We can only do this when
1768
		// 1) the MN is part of a CN cluster
1769
		// 2) the request is from an authenticated user
1770
		
1771
		return identifier;
1772
	}
1773

    
1774
	
1775

    
1776
	@Override
1777
	public QueryEngineDescription getQueryEngineDescription(Session session, String engine)
1778
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1779
			NotFound {
1780
	    if(engine != null && engine.equals(EnabledQueryEngines.PATHQUERYENGINE)) {
1781
	        if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.PATHQUERYENGINE)) {
1782
                throw new NotImplemented("0000", "MNodeService.query - the query engine "+engine +" hasn't been implemented or has been disabled.");
1783
            }
1784
	        QueryEngineDescription qed = new QueryEngineDescription();
1785
	        qed.setName(EnabledQueryEngines.PATHQUERYENGINE);
1786
	        qed.setQueryEngineVersion("1.0");
1787
	        qed.addAdditionalInfo("This is the traditional structured query for Metacat");
1788
	        Vector<String> pathsForIndexing = null;
1789
	        try {
1790
	            pathsForIndexing = SystemUtil.getPathsForIndexing();
1791
	        } catch (MetacatUtilException e) {
1792
	            logMetacat.warn("Could not get index paths", e);
1793
	        }
1794
	        for (String fieldName: pathsForIndexing) {
1795
	            QueryField field = new QueryField();
1796
	            field.addDescription("Indexed field for path '" + fieldName + "'");
1797
	            field.setName(fieldName);
1798
	            field.setReturnable(true);
1799
	            field.setSearchable(true);
1800
	            field.setSortable(false);
1801
	            // TODO: determine type and multivaluedness
1802
	            field.setType(String.class.getName());
1803
	            //field.setMultivalued(true);
1804
	            qed.addQueryField(field);
1805
	        }
1806
	        return qed;
1807
	    } else if (engine != null && engine.equals(EnabledQueryEngines.SOLRENGINE)) {
1808
	        if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.SOLRENGINE)) {
1809
                throw new NotImplemented("0000", "MNodeService.getQueryEngineDescription - the query engine "+engine +" hasn't been implemented or has been disabled.");
1810
            }
1811
	        try {
1812
	            QueryEngineDescription qed = MetacatSolrEngineDescriptionHandler.getInstance().getQueryEngineDescritpion();
1813
	            return qed;
1814
	        } catch (Exception e) {
1815
	            e.printStackTrace();
1816
	            throw new ServiceFailure("Solr server error", e.getMessage());
1817
	        }
1818
	    } else {
1819
	        throw new NotFound("404", "The Metacat member node can't find the query engine - "+engine);
1820
	    }
1821
		
1822
	}
1823

    
1824
	@Override
1825
	public QueryEngineList listQueryEngines(Session session) throws InvalidToken,
1826
			ServiceFailure, NotAuthorized, NotImplemented {
1827
		QueryEngineList qel = new QueryEngineList();
1828
		//qel.addQueryEngine(EnabledQueryEngines.PATHQUERYENGINE);
1829
		//qel.addQueryEngine(EnabledQueryEngines.SOLRENGINE);
1830
		List<String> enables = EnabledQueryEngines.getInstance().getEnabled();
1831
		for(String name : enables) {
1832
		    qel.addQueryEngine(name);
1833
		}
1834
		return qel;
1835
	}
1836

    
1837
	@Override
1838
	public InputStream query(Session session, String engine, String query) throws InvalidToken,
1839
			ServiceFailure, NotAuthorized, InvalidRequest, NotImplemented,
1840
			NotFound {
1841
	    String user = Constants.SUBJECT_PUBLIC;
1842
        String[] groups= null;
1843
        Set<Subject> subjects = null;
1844
        if (session != null) {
1845
            user = session.getSubject().getValue();
1846
            subjects = AuthUtils.authorizedClientSubjects(session);
1847
            if (subjects != null) {
1848
                List<String> groupList = new ArrayList<String>();
1849
                for (Subject subject: subjects) {
1850
                    groupList.add(subject.getValue());
1851
                }
1852
                groups = groupList.toArray(new String[0]);
1853
            }
1854
        } else {
1855
            //add the public user subject to the set 
1856
            Subject subject = new Subject();
1857
            subject.setValue(Constants.SUBJECT_PUBLIC);
1858
            subjects = new HashSet<Subject>();
1859
            subjects.add(subject);
1860
        }
1861
        //System.out.println("====== user is "+user);
1862
        //System.out.println("====== groups are "+groups);
1863
		if (engine != null && engine.equals(EnabledQueryEngines.PATHQUERYENGINE)) {
1864
		    if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.PATHQUERYENGINE)) {
1865
                throw new NotImplemented("0000", "MNodeService.query - the query engine "+engine +" hasn't been implemented or has been disabled.");
1866
            }
1867
			try {
1868
				DBQuery queryobj = new DBQuery();
1869
				
1870
				String results = queryobj.performPathquery(query, user, groups);
1871
				ContentTypeByteArrayInputStream ctbais = new ContentTypeByteArrayInputStream(results.getBytes(MetaCatServlet.DEFAULT_ENCODING));
1872
				ctbais.setContentType("text/xml");
1873
				return ctbais;
1874

    
1875
			} catch (Exception e) {
1876
				throw new ServiceFailure("Pathquery error", e.getMessage());
1877
			}
1878
			
1879
		} else if (engine != null && engine.equals(EnabledQueryEngines.SOLRENGINE)) {
1880
		    if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.SOLRENGINE)) {
1881
		        throw new NotImplemented("0000", "MNodeService.query - the query engine "+engine +" hasn't been implemented or has been disabled.");
1882
		    }
1883
		    logMetacat.info("The query is ==================================== \n"+query);
1884
		    try {
1885
		        
1886
                return MetacatSolrIndex.getInstance().query(query, subjects);
1887
            } catch (Exception e) {
1888
                // TODO Auto-generated catch block
1889
                throw new ServiceFailure("Solr server error", e.getMessage());
1890
            } 
1891
		}
1892
		return null;
1893
	}
1894
	
1895
	/**
1896
	 * Given an existing Science Metadata PID, this method mints a DOI
1897
	 * and updates the original object "publishing" the update with the DOI.
1898
	 * This includes updating the ORE map that describes the Science Metadata+data.
1899
	 * TODO: ensure all referenced objects allow public read
1900
	 * 
1901
	 * @see https://projects.ecoinformatics.org/ecoinfo/issues/6014
1902
	 * 
1903
	 * @param originalIdentifier
1904
	 * @param request
1905
	 * @throws InvalidRequest 
1906
	 * @throws NotImplemented 
1907
	 * @throws NotAuthorized 
1908
	 * @throws ServiceFailure 
1909
	 * @throws InvalidToken 
1910
	 * @throws NotFound
1911
	 * @throws InvalidSystemMetadata 
1912
	 * @throws InsufficientResources 
1913
	 * @throws UnsupportedType 
1914
	 * @throws IdentifierNotUnique 
1915
	 */
1916
	public Identifier publish(Session session, Identifier originalIdentifier) throws InvalidToken, 
1917
	ServiceFailure, NotAuthorized, NotImplemented, InvalidRequest, NotFound, IdentifierNotUnique, 
1918
	UnsupportedType, InsufficientResources, InvalidSystemMetadata, IOException {
1919
		
1920
	    String serviceFailureCode = "1030";
1921
	    Identifier sid = getPIDForSID(originalIdentifier, serviceFailureCode);
1922
	    if(sid != null) {
1923
	        originalIdentifier = sid;
1924
	    }
1925
		// get the original SM
1926
		SystemMetadata originalSystemMetadata = this.getSystemMetadata(session, originalIdentifier);
1927

    
1928
		// make copy of it using the marshaller to ensure DEEP copy
1929
		SystemMetadata sysmeta = null;
1930
		try {
1931
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
1932
			TypeMarshaller.marshalTypeToOutputStream(originalSystemMetadata, baos);
1933
			sysmeta = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class, new ByteArrayInputStream(baos.toByteArray()));
1934
		} catch (Exception e) {
1935
			// report as service failure
1936
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1937
			sf.initCause(e);
1938
			throw sf;
1939
		}
1940

    
1941
		// mint a DOI for the new revision
1942
		Identifier newIdentifier = this.generateIdentifier(session, MNodeService.DOI_SCHEME, null);
1943
				
1944
		// set new metadata values
1945
		sysmeta.setIdentifier(newIdentifier);
1946
		sysmeta.setObsoletes(originalIdentifier);
1947
		sysmeta.setObsoletedBy(null);
1948
		
1949
		// ensure it is publicly readable
1950
		sysmeta = makePublicIfNot(sysmeta, originalIdentifier);
1951
		
1952
		//Get the bytes
1953
		InputStream inputStream = null;		
1954
		boolean isScienceMetadata = isScienceMetadata(sysmeta);
1955
		//If it's a science metadata doc, we want to update the packageId first
1956
		if(isScienceMetadata){
1957
			InputStream originalObject = this.get(session, originalIdentifier);
1958
			
1959
			//Edit the science metadata with the new package Id (EML)
1960
			inputStream = editScienceMetadata(session, originalObject, originalIdentifier, newIdentifier);
1961
		}
1962
		else{
1963
			inputStream = this.get(session, originalIdentifier);
1964
		}
1965
		
1966
		// update the object
1967
		this.update(session, originalIdentifier, inputStream, newIdentifier, sysmeta);
1968
		
1969
		// update ORE that references the scimeta
1970
		// first try the naive method, then check the SOLR index
1971
		try {
1972
			String localId = IdentifierManager.getInstance().getLocalId(originalIdentifier.getValue());
1973
			
1974
			Identifier potentialOreIdentifier = new Identifier();
1975
			potentialOreIdentifier.setValue(SystemMetadataFactory.RESOURCE_MAP_PREFIX + localId);
1976
			
1977
			InputStream oreInputStream = null;
1978
			try {
1979
				oreInputStream = this.get(session, potentialOreIdentifier);
1980
			} catch (NotFound nf) {
1981
				// this is probably okay for many sci meta data docs
1982
				logMetacat.warn("No potential ORE map found for: " + potentialOreIdentifier.getValue());
1983
				// try the SOLR index
1984
				List<Identifier> potentialOreIdentifiers = this.lookupOreFor(originalIdentifier, false);
1985
				if (potentialOreIdentifiers != null) {
1986
					potentialOreIdentifier = potentialOreIdentifiers.get(0);
1987
					try {
1988
						oreInputStream = this.get(session, potentialOreIdentifier);
1989
					} catch (NotFound nf2) {
1990
						// this is probably okay for many sci meta data docs
1991
						logMetacat.warn("No potential ORE map found for: " + potentialOreIdentifier.getValue());
1992
					}
1993
				}
1994
			}
1995
			if (oreInputStream != null) {
1996
				Identifier newOreIdentifier = MNodeService.getInstance(request).generateIdentifier(session, MNodeService.UUID_SCHEME, null);
1997
	
1998
				Map<Identifier, Map<Identifier, List<Identifier>>> resourceMapStructure = ResourceMapFactory.getInstance().parseResourceMap(oreInputStream);
1999
				Map<Identifier, List<Identifier>> sciMetaMap = resourceMapStructure.get(potentialOreIdentifier);
2000
				List<Identifier> dataIdentifiers = sciMetaMap.get(originalIdentifier);
2001
					
2002
				// reconstruct the ORE with the new identifiers
2003
				sciMetaMap.remove(originalIdentifier);
2004
				sciMetaMap.put(newIdentifier, dataIdentifiers);
2005
				
2006
				ResourceMap resourceMap = ResourceMapFactory.getInstance().createResourceMap(newOreIdentifier, sciMetaMap);
2007
				String resourceMapString = ResourceMapFactory.getInstance().serializeResourceMap(resourceMap);
2008
				
2009
				// get the original ORE SM and update the values
2010
				SystemMetadata originalOreSysMeta = this.getSystemMetadata(session, potentialOreIdentifier);
2011
				SystemMetadata oreSysMeta = new SystemMetadata();
2012
				try {
2013
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
2014
					TypeMarshaller.marshalTypeToOutputStream(originalOreSysMeta, baos);
2015
					oreSysMeta = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class, new ByteArrayInputStream(baos.toByteArray()));
2016
				} catch (Exception e) {
2017
					// report as service failure
2018
					ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2019
					sf.initCause(e);
2020
					throw sf;
2021
				}
2022

    
2023
				oreSysMeta.setIdentifier(newOreIdentifier);
2024
				oreSysMeta.setObsoletes(potentialOreIdentifier);
2025
				oreSysMeta.setObsoletedBy(null);
2026
				oreSysMeta.setSize(BigInteger.valueOf(resourceMapString.getBytes("UTF-8").length));
2027
				oreSysMeta.setChecksum(ChecksumUtil.checksum(resourceMapString.getBytes("UTF-8"), oreSysMeta.getChecksum().getAlgorithm()));
2028
				
2029
				// ensure ORE is publicly readable
2030
				oreSysMeta = makePublicIfNot(oreSysMeta, potentialOreIdentifier);
2031
				
2032
				// ensure all data objects allow public read
2033
				List<String> pidsToSync = new ArrayList<String>();
2034
				for (Identifier dataId: dataIdentifiers) {
2035
					SystemMetadata dataSysMeta = this.getSystemMetadata(session, dataId);
2036
					dataSysMeta = makePublicIfNot(dataSysMeta, dataId);
2037
					this.updateSystemMetadata(dataSysMeta);
2038
					pidsToSync.add(dataId.getValue());
2039
				}
2040
				SyncAccessPolicy sap = new SyncAccessPolicy();
2041
				try {
2042
					sap.sync(pidsToSync);
2043
				} catch (Exception e) {
2044
					// ignore
2045
					logMetacat.warn("Error attempting to sync access for data objects when publishing package");
2046
				}
2047
				
2048
				// save the updated ORE
2049
				this.update(
2050
						session, 
2051
						potentialOreIdentifier, 
2052
						new ByteArrayInputStream(resourceMapString.getBytes("UTF-8")), 
2053
						newOreIdentifier, 
2054
						oreSysMeta);
2055
				
2056
			} else {
2057
				// create a new ORE for them
2058
				// https://projects.ecoinformatics.org/ecoinfo/issues/6194
2059
				try {
2060
					// find the local id for the NEW package.
2061
					String newLocalId = IdentifierManager.getInstance().getLocalId(newIdentifier.getValue());
2062
	
2063
					@SuppressWarnings("unused")
2064
					SystemMetadata extraSysMeta = SystemMetadataFactory.createSystemMetadata(newLocalId, true, false);
2065
					// should be done generating the ORE here, and the same permissions were used from the metadata object
2066
					
2067
				} catch (Exception e) {
2068
					// oops, guess there was a problem - no package for you
2069
					logMetacat.error("Could not generate new ORE for published object: " + newIdentifier.getValue(), e);
2070
				}
2071
			}
2072
		} catch (McdbDocNotFoundException e) {
2073
			// report as service failure
2074
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2075
			sf.initCause(e);
2076
			throw sf;
2077
		} catch (UnsupportedEncodingException e) {
2078
			// report as service failure
2079
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2080
			sf.initCause(e);
2081
			throw sf;
2082
		} catch (OREException e) {
2083
			// report as service failure
2084
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2085
			sf.initCause(e);
2086
			throw sf;
2087
		} catch (URISyntaxException e) {
2088
			// report as service failure
2089
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2090
			sf.initCause(e);
2091
			throw sf;
2092
		} catch (OREParserException e) {
2093
			// report as service failure
2094
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2095
			sf.initCause(e);
2096
			throw sf;
2097
		} catch (ORESerialiserException e) {
2098
			// report as service failure
2099
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2100
			sf.initCause(e);
2101
			throw sf;
2102
		} catch (NoSuchAlgorithmException e) {
2103
			// report as service failure
2104
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2105
			sf.initCause(e);
2106
			throw sf;
2107
		} catch (SQLException e) {
2108
            // report as service failure
2109
            ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2110
            sf.initCause(e);
2111
            throw sf;
2112
        }
2113
		
2114
		return newIdentifier;
2115
	}
2116
	
2117
	/**
2118
	   * Update a science metadata document with its new Identifier  
2119
	   * 
2120
	   * @param session - the Session object containing the credentials for the Subject
2121
	   * @param object - the InputStream for the XML object to be edited
2122
	   * @param pid - the Identifier of the XML object to be updated
2123
	   * @param newPid = the new Identifier to give to the modified XML doc
2124
	   * 
2125
	   * @return newObject - The InputStream for the modified XML object
2126
	   * 
2127
	   * @throws ServiceFailure
2128
	   * @throws IOException
2129
	   * @throws UnsupportedEncodingException
2130
	   * @throws InvalidToken
2131
	   * @throws NotAuthorized
2132
	   * @throws NotFound
2133
	   * @throws NotImplemented
2134
	   */
2135
	  public InputStream editScienceMetadata(Session session, InputStream object, Identifier pid, Identifier newPid)
2136
	  	throws ServiceFailure, IOException, UnsupportedEncodingException, InvalidToken, NotAuthorized, NotFound, NotImplemented {
2137
	    
2138
		logMetacat.debug("D1NodeService.editScienceMetadata() called.");
2139
		
2140
		 InputStream newObject = null;
2141
		
2142
	    try{   	
2143
	    	//Get the root node of the XML document
2144
	    	byte[] xmlBytes  = IOUtils.toByteArray(object);
2145
	        String xmlStr = new String(xmlBytes, "UTF-8");
2146
	        
2147
	    	Document doc = XMLUtilities.getXMLReaderAsDOMDocument(new StringReader(xmlStr));
2148
		    org.w3c.dom.Node docNode = doc.getDocumentElement();
2149

    
2150
		    //Get the system metadata for this object
2151
		    SystemMetadata sysMeta = null;
2152
		    try{
2153
		    	sysMeta = getSystemMetadata(session, pid);
2154
		    } catch(NotAuthorized e){
2155
		    	throw new ServiceFailure("1030", "D1NodeService.editScienceMetadata(): " + 
2156
		    			"This session is not authorized to access the system metadata for " +
2157
		    			pid.getValue() + " : " + e.getMessage());
2158
		    } catch(NotFound e){
2159
		    	throw new ServiceFailure("1030", "D1NodeService.editScienceMetadata(): " + 
2160
		    			"Could not find the system metadata for " +
2161
		    			pid.getValue() + " : " + e.getMessage());
2162
		    }
2163
		    
2164
		    //Get the formatId
2165
	        ObjectFormatIdentifier objFormatId = sysMeta.getFormatId();
2166
	        String formatId = objFormatId.getValue();
2167
	        
2168
	    	//For all EML formats
2169
	        if(formatId.indexOf("eml") == 0){
2170
	        	//Update or add the id attribute
2171
	    	    XMLUtilities.addAttributeNodeToDOMTree(docNode, XPATH_EML_ID, newPid.getValue());
2172
	        }
2173

    
2174
	        //The modified object InputStream
2175
		    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
2176
		    Source xmlSource = new DOMSource(docNode);
2177
		    Result outputTarget = new StreamResult(outputStream);
2178
		    TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
2179
		    newObject = new ByteArrayInputStream(outputStream.toByteArray());
2180
		    
2181
	    } catch(TransformerException e) {
2182
	    	throw new ServiceFailure("1030", "MNNodeService.editScienceMetadata(): " +
2183
	                "Could not update the ID in the XML document for " +
2184
	                "pid " + pid.getValue() +" : " + e.getMessage());
2185
	    } catch(IOException e){
2186
	    	throw new ServiceFailure("1030", "MNNodeService.editScienceMetadata(): " +
2187
	                "Could not update the ID in the XML document for " +
2188
	                "pid " + pid.getValue() +" : " + e.getMessage());
2189
	    }
2190
	    
2191
	    return newObject;
2192
	  }
2193
	
2194
	/**
2195
	 * Determines if we already have registered an ORE map for this package
2196
	 * NOTE: uses a solr query to locate OREs for the object
2197
	 * @param guid of the EML/packaging object
2198
	 * @return list of resource map identifiers for the given pid
2199
	 */
2200
	public List<Identifier> lookupOreFor(Identifier guid, boolean includeObsolete) {
2201
		// Search for the ORE if we can find it
2202
		String pid = guid.getValue();
2203
		List<Identifier> retList = null;
2204
		try {
2205
			String query = "fl=id,resourceMap&wt=xml&q=-obsoletedBy:[* TO *]+resourceMap:[* TO *]+id:\"" + pid + "\"";
2206
			if (includeObsolete) {
2207
				query = "fl=id,resourceMap&wt=xml&q=resourceMap:[* TO *]+id:\"" + pid + "\"";
2208
			}
2209
			
2210
			InputStream results = this.query(null, "solr", query);
2211
			org.w3c.dom.Node rootNode = XMLUtilities.getXMLReaderAsDOMTreeRootNode(new InputStreamReader(results, "UTF-8"));
2212
			//String resultString = XMLUtilities.getDOMTreeAsString(rootNode);
2213
			org.w3c.dom.NodeList nodeList = XMLUtilities.getNodeListWithXPath(rootNode, "//arr[@name=\"resourceMap\"]/str");
2214
			if (nodeList != null && nodeList.getLength() > 0) {
2215
				retList = new ArrayList<Identifier>();
2216
				for (int i = 0; i < nodeList.getLength(); i++) {
2217
					String found = nodeList.item(i).getFirstChild().getNodeValue();
2218
					Identifier oreId = new Identifier();
2219
					oreId.setValue(found);
2220
					retList.add(oreId);
2221
				}
2222
			}
2223
		} catch (Exception e) {
2224
			logMetacat.error("Error checking for resourceMap[s] on pid " + pid + ". " + e.getMessage(), e);
2225
		}
2226
		
2227
		return retList;
2228
	}
2229
	
2230

    
2231
	@Override
2232
	public InputStream getPackage(Session session, ObjectFormatIdentifier formatId,
2233
			Identifier pid) throws InvalidToken, ServiceFailure,
2234
			NotAuthorized, InvalidRequest, NotImplemented, NotFound {
2235
	    if(formatId == null) {
2236
	        throw new InvalidRequest("2873", "The format type can't be null in the getpackage method.");
2237
	    } else if(!formatId.getValue().equals("application/bagit-097")) {
2238
	        throw new NotImplemented("", "The format "+formatId.getValue()+" is not supported in the getpackage method");
2239
	    }
2240
	    String serviceFailureCode = "2871";
2241
	    Identifier sid = getPIDForSID(pid, serviceFailureCode);
2242
	    if(sid != null) {
2243
	        pid = sid;
2244
	    }
2245
		InputStream bagInputStream = null;
2246
		BagFactory bagFactory = new BagFactory();
2247
		Bag bag = bagFactory.createBag();
2248
		
2249
		// track the temp files we use so we can delete them when finished
2250
		List<File> tempFiles = new ArrayList<File>();
2251
		
2252
		// the pids to include in the package
2253
		List<Identifier> packagePids = new ArrayList<Identifier>();
2254
		
2255
		// catch non-D1 service errors and throw as ServiceFailures
2256
		try {
2257
			//Create a map of dataone ids and file names
2258
			Map<Identifier, String> fileNames = new HashMap<Identifier, String>();
2259
			
2260
			// track the pid-to-file mapping
2261
			StringBuffer pidMapping = new StringBuffer();
2262
			
2263
			// find the package contents
2264
			SystemMetadata sysMeta = this.getSystemMetadata(session, pid);
2265
			if (ObjectFormatCache.getInstance().getFormat(sysMeta.getFormatId()).getFormatType().equals("RESOURCE")) {
2266
				//Get the resource map as a map of Identifiers
2267
				InputStream oreInputStream = this.get(session, pid);
2268
				Map<Identifier, Map<Identifier, List<Identifier>>> resourceMapStructure = ResourceMapFactory.getInstance().parseResourceMap(oreInputStream);
2269
				packagePids.addAll(resourceMapStructure.keySet());
2270
				//Loop through each object in this resource map
2271
				for (Map<Identifier, List<Identifier>> entries: resourceMapStructure.values()) {
2272
					//Loop through each metadata object in this entry
2273
					Set<Identifier> metadataIdentifiers = entries.keySet();
2274
					for(Identifier metadataID: metadataIdentifiers){
2275
						try{
2276
							//Get the system metadata for this metadata object
2277
							SystemMetadata metadataSysMeta = this.getSystemMetadata(session, metadataID);
2278
							
2279
							// include user-friendly metadata
2280
							if (ObjectFormatCache.getInstance().getFormat(metadataSysMeta.getFormatId()).getFormatType().equals("METADATA")) {
2281
								InputStream metadataStream = this.get(session, metadataID);
2282
							
2283
								try {
2284
									// transform
2285
						            String format = "default";
2286

    
2287
									DBTransform transformer = new DBTransform();
2288
						            String documentContent = IOUtils.toString(metadataStream, "UTF-8");
2289
						            String sourceType = metadataSysMeta.getFormatId().getValue();
2290
						            String targetType = "-//W3C//HTML//EN";
2291
						            ByteArrayOutputStream baos = new ByteArrayOutputStream();
2292
						            Writer writer = new OutputStreamWriter(baos , "UTF-8");
2293
						            // TODO: include more params?
2294
						            Hashtable<String, String[]> params = new Hashtable<String, String[]>();
2295
						            String localId = null;
2296
									try {
2297
										localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
2298
									} catch (McdbDocNotFoundException e) {
2299
										throw new NotFound("1020", e.getMessage());
2300
									}
2301
									params.put("qformat", new String[] {format});	            
2302
						            params.put("docid", new String[] {localId});
2303
						            params.put("pid", new String[] {pid.getValue()});
2304
						            params.put("displaymodule", new String[] {"printall"});
2305
						            
2306
						            transformer.transformXMLDocument(
2307
						                    documentContent , 
2308
						                    sourceType, 
2309
						                    targetType , 
2310
						                    format, 
2311
						                    writer, 
2312
						                    params, 
2313
						                    null //sessionid
2314
						                    );
2315
						            
2316
						            // finally, get the HTML back
2317
						            ContentTypeByteArrayInputStream resultInputStream = new ContentTypeByteArrayInputStream(baos.toByteArray());
2318
						            
2319
						            // write to temp file with correct css path
2320
						            File tmpDir = File.createTempFile("package_", "_dir");
2321
						            tmpDir.delete();
2322
						            tmpDir.mkdir();
2323
						            File htmlFile = File.createTempFile("metadata", ".html", tmpDir);
2324
						            File cssDir = new File(tmpDir, format);
2325
						            cssDir.mkdir();
2326
						            File cssFile = new File(tmpDir, format + "/" + format + ".css");
2327
						            String pdfFileName = metadataID.getValue().replaceAll("[^a-zA-Z0-9\\-\\.]", "_") + "-METADATA.pdf";
2328
						            File pdfFile = new File(tmpDir, pdfFileName);
2329
						            //File pdfFile = File.createTempFile("metadata", ".pdf", tmpDir);
2330
						            
2331
						            // put the CSS file in place for the html to find it
2332
						            String originalCssPath = SystemUtil.getContextDir() + "/style/skins/" + format + "/" + format + ".css";
2333
						            IOUtils.copy(new FileInputStream(originalCssPath), new FileOutputStream(cssFile));
2334
						            
2335
						            // write the HTML file
2336
						            IOUtils.copy(resultInputStream, new FileOutputStream(htmlFile));
2337
						            
2338
						            // convert to PDF
2339
						            HtmlToPdf.export(htmlFile.getAbsolutePath(), pdfFile.getAbsolutePath());
2340
						            
2341
						            //add to the package
2342
						            bag.addFileToPayload(pdfFile);
2343
									pidMapping.append(metadataID.getValue() + " (pdf)" +  "\t" + "data/" + pdfFile.getName() + "\n");
2344
						            
2345
						            // mark for clean up after we are done
2346
									htmlFile.delete();
2347
									cssFile.delete();
2348
									cssDir.delete();
2349
						            tempFiles.add(tmpDir);
2350
									tempFiles.add(pdfFile); // delete this first later on
2351
						            
2352
								} catch (Exception e) {
2353
									logMetacat.warn("Could not transform metadata", e);
2354
								}
2355
							}
2356

    
2357
							
2358
							//If this is in eml format, extract the filename and GUID from each entity in its package
2359
							if (metadataSysMeta.getFormatId().getValue().startsWith("eml://")) {
2360
								//Get the package
2361
								DataPackageParserInterface parser = new Eml200DataPackageParser();
2362
								InputStream emlStream = this.get(session, metadataID);
2363
								parser.parse(emlStream);
2364
								DataPackage dataPackage = parser.getDataPackage();
2365
								
2366
								//Get all the entities in this package and loop through each to extract its ID and file name
2367
								Entity[] entities = dataPackage.getEntityList();
2368
								for(Entity entity: entities){
2369
									try{
2370
										//Get the file name from the metadata
2371
										String fileNameFromMetadata = entity.getName();
2372
										
2373
										//Get the ecogrid URL from the metadata
2374
										String ecogridIdentifier = entity.getEntityIdentifier();
2375
										//Parse the ecogrid URL to get the local id
2376
										String idFromMetadata = DocumentUtil.getAccessionNumberFromEcogridIdentifier(ecogridIdentifier);
2377
										
2378
										//Get the docid and rev pair
2379
										String docid = DocumentUtil.getDocIdFromString(idFromMetadata);
2380
										String rev = DocumentUtil.getRevisionStringFromString(idFromMetadata);
2381
										
2382
										//Get the GUID
2383
										String guid = IdentifierManager.getInstance().getGUID(docid, Integer.valueOf(rev));
2384
										Identifier dataIdentifier = new Identifier();
2385
										dataIdentifier.setValue(guid);
2386
										
2387
										//Add the GUID to our GUID & file name map
2388
										fileNames.put(dataIdentifier, fileNameFromMetadata);
2389
									}
2390
									catch(Exception e){
2391
										//Prevent just one entity error
2392
										e.printStackTrace();
2393
										logMetacat.debug(e.getMessage(), e);
2394
									}
2395
								}
2396
							}
2397
						}
2398
						catch(Exception e){
2399
							//Catch errors that would prevent package download
2400
							logMetacat.debug(e.toString());
2401
						}
2402
					}
2403
					packagePids.addAll(entries.keySet());
2404
					for (List<Identifier> dataPids: entries.values()) {
2405
						packagePids.addAll(dataPids);
2406
					}
2407
				}
2408
			} else {
2409
				// just the lone pid in this package
2410
				//packagePids.add(pid);
2411
			    //throw an invalid request exception
2412
			    throw new InvalidRequest("2873", "The given pid "+pid.getValue()+" is not a package id (resource map id). Please use a package id instead.");
2413
			}
2414
			
2415
			//Create a temp file, then delete it and make a directory with that name
2416
			File tempDir = File.createTempFile("temp", Long.toString(System.nanoTime()));
2417
			tempDir.delete();
2418
			tempDir = new File(tempDir.getPath() + "_dir");
2419
			tempDir.mkdir();			
2420
			tempFiles.add(tempDir);
2421
			File pidMappingFile = new File(tempDir, "pid-mapping.txt");
2422
			
2423
			// loop through the package contents
2424
			for (Identifier entryPid: packagePids) {
2425
				//Get the system metadata for each item
2426
				SystemMetadata entrySysMeta = this.getSystemMetadata(session, entryPid);					
2427
				
2428
				String objectFormatType = ObjectFormatCache.getInstance().getFormat(entrySysMeta.getFormatId()).getFormatType();
2429
				String fileName = null;
2430
				
2431
				//TODO: Be more specific of what characters to replace. Make sure periods arent replaced for the filename from metadata
2432
				//Our default file name is just the ID + format type (e.g. walker.1.1-DATA)
2433
				fileName = entryPid.getValue().replaceAll("[^a-zA-Z0-9\\-\\.]", "_") + "-" + objectFormatType;
2434

    
2435
				if (fileNames.containsKey(entryPid)){
2436
					//Let's use the file name and extension from the metadata is we have it
2437
					fileName = entryPid.getValue().replaceAll("[^a-zA-Z0-9\\-\\.]", "_") + "-" + fileNames.get(entryPid).replaceAll("[^a-zA-Z0-9\\-\\.]", "_");
2438
				}
2439
				
2440
				// ensure there is a file extension for the object
2441
				String extension = ObjectFormatInfo.instance().getExtension(entrySysMeta.getFormatId().getValue());
2442
				fileName += extension;
2443
				
2444
				// if SM has the file name, ignore everything else and use that
2445
				if (entrySysMeta.getFileName() != null) {
2446
					fileName = entrySysMeta.getFileName().replaceAll("[^a-zA-Z0-9\\-\\.]", "_");
2447
				}
2448
				
2449
		        //Create a new file for this item and add to the list
2450
				File tempFile = new File(tempDir, fileName);
2451
				tempFiles.add(tempFile);
2452
				
2453
				InputStream entryInputStream = this.get(session, entryPid);			
2454
				IOUtils.copy(entryInputStream, new FileOutputStream(tempFile));
2455
				bag.addFileToPayload(tempFile);
2456
				pidMapping.append(entryPid.getValue() + "\t" + "data/" + tempFile.getName() + "\n");
2457
			}
2458
			
2459
			//add the the pid to data file map
2460
			IOUtils.write(pidMapping.toString(), new FileOutputStream(pidMappingFile));
2461
			bag.addFileAsTag(pidMappingFile);
2462
			tempFiles.add(pidMappingFile);
2463
			
2464
			bag = bag.makeComplete();
2465
			
2466
			///Now create the zip file
2467
			//Use the pid as the file name prefix, replacing all non-word characters
2468
			String zipName = pid.getValue().replaceAll("\\W", "_");
2469
			
2470
			File bagFile = new File(tempDir, zipName+".zip");
2471
			
2472
			bag.setFile(bagFile);
2473
			ZipWriter zipWriter = new ZipWriter(bagFactory);
2474
			bag.write(zipWriter, bagFile);
2475
			bagFile = bag.getFile();
2476
			// use custom FIS that will delete the file when closed
2477
			bagInputStream = new DeleteOnCloseFileInputStream(bagFile);
2478
			// also mark for deletion on shutdown in case the stream is never closed
2479
			bagFile.deleteOnExit();
2480
			tempFiles.add(bagFile);
2481
			
2482
			// clean up other temp files
2483
			for (int i=tempFiles.size()-1; i>=0; i--){
2484
				tempFiles.get(i).delete();
2485
			}
2486
			
2487
		} catch (IOException e) {
2488
			// report as service failure
2489
		    e.printStackTrace();
2490
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2491
			sf.initCause(e);
2492
			throw sf;
2493
		} catch (OREException e) {
2494
			// report as service failure
2495
		    e.printStackTrace();
2496
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2497
			sf.initCause(e);
2498
			throw sf;
2499
		} catch (URISyntaxException e) {
2500
			// report as service failure
2501
		    e.printStackTrace();
2502
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2503
			sf.initCause(e);
2504
			throw sf;
2505
		} catch (OREParserException e) {
2506
			// report as service failure
2507
		    e.printStackTrace();
2508
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2509
			sf.initCause(e);
2510
			throw sf;
2511
		}
2512
		
2513
		return bagInputStream;
2514
	}
2515
	
2516
	 /**
2517
	   * Archives an object, where the object is either a 
2518
	   * data object or a science metadata object.
2519
	   * 
2520
	   * @param session - the Session object containing the credentials for the Subject
2521
	   * @param pid - The object identifier to be archived
2522
	   * 
2523
	   * @return pid - the identifier of the object used for the archiving
2524
	   * 
2525
	   * @throws InvalidToken
2526
	   * @throws ServiceFailure
2527
	   * @throws NotAuthorized
2528
	   * @throws NotFound
2529
	   * @throws NotImplemented
2530
	   * @throws InvalidRequest
2531
	   */
2532
	  public Identifier archive(Session session, Identifier pid) 
2533
	      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
2534
	      if(isReadOnlyMode()) {
2535
	            throw new ServiceFailure("2912", ReadOnlyChecker.DATAONEERROR);
2536
	        }
2537
	      boolean allowed = false;
2538
	      // do we have a valid pid?
2539
	      if (pid == null || pid.getValue().trim().equals("")) {
2540
	          throw new ServiceFailure("1350", "The provided identifier was invalid.");
2541
	      }
2542
	      
2543
	      String serviceFailureCode = "1350";
2544
	      Identifier sid = getPIDForSID(pid, serviceFailureCode);
2545
	      if(sid != null) {
2546
	          pid = sid;
2547
	      }
2548
	      // does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
2549
	      try {
2550
	            allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
2551
	        } catch (InvalidRequest e) {
2552
	          throw new ServiceFailure("1350", e.getDescription());
2553
	        } 
2554

    
2555
	      if (allowed) {
2556
	         try {
2557
	             HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
2558
	             logMetacat.debug("MNodeService.archive - lock the identifier "+pid.getValue()+" in the system metadata map.");
2559
	             SystemMetadata sysmeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
2560
	             boolean needModifyDate = true;
2561
	             boolean logArchive = true;
2562
	             super.archiveObject(logArchive, session, pid, sysmeta, needModifyDate); 
2563
	         } finally {
2564
	             HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
2565
	             logMetacat.debug("MNodeService.archive - unlock the identifier "+pid.getValue()+" in the system metadata map.");
2566
	         }
2567
	        
2568

    
2569
	      } else {
2570
	          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
2571
	      }
2572

    
2573
	      return pid;
2574
	  }
2575
    
2576
	/**
2577
	 * Update the system metadata of the specified pid.
2578
	 */
2579
	@Override
2580
	public boolean updateSystemMetadata(Session session, Identifier pid,
2581
            SystemMetadata sysmeta) throws NotImplemented, NotAuthorized,
2582
            ServiceFailure, InvalidRequest, InvalidSystemMetadata, InvalidToken {
2583
	  
2584
	  if(isReadOnlyMode()) {
2585
            throw new ServiceFailure("4868",  ReadOnlyChecker.DATAONEERROR);
2586
      }
2587
	 if(sysmeta == null) {
2588
	     throw  new InvalidRequest("4869", "The system metadata object should NOT be null in the updateSystemMetadata request.");
2589
	 }
2590
	 if(pid == null || pid.getValue() == null) {
2591
         throw new InvalidRequest("4869", "Please specify the id in the updateSystemMetadata request ") ;
2592
     }
2593

    
2594
     if (session == null) {
2595
         //TODO: many of the thrown exceptions do not use the correct error codes
2596
         //check these against the docs and correct them
2597
         throw new NotAuthorized("4861", "No Session - could not authorize for updating system metadata." +
2598
                 "  If you are not logged in, please do so and retry the request.");
2599
     } else {
2600
         try {
2601
             //Following session can do the change:
2602
           //- Authoritative Member Node (we can use isNodeAdmin since we checked isAuthoritativeNode )
2603
             //- Owner of object (coved by the userHasPermission method)
2604
             //- user subjects with the change permission
2605
             //Note: Coordinating Node can not because MN is authoritative
2606
             /*if(!isAuthoritativeNode(pid)) {
2607
                throw  new InvalidRequest("4863", "Client can only call updateSystemMetadata request on the authoritative memember node.");
2608
             }
2609
             if(!isNodeAdmin(session) && !userHasPermission(session, pid, Permission.CHANGE_PERMISSION)) {
2610
                 throw new NotAuthorized("4861", "The client -"+ session.getSubject().getValue()+ "is not authorized for updating the system metadata of the object "+pid.getValue());
2611
             }*/
2612
             if(!allowUpdating(session, pid, Permission.CHANGE_PERMISSION)) {
2613
                 throw new NotAuthorized("4861", "The client -"+ session.getSubject().getValue()+ "is not authorized for updating the system metadata of the object "+pid.getValue());
2614
             }
2615
         } catch (NotFound e) {
2616
             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());
2617
         } catch(ServiceFailure e) {
2618
             throw new ServiceFailure("4868", "Can't determine if the client has the permission to update the system metacat of the object with id "+pid.getValue()+" since "+e.getDescription());
2619
         } catch(NotAuthorized e) {
2620
             throw new NotAuthorized("4861", "Can't determine if the client has the permission to update the system metacat of the object with id "+pid.getValue()+" since "+e.getDescription());
2621
         } catch(NotImplemented e) {
2622
             throw new NotImplemented("4866","Can't determine if the client has the permission to update the system metacat of the object with id "+pid.getValue()+" since "+e.getDescription());
2623
         } catch(InvalidRequest e) {
2624
             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());
2625
         } catch(InvalidToken e) {
2626
             throw new InvalidToken("4957", "Can't determine if the client has the permission to update the system metacat of the object with id "+pid.getValue()+" since "+e.getDescription());
2627
         }
2628
         
2629
     }
2630
      //update the system metadata locally
2631
      boolean success = false;
2632
      try {
2633
          HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
2634
          SystemMetadata currentSysmeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
2635
          if(currentSysmeta == null) {
2636
              throw  new InvalidRequest("4869", "We can't find the current system metadata on the member node for the id "+pid.getValue());
2637
          }
2638
          Date currentModiDate = currentSysmeta.getDateSysMetadataModified();
2639
          Date commingModiDate = sysmeta.getDateSysMetadataModified();
2640
          if(commingModiDate == null) {
2641
              throw  new InvalidRequest("4869", "The system metadata modification date can't be null.");
2642
          }
2643
          if(currentModiDate != null && commingModiDate.getTime() != currentModiDate.getTime()) {
2644
              throw new InvalidRequest("4869", "Your system metadata modification date is "+commingModiDate.toString()+
2645
                      ". It doesn't match our current system metadata modification date in the member node - "+currentModiDate.toString()+
2646
                      ". Please check if you have got the newest version of the system metadata before the modification.");
2647
          }
2648
          boolean needUpdateModificationDate = true;
2649
          boolean fromCN = false;
2650
          success = updateSystemMetadata(session, pid, sysmeta, needUpdateModificationDate, currentSysmeta, fromCN);
2651
      } finally {
2652
          HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
2653
      }
2654
      
2655
      if(success) {
2656
          this.cn = D1Client.getCN();
2657
          //TODO
2658
          //notify the cns the synchornize the new system metadata.
2659
          // run it in a thread to avoid connection timeout
2660
          Runnable runner = new Runnable() {
2661
              private CNode cNode = null;
2662
              private SystemMetadata sys = null;
2663
              private Identifier id = null;
2664
              @Override
2665
              public void run() {
2666
                  try {
2667
                      if(this.cNode == null)  {
2668
                          logMetacat.warn("MNodeService.updateSystemMetadata - can't get the instance of the CN. So can't call cn.synchronize to update the system metadata in CN.");
2669
                      } else if(id != null) {
2670
                          logMetacat.info("MNodeService.updateSystemMetadata - calling cn.synchornized in another thread for pid "+id.getValue());
2671
                          this.cNode.synchronize(null, id);
2672
                      } else {
2673
                          logMetacat.warn("MNodeService.updateSystemMetadata - the pid is null. So can't call cn.synchronize to update the system metadata in CN.");
2674
                      }
2675
                  } catch (BaseException e) {
2676
                      e.printStackTrace();
2677
                      logMetacat.error("It is a DataONEBaseException and its detail code is "+e.getDetail_code() +" and its code is "+e.getCode());
2678
                      logMetacat.error("Can't update the systemmetadata of pid "+id.getValue()+" in CNs through cn.synchronize method since "+e.getMessage(), e);
2679
                  } catch (Exception e) {
2680
                      e.printStackTrace();
2681
                      logMetacat.error("Can't update the systemmetadata of pid "+id.getValue()+" in CNs through cn.synchronize method since "+e.getMessage(), e);
2682
                  }
2683
                  
2684
                  // attempt to re-register the identifier (it checks if it is a doi)
2685
                  try {
2686
                      logMetacat.info("MNodeSerice.updateSystemMetadata - register doi if the pid "+sys.getIdentifier().getValue()+" is a doi");
2687
                      DOIService.getInstance().registerDOI(sys);
2688
                  } catch (Exception e) {
2689
                    logMetacat.warn("Could not [re]register DOI: " + e.getMessage(), e);
2690
                  }
2691
              }
2692
              private Runnable init(CNode cn, SystemMetadata sys, Identifier id){
2693
                  this.cNode = cn;
2694
                  this.sys = sys;
2695
                  this.id = id;
2696
                  return this;
2697
                 
2698
              }
2699
          }.init(cn, sysmeta, pid);
2700
          // submit the task, and that's it
2701
          if(executor != null) {
2702
              executor.submit(runner);
2703
          } else {
2704
              logMetacat.warn("MNodeSerivce.updateSystemMetadata - since the executor service for submitting the call of cn.synchronize() is null, the system metadata change of the id "+pid.getValue()+" can't go to cn through cn.synchronize.");
2705
          }
2706
      }
2707
      return success;
2708
    }
2709
	
2710
	/*
2711
     * Determine if the current node is the authoritative node for the given pid.
2712
     */
2713
    protected boolean isAuthoritativeNode(Identifier pid) throws InvalidRequest {
2714
        boolean isAuthoritativeNode = false;
2715
        if(pid != null && pid.getValue() != null) {
2716
            SystemMetadata sys = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
2717
            if(sys != null) {
2718
                NodeReference node = sys.getAuthoritativeMemberNode();
2719
                if(node != null) {
2720
                    String nodeValue = node.getValue();
2721
                    logMetacat.debug("The authoritative node for id "+pid.getValue()+" is "+nodeValue);
2722
                    //System.out.println("The authoritative node for id "+pid.getValue()+" is "+nodeValue);
2723
                    String currentNodeId = Settings.getConfiguration().getString("dataone.nodeId");
2724
                    logMetacat.debug("The node id in metacat.properties is "+currentNodeId);
2725
                    //System.out.println("The node id in metacat.properties is "+currentNodeId);
2726
                    if(currentNodeId != null && !currentNodeId.trim().equals("") && currentNodeId.equals(nodeValue)) {
2727
                        logMetacat.debug("They are matching, so the authoritative mn of the object "+pid.getValue()+" is the current node");
2728
                        //System.out.println("They are matching");
2729
                        isAuthoritativeNode = true;
2730
                    }
2731
                } else {
2732
                    throw new InvalidRequest("4869", "Coudn't find the authoritative member node in the system metadata associated with the pid "+pid.getValue());
2733
                }
2734
            } else {
2735
                throw new InvalidRequest("4869", "Coudn't find the system metadata associated with the pid "+pid.getValue());
2736
            }
2737
        } else {
2738
            throw new InvalidRequest("4869", "The request pid is null");
2739
        }
2740
        return isAuthoritativeNode;
2741
    }
2742
    
2743
    /*
2744
     * Rules are:
2745
     * 1. If the session has an cn object, it is allowed.
2746
     * 2. If it is not a cn object, the client should have approperate permission and it should also happen on the authorative node.
2747
     * 3. If it's the authoritative node, the MN Admin Subject is allowed.
2748
     */
2749
    private boolean allowUpdating(Session session, Identifier pid, Permission permission) throws NotAuthorized, NotFound, InvalidRequest, ServiceFailure, NotImplemented, InvalidToken {
2750
        boolean allow = false;
2751
        
2752
        if( isCNAdmin (session) ) {
2753
            allow = true;
2754
            
2755
        } else {
2756
            if( isAuthoritativeNode(pid) ) {
2757
            	
2758
            	// Check for admin authorization
2759
            	try {
2760
					allow = isNodeAdmin(session);
2761
					
2762
				} catch (NotImplemented e) {
2763
					logMetacat.debug("Failed to authorize the Member Node Admin Subject: " + e.getMessage());
2764

    
2765
				} catch (ServiceFailure e) {
2766
					logMetacat.debug("Failed to authorize the Member Node Admin Subject: " + e.getMessage());
2767
					
2768
				}
2769
            	
2770
            	// Check for user authorization
2771
            	if ( !allow ) {
2772
                    allow = userHasPermission(session, pid, permission);
2773
                    
2774
            	}
2775
                    
2776
            } else {
2777
                throw new NotAuthorized("4861", "Client can only call the request on the authoritative memember node of the object "+pid.getValue());
2778
                
2779
            }
2780
        }
2781
        return allow;
2782
        
2783
    }
2784
    
2785
    /**
2786
     * Check if the metacat is in the read-only mode.
2787
     * @return true if it is; otherwise false.
2788
     */
2789
    protected boolean isReadOnlyMode() {
2790
        boolean readOnly = false;
2791
        ReadOnlyChecker checker = new ReadOnlyChecker();
2792
        readOnly = checker.isReadOnly();
2793
        return readOnly;
2794
    }
2795
    
2796
}
(5-5/8)