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.UnsupportedEncodingException;
|
36
|
import java.io.Writer;
|
37
|
import java.math.BigInteger;
|
38
|
import java.net.URISyntaxException;
|
39
|
import java.security.NoSuchAlgorithmException;
|
40
|
import java.sql.SQLException;
|
41
|
import java.util.ArrayList;
|
42
|
import java.util.Calendar;
|
43
|
import java.util.Date;
|
44
|
import java.util.HashMap;
|
45
|
import java.util.HashSet;
|
46
|
import java.util.Hashtable;
|
47
|
import java.util.List;
|
48
|
import java.util.Map;
|
49
|
import java.util.Set;
|
50
|
import java.util.Timer;
|
51
|
import java.util.UUID;
|
52
|
import java.util.Vector;
|
53
|
|
54
|
import javax.servlet.http.HttpServletRequest;
|
55
|
|
56
|
import org.apache.commons.io.IOUtils;
|
57
|
import org.apache.log4j.Logger;
|
58
|
import org.dataone.client.v2.CNode;
|
59
|
import org.dataone.client.v2.itk.D1Client;
|
60
|
import org.dataone.client.v2.MNode;
|
61
|
import org.dataone.client.v2.formats.ObjectFormatCache;
|
62
|
import org.dataone.client.auth.CertificateManager;
|
63
|
import org.dataone.client.v2.formats.ObjectFormatInfo;
|
64
|
import org.dataone.configuration.Settings;
|
65
|
import org.dataone.ore.ResourceMapFactory;
|
66
|
import org.dataone.service.exceptions.BaseException;
|
67
|
import org.dataone.service.exceptions.IdentifierNotUnique;
|
68
|
import org.dataone.service.exceptions.InsufficientResources;
|
69
|
import org.dataone.service.exceptions.InvalidRequest;
|
70
|
import org.dataone.service.exceptions.InvalidSystemMetadata;
|
71
|
import org.dataone.service.exceptions.InvalidToken;
|
72
|
import org.dataone.service.exceptions.NotAuthorized;
|
73
|
import org.dataone.service.exceptions.NotFound;
|
74
|
import org.dataone.service.exceptions.NotImplemented;
|
75
|
import org.dataone.service.exceptions.ServiceFailure;
|
76
|
import org.dataone.service.exceptions.SynchronizationFailed;
|
77
|
import org.dataone.service.exceptions.UnsupportedType;
|
78
|
import org.dataone.service.mn.tier1.v2.MNCore;
|
79
|
import org.dataone.service.mn.tier1.v2.MNRead;
|
80
|
import org.dataone.service.mn.tier2.v2.MNAuthorization;
|
81
|
import org.dataone.service.mn.tier3.v2.MNStorage;
|
82
|
import org.dataone.service.mn.tier4.v2.MNReplication;
|
83
|
import org.dataone.service.mn.v2.MNPackage;
|
84
|
import org.dataone.service.mn.v2.MNQuery;
|
85
|
import org.dataone.service.mn.v2.MNView;
|
86
|
import org.dataone.service.types.v1.AccessRule;
|
87
|
import org.dataone.service.types.v1.Checksum;
|
88
|
import org.dataone.service.types.v1.DescribeResponse;
|
89
|
import org.dataone.service.types.v1.Event;
|
90
|
import org.dataone.service.types.v1.Identifier;
|
91
|
import org.dataone.service.types.v2.Log;
|
92
|
import org.dataone.service.types.v2.LogEntry;
|
93
|
import org.dataone.service.types.v2.OptionList;
|
94
|
import org.dataone.service.types.v1.MonitorInfo;
|
95
|
import org.dataone.service.types.v1.MonitorList;
|
96
|
import org.dataone.service.types.v2.Node;
|
97
|
import org.dataone.service.types.v2.NodeList;
|
98
|
import org.dataone.service.types.v1.NodeReference;
|
99
|
import org.dataone.service.types.v1.NodeState;
|
100
|
import org.dataone.service.types.v1.NodeType;
|
101
|
import org.dataone.service.types.v2.ObjectFormat;
|
102
|
import org.dataone.service.types.v1.ObjectFormatIdentifier;
|
103
|
import org.dataone.service.types.v1.ObjectList;
|
104
|
import org.dataone.service.types.v1.Permission;
|
105
|
import org.dataone.service.types.v1.Ping;
|
106
|
import org.dataone.service.types.v1.ReplicationStatus;
|
107
|
import org.dataone.service.types.v1.Schedule;
|
108
|
import org.dataone.service.types.v1.Service;
|
109
|
import org.dataone.service.types.v1.Services;
|
110
|
import org.dataone.service.types.v1.Session;
|
111
|
import org.dataone.service.types.v1.Subject;
|
112
|
import org.dataone.service.types.v1.Synchronization;
|
113
|
import org.dataone.service.types.v2.SystemMetadata;
|
114
|
import org.dataone.service.types.v1.util.AuthUtils;
|
115
|
import org.dataone.service.types.v1.util.ChecksumUtil;
|
116
|
import org.dataone.service.types.v1_1.QueryEngineDescription;
|
117
|
import org.dataone.service.types.v1_1.QueryEngineList;
|
118
|
import org.dataone.service.types.v1_1.QueryField;
|
119
|
import org.dataone.service.util.Constants;
|
120
|
import org.dataone.service.util.TypeMarshaller;
|
121
|
import org.dspace.foresite.OREException;
|
122
|
import org.dspace.foresite.OREParserException;
|
123
|
import org.dspace.foresite.ORESerialiserException;
|
124
|
import org.dspace.foresite.ResourceMap;
|
125
|
import org.ecoinformatics.datamanager.parser.DataPackage;
|
126
|
import org.ecoinformatics.datamanager.parser.Entity;
|
127
|
import org.ecoinformatics.datamanager.parser.generic.DataPackageParserInterface;
|
128
|
import org.ecoinformatics.datamanager.parser.generic.Eml200DataPackageParser;
|
129
|
|
130
|
import edu.ucsb.nceas.ezid.EZIDException;
|
131
|
import edu.ucsb.nceas.metacat.DBQuery;
|
132
|
import edu.ucsb.nceas.metacat.DBTransform;
|
133
|
import edu.ucsb.nceas.metacat.EventLog;
|
134
|
import edu.ucsb.nceas.metacat.IdentifierManager;
|
135
|
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
|
136
|
import edu.ucsb.nceas.metacat.MetaCatServlet;
|
137
|
import edu.ucsb.nceas.metacat.MetacatHandler;
|
138
|
import edu.ucsb.nceas.metacat.common.query.EnabledQueryEngines;
|
139
|
import edu.ucsb.nceas.metacat.common.query.stream.ContentTypeByteArrayInputStream;
|
140
|
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
|
141
|
import edu.ucsb.nceas.metacat.index.MetacatSolrEngineDescriptionHandler;
|
142
|
import edu.ucsb.nceas.metacat.index.MetacatSolrIndex;
|
143
|
import edu.ucsb.nceas.metacat.properties.PropertyService;
|
144
|
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
|
145
|
import edu.ucsb.nceas.metacat.util.DeleteOnCloseFileInputStream;
|
146
|
import edu.ucsb.nceas.metacat.util.DocumentUtil;
|
147
|
import edu.ucsb.nceas.metacat.util.SkinUtil;
|
148
|
import edu.ucsb.nceas.metacat.util.SystemUtil;
|
149
|
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
|
150
|
import edu.ucsb.nceas.utilities.XMLUtilities;
|
151
|
import edu.ucsb.nceas.utilities.export.HtmlToPdf;
|
152
|
import gov.loc.repository.bagit.Bag;
|
153
|
import gov.loc.repository.bagit.BagFactory;
|
154
|
import gov.loc.repository.bagit.writer.impl.ZipWriter;
|
155
|
|
156
|
/**
|
157
|
* Represents Metacat's implementation of the DataONE Member Node
|
158
|
* service API. Methods implement the various MN* interfaces, and methods common
|
159
|
* to both Member Node and Coordinating Node interfaces are found in the
|
160
|
* D1NodeService base class.
|
161
|
*
|
162
|
* Implements:
|
163
|
* MNCore.ping()
|
164
|
* MNCore.getLogRecords()
|
165
|
* MNCore.getObjectStatistics()
|
166
|
* MNCore.getOperationStatistics()
|
167
|
* MNCore.getStatus()
|
168
|
* MNCore.getCapabilities()
|
169
|
* MNRead.get()
|
170
|
* MNRead.getSystemMetadata()
|
171
|
* MNRead.describe()
|
172
|
* MNRead.getChecksum()
|
173
|
* MNRead.listObjects()
|
174
|
* MNRead.synchronizationFailed()
|
175
|
* MNAuthorization.isAuthorized()
|
176
|
* MNAuthorization.setAccessPolicy()
|
177
|
* MNStorage.create()
|
178
|
* MNStorage.update()
|
179
|
* MNStorage.delete()
|
180
|
* MNStorage.updateSystemMetadata()
|
181
|
* MNReplication.replicate()
|
182
|
*
|
183
|
*/
|
184
|
public class MNodeService extends D1NodeService
|
185
|
implements MNAuthorization, MNCore, MNRead, MNReplication, MNStorage, MNQuery, MNView, MNPackage {
|
186
|
|
187
|
//private static final String PATHQUERY = "pathquery";
|
188
|
public static final String UUID_SCHEME = "UUID";
|
189
|
public static final String DOI_SCHEME = "DOI";
|
190
|
private static final String UUID_PREFIX = "urn:uuid:";
|
191
|
|
192
|
/* the logger instance */
|
193
|
private Logger logMetacat = null;
|
194
|
|
195
|
/* A reference to a remote Memeber Node */
|
196
|
private MNode mn;
|
197
|
|
198
|
/* A reference to a Coordinating Node */
|
199
|
private CNode cn;
|
200
|
|
201
|
|
202
|
/**
|
203
|
* Singleton accessor to get an instance of MNodeService.
|
204
|
*
|
205
|
* @return instance - the instance of MNodeService
|
206
|
*/
|
207
|
public static MNodeService getInstance(HttpServletRequest request) {
|
208
|
return new MNodeService(request);
|
209
|
}
|
210
|
|
211
|
/**
|
212
|
* Constructor, private for singleton access
|
213
|
*/
|
214
|
private MNodeService(HttpServletRequest request) {
|
215
|
super(request);
|
216
|
logMetacat = Logger.getLogger(MNodeService.class);
|
217
|
|
218
|
// set the Member Node certificate file location
|
219
|
CertificateManager.getInstance().setCertificateLocation(Settings.getConfiguration().getString("D1Client.certificate.file"));
|
220
|
}
|
221
|
|
222
|
/**
|
223
|
* Deletes an object from the Member Node, where the object is either a
|
224
|
* data object or a science metadata object.
|
225
|
*
|
226
|
* @param session - the Session object containing the credentials for the Subject
|
227
|
* @param pid - The object identifier to be deleted
|
228
|
*
|
229
|
* @return pid - the identifier of the object used for the deletion
|
230
|
*
|
231
|
* @throws InvalidToken
|
232
|
* @throws ServiceFailure
|
233
|
* @throws NotAuthorized
|
234
|
* @throws NotFound
|
235
|
* @throws NotImplemented
|
236
|
* @throws InvalidRequest
|
237
|
*/
|
238
|
@Override
|
239
|
public Identifier delete(Session session, Identifier pid)
|
240
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
|
241
|
|
242
|
// only admin of the MN or the CN is allowed a full delete
|
243
|
boolean allowed = false;
|
244
|
allowed = isAdminAuthorized(session);
|
245
|
|
246
|
String serviceFailureCode = "2902";
|
247
|
Identifier sid = getPIDForSID(pid, serviceFailureCode);
|
248
|
if(sid != null) {
|
249
|
pid = sid;
|
250
|
}
|
251
|
|
252
|
//check if it is the authoritative member node
|
253
|
if(!allowed) {
|
254
|
allowed = isAuthoritativeMNodeAdmin(session, pid);
|
255
|
}
|
256
|
|
257
|
if (!allowed) {
|
258
|
throw new NotAuthorized("1320", "The provided identity does not have " + "permission to delete objects on the Node.");
|
259
|
}
|
260
|
|
261
|
// defer to superclass implementation
|
262
|
return super.delete(session, pid);
|
263
|
}
|
264
|
|
265
|
/**
|
266
|
* Updates an existing object by creating a new object identified by
|
267
|
* newPid on the Member Node which explicitly obsoletes the object
|
268
|
* identified by pid through appropriate changes to the SystemMetadata
|
269
|
* of pid and newPid
|
270
|
*
|
271
|
* @param session - the Session object containing the credentials for the Subject
|
272
|
* @param pid - The identifier of the object to be updated
|
273
|
* @param object - the new object bytes
|
274
|
* @param sysmeta - the new system metadata describing the object
|
275
|
*
|
276
|
* @return newPid - the identifier of the new object
|
277
|
*
|
278
|
* @throws InvalidToken
|
279
|
* @throws ServiceFailure
|
280
|
* @throws NotAuthorized
|
281
|
* @throws NotFound
|
282
|
* @throws NotImplemented
|
283
|
* @throws IdentifierNotUnique
|
284
|
* @throws UnsupportedType
|
285
|
* @throws InsufficientResources
|
286
|
* @throws InvalidSystemMetadata
|
287
|
* @throws InvalidRequest
|
288
|
*/
|
289
|
@Override
|
290
|
public Identifier update(Session session, Identifier pid, InputStream object,
|
291
|
Identifier newPid, SystemMetadata sysmeta)
|
292
|
throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique,
|
293
|
UnsupportedType, InsufficientResources, NotFound,
|
294
|
InvalidSystemMetadata, NotImplemented, InvalidRequest {
|
295
|
|
296
|
//transform a sid to a pid if it is applicable
|
297
|
String serviceFailureCode = "1310";
|
298
|
Identifier sid = getPIDForSID(pid, serviceFailureCode);
|
299
|
if(sid != null) {
|
300
|
pid = sid;
|
301
|
}
|
302
|
|
303
|
String localId = null;
|
304
|
boolean allowed = false;
|
305
|
boolean isScienceMetadata = false;
|
306
|
|
307
|
if (session == null) {
|
308
|
throw new InvalidToken("1210", "No session has been provided");
|
309
|
}
|
310
|
Subject subject = session.getSubject();
|
311
|
|
312
|
// verify the pid is valid format
|
313
|
if (!isValidIdentifier(pid)) {
|
314
|
throw new InvalidRequest("1202", "The provided identifier is invalid.");
|
315
|
}
|
316
|
|
317
|
// verify the new pid is valid format
|
318
|
if (!isValidIdentifier(newPid)) {
|
319
|
throw new InvalidRequest("1202", "The provided identifier is invalid.");
|
320
|
}
|
321
|
|
322
|
// make sure that the newPid doesn't exists
|
323
|
boolean idExists = true;
|
324
|
try {
|
325
|
idExists = IdentifierManager.getInstance().identifierExists(newPid.getValue());
|
326
|
} catch (SQLException e) {
|
327
|
throw new ServiceFailure("1310",
|
328
|
"The requested identifier " + newPid.getValue() +
|
329
|
" couldn't be determined if it is unique since : "+e.getMessage());
|
330
|
}
|
331
|
if (idExists) {
|
332
|
throw new IdentifierNotUnique("1220",
|
333
|
"The requested identifier " + newPid.getValue() +
|
334
|
" is already used by another object and" +
|
335
|
"therefore can not be used for this object. Clients should choose" +
|
336
|
"a new identifier that is unique and retry the operation or " +
|
337
|
"use CN.reserveIdentifier() to reserve one.");
|
338
|
|
339
|
}
|
340
|
|
341
|
|
342
|
|
343
|
// check for the existing identifier
|
344
|
try {
|
345
|
localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
|
346
|
|
347
|
} catch (McdbDocNotFoundException e) {
|
348
|
throw new InvalidRequest("1202", "The object with the provided " +
|
349
|
"identifier was not found.");
|
350
|
|
351
|
} catch (SQLException ee) {
|
352
|
throw new ServiceFailure("1310", "The object with the provided " +
|
353
|
"identifier "+pid.getValue()+" can't be identified since - "+ee.getMessage());
|
354
|
}
|
355
|
|
356
|
// set the originating node
|
357
|
NodeReference originMemberNode = this.getCapabilities().getIdentifier();
|
358
|
sysmeta.setOriginMemberNode(originMemberNode);
|
359
|
|
360
|
// set the submitter to match the certificate
|
361
|
sysmeta.setSubmitter(subject);
|
362
|
// set the dates
|
363
|
Date now = Calendar.getInstance().getTime();
|
364
|
sysmeta.setDateSysMetadataModified(now);
|
365
|
sysmeta.setDateUploaded(now);
|
366
|
|
367
|
// make sure serial version is set to something
|
368
|
BigInteger serialVersion = sysmeta.getSerialVersion();
|
369
|
if (serialVersion == null) {
|
370
|
sysmeta.setSerialVersion(BigInteger.ZERO);
|
371
|
}
|
372
|
|
373
|
// does the subject have WRITE ( == update) priveleges on the pid?
|
374
|
//allowed = isAuthorized(session, pid, Permission.WRITE);
|
375
|
//CN having the permission is allowed; user with the write permission and calling on the authoritative node is allowed.
|
376
|
allowed = allowUpdating(session, pid, Permission.WRITE);
|
377
|
if (allowed) {
|
378
|
|
379
|
// check quality of SM
|
380
|
if (sysmeta.getObsoletedBy() != null) {
|
381
|
throw new InvalidSystemMetadata("1300", "Cannot include obsoletedBy when updating object");
|
382
|
}
|
383
|
if (sysmeta.getObsoletes() != null && !sysmeta.getObsoletes().getValue().equals(pid.getValue())) {
|
384
|
throw new InvalidSystemMetadata("1300", "The identifier provided in obsoletes does not match old Identifier");
|
385
|
}
|
386
|
|
387
|
// get the existing system metadata for the object
|
388
|
SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
|
389
|
//System.out.println("the archive is "+existingSysMeta.getArchived());
|
390
|
//Base on documentation, we can't update an archived object:
|
391
|
//The update operation MUST fail with Exceptions.InvalidRequest on objects that have the Types.SystemMetadata.archived property set to true.
|
392
|
if(existingSysMeta.getArchived() != null && existingSysMeta.getArchived()) {
|
393
|
throw new InvalidRequest("1202","An archived object"+pid.getValue()+" can't be updated");
|
394
|
}
|
395
|
|
396
|
// check for previous update
|
397
|
// see: https://redmine.dataone.org/issues/3336
|
398
|
Identifier existingObsoletedBy = existingSysMeta.getObsoletedBy();
|
399
|
if (existingObsoletedBy != null) {
|
400
|
throw new InvalidRequest("1202",
|
401
|
"The previous identifier has already been made obsolete by: " + existingObsoletedBy.getValue());
|
402
|
}
|
403
|
//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.
|
404
|
Identifier sidInSys = sysmeta.getSeriesId();
|
405
|
if(sidInSys != null) {
|
406
|
if (!isValidIdentifier(sidInSys)) {
|
407
|
throw new InvalidSystemMetadata("1300", "The provided series id in the system metadata is invalid.");
|
408
|
}
|
409
|
Identifier previousSid = existingSysMeta.getSeriesId();
|
410
|
if(previousSid != null) {
|
411
|
// there is a previous sid, if the new sid doesn't match it, the new sid should be non-existing.
|
412
|
if(!sidInSys.getValue().equals(previousSid.getValue())) {
|
413
|
try {
|
414
|
idExists = IdentifierManager.getInstance().identifierExists(sidInSys.getValue());
|
415
|
} catch (SQLException e) {
|
416
|
throw new ServiceFailure("1310",
|
417
|
"The requested identifier " + sidInSys.getValue() +
|
418
|
" couldn't be determined if it is unique since : "+e.getMessage());
|
419
|
}
|
420
|
if(idExists) {
|
421
|
throw new InvalidSystemMetadata("1300", "The series id "+sidInSys.getValue()+" in the system metadata doesn't match the previous series id "
|
422
|
+previousSid.getValue()+", so it should NOT exist. However, it was used by another object.");
|
423
|
}
|
424
|
}
|
425
|
} else {
|
426
|
// there is no previous sid, the new sid should be non-existing.
|
427
|
try {
|
428
|
idExists = IdentifierManager.getInstance().identifierExists(sidInSys.getValue());
|
429
|
} catch (SQLException e) {
|
430
|
throw new ServiceFailure("1310",
|
431
|
"The requested identifier " + sidInSys.getValue() +
|
432
|
" couldn't be determined if it is unique since : "+e.getMessage());
|
433
|
}
|
434
|
if(idExists) {
|
435
|
throw new InvalidSystemMetadata("1300", "The series id "+sidInSys.getValue()+" in the system metadata should NOT exist since the previous series id is null."
|
436
|
+"However, it was used by another object.");
|
437
|
}
|
438
|
}
|
439
|
//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)
|
440
|
if(sidInSys.getValue().equals(newPid.getValue())) {
|
441
|
throw new InvalidSystemMetadata("1300", "The series id "+sidInSys.getValue()+" in the system metadata shouldn't have the same value of the pid.");
|
442
|
}
|
443
|
}
|
444
|
|
445
|
isScienceMetadata = isScienceMetadata(sysmeta);
|
446
|
|
447
|
// do we have XML metadata or a data object?
|
448
|
if (isScienceMetadata) {
|
449
|
|
450
|
// update the science metadata XML document
|
451
|
// TODO: handle non-XML metadata/data documents (like netCDF)
|
452
|
// TODO: don't put objects into memory using stream to string
|
453
|
//String objectAsXML = "";
|
454
|
try {
|
455
|
//objectAsXML = IOUtils.toString(object, "UTF-8");
|
456
|
// give the old pid so we can calculate the new local id
|
457
|
localId = insertOrUpdateDocument(object, "UTF-8", pid, session, "update");
|
458
|
// register the newPid and the generated localId
|
459
|
if (newPid != null) {
|
460
|
IdentifierManager.getInstance().createMapping(newPid.getValue(), localId);
|
461
|
|
462
|
}
|
463
|
|
464
|
} catch (IOException e) {
|
465
|
String msg = "The Node is unable to create the object. " + "There was a problem converting the object to XML";
|
466
|
logMetacat.info(msg);
|
467
|
throw new ServiceFailure("1310", msg + ": " + e.getMessage());
|
468
|
|
469
|
}
|
470
|
|
471
|
} else {
|
472
|
|
473
|
// update the data object
|
474
|
localId = insertDataObject(object, newPid, session);
|
475
|
|
476
|
}
|
477
|
|
478
|
// add the newPid to the obsoletedBy list for the existing sysmeta
|
479
|
existingSysMeta.setObsoletedBy(newPid);
|
480
|
|
481
|
// then update the existing system metadata
|
482
|
updateSystemMetadata(existingSysMeta);
|
483
|
|
484
|
// prep the new system metadata, add pid to the affected lists
|
485
|
sysmeta.setObsoletes(pid);
|
486
|
//sysmeta.addDerivedFrom(pid);
|
487
|
|
488
|
// and insert the new system metadata
|
489
|
insertSystemMetadata(sysmeta);
|
490
|
|
491
|
// log the update event
|
492
|
EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), subject.getValue(), localId, Event.UPDATE.toString());
|
493
|
|
494
|
// attempt to register the identifier - it checks if it is a doi
|
495
|
try {
|
496
|
DOIService.getInstance().registerDOI(sysmeta);
|
497
|
} catch (Exception e) {
|
498
|
throw new ServiceFailure("1190", "Could not register DOI: " + e.getMessage());
|
499
|
}
|
500
|
|
501
|
} else {
|
502
|
throw new NotAuthorized("1200", "The provided identity does not have " + "permission to UPDATE the object identified by " + pid.getValue()
|
503
|
+ " on the Member Node.");
|
504
|
}
|
505
|
|
506
|
return newPid;
|
507
|
}
|
508
|
|
509
|
public Identifier create(Session session, Identifier pid, InputStream object, SystemMetadata sysmeta) throws InvalidToken, ServiceFailure, NotAuthorized,
|
510
|
IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, InvalidRequest {
|
511
|
|
512
|
// check for null session
|
513
|
if (session == null) {
|
514
|
throw new InvalidToken("1110", "Session is required to WRITE to the Node.");
|
515
|
}
|
516
|
// verify the pid is valid format
|
517
|
if (!isValidIdentifier(pid)) {
|
518
|
throw new InvalidRequest("1102", "The provided identifier is invalid.");
|
519
|
}
|
520
|
// set the submitter to match the certificate
|
521
|
sysmeta.setSubmitter(session.getSubject());
|
522
|
// set the originating node
|
523
|
NodeReference originMemberNode = this.getCapabilities().getIdentifier();
|
524
|
sysmeta.setOriginMemberNode(originMemberNode);
|
525
|
sysmeta.setArchived(false);
|
526
|
|
527
|
// set the dates
|
528
|
Date now = Calendar.getInstance().getTime();
|
529
|
sysmeta.setDateSysMetadataModified(now);
|
530
|
sysmeta.setDateUploaded(now);
|
531
|
|
532
|
// set the serial version
|
533
|
sysmeta.setSerialVersion(BigInteger.ZERO);
|
534
|
|
535
|
// check that we are not attempting to subvert versioning
|
536
|
if (sysmeta.getObsoletes() != null && sysmeta.getObsoletes().getValue() != null) {
|
537
|
throw new InvalidSystemMetadata("1180",
|
538
|
"The supplied system metadata is invalid. " +
|
539
|
"The obsoletes field cannot have a value when creating entries.");
|
540
|
}
|
541
|
|
542
|
if (sysmeta.getObsoletedBy() != null && sysmeta.getObsoletedBy().getValue() != null) {
|
543
|
throw new InvalidSystemMetadata("1180",
|
544
|
"The supplied system metadata is invalid. " +
|
545
|
"The obsoletedBy field cannot have a value when creating entries.");
|
546
|
}
|
547
|
|
548
|
// verify the sid in the system metadata
|
549
|
Identifier sid = sysmeta.getSeriesId();
|
550
|
boolean idExists = false;
|
551
|
if(sid != null) {
|
552
|
if (!isValidIdentifier(sid)) {
|
553
|
throw new InvalidSystemMetadata("1180", "The provided series id is invalid.");
|
554
|
}
|
555
|
try {
|
556
|
idExists = IdentifierManager.getInstance().identifierExists(sid.getValue());
|
557
|
} catch (SQLException e) {
|
558
|
throw new ServiceFailure("1190",
|
559
|
"The series identifier " + sid.getValue() +
|
560
|
" in the system metadata couldn't be determined if it is unique since : "+e.getMessage());
|
561
|
}
|
562
|
if (idExists) {
|
563
|
throw new InvalidSystemMetadata("1180",
|
564
|
"The series identifier " + sid.getValue() +
|
565
|
" is already used by another object and" +
|
566
|
"therefore can not be used for this object. Clients should choose" +
|
567
|
"a new identifier that is unique and retry the operation or " +
|
568
|
"use CN.reserveIdentifier() to reserve one.");
|
569
|
|
570
|
}
|
571
|
//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 )
|
572
|
if(sid.getValue().equals(pid.getValue())) {
|
573
|
throw new InvalidSystemMetadata("1180", "The series id "+sid.getValue()+" in the system metadata shouldn't have the same value of the pid.");
|
574
|
}
|
575
|
}
|
576
|
|
577
|
// call the shared impl
|
578
|
Identifier resultPid = super.create(session, pid, object, sysmeta);
|
579
|
|
580
|
// attempt to register the identifier - it checks if it is a doi
|
581
|
try {
|
582
|
DOIService.getInstance().registerDOI(sysmeta);
|
583
|
} catch (Exception e) {
|
584
|
ServiceFailure sf = new ServiceFailure("1190", "Could not register DOI: " + e.getMessage());
|
585
|
sf.initCause(e);
|
586
|
throw sf;
|
587
|
}
|
588
|
|
589
|
// return
|
590
|
return resultPid ;
|
591
|
}
|
592
|
|
593
|
/**
|
594
|
* Called by a Coordinating Node to request that the Member Node create a
|
595
|
* copy of the specified object by retrieving it from another Member
|
596
|
* Node and storing it locally so that it can be made accessible to
|
597
|
* the DataONE system.
|
598
|
*
|
599
|
* @param session - the Session object containing the credentials for the Subject
|
600
|
* @param sysmeta - Copy of the CN held system metadata for the object
|
601
|
* @param sourceNode - A reference to node from which the content should be
|
602
|
* retrieved. The reference should be resolved by
|
603
|
* checking the CN node registry.
|
604
|
*
|
605
|
* @return true if the replication succeeds
|
606
|
*
|
607
|
* @throws ServiceFailure
|
608
|
* @throws NotAuthorized
|
609
|
* @throws NotImplemented
|
610
|
* @throws UnsupportedType
|
611
|
* @throws InsufficientResources
|
612
|
* @throws InvalidRequest
|
613
|
*/
|
614
|
@Override
|
615
|
public boolean replicate(Session session, SystemMetadata sysmeta,
|
616
|
NodeReference sourceNode) throws NotImplemented, ServiceFailure,
|
617
|
NotAuthorized, InvalidRequest, InsufficientResources,
|
618
|
UnsupportedType {
|
619
|
|
620
|
if (session != null && sysmeta != null && sourceNode != null) {
|
621
|
logMetacat.info("MNodeService.replicate() called with parameters: \n" +
|
622
|
"\tSession.Subject = " +
|
623
|
session.getSubject().getValue() + "\n" +
|
624
|
"\tidentifier = " +
|
625
|
sysmeta.getIdentifier().getValue() +
|
626
|
"\n" + "\tSource NodeReference =" +
|
627
|
sourceNode.getValue());
|
628
|
}
|
629
|
boolean result = false;
|
630
|
String nodeIdStr = null;
|
631
|
NodeReference nodeId = null;
|
632
|
|
633
|
// get the referenced object
|
634
|
Identifier pid = sysmeta.getIdentifier();
|
635
|
// verify the pid is valid format
|
636
|
if (!isValidIdentifier(pid)) {
|
637
|
throw new InvalidRequest("2153", "The provided identifier in the system metadata is invalid.");
|
638
|
}
|
639
|
|
640
|
// get from the membernode
|
641
|
// TODO: switch credentials for the server retrieval?
|
642
|
this.mn = D1Client.getMN(sourceNode);
|
643
|
this.cn = D1Client.getCN();
|
644
|
InputStream object = null;
|
645
|
Session thisNodeSession = null;
|
646
|
SystemMetadata localSystemMetadata = null;
|
647
|
BaseException failure = null;
|
648
|
String localId = null;
|
649
|
|
650
|
// TODO: check credentials
|
651
|
// cannot be called by public
|
652
|
if (session == null || session.getSubject() == null) {
|
653
|
String msg = "No session was provided to replicate identifier " +
|
654
|
sysmeta.getIdentifier().getValue();
|
655
|
logMetacat.error(msg);
|
656
|
throw new NotAuthorized("2152", msg);
|
657
|
|
658
|
}
|
659
|
|
660
|
|
661
|
// get the local node id
|
662
|
try {
|
663
|
nodeIdStr = PropertyService.getProperty("dataone.nodeId");
|
664
|
nodeId = new NodeReference();
|
665
|
nodeId.setValue(nodeIdStr);
|
666
|
|
667
|
} catch (PropertyNotFoundException e1) {
|
668
|
String msg = "Couldn't get dataone.nodeId property: " + e1.getMessage();
|
669
|
failure = new ServiceFailure("2151", msg);
|
670
|
//setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
|
671
|
logMetacat.error(msg);
|
672
|
//return true;
|
673
|
throw new ServiceFailure("2151", msg);
|
674
|
|
675
|
}
|
676
|
|
677
|
|
678
|
try {
|
679
|
// do we already have a replica?
|
680
|
try {
|
681
|
localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
|
682
|
// if we have a local id, get the local object
|
683
|
try {
|
684
|
object = MetacatHandler.read(localId);
|
685
|
} catch (Exception e) {
|
686
|
// NOTE: we may already know about this ID because it could be a data file described by a metadata file
|
687
|
// https://redmine.dataone.org/issues/2572
|
688
|
// TODO: fix this so that we don't prevent ourselves from getting replicas
|
689
|
|
690
|
// let the CN know that the replication failed
|
691
|
logMetacat.warn("Object content not found on this node despite having localId: " + localId);
|
692
|
String msg = "Can't read the object bytes properly, replica is invalid.";
|
693
|
ServiceFailure serviceFailure = new ServiceFailure("2151", msg);
|
694
|
setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, serviceFailure);
|
695
|
logMetacat.warn(msg);
|
696
|
throw serviceFailure;
|
697
|
|
698
|
}
|
699
|
|
700
|
} catch (McdbDocNotFoundException e) {
|
701
|
logMetacat.info("No replica found. Continuing.");
|
702
|
|
703
|
} catch (SQLException ee) {
|
704
|
throw new ServiceFailure("2151", "Couldn't identify the local id of the object with the specified identifier "
|
705
|
+pid.getValue()+" since - "+ee.getMessage());
|
706
|
}
|
707
|
|
708
|
// no local replica, get a replica
|
709
|
if ( object == null ) {
|
710
|
// session should be null to use the default certificate
|
711
|
// location set in the Certificate manager
|
712
|
object = mn.getReplica(thisNodeSession, pid);
|
713
|
logMetacat.info("MNodeService.getReplica() called for identifier "
|
714
|
+ pid.getValue());
|
715
|
|
716
|
}
|
717
|
|
718
|
} catch (InvalidToken e) {
|
719
|
String msg = "Could not retrieve object to replicate (InvalidToken): "+ e.getMessage();
|
720
|
failure = new ServiceFailure("2151", msg);
|
721
|
setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
|
722
|
logMetacat.error(msg);
|
723
|
throw new ServiceFailure("2151", msg);
|
724
|
|
725
|
} catch (NotFound e) {
|
726
|
String msg = "Could not retrieve object to replicate (NotFound): "+ e.getMessage();
|
727
|
failure = new ServiceFailure("2151", msg);
|
728
|
setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
|
729
|
logMetacat.error(msg);
|
730
|
throw new ServiceFailure("2151", msg);
|
731
|
|
732
|
} catch (NotAuthorized e) {
|
733
|
String msg = "Could not retrieve object to replicate (NotAuthorized): "+ e.getMessage();
|
734
|
failure = new ServiceFailure("2151", msg);
|
735
|
setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
|
736
|
logMetacat.error(msg);
|
737
|
throw new ServiceFailure("2151", msg);
|
738
|
} catch (NotImplemented e) {
|
739
|
String msg = "Could not retrieve object to replicate (mn.getReplica NotImplemented): "+ e.getMessage();
|
740
|
failure = new ServiceFailure("2151", msg);
|
741
|
setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
|
742
|
logMetacat.error(msg);
|
743
|
throw new ServiceFailure("2151", msg);
|
744
|
} catch (ServiceFailure e) {
|
745
|
String msg = "Could not retrieve object to replicate (ServiceFailure): "+ e.getMessage();
|
746
|
failure = new ServiceFailure("2151", msg);
|
747
|
setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
|
748
|
logMetacat.error(msg);
|
749
|
throw new ServiceFailure("2151", msg);
|
750
|
} catch (InsufficientResources e) {
|
751
|
String msg = "Could not retrieve object to replicate (InsufficientResources): "+ e.getMessage();
|
752
|
failure = new ServiceFailure("2151", msg);
|
753
|
setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
|
754
|
logMetacat.error(msg);
|
755
|
throw new ServiceFailure("2151", msg);
|
756
|
}
|
757
|
|
758
|
// verify checksum on the object, if supported
|
759
|
if (object.markSupported()) {
|
760
|
Checksum givenChecksum = sysmeta.getChecksum();
|
761
|
Checksum computedChecksum = null;
|
762
|
try {
|
763
|
computedChecksum = ChecksumUtil.checksum(object, givenChecksum.getAlgorithm());
|
764
|
object.reset();
|
765
|
|
766
|
} catch (Exception e) {
|
767
|
String msg = "Error computing checksum on replica: " + e.getMessage();
|
768
|
logMetacat.error(msg);
|
769
|
ServiceFailure sf = new ServiceFailure("2151", msg);
|
770
|
sf.initCause(e);
|
771
|
setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, sf);
|
772
|
throw sf;
|
773
|
}
|
774
|
if (!givenChecksum.getValue().equals(computedChecksum.getValue())) {
|
775
|
logMetacat.error("Given checksum for " + pid.getValue() +
|
776
|
"is " + givenChecksum.getValue());
|
777
|
logMetacat.error("Computed checksum for " + pid.getValue() +
|
778
|
"is " + computedChecksum.getValue());
|
779
|
String msg = "Computed checksum does not match declared checksum";
|
780
|
failure = new ServiceFailure("2151", msg);
|
781
|
setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
|
782
|
throw new ServiceFailure("2151", msg);
|
783
|
}
|
784
|
}
|
785
|
|
786
|
// add it to local store
|
787
|
Identifier retPid;
|
788
|
try {
|
789
|
// skip the MN.create -- this mutates the system metadata and we don't want it to
|
790
|
if ( localId == null ) {
|
791
|
// TODO: this will fail if we already "know" about the identifier
|
792
|
// FIXME: see https://redmine.dataone.org/issues/2572
|
793
|
retPid = super.create(session, pid, object, sysmeta);
|
794
|
result = (retPid.getValue().equals(pid.getValue()));
|
795
|
}
|
796
|
|
797
|
} catch (Exception e) {
|
798
|
String msg = "Could not save object to local store (" + e.getClass().getName() + "): " + e.getMessage();
|
799
|
failure = new ServiceFailure("2151", msg);
|
800
|
setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
|
801
|
logMetacat.error(msg);
|
802
|
throw new ServiceFailure("2151", msg);
|
803
|
|
804
|
}
|
805
|
|
806
|
// finish by setting the replication status
|
807
|
setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.COMPLETED, null);
|
808
|
return result;
|
809
|
|
810
|
}
|
811
|
|
812
|
/**
|
813
|
* Return the object identified by the given object identifier
|
814
|
*
|
815
|
* @param session - the Session object containing the credentials for the Subject
|
816
|
* @param pid - the object identifier for the given object
|
817
|
*
|
818
|
* @return inputStream - the input stream of the given object
|
819
|
*
|
820
|
* @throws InvalidToken
|
821
|
* @throws ServiceFailure
|
822
|
* @throws NotAuthorized
|
823
|
* @throws InvalidRequest
|
824
|
* @throws NotImplemented
|
825
|
*/
|
826
|
@Override
|
827
|
public InputStream get(Session session, Identifier pid)
|
828
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
|
829
|
|
830
|
return super.get(session, pid);
|
831
|
|
832
|
}
|
833
|
|
834
|
/**
|
835
|
* Returns a Checksum for the specified object using an accepted hashing algorithm
|
836
|
*
|
837
|
* @param session - the Session object containing the credentials for the Subject
|
838
|
* @param pid - the object identifier for the given object
|
839
|
* @param algorithm - the name of an algorithm that will be used to compute
|
840
|
* a checksum of the bytes of the object
|
841
|
*
|
842
|
* @return checksum - the checksum of the given object
|
843
|
*
|
844
|
* @throws InvalidToken
|
845
|
* @throws ServiceFailure
|
846
|
* @throws NotAuthorized
|
847
|
* @throws NotFound
|
848
|
* @throws InvalidRequest
|
849
|
* @throws NotImplemented
|
850
|
*/
|
851
|
@Override
|
852
|
public Checksum getChecksum(Session session, Identifier pid, String algorithm)
|
853
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
854
|
InvalidRequest, NotImplemented {
|
855
|
|
856
|
Checksum checksum = null;
|
857
|
String serviceFailure = "1410";
|
858
|
String notFound = "1420";
|
859
|
//Checkum only handles the pid, not sid
|
860
|
checkV1SystemMetaPidExist(pid, serviceFailure, "The checksum for the object specified by "+pid.getValue()+" couldn't be returned ", notFound,
|
861
|
"The object specified by "+pid.getValue()+" does not exist at this node.");
|
862
|
InputStream inputStream = get(session, pid);
|
863
|
|
864
|
try {
|
865
|
checksum = ChecksumUtil.checksum(inputStream, algorithm);
|
866
|
|
867
|
} catch (NoSuchAlgorithmException e) {
|
868
|
throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
|
869
|
+ e.getMessage());
|
870
|
} catch (IOException e) {
|
871
|
throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
|
872
|
+ e.getMessage());
|
873
|
}
|
874
|
|
875
|
if (checksum == null) {
|
876
|
throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
|
877
|
}
|
878
|
|
879
|
return checksum;
|
880
|
}
|
881
|
|
882
|
/**
|
883
|
* Return the system metadata for a given object
|
884
|
*
|
885
|
* @param session - the Session object containing the credentials for the Subject
|
886
|
* @param pid - the object identifier for the given object
|
887
|
*
|
888
|
* @return inputStream - the input stream of the given system metadata object
|
889
|
*
|
890
|
* @throws InvalidToken
|
891
|
* @throws ServiceFailure
|
892
|
* @throws NotAuthorized
|
893
|
* @throws NotFound
|
894
|
* @throws InvalidRequest
|
895
|
* @throws NotImplemented
|
896
|
*/
|
897
|
@Override
|
898
|
public SystemMetadata getSystemMetadata(Session session, Identifier pid)
|
899
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
900
|
NotImplemented {
|
901
|
|
902
|
return super.getSystemMetadata(session, pid);
|
903
|
}
|
904
|
|
905
|
/**
|
906
|
* Retrieve the list of objects present on the MN that match the calling parameters
|
907
|
*
|
908
|
* @param session - the Session object containing the credentials for the Subject
|
909
|
* @param startTime - Specifies the beginning of the time range from which
|
910
|
* to return object (>=)
|
911
|
* @param endTime - Specifies the beginning of the time range from which
|
912
|
* to return object (>=)
|
913
|
* @param objectFormat - Restrict results to the specified object format
|
914
|
* @param replicaStatus - Indicates if replicated objects should be returned in the list
|
915
|
* @param start - The zero-based index of the first value, relative to the
|
916
|
* first record of the resultset that matches the parameters.
|
917
|
* @param count - The maximum number of entries that should be returned in
|
918
|
* the response. The Member Node may return less entries
|
919
|
* than specified in this value.
|
920
|
*
|
921
|
* @return objectList - the list of objects matching the criteria
|
922
|
*
|
923
|
* @throws InvalidToken
|
924
|
* @throws ServiceFailure
|
925
|
* @throws NotAuthorized
|
926
|
* @throws InvalidRequest
|
927
|
* @throws NotImplemented
|
928
|
*/
|
929
|
@Override
|
930
|
public ObjectList listObjects(Session session, Date startTime, Date endTime, ObjectFormatIdentifier objectFormatId, Identifier identifier, Boolean replicaStatus, Integer start,
|
931
|
Integer count) throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken {
|
932
|
NodeReference nodeId = null;
|
933
|
if(!replicaStatus) {
|
934
|
//not include those objects whose authoritative node is not this mn
|
935
|
nodeId = new NodeReference();
|
936
|
try {
|
937
|
String currentNodeId = PropertyService.getInstance().getProperty("dataone.nodeId"); // return only pids for which this mn
|
938
|
nodeId.setValue(currentNodeId);
|
939
|
} catch(Exception e) {
|
940
|
throw new ServiceFailure("1580", e.getMessage());
|
941
|
}
|
942
|
}
|
943
|
return super.listObjects(session, startTime, endTime, objectFormatId, identifier, nodeId, start, count);
|
944
|
}
|
945
|
|
946
|
/**
|
947
|
* Return a description of the node's capabilities and services.
|
948
|
*
|
949
|
* @return node - the technical capabilities of the Member Node
|
950
|
*
|
951
|
* @throws ServiceFailure
|
952
|
* @throws NotAuthorized
|
953
|
* @throws InvalidRequest
|
954
|
* @throws NotImplemented
|
955
|
*/
|
956
|
@Override
|
957
|
public Node getCapabilities()
|
958
|
throws NotImplemented, ServiceFailure {
|
959
|
|
960
|
String nodeName = null;
|
961
|
String nodeId = null;
|
962
|
String subject = null;
|
963
|
String contactSubject = null;
|
964
|
String nodeDesc = null;
|
965
|
String nodeTypeString = null;
|
966
|
NodeType nodeType = null;
|
967
|
List<String> mnCoreServiceVersions = null;
|
968
|
List<String> mnReadServiceVersions = null;
|
969
|
List<String> mnAuthorizationServiceVersions = null;
|
970
|
List<String> mnStorageServiceVersions = null;
|
971
|
List<String> mnReplicationServiceVersions = null;
|
972
|
|
973
|
boolean nodeSynchronize = false;
|
974
|
boolean nodeReplicate = false;
|
975
|
List<String> mnCoreServiceAvailables = null;
|
976
|
List<String> mnReadServiceAvailables = null;
|
977
|
List<String> mnAuthorizationServiceAvailables = null;
|
978
|
List<String> mnStorageServiceAvailables = null;
|
979
|
List<String> mnReplicationServiceAvailables = null;
|
980
|
|
981
|
try {
|
982
|
// get the properties of the node based on configuration information
|
983
|
nodeName = Settings.getConfiguration().getString("dataone.nodeName");
|
984
|
nodeId = Settings.getConfiguration().getString("dataone.nodeId");
|
985
|
subject = Settings.getConfiguration().getString("dataone.subject");
|
986
|
contactSubject = Settings.getConfiguration().getString("dataone.contactSubject");
|
987
|
nodeDesc = Settings.getConfiguration().getString("dataone.nodeDescription");
|
988
|
nodeTypeString = Settings.getConfiguration().getString("dataone.nodeType");
|
989
|
nodeType = NodeType.convert(nodeTypeString);
|
990
|
nodeSynchronize = new Boolean(Settings.getConfiguration().getString("dataone.nodeSynchronize")).booleanValue();
|
991
|
nodeReplicate = new Boolean(Settings.getConfiguration().getString("dataone.nodeReplicate")).booleanValue();
|
992
|
|
993
|
// Set the properties of the node based on configuration information and
|
994
|
// calls to current status methods
|
995
|
String serviceName = SystemUtil.getSecureContextURL() + "/" + PropertyService.getProperty("dataone.serviceName");
|
996
|
Node node = new Node();
|
997
|
node.setBaseURL(serviceName + "/" + nodeTypeString);
|
998
|
node.setDescription(nodeDesc);
|
999
|
|
1000
|
// set the node's health information
|
1001
|
node.setState(NodeState.UP);
|
1002
|
|
1003
|
// set the ping response to the current value
|
1004
|
Ping canPing = new Ping();
|
1005
|
canPing.setSuccess(false);
|
1006
|
try {
|
1007
|
Date pingDate = ping();
|
1008
|
canPing.setSuccess(pingDate != null);
|
1009
|
} catch (BaseException e) {
|
1010
|
e.printStackTrace();
|
1011
|
// guess it can't be pinged
|
1012
|
}
|
1013
|
|
1014
|
node.setPing(canPing);
|
1015
|
|
1016
|
NodeReference identifier = new NodeReference();
|
1017
|
identifier.setValue(nodeId);
|
1018
|
node.setIdentifier(identifier);
|
1019
|
Subject s = new Subject();
|
1020
|
s.setValue(subject);
|
1021
|
node.addSubject(s);
|
1022
|
Subject contact = new Subject();
|
1023
|
contact.setValue(contactSubject);
|
1024
|
node.addContactSubject(contact);
|
1025
|
node.setName(nodeName);
|
1026
|
node.setReplicate(nodeReplicate);
|
1027
|
node.setSynchronize(nodeSynchronize);
|
1028
|
|
1029
|
// services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
|
1030
|
Services services = new Services();
|
1031
|
|
1032
|
mnCoreServiceVersions = Settings.getConfiguration().getList("dataone.mnCore.serviceVersion");
|
1033
|
mnCoreServiceAvailables = Settings.getConfiguration().getList("dataone.mnCore.serviceAvailable");
|
1034
|
if(mnCoreServiceVersions != null && mnCoreServiceAvailables != null && mnCoreServiceVersions.size() == mnCoreServiceAvailables.size()) {
|
1035
|
for(int i=0; i<mnCoreServiceVersions.size(); i++) {
|
1036
|
String version = mnCoreServiceVersions.get(i);
|
1037
|
boolean available = new Boolean(mnCoreServiceAvailables.get(i)).booleanValue();
|
1038
|
Service sMNCore = new Service();
|
1039
|
sMNCore.setName("MNCore");
|
1040
|
sMNCore.setVersion(version);
|
1041
|
sMNCore.setAvailable(available);
|
1042
|
services.addService(sMNCore);
|
1043
|
}
|
1044
|
}
|
1045
|
|
1046
|
mnReadServiceVersions = Settings.getConfiguration().getList("dataone.mnRead.serviceVersion");
|
1047
|
mnReadServiceAvailables = Settings.getConfiguration().getList("dataone.mnRead.serviceAvailable");
|
1048
|
if(mnReadServiceVersions != null && mnReadServiceAvailables != null && mnReadServiceVersions.size()==mnReadServiceAvailables.size()) {
|
1049
|
for(int i=0; i<mnReadServiceVersions.size(); i++) {
|
1050
|
String version = mnReadServiceVersions.get(i);
|
1051
|
boolean available = new Boolean(mnReadServiceAvailables.get(i)).booleanValue();
|
1052
|
Service sMNRead = new Service();
|
1053
|
sMNRead.setName("MNRead");
|
1054
|
sMNRead.setVersion(version);
|
1055
|
sMNRead.setAvailable(available);
|
1056
|
services.addService(sMNRead);
|
1057
|
}
|
1058
|
}
|
1059
|
|
1060
|
mnAuthorizationServiceVersions = Settings.getConfiguration().getList("dataone.mnAuthorization.serviceVersion");
|
1061
|
mnAuthorizationServiceAvailables = Settings.getConfiguration().getList("dataone.mnAuthorization.serviceAvailable");
|
1062
|
if(mnAuthorizationServiceVersions != null && mnAuthorizationServiceAvailables != null && mnAuthorizationServiceVersions.size()==mnAuthorizationServiceAvailables.size()) {
|
1063
|
for(int i=0; i<mnAuthorizationServiceVersions.size(); i++) {
|
1064
|
String version = mnAuthorizationServiceVersions.get(i);
|
1065
|
boolean available = new Boolean(mnAuthorizationServiceAvailables.get(i)).booleanValue();
|
1066
|
Service sMNAuthorization = new Service();
|
1067
|
sMNAuthorization.setName("MNAuthorization");
|
1068
|
sMNAuthorization.setVersion(version);
|
1069
|
sMNAuthorization.setAvailable(available);
|
1070
|
services.addService(sMNAuthorization);
|
1071
|
}
|
1072
|
}
|
1073
|
|
1074
|
mnStorageServiceVersions = Settings.getConfiguration().getList("dataone.mnStorage.serviceVersion");
|
1075
|
mnStorageServiceAvailables = Settings.getConfiguration().getList("dataone.mnStorage.serviceAvailable");
|
1076
|
if(mnStorageServiceVersions != null && mnStorageServiceAvailables != null && mnStorageServiceVersions.size() == mnStorageServiceAvailables.size()) {
|
1077
|
for(int i=0; i<mnStorageServiceVersions.size(); i++) {
|
1078
|
String version = mnStorageServiceVersions.get(i);
|
1079
|
boolean available = new Boolean(mnStorageServiceAvailables.get(i)).booleanValue();
|
1080
|
Service sMNStorage = new Service();
|
1081
|
sMNStorage.setName("MNStorage");
|
1082
|
sMNStorage.setVersion(version);
|
1083
|
sMNStorage.setAvailable(available);
|
1084
|
services.addService(sMNStorage);
|
1085
|
}
|
1086
|
}
|
1087
|
|
1088
|
mnReplicationServiceVersions = Settings.getConfiguration().getList("dataone.mnReplication.serviceVersion");
|
1089
|
mnReplicationServiceAvailables = Settings.getConfiguration().getList("dataone.mnReplication.serviceAvailable");
|
1090
|
if(mnReplicationServiceVersions != null && mnReplicationServiceAvailables != null && mnReplicationServiceVersions.size() == mnReplicationServiceAvailables.size()) {
|
1091
|
for (int i=0; i<mnReplicationServiceVersions.size(); i++) {
|
1092
|
String version = mnReplicationServiceVersions.get(i);
|
1093
|
boolean available = new Boolean(mnReplicationServiceAvailables.get(i)).booleanValue();
|
1094
|
Service sMNReplication = new Service();
|
1095
|
sMNReplication.setName("MNReplication");
|
1096
|
sMNReplication.setVersion(version);
|
1097
|
sMNReplication.setAvailable(available);
|
1098
|
services.addService(sMNReplication);
|
1099
|
}
|
1100
|
}
|
1101
|
|
1102
|
node.setServices(services);
|
1103
|
|
1104
|
// Set the schedule for synchronization
|
1105
|
Synchronization synchronization = new Synchronization();
|
1106
|
Schedule schedule = new Schedule();
|
1107
|
Date now = new Date();
|
1108
|
schedule.setYear(PropertyService.getProperty("dataone.nodeSynchronization.schedule.year"));
|
1109
|
schedule.setMon(PropertyService.getProperty("dataone.nodeSynchronization.schedule.mon"));
|
1110
|
schedule.setMday(PropertyService.getProperty("dataone.nodeSynchronization.schedule.mday"));
|
1111
|
schedule.setWday(PropertyService.getProperty("dataone.nodeSynchronization.schedule.wday"));
|
1112
|
schedule.setHour(PropertyService.getProperty("dataone.nodeSynchronization.schedule.hour"));
|
1113
|
schedule.setMin(PropertyService.getProperty("dataone.nodeSynchronization.schedule.min"));
|
1114
|
schedule.setSec(PropertyService.getProperty("dataone.nodeSynchronization.schedule.sec"));
|
1115
|
synchronization.setSchedule(schedule);
|
1116
|
synchronization.setLastHarvested(now);
|
1117
|
synchronization.setLastCompleteHarvest(now);
|
1118
|
node.setSynchronization(synchronization);
|
1119
|
|
1120
|
node.setType(nodeType);
|
1121
|
return node;
|
1122
|
|
1123
|
} catch (PropertyNotFoundException pnfe) {
|
1124
|
String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
|
1125
|
logMetacat.error(msg);
|
1126
|
throw new ServiceFailure("2162", msg);
|
1127
|
}
|
1128
|
}
|
1129
|
|
1130
|
|
1131
|
|
1132
|
/**
|
1133
|
* A callback method used by a CN to indicate to a MN that it cannot
|
1134
|
* complete synchronization of the science metadata identified by pid. Log
|
1135
|
* the event in the metacat event log.
|
1136
|
*
|
1137
|
* @param session
|
1138
|
* @param syncFailed
|
1139
|
*
|
1140
|
* @throws ServiceFailure
|
1141
|
* @throws NotAuthorized
|
1142
|
* @throws NotImplemented
|
1143
|
*/
|
1144
|
@Override
|
1145
|
public boolean synchronizationFailed(Session session, SynchronizationFailed syncFailed)
|
1146
|
throws NotImplemented, ServiceFailure, NotAuthorized {
|
1147
|
|
1148
|
String localId;
|
1149
|
Identifier pid;
|
1150
|
if ( syncFailed.getPid() != null ) {
|
1151
|
pid = new Identifier();
|
1152
|
pid.setValue(syncFailed.getPid());
|
1153
|
boolean allowed;
|
1154
|
|
1155
|
//are we allowed? only CNs
|
1156
|
try {
|
1157
|
allowed = isAdminAuthorized(session);
|
1158
|
if ( !allowed ){
|
1159
|
throw new NotAuthorized("2162",
|
1160
|
"Not allowed to call synchronizationFailed() on this node.");
|
1161
|
}
|
1162
|
} catch (InvalidToken e) {
|
1163
|
throw new NotAuthorized("2162",
|
1164
|
"Not allowed to call synchronizationFailed() on this node.");
|
1165
|
|
1166
|
}
|
1167
|
|
1168
|
} else {
|
1169
|
throw new ServiceFailure("2161", "The identifier cannot be null.");
|
1170
|
|
1171
|
}
|
1172
|
|
1173
|
try {
|
1174
|
localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
|
1175
|
} catch (McdbDocNotFoundException e) {
|
1176
|
throw new ServiceFailure("2161", "The identifier specified by " +
|
1177
|
syncFailed.getPid() + " was not found on this node.");
|
1178
|
|
1179
|
} catch (SQLException e) {
|
1180
|
throw new ServiceFailure("2161", "Couldn't identify the local id of the identifier specified by " +
|
1181
|
syncFailed.getPid() + " since "+e.getMessage());
|
1182
|
}
|
1183
|
// TODO: update the CN URL below when the CNRead.SynchronizationFailed
|
1184
|
// method is changed to include the URL as a parameter
|
1185
|
logMetacat.debug("Synchronization for the object identified by " +
|
1186
|
pid.getValue() + " failed from " + syncFailed.getNodeId() +
|
1187
|
" Logging the event to the Metacat EventLog as a 'syncFailed' event.");
|
1188
|
// TODO: use the event type enum when the SYNCHRONIZATION_FAILED event is added
|
1189
|
String principal = Constants.SUBJECT_PUBLIC;
|
1190
|
if (session != null && session.getSubject() != null) {
|
1191
|
principal = session.getSubject().getValue();
|
1192
|
}
|
1193
|
try {
|
1194
|
EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "synchronization_failed");
|
1195
|
} catch (Exception e) {
|
1196
|
throw new ServiceFailure("2161", "Could not log the error for: " + pid.getValue());
|
1197
|
}
|
1198
|
//EventLog.getInstance().log("CN URL WILL GO HERE",
|
1199
|
// session.getSubject().getValue(), localId, Event.SYNCHRONIZATION_FAILED);
|
1200
|
return true;
|
1201
|
|
1202
|
}
|
1203
|
|
1204
|
/**
|
1205
|
* Essentially a get() but with different logging behavior
|
1206
|
*/
|
1207
|
@Override
|
1208
|
public InputStream getReplica(Session session, Identifier pid)
|
1209
|
throws NotAuthorized, NotImplemented, ServiceFailure, InvalidToken {
|
1210
|
|
1211
|
logMetacat.info("MNodeService.getReplica() called.");
|
1212
|
|
1213
|
// cannot be called by public
|
1214
|
if (session == null) {
|
1215
|
throw new InvalidToken("2183", "No session was provided.");
|
1216
|
}
|
1217
|
|
1218
|
logMetacat.info("MNodeService.getReplica() called with parameters: \n" +
|
1219
|
"\tSession.Subject = " + session.getSubject().getValue() + "\n" +
|
1220
|
"\tIdentifier = " + pid.getValue());
|
1221
|
|
1222
|
InputStream inputStream = null; // bytes to be returned
|
1223
|
handler = new MetacatHandler(new Timer());
|
1224
|
boolean allowed = false;
|
1225
|
String localId; // the metacat docid for the pid
|
1226
|
|
1227
|
// get the local docid from Metacat
|
1228
|
try {
|
1229
|
localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
|
1230
|
} catch (McdbDocNotFoundException e) {
|
1231
|
throw new ServiceFailure("2181", "The object specified by " +
|
1232
|
pid.getValue() + " does not exist at this node.");
|
1233
|
|
1234
|
} catch (SQLException e) {
|
1235
|
throw new ServiceFailure("2181", "The local id of the object specified by " +
|
1236
|
pid.getValue() + " couldn't be identified since "+e.getMessage());
|
1237
|
}
|
1238
|
|
1239
|
Subject targetNodeSubject = session.getSubject();
|
1240
|
|
1241
|
// check for authorization to replicate, null session to act as this source MN
|
1242
|
try {
|
1243
|
allowed = D1Client.getCN().isNodeAuthorized(null, targetNodeSubject, pid);
|
1244
|
} catch (InvalidToken e1) {
|
1245
|
throw new ServiceFailure("2181", "Could not determine if node is authorized: "
|
1246
|
+ e1.getMessage());
|
1247
|
|
1248
|
} catch (NotFound e1) {
|
1249
|
throw new ServiceFailure("2181", "Could not determine if node is authorized: "
|
1250
|
+ e1.getMessage());
|
1251
|
|
1252
|
} catch (InvalidRequest e1) {
|
1253
|
throw new ServiceFailure("2181", "Could not determine if node is authorized: "
|
1254
|
+ e1.getMessage());
|
1255
|
|
1256
|
}
|
1257
|
|
1258
|
logMetacat.info("Called D1Client.isNodeAuthorized(). Allowed = " + allowed +
|
1259
|
" for identifier " + pid.getValue());
|
1260
|
|
1261
|
// if the person is authorized, perform the read
|
1262
|
if (allowed) {
|
1263
|
try {
|
1264
|
inputStream = MetacatHandler.read(localId);
|
1265
|
} catch (Exception e) {
|
1266
|
throw new ServiceFailure("1020", "The object specified by " +
|
1267
|
pid.getValue() + "could not be returned due to error: " + e.getMessage());
|
1268
|
}
|
1269
|
}
|
1270
|
|
1271
|
// if we fail to set the input stream
|
1272
|
if (inputStream == null) {
|
1273
|
throw new ServiceFailure("2181", "The object specified by " +
|
1274
|
pid.getValue() + "does not exist at this node.");
|
1275
|
}
|
1276
|
|
1277
|
// log the replica event
|
1278
|
String principal = null;
|
1279
|
if (session.getSubject() != null) {
|
1280
|
principal = session.getSubject().getValue();
|
1281
|
}
|
1282
|
EventLog.getInstance().log(request.getRemoteAddr(),
|
1283
|
request.getHeader("User-Agent"), principal, localId, "replicate");
|
1284
|
|
1285
|
return inputStream;
|
1286
|
}
|
1287
|
|
1288
|
/**
|
1289
|
* A method to notify the Member Node that the authoritative copy of
|
1290
|
* system metadata on the Coordinating Nodes has changed.
|
1291
|
*
|
1292
|
* @param session Session information that contains the identity of the
|
1293
|
* calling user as retrieved from the X.509 certificate
|
1294
|
* which must be traceable to the CILogon service.
|
1295
|
* @param serialVersion The serialVersion of the system metadata
|
1296
|
* @param dateSysMetaLastModified The time stamp for when the system metadata was changed
|
1297
|
* @throws NotImplemented
|
1298
|
* @throws ServiceFailure
|
1299
|
* @throws NotAuthorized
|
1300
|
* @throws InvalidRequest
|
1301
|
* @throws InvalidToken
|
1302
|
*/
|
1303
|
public boolean systemMetadataChanged(Session session, Identifier pid,
|
1304
|
long serialVersion, Date dateSysMetaLastModified)
|
1305
|
throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest,
|
1306
|
InvalidToken {
|
1307
|
|
1308
|
// cannot be called by public
|
1309
|
if (session == null) {
|
1310
|
throw new InvalidToken("1332", "No session was provided.");
|
1311
|
}
|
1312
|
|
1313
|
String serviceFailureCode = "1333";
|
1314
|
Identifier sid = getPIDForSID(pid, serviceFailureCode);
|
1315
|
if(sid != null) {
|
1316
|
pid = sid;
|
1317
|
}
|
1318
|
|
1319
|
SystemMetadata currentLocalSysMeta = null;
|
1320
|
SystemMetadata newSysMeta = null;
|
1321
|
CNode cn = D1Client.getCN();
|
1322
|
NodeList nodeList = null;
|
1323
|
Subject callingSubject = null;
|
1324
|
boolean allowed = false;
|
1325
|
|
1326
|
// are we allowed to call this?
|
1327
|
callingSubject = session.getSubject();
|
1328
|
nodeList = cn.listNodes();
|
1329
|
|
1330
|
for(Node node : nodeList.getNodeList()) {
|
1331
|
// must be a CN
|
1332
|
if ( node.getType().equals(NodeType.CN)) {
|
1333
|
List<Subject> subjectList = node.getSubjectList();
|
1334
|
// the calling subject must be in the subject list
|
1335
|
if ( subjectList.contains(callingSubject)) {
|
1336
|
allowed = true;
|
1337
|
|
1338
|
}
|
1339
|
|
1340
|
}
|
1341
|
}
|
1342
|
|
1343
|
if (!allowed ) {
|
1344
|
String msg = "The subject identified by " + callingSubject.getValue() +
|
1345
|
" is not authorized to call this service.";
|
1346
|
throw new NotAuthorized("1331", msg);
|
1347
|
|
1348
|
}
|
1349
|
|
1350
|
// compare what we have locally to what is sent in the change notification
|
1351
|
try {
|
1352
|
currentLocalSysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
|
1353
|
|
1354
|
} catch (RuntimeException e) {
|
1355
|
String msg = "SystemMetadata for pid " + pid.getValue() +
|
1356
|
" couldn't be updated because it couldn't be found locally: " +
|
1357
|
e.getMessage();
|
1358
|
logMetacat.error(msg);
|
1359
|
ServiceFailure sf = new ServiceFailure("1333", msg);
|
1360
|
sf.initCause(e);
|
1361
|
throw sf;
|
1362
|
}
|
1363
|
|
1364
|
if (currentLocalSysMeta.getSerialVersion().longValue() < serialVersion ) {
|
1365
|
try {
|
1366
|
newSysMeta = cn.getSystemMetadata(null, pid);
|
1367
|
} catch (NotFound e) {
|
1368
|
// huh? you just said you had it
|
1369
|
String msg = "On updating the local copy of system metadata " +
|
1370
|
"for pid " + pid.getValue() +", the CN reports it is not found." +
|
1371
|
" The error message was: " + e.getMessage();
|
1372
|
logMetacat.error(msg);
|
1373
|
ServiceFailure sf = new ServiceFailure("1333", msg);
|
1374
|
sf.initCause(e);
|
1375
|
throw sf;
|
1376
|
}
|
1377
|
|
1378
|
//check about the sid in the system metadata
|
1379
|
Identifier newSID = newSysMeta.getSeriesId();
|
1380
|
if(newSID != null) {
|
1381
|
if (!isValidIdentifier(newSID)) {
|
1382
|
throw new InvalidRequest("1334", "The series identifier in the new system metadata is invalid.");
|
1383
|
}
|
1384
|
Identifier currentSID = currentLocalSysMeta.getSeriesId();
|
1385
|
if( currentSID != null && currentSID.getValue() != null) {
|
1386
|
if(!newSID.getValue().equals(currentSID.getValue())) {
|
1387
|
//newSID doesn't match the currentSID. The newSID shouldn't be used.
|
1388
|
try {
|
1389
|
if(IdentifierManager.getInstance().identifierExists(newSID.getValue())) {
|
1390
|
throw new InvalidRequest("1334", "The series identifier "+newSID.getValue()+" in the new system metadata has been used by another object.");
|
1391
|
}
|
1392
|
} catch (SQLException sql) {
|
1393
|
throw new ServiceFailure("1333", "Couldn't determine if the SID "+newSID.getValue()+" in the system metadata exists in the node since "+sql.getMessage());
|
1394
|
}
|
1395
|
|
1396
|
}
|
1397
|
} else {
|
1398
|
//newSID shouldn't be used
|
1399
|
try {
|
1400
|
if(IdentifierManager.getInstance().identifierExists(newSID.getValue())) {
|
1401
|
throw new InvalidRequest("1334", "The series identifier "+newSID.getValue()+" in the new system metadata has been used by another object.");
|
1402
|
}
|
1403
|
} catch (SQLException sql) {
|
1404
|
throw new ServiceFailure("1333", "Couldn't determine if the SID "+newSID.getValue()+" in the system metadata exists in the node since "+sql.getMessage());
|
1405
|
}
|
1406
|
}
|
1407
|
}
|
1408
|
// update the local copy of system metadata for the pid
|
1409
|
try {
|
1410
|
HazelcastService.getInstance().getSystemMetadataMap().put(newSysMeta.getIdentifier(), newSysMeta);
|
1411
|
logMetacat.info("Updated local copy of system metadata for pid " +
|
1412
|
pid.getValue() + " after change notification from the CN.");
|
1413
|
|
1414
|
// TODO: consider inspecting the change for archive
|
1415
|
// see: https://projects.ecoinformatics.org/ecoinfo/issues/6417
|
1416
|
// if (newSysMeta.getArchived() != null && newSysMeta.getArchived().booleanValue()) {
|
1417
|
// try {
|
1418
|
// this.archive(session, newSysMeta.getIdentifier());
|
1419
|
// } catch (NotFound e) {
|
1420
|
// // do we care? nothing to do about it now
|
1421
|
// logMetacat.error(e.getMessage(), e);
|
1422
|
// }
|
1423
|
// }
|
1424
|
|
1425
|
} catch (RuntimeException e) {
|
1426
|
String msg = "SystemMetadata for pid " + pid.getValue() +
|
1427
|
" couldn't be updated: " +
|
1428
|
e.getMessage();
|
1429
|
logMetacat.error(msg);
|
1430
|
ServiceFailure sf = new ServiceFailure("1333", msg);
|
1431
|
sf.initCause(e);
|
1432
|
throw sf;
|
1433
|
}
|
1434
|
|
1435
|
// attempt to re-register the identifier (it checks if it is a doi)
|
1436
|
try {
|
1437
|
DOIService.getInstance().registerDOI(newSysMeta);
|
1438
|
} catch (Exception e) {
|
1439
|
logMetacat.warn("Could not [re]register DOI: " + e.getMessage(), e);
|
1440
|
}
|
1441
|
|
1442
|
// submit for indexing
|
1443
|
try {
|
1444
|
MetacatSolrIndex.getInstance().submit(newSysMeta.getIdentifier(), newSysMeta, null, true);
|
1445
|
} catch (Exception e) {
|
1446
|
logMetacat.error("Could not submit changed systemMetadata for indexing, pid: " + newSysMeta.getIdentifier().getValue(), e);
|
1447
|
}
|
1448
|
}
|
1449
|
|
1450
|
return true;
|
1451
|
|
1452
|
}
|
1453
|
|
1454
|
/*
|
1455
|
* Set the replication status for the object on the Coordinating Node
|
1456
|
*
|
1457
|
* @param session - the session for the this target node
|
1458
|
* @param pid - the identifier of the object being updated
|
1459
|
* @param nodeId - the identifier of this target node
|
1460
|
* @param status - the replication status to set
|
1461
|
* @param failure - the exception to include, if any
|
1462
|
*/
|
1463
|
private void setReplicationStatus(Session session, Identifier pid,
|
1464
|
NodeReference nodeId, ReplicationStatus status, BaseException failure)
|
1465
|
throws ServiceFailure, NotImplemented, NotAuthorized,
|
1466
|
InvalidRequest {
|
1467
|
|
1468
|
// call the CN as the MN to set the replication status
|
1469
|
try {
|
1470
|
this.cn = D1Client.getCN();
|
1471
|
this.cn.setReplicationStatus(session, pid, nodeId,
|
1472
|
status, failure);
|
1473
|
|
1474
|
} catch (InvalidToken e) {
|
1475
|
String msg = "Could not set the replication status for " + pid.getValue() + " on the CN (InvalidToken): " + e.getMessage();
|
1476
|
logMetacat.error(msg);
|
1477
|
throw new ServiceFailure("2151",
|
1478
|
msg);
|
1479
|
|
1480
|
} catch (NotFound e) {
|
1481
|
String msg = "Could not set the replication status for " + pid.getValue() + " on the CN (NotFound): " + e.getMessage();
|
1482
|
logMetacat.error(msg);
|
1483
|
throw new ServiceFailure("2151",
|
1484
|
msg);
|
1485
|
|
1486
|
}
|
1487
|
}
|
1488
|
|
1489
|
private SystemMetadata makePublicIfNot(SystemMetadata sysmeta, Identifier pid) throws ServiceFailure, InvalidToken, NotFound, NotImplemented, InvalidRequest {
|
1490
|
// check if it is publicly readable
|
1491
|
boolean isPublic = false;
|
1492
|
Subject publicSubject = new Subject();
|
1493
|
publicSubject.setValue(Constants.SUBJECT_PUBLIC);
|
1494
|
Session publicSession = new Session();
|
1495
|
publicSession.setSubject(publicSubject);
|
1496
|
AccessRule publicRule = new AccessRule();
|
1497
|
publicRule.addPermission(Permission.READ);
|
1498
|
publicRule.addSubject(publicSubject);
|
1499
|
|
1500
|
// see if we need to add the rule
|
1501
|
try {
|
1502
|
isPublic = this.isAuthorized(publicSession, pid, Permission.READ);
|
1503
|
} catch (NotAuthorized na) {
|
1504
|
// well, certainly not authorized for public read!
|
1505
|
}
|
1506
|
if (!isPublic) {
|
1507
|
sysmeta.getAccessPolicy().addAllow(publicRule);
|
1508
|
}
|
1509
|
|
1510
|
return sysmeta;
|
1511
|
}
|
1512
|
|
1513
|
@Override
|
1514
|
public Identifier generateIdentifier(Session session, String scheme, String fragment)
|
1515
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
|
1516
|
InvalidRequest {
|
1517
|
|
1518
|
// check for null session
|
1519
|
if (session == null) {
|
1520
|
throw new InvalidToken("2190", "Session is required to generate an Identifier at this Node.");
|
1521
|
}
|
1522
|
|
1523
|
Identifier identifier = new Identifier();
|
1524
|
|
1525
|
// handle different schemes
|
1526
|
if (scheme.equalsIgnoreCase(UUID_SCHEME)) {
|
1527
|
// UUID
|
1528
|
UUID uuid = UUID.randomUUID();
|
1529
|
identifier.setValue(UUID_PREFIX + uuid.toString());
|
1530
|
} else if (scheme.equalsIgnoreCase(DOI_SCHEME)) {
|
1531
|
// generate a DOI
|
1532
|
try {
|
1533
|
identifier = DOIService.getInstance().generateDOI();
|
1534
|
} catch (EZIDException e) {
|
1535
|
ServiceFailure sf = new ServiceFailure("2191", "Could not generate DOI: " + e.getMessage());
|
1536
|
sf.initCause(e);
|
1537
|
throw sf;
|
1538
|
}
|
1539
|
} else {
|
1540
|
// default if we don't know the scheme
|
1541
|
if (fragment != null) {
|
1542
|
// for now, just autogen with fragment
|
1543
|
String autogenId = DocumentUtil.generateDocumentId(fragment, 0);
|
1544
|
identifier.setValue(autogenId);
|
1545
|
} else {
|
1546
|
// autogen with no fragment
|
1547
|
String autogenId = DocumentUtil.generateDocumentId(0);
|
1548
|
identifier.setValue(autogenId);
|
1549
|
}
|
1550
|
}
|
1551
|
|
1552
|
// TODO: reserve the identifier with the CN. We can only do this when
|
1553
|
// 1) the MN is part of a CN cluster
|
1554
|
// 2) the request is from an authenticated user
|
1555
|
|
1556
|
return identifier;
|
1557
|
}
|
1558
|
|
1559
|
|
1560
|
|
1561
|
@Override
|
1562
|
public QueryEngineDescription getQueryEngineDescription(Session session, String engine)
|
1563
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
|
1564
|
NotFound {
|
1565
|
if(engine != null && engine.equals(EnabledQueryEngines.PATHQUERYENGINE)) {
|
1566
|
if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.PATHQUERYENGINE)) {
|
1567
|
throw new NotImplemented("0000", "MNodeService.query - the query engine "+engine +" hasn't been implemented or has been disabled.");
|
1568
|
}
|
1569
|
QueryEngineDescription qed = new QueryEngineDescription();
|
1570
|
qed.setName(EnabledQueryEngines.PATHQUERYENGINE);
|
1571
|
qed.setQueryEngineVersion("1.0");
|
1572
|
qed.addAdditionalInfo("This is the traditional structured query for Metacat");
|
1573
|
Vector<String> pathsForIndexing = null;
|
1574
|
try {
|
1575
|
pathsForIndexing = SystemUtil.getPathsForIndexing();
|
1576
|
} catch (MetacatUtilException e) {
|
1577
|
logMetacat.warn("Could not get index paths", e);
|
1578
|
}
|
1579
|
for (String fieldName: pathsForIndexing) {
|
1580
|
QueryField field = new QueryField();
|
1581
|
field.addDescription("Indexed field for path '" + fieldName + "'");
|
1582
|
field.setName(fieldName);
|
1583
|
field.setReturnable(true);
|
1584
|
field.setSearchable(true);
|
1585
|
field.setSortable(false);
|
1586
|
// TODO: determine type and multivaluedness
|
1587
|
field.setType(String.class.getName());
|
1588
|
//field.setMultivalued(true);
|
1589
|
qed.addQueryField(field);
|
1590
|
}
|
1591
|
return qed;
|
1592
|
} else if (engine != null && engine.equals(EnabledQueryEngines.SOLRENGINE)) {
|
1593
|
if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.SOLRENGINE)) {
|
1594
|
throw new NotImplemented("0000", "MNodeService.getQueryEngineDescription - the query engine "+engine +" hasn't been implemented or has been disabled.");
|
1595
|
}
|
1596
|
try {
|
1597
|
QueryEngineDescription qed = MetacatSolrEngineDescriptionHandler.getInstance().getQueryEngineDescritpion();
|
1598
|
return qed;
|
1599
|
} catch (Exception e) {
|
1600
|
e.printStackTrace();
|
1601
|
throw new ServiceFailure("Solr server error", e.getMessage());
|
1602
|
}
|
1603
|
} else {
|
1604
|
throw new NotFound("404", "The Metacat member node can't find the query engine - "+engine);
|
1605
|
}
|
1606
|
|
1607
|
}
|
1608
|
|
1609
|
@Override
|
1610
|
public QueryEngineList listQueryEngines(Session session) throws InvalidToken,
|
1611
|
ServiceFailure, NotAuthorized, NotImplemented {
|
1612
|
QueryEngineList qel = new QueryEngineList();
|
1613
|
//qel.addQueryEngine(EnabledQueryEngines.PATHQUERYENGINE);
|
1614
|
//qel.addQueryEngine(EnabledQueryEngines.SOLRENGINE);
|
1615
|
List<String> enables = EnabledQueryEngines.getInstance().getEnabled();
|
1616
|
for(String name : enables) {
|
1617
|
qel.addQueryEngine(name);
|
1618
|
}
|
1619
|
return qel;
|
1620
|
}
|
1621
|
|
1622
|
@Override
|
1623
|
public InputStream query(Session session, String engine, String query) throws InvalidToken,
|
1624
|
ServiceFailure, NotAuthorized, InvalidRequest, NotImplemented,
|
1625
|
NotFound {
|
1626
|
String user = Constants.SUBJECT_PUBLIC;
|
1627
|
String[] groups= null;
|
1628
|
Set<Subject> subjects = null;
|
1629
|
if (session != null) {
|
1630
|
user = session.getSubject().getValue();
|
1631
|
subjects = AuthUtils.authorizedClientSubjects(session);
|
1632
|
if (subjects != null) {
|
1633
|
List<String> groupList = new ArrayList<String>();
|
1634
|
for (Subject subject: subjects) {
|
1635
|
groupList.add(subject.getValue());
|
1636
|
}
|
1637
|
groups = groupList.toArray(new String[0]);
|
1638
|
}
|
1639
|
} else {
|
1640
|
//add the public user subject to the set
|
1641
|
Subject subject = new Subject();
|
1642
|
subject.setValue(Constants.SUBJECT_PUBLIC);
|
1643
|
subjects = new HashSet<Subject>();
|
1644
|
subjects.add(subject);
|
1645
|
}
|
1646
|
//System.out.println("====== user is "+user);
|
1647
|
//System.out.println("====== groups are "+groups);
|
1648
|
if (engine != null && engine.equals(EnabledQueryEngines.PATHQUERYENGINE)) {
|
1649
|
if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.PATHQUERYENGINE)) {
|
1650
|
throw new NotImplemented("0000", "MNodeService.query - the query engine "+engine +" hasn't been implemented or has been disabled.");
|
1651
|
}
|
1652
|
try {
|
1653
|
DBQuery queryobj = new DBQuery();
|
1654
|
|
1655
|
String results = queryobj.performPathquery(query, user, groups);
|
1656
|
ContentTypeByteArrayInputStream ctbais = new ContentTypeByteArrayInputStream(results.getBytes(MetaCatServlet.DEFAULT_ENCODING));
|
1657
|
ctbais.setContentType("text/xml");
|
1658
|
return ctbais;
|
1659
|
|
1660
|
} catch (Exception e) {
|
1661
|
throw new ServiceFailure("Pathquery error", e.getMessage());
|
1662
|
}
|
1663
|
|
1664
|
} else if (engine != null && engine.equals(EnabledQueryEngines.SOLRENGINE)) {
|
1665
|
if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.SOLRENGINE)) {
|
1666
|
throw new NotImplemented("0000", "MNodeService.query - the query engine "+engine +" hasn't been implemented or has been disabled.");
|
1667
|
}
|
1668
|
logMetacat.info("The query is ==================================== \n"+query);
|
1669
|
try {
|
1670
|
|
1671
|
return MetacatSolrIndex.getInstance().query(query, subjects);
|
1672
|
} catch (Exception e) {
|
1673
|
// TODO Auto-generated catch block
|
1674
|
throw new ServiceFailure("Solr server error", e.getMessage());
|
1675
|
}
|
1676
|
}
|
1677
|
return null;
|
1678
|
}
|
1679
|
|
1680
|
/**
|
1681
|
* Given an existing Science Metadata PID, this method mints a DOI
|
1682
|
* and updates the original object "publishing" the update with the DOI.
|
1683
|
* This includes updating the ORE map that describes the Science Metadata+data.
|
1684
|
* TODO: ensure all referenced objects allow public read
|
1685
|
*
|
1686
|
* @see https://projects.ecoinformatics.org/ecoinfo/issues/6014
|
1687
|
*
|
1688
|
* @param originalIdentifier
|
1689
|
* @param request
|
1690
|
* @throws InvalidRequest
|
1691
|
* @throws NotImplemented
|
1692
|
* @throws NotAuthorized
|
1693
|
* @throws ServiceFailure
|
1694
|
* @throws InvalidToken
|
1695
|
* @throws NotFound
|
1696
|
* @throws InvalidSystemMetadata
|
1697
|
* @throws InsufficientResources
|
1698
|
* @throws UnsupportedType
|
1699
|
* @throws IdentifierNotUnique
|
1700
|
*/
|
1701
|
public Identifier publish(Session session, Identifier originalIdentifier) throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented, InvalidRequest, NotFound, IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata {
|
1702
|
|
1703
|
String serviceFailureCode = "1030";
|
1704
|
Identifier sid = getPIDForSID(originalIdentifier, serviceFailureCode);
|
1705
|
if(sid != null) {
|
1706
|
originalIdentifier = sid;
|
1707
|
}
|
1708
|
// get the original SM
|
1709
|
SystemMetadata originalSystemMetadata = this.getSystemMetadata(session, originalIdentifier);
|
1710
|
|
1711
|
// make copy of it using the marshaller to ensure DEEP copy
|
1712
|
SystemMetadata sysmeta = null;
|
1713
|
try {
|
1714
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
1715
|
TypeMarshaller.marshalTypeToOutputStream(originalSystemMetadata, baos);
|
1716
|
sysmeta = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class, new ByteArrayInputStream(baos.toByteArray()));
|
1717
|
} catch (Exception e) {
|
1718
|
// report as service failure
|
1719
|
ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
|
1720
|
sf.initCause(e);
|
1721
|
throw sf;
|
1722
|
}
|
1723
|
|
1724
|
// mint a DOI for the new revision
|
1725
|
Identifier newIdentifier = this.generateIdentifier(session, MNodeService.DOI_SCHEME, null);
|
1726
|
|
1727
|
// set new metadata values
|
1728
|
sysmeta.setIdentifier(newIdentifier);
|
1729
|
sysmeta.setObsoletes(originalIdentifier);
|
1730
|
sysmeta.setObsoletedBy(null);
|
1731
|
|
1732
|
// ensure it is publicly readable
|
1733
|
sysmeta = makePublicIfNot(sysmeta, originalIdentifier);
|
1734
|
|
1735
|
// get the bytes
|
1736
|
InputStream inputStream = this.get(session, originalIdentifier);
|
1737
|
|
1738
|
// update the object
|
1739
|
this.update(session, originalIdentifier, inputStream, newIdentifier, sysmeta);
|
1740
|
|
1741
|
// update ORE that references the scimeta
|
1742
|
// first try the naive method, then check the SOLR index
|
1743
|
try {
|
1744
|
String localId = IdentifierManager.getInstance().getLocalId(originalIdentifier.getValue());
|
1745
|
|
1746
|
Identifier potentialOreIdentifier = new Identifier();
|
1747
|
potentialOreIdentifier.setValue(SystemMetadataFactory.RESOURCE_MAP_PREFIX + localId);
|
1748
|
|
1749
|
InputStream oreInputStream = null;
|
1750
|
try {
|
1751
|
oreInputStream = this.get(session, potentialOreIdentifier);
|
1752
|
} catch (NotFound nf) {
|
1753
|
// this is probably okay for many sci meta data docs
|
1754
|
logMetacat.warn("No potential ORE map found for: " + potentialOreIdentifier.getValue());
|
1755
|
// try the SOLR index
|
1756
|
List<Identifier> potentialOreIdentifiers = this.lookupOreFor(originalIdentifier, false);
|
1757
|
if (potentialOreIdentifiers != null) {
|
1758
|
potentialOreIdentifier = potentialOreIdentifiers.get(0);
|
1759
|
try {
|
1760
|
oreInputStream = this.get(session, potentialOreIdentifier);
|
1761
|
} catch (NotFound nf2) {
|
1762
|
// this is probably okay for many sci meta data docs
|
1763
|
logMetacat.warn("No potential ORE map found for: " + potentialOreIdentifier.getValue());
|
1764
|
}
|
1765
|
}
|
1766
|
}
|
1767
|
if (oreInputStream != null) {
|
1768
|
Identifier newOreIdentifier = MNodeService.getInstance(request).generateIdentifier(session, MNodeService.UUID_SCHEME, null);
|
1769
|
|
1770
|
Map<Identifier, Map<Identifier, List<Identifier>>> resourceMapStructure = ResourceMapFactory.getInstance().parseResourceMap(oreInputStream);
|
1771
|
Map<Identifier, List<Identifier>> sciMetaMap = resourceMapStructure.get(potentialOreIdentifier);
|
1772
|
List<Identifier> dataIdentifiers = sciMetaMap.get(originalIdentifier);
|
1773
|
|
1774
|
// reconstruct the ORE with the new identifiers
|
1775
|
sciMetaMap.remove(originalIdentifier);
|
1776
|
sciMetaMap.put(newIdentifier, dataIdentifiers);
|
1777
|
|
1778
|
ResourceMap resourceMap = ResourceMapFactory.getInstance().createResourceMap(newOreIdentifier, sciMetaMap);
|
1779
|
String resourceMapString = ResourceMapFactory.getInstance().serializeResourceMap(resourceMap);
|
1780
|
|
1781
|
// get the original ORE SM and update the values
|
1782
|
SystemMetadata originalOreSysMeta = this.getSystemMetadata(session, potentialOreIdentifier);
|
1783
|
SystemMetadata oreSysMeta = new SystemMetadata();
|
1784
|
try {
|
1785
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
1786
|
TypeMarshaller.marshalTypeToOutputStream(originalOreSysMeta, baos);
|
1787
|
oreSysMeta = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class, new ByteArrayInputStream(baos.toByteArray()));
|
1788
|
} catch (Exception e) {
|
1789
|
// report as service failure
|
1790
|
ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
|
1791
|
sf.initCause(e);
|
1792
|
throw sf;
|
1793
|
}
|
1794
|
|
1795
|
oreSysMeta.setIdentifier(newOreIdentifier);
|
1796
|
oreSysMeta.setObsoletes(potentialOreIdentifier);
|
1797
|
oreSysMeta.setObsoletedBy(null);
|
1798
|
oreSysMeta.setSize(BigInteger.valueOf(resourceMapString.getBytes("UTF-8").length));
|
1799
|
oreSysMeta.setChecksum(ChecksumUtil.checksum(resourceMapString.getBytes("UTF-8"), oreSysMeta.getChecksum().getAlgorithm()));
|
1800
|
|
1801
|
// ensure ORE is publicly readable
|
1802
|
oreSysMeta = makePublicIfNot(oreSysMeta, potentialOreIdentifier);
|
1803
|
|
1804
|
// ensure all data objects allow public read
|
1805
|
List<String> pidsToSync = new ArrayList<String>();
|
1806
|
for (Identifier dataId: dataIdentifiers) {
|
1807
|
SystemMetadata dataSysMeta = this.getSystemMetadata(session, dataId);
|
1808
|
dataSysMeta = makePublicIfNot(dataSysMeta, dataId);
|
1809
|
this.updateSystemMetadata(dataSysMeta);
|
1810
|
pidsToSync.add(dataId.getValue());
|
1811
|
}
|
1812
|
SyncAccessPolicy sap = new SyncAccessPolicy();
|
1813
|
try {
|
1814
|
sap.sync(pidsToSync);
|
1815
|
} catch (Exception e) {
|
1816
|
// ignore
|
1817
|
logMetacat.warn("Error attempting to sync access for data objects when publishing package");
|
1818
|
}
|
1819
|
|
1820
|
// save the updated ORE
|
1821
|
this.update(
|
1822
|
session,
|
1823
|
potentialOreIdentifier,
|
1824
|
new ByteArrayInputStream(resourceMapString.getBytes("UTF-8")),
|
1825
|
newOreIdentifier,
|
1826
|
oreSysMeta);
|
1827
|
|
1828
|
} else {
|
1829
|
// create a new ORE for them
|
1830
|
// https://projects.ecoinformatics.org/ecoinfo/issues/6194
|
1831
|
try {
|
1832
|
// find the local id for the NEW package.
|
1833
|
String newLocalId = IdentifierManager.getInstance().getLocalId(newIdentifier.getValue());
|
1834
|
|
1835
|
@SuppressWarnings("unused")
|
1836
|
SystemMetadata extraSysMeta = SystemMetadataFactory.createSystemMetadata(newLocalId, true, false);
|
1837
|
// should be done generating the ORE here, and the same permissions were used from the metadata object
|
1838
|
|
1839
|
} catch (Exception e) {
|
1840
|
// oops, guess there was a problem - no package for you
|
1841
|
logMetacat.error("Could not generate new ORE for published object: " + newIdentifier.getValue(), e);
|
1842
|
}
|
1843
|
}
|
1844
|
} catch (McdbDocNotFoundException e) {
|
1845
|
// report as service failure
|
1846
|
ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
|
1847
|
sf.initCause(e);
|
1848
|
throw sf;
|
1849
|
} catch (UnsupportedEncodingException e) {
|
1850
|
// report as service failure
|
1851
|
ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
|
1852
|
sf.initCause(e);
|
1853
|
throw sf;
|
1854
|
} catch (OREException e) {
|
1855
|
// report as service failure
|
1856
|
ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
|
1857
|
sf.initCause(e);
|
1858
|
throw sf;
|
1859
|
} catch (URISyntaxException e) {
|
1860
|
// report as service failure
|
1861
|
ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
|
1862
|
sf.initCause(e);
|
1863
|
throw sf;
|
1864
|
} catch (OREParserException e) {
|
1865
|
// report as service failure
|
1866
|
ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
|
1867
|
sf.initCause(e);
|
1868
|
throw sf;
|
1869
|
} catch (ORESerialiserException e) {
|
1870
|
// report as service failure
|
1871
|
ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
|
1872
|
sf.initCause(e);
|
1873
|
throw sf;
|
1874
|
} catch (NoSuchAlgorithmException e) {
|
1875
|
// report as service failure
|
1876
|
ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
|
1877
|
sf.initCause(e);
|
1878
|
throw sf;
|
1879
|
} catch (SQLException e) {
|
1880
|
// report as service failure
|
1881
|
ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
|
1882
|
sf.initCause(e);
|
1883
|
throw sf;
|
1884
|
}
|
1885
|
|
1886
|
return newIdentifier;
|
1887
|
}
|
1888
|
|
1889
|
/**
|
1890
|
* Determines if we already have registered an ORE map for this package
|
1891
|
* NOTE: uses a solr query to locate OREs for the object
|
1892
|
* @param guid of the EML/packaging object
|
1893
|
* @return list of resource map identifiers for the given pid
|
1894
|
*/
|
1895
|
public List<Identifier> lookupOreFor(Identifier guid, boolean includeObsolete) {
|
1896
|
// Search for the ORE if we can find it
|
1897
|
String pid = guid.getValue();
|
1898
|
List<Identifier> retList = null;
|
1899
|
try {
|
1900
|
String query = "fl=id,resourceMap&wt=xml&q=-obsoletedBy:[* TO *]+resourceMap:[* TO *]+id:\"" + pid + "\"";
|
1901
|
if (includeObsolete) {
|
1902
|
query = "fl=id,resourceMap&wt=xml&q=resourceMap:[* TO *]+id:\"" + pid + "\"";
|
1903
|
}
|
1904
|
|
1905
|
InputStream results = this.query(null, "solr", query);
|
1906
|
org.w3c.dom.Node rootNode = XMLUtilities.getXMLReaderAsDOMTreeRootNode(new InputStreamReader(results, "UTF-8"));
|
1907
|
//String resultString = XMLUtilities.getDOMTreeAsString(rootNode);
|
1908
|
org.w3c.dom.NodeList nodeList = XMLUtilities.getNodeListWithXPath(rootNode, "//arr[@name=\"resourceMap\"]/str");
|
1909
|
if (nodeList != null && nodeList.getLength() > 0) {
|
1910
|
retList = new ArrayList<Identifier>();
|
1911
|
for (int i = 0; i < nodeList.getLength(); i++) {
|
1912
|
String found = nodeList.item(i).getFirstChild().getNodeValue();
|
1913
|
Identifier oreId = new Identifier();
|
1914
|
oreId.setValue(found);
|
1915
|
retList.add(oreId);
|
1916
|
}
|
1917
|
}
|
1918
|
} catch (Exception e) {
|
1919
|
logMetacat.error("Error checking for resourceMap[s] on pid " + pid + ". " + e.getMessage(), e);
|
1920
|
}
|
1921
|
|
1922
|
return retList;
|
1923
|
}
|
1924
|
|
1925
|
|
1926
|
@Override
|
1927
|
public InputStream getPackage(Session session, ObjectFormatIdentifier formatId,
|
1928
|
Identifier pid) throws InvalidToken, ServiceFailure,
|
1929
|
NotAuthorized, InvalidRequest, NotImplemented, NotFound {
|
1930
|
|
1931
|
String serviceFailureCode = "2871";
|
1932
|
Identifier sid = getPIDForSID(pid, serviceFailureCode);
|
1933
|
if(sid != null) {
|
1934
|
pid = sid;
|
1935
|
}
|
1936
|
InputStream bagInputStream = null;
|
1937
|
BagFactory bagFactory = new BagFactory();
|
1938
|
Bag bag = bagFactory.createBag();
|
1939
|
|
1940
|
// track the temp files we use so we can delete them when finished
|
1941
|
List<File> tempFiles = new ArrayList<File>();
|
1942
|
|
1943
|
// the pids to include in the package
|
1944
|
List<Identifier> packagePids = new ArrayList<Identifier>();
|
1945
|
|
1946
|
// catch non-D1 service errors and throw as ServiceFailures
|
1947
|
try {
|
1948
|
//Create a map of dataone ids and file names
|
1949
|
Map<Identifier, String> fileNames = new HashMap<Identifier, String>();
|
1950
|
|
1951
|
// track the pid-to-file mapping
|
1952
|
StringBuffer pidMapping = new StringBuffer();
|
1953
|
|
1954
|
// find the package contents
|
1955
|
SystemMetadata sysMeta = this.getSystemMetadata(session, pid);
|
1956
|
if (ObjectFormatCache.getInstance().getFormat(sysMeta.getFormatId()).getFormatType().equals("RESOURCE")) {
|
1957
|
//Get the resource map as a map of Identifiers
|
1958
|
InputStream oreInputStream = this.get(session, pid);
|
1959
|
Map<Identifier, Map<Identifier, List<Identifier>>> resourceMapStructure = ResourceMapFactory.getInstance().parseResourceMap(oreInputStream);
|
1960
|
packagePids.addAll(resourceMapStructure.keySet());
|
1961
|
//Loop through each object in this resource map
|
1962
|
for (Map<Identifier, List<Identifier>> entries: resourceMapStructure.values()) {
|
1963
|
//Loop through each metadata object in this entry
|
1964
|
Set<Identifier> metadataIdentifiers = entries.keySet();
|
1965
|
for(Identifier metadataID: metadataIdentifiers){
|
1966
|
try{
|
1967
|
//Get the system metadata for this metadata object
|
1968
|
SystemMetadata metadataSysMeta = this.getSystemMetadata(session, metadataID);
|
1969
|
|
1970
|
// include user-friendly metadata
|
1971
|
if (ObjectFormatCache.getInstance().getFormat(metadataSysMeta.getFormatId()).getFormatType().equals("METADATA")) {
|
1972
|
InputStream metadataStream = this.get(session, metadataID);
|
1973
|
|
1974
|
try {
|
1975
|
// transform
|
1976
|
String format = "default";
|
1977
|
|
1978
|
DBTransform transformer = new DBTransform();
|
1979
|
String documentContent = IOUtils.toString(metadataStream, "UTF-8");
|
1980
|
String sourceType = metadataSysMeta.getFormatId().getValue();
|
1981
|
String targetType = "-//W3C//HTML//EN";
|
1982
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
1983
|
Writer writer = new OutputStreamWriter(baos , "UTF-8");
|
1984
|
// TODO: include more params?
|
1985
|
Hashtable<String, String[]> params = new Hashtable<String, String[]>();
|
1986
|
String localId = null;
|
1987
|
try {
|
1988
|
localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
|
1989
|
} catch (McdbDocNotFoundException e) {
|
1990
|
throw new NotFound("1020", e.getMessage());
|
1991
|
}
|
1992
|
params.put("qformat", new String[] {format});
|
1993
|
params.put("docid", new String[] {localId});
|
1994
|
params.put("pid", new String[] {pid.getValue()});
|
1995
|
params.put("displaymodule", new String[] {"printall"});
|
1996
|
|
1997
|
transformer.transformXMLDocument(
|
1998
|
documentContent ,
|
1999
|
sourceType,
|
2000
|
targetType ,
|
2001
|
format,
|
2002
|
writer,
|
2003
|
params,
|
2004
|
null //sessionid
|
2005
|
);
|
2006
|
|
2007
|
// finally, get the HTML back
|
2008
|
ContentTypeByteArrayInputStream resultInputStream = new ContentTypeByteArrayInputStream(baos.toByteArray());
|
2009
|
|
2010
|
// write to temp file with correct css path
|
2011
|
File tmpDir = File.createTempFile("package_", "_dir");
|
2012
|
tmpDir.delete();
|
2013
|
tmpDir.mkdir();
|
2014
|
File htmlFile = File.createTempFile("metadata", ".html", tmpDir);
|
2015
|
File cssDir = new File(tmpDir, format);
|
2016
|
cssDir.mkdir();
|
2017
|
File cssFile = new File(tmpDir, format + "/" + format + ".css");
|
2018
|
String pdfFileName = metadataID.getValue().replaceAll("[^a-zA-Z0-9\\-\\.]", "_") + "-METADATA.pdf";
|
2019
|
File pdfFile = new File(tmpDir, pdfFileName);
|
2020
|
//File pdfFile = File.createTempFile("metadata", ".pdf", tmpDir);
|
2021
|
|
2022
|
// put the CSS file in place for the html to find it
|
2023
|
String originalCssPath = SystemUtil.getContextDir() + "/style/skins/" + format + "/" + format + ".css";
|
2024
|
IOUtils.copy(new FileInputStream(originalCssPath), new FileOutputStream(cssFile));
|
2025
|
|
2026
|
// write the HTML file
|
2027
|
IOUtils.copy(resultInputStream, new FileOutputStream(htmlFile));
|
2028
|
|
2029
|
// convert to PDF
|
2030
|
HtmlToPdf.export(htmlFile.getAbsolutePath(), pdfFile.getAbsolutePath());
|
2031
|
|
2032
|
//add to the package
|
2033
|
bag.addFileToPayload(pdfFile);
|
2034
|
pidMapping.append(metadataID.getValue() + " (pdf)" + "\t" + "data/" + pdfFile.getName() + "\n");
|
2035
|
|
2036
|
// mark for clean up after we are done
|
2037
|
htmlFile.delete();
|
2038
|
cssFile.delete();
|
2039
|
cssDir.delete();
|
2040
|
tempFiles.add(tmpDir);
|
2041
|
tempFiles.add(pdfFile); // delete this first later on
|
2042
|
|
2043
|
} catch (Exception e) {
|
2044
|
logMetacat.warn("Could not transform metadata", e);
|
2045
|
}
|
2046
|
}
|
2047
|
|
2048
|
|
2049
|
//If this is in eml format, extract the filename and GUID from each entity in its package
|
2050
|
if (metadataSysMeta.getFormatId().getValue().startsWith("eml://")) {
|
2051
|
//Get the package
|
2052
|
DataPackageParserInterface parser = new Eml200DataPackageParser();
|
2053
|
InputStream emlStream = this.get(session, metadataID);
|
2054
|
parser.parse(emlStream);
|
2055
|
DataPackage dataPackage = parser.getDataPackage();
|
2056
|
|
2057
|
//Get all the entities in this package and loop through each to extract its ID and file name
|
2058
|
Entity[] entities = dataPackage.getEntityList();
|
2059
|
for(Entity entity: entities){
|
2060
|
try{
|
2061
|
//Get the file name from the metadata
|
2062
|
String fileNameFromMetadata = entity.getName();
|
2063
|
|
2064
|
//Get the ecogrid URL from the metadata
|
2065
|
String ecogridIdentifier = entity.getEntityIdentifier();
|
2066
|
//Parse the ecogrid URL to get the local id
|
2067
|
String idFromMetadata = DocumentUtil.getAccessionNumberFromEcogridIdentifier(ecogridIdentifier);
|
2068
|
|
2069
|
//Get the docid and rev pair
|
2070
|
String docid = DocumentUtil.getDocIdFromString(idFromMetadata);
|
2071
|
String rev = DocumentUtil.getRevisionStringFromString(idFromMetadata);
|
2072
|
|
2073
|
//Get the GUID
|
2074
|
String guid = IdentifierManager.getInstance().getGUID(docid, Integer.valueOf(rev));
|
2075
|
Identifier dataIdentifier = new Identifier();
|
2076
|
dataIdentifier.setValue(guid);
|
2077
|
|
2078
|
//Add the GUID to our GUID & file name map
|
2079
|
fileNames.put(dataIdentifier, fileNameFromMetadata);
|
2080
|
}
|
2081
|
catch(Exception e){
|
2082
|
//Prevent just one entity error
|
2083
|
e.printStackTrace();
|
2084
|
logMetacat.debug(e.getMessage(), e);
|
2085
|
}
|
2086
|
}
|
2087
|
}
|
2088
|
}
|
2089
|
catch(Exception e){
|
2090
|
//Catch errors that would prevent package download
|
2091
|
logMetacat.debug(e.toString());
|
2092
|
}
|
2093
|
}
|
2094
|
packagePids.addAll(entries.keySet());
|
2095
|
for (List<Identifier> dataPids: entries.values()) {
|
2096
|
packagePids.addAll(dataPids);
|
2097
|
}
|
2098
|
}
|
2099
|
} else {
|
2100
|
// just the lone pid in this package
|
2101
|
packagePids.add(pid);
|
2102
|
}
|
2103
|
|
2104
|
//Create a temp file, then delete it and make a directory with that name
|
2105
|
File tempDir = File.createTempFile("temp", Long.toString(System.nanoTime()));
|
2106
|
tempDir.delete();
|
2107
|
tempDir = new File(tempDir.getPath() + "_dir");
|
2108
|
tempDir.mkdir();
|
2109
|
tempFiles.add(tempDir);
|
2110
|
File pidMappingFile = new File(tempDir, "pid-mapping.txt");
|
2111
|
|
2112
|
// loop through the package contents
|
2113
|
for (Identifier entryPid: packagePids) {
|
2114
|
//Get the system metadata for each item
|
2115
|
SystemMetadata entrySysMeta = this.getSystemMetadata(session, entryPid);
|
2116
|
|
2117
|
String objectFormatType = ObjectFormatCache.getInstance().getFormat(entrySysMeta.getFormatId()).getFormatType();
|
2118
|
String fileName = null;
|
2119
|
|
2120
|
//TODO: Be more specific of what characters to replace. Make sure periods arent replaced for the filename from metadata
|
2121
|
//Our default file name is just the ID + format type (e.g. walker.1.1-DATA)
|
2122
|
fileName = entryPid.getValue().replaceAll("[^a-zA-Z0-9\\-\\.]", "_") + "-" + objectFormatType;
|
2123
|
|
2124
|
if(fileNames.containsKey(entryPid)){
|
2125
|
//Let's use the file name and extension from the metadata is we have it
|
2126
|
fileName = entryPid.getValue().replaceAll("[^a-zA-Z0-9\\-\\.]", "_") + "-" + fileNames.get(entryPid).replaceAll("[^a-zA-Z0-9\\-\\.]", "_");
|
2127
|
}
|
2128
|
else{
|
2129
|
//If we couldn't find a given file name, use the system metadata extension
|
2130
|
String extension = ObjectFormatInfo.instance().getExtension(entrySysMeta.getFormatId().getValue());
|
2131
|
fileName += extension;
|
2132
|
}
|
2133
|
|
2134
|
//Create a new file for this item and add to the list
|
2135
|
File tempFile = new File(tempDir, fileName);
|
2136
|
tempFiles.add(tempFile);
|
2137
|
|
2138
|
InputStream entryInputStream = this.get(session, entryPid);
|
2139
|
IOUtils.copy(entryInputStream, new FileOutputStream(tempFile));
|
2140
|
bag.addFileToPayload(tempFile);
|
2141
|
pidMapping.append(entryPid.getValue() + "\t" + "data/" + tempFile.getName() + "\n");
|
2142
|
}
|
2143
|
|
2144
|
//add the the pid to data file map
|
2145
|
IOUtils.write(pidMapping.toString(), new FileOutputStream(pidMappingFile));
|
2146
|
bag.addFileAsTag(pidMappingFile);
|
2147
|
tempFiles.add(pidMappingFile);
|
2148
|
|
2149
|
bag = bag.makeComplete();
|
2150
|
|
2151
|
///Now create the zip file
|
2152
|
//Use the pid as the file name prefix, replacing all non-word characters
|
2153
|
String zipName = pid.getValue().replaceAll("\\W", "_");
|
2154
|
|
2155
|
File bagFile = new File(tempDir, zipName+".zip");
|
2156
|
|
2157
|
bag.setFile(bagFile);
|
2158
|
ZipWriter zipWriter = new ZipWriter(bagFactory);
|
2159
|
bag.write(zipWriter, bagFile);
|
2160
|
bagFile = bag.getFile();
|
2161
|
// use custom FIS that will delete the file when closed
|
2162
|
bagInputStream = new DeleteOnCloseFileInputStream(bagFile);
|
2163
|
// also mark for deletion on shutdown in case the stream is never closed
|
2164
|
bagFile.deleteOnExit();
|
2165
|
tempFiles.add(bagFile);
|
2166
|
|
2167
|
// clean up other temp files
|
2168
|
for (int i=tempFiles.size()-1; i>=0; i--){
|
2169
|
tempFiles.get(i).delete();
|
2170
|
}
|
2171
|
|
2172
|
} catch (IOException e) {
|
2173
|
// report as service failure
|
2174
|
ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
|
2175
|
sf.initCause(e);
|
2176
|
throw sf;
|
2177
|
} catch (OREException e) {
|
2178
|
// report as service failure
|
2179
|
ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
|
2180
|
sf.initCause(e);
|
2181
|
throw sf;
|
2182
|
} catch (URISyntaxException e) {
|
2183
|
// report as service failure
|
2184
|
ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
|
2185
|
sf.initCause(e);
|
2186
|
throw sf;
|
2187
|
} catch (OREParserException e) {
|
2188
|
// report as service failure
|
2189
|
ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
|
2190
|
sf.initCause(e);
|
2191
|
throw sf;
|
2192
|
}
|
2193
|
|
2194
|
return bagInputStream;
|
2195
|
}
|
2196
|
|
2197
|
/**
|
2198
|
* Update the system metadata of the specified pid.
|
2199
|
*/
|
2200
|
@Override
|
2201
|
public boolean updateSystemMetadata(Session session, Identifier pid,
|
2202
|
SystemMetadata sysmeta) throws NotImplemented, NotAuthorized,
|
2203
|
ServiceFailure, InvalidRequest, InvalidSystemMetadata, InvalidToken {
|
2204
|
if(sysmeta == null) {
|
2205
|
throw new InvalidRequest("4863", "The system metadata object should NOT be null in the updateSystemMetadata request.");
|
2206
|
}
|
2207
|
if(pid == null || pid.getValue() == null) {
|
2208
|
throw new InvalidRequest("4863", "Please specify the id in the updateSystemMetadata request ") ;
|
2209
|
}
|
2210
|
|
2211
|
if (session == null) {
|
2212
|
//TODO: many of the thrown exceptions do not use the correct error codes
|
2213
|
//check these against the docs and correct them
|
2214
|
throw new NotAuthorized("4861", "No Session - could not authorize for updating system metadata." +
|
2215
|
" If you are not logged in, please do so and retry the request.");
|
2216
|
} else {
|
2217
|
try {
|
2218
|
//Following session can do the change:
|
2219
|
//- Authoritative Member Node (we can use isNodeAdmin since we checked isAuthoritativeNode )
|
2220
|
//- Owner of object (coved by the userHasPermission method)
|
2221
|
//- user subjects with the change permission
|
2222
|
//Note: Coordinating Node can not because MN is authoritative
|
2223
|
/*if(!isAuthoritativeNode(pid)) {
|
2224
|
throw new InvalidRequest("4863", "Client can only call updateSystemMetadata request on the authoritative memember node.");
|
2225
|
}
|
2226
|
if(!isNodeAdmin(session) && !userHasPermission(session, pid, Permission.CHANGE_PERMISSION)) {
|
2227
|
throw new NotAuthorized("4861", "The client -"+ session.getSubject().getValue()+ "is not authorized for updating the system metadata of the object "+pid.getValue());
|
2228
|
}*/
|
2229
|
if(!allowUpdating(session, pid, Permission.CHANGE_PERMISSION)) {
|
2230
|
throw new NotAuthorized("4861", "The client -"+ session.getSubject().getValue()+ "is not authorized for updating the system metadata of the object "+pid.getValue());
|
2231
|
}
|
2232
|
} catch (NotFound e) {
|
2233
|
throw new InvalidRequest("4863", "Can't determine if the client has the permission to update the system metacat of the object with id "+pid.getValue()+" since "+e.getDescription());
|
2234
|
}
|
2235
|
|
2236
|
}
|
2237
|
//update the system metadata locally
|
2238
|
boolean success = super.updateSystemMetadata(session, pid, sysmeta);
|
2239
|
|
2240
|
if(success) {
|
2241
|
//TODO
|
2242
|
//notify the cns the synchornize the new system metadata.
|
2243
|
this.cn = D1Client.getCN();
|
2244
|
try {
|
2245
|
if(this.cn == null) {
|
2246
|
logMetacat.warn("updateSystemMetadata - can't get the instance of the CN. So the system metadata in CN can't be updated.");
|
2247
|
} else {
|
2248
|
this.cn.synchronize(null, pid);
|
2249
|
}
|
2250
|
} catch (BaseException e) {
|
2251
|
e.printStackTrace();
|
2252
|
logMetacat.error("It is a DataONEBaseException and its detail code is "+e.getDetail_code() +" and its code is "+e.getCode());
|
2253
|
logMetacat.error("Can't update the systemmetadata of pid "+pid.getValue()+" in CNs since "+e.getMessage());
|
2254
|
} catch (Exception e) {
|
2255
|
e.printStackTrace();
|
2256
|
logMetacat.error("Can't update the systemmetadata of pid "+pid.getValue()+" in CNs since "+e.getMessage());
|
2257
|
}
|
2258
|
|
2259
|
// attempt to re-register the identifier (it checks if it is a doi)
|
2260
|
try {
|
2261
|
DOIService.getInstance().registerDOI(sysmeta);
|
2262
|
} catch (Exception e) {
|
2263
|
logMetacat.warn("Could not [re]register DOI: " + e.getMessage(), e);
|
2264
|
}
|
2265
|
}
|
2266
|
return success;
|
2267
|
}
|
2268
|
|
2269
|
/*
|
2270
|
* Determine if the current node is the authoritative node for the given pid.
|
2271
|
*/
|
2272
|
protected boolean isAuthoritativeNode(Identifier pid) {
|
2273
|
boolean isAuthoritativeNode = false;
|
2274
|
if(pid != null && pid.getValue() != null) {
|
2275
|
SystemMetadata sys = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
|
2276
|
if(sys != null) {
|
2277
|
NodeReference node = sys.getAuthoritativeMemberNode();
|
2278
|
if(node != null) {
|
2279
|
String nodeValue = node.getValue();
|
2280
|
logMetacat.debug("The authoritative node for id "+pid.getValue()+" is "+nodeValue);
|
2281
|
//System.out.println("The authoritative node for id "+pid.getValue()+" is "+nodeValue);
|
2282
|
String currentNodeId = Settings.getConfiguration().getString("dataone.nodeId");
|
2283
|
logMetacat.debug("The node id in metacat.properties is "+currentNodeId);
|
2284
|
//System.out.println("The node id in metacat.properties is "+currentNodeId);
|
2285
|
if(currentNodeId != null && !currentNodeId.trim().equals("") && currentNodeId.equals(nodeValue)) {
|
2286
|
logMetacat.debug("They are matching");
|
2287
|
//System.out.println("They are matching");
|
2288
|
isAuthoritativeNode = true;
|
2289
|
}
|
2290
|
}
|
2291
|
}
|
2292
|
}
|
2293
|
return isAuthoritativeNode;
|
2294
|
}
|
2295
|
|
2296
|
/*
|
2297
|
* Rules are:
|
2298
|
* 1. If the session has an cn object, it is allowed.
|
2299
|
* 2. If it is not a cn object, the client should have approperate permission and it should also happen on the authorative node.
|
2300
|
*/
|
2301
|
private boolean allowUpdating(Session session, Identifier pid, Permission permission) throws NotAuthorized, NotFound{
|
2302
|
boolean allow = false;
|
2303
|
if(isCNAdmin (session)) {
|
2304
|
allow = true;
|
2305
|
} else {
|
2306
|
if(isAuthoritativeNode(pid)) {
|
2307
|
if(userHasPermission(session, pid, permission)) {
|
2308
|
allow = true;
|
2309
|
} else {
|
2310
|
allow = false;
|
2311
|
}
|
2312
|
} else {
|
2313
|
throw new NotAuthorized("4861", "Client can only call the request on the authoritative memember node.");
|
2314
|
}
|
2315
|
}
|
2316
|
return allow;
|
2317
|
|
2318
|
}
|
2319
|
|
2320
|
}
|