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.Date;
|
35
|
import java.util.Enumeration;
|
36
|
import java.util.Hashtable;
|
37
|
import java.util.Timer;
|
38
|
import java.util.List;
|
39
|
|
40
|
import javax.servlet.ServletContext;
|
41
|
import javax.servlet.http.HttpServletRequest;
|
42
|
import javax.servlet.http.HttpServletResponse;
|
43
|
|
44
|
import org.apache.commons.io.IOUtils;
|
45
|
import org.apache.log4j.Logger;
|
46
|
import org.dataone.service.exceptions.IdentifierNotUnique;
|
47
|
import org.dataone.service.exceptions.InsufficientResources;
|
48
|
import org.dataone.service.exceptions.InvalidRequest;
|
49
|
import org.dataone.service.exceptions.InvalidSystemMetadata;
|
50
|
import org.dataone.service.exceptions.InvalidToken;
|
51
|
import org.dataone.service.exceptions.NotAuthorized;
|
52
|
import org.dataone.service.exceptions.NotFound;
|
53
|
import org.dataone.service.exceptions.NotImplemented;
|
54
|
import org.dataone.service.exceptions.ServiceFailure;
|
55
|
import org.dataone.service.exceptions.UnsupportedType;
|
56
|
import org.dataone.service.mn.MemberNodeCrud;
|
57
|
import org.dataone.service.types.AuthToken;
|
58
|
import org.dataone.service.types.Checksum;
|
59
|
import org.dataone.service.types.DescribeResponse;
|
60
|
import org.dataone.service.types.Identifier;
|
61
|
import org.dataone.service.types.LogRecordSet;
|
62
|
import org.dataone.service.types.SystemMetadata;
|
63
|
import org.jibx.runtime.BindingDirectory;
|
64
|
import org.jibx.runtime.IBindingFactory;
|
65
|
import org.jibx.runtime.IMarshallingContext;
|
66
|
import org.jibx.runtime.IUnmarshallingContext;
|
67
|
import org.jibx.runtime.JiBXException;
|
68
|
|
69
|
import com.gc.iotools.stream.is.InputStreamFromOutputStream;
|
70
|
|
71
|
import edu.ucsb.nceas.metacat.AccessionNumberException;
|
72
|
import edu.ucsb.nceas.metacat.DocumentImpl;
|
73
|
import edu.ucsb.nceas.metacat.EventLog;
|
74
|
import edu.ucsb.nceas.metacat.IdentifierManager;
|
75
|
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
|
76
|
import edu.ucsb.nceas.metacat.McdbException;
|
77
|
import edu.ucsb.nceas.metacat.MetacatHandler;
|
78
|
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
|
79
|
import edu.ucsb.nceas.metacat.properties.PropertyService;
|
80
|
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
|
81
|
import edu.ucsb.nceas.metacat.service.SessionService;
|
82
|
import edu.ucsb.nceas.metacat.util.DocumentUtil;
|
83
|
import edu.ucsb.nceas.metacat.util.SessionData;
|
84
|
import edu.ucsb.nceas.utilities.ParseLSIDException;
|
85
|
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
|
86
|
|
87
|
/**
|
88
|
*
|
89
|
* Implements DataONE MemberNode CRUD API for Metacat.
|
90
|
*
|
91
|
* @author Matthew Jones
|
92
|
*/
|
93
|
public class CrudService implements MemberNodeCrud {
|
94
|
|
95
|
/*private ServletContext servletContext;
|
96
|
private HttpServletRequest request;
|
97
|
private HttpServletResponse response;*/
|
98
|
|
99
|
private static CrudService crudService = null;
|
100
|
|
101
|
private MetacatHandler handler;
|
102
|
private Hashtable<String, String[]> params;
|
103
|
Logger logMetacat = null;
|
104
|
|
105
|
private String metacatUrl;
|
106
|
|
107
|
/**
|
108
|
* singleton accessor
|
109
|
*/
|
110
|
public static CrudService getInstance()
|
111
|
{
|
112
|
if(crudService == null)
|
113
|
{
|
114
|
crudService = new CrudService();
|
115
|
}
|
116
|
|
117
|
return crudService;
|
118
|
}
|
119
|
|
120
|
/**
|
121
|
* Initializes new instance by setting servlet context,request and response.
|
122
|
* TODO: remove dependency on Servlet infrastructure
|
123
|
* TODO: Make this a real service, and make it a Singleton
|
124
|
*/
|
125
|
public CrudService() {
|
126
|
//change crud service into a singleton. dont pass servlet data structures here
|
127
|
logMetacat = Logger.getLogger(CrudService.class);
|
128
|
try
|
129
|
{
|
130
|
String server = PropertyService.getProperty("server.name");
|
131
|
String port = PropertyService.getProperty("server.httpPort");
|
132
|
String context = PropertyService.getProperty("application.context");
|
133
|
metacatUrl = "http://" + server + ":" + port + "/" + context;
|
134
|
logMetacat.debug("Initializing CrudService with url " + metacatUrl);
|
135
|
}
|
136
|
catch(Exception e)
|
137
|
{
|
138
|
logMetacat.error("Could not find servlet url in CrudService: " + e.getMessage());
|
139
|
e.printStackTrace();
|
140
|
throw new RuntimeException("Error getting servlet url in CrudService: " + e.getMessage());
|
141
|
}
|
142
|
|
143
|
/*this.servletContext = servletContext;
|
144
|
this.request = request;
|
145
|
this.response = response;*/
|
146
|
|
147
|
params = new Hashtable<String, String[]>();
|
148
|
|
149
|
handler = new MetacatHandler(new Timer());
|
150
|
|
151
|
}
|
152
|
|
153
|
/**
|
154
|
* return the context url CrudService is using.
|
155
|
*/
|
156
|
public String getContextUrl()
|
157
|
{
|
158
|
return metacatUrl;
|
159
|
}
|
160
|
|
161
|
/**
|
162
|
* set the params for this service from an HttpServletRequest param list
|
163
|
*/
|
164
|
public void setParamsFromRequest(HttpServletRequest request)
|
165
|
{
|
166
|
Enumeration paramlist = request.getParameterNames();
|
167
|
while (paramlist.hasMoreElements()) {
|
168
|
String name = (String) paramlist.nextElement();
|
169
|
String[] value = (String[])request.getParameterValues(name);
|
170
|
params.put(name, value);
|
171
|
}
|
172
|
}
|
173
|
|
174
|
/**
|
175
|
* set the parameter values needed for this request
|
176
|
*/
|
177
|
public void setParameter(String name, String[] value)
|
178
|
{
|
179
|
params.put(name, value);
|
180
|
}
|
181
|
|
182
|
public Identifier create(AuthToken token, Identifier guid,
|
183
|
InputStream object, SystemMetadata sysmeta) throws InvalidToken,
|
184
|
ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType,
|
185
|
InsufficientResources, InvalidSystemMetadata, NotImplemented {
|
186
|
|
187
|
logMetacat.debug("Starting CrudService.create()...");
|
188
|
|
189
|
// authenticate & get user info
|
190
|
SessionData sessionData = getSessionData(token);
|
191
|
String username = sessionData.getUserName();
|
192
|
String[] groups = sessionData.getGroupNames();
|
193
|
|
194
|
// verify that guid == SystemMetadata.getIdentifier()
|
195
|
logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
|
196
|
if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
|
197
|
throw new InvalidSystemMetadata(1180,
|
198
|
"GUID in method call does not match GUID in system metadata.");
|
199
|
}
|
200
|
|
201
|
logMetacat.debug("Checking if identifier exists...");
|
202
|
// Check that the identifier does not already exist
|
203
|
IdentifierManager im = IdentifierManager.getInstance();
|
204
|
if (im.identifierExists(guid.getValue())) {
|
205
|
throw new IdentifierNotUnique(1120,
|
206
|
"GUID is already in use by an existing object.");
|
207
|
}
|
208
|
|
209
|
// Check if we are handling metadata or data
|
210
|
boolean isScienceMetadata = isScienceMetadata(sysmeta);
|
211
|
|
212
|
if (isScienceMetadata) {
|
213
|
// CASE METADATA:
|
214
|
try {
|
215
|
this.insertDocument(object, guid, sessionData);
|
216
|
} catch (IOException e) {
|
217
|
String msg = "Could not create string from XML stream: " +
|
218
|
" " + e.getMessage();
|
219
|
logMetacat.debug(msg);
|
220
|
throw new ServiceFailure(1190, msg);
|
221
|
}
|
222
|
|
223
|
} else {
|
224
|
// DEFAULT CASE: DATA (needs to be checked and completed)
|
225
|
insertDataObject(object, guid, sessionData);
|
226
|
|
227
|
}
|
228
|
|
229
|
// For Metadata and Data, insert the system metadata into the object store too
|
230
|
insertSystemMetadata(sysmeta, sessionData);
|
231
|
|
232
|
logMetacat.debug("Returning from CrudService.create()");
|
233
|
return guid;
|
234
|
}
|
235
|
|
236
|
/**
|
237
|
* update an existing object with a new object. Change the system metadata
|
238
|
* to reflect the changes and update it as well.
|
239
|
*/
|
240
|
public Identifier update(AuthToken token, Identifier guid,
|
241
|
InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta)
|
242
|
throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique,
|
243
|
UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata,
|
244
|
NotImplemented {
|
245
|
try
|
246
|
{
|
247
|
SessionData sessionData = getSessionData(token);
|
248
|
|
249
|
//find the old systemmetadata (sm.old) document id (the one linked to obsoletedGuid)
|
250
|
SystemMetadata sm = getSystemMetadata(token, obsoletedGuid);
|
251
|
//change sm.old's obsoletedBy field
|
252
|
List l = sm.getObsoletedByList();
|
253
|
l.add(guid);
|
254
|
sm.setObsoletedByList(l);
|
255
|
//update sm.old
|
256
|
updateSystemMetadata(sm, sessionData);
|
257
|
|
258
|
//change the obsoletes field of the new systemMetadata (sm.new) to point to the id of the old one
|
259
|
sysmeta.addObsolete(obsoletedGuid);
|
260
|
//insert sm.new
|
261
|
insertSystemMetadata(sysmeta, sessionData);
|
262
|
|
263
|
boolean isScienceMetadata = isScienceMetadata(sysmeta);
|
264
|
if(isScienceMetadata)
|
265
|
{
|
266
|
//update the doc
|
267
|
updateDocument(object, obsoletedGuid, guid, sessionData);
|
268
|
}
|
269
|
else
|
270
|
{
|
271
|
//update a data file, not xml
|
272
|
insertDataObject(object, guid, sessionData);
|
273
|
}
|
274
|
return guid;
|
275
|
}
|
276
|
catch(Exception e)
|
277
|
{
|
278
|
throw new ServiceFailure(1030, "Error updating document in CrudService: " + e.getMessage());
|
279
|
}
|
280
|
}
|
281
|
|
282
|
public Identifier delete(AuthToken token, Identifier guid)
|
283
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
284
|
NotImplemented {
|
285
|
throw new NotImplemented(1000, "This method not yet implemented.");
|
286
|
}
|
287
|
|
288
|
public DescribeResponse describe(AuthToken token, Identifier guid)
|
289
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
290
|
NotImplemented {
|
291
|
throw new NotImplemented(1000, "This method not yet implemented.");
|
292
|
}
|
293
|
|
294
|
public InputStream get(AuthToken token, Identifier guid)
|
295
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
296
|
NotImplemented {
|
297
|
|
298
|
// Retrieve the session information from the AuthToken
|
299
|
// If the session is expired, then the user is 'public'
|
300
|
final SessionData sessionData = getSessionData(token);
|
301
|
|
302
|
// Look up the localId for this global identifier
|
303
|
IdentifierManager im = IdentifierManager.getInstance();
|
304
|
try {
|
305
|
final String localId = im.getLocalId(guid.getValue());
|
306
|
|
307
|
final InputStreamFromOutputStream<String> objectStream =
|
308
|
new InputStreamFromOutputStream<String>() {
|
309
|
|
310
|
@Override
|
311
|
public String produce(final OutputStream dataSink) throws Exception {
|
312
|
|
313
|
try {
|
314
|
handler.readFromMetacat(metacatUrl, null,
|
315
|
dataSink, localId, "xml",
|
316
|
sessionData.getUserName(),
|
317
|
sessionData.getGroupNames(), true, params);
|
318
|
} catch (PropertyNotFoundException e) {
|
319
|
throw new ServiceFailure(1030, e.getMessage());
|
320
|
} catch (ClassNotFoundException e) {
|
321
|
throw new ServiceFailure(1030, e.getMessage());
|
322
|
} catch (IOException e) {
|
323
|
throw new ServiceFailure(1030, e.getMessage());
|
324
|
} catch (SQLException e) {
|
325
|
throw new ServiceFailure(1030, e.getMessage());
|
326
|
} catch (McdbException e) {
|
327
|
throw new ServiceFailure(1030, e.getMessage());
|
328
|
} catch (ParseLSIDException e) {
|
329
|
throw new NotFound(1020, e.getMessage());
|
330
|
} catch (InsufficientKarmaException e) {
|
331
|
throw new NotAuthorized(1000, "Not authorized for get().");
|
332
|
}
|
333
|
|
334
|
return "Completed";
|
335
|
}
|
336
|
};
|
337
|
return objectStream;
|
338
|
|
339
|
} catch (McdbDocNotFoundException e) {
|
340
|
throw new NotFound(1020, e.getMessage());
|
341
|
}
|
342
|
}
|
343
|
|
344
|
public Checksum getChecksum(AuthToken token, Identifier guid)
|
345
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
346
|
InvalidRequest, NotImplemented {
|
347
|
throw new NotImplemented(1000, "This method not yet implemented.");
|
348
|
}
|
349
|
|
350
|
public Checksum getChecksum(AuthToken token, Identifier guid,
|
351
|
String checksumAlgorithm) throws InvalidToken, ServiceFailure,
|
352
|
NotAuthorized, NotFound, InvalidRequest, NotImplemented {
|
353
|
throw new NotImplemented(1000, "This method not yet implemented.");
|
354
|
}
|
355
|
|
356
|
public LogRecordSet getLogRecords(AuthToken token, Date fromDate, Date toDate)
|
357
|
throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest,
|
358
|
NotImplemented {
|
359
|
throw new NotImplemented(1000, "This method not yet implemented.");
|
360
|
}
|
361
|
|
362
|
public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
|
363
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
364
|
InvalidRequest, NotImplemented {
|
365
|
|
366
|
logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
|
367
|
|
368
|
// Retrieve the session information from the AuthToken
|
369
|
// If the session is expired, then the user is 'public'
|
370
|
final SessionData sessionData = getSessionData(token);
|
371
|
|
372
|
// TODO: Check access control rules
|
373
|
|
374
|
try {
|
375
|
IdentifierManager im = IdentifierManager.getInstance();
|
376
|
final String localId = im.getSystemMetadataId(guid.getValue());
|
377
|
|
378
|
// Read system metadata from metacat's db
|
379
|
final InputStreamFromOutputStream<String> objectStream =
|
380
|
new InputStreamFromOutputStream<String>() {
|
381
|
|
382
|
@Override
|
383
|
public String produce(final OutputStream dataSink) throws Exception {
|
384
|
try {
|
385
|
handler.readFromMetacat(metacatUrl, null,
|
386
|
dataSink, localId, "xml",
|
387
|
sessionData.getUserName(),
|
388
|
sessionData.getGroupNames(), true, params);
|
389
|
} catch (PropertyNotFoundException e) {
|
390
|
throw new ServiceFailure(1030, e.getMessage());
|
391
|
} catch (ClassNotFoundException e) {
|
392
|
throw new ServiceFailure(1030, e.getMessage());
|
393
|
} catch (IOException e) {
|
394
|
throw new ServiceFailure(1030, e.getMessage());
|
395
|
} catch (SQLException e) {
|
396
|
throw new ServiceFailure(1030, e.getMessage());
|
397
|
} catch (McdbException e) {
|
398
|
throw new ServiceFailure(1030, e.getMessage());
|
399
|
} catch (ParseLSIDException e) {
|
400
|
throw new NotFound(1020, e.getMessage());
|
401
|
} catch (InsufficientKarmaException e) {
|
402
|
throw new NotAuthorized(1000, "Not authorized for get().");
|
403
|
}
|
404
|
|
405
|
return "Completed";
|
406
|
}
|
407
|
};
|
408
|
|
409
|
// Deserialize the xml to create a SystemMetadata object
|
410
|
SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
|
411
|
return sysmeta;
|
412
|
|
413
|
} catch (McdbDocNotFoundException e) {
|
414
|
//e.printStackTrace();
|
415
|
throw new NotFound(1000, e.getMessage());
|
416
|
}
|
417
|
}
|
418
|
|
419
|
/*
|
420
|
* Look up the information on the session using the token provided in
|
421
|
* the AuthToken. The Session should have all relevant user information.
|
422
|
* If the session has expired or is invalid, the 'public' session will
|
423
|
* be returned, giving the user anonymous access.
|
424
|
*/
|
425
|
private static SessionData getSessionData(AuthToken token) {
|
426
|
SessionData sessionData = null;
|
427
|
String sessionId = "PUBLIC";
|
428
|
if (token != null) {
|
429
|
sessionId = token.getToken();
|
430
|
}
|
431
|
|
432
|
// if the session id is registered in SessionService, get the
|
433
|
// SessionData for it. Otherwise, use the public session.
|
434
|
if (SessionService.isSessionRegistered(sessionId)) {
|
435
|
sessionData = SessionService.getRegisteredSession(sessionId);
|
436
|
} else {
|
437
|
sessionData = SessionService.getPublicSession();
|
438
|
}
|
439
|
|
440
|
return sessionData;
|
441
|
}
|
442
|
|
443
|
/**
|
444
|
* Determine if a given object should be treated as an XML science metadata
|
445
|
* object.
|
446
|
*
|
447
|
* TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
|
448
|
*
|
449
|
* @param sysmeta the SystemMetadata describig the object
|
450
|
* @return true if the object should be treated as science metadata
|
451
|
*/
|
452
|
private boolean isScienceMetadata(SystemMetadata sysmeta) {
|
453
|
boolean scimeta = false;
|
454
|
switch (sysmeta.getObjectFormat()) {
|
455
|
case EML_2_1_0: scimeta = true; break;
|
456
|
case EML_2_0_1: scimeta = true; break;
|
457
|
case EML_2_0_0: scimeta = true; break;
|
458
|
case FGDC_STD_001_1_1999: scimeta = true; break;
|
459
|
case FGDC_STD_001_1998: scimeta = true; break;
|
460
|
case NCML_2_2: scimeta = true; break;
|
461
|
}
|
462
|
|
463
|
return scimeta;
|
464
|
}
|
465
|
|
466
|
private void insertDataObject(InputStream object, Identifier guid,
|
467
|
SessionData sessionData) throws ServiceFailure {
|
468
|
|
469
|
String username = sessionData.getUserName();
|
470
|
String[] groups = sessionData.getGroupNames();
|
471
|
|
472
|
// generate guid/localId pair for object
|
473
|
logMetacat.debug("Generating a guid/localId mapping");
|
474
|
IdentifierManager im = IdentifierManager.getInstance();
|
475
|
String localId = im.generateLocalId(guid.getValue(), 1);
|
476
|
|
477
|
try {
|
478
|
logMetacat.debug("Case DATA: starting to write to disk.");
|
479
|
if (DocumentImpl.getDataFileLockGrant(localId)) {
|
480
|
|
481
|
// Save the data file to disk using "localId" as the name
|
482
|
try {
|
483
|
String datafilepath = PropertyService.getProperty("application.datafilepath");
|
484
|
|
485
|
File dataDirectory = new File(datafilepath);
|
486
|
dataDirectory.mkdirs();
|
487
|
|
488
|
File newFile = writeStreamToFile(dataDirectory, localId, object);
|
489
|
|
490
|
// TODO: Check that the file size matches SystemMetadata
|
491
|
// long size = newFile.length();
|
492
|
// if (size == 0) {
|
493
|
// throw new IOException("Uploaded file is 0 bytes!");
|
494
|
// }
|
495
|
|
496
|
// Register the file in the database (which generates an exception
|
497
|
// if the localId is not acceptable or other untoward things happen
|
498
|
try {
|
499
|
logMetacat.debug("Registering document...");
|
500
|
System.out.println("inserting data object: localId: " + localId);
|
501
|
DocumentImpl.registerDocument(localId, "BIN", localId,
|
502
|
username, groups);
|
503
|
logMetacat.debug("Registration step completed.");
|
504
|
} catch (SQLException e) {
|
505
|
//newFile.delete();
|
506
|
logMetacat.debug("SQLE: " + e.getMessage());
|
507
|
e.printStackTrace(System.out);
|
508
|
throw new ServiceFailure(1190, "Registration failed: " + e.getMessage());
|
509
|
} catch (AccessionNumberException e) {
|
510
|
//newFile.delete();
|
511
|
logMetacat.debug("ANE: " + e.getMessage());
|
512
|
e.printStackTrace(System.out);
|
513
|
throw new ServiceFailure(1190, "Registration failed: " + e.getMessage());
|
514
|
} catch (Exception e) {
|
515
|
//newFile.delete();
|
516
|
logMetacat.debug("Exception: " + e.getMessage());
|
517
|
e.printStackTrace(System.out);
|
518
|
throw new ServiceFailure(1190, "Registration failed: " + e.getMessage());
|
519
|
}
|
520
|
|
521
|
logMetacat.debug("Logging the creation event.");
|
522
|
EventLog.getInstance().log(metacatUrl,
|
523
|
username, localId, "create");
|
524
|
|
525
|
// Schedule replication for this data file
|
526
|
logMetacat.debug("Scheduling replication.");
|
527
|
ForceReplicationHandler frh = new ForceReplicationHandler(
|
528
|
localId, "insert", false, null);
|
529
|
|
530
|
} catch (PropertyNotFoundException e) {
|
531
|
throw new ServiceFailure(1190, "Could not lock file for writing:" + e.getMessage());
|
532
|
}
|
533
|
|
534
|
}
|
535
|
} catch (Exception e) {
|
536
|
// Could not get a lock on the document, so we can not update the file now
|
537
|
throw new ServiceFailure(1190, "Failed to lock file: " + e.getMessage());
|
538
|
}
|
539
|
}
|
540
|
|
541
|
private File writeStreamToFile(File dir, String fileName, InputStream data)
|
542
|
throws ServiceFailure {
|
543
|
|
544
|
File newFile = new File(dir, fileName);
|
545
|
logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
|
546
|
|
547
|
try {
|
548
|
if (newFile.createNewFile()) {
|
549
|
// write data stream to desired file
|
550
|
OutputStream os = new FileOutputStream(newFile);
|
551
|
long length = IOUtils.copyLarge(data, os);
|
552
|
os.flush();
|
553
|
os.close();
|
554
|
} else {
|
555
|
logMetacat.debug("File creation failed, or file already exists.");
|
556
|
throw new ServiceFailure(1190, "File already exists: " + fileName);
|
557
|
}
|
558
|
} catch (FileNotFoundException e) {
|
559
|
logMetacat.debug("FNF: " + e.getMessage());
|
560
|
throw new ServiceFailure(1190, "File not found: " + fileName + " "
|
561
|
+ e.getMessage());
|
562
|
} catch (IOException e) {
|
563
|
logMetacat.debug("IOE: " + e.getMessage());
|
564
|
throw new ServiceFailure(1190, "File was not written: " + fileName
|
565
|
+ " " + e.getMessage());
|
566
|
}
|
567
|
|
568
|
return newFile;
|
569
|
}
|
570
|
|
571
|
/**
|
572
|
* insert a systemMetadata doc
|
573
|
*/
|
574
|
private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData)
|
575
|
throws ServiceFailure {
|
576
|
logMetacat.debug("Starting to insert SystemMetadata...");
|
577
|
|
578
|
// generate guid/localId pair for sysmeta
|
579
|
Identifier sysMetaGuid = new Identifier();
|
580
|
sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
|
581
|
sysmeta.setDateSysMetadataModified(new Date());
|
582
|
|
583
|
String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
|
584
|
String localId = insertDocument(xml, sysMetaGuid, sessionData);
|
585
|
//insert the system metadata doc id into the identifiers table to
|
586
|
//link it to the data or metadata document
|
587
|
IdentifierManager.getInstance().createSystemMetadataMapping(sysmeta.getIdentifier().getValue(), sysMetaGuid.getValue());
|
588
|
}
|
589
|
|
590
|
/**
|
591
|
* update a systemMetadata doc
|
592
|
*/
|
593
|
private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
|
594
|
throws ServiceFailure
|
595
|
{
|
596
|
try
|
597
|
{
|
598
|
String smId = IdentifierManager.getInstance().getSystemMetadataId(sm.getIdentifier().getValue());
|
599
|
sm.setDateSysMetadataModified(new Date());
|
600
|
String xml = new String(serializeSystemMetadata(sm).toByteArray());
|
601
|
Identifier id = new Identifier();
|
602
|
id.setValue(smId);
|
603
|
String localId = updateDocument(xml, id, null, sessionData);
|
604
|
IdentifierManager.getInstance().updateSystemMetadataMapping(sm.getIdentifier().getValue(), localId);
|
605
|
}
|
606
|
catch(Exception e)
|
607
|
{
|
608
|
throw new ServiceFailure(1030, "Error updating system metadata: " + e.getMessage());
|
609
|
}
|
610
|
}
|
611
|
|
612
|
/**
|
613
|
* insert a document
|
614
|
* NOTE: this method shouldn't be used from the update or create() methods.
|
615
|
* we shouldn't be putting the science metadata or data objects into memory.
|
616
|
*/
|
617
|
private String insertDocument(String xml, Identifier guid, SessionData sessionData)
|
618
|
throws ServiceFailure
|
619
|
{
|
620
|
return insertOrUpdateDocument(xml, guid, sessionData, "insert");
|
621
|
}
|
622
|
|
623
|
/**
|
624
|
* insert a document from a stream
|
625
|
*/
|
626
|
private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
|
627
|
throws IOException, ServiceFailure
|
628
|
{
|
629
|
//HACK: change this eventually. we should not be converting the stream to a string
|
630
|
String xml = IOUtils.toString(is);
|
631
|
return insertDocument(xml, guid, sessionData);
|
632
|
}
|
633
|
|
634
|
/**
|
635
|
* update a document
|
636
|
* NOTE: this method shouldn't be used from the update or create() methods.
|
637
|
* we shouldn't be putting the science metadata or data objects into memory.
|
638
|
*/
|
639
|
private String updateDocument(String xml, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
|
640
|
throws ServiceFailure
|
641
|
{
|
642
|
return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update");
|
643
|
}
|
644
|
|
645
|
/**
|
646
|
* update a document from a stream
|
647
|
*/
|
648
|
private String updateDocument(InputStream is, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
|
649
|
throws IOException, ServiceFailure
|
650
|
{
|
651
|
//HACK: change this eventually. we should not be converting the stream to a string
|
652
|
String xml = IOUtils.toString(is);
|
653
|
String localId = updateDocument(xml, obsoleteGuid, guid, sessionData);
|
654
|
IdentifierManager im = IdentifierManager.getInstance();
|
655
|
if(guid != null)
|
656
|
{
|
657
|
im.createMapping(guid.getValue(), localId);
|
658
|
}
|
659
|
return localId;
|
660
|
}
|
661
|
|
662
|
/**
|
663
|
* insert a document, return the id of the document that was inserted
|
664
|
*/
|
665
|
private String insertOrUpdateDocument(String xml, Identifier guid, SessionData sessionData, String insertOrUpdate)
|
666
|
throws ServiceFailure {
|
667
|
logMetacat.debug("Starting to insert xml document...");
|
668
|
IdentifierManager im = IdentifierManager.getInstance();
|
669
|
|
670
|
// generate guid/localId pair for sysmeta
|
671
|
String localId = null;
|
672
|
if(insertOrUpdate.equals("insert"))
|
673
|
{
|
674
|
localId = im.generateLocalId(guid.getValue(), 1);
|
675
|
}
|
676
|
else
|
677
|
{
|
678
|
//localid should already exist in the identifier table, so just find it
|
679
|
try
|
680
|
{
|
681
|
localId = im.getLocalId(guid.getValue());
|
682
|
//increment the revision
|
683
|
String docid = localId.substring(0, localId.lastIndexOf("."));
|
684
|
String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
|
685
|
int rev = new Integer(revS).intValue();
|
686
|
rev++;
|
687
|
docid = docid + "." + rev;
|
688
|
localId = docid;
|
689
|
}
|
690
|
catch(McdbDocNotFoundException e)
|
691
|
{
|
692
|
throw new ServiceFailure(1030, "CrudService.insertOrUpdateDocument(): " +
|
693
|
"guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
|
694
|
}
|
695
|
}
|
696
|
logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
|
697
|
localId);
|
698
|
|
699
|
String[] action = new String[1];
|
700
|
action[0] = insertOrUpdate;
|
701
|
params.put("action", action);
|
702
|
String[] docid = new String[1];
|
703
|
docid[0] = localId;
|
704
|
params.put("docid", docid);
|
705
|
String[] doctext = new String[1];
|
706
|
doctext[0] = xml;
|
707
|
logMetacat.debug(doctext[0]);
|
708
|
params.put("doctext", doctext);
|
709
|
|
710
|
// TODO: refactor handleInsertOrUpdateAction() to not output XML directly
|
711
|
// onto output stream, or alternatively, capture that and parse it to
|
712
|
// generate the right exceptions
|
713
|
//ByteArrayOutputStream output = new ByteArrayOutputStream();
|
714
|
//PrintWriter pw = new PrintWriter(output);
|
715
|
String result = handler.handleInsertOrUpdateAction(metacatUrl, null,
|
716
|
null, params, sessionData.getUserName(), sessionData.getGroupNames());
|
717
|
//String outputS = new String(output.toByteArray());
|
718
|
logMetacat.debug("CrudService.insertDocument - Metacat returned: " + result);
|
719
|
// if (!(outputS.indexOf("<success>") > 0 && outputS.indexOf(localId) > 0)) {
|
720
|
// throw new ServiceFailure(1190, outputS);
|
721
|
// }
|
722
|
logMetacat.debug("Finsished inserting xml document with id " + localId);
|
723
|
return localId;
|
724
|
}
|
725
|
|
726
|
public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta)
|
727
|
throws ServiceFailure {
|
728
|
IBindingFactory bfact;
|
729
|
ByteArrayOutputStream sysmetaOut = null;
|
730
|
try {
|
731
|
bfact = BindingDirectory.getFactory(SystemMetadata.class);
|
732
|
IMarshallingContext mctx = bfact.createMarshallingContext();
|
733
|
sysmetaOut = new ByteArrayOutputStream();
|
734
|
mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
|
735
|
} catch (JiBXException e) {
|
736
|
throw new ServiceFailure(1190, "Failed to serialize and insert SystemMetadata: " + e.getMessage());
|
737
|
}
|
738
|
|
739
|
return sysmetaOut;
|
740
|
}
|
741
|
|
742
|
public static SystemMetadata deserializeSystemMetadata(InputStream xml)
|
743
|
throws ServiceFailure {
|
744
|
try {
|
745
|
IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
|
746
|
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
|
747
|
SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
|
748
|
return sysmeta;
|
749
|
} catch (JiBXException e) {
|
750
|
throw new ServiceFailure(1190, "Failed to serialize and insert SystemMetadata: " + e.getMessage());
|
751
|
}
|
752
|
}
|
753
|
}
|