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.FileInputStream;
|
28
|
import java.io.FileNotFoundException;
|
29
|
import java.io.FileOutputStream;
|
30
|
import java.io.IOException;
|
31
|
import java.io.InputStream;
|
32
|
import java.io.OutputStream;
|
33
|
import java.security.NoSuchAlgorithmException;
|
34
|
import java.sql.SQLException;
|
35
|
import java.text.DateFormat;
|
36
|
import java.text.SimpleDateFormat;
|
37
|
import java.util.Calendar;
|
38
|
import java.util.Date;
|
39
|
import java.util.Enumeration;
|
40
|
import java.util.Hashtable;
|
41
|
import java.util.List;
|
42
|
import java.util.TimeZone;
|
43
|
import java.util.Timer;
|
44
|
import java.util.TimerTask;
|
45
|
import java.util.Vector;
|
46
|
|
47
|
import javax.servlet.http.HttpServletRequest;
|
48
|
|
49
|
import org.apache.commons.io.IOUtils;
|
50
|
import org.apache.log4j.Logger;
|
51
|
import org.dataone.service.exceptions.BaseException;
|
52
|
import org.dataone.service.exceptions.IdentifierNotUnique;
|
53
|
import org.dataone.service.exceptions.InsufficientResources;
|
54
|
import org.dataone.service.exceptions.InvalidRequest;
|
55
|
import org.dataone.service.exceptions.InvalidSystemMetadata;
|
56
|
import org.dataone.service.exceptions.InvalidToken;
|
57
|
import org.dataone.service.exceptions.NotAuthorized;
|
58
|
import org.dataone.service.exceptions.NotFound;
|
59
|
import org.dataone.service.exceptions.NotImplemented;
|
60
|
import org.dataone.service.exceptions.ServiceFailure;
|
61
|
import org.dataone.service.exceptions.UnsupportedType;
|
62
|
import org.dataone.service.mn.MemberNodeCrud;
|
63
|
import org.dataone.service.types.AuthToken;
|
64
|
import org.dataone.service.types.Checksum;
|
65
|
import org.dataone.service.types.ChecksumAlgorithm;
|
66
|
import org.dataone.service.types.DescribeResponse;
|
67
|
import org.dataone.service.types.Event;
|
68
|
import org.dataone.service.types.Identifier;
|
69
|
import org.dataone.service.types.Log;
|
70
|
import org.dataone.service.types.LogEntry;
|
71
|
import org.dataone.service.types.NodeReference;
|
72
|
import org.dataone.service.types.ObjectFormat;
|
73
|
import org.dataone.service.types.ObjectList;
|
74
|
import org.dataone.service.types.Principal;
|
75
|
import org.dataone.service.types.SystemMetadata;
|
76
|
import org.dataone.service.types.util.ServiceTypeUtil;
|
77
|
import org.jibx.runtime.BindingDirectory;
|
78
|
import org.jibx.runtime.IBindingFactory;
|
79
|
import org.jibx.runtime.IMarshallingContext;
|
80
|
import org.jibx.runtime.IUnmarshallingContext;
|
81
|
import org.jibx.runtime.JiBXException;
|
82
|
|
83
|
import edu.ucsb.nceas.metacat.AccessionNumber;
|
84
|
import edu.ucsb.nceas.metacat.AccessionNumberException;
|
85
|
import edu.ucsb.nceas.metacat.DocumentImpl;
|
86
|
import edu.ucsb.nceas.metacat.EventLog;
|
87
|
import edu.ucsb.nceas.metacat.IdentifierManager;
|
88
|
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
|
89
|
import edu.ucsb.nceas.metacat.McdbException;
|
90
|
import edu.ucsb.nceas.metacat.MetacatHandler;
|
91
|
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
|
92
|
import edu.ucsb.nceas.metacat.client.rest.MetacatRestClient;
|
93
|
import edu.ucsb.nceas.metacat.properties.PropertyService;
|
94
|
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
|
95
|
import edu.ucsb.nceas.metacat.service.SessionService;
|
96
|
import edu.ucsb.nceas.metacat.util.DocumentUtil;
|
97
|
import edu.ucsb.nceas.metacat.util.SessionData;
|
98
|
import edu.ucsb.nceas.utilities.ParseLSIDException;
|
99
|
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
|
100
|
|
101
|
/**
|
102
|
*
|
103
|
* Implements DataONE MemberNode CRUD API for Metacat.
|
104
|
*
|
105
|
* @author Matthew Jones
|
106
|
*/
|
107
|
public class CrudService implements MemberNodeCrud
|
108
|
{
|
109
|
private static CrudService crudService = null;
|
110
|
|
111
|
private MetacatHandler handler;
|
112
|
private Hashtable<String, String[]> params;
|
113
|
private Logger logMetacat = null;
|
114
|
private Logger logCrud = null;
|
115
|
|
116
|
private String metacatUrl;
|
117
|
|
118
|
private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
|
119
|
|
120
|
/**
|
121
|
* singleton accessor
|
122
|
*/
|
123
|
public static CrudService getInstance()
|
124
|
{
|
125
|
if(crudService == null)
|
126
|
{
|
127
|
crudService = new CrudService();
|
128
|
}
|
129
|
|
130
|
return crudService;
|
131
|
}
|
132
|
|
133
|
/**
|
134
|
* Constructor, private for singleton access
|
135
|
*/
|
136
|
private CrudService() {
|
137
|
logMetacat = Logger.getLogger(CrudService.class);
|
138
|
logCrud = Logger.getLogger("DataOneLogger");
|
139
|
try
|
140
|
{
|
141
|
String server = PropertyService.getProperty("server.name");
|
142
|
String port = PropertyService.getProperty("server.httpPort");
|
143
|
String context = PropertyService.getProperty("application.context");
|
144
|
metacatUrl = "http://" + server + ":" + port + "/" + context + "/d1";
|
145
|
logMetacat.debug("Initializing CrudService with url " + metacatUrl);
|
146
|
}
|
147
|
catch(Exception e)
|
148
|
{
|
149
|
logMetacat.error("Could not find servlet url in CrudService: " + e.getMessage());
|
150
|
e.printStackTrace();
|
151
|
throw new RuntimeException("Error getting servlet url in CrudService: " + e.getMessage());
|
152
|
}
|
153
|
|
154
|
params = new Hashtable<String, String[]>();
|
155
|
handler = new MetacatHandler(new Timer());
|
156
|
}
|
157
|
|
158
|
/**
|
159
|
* return the context url CrudService is using.
|
160
|
*/
|
161
|
public String getContextUrl()
|
162
|
{
|
163
|
return metacatUrl;
|
164
|
}
|
165
|
|
166
|
/**
|
167
|
* Set the context url that this service uses. It is normally not necessary
|
168
|
* to call this method unless you are trying to connect to a server other
|
169
|
* than the one in which this service is installed. Otherwise, this value is
|
170
|
* taken from the metacat.properties file (server.name, server.port, application.context).
|
171
|
*/
|
172
|
public void setContextUrl(String url)
|
173
|
{
|
174
|
metacatUrl = url;
|
175
|
}
|
176
|
|
177
|
/**
|
178
|
* set the params for this service from an HttpServletRequest param list
|
179
|
*/
|
180
|
public void setParamsFromRequest(HttpServletRequest request)
|
181
|
{
|
182
|
Enumeration paramlist = request.getParameterNames();
|
183
|
while (paramlist.hasMoreElements()) {
|
184
|
String name = (String) paramlist.nextElement();
|
185
|
String[] value = (String[])request.getParameterValues(name);
|
186
|
params.put(name, value);
|
187
|
}
|
188
|
}
|
189
|
|
190
|
/**
|
191
|
* Authenticate against metacat and get a token.
|
192
|
* @param username
|
193
|
* @param password
|
194
|
* @return
|
195
|
* @throws ServiceFailure
|
196
|
*/
|
197
|
public AuthToken authenticate(String username, String password)
|
198
|
throws ServiceFailure
|
199
|
{
|
200
|
/* TODO:
|
201
|
* This method is not in the original D1 crud spec. It is highly
|
202
|
* metacat centric. Higher level decisions need to be made on authentication
|
203
|
* interfaces for D1 nodes.
|
204
|
*/
|
205
|
try
|
206
|
{
|
207
|
MetacatRestClient restClient = new MetacatRestClient(getContextUrl());
|
208
|
String response = restClient.login(username, password);
|
209
|
String sessionid = restClient.getSessionId();
|
210
|
SessionService sessionService = SessionService.getInstance();
|
211
|
sessionService.registerSession(new SessionData(sessionid, username, new String[0], password, "CrudServiceLogin"));
|
212
|
AuthToken token = new AuthToken(sessionid);
|
213
|
EventLog.getInstance().log(metacatUrl,
|
214
|
username, null, "authenticate");
|
215
|
logCrud.info("authenticate");
|
216
|
return token;
|
217
|
}
|
218
|
catch(Exception e)
|
219
|
{
|
220
|
throw new ServiceFailure("1620", "Error authenticating with metacat: " + e.getMessage());
|
221
|
}
|
222
|
}
|
223
|
|
224
|
/**
|
225
|
* set the parameter values needed for this request
|
226
|
*/
|
227
|
public void setParameter(String name, String[] value)
|
228
|
{
|
229
|
params.put(name, value);
|
230
|
}
|
231
|
|
232
|
/**
|
233
|
* Generate SystemMetadata for any object in the object store that does
|
234
|
* not already have it. SystemMetadata documents themselves, are, of course,
|
235
|
* exempt. This is a utility method for migration of existing object
|
236
|
* stores to DataONE where SystemMetadata is required for all objects. See
|
237
|
* https://trac.dataone.org/ticket/591
|
238
|
*
|
239
|
* @param token an authtoken with appropriate permissions to read all
|
240
|
* documents in the object store. To work correctly, this should probably
|
241
|
* be an adminstrative credential.
|
242
|
*/
|
243
|
public void generateMissingSystemMetadata(AuthToken token) {
|
244
|
IdentifierManager im = IdentifierManager.getInstance();
|
245
|
//get the list of ids with no SM
|
246
|
List<String> idList = im.getLocalIdsWithNoSystemMetadata();
|
247
|
for (String localId : idList) {
|
248
|
//for each id, add a system metadata doc
|
249
|
generateMissingSystemMetadata(token, localId);
|
250
|
}
|
251
|
logCrud.info("generateMissingSystemMetadata(token)");
|
252
|
}
|
253
|
|
254
|
/**
|
255
|
* Generate SystemMetadata for a particular object with identifier localId.
|
256
|
* This is a utility method for migration of existing objects
|
257
|
* to DataONE where SystemMetadata is required for all objects.
|
258
|
*
|
259
|
* @param token an authtoken with appropriate permissions to read all
|
260
|
* documents in the object store. To work correctly, this should
|
261
|
* be an adminstrative credential.
|
262
|
* @param localId the identifier of the object to be processed
|
263
|
*/
|
264
|
public void generateMissingSystemMetadata(AuthToken token, String localId) {
|
265
|
System.out.println("Creating SystemMetadata for localId " + localId);
|
266
|
try {
|
267
|
//generate required system metadata fields from the document
|
268
|
SystemMetadata sm = createSystemMetadata(localId, token);
|
269
|
|
270
|
//insert the systemmetadata object
|
271
|
SessionData sessionData = getSessionData(token);
|
272
|
String smlocalid = insertSystemMetadata(sm, sessionData);
|
273
|
System.out.println("setting access on SM doc with localid " + smlocalid);
|
274
|
handler.setAccess(metacatUrl, sessionData.getUserName(), smlocalid, "public", "4", "allow", "allowFirst");
|
275
|
|
276
|
String username = "public";
|
277
|
if (sessionData != null) {
|
278
|
username = sessionData.getUserName();
|
279
|
}
|
280
|
EventLog.getInstance().log(metacatUrl, username, localId, "generateMissingSystemMetadata");
|
281
|
} catch (Exception e) { // TODO: Please don't catch Exception -- it masks bad things
|
282
|
e.printStackTrace();
|
283
|
System.out.println("Exception generating missing system metadata: " + e.getMessage());
|
284
|
logMetacat.error("Could not generate missing system metadata: " + e.getMessage());
|
285
|
}
|
286
|
logCrud.info("generateMissingSystemMetadata(token, localId)");
|
287
|
}
|
288
|
|
289
|
/**
|
290
|
* create an object via the crud interface
|
291
|
*/
|
292
|
public Identifier create(AuthToken token, Identifier guid,
|
293
|
InputStream object, SystemMetadata sysmeta) throws InvalidToken,
|
294
|
ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType,
|
295
|
InsufficientResources, InvalidSystemMetadata, NotImplemented {
|
296
|
logMetacat.debug("Starting CrudService.create()...");
|
297
|
|
298
|
// authenticate & get user info
|
299
|
SessionData sessionData = getSessionData(token);
|
300
|
String username = "public";
|
301
|
String[] groups = null;
|
302
|
if(sessionData != null)
|
303
|
{
|
304
|
username = sessionData.getUserName();
|
305
|
groups = sessionData.getGroupNames();
|
306
|
}
|
307
|
String localId = null;
|
308
|
|
309
|
if (username == null || username.equals("public"))
|
310
|
{
|
311
|
//TODO: many of the thrown exceptions do not use the correct error codes
|
312
|
//check these against the docs and correct them
|
313
|
throw new NotAuthorized("1100", "User " + username + " is not authorized to create content." +
|
314
|
" If you are not logged in, please do so and retry the request.");
|
315
|
}
|
316
|
|
317
|
// verify that guid == SystemMetadata.getIdentifier()
|
318
|
logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
|
319
|
if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
|
320
|
throw new InvalidSystemMetadata("1180",
|
321
|
"GUID in method call (" + guid.getValue() + ") does not match GUID in system metadata (" +
|
322
|
sysmeta.getIdentifier().getValue() + ").");
|
323
|
}
|
324
|
|
325
|
logMetacat.debug("Checking if identifier exists...");
|
326
|
// Check that the identifier does not already exist
|
327
|
IdentifierManager im = IdentifierManager.getInstance();
|
328
|
if (im.identifierExists(guid.getValue())) {
|
329
|
throw new IdentifierNotUnique("1120",
|
330
|
"GUID is already in use by an existing object.");
|
331
|
}
|
332
|
|
333
|
// Check if we are handling metadata or data
|
334
|
boolean isScienceMetadata = isScienceMetadata(sysmeta);
|
335
|
|
336
|
if (isScienceMetadata) {
|
337
|
// CASE METADATA:
|
338
|
try {
|
339
|
//System.out.println("CrudService: inserting document with guid " + guid.getValue());
|
340
|
this.insertDocument(object, guid, sessionData);
|
341
|
localId = im.getLocalId(guid.getValue());
|
342
|
} catch (IOException e) {
|
343
|
String msg = "Could not create string from XML stream: " +
|
344
|
" " + e.getMessage();
|
345
|
logMetacat.debug(msg);
|
346
|
throw new ServiceFailure("1190", msg);
|
347
|
} catch(Exception e) {
|
348
|
String msg = "Unexpected error in CrudService.create: " + e.getMessage();
|
349
|
logMetacat.debug(msg);
|
350
|
throw new ServiceFailure("1190", msg);
|
351
|
}
|
352
|
|
353
|
|
354
|
} else {
|
355
|
// DEFAULT CASE: DATA (needs to be checked and completed)
|
356
|
localId = insertDataObject(object, guid, sessionData);
|
357
|
|
358
|
}
|
359
|
|
360
|
// For Metadata and Data, insert the system metadata into the object store too
|
361
|
String sysMetaLocalId = insertSystemMetadata(sysmeta, sessionData);
|
362
|
//get the document info. add any access params for the sysmeta too
|
363
|
//System.out.println("looking for access records to add for system " +
|
364
|
// "metadata who's parent doc's local id is " + localId);
|
365
|
try
|
366
|
{
|
367
|
Hashtable<String, Object> h = im.getDocumentInfo(localId.substring(0, localId.lastIndexOf(".")));
|
368
|
Vector v = (Vector)h.get("access");
|
369
|
for(int i=0; i<v.size(); i++)
|
370
|
{
|
371
|
Hashtable ah = (Hashtable)v.elementAt(i);
|
372
|
String principal = (String)ah.get("principal_name");
|
373
|
String permission = (String)ah.get("permission");
|
374
|
String permissionType = (String)ah.get("permission_type");
|
375
|
String permissionOrder = (String)ah.get("permission_order");
|
376
|
int perm = new Integer(permission).intValue();
|
377
|
//System.out.println("found access record for principal " + principal);
|
378
|
//System.out.println("permission: " + perm + " perm_type: " + permissionType +
|
379
|
// " perm_order: " + permissionOrder);
|
380
|
this.setAccess(token, guid, principal, perm, permissionType, permissionOrder, true);
|
381
|
}
|
382
|
}
|
383
|
catch(Exception e)
|
384
|
{
|
385
|
logMetacat.error("Error setting permissions on System Metadata object " +
|
386
|
" with id " + sysMetaLocalId + ": " + e.getMessage());
|
387
|
//TODO: decide if this error should cancel the entire create or
|
388
|
//if it should continue with just a logged error.
|
389
|
}
|
390
|
|
391
|
|
392
|
logMetacat.debug("Returning from CrudService.create()");
|
393
|
EventLog.getInstance().log(metacatUrl,
|
394
|
username, localId, "create");
|
395
|
logCrud.info("create D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId +
|
396
|
":D1SYSMETADATA:"+ sysMetaLocalId + ":");
|
397
|
return guid;
|
398
|
}
|
399
|
|
400
|
/**
|
401
|
* update an existing object with a new object. Change the system metadata
|
402
|
* to reflect the changes and update it as well.
|
403
|
*/
|
404
|
public Identifier update(AuthToken token, Identifier guid,
|
405
|
InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta)
|
406
|
throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique,
|
407
|
UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata,
|
408
|
NotImplemented {
|
409
|
try
|
410
|
{
|
411
|
SessionData sessionData = getSessionData(token);
|
412
|
|
413
|
//find the old systemmetadata (sm.old) document id (the one linked to obsoletedGuid)
|
414
|
SystemMetadata sm = getSystemMetadata(token, obsoletedGuid);
|
415
|
//change sm.old's obsoletedBy field
|
416
|
List l = sm.getObsoletedByList();
|
417
|
l.add(guid);
|
418
|
sm.setObsoletedByList(l);
|
419
|
//update sm.old
|
420
|
updateSystemMetadata(sm, sessionData);
|
421
|
|
422
|
//change the obsoletes field of the new systemMetadata (sm.new) to point to the id of the old one
|
423
|
sysmeta.addObsolete(obsoletedGuid);
|
424
|
//insert sm.new
|
425
|
String sysMetaLocalId = insertSystemMetadata(sysmeta, sessionData);
|
426
|
String localId;
|
427
|
|
428
|
boolean isScienceMetadata = isScienceMetadata(sysmeta);
|
429
|
if(isScienceMetadata)
|
430
|
{
|
431
|
//update the doc
|
432
|
localId = updateDocument(object, obsoletedGuid, guid, sessionData, false);
|
433
|
}
|
434
|
else
|
435
|
{
|
436
|
//update a data file, not xml
|
437
|
localId = insertDataObject(object, guid, sessionData);
|
438
|
}
|
439
|
|
440
|
IdentifierManager im = IdentifierManager.getInstance();
|
441
|
String username = "public";
|
442
|
if(sessionData != null)
|
443
|
{
|
444
|
username = sessionData.getUserName();
|
445
|
}
|
446
|
EventLog.getInstance().log(metacatUrl,
|
447
|
username, im.getLocalId(guid.getValue()), "update");
|
448
|
logCrud.info("update D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId +
|
449
|
":D1SYSMETADATA:"+ sysMetaLocalId + ":");
|
450
|
return guid;
|
451
|
}
|
452
|
catch(Exception e)
|
453
|
{
|
454
|
throw new ServiceFailure("1310", "Error updating document in CrudService: " + e.getMessage());
|
455
|
}
|
456
|
}
|
457
|
|
458
|
/**
|
459
|
* set access permissions on both the science metadata and system metadata
|
460
|
*/
|
461
|
public void setAccess(AuthToken token, Identifier id, String principal, String permission,
|
462
|
String permissionType, String permissionOrder)
|
463
|
throws ServiceFailure
|
464
|
{
|
465
|
setAccess(token, id, principal, permission, permissionType, permissionOrder, true);
|
466
|
}
|
467
|
|
468
|
/**
|
469
|
* set access control on the doc
|
470
|
* @param token
|
471
|
* @param id
|
472
|
* @param principal
|
473
|
* @param permission
|
474
|
*/
|
475
|
public void setAccess(AuthToken token, Identifier id, String principal, int permission,
|
476
|
String permissionType, String permissionOrder, boolean setSystemMetadata)
|
477
|
throws ServiceFailure
|
478
|
{
|
479
|
String perm = "";
|
480
|
if(permission >= 4)
|
481
|
{
|
482
|
perm = "read";
|
483
|
}
|
484
|
if(permission >= 6)
|
485
|
{
|
486
|
perm = "write";
|
487
|
}
|
488
|
//System.out.println("perm in setAccess: " + perm);
|
489
|
//System.out.println("permission in setAccess: " + permission);
|
490
|
setAccess(token, id, principal, perm, permissionType, permissionOrder,
|
491
|
setSystemMetadata);
|
492
|
|
493
|
}
|
494
|
|
495
|
/**
|
496
|
* set the permission on the document
|
497
|
* @param token
|
498
|
* @param principal
|
499
|
* @param permission
|
500
|
* @param permissionType
|
501
|
* @param permissionOrder
|
502
|
* @return
|
503
|
*/
|
504
|
public void setAccess(AuthToken token, Identifier id, String principal, String permission,
|
505
|
String permissionType, String permissionOrder, boolean setSystemMetadata)
|
506
|
throws ServiceFailure
|
507
|
{
|
508
|
/* TODO:
|
509
|
* This is also not part of the D1 Crud spec. This method is needed for
|
510
|
* systems such as metacat where access to objects is controlled by
|
511
|
* and ACL. Higher level decisions need to be made about how this
|
512
|
* should work within D1.
|
513
|
*/
|
514
|
try
|
515
|
{
|
516
|
final SessionData sessionData = getSessionData(token);
|
517
|
if(sessionData == null)
|
518
|
{
|
519
|
throw new ServiceFailure("1000", "User must be logged in to set access.");
|
520
|
}
|
521
|
IdentifierManager im = IdentifierManager.getInstance();
|
522
|
String docid = im.getLocalId(id.getValue());
|
523
|
|
524
|
String permNum = "0";
|
525
|
if(permission.equals("read"))
|
526
|
{
|
527
|
permNum = "4";
|
528
|
}
|
529
|
else if(permission.equals("write"))
|
530
|
{
|
531
|
permNum = "6";
|
532
|
}
|
533
|
System.out.println("user " + sessionData.getUserName() +
|
534
|
" is setting access level " + permNum + " for permission " +
|
535
|
permissionType + " on doc with localid " + docid);
|
536
|
handler.setAccess(metacatUrl, sessionData.getUserName(), docid,
|
537
|
principal, permNum, permissionType, permissionOrder);
|
538
|
if(setSystemMetadata)
|
539
|
{
|
540
|
//set the same perms on the system metadata doc
|
541
|
String smlocalid = im.getSystemMetadataLocalId(id.getValue());
|
542
|
System.out.println("setting access on SM doc with localid " + smlocalid);
|
543
|
//cs.setAccess(token, smid, principal, permission, permissionType, permissionOrder);
|
544
|
handler.setAccess(metacatUrl, sessionData.getUserName(), smlocalid,
|
545
|
principal, permNum, permissionType, permissionOrder);
|
546
|
}
|
547
|
String username = "public";
|
548
|
if(sessionData != null)
|
549
|
{
|
550
|
username = sessionData.getUserName();
|
551
|
}
|
552
|
EventLog.getInstance().log(metacatUrl,
|
553
|
username, im.getLocalId(id.getValue()), "setAccess");
|
554
|
logCrud.info("setAccess");
|
555
|
}
|
556
|
catch(Exception e)
|
557
|
{
|
558
|
e.printStackTrace();
|
559
|
throw new ServiceFailure("1000", "Could not set access on the document with id " + id.getValue());
|
560
|
}
|
561
|
}
|
562
|
|
563
|
/**
|
564
|
* Retrieve the list of objects present on the MN that match the calling
|
565
|
* parameters. This method is required to support the process of Member
|
566
|
* Node synchronization. At a minimum, this method should be able to
|
567
|
* return a list of objects that match:
|
568
|
* startTime <= SystemMetadata.dateSysMetadataModified
|
569
|
* but is expected to also support date range (by also specifying endTime),
|
570
|
* and should also support slicing of the matching set of records by
|
571
|
* indicating the starting index of the response (where 0 is the index
|
572
|
* of the first item) and the count of elements to be returned.
|
573
|
*
|
574
|
* If startTime or endTime is null, the query is not restricted by that parameter.
|
575
|
*
|
576
|
* @see http://mule1.dataone.org/ArchitectureDocs/mn_api_replication.html#MN_replication.listObjects
|
577
|
* @param token
|
578
|
* @param startTime
|
579
|
* @param endTime
|
580
|
* @param objectFormat
|
581
|
* @param replicaStatus
|
582
|
* @param start
|
583
|
* @param count
|
584
|
* @return ObjectList
|
585
|
* @throws NotAuthorized
|
586
|
* @throws InvalidRequest
|
587
|
* @throws NotImplemented
|
588
|
* @throws ServiceFailure
|
589
|
* @throws InvalidToken
|
590
|
*/
|
591
|
public ObjectList listObjects(AuthToken token, Date startTime, Date endTime,
|
592
|
ObjectFormat objectFormat, boolean replicaStatus, int start, int count)
|
593
|
throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
|
594
|
{
|
595
|
//ObjectList ol = new ObjectList();
|
596
|
//final SessionData sessionData = getSessionData(token);
|
597
|
//int totalAfterQuery = 0;
|
598
|
|
599
|
|
600
|
return IdentifierManager.getInstance().querySystemMetadata(startTime, endTime,
|
601
|
objectFormat, replicaStatus, start, count);
|
602
|
|
603
|
|
604
|
/////////////////////////////////////////////////////////////////////////
|
605
|
///////////////// OLD CODE //////////////////////////////////////////////
|
606
|
/////////////////////////////////////////////////////////////////////////
|
607
|
|
608
|
// try
|
609
|
// {
|
610
|
// if (PropertyService.getProperty("database.queryCacheOn").equals("true"))
|
611
|
// {
|
612
|
// //System.out.println("the string stored into cache is "+ resultsetBuffer.toString());
|
613
|
// DBQuery.clearQueryResultCache();
|
614
|
// }
|
615
|
// }
|
616
|
// catch (PropertyNotFoundException e1)
|
617
|
// {
|
618
|
// //just don't do anything
|
619
|
// }
|
620
|
//
|
621
|
// try
|
622
|
// {
|
623
|
// //TODO: Milliseconds need to be added to the dateFormat
|
624
|
// System.out.println("=========== Listing Objects =============");
|
625
|
// System.out.println("Current server time is: " + new Date());
|
626
|
// if(startTime != null)
|
627
|
// {
|
628
|
// System.out.println("query start time is " + startTime);
|
629
|
// }
|
630
|
// if(endTime != null)
|
631
|
// {
|
632
|
// System.out.println("query end time is " + endTime);
|
633
|
// }
|
634
|
// params.clear();
|
635
|
// params.put("qformat", new String[] {PropertyService.getProperty("crudService.listObjects.QFormat")});
|
636
|
// params.put("action", new String[] {"squery"});
|
637
|
// params.put("query", new String[] {createListObjectsPathQueryDocument()});
|
638
|
//
|
639
|
// /*System.out.println("query is: metacatUrl: " + metacatUrl + " user: " + sessionData.getUserName() +
|
640
|
// " sessionid: " + sessionData.getId() + " params: ");
|
641
|
// String url = metacatUrl + "/metacat?action=query&sessionid=" + sessionData.getId();
|
642
|
// Enumeration keys = params.keys();
|
643
|
// while(keys.hasMoreElements())
|
644
|
// {
|
645
|
// String key = (String)keys.nextElement();
|
646
|
// String[] parr = params.get(key);
|
647
|
// for(int i=0; i<parr.length; i++)
|
648
|
// {
|
649
|
// System.out.println("param " + key + ": " + parr[i]);
|
650
|
// url += "&" + key + "=" + parr[i] ;
|
651
|
// }
|
652
|
// }
|
653
|
// System.out.println("query url: " + url);
|
654
|
// */
|
655
|
// String username = "public";
|
656
|
// String[] groups = null;
|
657
|
// String sessionid = "";
|
658
|
// if(sessionData != null)
|
659
|
// {
|
660
|
// username = sessionData.getUserName();
|
661
|
// groups = sessionData.getGroupNames();
|
662
|
// sessionid = sessionData.getId();
|
663
|
// }
|
664
|
//
|
665
|
// MetacatResultSet rs = handler.query(metacatUrl, params, username,
|
666
|
// groups, sessionid);
|
667
|
// List docs = rs.getDocuments();
|
668
|
//
|
669
|
// System.out.println("query returned " + docs.size() + " documents.");
|
670
|
// Vector<Document> docCopy = new Vector<Document>();
|
671
|
//
|
672
|
// //preparse the list to remove any that don't match the query params
|
673
|
// /* TODO: this type of query/subquery processing is probably not scalable
|
674
|
// * to larger object stores. This code should be revisited. The metacat
|
675
|
// * query handler should probably be altered to handle the type of query
|
676
|
// * done here.
|
677
|
// */
|
678
|
// for(int i=0; i<docs.size(); i++)
|
679
|
// {
|
680
|
// Document d = (Document)docs.get(i);
|
681
|
//
|
682
|
// ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
|
683
|
//
|
684
|
// if(returnedObjectFormat != null &&
|
685
|
// objectFormat != null &&
|
686
|
// !objectFormat.toString().trim().equals(returnedObjectFormat.toString().trim()))
|
687
|
// { //make sure the objectFormat is the one specified
|
688
|
// continue;
|
689
|
// }
|
690
|
//
|
691
|
// String dateSMM = d.getField("dateSysMetadataModified");
|
692
|
// if((startTime != null || endTime != null) && dateSMM == null)
|
693
|
// { //if startTime or endTime are not null, we need a date to compare to
|
694
|
// continue;
|
695
|
// }
|
696
|
//
|
697
|
// //date parse
|
698
|
// Date dateSysMetadataModified = null;
|
699
|
// if(dateSMM != null)
|
700
|
// {
|
701
|
//
|
702
|
// /*
|
703
|
// if(dateSMM.indexOf(".") != -1)
|
704
|
// { //strip the milliseconds
|
705
|
// //TODO: don't do this. we need milliseconds now.
|
706
|
// //TODO: explore ISO 8601 to figure out milliseconds
|
707
|
// dateSMM = dateSMM.substring(0, dateSMM.indexOf(".")) + 'Z';
|
708
|
// }
|
709
|
// */
|
710
|
// //System.out.println("dateSMM: " + dateSMM);
|
711
|
// //dateFormat.setTimeZone(TimeZone.getTimeZone("GMT-0"));
|
712
|
// try
|
713
|
// { //the format we want
|
714
|
// dateSysMetadataModified = dateFormat.parse(dateSMM);
|
715
|
// }
|
716
|
// catch(java.text.ParseException pe)
|
717
|
// { //try another legacy format
|
718
|
// try
|
719
|
// {
|
720
|
// DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.S'Z'");
|
721
|
// dateFormat2.setTimeZone(TimeZone.getTimeZone("GMT-0"));
|
722
|
// dateSysMetadataModified = dateFormat2.parse(dateSMM);
|
723
|
// }
|
724
|
// catch(java.text.ParseException pe2)
|
725
|
// {
|
726
|
// //try another legacy format
|
727
|
// DateFormat dateFormat3 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
|
728
|
// dateFormat3.setTimeZone(TimeZone.getTimeZone("GMT-0"));
|
729
|
// dateSysMetadataModified = dateFormat3.parse(dateSMM);
|
730
|
// }
|
731
|
//
|
732
|
// }
|
733
|
// }
|
734
|
//
|
735
|
// /*System.out.println("====================================");
|
736
|
// System.out.println("doc number " + i);
|
737
|
// System.out.println("docid: " + d.docid);
|
738
|
// System.out.println("guid: " + d.getField("identifier").trim());
|
739
|
// System.out.println("dateSMM: " + dateSMM);
|
740
|
// System.out.println("dateSysMetadataModified: " + dateSysMetadataModified);
|
741
|
// System.out.println("startTime: " + startTime);
|
742
|
// System.out.println("endtime: " + endTime);*/
|
743
|
//
|
744
|
// int startDateComparison = 0;
|
745
|
// int endDateComparison = 0;
|
746
|
// if(startTime != null)
|
747
|
// {
|
748
|
// Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
|
749
|
// zTime.setTime(startTime);
|
750
|
// startTime = zTime.getTime();
|
751
|
//
|
752
|
// if(dateSysMetadataModified == null)
|
753
|
// {
|
754
|
// startDateComparison = -1;
|
755
|
// }
|
756
|
// else
|
757
|
// {
|
758
|
// startDateComparison = dateSysMetadataModified.compareTo(startTime);
|
759
|
// }
|
760
|
// //System.out.println("startDateCom: " + startDateComparison);
|
761
|
// }
|
762
|
// else
|
763
|
// {
|
764
|
// startDateComparison = 1;
|
765
|
// }
|
766
|
//
|
767
|
// if(endTime != null)
|
768
|
// {
|
769
|
// Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
|
770
|
// zTime.setTime(endTime);
|
771
|
// endTime = zTime.getTime();
|
772
|
//
|
773
|
// if(dateSysMetadataModified == null)
|
774
|
// {
|
775
|
// endDateComparison = 1;
|
776
|
// }
|
777
|
// else
|
778
|
// {
|
779
|
// endDateComparison = dateSysMetadataModified.compareTo(endTime);
|
780
|
// }
|
781
|
// //System.out.println("endDateCom: " + endDateComparison);
|
782
|
// }
|
783
|
// else
|
784
|
// {
|
785
|
// endDateComparison = -1;
|
786
|
// }
|
787
|
//
|
788
|
//
|
789
|
// if(startDateComparison < 0 || endDateComparison > 0)
|
790
|
// {
|
791
|
// continue;
|
792
|
// }
|
793
|
//
|
794
|
// docCopy.add((Document)docs.get(i));
|
795
|
// } //end pre-parse
|
796
|
//
|
797
|
// docs = docCopy;
|
798
|
// totalAfterQuery = docs.size();
|
799
|
// //System.out.println("total after subquery: " + totalAfterQuery);
|
800
|
//
|
801
|
// //make sure we don't run over the end
|
802
|
// int end = start + count;
|
803
|
// if(end > docs.size())
|
804
|
// {
|
805
|
// end = docs.size();
|
806
|
// }
|
807
|
//
|
808
|
// for(int i=start; i<end; i++)
|
809
|
// {
|
810
|
// //get the document from the result
|
811
|
// Document d = (Document)docs.get(i);
|
812
|
// //System.out.println("processing doc " + d.docid);
|
813
|
//
|
814
|
// String dateSMM = d.getField("dateSysMetadataModified");
|
815
|
// //System.out.println("dateSMM: " + dateSMM);
|
816
|
// //System.out.println("parsed date: " + parseDate(dateSMM));
|
817
|
// Date dateSysMetadataModified = null;
|
818
|
// if(dateSMM != null)
|
819
|
// {
|
820
|
// try
|
821
|
// {
|
822
|
// dateSysMetadataModified = parseDate(dateSMM);
|
823
|
// }
|
824
|
// catch(Exception e)
|
825
|
// { //if we fail to parse the date, just ignore the value
|
826
|
// dateSysMetadataModified = null;
|
827
|
// }
|
828
|
// }
|
829
|
// ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
|
830
|
//
|
831
|
//
|
832
|
// ObjectInfo info = new ObjectInfo();
|
833
|
// //add the fields to the info object
|
834
|
// Checksum cs = new Checksum();
|
835
|
// cs.setValue(d.getField("checksum"));
|
836
|
// String csalg = d.getField("algorithm");
|
837
|
// if(csalg == null)
|
838
|
// {
|
839
|
// csalg = "MD5";
|
840
|
// }
|
841
|
// ChecksumAlgorithm ca = ChecksumAlgorithm.convert(csalg);
|
842
|
// cs.setAlgorithm(ca);
|
843
|
// info.setChecksum(cs);
|
844
|
// info.setDateSysMetadataModified(dateSysMetadataModified);
|
845
|
// Identifier id = new Identifier();
|
846
|
// id.setValue(d.getField("identifier").trim());
|
847
|
// info.setIdentifier(id);
|
848
|
// info.setObjectFormat(returnedObjectFormat);
|
849
|
// String size = d.getField("size");
|
850
|
// if(size != null)
|
851
|
// {
|
852
|
// info.setSize(new Long(size.trim()).longValue());
|
853
|
// }
|
854
|
// //add the ObjectInfo to the ObjectList
|
855
|
// //logCrud.info("objectFormat: " + info.getObjectFormat().toString());
|
856
|
// //logCrud.info("id: " + info.getIdentifier().getValue());
|
857
|
//
|
858
|
// if(info.getIdentifier().getValue() != null)
|
859
|
// { //id can be null from tests. should not happen in production.
|
860
|
// if((info.getObjectFormat() != null && !info.getObjectFormat().toString().trim().equals("")))
|
861
|
// { //objectFormat needs to not be null and not be an empty string
|
862
|
// ol.addObjectInfo(info);
|
863
|
// }
|
864
|
// else
|
865
|
// {
|
866
|
// logCrud.info("Not adding object with null objectFormat" + info.getIdentifier().getValue().toString());
|
867
|
// }
|
868
|
// }
|
869
|
//
|
870
|
// }
|
871
|
// }
|
872
|
// catch(Exception e)
|
873
|
// {
|
874
|
// e.printStackTrace();
|
875
|
// logCrud.error("Error creating ObjectList: " + e.getMessage() + " cause: " + e.getCause());
|
876
|
// throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
|
877
|
// }
|
878
|
// String username = "public";
|
879
|
// if(sessionData != null)
|
880
|
// {
|
881
|
// username = sessionData.getUserName();
|
882
|
// }
|
883
|
// EventLog.getInstance().log(metacatUrl,
|
884
|
// username, null, "read");
|
885
|
// logCrud.info("listObjects");
|
886
|
// if(totalAfterQuery < count)
|
887
|
// {
|
888
|
// count = totalAfterQuery;
|
889
|
// }
|
890
|
// ol.setCount(count);
|
891
|
// ol.setStart(start);
|
892
|
// ol.setTotal(totalAfterQuery);
|
893
|
// return ol;
|
894
|
}
|
895
|
|
896
|
/**
|
897
|
* Call listObjects with the default values for replicaStatus (true), start (0),
|
898
|
* and count (1000).
|
899
|
* @param token
|
900
|
* @param startTime
|
901
|
* @param endTime
|
902
|
* @param objectFormat
|
903
|
* @return
|
904
|
* @throws NotAuthorized
|
905
|
* @throws InvalidRequest
|
906
|
* @throws NotImplemented
|
907
|
* @throws ServiceFailure
|
908
|
* @throws InvalidToken
|
909
|
*/
|
910
|
public ObjectList listObjects(AuthToken token, Date startTime, Date endTime,
|
911
|
ObjectFormat objectFormat)
|
912
|
throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
|
913
|
{
|
914
|
return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
|
915
|
}
|
916
|
|
917
|
/**
|
918
|
* Delete a document.
|
919
|
*/
|
920
|
public Identifier delete(AuthToken token, Identifier guid)
|
921
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
922
|
NotImplemented, InvalidRequest {
|
923
|
logCrud.info("delete");
|
924
|
|
925
|
if(token == null || token.getToken().equals("publid"))
|
926
|
{
|
927
|
throw new NotAuthorized("1320", "You must be logged in to delete records.");
|
928
|
}
|
929
|
|
930
|
if(guid == null || guid.getValue().trim().equals(""))
|
931
|
{
|
932
|
throw new InvalidRequest("1322", "No GUID specified in CrudService.delete()");
|
933
|
}
|
934
|
final SessionData sessionData = getSessionData(token);
|
935
|
IdentifierManager manager = IdentifierManager.getInstance();
|
936
|
|
937
|
String docid;
|
938
|
try
|
939
|
{
|
940
|
docid = manager.getLocalId(guid.getValue());
|
941
|
}
|
942
|
catch(McdbDocNotFoundException mnfe)
|
943
|
{
|
944
|
throw new InvalidRequest("1322", "GUID " + guid + " not found.");
|
945
|
}
|
946
|
|
947
|
try
|
948
|
{
|
949
|
DocumentImpl.delete(docid, sessionData.getUserName(), sessionData.getGroupNames(), null);
|
950
|
}
|
951
|
catch(Exception e)
|
952
|
{
|
953
|
throw new ServiceFailure("1350", "Could not delete document: " + e.getMessage());
|
954
|
}
|
955
|
|
956
|
return guid;
|
957
|
}
|
958
|
|
959
|
/**
|
960
|
* describe a document.
|
961
|
*/
|
962
|
public DescribeResponse describe(AuthToken token, Identifier guid)
|
963
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
964
|
NotImplemented, InvalidRequest {
|
965
|
logCrud.info("describe");
|
966
|
|
967
|
if(token == null)
|
968
|
{
|
969
|
throw new InvalidToken("1370", "Authentication token is null");
|
970
|
}
|
971
|
|
972
|
if(guid == null || guid.getValue().trim().equals(""))
|
973
|
{
|
974
|
throw new InvalidRequest("1362", "Guid is null. A valid guid is required.");
|
975
|
}
|
976
|
|
977
|
SystemMetadata sm = getSystemMetadata(token, guid);
|
978
|
DescribeResponse dr = new DescribeResponse(sm.getObjectFormat(),
|
979
|
sm.getSize(), sm.getDateSysMetadataModified(), sm.getChecksum());
|
980
|
return dr;
|
981
|
}
|
982
|
|
983
|
/**
|
984
|
* get a document with a specified guid.
|
985
|
*/
|
986
|
public InputStream get(AuthToken token, Identifier guid)
|
987
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
988
|
NotImplemented {
|
989
|
|
990
|
// Retrieve the session information from the AuthToken
|
991
|
// If the session is expired, then the user is 'public'
|
992
|
if(token == null)
|
993
|
{
|
994
|
token = new AuthToken("Public");
|
995
|
}
|
996
|
final SessionData sessionData = getSessionData(token);
|
997
|
|
998
|
// Look up the localId for this global identifier
|
999
|
IdentifierManager im = IdentifierManager.getInstance();
|
1000
|
|
1001
|
try
|
1002
|
{
|
1003
|
final String localId = im.getLocalId(guid.getValue());
|
1004
|
InputStream objectStream;
|
1005
|
try
|
1006
|
{
|
1007
|
String username = "public";
|
1008
|
String[] groups = new String[0];
|
1009
|
if(sessionData != null)
|
1010
|
{
|
1011
|
username = sessionData.getUserName();
|
1012
|
groups = sessionData.getGroupNames();
|
1013
|
}
|
1014
|
|
1015
|
objectStream = readFromMetacat(localId, username, groups);
|
1016
|
|
1017
|
} catch (PropertyNotFoundException e) {
|
1018
|
e.printStackTrace();
|
1019
|
throw new ServiceFailure("1030", "Error getting property from metacat: " + e.getMessage());
|
1020
|
} catch (ClassNotFoundException e) {
|
1021
|
e.printStackTrace();
|
1022
|
throw new ServiceFailure("1030", "Class not found error when reading from metacat: " + e.getMessage());
|
1023
|
} catch (IOException e) {
|
1024
|
e.printStackTrace();
|
1025
|
throw new ServiceFailure("1030", "IOException while reading from metacat: " + e.getMessage());
|
1026
|
} catch (SQLException e) {
|
1027
|
e.printStackTrace();
|
1028
|
throw new ServiceFailure("1030", "SQLException while reading from metacat: " + e.getMessage());
|
1029
|
} catch (McdbException e) {
|
1030
|
e.printStackTrace();
|
1031
|
throw new ServiceFailure("1030", "Metacat DB exception while reading from metacat: " + e.getMessage());
|
1032
|
} catch (ParseLSIDException e) {
|
1033
|
e.printStackTrace();
|
1034
|
throw new NotFound("1020", "LSID parsing exception while reading from metacat: " + e.getMessage());
|
1035
|
} catch (InsufficientKarmaException e) {
|
1036
|
e.printStackTrace();
|
1037
|
throw new NotAuthorized("1000", "User not authorized for get(): " + e.getMessage());
|
1038
|
}
|
1039
|
|
1040
|
|
1041
|
String username = "public";
|
1042
|
if(sessionData != null)
|
1043
|
{
|
1044
|
username = sessionData.getUserName();
|
1045
|
}
|
1046
|
|
1047
|
EventLog.getInstance().log(metacatUrl,
|
1048
|
username, im.getLocalId(guid.getValue()), "read");
|
1049
|
logCrud.info("get D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId +
|
1050
|
":");
|
1051
|
|
1052
|
return objectStream;
|
1053
|
}
|
1054
|
catch (McdbDocNotFoundException e)
|
1055
|
{
|
1056
|
throw new NotFound("1020", e.getMessage());
|
1057
|
}
|
1058
|
}
|
1059
|
|
1060
|
/**
|
1061
|
* get the checksum for a document. defaults to MD5.
|
1062
|
*/
|
1063
|
public Checksum getChecksum(AuthToken token, Identifier guid)
|
1064
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
1065
|
InvalidRequest, NotImplemented
|
1066
|
{
|
1067
|
logCrud.info("getChecksum");
|
1068
|
return getChecksum(token, guid, "MD5");
|
1069
|
}
|
1070
|
|
1071
|
/**
|
1072
|
* get the checksum for a document with the given algorithm
|
1073
|
*/
|
1074
|
public Checksum getChecksum(AuthToken token, Identifier guid,
|
1075
|
String checksumAlgorithm) throws InvalidToken, ServiceFailure,
|
1076
|
NotAuthorized, NotFound, InvalidRequest, NotImplemented
|
1077
|
{
|
1078
|
logCrud.info("getChecksum");
|
1079
|
SystemMetadata sm = getSystemMetadata(token, guid);
|
1080
|
Checksum cs = sm.getChecksum();
|
1081
|
if(cs.getAlgorithm().toString().equals(checksumAlgorithm))
|
1082
|
{
|
1083
|
return cs;
|
1084
|
}
|
1085
|
else
|
1086
|
{
|
1087
|
if(checksumAlgorithm == null)
|
1088
|
{
|
1089
|
checksumAlgorithm = "MD5";
|
1090
|
}
|
1091
|
InputStream docStream = get(token, guid);
|
1092
|
String checksum;
|
1093
|
try
|
1094
|
{
|
1095
|
checksum = checksum(docStream, checksumAlgorithm);
|
1096
|
}
|
1097
|
catch(Exception e)
|
1098
|
{
|
1099
|
throw new ServiceFailure("1410", "Error getting checksum: " + e.getMessage());
|
1100
|
}
|
1101
|
Checksum c = new Checksum();
|
1102
|
c.setAlgorithm(ChecksumAlgorithm.convert(checksumAlgorithm));
|
1103
|
c.setValue(checksum);
|
1104
|
return c;
|
1105
|
}
|
1106
|
}
|
1107
|
|
1108
|
/**
|
1109
|
* get log records.
|
1110
|
*/
|
1111
|
public Log getLogRecords(AuthToken token, Date fromDate, Date toDate, Event event)
|
1112
|
throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest,
|
1113
|
NotImplemented
|
1114
|
{
|
1115
|
/*System.out.println("=================== Getting log records ===================");
|
1116
|
System.out.println("Current server time is: " + new Date());
|
1117
|
if(fromDate != null)
|
1118
|
{
|
1119
|
System.out.println("query start time is " + fromDate);
|
1120
|
}
|
1121
|
if(toDate != null)
|
1122
|
{
|
1123
|
System.out.println("query end time is " + toDate);
|
1124
|
}*/
|
1125
|
Log log = new Log();
|
1126
|
Vector<LogEntry> logs = new Vector<LogEntry>();
|
1127
|
IdentifierManager im = IdentifierManager.getInstance();
|
1128
|
EventLog el = EventLog.getInstance();
|
1129
|
if(fromDate == null)
|
1130
|
{
|
1131
|
//System.out.println("setting fromdate from null");
|
1132
|
fromDate = new Date(1);
|
1133
|
}
|
1134
|
if(toDate == null)
|
1135
|
{
|
1136
|
//System.out.println("setting todate from null");
|
1137
|
toDate = new Date();
|
1138
|
}
|
1139
|
|
1140
|
//System.out.println("fromDate: " + fromDate);
|
1141
|
//System.out.println("toDate: " + toDate);
|
1142
|
|
1143
|
String report = el.getReport(null, null, null, null,
|
1144
|
new java.sql.Timestamp(fromDate.getTime()),
|
1145
|
new java.sql.Timestamp(toDate.getTime()), false);
|
1146
|
|
1147
|
//System.out.println("report: " + report);
|
1148
|
|
1149
|
String logEntry = "<logEntry>";
|
1150
|
String endLogEntry = "</logEntry>";
|
1151
|
int startIndex = 0;
|
1152
|
int foundIndex = report.indexOf(logEntry, startIndex);
|
1153
|
while(foundIndex != -1)
|
1154
|
{
|
1155
|
//parse out each entry
|
1156
|
int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
|
1157
|
String entry = report.substring(foundIndex, endEntryIndex);
|
1158
|
//System.out.println("entry: " + entry);
|
1159
|
startIndex = endEntryIndex + endLogEntry.length();
|
1160
|
foundIndex = report.indexOf(logEntry, startIndex);
|
1161
|
|
1162
|
String entryId = getLogEntryField("entryid", entry);
|
1163
|
String ipAddress = getLogEntryField("ipAddress", entry);
|
1164
|
String principal = getLogEntryField("principal", entry);
|
1165
|
String docid = getLogEntryField("docid", entry);
|
1166
|
String eventS = getLogEntryField("event", entry);
|
1167
|
String dateLogged = getLogEntryField("dateLogged", entry);
|
1168
|
|
1169
|
LogEntry le = new LogEntry();
|
1170
|
|
1171
|
Event e = Event.convert(eventS);
|
1172
|
if(e == null)
|
1173
|
{ //skip any events that are not Dataone Crud events
|
1174
|
continue;
|
1175
|
}
|
1176
|
le.setEvent(e);
|
1177
|
Identifier entryid = new Identifier();
|
1178
|
entryid.setValue(entryId);
|
1179
|
le.setEntryId(entryid);
|
1180
|
Identifier identifier = new Identifier();
|
1181
|
try
|
1182
|
{
|
1183
|
//System.out.println("converting docid '" + docid + "' to a guid.");
|
1184
|
if(docid == null || docid.trim().equals("") || docid.trim().equals("null"))
|
1185
|
{
|
1186
|
continue;
|
1187
|
}
|
1188
|
docid = docid.substring(0, docid.lastIndexOf("."));
|
1189
|
identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
|
1190
|
}
|
1191
|
catch(Exception ex)
|
1192
|
{ //try to get the guid, if that doesn't work, just use the local id
|
1193
|
//throw new ServiceFailure("1030", "Error getting guid for localId " +
|
1194
|
// docid + ": " + ex.getMessage());\
|
1195
|
|
1196
|
//skip it if the guid can't be found
|
1197
|
continue;
|
1198
|
}
|
1199
|
|
1200
|
le.setIdentifier(identifier);
|
1201
|
le.setIpAddress(ipAddress);
|
1202
|
Calendar c = Calendar.getInstance();
|
1203
|
String year = dateLogged.substring(0, 4);
|
1204
|
String month = dateLogged.substring(5, 7);
|
1205
|
String date = dateLogged.substring(8, 10);
|
1206
|
//System.out.println("year: " + year + " month: " + month + " day: " + date);
|
1207
|
c.set(new Integer(year).intValue(), new Integer(month).intValue(), new Integer(date).intValue());
|
1208
|
Date logDate = c.getTime();
|
1209
|
le.setDateLogged(logDate);
|
1210
|
NodeReference memberNode = new NodeReference();
|
1211
|
memberNode.setValue(ipAddress);
|
1212
|
le.setMemberNode(memberNode);
|
1213
|
Principal princ = new Principal();
|
1214
|
princ.setValue(principal);
|
1215
|
le.setPrincipal(princ);
|
1216
|
le.setUserAgent("metacat/RESTService");
|
1217
|
|
1218
|
if(event == null)
|
1219
|
{
|
1220
|
logs.add(le);
|
1221
|
}
|
1222
|
|
1223
|
if(event != null &&
|
1224
|
e.toString().toLowerCase().trim().equals(event.toString().toLowerCase().trim()))
|
1225
|
{
|
1226
|
logs.add(le);
|
1227
|
}
|
1228
|
}
|
1229
|
|
1230
|
log.setLogEntryList(logs);
|
1231
|
logCrud.info("getLogRecords");
|
1232
|
return log;
|
1233
|
}
|
1234
|
|
1235
|
/**
|
1236
|
* parse a logEntry and get the relavent field from it
|
1237
|
* @param fieldname
|
1238
|
* @param entry
|
1239
|
* @return
|
1240
|
*/
|
1241
|
private String getLogEntryField(String fieldname, String entry)
|
1242
|
{
|
1243
|
String begin = "<" + fieldname + ">";
|
1244
|
String end = "</" + fieldname + ">";
|
1245
|
//System.out.println("looking for " + begin + " and " + end + " in entry " + entry);
|
1246
|
String s = entry.substring(entry.indexOf(begin) + begin.length(), entry.indexOf(end));
|
1247
|
//System.out.println("entry " + fieldname + " : " + s);
|
1248
|
return s;
|
1249
|
}
|
1250
|
|
1251
|
/**
|
1252
|
* get the system metadata for a document with a specified guid.
|
1253
|
*/
|
1254
|
public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
|
1255
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
1256
|
InvalidRequest, NotImplemented {
|
1257
|
|
1258
|
logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
|
1259
|
|
1260
|
// Retrieve the session information from the AuthToken
|
1261
|
// If the session is expired, then the user is 'public'
|
1262
|
final SessionData sessionData = getSessionData(token);
|
1263
|
|
1264
|
try {
|
1265
|
IdentifierManager im = IdentifierManager.getInstance();
|
1266
|
final String localId = im.getSystemMetadataLocalId(guid.getValue());
|
1267
|
InputStream objectStream;
|
1268
|
|
1269
|
try {
|
1270
|
String username = "public";
|
1271
|
String[] groupnames = null;
|
1272
|
if(sessionData != null)
|
1273
|
{
|
1274
|
username = sessionData.getUserName();
|
1275
|
groupnames = sessionData.getGroupNames();
|
1276
|
}
|
1277
|
|
1278
|
objectStream = readFromMetacat(localId, username, groupnames);
|
1279
|
|
1280
|
} catch (PropertyNotFoundException e) {
|
1281
|
e.printStackTrace();
|
1282
|
throw new ServiceFailure("1090", "Property not found while reading system metadata from metacat: " + e.getMessage());
|
1283
|
} catch (ClassNotFoundException e) {
|
1284
|
e.printStackTrace();
|
1285
|
throw new ServiceFailure("1090", "Class not found while reading system metadata from metacat: " + e.getMessage());
|
1286
|
} catch (IOException e) {
|
1287
|
e.printStackTrace();
|
1288
|
throw new ServiceFailure("1090", "IOException while reading system metadata from metacat: " + e.getMessage());
|
1289
|
} catch (SQLException e) {
|
1290
|
e.printStackTrace();
|
1291
|
throw new ServiceFailure("1090", "SQLException while reading system metadata from metacat: " + e.getMessage());
|
1292
|
} catch (McdbException e) {
|
1293
|
e.printStackTrace();
|
1294
|
throw new ServiceFailure("1090", "Metacat DB Exception while reading system metadata from metacat: " + e.getMessage());
|
1295
|
} catch (ParseLSIDException e) {
|
1296
|
e.printStackTrace();
|
1297
|
throw new NotFound("1060", "Error parsing LSID while reading system metadata from metacat: " + e.getMessage());
|
1298
|
} catch (InsufficientKarmaException e) {
|
1299
|
e.printStackTrace();
|
1300
|
throw new NotAuthorized("1040", "User not authorized for get() on system metadata: " + e.getMessage());
|
1301
|
}
|
1302
|
|
1303
|
// Deserialize the xml to create a SystemMetadata object
|
1304
|
SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
|
1305
|
String username = "public";
|
1306
|
if(sessionData != null)
|
1307
|
{
|
1308
|
username = sessionData.getUserName();
|
1309
|
}
|
1310
|
EventLog.getInstance().log(metacatUrl,
|
1311
|
username, im.getLocalId(guid.getValue()), "read");
|
1312
|
logCrud.info("getsystemmetadata D1GUID:" + guid.getValue() +
|
1313
|
":D1SYSMETADATA:"+ localId + ":");
|
1314
|
return sysmeta;
|
1315
|
|
1316
|
} catch (McdbDocNotFoundException e) {
|
1317
|
//e.printStackTrace();
|
1318
|
throw new NotFound("1040", e.getMessage());
|
1319
|
}
|
1320
|
}
|
1321
|
|
1322
|
/**
|
1323
|
* parse the date in the systemMetadata
|
1324
|
* @param s
|
1325
|
* @return
|
1326
|
* @throws Exception
|
1327
|
*/
|
1328
|
public Date parseDate(String s)
|
1329
|
throws Exception
|
1330
|
{
|
1331
|
/* TODO:
|
1332
|
* This method should be replaced by a DateFormatter
|
1333
|
*/
|
1334
|
Date d = null;
|
1335
|
int tIndex = s.indexOf("T");
|
1336
|
int zIndex = s.indexOf("Z");
|
1337
|
if(tIndex != -1 && zIndex != -1)
|
1338
|
{ //parse a date that looks like 2010-05-18T21:12:54.362Z
|
1339
|
//System.out.println("original date: " + s);
|
1340
|
|
1341
|
String date = s.substring(0, tIndex);
|
1342
|
String year = date.substring(0, date.indexOf("-"));
|
1343
|
String month = date.substring(date.indexOf("-") + 1, date.lastIndexOf("-"));
|
1344
|
String day = date.substring(date.lastIndexOf("-") + 1, date.length());
|
1345
|
/*System.out.println("date: " + "year: " + new Integer(year).intValue() +
|
1346
|
" month: " + new Integer(month).intValue() + " day: " +
|
1347
|
new Integer(day).intValue());
|
1348
|
*/
|
1349
|
String time = s.substring(tIndex + 1, zIndex);
|
1350
|
String hour = time.substring(0, time.indexOf(":"));
|
1351
|
String minute = time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"));
|
1352
|
String seconds = "00";
|
1353
|
String milliseconds = "00";
|
1354
|
if(time.indexOf(".") != -1)
|
1355
|
{
|
1356
|
seconds = time.substring(time.lastIndexOf(":") + 1, time.indexOf("."));
|
1357
|
milliseconds = time.substring(time.indexOf(".") + 1, time.length());
|
1358
|
}
|
1359
|
else
|
1360
|
{
|
1361
|
seconds = time.substring(time.lastIndexOf(":") + 1, time.length());
|
1362
|
}
|
1363
|
/*System.out.println("time: " + "hour: " + new Integer(hour).intValue() +
|
1364
|
" minute: " + new Integer(minute).intValue() + " seconds: " +
|
1365
|
new Integer(seconds).intValue() + " milli: " +
|
1366
|
new Integer(milliseconds).intValue());*/
|
1367
|
|
1368
|
//d = DateFormat.getDateTimeInstance().parse(date + " " + time);
|
1369
|
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-0")/*TimeZone.getDefault()*/);
|
1370
|
c.set(new Integer(year).intValue(), new Integer(month).intValue() - 1,
|
1371
|
new Integer(day).intValue(), new Integer(hour).intValue(),
|
1372
|
new Integer(minute).intValue(), new Integer(seconds).intValue());
|
1373
|
c.set(Calendar.MILLISECOND, new Integer(milliseconds).intValue());
|
1374
|
d = new Date(c.getTimeInMillis());
|
1375
|
//System.out.println("d: " + d);
|
1376
|
return d;
|
1377
|
}
|
1378
|
else
|
1379
|
{ //if it's not in the expected format, try the formatter
|
1380
|
return DateFormat.getDateTimeInstance().parse(s);
|
1381
|
}
|
1382
|
}
|
1383
|
|
1384
|
/*
|
1385
|
* Look up the information on the session using the token provided in
|
1386
|
* the AuthToken. The Session should have all relevant user information.
|
1387
|
* If the session has expired or is invalid, the 'public' session will
|
1388
|
* be returned, giving the user anonymous access.
|
1389
|
*/
|
1390
|
public static SessionData getSessionData(AuthToken token) {
|
1391
|
SessionData sessionData = null;
|
1392
|
String sessionId = "PUBLIC";
|
1393
|
if (token != null) {
|
1394
|
sessionId = token.getToken();
|
1395
|
}
|
1396
|
|
1397
|
// if the session id is registered in SessionService, get the
|
1398
|
// SessionData for it. Otherwise, use the public session.
|
1399
|
//System.out.println("sessionid: " + sessionId);
|
1400
|
if (sessionId != null &&
|
1401
|
!sessionId.toLowerCase().equals("public") &&
|
1402
|
SessionService.getInstance().isSessionRegistered(sessionId))
|
1403
|
{
|
1404
|
sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
|
1405
|
} else {
|
1406
|
sessionData = SessionService.getInstance().getPublicSession();
|
1407
|
}
|
1408
|
|
1409
|
return sessionData;
|
1410
|
}
|
1411
|
|
1412
|
/**
|
1413
|
* Determine if a given object should be treated as an XML science metadata
|
1414
|
* object.
|
1415
|
*
|
1416
|
* TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
|
1417
|
*
|
1418
|
* @param sysmeta the SystemMetadata describig the object
|
1419
|
* @return true if the object should be treated as science metadata
|
1420
|
*/
|
1421
|
private boolean isScienceMetadata(SystemMetadata sysmeta) {
|
1422
|
/*boolean scimeta = false;
|
1423
|
//TODO: this should be read from a .properties file instead of being hard coded
|
1424
|
switch (sysmeta.getObjectFormat()) {
|
1425
|
case EML_2_1_0: scimeta = true; break;
|
1426
|
case EML_2_0_1: scimeta = true; break;
|
1427
|
case EML_2_0_0: scimeta = true; break;
|
1428
|
case FGDC_STD_001_1_1999: scimeta = true; break;
|
1429
|
case FGDC_STD_001_1998: scimeta = true; break;
|
1430
|
case NCML_2_2: scimeta = true; break;
|
1431
|
case DSPACE_METS_SIP_1_0: scimeta = true; break;
|
1432
|
}
|
1433
|
|
1434
|
return scimeta;*/
|
1435
|
|
1436
|
return MetadataTypeRegister.isMetadataType(sysmeta.getObjectFormat());
|
1437
|
}
|
1438
|
|
1439
|
/**
|
1440
|
* insert a data doc
|
1441
|
* @param object
|
1442
|
* @param guid
|
1443
|
* @param sessionData
|
1444
|
* @throws ServiceFailure
|
1445
|
* @returns localId of the data object inserted
|
1446
|
*/
|
1447
|
private String insertDataObject(InputStream object, Identifier guid,
|
1448
|
SessionData sessionData) throws ServiceFailure {
|
1449
|
|
1450
|
String username = "public";
|
1451
|
String[] groups = null;
|
1452
|
if(sessionData != null)
|
1453
|
{
|
1454
|
username = sessionData.getUserName();
|
1455
|
groups = sessionData.getGroupNames();
|
1456
|
}
|
1457
|
|
1458
|
// generate guid/localId pair for object
|
1459
|
logMetacat.debug("Generating a guid/localId mapping");
|
1460
|
IdentifierManager im = IdentifierManager.getInstance();
|
1461
|
String localId = im.generateLocalId(guid.getValue(), 1);
|
1462
|
|
1463
|
try {
|
1464
|
logMetacat.debug("Case DATA: starting to write to disk.");
|
1465
|
if (DocumentImpl.getDataFileLockGrant(localId)) {
|
1466
|
|
1467
|
// Save the data file to disk using "localId" as the name
|
1468
|
try {
|
1469
|
String datafilepath = PropertyService.getProperty("application.datafilepath");
|
1470
|
|
1471
|
File dataDirectory = new File(datafilepath);
|
1472
|
dataDirectory.mkdirs();
|
1473
|
|
1474
|
File newFile = writeStreamToFile(dataDirectory, localId, object);
|
1475
|
|
1476
|
// TODO: Check that the file size matches SystemMetadata
|
1477
|
// long size = newFile.length();
|
1478
|
// if (size == 0) {
|
1479
|
// throw new IOException("Uploaded file is 0 bytes!");
|
1480
|
// }
|
1481
|
|
1482
|
// Register the file in the database (which generates an exception
|
1483
|
// if the localId is not acceptable or other untoward things happen
|
1484
|
try {
|
1485
|
logMetacat.debug("Registering document...");
|
1486
|
DocumentImpl.registerDocument(localId, "BIN", localId,
|
1487
|
username, groups);
|
1488
|
logMetacat.debug("Registration step completed.");
|
1489
|
} catch (SQLException e) {
|
1490
|
//newFile.delete();
|
1491
|
logMetacat.debug("SQLE: " + e.getMessage());
|
1492
|
e.printStackTrace(System.out);
|
1493
|
throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
|
1494
|
} catch (AccessionNumberException e) {
|
1495
|
//newFile.delete();
|
1496
|
logMetacat.debug("ANE: " + e.getMessage());
|
1497
|
e.printStackTrace(System.out);
|
1498
|
throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
|
1499
|
} catch (Exception e) {
|
1500
|
//newFile.delete();
|
1501
|
logMetacat.debug("Exception: " + e.getMessage());
|
1502
|
e.printStackTrace(System.out);
|
1503
|
throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
|
1504
|
}
|
1505
|
|
1506
|
logMetacat.debug("Logging the creation event.");
|
1507
|
EventLog.getInstance().log(metacatUrl,
|
1508
|
username, localId, "create");
|
1509
|
|
1510
|
// Schedule replication for this data file
|
1511
|
logMetacat.debug("Scheduling replication.");
|
1512
|
ForceReplicationHandler frh = new ForceReplicationHandler(
|
1513
|
localId, "create", false, null);
|
1514
|
|
1515
|
} catch (PropertyNotFoundException e) {
|
1516
|
throw new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
|
1517
|
}
|
1518
|
}
|
1519
|
return localId;
|
1520
|
} catch (Exception e) {
|
1521
|
// Could not get a lock on the document, so we can not update the file now
|
1522
|
throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
|
1523
|
}
|
1524
|
}
|
1525
|
|
1526
|
/**
|
1527
|
* write a file to a stream
|
1528
|
* @param dir
|
1529
|
* @param fileName
|
1530
|
* @param data
|
1531
|
* @return
|
1532
|
* @throws ServiceFailure
|
1533
|
*/
|
1534
|
private File writeStreamToFile(File dir, String fileName, InputStream data)
|
1535
|
throws ServiceFailure {
|
1536
|
|
1537
|
File newFile = new File(dir, fileName);
|
1538
|
logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
|
1539
|
|
1540
|
try {
|
1541
|
if (newFile.createNewFile()) {
|
1542
|
// write data stream to desired file
|
1543
|
OutputStream os = new FileOutputStream(newFile);
|
1544
|
long length = IOUtils.copyLarge(data, os);
|
1545
|
os.flush();
|
1546
|
os.close();
|
1547
|
} else {
|
1548
|
logMetacat.debug("File creation failed, or file already exists.");
|
1549
|
throw new ServiceFailure("1190", "File already exists: " + fileName);
|
1550
|
}
|
1551
|
} catch (FileNotFoundException e) {
|
1552
|
logMetacat.debug("FNF: " + e.getMessage());
|
1553
|
throw new ServiceFailure("1190", "File not found: " + fileName + " "
|
1554
|
+ e.getMessage());
|
1555
|
} catch (IOException e) {
|
1556
|
logMetacat.debug("IOE: " + e.getMessage());
|
1557
|
throw new ServiceFailure("1190", "File was not written: " + fileName
|
1558
|
+ " " + e.getMessage());
|
1559
|
}
|
1560
|
|
1561
|
return newFile;
|
1562
|
}
|
1563
|
|
1564
|
/**
|
1565
|
* insert a systemMetadata doc, return the localId of the sysmeta
|
1566
|
*/
|
1567
|
private String insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData)
|
1568
|
throws ServiceFailure
|
1569
|
{
|
1570
|
logMetacat.debug("Starting to insert SystemMetadata...");
|
1571
|
|
1572
|
// generate guid/localId pair for sysmeta
|
1573
|
Identifier sysMetaGuid = new Identifier();
|
1574
|
sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
|
1575
|
sysmeta.setDateSysMetadataModified(new Date());
|
1576
|
System.out.println("****inserting new system metadata with modified date " +
|
1577
|
sysmeta.getDateSysMetadataModified());
|
1578
|
|
1579
|
String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
|
1580
|
System.out.println("sysmeta: " + xml);
|
1581
|
String localId = insertDocument(xml, sysMetaGuid, sessionData, true);
|
1582
|
System.out.println("sysmeta inserted with localId " + localId);
|
1583
|
//insert the system metadata doc id into the systemmetadata table to
|
1584
|
//link it to the data or metadata document
|
1585
|
IdentifierManager.getInstance().createSystemMetadataMapping(
|
1586
|
sysmeta, sysMetaGuid.getValue());
|
1587
|
return localId;
|
1588
|
}
|
1589
|
|
1590
|
/**
|
1591
|
* update a systemMetadata doc
|
1592
|
*/
|
1593
|
private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
|
1594
|
throws ServiceFailure
|
1595
|
{
|
1596
|
try
|
1597
|
{
|
1598
|
String smId = IdentifierManager.getInstance().getSystemMetadataLocalId(sm.getIdentifier().getValue());
|
1599
|
System.out.println("setting date modified to " + new Date());
|
1600
|
sm.setDateSysMetadataModified(new Date());
|
1601
|
String xml = new String(serializeSystemMetadata(sm).toByteArray());
|
1602
|
String localId = updateDocument(xml, sm.getIdentifier(), null, sessionData, true);
|
1603
|
IdentifierManager.getInstance().updateSystemMetadataMapping(sm.getIdentifier().getValue(), localId);
|
1604
|
}
|
1605
|
catch(Exception e)
|
1606
|
{
|
1607
|
throw new ServiceFailure("1030", "Error updating system metadata: " + e.getMessage());
|
1608
|
}
|
1609
|
}
|
1610
|
|
1611
|
private String insertDocument(String xml, Identifier guid, SessionData sessionData)
|
1612
|
throws ServiceFailure
|
1613
|
{
|
1614
|
return insertDocument(xml, guid, sessionData, false);
|
1615
|
}
|
1616
|
|
1617
|
/**
|
1618
|
* insert a document
|
1619
|
* NOTE: this method shouldn't be used from the update or create() methods.
|
1620
|
* we shouldn't be putting the science metadata or data objects into memory.
|
1621
|
*/
|
1622
|
private String insertDocument(String xml, Identifier guid, SessionData sessionData,
|
1623
|
boolean isSystemMetadata)
|
1624
|
throws ServiceFailure
|
1625
|
{
|
1626
|
return insertOrUpdateDocument(xml, guid, sessionData, "insert", isSystemMetadata);
|
1627
|
}
|
1628
|
|
1629
|
/**
|
1630
|
* insert a document from a stream
|
1631
|
*/
|
1632
|
private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
|
1633
|
throws IOException, ServiceFailure
|
1634
|
{
|
1635
|
//HACK: change this eventually. we should not be converting the stream to a string
|
1636
|
String xml = IOUtils.toString(is);
|
1637
|
return insertDocument(xml, guid, sessionData);
|
1638
|
}
|
1639
|
|
1640
|
/**
|
1641
|
* update a document
|
1642
|
* NOTE: this method shouldn't be used from the update or create() methods.
|
1643
|
* we shouldn't be putting the science metadata or data objects into memory.
|
1644
|
*/
|
1645
|
private String updateDocument(String xml, Identifier obsoleteGuid,
|
1646
|
Identifier guid, SessionData sessionData, boolean isSystemMetadata)
|
1647
|
throws ServiceFailure
|
1648
|
{
|
1649
|
return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update", isSystemMetadata);
|
1650
|
}
|
1651
|
|
1652
|
/**
|
1653
|
* update a document from a stream
|
1654
|
*/
|
1655
|
private String updateDocument(InputStream is, Identifier obsoleteGuid,
|
1656
|
Identifier guid, SessionData sessionData, boolean isSystemMetadata)
|
1657
|
throws IOException, ServiceFailure
|
1658
|
{
|
1659
|
//HACK: change this eventually. we should not be converting the stream to a string
|
1660
|
String xml = IOUtils.toString(is);
|
1661
|
String localId = updateDocument(xml, obsoleteGuid, guid, sessionData, isSystemMetadata);
|
1662
|
IdentifierManager im = IdentifierManager.getInstance();
|
1663
|
if(guid != null)
|
1664
|
{
|
1665
|
im.createMapping(guid.getValue(), localId);
|
1666
|
}
|
1667
|
return localId;
|
1668
|
}
|
1669
|
|
1670
|
/**
|
1671
|
* insert a document, return the id of the document that was inserted
|
1672
|
*/
|
1673
|
protected String insertOrUpdateDocument(String xml, Identifier guid,
|
1674
|
SessionData sessionData, String insertOrUpdate, boolean isSystemMetadata)
|
1675
|
throws ServiceFailure {
|
1676
|
logMetacat.debug("Starting to insert xml document...");
|
1677
|
IdentifierManager im = IdentifierManager.getInstance();
|
1678
|
|
1679
|
// generate guid/localId pair for sysmeta
|
1680
|
String localId = null;
|
1681
|
if(insertOrUpdate.equals("insert"))
|
1682
|
{
|
1683
|
localId = im.generateLocalId(guid.getValue(), 1, isSystemMetadata);
|
1684
|
}
|
1685
|
else
|
1686
|
{
|
1687
|
//localid should already exist in the identifier table, so just find it
|
1688
|
try
|
1689
|
{
|
1690
|
System.out.println("updating guid " + guid.getValue());
|
1691
|
if(!isSystemMetadata)
|
1692
|
{
|
1693
|
System.out.println("looking in identifier table for guid " + guid.getValue());
|
1694
|
localId = im.getLocalId(guid.getValue());
|
1695
|
}
|
1696
|
else
|
1697
|
{
|
1698
|
System.out.println("looking in systemmetadata table for guid " + guid.getValue());
|
1699
|
localId = im.getSystemMetadataLocalId(guid.getValue());
|
1700
|
}
|
1701
|
System.out.println("localId: " + localId);
|
1702
|
//increment the revision
|
1703
|
String docid = localId.substring(0, localId.lastIndexOf("."));
|
1704
|
String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
|
1705
|
int rev = new Integer(revS).intValue();
|
1706
|
rev++;
|
1707
|
docid = docid + "." + rev;
|
1708
|
localId = docid;
|
1709
|
System.out.println("incremented localId: " + localId);
|
1710
|
}
|
1711
|
catch(McdbDocNotFoundException e)
|
1712
|
{
|
1713
|
throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
|
1714
|
"guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
|
1715
|
}
|
1716
|
}
|
1717
|
logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
|
1718
|
localId);
|
1719
|
|
1720
|
String[] action = new String[1];
|
1721
|
action[0] = insertOrUpdate;
|
1722
|
params.put("action", action);
|
1723
|
String[] docid = new String[1];
|
1724
|
docid[0] = localId;
|
1725
|
params.put("docid", docid);
|
1726
|
String[] doctext = new String[1];
|
1727
|
doctext[0] = xml;
|
1728
|
logMetacat.debug(doctext[0]);
|
1729
|
params.put("doctext", doctext);
|
1730
|
|
1731
|
// TODO: refactor handleInsertOrUpdateAction() to not output XML directly
|
1732
|
// onto output stream, or alternatively, capture that and parse it to
|
1733
|
// generate the right exceptions
|
1734
|
//ByteArrayOutputStream output = new ByteArrayOutputStream();
|
1735
|
//PrintWriter pw = new PrintWriter(output);
|
1736
|
String username = "public";
|
1737
|
String[] groupnames = null;
|
1738
|
if(sessionData != null)
|
1739
|
{
|
1740
|
username = sessionData.getUserName();
|
1741
|
groupnames = sessionData.getGroupNames();
|
1742
|
}
|
1743
|
String result = handler.handleInsertOrUpdateAction(metacatUrl, null,
|
1744
|
null, params, username, groupnames);
|
1745
|
if(result.indexOf("<error>") != -1)
|
1746
|
{
|
1747
|
throw new ServiceFailure("1000", "Error inserting or updating document: " + result);
|
1748
|
}
|
1749
|
//String outputS = new String(output.toByteArray());
|
1750
|
logMetacat.debug("CrudService.insertDocument - Metacat returned: " + result);
|
1751
|
logMetacat.debug("Finsished inserting xml document with id " + localId);
|
1752
|
return localId;
|
1753
|
}
|
1754
|
|
1755
|
/**
|
1756
|
* serialize a dataone type
|
1757
|
*/
|
1758
|
private void serializeServiceType(Class type, Object object, OutputStream out)
|
1759
|
throws JiBXException
|
1760
|
{
|
1761
|
IBindingFactory bfact = BindingDirectory.getFactory(type);
|
1762
|
IMarshallingContext mctx = bfact.createMarshallingContext();
|
1763
|
mctx.marshalDocument(object, "UTF-8", null, out);
|
1764
|
}
|
1765
|
|
1766
|
/**
|
1767
|
* serialize a system metadata doc
|
1768
|
* @param sysmeta
|
1769
|
* @return
|
1770
|
* @throws ServiceFailure
|
1771
|
*/
|
1772
|
public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta)
|
1773
|
throws ServiceFailure {
|
1774
|
IBindingFactory bfact;
|
1775
|
ByteArrayOutputStream sysmetaOut = null;
|
1776
|
try {
|
1777
|
bfact = BindingDirectory.getFactory(SystemMetadata.class);
|
1778
|
IMarshallingContext mctx = bfact.createMarshallingContext();
|
1779
|
sysmetaOut = new ByteArrayOutputStream();
|
1780
|
mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
|
1781
|
} catch (JiBXException e) {
|
1782
|
e.printStackTrace();
|
1783
|
throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
|
1784
|
}
|
1785
|
|
1786
|
return sysmetaOut;
|
1787
|
}
|
1788
|
|
1789
|
/**
|
1790
|
* deserialize a system metadata doc
|
1791
|
* @param xml
|
1792
|
* @return
|
1793
|
* @throws ServiceFailure
|
1794
|
*/
|
1795
|
public static SystemMetadata deserializeSystemMetadata(InputStream xml)
|
1796
|
throws ServiceFailure {
|
1797
|
try {
|
1798
|
IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
|
1799
|
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
|
1800
|
SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
|
1801
|
return sysmeta;
|
1802
|
} catch (JiBXException e) {
|
1803
|
e.printStackTrace();
|
1804
|
throw new ServiceFailure("1190", "Failed to deserialize and insert SystemMetadata: " + e.getMessage());
|
1805
|
}
|
1806
|
}
|
1807
|
|
1808
|
/**
|
1809
|
* read a document from metacat and return the InputStream
|
1810
|
*
|
1811
|
* @param localId
|
1812
|
* @param username
|
1813
|
* @param groups
|
1814
|
* @return
|
1815
|
* @throws InsufficientKarmaException
|
1816
|
* @throws ParseLSIDException
|
1817
|
* @throws PropertyNotFoundException
|
1818
|
* @throws McdbException
|
1819
|
* @throws SQLException
|
1820
|
* @throws ClassNotFoundException
|
1821
|
* @throws IOException
|
1822
|
*/
|
1823
|
private InputStream readFromMetacat(String localId, String username, String[] groups)
|
1824
|
throws InsufficientKarmaException, ParseLSIDException,
|
1825
|
PropertyNotFoundException, McdbException, SQLException,
|
1826
|
ClassNotFoundException, IOException
|
1827
|
{
|
1828
|
File tmpDir;
|
1829
|
try
|
1830
|
{
|
1831
|
tmpDir = new File(PropertyService.getProperty("application.tempDir"));
|
1832
|
}
|
1833
|
catch(PropertyNotFoundException pnfe)
|
1834
|
{
|
1835
|
logMetacat.error("ResourceHandler.writeMMPPartstoFiles: " +
|
1836
|
"application.tmpDir not found. Using /tmp instead.");
|
1837
|
tmpDir = new File("/tmp");
|
1838
|
}
|
1839
|
Date d = new Date();
|
1840
|
final File outputFile = new File(tmpDir, "metacat.output." + d.getTime());
|
1841
|
FileOutputStream dataSink = new FileOutputStream(outputFile);
|
1842
|
|
1843
|
handler.readFromMetacat(metacatUrl, null,
|
1844
|
dataSink, localId, "xml",
|
1845
|
username,
|
1846
|
groups, true, params);
|
1847
|
|
1848
|
//set a timer to clean up the temp files
|
1849
|
Timer t = new Timer();
|
1850
|
TimerTask tt = new TimerTask() {
|
1851
|
@Override
|
1852
|
public void run()
|
1853
|
{
|
1854
|
outputFile.delete();
|
1855
|
}
|
1856
|
};
|
1857
|
t.schedule(tt, 20000); //schedule after 20 secs
|
1858
|
|
1859
|
InputStream objectStream = new FileInputStream(outputFile);
|
1860
|
return objectStream;
|
1861
|
}
|
1862
|
|
1863
|
/**
|
1864
|
* return an MD5 checksum for the stream
|
1865
|
* @param is
|
1866
|
* @return
|
1867
|
* @throws IOException
|
1868
|
* @throws NoSuchAlgorithmException
|
1869
|
*/
|
1870
|
public static String checksum(InputStream is) throws NoSuchAlgorithmException, IOException
|
1871
|
{
|
1872
|
return checksum(is, "MD5");
|
1873
|
}
|
1874
|
|
1875
|
/**
|
1876
|
* produce a checksum for item using the given algorithm
|
1877
|
* @throws IOException
|
1878
|
* @throws NoSuchAlgorithmException
|
1879
|
*/
|
1880
|
public static String checksum(InputStream is, String algorithm) throws NoSuchAlgorithmException, IOException
|
1881
|
{
|
1882
|
return ServiceTypeUtil.checksum(is, ChecksumAlgorithm.convert(algorithm)).getValue();
|
1883
|
}
|
1884
|
|
1885
|
/**
|
1886
|
* parse the metacat date which looks like 2010-06-08 (YYYY-MM-DD) into
|
1887
|
* a proper date object
|
1888
|
* @param date
|
1889
|
* @return
|
1890
|
*/
|
1891
|
private Date parseMetacatDate(String date)
|
1892
|
{
|
1893
|
String year = date.substring(0, 4);
|
1894
|
String month = date.substring(5, 7);
|
1895
|
String day = date.substring(8, 10);
|
1896
|
Calendar c = Calendar.getInstance(TimeZone.getDefault());
|
1897
|
c.set(new Integer(year).intValue(),
|
1898
|
new Integer(month).intValue(),
|
1899
|
new Integer(day).intValue());
|
1900
|
System.out.println("time in parseMetacatDate: " + c.getTime());
|
1901
|
return c.getTime();
|
1902
|
}
|
1903
|
|
1904
|
/**
|
1905
|
* find the size (in bytes) of a stream
|
1906
|
* @param is
|
1907
|
* @return
|
1908
|
* @throws IOException
|
1909
|
*/
|
1910
|
private long sizeOfStream(InputStream is)
|
1911
|
throws IOException
|
1912
|
{
|
1913
|
long size = 0;
|
1914
|
byte[] b = new byte[1024];
|
1915
|
int numread = is.read(b, 0, 1024);
|
1916
|
while(numread != -1)
|
1917
|
{
|
1918
|
size += numread;
|
1919
|
numread = is.read(b, 0, 1024);
|
1920
|
}
|
1921
|
return size;
|
1922
|
}
|
1923
|
|
1924
|
/**
|
1925
|
* create system metadata with a specified id, doc and format
|
1926
|
* @throws McdbDocNotFoundException
|
1927
|
* @throws SQLException
|
1928
|
* @throws AccessionNumberException
|
1929
|
* @throws NumberFormatException
|
1930
|
* @throws IOException
|
1931
|
* @throws NoSuchAlgorithmException
|
1932
|
* @throws PropertyNotFoundException
|
1933
|
*/
|
1934
|
private SystemMetadata createSystemMetadata(String localId, AuthToken token)
|
1935
|
throws McdbDocNotFoundException, NumberFormatException, AccessionNumberException,
|
1936
|
SQLException, NoSuchAlgorithmException, IOException, PropertyNotFoundException, BaseException {
|
1937
|
|
1938
|
IdentifierManager im = IdentifierManager.getInstance();
|
1939
|
Hashtable<String, Object> docInfo = im.getDocumentInfo(localId);
|
1940
|
|
1941
|
//get the document text
|
1942
|
int rev = im.getLatestRevForLocalId(localId);
|
1943
|
Identifier identifier = new Identifier();
|
1944
|
try {
|
1945
|
identifier.setValue(im.getGUID(localId, rev));
|
1946
|
} catch (McdbDocNotFoundException mcdbe) {
|
1947
|
//we're creating a new SM doc for a doc that is not in the identifier table
|
1948
|
//so we need to add it to
|
1949
|
System.out.println("No guid in the identifier table. adding it for " + localId);
|
1950
|
im.createMapping(localId, localId);
|
1951
|
System.out.println("mapping created for " + localId);
|
1952
|
AccessionNumber accNum = new AccessionNumber(localId, "NONE");
|
1953
|
identifier.setValue(im.getGUID(accNum.getDocid(), rev));
|
1954
|
}
|
1955
|
|
1956
|
System.out.println("creating system metadata for guid " + identifier.getValue());
|
1957
|
InputStream is = this.get(token, identifier);
|
1958
|
SystemMetadata sm = new SystemMetadata();
|
1959
|
|
1960
|
//set the id
|
1961
|
sm.setIdentifier(identifier);
|
1962
|
|
1963
|
//set the object format
|
1964
|
String doctype = (String) docInfo.get("doctype");
|
1965
|
ObjectFormat format = ObjectFormat.convert((String) docInfo.get("doctype"));
|
1966
|
if (format == null) {
|
1967
|
if (doctype.trim().equals("BIN")) {
|
1968
|
format = ObjectFormat.OCTET_STREAM;
|
1969
|
} else {
|
1970
|
format = ObjectFormat.convert("text/plain");
|
1971
|
}
|
1972
|
}
|
1973
|
sm.setObjectFormat(format);
|
1974
|
|
1975
|
//create the checksum
|
1976
|
String checksumS = checksum(is);
|
1977
|
ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
|
1978
|
Checksum checksum = new Checksum();
|
1979
|
checksum.setValue(checksumS);
|
1980
|
checksum.setAlgorithm(ca);
|
1981
|
sm.setChecksum(checksum);
|
1982
|
|
1983
|
//set the size
|
1984
|
is = this.get(token, identifier);
|
1985
|
sm.setSize(sizeOfStream(is));
|
1986
|
|
1987
|
//submitter
|
1988
|
Principal p = new Principal();
|
1989
|
p.setValue((String) docInfo.get("user_owner"));
|
1990
|
sm.setSubmitter(p);
|
1991
|
sm.setRightsHolder(p);
|
1992
|
try {
|
1993
|
Date dateCreated = parseMetacatDate((String) docInfo.get("date_created"));
|
1994
|
sm.setDateUploaded(dateCreated);
|
1995
|
Date dateUpdated = parseMetacatDate((String) docInfo.get("date_updated"));
|
1996
|
sm.setDateSysMetadataModified(dateUpdated);
|
1997
|
} catch (Exception e) {
|
1998
|
System.out.println("POSSIBLE ERROR: couldn't parse a date: " + e.getMessage());
|
1999
|
Date dateCreated = new Date();
|
2000
|
sm.setDateUploaded(dateCreated);
|
2001
|
Date dateUpdated = new Date();
|
2002
|
sm.setDateSysMetadataModified(dateUpdated);
|
2003
|
}
|
2004
|
NodeReference nr = new NodeReference();
|
2005
|
nr.setValue(PropertyService.getProperty("dataone.memberNodeId"));
|
2006
|
sm.setOriginMemberNode(nr);
|
2007
|
sm.setAuthoritativeMemberNode(nr);
|
2008
|
|
2009
|
// TODO: Need to set describes/describedBy
|
2010
|
|
2011
|
return sm;
|
2012
|
}
|
2013
|
|
2014
|
/**
|
2015
|
* create the listObjects pathQuery document
|
2016
|
*/
|
2017
|
private String createListObjectsPathQueryDocument()
|
2018
|
throws PropertyNotFoundException
|
2019
|
{
|
2020
|
String s = "<pathquery>";
|
2021
|
s += "<returndoctype>" + PropertyService.getProperty("crudService.listObjects.ReturnDoctype") + "</returndoctype>";
|
2022
|
s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.1") + "</returnfield>";
|
2023
|
s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.2") + "</returnfield>";
|
2024
|
s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.3") + "</returnfield>";
|
2025
|
s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.4") + "</returnfield>";
|
2026
|
s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.5") + "</returnfield>";
|
2027
|
s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.6") + "</returnfield>";
|
2028
|
s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.7") + "</returnfield>";
|
2029
|
s += "<querygroup operator=\"UNION\"><queryterm casesensitive=\"false\" searchmode=\"contains\">";
|
2030
|
s += "<value>%</value>";
|
2031
|
s += "<pathexpr>" + PropertyService.getProperty("crudService.listObjects.ReturnField.3") + "</pathexpr>";
|
2032
|
s += "</queryterm></querygroup></pathquery>";
|
2033
|
|
2034
|
return s;
|
2035
|
}
|
2036
|
}
|
2037
|
|