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