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: leinfelder $'
|
7
|
* '$Date: 2011-12-08 13:51:10 -0800 (Thu, 08 Dec 2011) $'
|
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.File;
|
27
|
import java.io.FileNotFoundException;
|
28
|
import java.io.FileOutputStream;
|
29
|
import java.io.IOException;
|
30
|
import java.io.InputStream;
|
31
|
import java.io.OutputStream;
|
32
|
import java.sql.SQLException;
|
33
|
import java.util.ArrayList;
|
34
|
import java.util.Calendar;
|
35
|
import java.util.Date;
|
36
|
import java.util.Hashtable;
|
37
|
import java.util.List;
|
38
|
import java.util.Timer;
|
39
|
import java.util.Vector;
|
40
|
|
41
|
import javax.servlet.http.HttpServletRequest;
|
42
|
|
43
|
|
44
|
import org.apache.commons.io.IOUtils;
|
45
|
import org.apache.log4j.Logger;
|
46
|
import org.dataone.client.ObjectFormatCache;
|
47
|
import org.dataone.service.util.Constants;
|
48
|
import org.dataone.service.exceptions.IdentifierNotUnique;
|
49
|
import org.dataone.service.exceptions.InsufficientResources;
|
50
|
import org.dataone.service.exceptions.InvalidRequest;
|
51
|
import org.dataone.service.exceptions.InvalidSystemMetadata;
|
52
|
import org.dataone.service.exceptions.InvalidToken;
|
53
|
import org.dataone.service.exceptions.NotAuthorized;
|
54
|
import org.dataone.service.exceptions.NotFound;
|
55
|
import org.dataone.service.exceptions.NotImplemented;
|
56
|
import org.dataone.service.exceptions.ServiceFailure;
|
57
|
import org.dataone.service.exceptions.UnsupportedType;
|
58
|
import org.dataone.service.types.v1.AccessPolicy;
|
59
|
import org.dataone.service.types.v1.AccessRule;
|
60
|
import org.dataone.service.types.v1.Event;
|
61
|
import org.dataone.service.types.v1.Identifier;
|
62
|
import org.dataone.service.types.v1.Group;
|
63
|
import org.dataone.service.types.v1.Log;
|
64
|
import org.dataone.service.types.v1.LogEntry;
|
65
|
import org.dataone.service.types.v1.NodeReference;
|
66
|
import org.dataone.service.types.v1.ObjectFormat;
|
67
|
import org.dataone.service.types.v1.Permission;
|
68
|
import org.dataone.service.types.v1.Person;
|
69
|
import org.dataone.service.types.v1.Session;
|
70
|
import org.dataone.service.types.v1.Subject;
|
71
|
import org.dataone.service.types.v1.SubjectInfo;
|
72
|
import org.dataone.service.types.v1.SubjectList;
|
73
|
import org.dataone.service.types.v1.SystemMetadata;
|
74
|
import org.dataone.service.types.v1.util.ChecksumUtil;
|
75
|
|
76
|
import edu.ucsb.nceas.metacat.AccessionNumberException;
|
77
|
import edu.ucsb.nceas.metacat.DocumentImpl;
|
78
|
import edu.ucsb.nceas.metacat.EventLog;
|
79
|
import edu.ucsb.nceas.metacat.IdentifierManager;
|
80
|
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
|
81
|
import edu.ucsb.nceas.metacat.MetacatHandler;
|
82
|
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
|
83
|
import edu.ucsb.nceas.metacat.properties.PropertyService;
|
84
|
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
|
85
|
import edu.ucsb.nceas.metacat.util.SystemUtil;
|
86
|
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
|
87
|
|
88
|
public abstract class D1NodeService {
|
89
|
|
90
|
private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
|
91
|
|
92
|
/** For logging the operations */
|
93
|
protected HttpServletRequest request;
|
94
|
|
95
|
/* reference to the metacat handler */
|
96
|
protected MetacatHandler handler;
|
97
|
|
98
|
/* parameters set in the incoming request */
|
99
|
private Hashtable<String, String[]> params;
|
100
|
|
101
|
/**
|
102
|
* Constructor - used to set the metacatUrl from a subclass extending D1NodeService
|
103
|
*
|
104
|
* @param metacatUrl - the URL of the metacat service, including the ending /d1
|
105
|
*/
|
106
|
public D1NodeService(HttpServletRequest request) {
|
107
|
this.request = request;
|
108
|
}
|
109
|
|
110
|
/**
|
111
|
* Adds a new object to the Node, where the object is either a data
|
112
|
* object or a science metadata object. This method is called by clients
|
113
|
* to create new data objects on Member Nodes or internally for Coordinating
|
114
|
* Nodes
|
115
|
*
|
116
|
* @param session - the Session object containing the credentials for the Subject
|
117
|
* @param pid - The object identifier to be created
|
118
|
* @param object - the object bytes
|
119
|
* @param sysmeta - the system metadata that describes the object
|
120
|
*
|
121
|
* @return pid - the object identifier created
|
122
|
*
|
123
|
* @throws InvalidToken
|
124
|
* @throws ServiceFailure
|
125
|
* @throws NotAuthorized
|
126
|
* @throws IdentifierNotUnique
|
127
|
* @throws UnsupportedType
|
128
|
* @throws InsufficientResources
|
129
|
* @throws InvalidSystemMetadata
|
130
|
* @throws NotImplemented
|
131
|
* @throws InvalidRequest
|
132
|
*/
|
133
|
public Identifier create(Session session, Identifier pid, InputStream object,
|
134
|
SystemMetadata sysmeta)
|
135
|
throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique,
|
136
|
UnsupportedType, InsufficientResources, InvalidSystemMetadata,
|
137
|
NotImplemented, InvalidRequest {
|
138
|
|
139
|
Identifier resultPid = null;
|
140
|
String localId = null;
|
141
|
boolean allowed = false;
|
142
|
|
143
|
// check for null session
|
144
|
if (session == null) {
|
145
|
throw new InvalidToken("4894", "Session is required to WRITE to the Node.");
|
146
|
}
|
147
|
Subject subject = session.getSubject();
|
148
|
|
149
|
Subject publicSubject = new Subject();
|
150
|
publicSubject.setValue(Constants.SUBJECT_PUBLIC);
|
151
|
// be sure the user is authenticated for create()
|
152
|
if (subject == null || subject.getValue() == null ||
|
153
|
subject.equals(publicSubject) ) {
|
154
|
throw new NotAuthorized("1100", "The provided identity does not have " +
|
155
|
"permission to WRITE to the Node.");
|
156
|
|
157
|
}
|
158
|
|
159
|
// verify that pid == SystemMetadata.getIdentifier()
|
160
|
logMetacat.debug("Comparing pid|sysmeta_pid: " +
|
161
|
pid.getValue() + "|" + sysmeta.getIdentifier().getValue());
|
162
|
if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
|
163
|
throw new InvalidSystemMetadata("1180",
|
164
|
"The supplied system metadata is invalid. " +
|
165
|
"The identifier " + pid.getValue() + " does not match identifier" +
|
166
|
"in the system metadata identified by " +
|
167
|
sysmeta.getIdentifier().getValue() + ".");
|
168
|
|
169
|
}
|
170
|
|
171
|
logMetacat.debug("Checking if identifier exists...");
|
172
|
// Check that the identifier does not already exist
|
173
|
if (IdentifierManager.getInstance().identifierExists(pid.getValue())) {
|
174
|
throw new IdentifierNotUnique("1120",
|
175
|
"The requested identifier " + pid.getValue() +
|
176
|
" is already used by another object and" +
|
177
|
"therefore can not be used for this object. Clients should choose" +
|
178
|
"a new identifier that is unique and retry the operation or " +
|
179
|
"use CN.reserveIdentifier() to reserve one.");
|
180
|
|
181
|
}
|
182
|
|
183
|
// check that we are not attempting to subvert versioning
|
184
|
if (sysmeta.getObsoletes() != null && sysmeta.getObsoletes().getValue() != null) {
|
185
|
throw new InvalidSystemMetadata("1180",
|
186
|
"The supplied system metadata is invalid. " +
|
187
|
"The obsoletes field cannot have a value when creating entries.");
|
188
|
}
|
189
|
if (sysmeta.getObsoletedBy() != null && sysmeta.getObsoletedBy().getValue() != null) {
|
190
|
throw new InvalidSystemMetadata("1180",
|
191
|
"The supplied system metadata is invalid. " +
|
192
|
"The obsoletedBy field cannot have a value when creating entries.");
|
193
|
}
|
194
|
|
195
|
// TODO: this probably needs to be refined more
|
196
|
try {
|
197
|
allowed = isAuthorized(session, pid, Permission.WRITE);
|
198
|
|
199
|
} catch (NotFound e) {
|
200
|
// The identifier doesn't exist, writing should be fine.
|
201
|
allowed = true;
|
202
|
}
|
203
|
|
204
|
// verify checksum, only if we can reset the inputstream
|
205
|
if (object.markSupported()) {
|
206
|
String checksumAlgorithm = sysmeta.getChecksum().getAlgorithm();
|
207
|
String checksumValue = sysmeta.getChecksum().getValue();
|
208
|
try {
|
209
|
String computedChecksumValue = ChecksumUtil.checksum(object, checksumAlgorithm).getValue();
|
210
|
// it's very important that we don't consume the stream
|
211
|
object.reset();
|
212
|
if (!computedChecksumValue.equals(checksumValue)) {
|
213
|
throw new InvalidSystemMetadata("4896", "Checksum given does not match that of the object");
|
214
|
}
|
215
|
} catch (Exception e) {
|
216
|
String msg = "Error verifying checksum values";
|
217
|
logMetacat.error(msg, e);
|
218
|
throw new ServiceFailure("1190", msg + ": " + e.getMessage());
|
219
|
}
|
220
|
} else {
|
221
|
logMetacat.warn("mark is not supported on the object's input stream - cannot verify checksum without consuming stream");
|
222
|
}
|
223
|
|
224
|
// we have the go ahead
|
225
|
if ( allowed ) {
|
226
|
|
227
|
// Science metadata (XML) or science data object?
|
228
|
// TODO: there are cases where certain object formats are science metadata
|
229
|
// but are not XML (netCDF ...). Handle this.
|
230
|
if ( isScienceMetadata(sysmeta) ) {
|
231
|
|
232
|
// CASE METADATA:
|
233
|
String objectAsXML = "";
|
234
|
try {
|
235
|
objectAsXML = IOUtils.toString(object, "UTF-8");
|
236
|
localId = insertOrUpdateDocument(objectAsXML, pid, session, "insert");
|
237
|
//localId = im.getLocalId(pid.getValue());
|
238
|
|
239
|
} catch (IOException e) {
|
240
|
String msg = "The Node is unable to create the object. " +
|
241
|
"There was a problem converting the object to XML";
|
242
|
logMetacat.info(msg);
|
243
|
throw new ServiceFailure("1190", msg + ": " + e.getMessage());
|
244
|
|
245
|
}
|
246
|
|
247
|
} else {
|
248
|
|
249
|
// DEFAULT CASE: DATA (needs to be checked and completed)
|
250
|
localId = insertDataObject(object, pid, session);
|
251
|
}
|
252
|
|
253
|
}
|
254
|
|
255
|
// save the sysmeta
|
256
|
try {
|
257
|
// lock and unlock of the pid happens in the subclass
|
258
|
HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
|
259
|
|
260
|
} catch (Exception e) {
|
261
|
logMetacat.error("Problem creating system metadata: " + pid.getValue(), e);
|
262
|
throw new ServiceFailure("1190", e.getMessage());
|
263
|
}
|
264
|
|
265
|
// setting the resulting identifier failed
|
266
|
if (localId == null ) {
|
267
|
throw new ServiceFailure("1190", "The Node is unable to create the object. ");
|
268
|
}
|
269
|
|
270
|
resultPid = pid;
|
271
|
|
272
|
return resultPid;
|
273
|
}
|
274
|
|
275
|
/**
|
276
|
* Return the log records associated with a given event between the start and
|
277
|
* end dates listed given a particular Subject listed in the Session
|
278
|
*
|
279
|
* @param session - the Session object containing the credentials for the Subject
|
280
|
* @param fromDate - the start date of the desired log records
|
281
|
* @param toDate - the end date of the desired log records
|
282
|
* @param event - restrict log records of a specific event type
|
283
|
* @param start - zero based offset from the first record in the
|
284
|
* set of matching log records. Used to assist with
|
285
|
* paging the response.
|
286
|
* @param count - maximum number of log records to return in the response.
|
287
|
* Used to assist with paging the response.
|
288
|
*
|
289
|
* @return the desired log records
|
290
|
*
|
291
|
* @throws InvalidToken
|
292
|
* @throws ServiceFailure
|
293
|
* @throws NotAuthorized
|
294
|
* @throws InvalidRequest
|
295
|
* @throws NotImplemented
|
296
|
*/
|
297
|
public Log getLogRecords(Session session, Date fromDate, Date toDate,
|
298
|
Event event, Integer start, Integer count) throws InvalidToken, ServiceFailure,
|
299
|
NotAuthorized, InvalidRequest, NotImplemented {
|
300
|
|
301
|
|
302
|
Log log = new Log();
|
303
|
List<LogEntry> logs = new Vector<LogEntry>();
|
304
|
IdentifierManager im = IdentifierManager.getInstance();
|
305
|
EventLog el = EventLog.getInstance();
|
306
|
if ( fromDate == null ) {
|
307
|
logMetacat.debug("setting fromdate from null");
|
308
|
fromDate = new Date(1);
|
309
|
}
|
310
|
if ( toDate == null ) {
|
311
|
logMetacat.debug("setting todate from null");
|
312
|
toDate = new Date();
|
313
|
}
|
314
|
|
315
|
if ( start == null ) {
|
316
|
start = 0;
|
317
|
|
318
|
}
|
319
|
|
320
|
if ( count == null ) {
|
321
|
count = 1000;
|
322
|
|
323
|
}
|
324
|
|
325
|
logMetacat.debug("fromDate: " + fromDate);
|
326
|
logMetacat.debug("toDate: " + toDate);
|
327
|
|
328
|
String report = el.getReport(null, null, null, null,
|
329
|
new java.sql.Timestamp(fromDate.getTime()),
|
330
|
new java.sql.Timestamp(toDate.getTime()), false);
|
331
|
|
332
|
logMetacat.debug("report: " + report);
|
333
|
|
334
|
String logEntry = "<logEntry>";
|
335
|
String endLogEntry = "</logEntry>";
|
336
|
int startIndex = 0;
|
337
|
int foundIndex = report.indexOf(logEntry, startIndex);
|
338
|
while (foundIndex != -1) {
|
339
|
// parse out each entry
|
340
|
int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
|
341
|
String entry = report.substring(foundIndex, endEntryIndex);
|
342
|
logMetacat.debug("entry: " + entry);
|
343
|
startIndex = endEntryIndex + endLogEntry.length();
|
344
|
foundIndex = report.indexOf(logEntry, startIndex);
|
345
|
|
346
|
String entryId = getLogEntryField("entryid", entry);
|
347
|
String ipAddress = getLogEntryField("ipAddress", entry);
|
348
|
String principal = getLogEntryField("principal", entry);
|
349
|
String userAgent = getLogEntryField("userAgent", entry);
|
350
|
String docid = getLogEntryField("docid", entry);
|
351
|
String eventS = getLogEntryField("event", entry);
|
352
|
String dateLogged = getLogEntryField("dateLogged", entry);
|
353
|
|
354
|
LogEntry le = new LogEntry();
|
355
|
|
356
|
Event e = Event.convert(eventS);
|
357
|
if (e == null) { // skip any events that are not Dataone Crud events
|
358
|
continue;
|
359
|
}
|
360
|
le.setEvent(e);
|
361
|
le.setEntryId(entryId);
|
362
|
Identifier identifier = new Identifier();
|
363
|
try {
|
364
|
logMetacat.debug("converting docid '" + docid + "' to a pid.");
|
365
|
if (docid == null || docid.trim().equals("") || docid.trim().equals("null")) {
|
366
|
continue;
|
367
|
}
|
368
|
docid = docid.substring(0, docid.lastIndexOf("."));
|
369
|
identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
|
370
|
} catch (Exception ex) {
|
371
|
// try to get the pid, if that doesn't
|
372
|
// work, just use the local id
|
373
|
// throw new ServiceFailure("1030",
|
374
|
// "Error getting pid for localId " +
|
375
|
// docid + ": " + ex.getMessage());\
|
376
|
|
377
|
// skip it if the pid can't be found
|
378
|
continue;
|
379
|
}
|
380
|
|
381
|
le.setIdentifier(identifier);
|
382
|
le.setIpAddress(ipAddress);
|
383
|
Calendar c = Calendar.getInstance();
|
384
|
String year = dateLogged.substring(0, 4);
|
385
|
String month = dateLogged.substring(5, 7);
|
386
|
String date = dateLogged.substring(8, 10);
|
387
|
logMetacat.debug("year: " + year + " month: " + month + " day: " + date);
|
388
|
c.set(new Integer(year).intValue(), new Integer(month).intValue(),
|
389
|
new Integer(date).intValue());
|
390
|
Date logDate = c.getTime();
|
391
|
le.setDateLogged(logDate);
|
392
|
NodeReference memberNode = new NodeReference();
|
393
|
memberNode.setValue(ipAddress);
|
394
|
le.setNodeIdentifier(memberNode);
|
395
|
Subject princ = new Subject();
|
396
|
princ.setValue(principal);
|
397
|
le.setSubject(princ);
|
398
|
le.setUserAgent(userAgent);
|
399
|
|
400
|
// event filtering?
|
401
|
if (event == null) {
|
402
|
logs.add(le);
|
403
|
} else if (le.getEvent().equals(event)) {
|
404
|
logs.add(le);
|
405
|
}
|
406
|
}
|
407
|
|
408
|
// d1 paging
|
409
|
int total = logs.size();
|
410
|
if (start != null && count != null) {
|
411
|
int toIndex = start + count;
|
412
|
if (toIndex <= total) {
|
413
|
logs = new ArrayList<LogEntry>(logs.subList(start, toIndex));
|
414
|
}
|
415
|
}
|
416
|
|
417
|
log.setLogEntryList(logs);
|
418
|
log.setStart(start);
|
419
|
log.setCount(logs.size());
|
420
|
log.setTotal(total);
|
421
|
logMetacat.info("getLogRecords");
|
422
|
return log;
|
423
|
}
|
424
|
|
425
|
/**
|
426
|
* Return the object identified by the given object identifier
|
427
|
*
|
428
|
* @param session - the Session object containing the credentials for the Subject
|
429
|
* @param pid - the object identifier for the given object
|
430
|
*
|
431
|
* TODO: The D1 Authorization API doesn't provide information on which
|
432
|
* authentication system the Subject belongs to, and so it's not possible to
|
433
|
* discern which Person or Group is a valid KNB LDAP DN. Fix this.
|
434
|
*
|
435
|
* @return inputStream - the input stream of the given object
|
436
|
*
|
437
|
* @throws InvalidToken
|
438
|
* @throws ServiceFailure
|
439
|
* @throws NotAuthorized
|
440
|
* @throws InvalidRequest
|
441
|
* @throws NotImplemented
|
442
|
*/
|
443
|
public InputStream get(Session session, Identifier pid)
|
444
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
445
|
NotImplemented {
|
446
|
|
447
|
InputStream inputStream = null; // bytes to be returned
|
448
|
handler = new MetacatHandler(new Timer());
|
449
|
boolean allowed = false;
|
450
|
String localId; // the metacat docid for the pid
|
451
|
|
452
|
// get the local docid from Metacat
|
453
|
try {
|
454
|
localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
|
455
|
|
456
|
} catch (McdbDocNotFoundException e) {
|
457
|
throw new NotFound("1020", "The object specified by " +
|
458
|
pid.getValue() +
|
459
|
" does not exist at this node.");
|
460
|
}
|
461
|
|
462
|
// check for authorization
|
463
|
allowed = isAuthorized(session, pid, Permission.READ);
|
464
|
|
465
|
// if the person is authorized, perform the read
|
466
|
if (allowed) {
|
467
|
try {
|
468
|
inputStream = handler.read(localId);
|
469
|
} catch (Exception e) {
|
470
|
throw new ServiceFailure("1020", "The object specified by " +
|
471
|
pid.getValue() +
|
472
|
"could not be returned due to error: " +
|
473
|
e.getMessage());
|
474
|
}
|
475
|
}
|
476
|
|
477
|
// if we fail to set the input stream
|
478
|
if ( inputStream == null ) {
|
479
|
throw new NotFound("1020", "The object specified by " +
|
480
|
pid.getValue() +
|
481
|
"does not exist at this node.");
|
482
|
}
|
483
|
|
484
|
// log the read event
|
485
|
String principal = Constants.SUBJECT_PUBLIC;
|
486
|
if (session != null && session.getSubject() != null) {
|
487
|
principal = session.getSubject().getValue();
|
488
|
}
|
489
|
EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "read");
|
490
|
|
491
|
return inputStream;
|
492
|
}
|
493
|
|
494
|
/**
|
495
|
* Return the system metadata for a given object
|
496
|
*
|
497
|
* @param session - the Session object containing the credentials for the Subject
|
498
|
* @param pid - the object identifier for the given object
|
499
|
*
|
500
|
* @return inputStream - the input stream of the given system metadata object
|
501
|
*
|
502
|
* @throws InvalidToken
|
503
|
* @throws ServiceFailure
|
504
|
* @throws NotAuthorized
|
505
|
* @throws NotFound
|
506
|
* @throws InvalidRequest
|
507
|
* @throws NotImplemented
|
508
|
*/
|
509
|
public SystemMetadata getSystemMetadata(Session session, Identifier pid)
|
510
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
511
|
NotImplemented {
|
512
|
|
513
|
if (!isAuthorized(session, pid, Permission.READ)) {
|
514
|
throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());
|
515
|
}
|
516
|
SystemMetadata systemMetadata = null;
|
517
|
try {
|
518
|
HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
|
519
|
systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
|
520
|
HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
|
521
|
|
522
|
} catch (Exception e) {
|
523
|
// convert hazelcast RuntimeException to NotFound
|
524
|
throw new NotFound("1420", "No record found for: " + pid.getValue());
|
525
|
|
526
|
}
|
527
|
|
528
|
return systemMetadata;
|
529
|
}
|
530
|
|
531
|
/**
|
532
|
* Test if the user identified by the provided token has authorization
|
533
|
* for operation on the specified object.
|
534
|
*
|
535
|
* @param session - the Session object containing the credentials for the Subject
|
536
|
* @param pid - The identifer of the resource for which access is being checked
|
537
|
* @param operation - The type of operation which is being requested for the given pid
|
538
|
*
|
539
|
* @return true if the operation is allowed
|
540
|
*
|
541
|
* @throws ServiceFailure
|
542
|
* @throws InvalidToken
|
543
|
* @throws NotFound
|
544
|
* @throws NotAuthorized
|
545
|
* @throws NotImplemented
|
546
|
* @throws InvalidRequest
|
547
|
*/
|
548
|
public boolean isAuthorized(Session session, Identifier pid, Permission permission)
|
549
|
throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
|
550
|
NotImplemented {
|
551
|
|
552
|
boolean allowed = false;
|
553
|
|
554
|
// get the subjects from the session
|
555
|
List<Subject> subjects = new ArrayList<Subject>();
|
556
|
if (session != null) {
|
557
|
Subject subject = session.getSubject();
|
558
|
if (subject != null) {
|
559
|
subjects.add(subject);
|
560
|
}
|
561
|
SubjectInfo subjectInfo = session.getSubjectInfo();
|
562
|
if (subjectInfo != null) {
|
563
|
List<Person> personList = subjectInfo.getPersonList();
|
564
|
if (personList != null) {
|
565
|
for (Person p: personList) {
|
566
|
subjects.add(p.getSubject());
|
567
|
if (p.getVerified()) {
|
568
|
// add the verified symbolic user
|
569
|
Subject verifiedSubject = new Subject();
|
570
|
verifiedSubject.setValue(Constants.SUBJECT_VERIFIED_USER);
|
571
|
if (!subjects.contains(verifiedSubject)) {
|
572
|
subjects.add(verifiedSubject);
|
573
|
}
|
574
|
}
|
575
|
}
|
576
|
}
|
577
|
List<Group> groupList = subjectInfo.getGroupList();
|
578
|
if (groupList != null) {
|
579
|
for (Group g: groupList) {
|
580
|
subjects.add(g.getSubject());
|
581
|
}
|
582
|
}
|
583
|
}
|
584
|
// add the authenticated symbolic as a check
|
585
|
Subject authenticatedSubject = new Subject();
|
586
|
authenticatedSubject.setValue(Constants.SUBJECT_AUTHENTICATED_USER);
|
587
|
subjects.add(authenticatedSubject);
|
588
|
|
589
|
}
|
590
|
|
591
|
// add public subject
|
592
|
Subject publicSubject = new Subject();
|
593
|
publicSubject.setValue(Constants.SUBJECT_PUBLIC);
|
594
|
subjects.add(publicSubject);
|
595
|
|
596
|
// get the system metadata
|
597
|
String pidStr = pid.getValue();
|
598
|
SystemMetadata systemMetadata = null;
|
599
|
try {
|
600
|
HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
|
601
|
systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
|
602
|
HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
|
603
|
|
604
|
} catch (Exception e) {
|
605
|
// convert Hazelcast RuntimeException to NotFound
|
606
|
logMetacat.error("An error occurred while getting system metadata for identifier " +
|
607
|
pid.getValue() + ". The error message was: " + e.getMessage());
|
608
|
throw new NotFound("1800", "No record found for " + pidStr);
|
609
|
|
610
|
} finally {
|
611
|
HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
|
612
|
|
613
|
}
|
614
|
|
615
|
// throw not found if it was not found
|
616
|
if (systemMetadata == null) {
|
617
|
throw new NotFound("1800", "No system metadata could be found for given PID: " + pidStr);
|
618
|
}
|
619
|
|
620
|
// do we own it?
|
621
|
for (Subject s: subjects) {
|
622
|
allowed = systemMetadata.getRightsHolder().equals(s);
|
623
|
if (allowed) {
|
624
|
return allowed;
|
625
|
}
|
626
|
}
|
627
|
|
628
|
// otherwise check the access rules
|
629
|
try {
|
630
|
List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
|
631
|
search: // label break
|
632
|
for (AccessRule accessRule: allows) {
|
633
|
for (Subject s: subjects) {
|
634
|
//if (accessRule.getSubjectList().contains(s)) {
|
635
|
for (Subject ruleSubject: accessRule.getSubjectList()) {
|
636
|
if (ruleSubject.equals(s)) {
|
637
|
allowed = accessRule.getPermissionList().contains(permission);
|
638
|
if (allowed) {
|
639
|
break search; //label break
|
640
|
}
|
641
|
}
|
642
|
}
|
643
|
}
|
644
|
}
|
645
|
} catch (Exception e) {
|
646
|
// catch all for errors - safe side should be to deny the access
|
647
|
logMetacat.error("Problem checking authorization - defaulting to deny", e);
|
648
|
allowed = false;
|
649
|
}
|
650
|
|
651
|
// throw or return?
|
652
|
if (!allowed) {
|
653
|
throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
|
654
|
}
|
655
|
|
656
|
return allowed;
|
657
|
|
658
|
}
|
659
|
|
660
|
/*
|
661
|
* parse a logEntry and get the relevant field from it
|
662
|
*
|
663
|
* @param fieldname
|
664
|
* @param entry
|
665
|
* @return
|
666
|
*/
|
667
|
private String getLogEntryField(String fieldname, String entry) {
|
668
|
String begin = "<" + fieldname + ">";
|
669
|
String end = "</" + fieldname + ">";
|
670
|
// logMetacat.debug("looking for " + begin + " and " + end +
|
671
|
// " in entry " + entry);
|
672
|
String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
|
673
|
.indexOf(end));
|
674
|
logMetacat.debug("entry " + fieldname + " : " + s);
|
675
|
return s;
|
676
|
}
|
677
|
|
678
|
/**
|
679
|
* Determine if a given object should be treated as an XML science metadata
|
680
|
* object.
|
681
|
*
|
682
|
* @param sysmeta - the SystemMetadata describing the object
|
683
|
* @return true if the object should be treated as science metadata
|
684
|
*/
|
685
|
public static boolean isScienceMetadata(SystemMetadata sysmeta) {
|
686
|
|
687
|
ObjectFormat objectFormat = null;
|
688
|
boolean isScienceMetadata = false;
|
689
|
|
690
|
try {
|
691
|
objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
|
692
|
if ( objectFormat.getFormatType().equals("METADATA") ) {
|
693
|
isScienceMetadata = true;
|
694
|
|
695
|
}
|
696
|
|
697
|
} catch (InvalidRequest e) {
|
698
|
logMetacat.debug("There was a problem determining if the object identified by" +
|
699
|
sysmeta.getIdentifier().getValue() +
|
700
|
" is science metadata: " + e.getMessage());
|
701
|
|
702
|
} catch (ServiceFailure e) {
|
703
|
logMetacat.debug("There was a problem determining if the object identified by" +
|
704
|
sysmeta.getIdentifier().getValue() +
|
705
|
" is science metadata: " + e.getMessage());
|
706
|
|
707
|
} catch (NotFound e) {
|
708
|
logMetacat.debug("There was a problem determining if the object identified by" +
|
709
|
sysmeta.getIdentifier().getValue() +
|
710
|
" is science metadata: " + e.getMessage());
|
711
|
|
712
|
} catch (InsufficientResources e) {
|
713
|
logMetacat.debug("There was a problem determining if the object identified by" +
|
714
|
sysmeta.getIdentifier().getValue() +
|
715
|
" is science metadata: " + e.getMessage());
|
716
|
|
717
|
} catch (NotImplemented e) {
|
718
|
logMetacat.debug("There was a problem determining if the object identified by" +
|
719
|
sysmeta.getIdentifier().getValue() +
|
720
|
" is science metadata: " + e.getMessage());
|
721
|
|
722
|
}
|
723
|
|
724
|
return isScienceMetadata;
|
725
|
|
726
|
}
|
727
|
|
728
|
/**
|
729
|
* Insert or update an XML document into Metacat
|
730
|
*
|
731
|
* @param xml - the XML document to insert or update
|
732
|
* @param pid - the identifier to be used for the resulting object
|
733
|
*
|
734
|
* @return localId - the resulting docid of the document created or updated
|
735
|
*
|
736
|
*/
|
737
|
protected String insertOrUpdateDocument(String xml, Identifier pid,
|
738
|
Session session, String insertOrUpdate)
|
739
|
throws ServiceFailure {
|
740
|
|
741
|
logMetacat.debug("Starting to insert xml document...");
|
742
|
IdentifierManager im = IdentifierManager.getInstance();
|
743
|
|
744
|
// generate pid/localId pair for sysmeta
|
745
|
String localId = null;
|
746
|
|
747
|
if(insertOrUpdate.equals("insert")) {
|
748
|
localId = im.generateLocalId(pid.getValue(), 1);
|
749
|
|
750
|
} else {
|
751
|
//localid should already exist in the identifier table, so just find it
|
752
|
try {
|
753
|
logMetacat.debug("Updating pid " + pid.getValue());
|
754
|
logMetacat.debug("looking in identifier table for pid " + pid.getValue());
|
755
|
|
756
|
localId = im.getLocalId(pid.getValue());
|
757
|
|
758
|
logMetacat.debug("localId: " + localId);
|
759
|
//increment the revision
|
760
|
String docid = localId.substring(0, localId.lastIndexOf("."));
|
761
|
String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
|
762
|
int rev = new Integer(revS).intValue();
|
763
|
rev++;
|
764
|
docid = docid + "." + rev;
|
765
|
localId = docid;
|
766
|
logMetacat.debug("incremented localId: " + localId);
|
767
|
|
768
|
} catch(McdbDocNotFoundException e) {
|
769
|
throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
|
770
|
"pid " + pid.getValue() +
|
771
|
" should have been in the identifier table, but it wasn't: " +
|
772
|
e.getMessage());
|
773
|
|
774
|
}
|
775
|
|
776
|
}
|
777
|
|
778
|
params = new Hashtable<String, String[]>();
|
779
|
String[] action = new String[1];
|
780
|
action[0] = insertOrUpdate;
|
781
|
params.put("action", action);
|
782
|
String[] docid = new String[1];
|
783
|
docid[0] = localId;
|
784
|
params.put("docid", docid);
|
785
|
String[] doctext = new String[1];
|
786
|
doctext[0] = xml;
|
787
|
params.put("doctext", doctext);
|
788
|
|
789
|
String username = Constants.SUBJECT_PUBLIC;
|
790
|
String[] groupnames = null;
|
791
|
if (session != null ) {
|
792
|
username = session.getSubject().getValue();
|
793
|
if (session.getSubjectInfo() != null) {
|
794
|
List<Group> groupList = session.getSubjectInfo().getGroupList();
|
795
|
if (groupList != null) {
|
796
|
groupnames = new String[groupList.size()];
|
797
|
for (int i = 0; i > groupList.size(); i++ ) {
|
798
|
groupnames[i] = groupList.get(i).getGroupName();
|
799
|
}
|
800
|
}
|
801
|
}
|
802
|
}
|
803
|
|
804
|
// do the insert or update action
|
805
|
handler = new MetacatHandler(new Timer());
|
806
|
String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null,
|
807
|
null, params, username, groupnames);
|
808
|
|
809
|
if(result.indexOf("<error>") != -1) {
|
810
|
String detailCode = "";
|
811
|
if ( insertOrUpdate.equals("insert") ) {
|
812
|
detailCode = "1190";
|
813
|
|
814
|
} else if ( insertOrUpdate.equals("update") ) {
|
815
|
detailCode = "1310";
|
816
|
|
817
|
}
|
818
|
throw new ServiceFailure(detailCode,
|
819
|
"Error inserting or updating document: " + result);
|
820
|
}
|
821
|
logMetacat.debug("Finsished inserting xml document with id " + localId);
|
822
|
|
823
|
return localId;
|
824
|
}
|
825
|
|
826
|
/**
|
827
|
* Insert a data document
|
828
|
*
|
829
|
* @param object
|
830
|
* @param pid
|
831
|
* @param sessionData
|
832
|
* @throws ServiceFailure
|
833
|
* @returns localId of the data object inserted
|
834
|
*/
|
835
|
protected String insertDataObject(InputStream object, Identifier pid,
|
836
|
Session session) throws ServiceFailure {
|
837
|
|
838
|
String username = Constants.SUBJECT_PUBLIC;
|
839
|
String[] groupnames = null;
|
840
|
if (session != null ) {
|
841
|
username = session.getSubject().getValue();
|
842
|
if (session.getSubjectInfo() != null) {
|
843
|
List<Group> groupList = session.getSubjectInfo().getGroupList();
|
844
|
if (groupList != null) {
|
845
|
groupnames = new String[groupList.size()];
|
846
|
for (int i = 0; i > groupList.size(); i++ ) {
|
847
|
groupnames[i] = groupList.get(i).getGroupName();
|
848
|
}
|
849
|
}
|
850
|
}
|
851
|
}
|
852
|
|
853
|
// generate pid/localId pair for object
|
854
|
logMetacat.debug("Generating a pid/localId mapping");
|
855
|
IdentifierManager im = IdentifierManager.getInstance();
|
856
|
String localId = im.generateLocalId(pid.getValue(), 1);
|
857
|
|
858
|
// Save the data file to disk using "localId" as the name
|
859
|
String datafilepath = null;
|
860
|
try {
|
861
|
datafilepath = PropertyService.getProperty("application.datafilepath");
|
862
|
} catch (PropertyNotFoundException e) {
|
863
|
ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
|
864
|
sf.initCause(e);
|
865
|
throw sf;
|
866
|
}
|
867
|
boolean locked = false;
|
868
|
try {
|
869
|
locked = DocumentImpl.getDataFileLockGrant(localId);
|
870
|
} catch (Exception e) {
|
871
|
ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
|
872
|
sf.initCause(e);
|
873
|
throw sf;
|
874
|
}
|
875
|
|
876
|
logMetacat.debug("Case DATA: starting to write to disk.");
|
877
|
if (locked) {
|
878
|
|
879
|
File dataDirectory = new File(datafilepath);
|
880
|
dataDirectory.mkdirs();
|
881
|
|
882
|
File newFile = writeStreamToFile(dataDirectory, localId, object);
|
883
|
|
884
|
// TODO: Check that the file size matches SystemMetadata
|
885
|
// long size = newFile.length();
|
886
|
// if (size == 0) {
|
887
|
// throw new IOException("Uploaded file is 0 bytes!");
|
888
|
// }
|
889
|
|
890
|
// Register the file in the database (which generates an exception
|
891
|
// if the localId is not acceptable or other untoward things happen
|
892
|
try {
|
893
|
logMetacat.debug("Registering document...");
|
894
|
DocumentImpl.registerDocument(localId, "BIN", localId,
|
895
|
username, groupnames);
|
896
|
logMetacat.debug("Registration step completed.");
|
897
|
|
898
|
} catch (SQLException e) {
|
899
|
//newFile.delete();
|
900
|
logMetacat.debug("SQLE: " + e.getMessage());
|
901
|
e.printStackTrace(System.out);
|
902
|
throw new ServiceFailure("1190", "Registration failed: " +
|
903
|
e.getMessage());
|
904
|
|
905
|
} catch (AccessionNumberException e) {
|
906
|
//newFile.delete();
|
907
|
logMetacat.debug("ANE: " + e.getMessage());
|
908
|
e.printStackTrace(System.out);
|
909
|
throw new ServiceFailure("1190", "Registration failed: " +
|
910
|
e.getMessage());
|
911
|
|
912
|
} catch (Exception e) {
|
913
|
//newFile.delete();
|
914
|
logMetacat.debug("Exception: " + e.getMessage());
|
915
|
e.printStackTrace(System.out);
|
916
|
throw new ServiceFailure("1190", "Registration failed: " +
|
917
|
e.getMessage());
|
918
|
}
|
919
|
|
920
|
logMetacat.debug("Logging the creation event.");
|
921
|
EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
|
922
|
|
923
|
// Schedule replication for this data file
|
924
|
logMetacat.debug("Scheduling replication.");
|
925
|
ForceReplicationHandler frh = new ForceReplicationHandler(
|
926
|
localId, "create", false, null);
|
927
|
}
|
928
|
|
929
|
return localId;
|
930
|
|
931
|
}
|
932
|
|
933
|
/**
|
934
|
* Insert a systemMetadata document and return its localId
|
935
|
*/
|
936
|
protected void insertSystemMetadata(SystemMetadata sysmeta)
|
937
|
throws ServiceFailure {
|
938
|
|
939
|
logMetacat.debug("Starting to insert SystemMetadata...");
|
940
|
sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
|
941
|
logMetacat.debug("Inserting new system metadata with modified date " +
|
942
|
sysmeta.getDateSysMetadataModified());
|
943
|
|
944
|
//insert the system metadata
|
945
|
try {
|
946
|
// note: the calling subclass handles the map hazelcast lock/unlock
|
947
|
HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
|
948
|
|
949
|
} catch (Exception e) {
|
950
|
throw new ServiceFailure("1190", e.getMessage());
|
951
|
|
952
|
}
|
953
|
}
|
954
|
|
955
|
/**
|
956
|
* Update a systemMetadata document
|
957
|
*
|
958
|
* @param sysMeta - the system metadata object in the system to update
|
959
|
*/
|
960
|
protected void updateSystemMetadata(SystemMetadata sysMeta)
|
961
|
throws ServiceFailure {
|
962
|
|
963
|
logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
|
964
|
sysMeta.setDateSysMetadataModified(new Date());
|
965
|
try {
|
966
|
HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
|
967
|
HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
|
968
|
HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
|
969
|
} catch (Exception e) {
|
970
|
throw new ServiceFailure("4862", e.getMessage());
|
971
|
} finally {
|
972
|
HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
|
973
|
}
|
974
|
|
975
|
}
|
976
|
|
977
|
/*
|
978
|
* Write a stream to a file
|
979
|
*
|
980
|
* @param dir - the directory to write to
|
981
|
* @param fileName - the file name to write to
|
982
|
* @param data - the object bytes as an input stream
|
983
|
*
|
984
|
* @return newFile - the new file created
|
985
|
*
|
986
|
* @throws ServiceFailure
|
987
|
*/
|
988
|
private File writeStreamToFile(File dir, String fileName, InputStream data)
|
989
|
throws ServiceFailure {
|
990
|
|
991
|
File newFile = new File(dir, fileName);
|
992
|
logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
|
993
|
|
994
|
try {
|
995
|
if (newFile.createNewFile()) {
|
996
|
// write data stream to desired file
|
997
|
OutputStream os = new FileOutputStream(newFile);
|
998
|
long length = IOUtils.copyLarge(data, os);
|
999
|
os.flush();
|
1000
|
os.close();
|
1001
|
} else {
|
1002
|
logMetacat.debug("File creation failed, or file already exists.");
|
1003
|
throw new ServiceFailure("1190", "File already exists: " + fileName);
|
1004
|
}
|
1005
|
} catch (FileNotFoundException e) {
|
1006
|
logMetacat.debug("FNF: " + e.getMessage());
|
1007
|
throw new ServiceFailure("1190", "File not found: " + fileName + " "
|
1008
|
+ e.getMessage());
|
1009
|
} catch (IOException e) {
|
1010
|
logMetacat.debug("IOE: " + e.getMessage());
|
1011
|
throw new ServiceFailure("1190", "File was not written: " + fileName
|
1012
|
+ " " + e.getMessage());
|
1013
|
}
|
1014
|
|
1015
|
return newFile;
|
1016
|
}
|
1017
|
|
1018
|
}
|