1
|
/**
|
2
|
* '$RCSfile$'
|
3
|
* Copyright: 2000 Regents of the University of California and the
|
4
|
* National Center for Ecological Analysis and Synthesis
|
5
|
*
|
6
|
* '$Author: $'
|
7
|
* '$Date: 2009-06-13 15:28:13 +0300 $'
|
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
|
package edu.ucsb.nceas.metacat.dataone;
|
24
|
|
25
|
import java.io.ByteArrayOutputStream;
|
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.io.PrintWriter;
|
33
|
import java.sql.SQLException;
|
34
|
import java.util.*;
|
35
|
import java.text.DateFormat;
|
36
|
|
37
|
import javax.servlet.ServletContext;
|
38
|
import javax.servlet.http.HttpServletRequest;
|
39
|
import javax.servlet.http.HttpServletResponse;
|
40
|
|
41
|
import org.apache.commons.io.IOUtils;
|
42
|
import org.apache.log4j.Logger;
|
43
|
import org.dataone.service.exceptions.IdentifierNotUnique;
|
44
|
import org.dataone.service.exceptions.InsufficientResources;
|
45
|
import org.dataone.service.exceptions.InvalidRequest;
|
46
|
import org.dataone.service.exceptions.InvalidSystemMetadata;
|
47
|
import org.dataone.service.exceptions.InvalidToken;
|
48
|
import org.dataone.service.exceptions.NotAuthorized;
|
49
|
import org.dataone.service.exceptions.NotFound;
|
50
|
import org.dataone.service.exceptions.NotImplemented;
|
51
|
import org.dataone.service.exceptions.ServiceFailure;
|
52
|
import org.dataone.service.exceptions.UnsupportedType;
|
53
|
import org.dataone.service.mn.MemberNodeCrud;
|
54
|
import org.dataone.service.types.*;
|
55
|
import org.jibx.runtime.BindingDirectory;
|
56
|
import org.jibx.runtime.IBindingFactory;
|
57
|
import org.jibx.runtime.IMarshallingContext;
|
58
|
import org.jibx.runtime.IUnmarshallingContext;
|
59
|
import org.jibx.runtime.JiBXException;
|
60
|
|
61
|
import com.gc.iotools.stream.is.InputStreamFromOutputStream;
|
62
|
|
63
|
import edu.ucsb.nceas.metacat.AccessionNumberException;
|
64
|
import edu.ucsb.nceas.metacat.MetacatResultSet;
|
65
|
import edu.ucsb.nceas.metacat.MetacatResultSet.Document;
|
66
|
import edu.ucsb.nceas.metacat.DocumentImpl;
|
67
|
import edu.ucsb.nceas.metacat.EventLog;
|
68
|
import edu.ucsb.nceas.metacat.IdentifierManager;
|
69
|
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
|
70
|
import edu.ucsb.nceas.metacat.McdbException;
|
71
|
import edu.ucsb.nceas.metacat.MetacatHandler;
|
72
|
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
|
73
|
import edu.ucsb.nceas.metacat.client.rest.MetacatRestClient;
|
74
|
import edu.ucsb.nceas.metacat.properties.PropertyService;
|
75
|
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
|
76
|
import edu.ucsb.nceas.metacat.service.SessionService;
|
77
|
import edu.ucsb.nceas.metacat.util.DocumentUtil;
|
78
|
import edu.ucsb.nceas.metacat.util.SessionData;
|
79
|
import edu.ucsb.nceas.utilities.ParseLSIDException;
|
80
|
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
|
81
|
|
82
|
/**
|
83
|
*
|
84
|
* Implements DataONE MemberNode CRUD API for Metacat.
|
85
|
*
|
86
|
* @author Matthew Jones
|
87
|
*/
|
88
|
public class CrudService implements MemberNodeCrud {
|
89
|
|
90
|
/*private ServletContext servletContext;
|
91
|
private HttpServletRequest request;
|
92
|
private HttpServletResponse response;*/
|
93
|
|
94
|
private static CrudService crudService = null;
|
95
|
|
96
|
private MetacatHandler handler;
|
97
|
private Hashtable<String, String[]> params;
|
98
|
Logger logMetacat = null;
|
99
|
|
100
|
private String metacatUrl;
|
101
|
|
102
|
/**
|
103
|
* singleton accessor
|
104
|
*/
|
105
|
public static CrudService getInstance()
|
106
|
{
|
107
|
if(crudService == null)
|
108
|
{
|
109
|
crudService = new CrudService();
|
110
|
}
|
111
|
|
112
|
return crudService;
|
113
|
}
|
114
|
|
115
|
/**
|
116
|
* Initializes new instance by setting servlet context,request and response.
|
117
|
* TODO: remove dependency on Servlet infrastructure
|
118
|
* TODO: Make this a real service, and make it a Singleton
|
119
|
*/
|
120
|
public CrudService() {
|
121
|
//change crud service into a singleton. dont pass servlet data structures here
|
122
|
logMetacat = Logger.getLogger(CrudService.class);
|
123
|
try
|
124
|
{
|
125
|
String server = PropertyService.getProperty("server.name");
|
126
|
String port = PropertyService.getProperty("server.httpPort");
|
127
|
String context = PropertyService.getProperty("application.context");
|
128
|
metacatUrl = "http://" + server + ":" + port + "/" + context;
|
129
|
logMetacat.debug("Initializing CrudService with url " + metacatUrl);
|
130
|
}
|
131
|
catch(Exception e)
|
132
|
{
|
133
|
logMetacat.error("Could not find servlet url in CrudService: " + e.getMessage());
|
134
|
e.printStackTrace();
|
135
|
throw new RuntimeException("Error getting servlet url in CrudService: " + e.getMessage());
|
136
|
}
|
137
|
|
138
|
/*this.servletContext = servletContext;
|
139
|
this.request = request;
|
140
|
this.response = response;*/
|
141
|
|
142
|
params = new Hashtable<String, String[]>();
|
143
|
|
144
|
handler = new MetacatHandler(new Timer());
|
145
|
|
146
|
}
|
147
|
|
148
|
/**
|
149
|
* return the context url CrudService is using.
|
150
|
*/
|
151
|
public String getContextUrl()
|
152
|
{
|
153
|
return metacatUrl;
|
154
|
}
|
155
|
|
156
|
/**
|
157
|
* set the params for this service from an HttpServletRequest param list
|
158
|
*/
|
159
|
public void setParamsFromRequest(HttpServletRequest request)
|
160
|
{
|
161
|
Enumeration paramlist = request.getParameterNames();
|
162
|
while (paramlist.hasMoreElements()) {
|
163
|
String name = (String) paramlist.nextElement();
|
164
|
String[] value = (String[])request.getParameterValues(name);
|
165
|
params.put(name, value);
|
166
|
}
|
167
|
}
|
168
|
|
169
|
/**
|
170
|
* Authenticate against metacat and get a token.
|
171
|
* @param username
|
172
|
* @param password
|
173
|
* @return
|
174
|
* @throws ServiceFailure
|
175
|
*/
|
176
|
public AuthToken authenticate(String username, String password)
|
177
|
throws ServiceFailure
|
178
|
{
|
179
|
try
|
180
|
{
|
181
|
MetacatRestClient restClient = new MetacatRestClient(getContextUrl());
|
182
|
String response = restClient.login(username, password);
|
183
|
String sessionid = restClient.getSessionId();
|
184
|
SessionService sessionService = SessionService.getInstance();
|
185
|
sessionService.registerSession(new SessionData(sessionid, username, new String[0], password, "CrudServiceLogin"));
|
186
|
AuthToken token = new AuthToken(sessionid);
|
187
|
return token;
|
188
|
}
|
189
|
catch(Exception e)
|
190
|
{
|
191
|
throw new ServiceFailure("1000", "Error authenticating with metacat: " + e.getMessage());
|
192
|
}
|
193
|
}
|
194
|
|
195
|
/**
|
196
|
* set the parameter values needed for this request
|
197
|
*/
|
198
|
public void setParameter(String name, String[] value)
|
199
|
{
|
200
|
params.put(name, value);
|
201
|
}
|
202
|
|
203
|
public Identifier create(AuthToken token, Identifier guid,
|
204
|
InputStream object, SystemMetadata sysmeta) throws InvalidToken,
|
205
|
ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType,
|
206
|
InsufficientResources, InvalidSystemMetadata, NotImplemented {
|
207
|
|
208
|
logMetacat.debug("Starting CrudService.create()...");
|
209
|
|
210
|
// authenticate & get user info
|
211
|
SessionData sessionData = getSessionData(token);
|
212
|
String username = sessionData.getUserName();
|
213
|
String[] groups = sessionData.getGroupNames();
|
214
|
|
215
|
// verify that guid == SystemMetadata.getIdentifier()
|
216
|
logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
|
217
|
if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
|
218
|
throw new InvalidSystemMetadata("1180",
|
219
|
"GUID in method call does not match GUID in system metadata.");
|
220
|
}
|
221
|
|
222
|
logMetacat.debug("Checking if identifier exists...");
|
223
|
// Check that the identifier does not already exist
|
224
|
IdentifierManager im = IdentifierManager.getInstance();
|
225
|
if (im.identifierExists(guid.getValue())) {
|
226
|
throw new IdentifierNotUnique("1120",
|
227
|
"GUID is already in use by an existing object.");
|
228
|
}
|
229
|
|
230
|
// Check if we are handling metadata or data
|
231
|
boolean isScienceMetadata = isScienceMetadata(sysmeta);
|
232
|
|
233
|
if (isScienceMetadata) {
|
234
|
// CASE METADATA:
|
235
|
try {
|
236
|
this.insertDocument(object, guid, sessionData);
|
237
|
} catch (IOException e) {
|
238
|
String msg = "Could not create string from XML stream: " +
|
239
|
" " + e.getMessage();
|
240
|
logMetacat.debug(msg);
|
241
|
throw new ServiceFailure("1190", msg);
|
242
|
}
|
243
|
|
244
|
} else {
|
245
|
// DEFAULT CASE: DATA (needs to be checked and completed)
|
246
|
insertDataObject(object, guid, sessionData);
|
247
|
|
248
|
}
|
249
|
|
250
|
// For Metadata and Data, insert the system metadata into the object store too
|
251
|
insertSystemMetadata(sysmeta, sessionData);
|
252
|
|
253
|
logMetacat.debug("Returning from CrudService.create()");
|
254
|
return guid;
|
255
|
}
|
256
|
|
257
|
/**
|
258
|
* update an existing object with a new object. Change the system metadata
|
259
|
* to reflect the changes and update it as well.
|
260
|
*/
|
261
|
public Identifier update(AuthToken token, Identifier guid,
|
262
|
InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta)
|
263
|
throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique,
|
264
|
UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata,
|
265
|
NotImplemented {
|
266
|
try
|
267
|
{
|
268
|
SessionData sessionData = getSessionData(token);
|
269
|
|
270
|
//find the old systemmetadata (sm.old) document id (the one linked to obsoletedGuid)
|
271
|
SystemMetadata sm = getSystemMetadata(token, obsoletedGuid);
|
272
|
//change sm.old's obsoletedBy field
|
273
|
List l = sm.getObsoletedByList();
|
274
|
l.add(guid);
|
275
|
sm.setObsoletedByList(l);
|
276
|
//update sm.old
|
277
|
updateSystemMetadata(sm, sessionData);
|
278
|
|
279
|
//change the obsoletes field of the new systemMetadata (sm.new) to point to the id of the old one
|
280
|
sysmeta.addObsolete(obsoletedGuid);
|
281
|
//insert sm.new
|
282
|
insertSystemMetadata(sysmeta, sessionData);
|
283
|
|
284
|
boolean isScienceMetadata = isScienceMetadata(sysmeta);
|
285
|
if(isScienceMetadata)
|
286
|
{
|
287
|
//update the doc
|
288
|
updateDocument(object, obsoletedGuid, guid, sessionData);
|
289
|
}
|
290
|
else
|
291
|
{
|
292
|
//update a data file, not xml
|
293
|
insertDataObject(object, guid, sessionData);
|
294
|
}
|
295
|
return guid;
|
296
|
}
|
297
|
catch(Exception e)
|
298
|
{
|
299
|
throw new ServiceFailure("1030", "Error updating document in CrudService: " + e.getMessage());
|
300
|
}
|
301
|
}
|
302
|
|
303
|
/**
|
304
|
* set the permission on the document
|
305
|
* @param token
|
306
|
* @param principal
|
307
|
* @param permission
|
308
|
* @param permissionType
|
309
|
* @param permissionOrder
|
310
|
* @return
|
311
|
*/
|
312
|
public void setAccess(AuthToken token, Identifier id, String principal, String permission,
|
313
|
String permissionType, String permissionOrder)
|
314
|
throws ServiceFailure
|
315
|
{
|
316
|
try
|
317
|
{
|
318
|
IdentifierManager im = IdentifierManager.getInstance();
|
319
|
String docid = im.getLocalId(id.getValue());
|
320
|
final SessionData sessionData = getSessionData(token);
|
321
|
String permNum = "0";
|
322
|
if(permission.equals("read"))
|
323
|
{
|
324
|
permNum = "4";
|
325
|
}
|
326
|
else if(permission.equals("write"))
|
327
|
{
|
328
|
permNum = "6";
|
329
|
}
|
330
|
handler.setAccess(metacatUrl, sessionData.getUserName(), docid,
|
331
|
principal, permNum, permissionType, permissionOrder);
|
332
|
}
|
333
|
catch(Exception e)
|
334
|
{
|
335
|
e.printStackTrace();
|
336
|
throw new ServiceFailure("1000", "Could not set access on the document with id " + id.getValue());
|
337
|
}
|
338
|
}
|
339
|
|
340
|
/**
|
341
|
* Retrieve the list of objects present on the MN that match the calling
|
342
|
* parameters. This method is required to support the process of Member
|
343
|
* Node synchronization. At a minimum, this method should be able to
|
344
|
* return a list of objects that match:
|
345
|
* startTime <= SystemMetadata.dateSysMetadataModified
|
346
|
* but is expected to also support date range (by also specifying endTime),
|
347
|
* and should also support slicing of the matching set of records by
|
348
|
* indicating the starting index of the response (where 0 is the index
|
349
|
* of the first item) and the count of elements to be returned.
|
350
|
*
|
351
|
* If startTime or endTime is null, the query is not restricted by that parameter.
|
352
|
*
|
353
|
* @see http://mule1.dataone.org/ArchitectureDocs/mn_api_replication.html#MN_replication.listObjects
|
354
|
* @param token
|
355
|
* @param startTime
|
356
|
* @param endTime
|
357
|
* @param objectFormat
|
358
|
* @param replicaStatus
|
359
|
* @param start
|
360
|
* @param count
|
361
|
* @return ObjectList
|
362
|
* @throws NotAuthorized
|
363
|
* @throws InvalidRequest
|
364
|
* @throws NotImplemented
|
365
|
* @throws ServiceFailure
|
366
|
* @throws InvalidToken
|
367
|
*/
|
368
|
public ObjectList listObjects(AuthToken token, Date startTime, Date endTime,
|
369
|
ObjectFormat objectFormat, boolean replicaStatus, int start, int count)
|
370
|
throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
|
371
|
{
|
372
|
ObjectList ol = new ObjectList();
|
373
|
final SessionData sessionData = getSessionData(token);
|
374
|
try
|
375
|
{
|
376
|
params.clear();
|
377
|
params.put("returndoctype", new String[] {"http://dataone.org/service/types/SystemMetadata/0.1"});
|
378
|
params.put("qformat", new String[] {"xml"});
|
379
|
params.put("returnfield", new String[] {"size", "originMemberNode",
|
380
|
"identifier", "objectFormat", "dateSysMetadataModified", "checksum", "@algorithm"});
|
381
|
params.put("anyfield", new String[] {"%"});
|
382
|
|
383
|
MetacatResultSet rs = handler.query(metacatUrl, params, sessionData.getUserName(),
|
384
|
sessionData.getGroupNames(), sessionData.getId());
|
385
|
List docs = rs.getDocuments();
|
386
|
|
387
|
if(count == 1000)
|
388
|
{
|
389
|
count = docs.size();
|
390
|
}
|
391
|
for(int i=start; i<count; i++)
|
392
|
{
|
393
|
//get the document from the results
|
394
|
Document d = (Document)docs.get(i);
|
395
|
ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
|
396
|
if(objectFormat != null && !objectFormat.toString().trim().equals(returnedObjectFormat.toString().trim()))
|
397
|
{ //make sure the objectFormat is the one specified
|
398
|
continue;
|
399
|
}
|
400
|
Date dateSysMetadataModified = parseDate(d.getField("dateSysMetadataModified"));
|
401
|
int startDateComparison = 0;
|
402
|
int endDateComparison = 0;
|
403
|
if(startTime != null)
|
404
|
{
|
405
|
startDateComparison = dateSysMetadataModified.compareTo(startTime);
|
406
|
}
|
407
|
|
408
|
if(endTime != null)
|
409
|
{
|
410
|
endDateComparison = dateSysMetadataModified.compareTo(endTime);
|
411
|
}
|
412
|
|
413
|
if(startDateComparison < 0 || endDateComparison > 0)
|
414
|
{ //this date falls outside of the startTime and endTime params, so
|
415
|
//skip it
|
416
|
continue;
|
417
|
}
|
418
|
|
419
|
ObjectInfo info = new ObjectInfo();
|
420
|
//add the fields to the info object
|
421
|
Checksum cs = new Checksum();
|
422
|
cs.setValue(d.getField("checksum"));
|
423
|
String csalg = d.getField("algorithm");
|
424
|
if(csalg == null)
|
425
|
{
|
426
|
csalg = "MD5";
|
427
|
}
|
428
|
ChecksumAlgorithm ca = ChecksumAlgorithm.convert(csalg);
|
429
|
cs.setAlgorithm(ca);
|
430
|
info.setChecksum(cs);
|
431
|
info.setDateSysMetadataModified(dateSysMetadataModified);
|
432
|
Identifier id = new Identifier();
|
433
|
id.setValue(d.getField("identifier"));
|
434
|
info.setIdentifier(id);
|
435
|
info.setObjectFormat(returnedObjectFormat);
|
436
|
info.setSize(new Long(d.getField("size").trim()).longValue());
|
437
|
//add the ObjectInfo to the ObjectList
|
438
|
ol.addObjectInfo(info);
|
439
|
//System.out.println(d.toString());
|
440
|
}
|
441
|
}
|
442
|
catch(Exception e)
|
443
|
{
|
444
|
e.printStackTrace();
|
445
|
throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
|
446
|
}
|
447
|
return ol;
|
448
|
}
|
449
|
|
450
|
/**
|
451
|
* Call listObjects with the default values for replicaStatus (true), start (0),
|
452
|
* and count (1000).
|
453
|
* @param token
|
454
|
* @param startTime
|
455
|
* @param endTime
|
456
|
* @param objectFormat
|
457
|
* @return
|
458
|
* @throws NotAuthorized
|
459
|
* @throws InvalidRequest
|
460
|
* @throws NotImplemented
|
461
|
* @throws ServiceFailure
|
462
|
* @throws InvalidToken
|
463
|
*/
|
464
|
public ObjectList listObjects(AuthToken token, Date startTime, Date endTime,
|
465
|
ObjectFormat objectFormat)
|
466
|
throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
|
467
|
{
|
468
|
return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
|
469
|
}
|
470
|
|
471
|
/**
|
472
|
* Delete a document. NOT IMPLEMENTED
|
473
|
*/
|
474
|
public Identifier delete(AuthToken token, Identifier guid)
|
475
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
476
|
NotImplemented {
|
477
|
throw new NotImplemented("1000", "This method not yet implemented.");
|
478
|
}
|
479
|
|
480
|
/**
|
481
|
* describe a document. NOT IMPLEMENTED
|
482
|
*/
|
483
|
public DescribeResponse describe(AuthToken token, Identifier guid)
|
484
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
485
|
NotImplemented {
|
486
|
throw new NotImplemented("1000", "This method not yet implemented.");
|
487
|
}
|
488
|
|
489
|
/**
|
490
|
* get a document with a specified guid.
|
491
|
*/
|
492
|
public InputStream get(AuthToken token, Identifier guid)
|
493
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
494
|
NotImplemented {
|
495
|
|
496
|
// Retrieve the session information from the AuthToken
|
497
|
// If the session is expired, then the user is 'public'
|
498
|
final SessionData sessionData = getSessionData(token);
|
499
|
|
500
|
// Look up the localId for this global identifier
|
501
|
IdentifierManager im = IdentifierManager.getInstance();
|
502
|
try {
|
503
|
final String localId = im.getLocalId(guid.getValue());
|
504
|
|
505
|
final InputStreamFromOutputStream<String> objectStream =
|
506
|
new InputStreamFromOutputStream<String>() {
|
507
|
|
508
|
@Override
|
509
|
public String produce(final OutputStream dataSink) throws Exception {
|
510
|
|
511
|
try {
|
512
|
handler.readFromMetacat(metacatUrl, null,
|
513
|
dataSink, localId, "xml",
|
514
|
sessionData.getUserName(),
|
515
|
sessionData.getGroupNames(), true, params);
|
516
|
} catch (PropertyNotFoundException e) {
|
517
|
throw new ServiceFailure("1030", e.getMessage());
|
518
|
} catch (ClassNotFoundException e) {
|
519
|
throw new ServiceFailure("1030", e.getMessage());
|
520
|
} catch (IOException e) {
|
521
|
throw new ServiceFailure("1030", e.getMessage());
|
522
|
} catch (SQLException e) {
|
523
|
throw new ServiceFailure("1030", e.getMessage());
|
524
|
} catch (McdbException e) {
|
525
|
throw new ServiceFailure("1030", e.getMessage());
|
526
|
} catch (ParseLSIDException e) {
|
527
|
throw new NotFound("1020", e.getMessage());
|
528
|
} catch (InsufficientKarmaException e) {
|
529
|
throw new NotAuthorized("1000", "Not authorized for get().");
|
530
|
}
|
531
|
|
532
|
return "Completed";
|
533
|
}
|
534
|
};
|
535
|
return objectStream;
|
536
|
|
537
|
} catch (McdbDocNotFoundException e) {
|
538
|
throw new NotFound("1020", e.getMessage());
|
539
|
}
|
540
|
}
|
541
|
|
542
|
/**
|
543
|
* get the checksum for a document. NOT IMPLEMENTED
|
544
|
*/
|
545
|
public Checksum getChecksum(AuthToken token, Identifier guid)
|
546
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
547
|
InvalidRequest, NotImplemented {
|
548
|
throw new NotImplemented("1000", "This method not yet implemented.");
|
549
|
}
|
550
|
|
551
|
/**
|
552
|
* get the checksum for a document. NOT IMPLEMENTED
|
553
|
*/
|
554
|
public Checksum getChecksum(AuthToken token, Identifier guid,
|
555
|
String checksumAlgorithm) throws InvalidToken, ServiceFailure,
|
556
|
NotAuthorized, NotFound, InvalidRequest, NotImplemented {
|
557
|
throw new NotImplemented("1000", "This method not yet implemented.");
|
558
|
}
|
559
|
|
560
|
/**
|
561
|
* get log records. NOT IMPLEMENTED
|
562
|
*/
|
563
|
public LogRecordSet getLogRecords(AuthToken token, Date fromDate, Date toDate)
|
564
|
throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest,
|
565
|
NotImplemented {
|
566
|
throw new NotImplemented("1000", "This method not yet implemented.");
|
567
|
}
|
568
|
|
569
|
/**
|
570
|
* get the system metadata for a document with a specified guid.
|
571
|
*/
|
572
|
public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
|
573
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
574
|
InvalidRequest, NotImplemented {
|
575
|
|
576
|
logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
|
577
|
|
578
|
// Retrieve the session information from the AuthToken
|
579
|
// If the session is expired, then the user is 'public'
|
580
|
final SessionData sessionData = getSessionData(token);
|
581
|
|
582
|
// TODO: Check access control rules
|
583
|
|
584
|
try {
|
585
|
IdentifierManager im = IdentifierManager.getInstance();
|
586
|
final String localId = im.getSystemMetadataId(guid.getValue());
|
587
|
|
588
|
// Read system metadata from metacat's db
|
589
|
final InputStreamFromOutputStream<String> objectStream =
|
590
|
new InputStreamFromOutputStream<String>() {
|
591
|
|
592
|
@Override
|
593
|
public String produce(final OutputStream dataSink) throws Exception {
|
594
|
try {
|
595
|
handler.readFromMetacat(metacatUrl, null,
|
596
|
dataSink, localId, "xml",
|
597
|
sessionData.getUserName(),
|
598
|
sessionData.getGroupNames(), true, params);
|
599
|
} catch (PropertyNotFoundException e) {
|
600
|
throw new ServiceFailure("1030", e.getMessage());
|
601
|
} catch (ClassNotFoundException e) {
|
602
|
throw new ServiceFailure("1030", e.getMessage());
|
603
|
} catch (IOException e) {
|
604
|
throw new ServiceFailure("1030", e.getMessage());
|
605
|
} catch (SQLException e) {
|
606
|
throw new ServiceFailure("1030", e.getMessage());
|
607
|
} catch (McdbException e) {
|
608
|
throw new ServiceFailure("1030", e.getMessage());
|
609
|
} catch (ParseLSIDException e) {
|
610
|
throw new NotFound("1020", e.getMessage());
|
611
|
} catch (InsufficientKarmaException e) {
|
612
|
throw new NotAuthorized("1000", "Not authorized for get().");
|
613
|
}
|
614
|
|
615
|
return "Completed";
|
616
|
}
|
617
|
};
|
618
|
|
619
|
// Deserialize the xml to create a SystemMetadata object
|
620
|
SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
|
621
|
return sysmeta;
|
622
|
|
623
|
} catch (McdbDocNotFoundException e) {
|
624
|
//e.printStackTrace();
|
625
|
throw new NotFound("1000", e.getMessage());
|
626
|
}
|
627
|
}
|
628
|
|
629
|
/**
|
630
|
* parse the date in the systemMetadata
|
631
|
* @param s
|
632
|
* @return
|
633
|
* @throws Exception
|
634
|
*/
|
635
|
private Date parseDate(String s)
|
636
|
throws Exception
|
637
|
{
|
638
|
Date d = null;
|
639
|
int tIndex = s.indexOf("T");
|
640
|
int zIndex = s.indexOf("Z");
|
641
|
if(tIndex != -1 && zIndex != -1)
|
642
|
{ //parse a date that looks like 2010-05-18T21:12:54.362Z
|
643
|
//System.out.println("original date: " + s);
|
644
|
|
645
|
String date = s.substring(0, tIndex);
|
646
|
String year = date.substring(0, date.indexOf("-"));
|
647
|
String month = date.substring(date.indexOf("-") + 1, date.lastIndexOf("-"));
|
648
|
String day = date.substring(date.lastIndexOf("-") + 1, date.length());
|
649
|
/*System.out.println("date: " + "year: " + new Integer(year).intValue() +
|
650
|
" month: " + new Integer(month).intValue() + " day: " +
|
651
|
new Integer(day).intValue());
|
652
|
*/
|
653
|
String time = s.substring(tIndex + 1, zIndex);
|
654
|
String hour = time.substring(0, time.indexOf(":"));
|
655
|
String minute = time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"));
|
656
|
String seconds = "00";
|
657
|
String milliseconds = "00";
|
658
|
if(time.indexOf(".") != -1)
|
659
|
{
|
660
|
seconds = time.substring(time.lastIndexOf(":") + 1, time.indexOf("."));
|
661
|
milliseconds = time.substring(time.indexOf(".") + 1, time.length());
|
662
|
}
|
663
|
/*System.out.println("time: " + "hour: " + new Integer(hour).intValue() +
|
664
|
" minute: " + new Integer(minute).intValue() + " seconds: " +
|
665
|
new Integer(seconds).intValue() + " milli: " +
|
666
|
new Integer(milliseconds).intValue());*/
|
667
|
|
668
|
//d = DateFormat.getDateTimeInstance().parse(date + " " + time);
|
669
|
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
|
670
|
c.set(new Integer(year).intValue(), new Integer(month).intValue() - 1,
|
671
|
new Integer(day).intValue(), new Integer(hour).intValue(),
|
672
|
new Integer(minute).intValue(), new Integer(seconds).intValue());
|
673
|
c.set(Calendar.MILLISECOND, new Integer(milliseconds).intValue());
|
674
|
d = new Date(c.getTimeInMillis());
|
675
|
//System.out.println("d: " + d);
|
676
|
return d;
|
677
|
}
|
678
|
else
|
679
|
{ //if it's not in the expected format, try the formatter
|
680
|
return DateFormat.getDateTimeInstance().parse(s);
|
681
|
}
|
682
|
}
|
683
|
|
684
|
/*
|
685
|
* Look up the information on the session using the token provided in
|
686
|
* the AuthToken. The Session should have all relevant user information.
|
687
|
* If the session has expired or is invalid, the 'public' session will
|
688
|
* be returned, giving the user anonymous access.
|
689
|
*/
|
690
|
private static SessionData getSessionData(AuthToken token) {
|
691
|
SessionData sessionData = null;
|
692
|
String sessionId = "PUBLIC";
|
693
|
if (token != null) {
|
694
|
sessionId = token.getToken();
|
695
|
}
|
696
|
|
697
|
// if the session id is registered in SessionService, get the
|
698
|
// SessionData for it. Otherwise, use the public session.
|
699
|
if (SessionService.isSessionRegistered(sessionId)) {
|
700
|
sessionData = SessionService.getRegisteredSession(sessionId);
|
701
|
} else {
|
702
|
sessionData = SessionService.getPublicSession();
|
703
|
}
|
704
|
|
705
|
return sessionData;
|
706
|
}
|
707
|
|
708
|
/**
|
709
|
* Determine if a given object should be treated as an XML science metadata
|
710
|
* object.
|
711
|
*
|
712
|
* TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
|
713
|
*
|
714
|
* @param sysmeta the SystemMetadata describig the object
|
715
|
* @return true if the object should be treated as science metadata
|
716
|
*/
|
717
|
private boolean isScienceMetadata(SystemMetadata sysmeta) {
|
718
|
boolean scimeta = false;
|
719
|
switch (sysmeta.getObjectFormat()) {
|
720
|
case EML_2_1_0: scimeta = true; break;
|
721
|
case EML_2_0_1: scimeta = true; break;
|
722
|
case EML_2_0_0: scimeta = true; break;
|
723
|
case FGDC_STD_001_1_1999: scimeta = true; break;
|
724
|
case FGDC_STD_001_1998: scimeta = true; break;
|
725
|
case NCML_2_2: scimeta = true; break;
|
726
|
}
|
727
|
|
728
|
return scimeta;
|
729
|
}
|
730
|
|
731
|
/**
|
732
|
* insert a data doc
|
733
|
* @param object
|
734
|
* @param guid
|
735
|
* @param sessionData
|
736
|
* @throws ServiceFailure
|
737
|
*/
|
738
|
private void insertDataObject(InputStream object, Identifier guid,
|
739
|
SessionData sessionData) throws ServiceFailure {
|
740
|
|
741
|
String username = sessionData.getUserName();
|
742
|
String[] groups = sessionData.getGroupNames();
|
743
|
|
744
|
// generate guid/localId pair for object
|
745
|
logMetacat.debug("Generating a guid/localId mapping");
|
746
|
IdentifierManager im = IdentifierManager.getInstance();
|
747
|
String localId = im.generateLocalId(guid.getValue(), 1);
|
748
|
|
749
|
try {
|
750
|
logMetacat.debug("Case DATA: starting to write to disk.");
|
751
|
if (DocumentImpl.getDataFileLockGrant(localId)) {
|
752
|
|
753
|
// Save the data file to disk using "localId" as the name
|
754
|
try {
|
755
|
String datafilepath = PropertyService.getProperty("application.datafilepath");
|
756
|
|
757
|
File dataDirectory = new File(datafilepath);
|
758
|
dataDirectory.mkdirs();
|
759
|
|
760
|
File newFile = writeStreamToFile(dataDirectory, localId, object);
|
761
|
|
762
|
// TODO: Check that the file size matches SystemMetadata
|
763
|
// long size = newFile.length();
|
764
|
// if (size == 0) {
|
765
|
// throw new IOException("Uploaded file is 0 bytes!");
|
766
|
// }
|
767
|
|
768
|
// Register the file in the database (which generates an exception
|
769
|
// if the localId is not acceptable or other untoward things happen
|
770
|
try {
|
771
|
logMetacat.debug("Registering document...");
|
772
|
System.out.println("inserting data object: localId: " + localId);
|
773
|
DocumentImpl.registerDocument(localId, "BIN", localId,
|
774
|
username, groups);
|
775
|
logMetacat.debug("Registration step completed.");
|
776
|
} catch (SQLException e) {
|
777
|
//newFile.delete();
|
778
|
logMetacat.debug("SQLE: " + e.getMessage());
|
779
|
e.printStackTrace(System.out);
|
780
|
throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
|
781
|
} catch (AccessionNumberException e) {
|
782
|
//newFile.delete();
|
783
|
logMetacat.debug("ANE: " + e.getMessage());
|
784
|
e.printStackTrace(System.out);
|
785
|
throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
|
786
|
} catch (Exception e) {
|
787
|
//newFile.delete();
|
788
|
logMetacat.debug("Exception: " + e.getMessage());
|
789
|
e.printStackTrace(System.out);
|
790
|
throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
|
791
|
}
|
792
|
|
793
|
logMetacat.debug("Logging the creation event.");
|
794
|
EventLog.getInstance().log(metacatUrl,
|
795
|
username, localId, "create");
|
796
|
|
797
|
// Schedule replication for this data file
|
798
|
logMetacat.debug("Scheduling replication.");
|
799
|
ForceReplicationHandler frh = new ForceReplicationHandler(
|
800
|
localId, "insert", false, null);
|
801
|
|
802
|
} catch (PropertyNotFoundException e) {
|
803
|
throw new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
|
804
|
}
|
805
|
|
806
|
}
|
807
|
} catch (Exception e) {
|
808
|
// Could not get a lock on the document, so we can not update the file now
|
809
|
throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
|
810
|
}
|
811
|
}
|
812
|
|
813
|
/**
|
814
|
* write a file to a stream
|
815
|
* @param dir
|
816
|
* @param fileName
|
817
|
* @param data
|
818
|
* @return
|
819
|
* @throws ServiceFailure
|
820
|
*/
|
821
|
private File writeStreamToFile(File dir, String fileName, InputStream data)
|
822
|
throws ServiceFailure {
|
823
|
|
824
|
File newFile = new File(dir, fileName);
|
825
|
logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
|
826
|
|
827
|
try {
|
828
|
if (newFile.createNewFile()) {
|
829
|
// write data stream to desired file
|
830
|
OutputStream os = new FileOutputStream(newFile);
|
831
|
long length = IOUtils.copyLarge(data, os);
|
832
|
os.flush();
|
833
|
os.close();
|
834
|
} else {
|
835
|
logMetacat.debug("File creation failed, or file already exists.");
|
836
|
throw new ServiceFailure("1190", "File already exists: " + fileName);
|
837
|
}
|
838
|
} catch (FileNotFoundException e) {
|
839
|
logMetacat.debug("FNF: " + e.getMessage());
|
840
|
throw new ServiceFailure("1190", "File not found: " + fileName + " "
|
841
|
+ e.getMessage());
|
842
|
} catch (IOException e) {
|
843
|
logMetacat.debug("IOE: " + e.getMessage());
|
844
|
throw new ServiceFailure("1190", "File was not written: " + fileName
|
845
|
+ " " + e.getMessage());
|
846
|
}
|
847
|
|
848
|
return newFile;
|
849
|
}
|
850
|
|
851
|
/**
|
852
|
* insert a systemMetadata doc
|
853
|
*/
|
854
|
private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData)
|
855
|
throws ServiceFailure {
|
856
|
logMetacat.debug("Starting to insert SystemMetadata...");
|
857
|
|
858
|
// generate guid/localId pair for sysmeta
|
859
|
Identifier sysMetaGuid = new Identifier();
|
860
|
sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
|
861
|
sysmeta.setDateSysMetadataModified(new Date());
|
862
|
|
863
|
String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
|
864
|
String localId = insertDocument(xml, sysMetaGuid, sessionData);
|
865
|
//insert the system metadata doc id into the identifiers table to
|
866
|
//link it to the data or metadata document
|
867
|
IdentifierManager.getInstance().createSystemMetadataMapping(sysmeta.getIdentifier().getValue(), sysMetaGuid.getValue());
|
868
|
}
|
869
|
|
870
|
/**
|
871
|
* update a systemMetadata doc
|
872
|
*/
|
873
|
private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
|
874
|
throws ServiceFailure
|
875
|
{
|
876
|
try
|
877
|
{
|
878
|
String smId = IdentifierManager.getInstance().getSystemMetadataId(sm.getIdentifier().getValue());
|
879
|
sm.setDateSysMetadataModified(new Date());
|
880
|
String xml = new String(serializeSystemMetadata(sm).toByteArray());
|
881
|
Identifier id = new Identifier();
|
882
|
id.setValue(smId);
|
883
|
String localId = updateDocument(xml, id, null, sessionData);
|
884
|
IdentifierManager.getInstance().updateSystemMetadataMapping(sm.getIdentifier().getValue(), localId);
|
885
|
}
|
886
|
catch(Exception e)
|
887
|
{
|
888
|
throw new ServiceFailure("1030", "Error updating system metadata: " + e.getMessage());
|
889
|
}
|
890
|
}
|
891
|
|
892
|
/**
|
893
|
* insert a document
|
894
|
* NOTE: this method shouldn't be used from the update or create() methods.
|
895
|
* we shouldn't be putting the science metadata or data objects into memory.
|
896
|
*/
|
897
|
private String insertDocument(String xml, Identifier guid, SessionData sessionData)
|
898
|
throws ServiceFailure
|
899
|
{
|
900
|
return insertOrUpdateDocument(xml, guid, sessionData, "insert");
|
901
|
}
|
902
|
|
903
|
/**
|
904
|
* insert a document from a stream
|
905
|
*/
|
906
|
private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
|
907
|
throws IOException, ServiceFailure
|
908
|
{
|
909
|
//HACK: change this eventually. we should not be converting the stream to a string
|
910
|
String xml = IOUtils.toString(is);
|
911
|
return insertDocument(xml, guid, sessionData);
|
912
|
}
|
913
|
|
914
|
/**
|
915
|
* update a document
|
916
|
* NOTE: this method shouldn't be used from the update or create() methods.
|
917
|
* we shouldn't be putting the science metadata or data objects into memory.
|
918
|
*/
|
919
|
private String updateDocument(String xml, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
|
920
|
throws ServiceFailure
|
921
|
{
|
922
|
return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update");
|
923
|
}
|
924
|
|
925
|
/**
|
926
|
* update a document from a stream
|
927
|
*/
|
928
|
private String updateDocument(InputStream is, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
|
929
|
throws IOException, ServiceFailure
|
930
|
{
|
931
|
//HACK: change this eventually. we should not be converting the stream to a string
|
932
|
String xml = IOUtils.toString(is);
|
933
|
String localId = updateDocument(xml, obsoleteGuid, guid, sessionData);
|
934
|
IdentifierManager im = IdentifierManager.getInstance();
|
935
|
if(guid != null)
|
936
|
{
|
937
|
im.createMapping(guid.getValue(), localId);
|
938
|
}
|
939
|
return localId;
|
940
|
}
|
941
|
|
942
|
/**
|
943
|
* insert a document, return the id of the document that was inserted
|
944
|
*/
|
945
|
private String insertOrUpdateDocument(String xml, Identifier guid, SessionData sessionData, String insertOrUpdate)
|
946
|
throws ServiceFailure {
|
947
|
logMetacat.debug("Starting to insert xml document...");
|
948
|
IdentifierManager im = IdentifierManager.getInstance();
|
949
|
|
950
|
// generate guid/localId pair for sysmeta
|
951
|
String localId = null;
|
952
|
if(insertOrUpdate.equals("insert"))
|
953
|
{
|
954
|
localId = im.generateLocalId(guid.getValue(), 1);
|
955
|
}
|
956
|
else
|
957
|
{
|
958
|
//localid should already exist in the identifier table, so just find it
|
959
|
try
|
960
|
{
|
961
|
localId = im.getLocalId(guid.getValue());
|
962
|
//increment the revision
|
963
|
String docid = localId.substring(0, localId.lastIndexOf("."));
|
964
|
String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
|
965
|
int rev = new Integer(revS).intValue();
|
966
|
rev++;
|
967
|
docid = docid + "." + rev;
|
968
|
localId = docid;
|
969
|
}
|
970
|
catch(McdbDocNotFoundException e)
|
971
|
{
|
972
|
throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
|
973
|
"guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
|
974
|
}
|
975
|
}
|
976
|
logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
|
977
|
localId);
|
978
|
|
979
|
String[] action = new String[1];
|
980
|
action[0] = insertOrUpdate;
|
981
|
params.put("action", action);
|
982
|
String[] docid = new String[1];
|
983
|
docid[0] = localId;
|
984
|
params.put("docid", docid);
|
985
|
String[] doctext = new String[1];
|
986
|
doctext[0] = xml;
|
987
|
logMetacat.debug(doctext[0]);
|
988
|
params.put("doctext", doctext);
|
989
|
|
990
|
// TODO: refactor handleInsertOrUpdateAction() to not output XML directly
|
991
|
// onto output stream, or alternatively, capture that and parse it to
|
992
|
// generate the right exceptions
|
993
|
//ByteArrayOutputStream output = new ByteArrayOutputStream();
|
994
|
//PrintWriter pw = new PrintWriter(output);
|
995
|
String result = handler.handleInsertOrUpdateAction(metacatUrl, null,
|
996
|
null, params, sessionData.getUserName(), sessionData.getGroupNames());
|
997
|
//String outputS = new String(output.toByteArray());
|
998
|
logMetacat.debug("CrudService.insertDocument - Metacat returned: " + result);
|
999
|
// if (!(outputS.indexOf("<success>") > 0 && outputS.indexOf(localId) > 0)) {
|
1000
|
// throw new ServiceFailure(1190, outputS);
|
1001
|
// }
|
1002
|
logMetacat.debug("Finsished inserting xml document with id " + localId);
|
1003
|
return localId;
|
1004
|
}
|
1005
|
|
1006
|
/**
|
1007
|
* serialize a system metadata doc
|
1008
|
* @param sysmeta
|
1009
|
* @return
|
1010
|
* @throws ServiceFailure
|
1011
|
*/
|
1012
|
public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta)
|
1013
|
throws ServiceFailure {
|
1014
|
IBindingFactory bfact;
|
1015
|
ByteArrayOutputStream sysmetaOut = null;
|
1016
|
try {
|
1017
|
bfact = BindingDirectory.getFactory(SystemMetadata.class);
|
1018
|
IMarshallingContext mctx = bfact.createMarshallingContext();
|
1019
|
sysmetaOut = new ByteArrayOutputStream();
|
1020
|
mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
|
1021
|
} catch (JiBXException e) {
|
1022
|
throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
|
1023
|
}
|
1024
|
|
1025
|
return sysmetaOut;
|
1026
|
}
|
1027
|
|
1028
|
/**
|
1029
|
* deserialize a system metadata doc
|
1030
|
* @param xml
|
1031
|
* @return
|
1032
|
* @throws ServiceFailure
|
1033
|
*/
|
1034
|
public static SystemMetadata deserializeSystemMetadata(InputStream xml)
|
1035
|
throws ServiceFailure {
|
1036
|
try {
|
1037
|
IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
|
1038
|
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
|
1039
|
SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
|
1040
|
return sysmeta;
|
1041
|
} catch (JiBXException e) {
|
1042
|
throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
|
1043
|
}
|
1044
|
}
|
1045
|
}
|