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: Serhan AKIN $'
|
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.restservice;
|
24
|
|
25
|
import java.io.ByteArrayOutputStream;
|
26
|
import java.io.IOException;
|
27
|
import java.io.InputStream;
|
28
|
import java.io.OutputStream;
|
29
|
import java.io.PrintWriter;
|
30
|
import java.util.Enumeration;
|
31
|
import java.util.Hashtable;
|
32
|
import java.util.Timer;
|
33
|
|
34
|
import javax.mail.BodyPart;
|
35
|
import javax.mail.MessagingException;
|
36
|
import javax.mail.internet.MimeMultipart;
|
37
|
import javax.servlet.ServletContext;
|
38
|
import javax.servlet.http.HttpServletRequest;
|
39
|
import javax.servlet.http.HttpServletResponse;
|
40
|
|
41
|
import org.apache.commons.io.IOUtils;
|
42
|
import org.apache.log4j.Logger;
|
43
|
import org.dataone.service.exceptions.BaseException;
|
44
|
import org.dataone.service.exceptions.IdentifierNotUnique;
|
45
|
import org.dataone.service.exceptions.InsufficientResources;
|
46
|
import org.dataone.service.exceptions.InvalidRequest;
|
47
|
import org.dataone.service.exceptions.InvalidSystemMetadata;
|
48
|
import org.dataone.service.exceptions.InvalidToken;
|
49
|
import org.dataone.service.exceptions.NotAuthorized;
|
50
|
import org.dataone.service.exceptions.NotImplemented;
|
51
|
import org.dataone.service.exceptions.ServiceFailure;
|
52
|
import org.dataone.service.exceptions.UnsupportedType;
|
53
|
import org.dataone.service.types.AuthToken;
|
54
|
import org.dataone.service.types.Identifier;
|
55
|
import org.dataone.service.types.SystemMetadata;
|
56
|
import org.jibx.runtime.BindingDirectory;
|
57
|
import org.jibx.runtime.IBindingFactory;
|
58
|
import org.jibx.runtime.IMarshallingContext;
|
59
|
import org.jibx.runtime.IUnmarshallingContext;
|
60
|
import org.jibx.runtime.JiBXException;
|
61
|
|
62
|
import edu.ucsb.nceas.metacat.DBUtil;
|
63
|
import edu.ucsb.nceas.metacat.IdentifierManager;
|
64
|
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
|
65
|
import edu.ucsb.nceas.metacat.MetacatHandler;
|
66
|
import edu.ucsb.nceas.metacat.dataone.CrudService;
|
67
|
import edu.ucsb.nceas.metacat.util.RequestUtil;
|
68
|
import edu.ucsb.nceas.metacat.util.SessionData;
|
69
|
|
70
|
/**
|
71
|
*
|
72
|
* Implements Earthgrid REST API to Metacat <br/><br/>
|
73
|
*
|
74
|
* <ul>
|
75
|
* <li>
|
76
|
* <h3> EarthGrid Query Service</h3>
|
77
|
* <ul><li>
|
78
|
* <h3>Get & Authenticated Get:</h3>
|
79
|
* is equal to Metacat's read action and returns a data file having
|
80
|
* the specified <doc-id> in the resource path. For authenticated Get service, a session id must be provided
|
81
|
* in the query string. <br/><br/>
|
82
|
*
|
83
|
* <b>REST URL:</b> <code>GET, [context-root]/object/[doc-id]?sessionid=[sessionid] </code><br/>
|
84
|
* <b>Returns:</b> data file <br/><br/>
|
85
|
* </li>
|
86
|
*
|
87
|
* <li>
|
88
|
* <h3>Query & Authenticated Query:</h3>
|
89
|
* Metacat's equivalent is squery action but this function
|
90
|
* receives a Earthgrid query document and returns Earthgrid resultset document by transforming those documents
|
91
|
* to Metacat's equivalents by the means of Metacat Implementation in Earthgrid library. For authenticated Query service
|
92
|
* a session id must be provided in the query string. See Earthgrid (a.k.a. Ecogrid) project for XSD files of
|
93
|
* query and resultset documents<br/><br/>
|
94
|
*
|
95
|
* <b>REST URL:</b> <code>POST, [context-root]/object?sessionid=[sessionid]</code> <br/>
|
96
|
* <b>POST Data:</b> Earthgrid query document , Content-type: <code>text/xml</code><br/>
|
97
|
* <b>Returns:</b> Earthgrid resultset document<br/><br/>
|
98
|
*
|
99
|
* </li>
|
100
|
* </ul>
|
101
|
*
|
102
|
* </li>
|
103
|
*
|
104
|
* <li>
|
105
|
* <h3> EarthGrid Authentication Service</h3>
|
106
|
* <ul><li>
|
107
|
* <h3>Login: </h3>
|
108
|
* Receives username and password parameters in POST data and
|
109
|
* returns SessionId (in XML format) or failure message and uses MetacatHandler's handleLoginAction function<br/><br/>
|
110
|
*
|
111
|
* <b>REST URL:</b> <code>POST, [context-root]/session?op=login</code> <br/>
|
112
|
* <b>POST Data:</b> username=[username]&password=[password], Content-type: <code>application/x-www-form-urlencoded</code>
|
113
|
* <b>Returns:</b> sessionId in XML format<br/><br/>
|
114
|
* </li>
|
115
|
*
|
116
|
* <li>
|
117
|
* <h3>Logout: </h3>
|
118
|
* Receives session Id parameters in querystring and returns xml message, calls
|
119
|
* MetacatHandler's handleLogoutAction function<br/><br/>
|
120
|
*
|
121
|
* <b>REST URL:</b> <code>GET, [context-root]/session?op=logout&sessionid=[sessionid]</code> <br/>
|
122
|
* <b>Returns:</b> message in XML format<br/><br/>
|
123
|
* </li>
|
124
|
* </ul>
|
125
|
*
|
126
|
* <li>
|
127
|
* <h3>EarthGrid Put Service</h3>
|
128
|
*
|
129
|
* <ul>
|
130
|
* <li><h3>Update/Insert: </h3>
|
131
|
* <br/>
|
132
|
* <b>REST URL:</b> <code>PUT, [context-root]/object/[doc-id]?op={update|insert}&sessionid=[sessionid]</code> <br/>
|
133
|
* <b>POST Data:</b> document object, Content-type: <code>text/xml</code><br/>
|
134
|
* <b>Returns:</b> message in XML format<br/><br/>
|
135
|
* </li>
|
136
|
*
|
137
|
* <li><h3>Delete: </h3>
|
138
|
* <br/>
|
139
|
* <b>REST URL:</b> <code>DELETE, [context-root]/object/[doc-id]?sessionid=[sessionid]</code> <br/>
|
140
|
* <b>Returns:</b> message in XML format<br/><br/>
|
141
|
* </li>
|
142
|
|
143
|
* </ul>
|
144
|
* </li>
|
145
|
*
|
146
|
* <li>
|
147
|
* <h3>EarthGrid Identifier Service</h3><br/>
|
148
|
*
|
149
|
* <ul>
|
150
|
* <li><h3>isRegistered: </h3> <br/>
|
151
|
* <b>REST URL:</b> <code>GET, [context-root]/identifier/[doc-id]?op=isregistered</code> <br/>
|
152
|
* <b>Returns:</b> message in XML format<br/><br/>
|
153
|
* </li>
|
154
|
|
155
|
* <li><h3>getAllDocIds:</h3> <br/>
|
156
|
* <b>REST URL:</b> <code>GET, [context-root]/identifier?op=getalldocids</code> <br/>
|
157
|
* <b>Returns:</b> document id list in XML format<br/><br/>
|
158
|
* </li>
|
159
|
*
|
160
|
* <li><h3>addLSID Function:</h3>
|
161
|
* Metacat does not support this function <br/>
|
162
|
* <b>REST URL:</b> <code>PUT, [context-root]/identifier/[doc-id]</code> <br/>
|
163
|
* <b>Returns:</b> error message in XML format<br/><br/>
|
164
|
* </li>
|
165
|
*
|
166
|
* <li><h3>getNextRevision:</h3> <br/>
|
167
|
* <b>REST URL:</b> <code>GET, [context-root]/identifier/[doc-id]?op=getnextrevision</code> <br/>
|
168
|
* <b>Returns:</b> message in XML format<br/><br/>
|
169
|
* </li>
|
170
|
*
|
171
|
* <li><h3>getNextObject:</h3> <br/>
|
172
|
* <b>REST URL:</b> <code>GET, [context-root]/identifier?op=getnextobject&scope=[scope]</code> <br/>
|
173
|
* <b>Returns:</b> message in XML format<br/><br/>
|
174
|
* </li>
|
175
|
*
|
176
|
* </li>
|
177
|
* </ul>
|
178
|
*
|
179
|
*/
|
180
|
public class ResourceHandler {
|
181
|
|
182
|
/**HTTP Verb GET*/
|
183
|
public static final byte GET = 1;
|
184
|
/**HTTP Verb POST*/
|
185
|
public static final byte POST = 2;
|
186
|
/**HTTP Verb PUT*/
|
187
|
public static final byte PUT = 3;
|
188
|
/**HTTP Verb DELETE*/
|
189
|
public static final byte DELETE = 4;
|
190
|
|
191
|
/*
|
192
|
* API Resources
|
193
|
*/
|
194
|
private static final String RESOURCE_OBJECTS = "object";
|
195
|
private static final String RESOURCE_META = "/meta";
|
196
|
private static final String RESOURCE_SESSION = "session";
|
197
|
private static final String RESOURCE_IDENTIFIER = "identifier";
|
198
|
|
199
|
/*
|
200
|
* API Functions used as URL parameters
|
201
|
*/
|
202
|
private static final String FUNCTION_KEYWORD = "op";
|
203
|
private static final String FUNCTION_NAME_LOGIN = "login";
|
204
|
private static final String FUNCTION_NAME_LOGOUT = "logout";
|
205
|
private static final String FUNCTION_NAME_ISREGISTERED = "isregistered";
|
206
|
private static final String FUNCTION_NAME_GETALLDOCS = "getalldocids";
|
207
|
private static final String FUNCTION_NAME_GETNEXTREV = "getnextrevision";
|
208
|
private static final String FUNCTION_NAME_GETNEXTOBJ = "getnextobject";
|
209
|
private static final String FUNCTION_NAME_INSERT = "insert";
|
210
|
private static final String FUNCTION_NAME_UPDATE = "update";
|
211
|
|
212
|
private ServletContext servletContext;
|
213
|
private Logger logMetacat;
|
214
|
private MetacatHandler handler;
|
215
|
private HttpServletRequest request;
|
216
|
private HttpServletResponse response;
|
217
|
private String username;
|
218
|
private String password;
|
219
|
private String sessionId;
|
220
|
private String[] groupNames;
|
221
|
|
222
|
private Hashtable<String, String[]> params;
|
223
|
|
224
|
/**Initializes new instance by setting servlet context,request and response*/
|
225
|
public ResourceHandler(ServletContext servletContext,
|
226
|
HttpServletRequest request, HttpServletResponse response) {
|
227
|
this.servletContext = servletContext;
|
228
|
this.request = request;
|
229
|
this.response = response;
|
230
|
}
|
231
|
|
232
|
/**
|
233
|
* copies request parameters to a hashtable which is given as argument to native metacathandler functions
|
234
|
*/
|
235
|
private void initParams() {
|
236
|
|
237
|
String name = null;
|
238
|
String[] value = null;
|
239
|
Enumeration paramlist = request.getParameterNames();
|
240
|
while (paramlist.hasMoreElements()) {
|
241
|
name = (String) paramlist.nextElement();
|
242
|
value = request.getParameterValues(name);
|
243
|
params.put(name, value);
|
244
|
}
|
245
|
|
246
|
}
|
247
|
|
248
|
/**
|
249
|
*
|
250
|
* Load user details of metacat session from the request
|
251
|
*
|
252
|
*/
|
253
|
private void loadSessionData() {
|
254
|
SessionData sessionData = RequestUtil.getSessionData(request);
|
255
|
|
256
|
// TODO: validate the session before allowing these values to be set
|
257
|
username = sessionData.getUserName();
|
258
|
password = sessionData.getPassword();
|
259
|
groupNames = sessionData.getGroupNames();
|
260
|
sessionId = sessionData.getId();
|
261
|
|
262
|
if (username == null) {
|
263
|
username = "public";
|
264
|
}
|
265
|
}
|
266
|
|
267
|
/**
|
268
|
* This function is called from REST APU servlet and handles each request to the servlet
|
269
|
*
|
270
|
* @param httpVerb (GET, POST, PUT or DELETE)
|
271
|
*/
|
272
|
public void handle(byte httpVerb) {
|
273
|
|
274
|
logMetacat = Logger.getLogger(ResourceHandler.class);
|
275
|
try {
|
276
|
String resource = request.getServletPath();
|
277
|
|
278
|
boolean status = false;
|
279
|
|
280
|
if (resource != null) {
|
281
|
resource = request.getServletPath().substring(1);
|
282
|
|
283
|
params = new Hashtable<String, String[]>();
|
284
|
initParams();
|
285
|
|
286
|
Timer timer = new Timer();
|
287
|
handler = new MetacatHandler(timer);
|
288
|
|
289
|
if (resource.equals(RESOURCE_SESSION) && httpVerb == POST
|
290
|
&& params.get(FUNCTION_KEYWORD) != null) {
|
291
|
if (params.get(FUNCTION_KEYWORD)[0]
|
292
|
.equals(FUNCTION_NAME_LOGIN)) {
|
293
|
login();
|
294
|
status = true;
|
295
|
} else if (params.get(FUNCTION_KEYWORD)[0]
|
296
|
.equals(FUNCTION_NAME_LOGOUT)) {
|
297
|
logout();
|
298
|
status = true;
|
299
|
}
|
300
|
} else if (resource.equals(RESOURCE_OBJECTS)) {
|
301
|
logMetacat.debug("D1 Rest: Starting resource processing...");
|
302
|
loadSessionData();
|
303
|
|
304
|
boolean isSysmetaRequest = false;
|
305
|
String objectId = request.getPathInfo();
|
306
|
if (objectId != null && objectId.length() > 1) {
|
307
|
objectId = request.getPathInfo().substring(1); //trim the slash
|
308
|
|
309
|
// Check if this is a request for SystemMetadata
|
310
|
// TODO: Note that this REST uri means that GUIDs can not contain the RESOURCE_META string
|
311
|
int start = objectId.indexOf(RESOURCE_META);
|
312
|
if (start >= 0) {
|
313
|
logMetacat.debug("Pruning meta at start value: " + start);
|
314
|
objectId = objectId.substring(0, start);
|
315
|
logMetacat.debug("New objectId for meta is: " + objectId);
|
316
|
isSysmetaRequest = true;
|
317
|
}
|
318
|
}
|
319
|
logMetacat.debug("Processing objectId: " + objectId);
|
320
|
logMetacat.debug("verb:" + httpVerb);
|
321
|
|
322
|
logMetacat.debug("objectId:" + objectId);
|
323
|
|
324
|
if (httpVerb == GET) {
|
325
|
if (isSysmetaRequest) {
|
326
|
getSystemMetadataObject(objectId);
|
327
|
} else {
|
328
|
getObject(objectId);
|
329
|
}
|
330
|
status = true;
|
331
|
} else if (httpVerb == POST) {
|
332
|
putObject(objectId, FUNCTION_NAME_INSERT);
|
333
|
status = true;
|
334
|
} else if (httpVerb == PUT) {
|
335
|
putObject(objectId, FUNCTION_NAME_UPDATE);
|
336
|
status = true;
|
337
|
} else if (httpVerb == DELETE) {
|
338
|
deleteObject(objectId);
|
339
|
status = true;
|
340
|
}
|
341
|
|
342
|
} else if (resource.equals(RESOURCE_IDENTIFIER)) {
|
343
|
|
344
|
String identifierId = request.getPathInfo();
|
345
|
if (identifierId != null && identifierId.length() > 1)
|
346
|
identifierId = request.getPathInfo().substring(1); //trim the slash
|
347
|
|
348
|
if (httpVerb == GET) {
|
349
|
String op = params.get(FUNCTION_KEYWORD)[0];
|
350
|
if (op.equals(FUNCTION_NAME_ISREGISTERED)) {
|
351
|
isRegistered(identifierId);
|
352
|
status = true;
|
353
|
} else if (op.equals(FUNCTION_NAME_GETALLDOCS)) {
|
354
|
getAllDocIds();
|
355
|
status = true;
|
356
|
} else if (op.equals(FUNCTION_NAME_GETNEXTREV)) {
|
357
|
getNextRevision(identifierId);
|
358
|
status = true;
|
359
|
} else if (op.equals(FUNCTION_NAME_GETNEXTOBJ)) {
|
360
|
getNextObject();
|
361
|
status = true;
|
362
|
}
|
363
|
|
364
|
} else if (httpVerb == PUT) {
|
365
|
//Earthgrid API > Identifier Service > addLSID Function
|
366
|
printError(
|
367
|
"This method is not supported by metacat. To "
|
368
|
+ "add a new LSID, add a document to metacat.",
|
369
|
response);
|
370
|
status = true;
|
371
|
}
|
372
|
|
373
|
}
|
374
|
if (!status)
|
375
|
printError("Incorrect parameters!", response);
|
376
|
} else {
|
377
|
printError("Incorrect resource!", response);
|
378
|
}
|
379
|
} catch (Exception e) {
|
380
|
logMetacat.error(e.getMessage());
|
381
|
e.printStackTrace();
|
382
|
}
|
383
|
}
|
384
|
|
385
|
/**
|
386
|
* Earthgrid API > Identifier Service > isRegistered Function : calls MetacatHandler > handleIdIsRegisteredAction
|
387
|
* @param guid
|
388
|
* @throws IOException
|
389
|
*/
|
390
|
private void isRegistered(String guid) throws IOException
|
391
|
{
|
392
|
|
393
|
// Look up the localId for this guid
|
394
|
IdentifierManager im = IdentifierManager.getInstance();
|
395
|
String localId = "";
|
396
|
try {
|
397
|
localId = im.getLocalId(guid);
|
398
|
} catch (McdbDocNotFoundException e) {
|
399
|
// TODO: Need to return the proper DataONE exception
|
400
|
}
|
401
|
|
402
|
params.put("docid", new String[] { localId });
|
403
|
PrintWriter out = response.getWriter();
|
404
|
handler.handleIdIsRegisteredAction(out, params, response);
|
405
|
out.close();
|
406
|
}
|
407
|
|
408
|
/**
|
409
|
* Earthgrid API > Identifier Service > getAllDocIds Function : calls MetacatHandler > handleGetAllDocidsAction
|
410
|
* @throws IOException
|
411
|
*/
|
412
|
private void getAllDocIds() throws IOException {
|
413
|
PrintWriter out = response.getWriter();
|
414
|
handler.handleGetAllDocidsAction(out, params, response);
|
415
|
out.close();
|
416
|
}
|
417
|
|
418
|
/**
|
419
|
* Earthgrid API > Identifier Service > getNextRevision Function : calls MetacatHandler > handleGetRevisionAndDocTypeAction
|
420
|
* @param guid
|
421
|
* @throws IOException
|
422
|
*/
|
423
|
private void getNextRevision(String guid) throws IOException
|
424
|
{
|
425
|
params.put("docid", new String[] { guid });
|
426
|
PrintWriter out = response.getWriter();
|
427
|
//handler.handleGetRevisionAndDocTypeAction(out, params);
|
428
|
|
429
|
try {
|
430
|
// Make sure there is a docid
|
431
|
if (guid == null || guid.equals("")) {
|
432
|
throw new Exception("User didn't specify docid!");
|
433
|
}
|
434
|
|
435
|
// Look up the localId for this guid
|
436
|
IdentifierManager im = IdentifierManager.getInstance();
|
437
|
String localId = "";
|
438
|
try {
|
439
|
localId = im.getLocalId(guid);
|
440
|
} catch (McdbDocNotFoundException e) {
|
441
|
// TODO: Need to return the proper DataONE exception
|
442
|
}
|
443
|
|
444
|
// Create a DBUtil object
|
445
|
DBUtil dbutil = new DBUtil();
|
446
|
// Get a rev and doctype
|
447
|
String revAndDocType = dbutil
|
448
|
.getCurrentRevisionAndDocTypeForGivenDocument(localId);
|
449
|
int revision = Integer.parseInt(revAndDocType.split(";")[0]) + 1;
|
450
|
|
451
|
out.println("<?xml version=\"1.0\"?>");
|
452
|
out.print("<next-revision>");
|
453
|
out.print(revision);
|
454
|
out.print("</next-revision>");
|
455
|
|
456
|
} catch (Exception e) {
|
457
|
// Handle exception
|
458
|
out.println("<?xml version=\"1.0\"?>");
|
459
|
out.println("<error>");
|
460
|
out.println(e.getMessage());
|
461
|
out.println("</error>");
|
462
|
}
|
463
|
|
464
|
out.close();
|
465
|
}
|
466
|
|
467
|
/**
|
468
|
* Earthgrid API > Identifier Service > getNextObject Function : calls MetacatHandler > handleGetMaxDocidAction
|
469
|
* @throws IOException
|
470
|
*/
|
471
|
private void getNextObject() throws IOException {
|
472
|
PrintWriter out = response.getWriter();
|
473
|
handler.handleGetMaxDocidAction(out, params, response);
|
474
|
out.close();
|
475
|
}
|
476
|
|
477
|
/**
|
478
|
* Implements REST version of DataONE CRUD API --> get
|
479
|
* @param guid ID of data object to be read
|
480
|
*/
|
481
|
private void getObject(String guid) {
|
482
|
//hack...fix this
|
483
|
//CrudService cs = new CrudService(servletContext, request, response);
|
484
|
CrudService cs = CrudService.getInstance();
|
485
|
cs.setParamsFromRequest(request);
|
486
|
AuthToken token = null;
|
487
|
OutputStream out = null;
|
488
|
try {
|
489
|
out = response.getOutputStream();
|
490
|
Identifier id = new Identifier();
|
491
|
id.setValue(guid);
|
492
|
InputStream data = cs.get(token, id);
|
493
|
IOUtils.copyLarge(data, response.getOutputStream());
|
494
|
} catch (BaseException e) {
|
495
|
serializeException(e, out);
|
496
|
} catch (IOException e) {
|
497
|
ServiceFailure sf = new ServiceFailure(1030, e.getMessage());
|
498
|
serializeException(sf, out);
|
499
|
}
|
500
|
}
|
501
|
|
502
|
/**
|
503
|
* Implements REST version of DataONE CRUD API --> getSystemMetadata
|
504
|
* @param guid ID of data object to be read
|
505
|
*/
|
506
|
private void getSystemMetadataObject(String guid) {
|
507
|
//CrudService cs = new CrudService(servletContext, request, response);
|
508
|
CrudService cs = CrudService.getInstance();
|
509
|
cs.setParamsFromRequest(request);
|
510
|
AuthToken token = null;
|
511
|
OutputStream out = null;
|
512
|
try {
|
513
|
out = response.getOutputStream();
|
514
|
Identifier id = new Identifier();
|
515
|
id.setValue(guid);
|
516
|
SystemMetadata sysmeta = cs.getSystemMetadata(token, id);
|
517
|
logMetacat.debug("Got sysmeta for: " + sysmeta.getIdentifier().getValue());
|
518
|
|
519
|
// Serialize and write it to the output stream
|
520
|
try {
|
521
|
IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
|
522
|
IMarshallingContext mctx = bfact.createMarshallingContext();
|
523
|
mctx.marshalDocument(sysmeta, "UTF-8", null, out);
|
524
|
} catch (JiBXException e) {
|
525
|
throw new ServiceFailure(1190, "Failed to serialize SystemMetadata: " + e.getMessage());
|
526
|
}
|
527
|
} catch (BaseException e) {
|
528
|
serializeException(e, out);
|
529
|
} catch (IOException e) {
|
530
|
ServiceFailure sf = new ServiceFailure(1030, e.getMessage());
|
531
|
serializeException(sf, out);
|
532
|
} finally {
|
533
|
IOUtils.closeQuietly(out);
|
534
|
}
|
535
|
}
|
536
|
|
537
|
/**
|
538
|
* Earthgrid API > Query Service > Query Function : translates ecogrid query document to metacat query
|
539
|
* then calls DBQuery > createResultDocument function and then again translate resultset to ecogrid resultset
|
540
|
*
|
541
|
* NOTE:
|
542
|
* This is the only method that uses EcoGrid classes for its implementation.
|
543
|
* It does so because it takes an EcoGrid Query as input, and outputs an
|
544
|
* EcoGrid ResultSet document. These documents are parsed by the auto-generated
|
545
|
* EcoGrid classes from axis, and so we link to them here rather than re-inventing them.
|
546
|
* This creates a circular dependency, because the Metacat classes are needed
|
547
|
* to build the EcoGrid implementation, and the EcoGrid jars are needed to build this query()
|
548
|
* method. This circularity could be resolved by moving the EcoGrid classes
|
549
|
* to Metacat directly. As we transition away from EcoGrid SOAP methods in
|
550
|
* favor of these REST interfaces, this circular dependency can be eliminated.
|
551
|
*
|
552
|
* @throws Exception
|
553
|
*/
|
554
|
private void query() throws Exception {
|
555
|
/* This block commented out because of the EcoGrid circular dependency.
|
556
|
* For now, query will not be supported until the circularity can be
|
557
|
* resolved, probably by moving the ecogrid query syntax transformers
|
558
|
* directly into the Metacat codebase. MBJ 2010-02-03
|
559
|
|
560
|
try {
|
561
|
EcogridQueryParser parser = new EcogridQueryParser(request
|
562
|
.getReader());
|
563
|
parser.parseXML();
|
564
|
QueryType queryType = parser.getEcogridQuery();
|
565
|
EcogridJavaToMetacatJavaQueryTransformer queryTransformer =
|
566
|
new EcogridJavaToMetacatJavaQueryTransformer();
|
567
|
QuerySpecification metacatQuery = queryTransformer
|
568
|
.transform(queryType);
|
569
|
|
570
|
DBQuery metacat = new DBQuery();
|
571
|
|
572
|
boolean useXMLIndex = (new Boolean(PropertyService
|
573
|
.getProperty("database.usexmlindex"))).booleanValue();
|
574
|
String xmlquery = "query"; // we don't care the query in resultset,
|
575
|
// the query can be anything
|
576
|
PrintWriter out = null; // we don't want metacat result, so set out null
|
577
|
|
578
|
// parameter: queryspecification, user, group, usingIndexOrNot
|
579
|
StringBuffer result = metacat.createResultDocument(xmlquery,
|
580
|
metacatQuery, out, username, groupNames, useXMLIndex);
|
581
|
|
582
|
// create result set transfer
|
583
|
String saxparser = PropertyService.getProperty("xml.saxparser");
|
584
|
MetacatResultsetParser metacatResultsetParser = new MetacatResultsetParser(
|
585
|
new StringReader(result.toString()), saxparser, queryType
|
586
|
.getNamespace().get_value());
|
587
|
ResultsetType records = metacatResultsetParser.getEcogridResult();
|
588
|
|
589
|
System.out
|
590
|
.println(EcogridResultsetTransformer.toXMLString(records));
|
591
|
response.setContentType("text/xml");
|
592
|
out = response.getWriter();
|
593
|
out.print(EcogridResultsetTransformer.toXMLString(records));
|
594
|
|
595
|
} catch (Exception e) {
|
596
|
e.printStackTrace();
|
597
|
}*/
|
598
|
response.setContentType("text/xml");
|
599
|
PrintWriter out = response.getWriter();
|
600
|
out.print("<error>Query operation not yet supported by Metacat.</error>");
|
601
|
out.close();
|
602
|
}
|
603
|
|
604
|
/**
|
605
|
* Earthgrid API > Put Service >Put Function : calls MetacatHandler > handleInsertOrUpdateAction
|
606
|
*
|
607
|
* @param guid ID of data object to be inserted or updated
|
608
|
* @throws IOException
|
609
|
*/
|
610
|
private void putObject(String guid, String action) {
|
611
|
logMetacat.debug("Entering putObject: " + guid + "/" + action);
|
612
|
|
613
|
// TODO: This function lacks proper handling of authz and authn, so it
|
614
|
// seems that anyone can insert or update; interacts with
|
615
|
// loadSessionData(), which doesn't validate the session
|
616
|
|
617
|
// Get an output stream for handling errors; this should really be passed in as
|
618
|
// a parameter
|
619
|
OutputStream out = null;
|
620
|
try {
|
621
|
out = response.getOutputStream();
|
622
|
} catch (IOException e1) {
|
623
|
logMetacat.error("Could not get the output stream for writing in putObject");
|
624
|
}
|
625
|
try {
|
626
|
if (action.equals(FUNCTION_NAME_UPDATE)
|
627
|
|| action.equals(FUNCTION_NAME_INSERT)) {
|
628
|
|
629
|
// Check if the objectId exists
|
630
|
IdentifierManager im = IdentifierManager.getInstance();
|
631
|
if (im.identifierExists(guid)) {
|
632
|
throw new IdentifierNotUnique(1000, "Identifier is already in use: " + guid);
|
633
|
}
|
634
|
|
635
|
// TODO: For updates, need to check if the old id exists, and if not throw an exception
|
636
|
|
637
|
// Read the incoming data from its Mime Multipart encoding
|
638
|
logMetacat.debug("Disassembling MIME multipart form");
|
639
|
InputStream object = null;
|
640
|
InputStream sysmeta = null;
|
641
|
MimeMultipart mmp = new MimeMultipart(new InputStreamDataSource("message", request.getInputStream()));
|
642
|
logMetacat.debug("MMP created.");
|
643
|
mmp.writeTo(System.out);
|
644
|
for (int i = 0; i < mmp.getCount(); i++) {
|
645
|
logMetacat.debug("Looping over MMP parts: " + i);
|
646
|
BodyPart part = mmp.getBodyPart(i);
|
647
|
String name = part.getFileName();
|
648
|
logMetacat.debug("Part name is: " + name);
|
649
|
logMetacat.debug("Part has class name: " + part.getClass().getName());
|
650
|
if (name.equals("object")) {
|
651
|
object = part.getInputStream();
|
652
|
logMetacat.debug("Found object part, size is: " + part.getSize());
|
653
|
} else if (name.equals("systemmetadata")) {
|
654
|
sysmeta = part.getInputStream();
|
655
|
logMetacat.debug("Found sysmeta part, size is: " + part.getSize());
|
656
|
} else {
|
657
|
throw new InvalidRequest(1000, "Request had malformed MIME part with name: " + name);
|
658
|
}
|
659
|
}
|
660
|
|
661
|
// TODO: access control -- should be in CrudService et al. I think
|
662
|
//if (username != null && !username.equals("public")) {
|
663
|
if (username != null) {
|
664
|
|
665
|
logMetacat.debug("Commence creation...");
|
666
|
AuthToken token = null;
|
667
|
IBindingFactory bfact =
|
668
|
BindingDirectory.getFactory(SystemMetadata.class);
|
669
|
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
|
670
|
SystemMetadata m = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
|
671
|
|
672
|
CrudService cs = CrudService.getInstance();
|
673
|
cs.setParamsFromRequest(request);
|
674
|
Identifier id = new Identifier();
|
675
|
id.setValue(guid);
|
676
|
cs.create(token, id, object, m);
|
677
|
|
678
|
} else {
|
679
|
logMetacat.debug("Unauthorized to create.");
|
680
|
throw new NotAuthorized(1000, "Permission denied for user " + username);
|
681
|
}
|
682
|
} else {
|
683
|
throw new InvalidRequest(1000, "Operation must be create or update.");
|
684
|
}
|
685
|
} catch (NotAuthorized e) {
|
686
|
serializeException(e, out);
|
687
|
} catch (InvalidToken e) {
|
688
|
serializeException(e, out);
|
689
|
} catch (ServiceFailure e) {
|
690
|
serializeException(e, out);
|
691
|
} catch (IdentifierNotUnique e) {
|
692
|
serializeException(e, out);
|
693
|
} catch (UnsupportedType e) {
|
694
|
serializeException(e, out);
|
695
|
} catch (InsufficientResources e) {
|
696
|
serializeException(e, out);
|
697
|
} catch (InvalidSystemMetadata e) {
|
698
|
serializeException(e, out);
|
699
|
} catch (NotImplemented e) {
|
700
|
serializeException(e, out);
|
701
|
} catch (InvalidRequest e) {
|
702
|
serializeException(e, out);
|
703
|
} catch (MessagingException e) {
|
704
|
ServiceFailure sf = new ServiceFailure(1000, e.getMessage());
|
705
|
serializeException(sf, out);
|
706
|
} catch (IOException e) {
|
707
|
ServiceFailure sf = new ServiceFailure(1000, e.getMessage());
|
708
|
serializeException(sf, out);
|
709
|
} catch (JiBXException e) {
|
710
|
e.printStackTrace(System.out);
|
711
|
InvalidSystemMetadata ism = new InvalidSystemMetadata(1080, e.getMessage());
|
712
|
serializeException(ism, out);
|
713
|
}
|
714
|
}
|
715
|
|
716
|
/**
|
717
|
* Earthgrid API > Put Service > Delete Function : calls MetacatHandler > handleDeleteAction
|
718
|
*
|
719
|
* @param guid ID of data object to be deleted
|
720
|
* @throws IOException
|
721
|
*/
|
722
|
private void deleteObject(String guid) throws IOException
|
723
|
{
|
724
|
// Look up the localId for this global identifier
|
725
|
IdentifierManager im = IdentifierManager.getInstance();
|
726
|
String localId = "";
|
727
|
try {
|
728
|
localId = im.getLocalId(guid);
|
729
|
} catch (McdbDocNotFoundException e) {
|
730
|
// TODO: Need to return the proper DataONE exception
|
731
|
}
|
732
|
|
733
|
params.put("docid", new String[] { localId });
|
734
|
PrintWriter out = response.getWriter();
|
735
|
handler.handleDeleteAction(out, params, request, response, username,
|
736
|
groupNames);
|
737
|
out.close();
|
738
|
}
|
739
|
|
740
|
/**
|
741
|
* Earthgrid API > Authentication Service > Login Function : calls MetacatHandler > handleLoginAction
|
742
|
*
|
743
|
* @throws IOException
|
744
|
*/
|
745
|
private void login() throws IOException {
|
746
|
PrintWriter out = response.getWriter();
|
747
|
handler.handleLoginAction(out, params, request, response);
|
748
|
out.close();
|
749
|
}
|
750
|
|
751
|
/**
|
752
|
* Earthgrid API > Authentication Service > Logout Function : calls MetacatHandler > handleLogoutAction
|
753
|
*
|
754
|
* @throws IOException
|
755
|
*/
|
756
|
private void logout() throws IOException {
|
757
|
PrintWriter out = response.getWriter();
|
758
|
handler.handleLogoutAction(out, params, request, response);
|
759
|
out.close();
|
760
|
}
|
761
|
|
762
|
/**
|
763
|
* Prints xml response
|
764
|
* @param message Message to be displayed
|
765
|
* @param response Servlet response that xml message will be printed
|
766
|
* */
|
767
|
private void printError(String message, HttpServletResponse response) {
|
768
|
try {
|
769
|
PrintWriter out = response.getWriter();
|
770
|
response.setContentType("text/xml");
|
771
|
out.println("<?xml version=\"1.0\"?>");
|
772
|
out.println("<error>");
|
773
|
out.println(message);
|
774
|
out.println("</error>");
|
775
|
out.close();
|
776
|
} catch (IOException e) {
|
777
|
e.printStackTrace();
|
778
|
}
|
779
|
}
|
780
|
|
781
|
private void serializeException(BaseException e, OutputStream out) {
|
782
|
// TODO: Use content negotiation to determine which return format to use
|
783
|
response.setContentType("text/xml");
|
784
|
response.setStatus(e.getCode());
|
785
|
try {
|
786
|
IOUtils.write(e.serialize(BaseException.FMT_XML), out);
|
787
|
} catch (IOException e1) {
|
788
|
logMetacat.error("Error writing exception to stream. "
|
789
|
+ e1.getMessage());
|
790
|
}
|
791
|
}
|
792
|
|
793
|
}
|