Project

General

Profile

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
import java.text.ParseException;
36
import java.text.ParsePosition;
37
import java.text.SimpleDateFormat;
38

    
39

    
40
import org.apache.commons.httpclient.util.DateParser;
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.exceptions.NotFound;
54
import org.dataone.service.types.*;
55
import org.jibx.runtime.BindingDirectory;
56
import org.jibx.runtime.IBindingFactory;
57
import org.jibx.runtime.IMarshallingContext;
58
import org.jibx.runtime.IUnmarshallingContext;
59
import org.jibx.runtime.JiBXException;
60

    
61
import edu.ucsb.nceas.metacat.DBUtil;
62
import edu.ucsb.nceas.metacat.IdentifierManager;
63
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
64
import edu.ucsb.nceas.metacat.MetacatHandler;
65
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
66
import edu.ucsb.nceas.metacat.dataone.CrudService;
67
import edu.ucsb.nceas.metacat.service.SessionService;
68
import edu.ucsb.nceas.metacat.util.RequestUtil;
69
import edu.ucsb.nceas.metacat.util.SessionData;
70

    
71
/**
72
 * 
73
 * Implements Earthgrid REST API to Metacat <br/><br/> 
74
 * 
75
 * <ul>
76
 * <li>
77
 * <h3> EarthGrid Query Service</h3>
78
 * <ul><li>
79
 * <h3>Get & Authenticated Get:</h3> 
80
 * is equal to Metacat's read action and returns a data file having
81
 * the specified <doc-id> in the resource path. For authenticated Get service, a session id must be provided 
82
 * in the query string. <br/><br/>
83
 * 
84
 * <b>REST URL:</b>	<code>GET, [context-root]/object/[doc-id]?sessionid=[sessionid] </code><br/>
85
 * <b>Returns:</b> data file <br/><br/>
86
 * </li>
87
 * 
88
 * <li>
89
 * <h3>Query & Authenticated Query:</h3> 
90
 * Metacat's equivalent is squery action but this function 
91
 * receives a Earthgrid query document and returns Earthgrid resultset document by transforming those documents
92
 * to Metacat's equivalents by the means of Metacat Implementation in Earthgrid library. For authenticated Query service 
93
 * a session id must be provided in the query string. See Earthgrid (a.k.a. Ecogrid) project for XSD files of 
94
 * query and resultset documents<br/><br/>
95
 * 
96
 * <b>REST URL:</b>	<code>POST, [context-root]/object?sessionid=[sessionid]</code>    <br/>
97
 * <b>POST Data:</b> Earthgrid query document , Content-type: <code>text/xml</code><br/>
98
 * <b>Returns:</b> Earthgrid resultset document<br/><br/>
99
 * 
100
 * </li>
101
 * </ul>
102
 * 
103
 * </li>
104
 * 
105
 * <li>
106
 * <h3> EarthGrid Authentication Service</h3>
107
 * <ul><li>
108
 * <h3>Login: </h3> 
109
 * Receives username and password parameters in POST data and 
110
 * returns SessionId (in XML format) or failure message and uses MetacatHandler's handleLoginAction function<br/><br/>
111
 *  
112
 * <b>REST URL:</b> <code>POST, [context-root]/session?op=login</code> <br/>
113
 * <b>POST Data:</b> username=[username]&password=[password], Content-type: <code>application/x-www-form-urlencoded</code>
114
 * <b>Returns:</b> sessionId in XML format<br/><br/>
115
 * </li>
116
 * 
117
 * <li>
118
 * <h3>Logout: </h3> 
119
 * Receives session Id parameters in querystring and returns xml message, calls 
120
 * MetacatHandler's handleLogoutAction function<br/><br/>
121
 *  
122
 * <b>REST URL:</b>	<code>GET, [context-root]/session?op=logout&sessionid=[sessionid]</code>   <br/>
123
 * <b>Returns:</b> message in XML format<br/><br/>
124
 * </li>
125
 * </ul>
126
 * 
127
 * <li>
128
 * <h3>EarthGrid Put Service</h3>
129
 * 
130
 * <ul>
131
 * <li><h3>Update/Insert: </h3>		
132
 * <br/>
133
 * <b>REST URL:</b>	<code>PUT, [context-root]/object/[doc-id]?op={update|insert}&sessionid=[sessionid]</code>   <br/>
134
 * <b>POST Data:</b> document object, Content-type: <code>text/xml</code><br/>
135
 * <b>Returns:</b> message in XML format<br/><br/>
136
 * </li>
137
 * 
138
 * <li><h3>Delete: </h3>		
139
 * <br/>
140
 * <b>REST URL:</b>	<code>DELETE, [context-root]/object/[doc-id]?sessionid=[sessionid]</code>   <br/>
141
 * <b>Returns:</b> message in XML format<br/><br/>
142
 * </li>
143

    
144
 * </ul>
145
 * </li>
146
 * 
147
 * <li>
148
 * <h3>EarthGrid Identifier Service</h3><br/>
149
 * 
150
 * <ul>
151
 * <li><h3>isRegistered: </h3>		<br/>
152
 * <b>REST URL:</b>	<code>GET, [context-root]/identifier/[doc-id]?op=isregistered</code>   <br/>
153
 * <b>Returns:</b> message in XML format<br/><br/>
154
 * </li>
155

    
156
 * <li><h3>getAllDocIds:</h3>		<br/>		
157
 * <b>REST URL:</b>	<code>GET, [context-root]/identifier?op=getalldocids</code>   <br/>
158
 * <b>Returns:</b> document id list in XML format<br/><br/>
159
 * </li>
160
 * 
161
 * <li><h3>addLSID Function:</h3> 
162
 * Metacat does not support this function 		<br/>
163
 * <b>REST URL:</b>	<code>PUT, [context-root]/identifier/[doc-id]</code>   <br/>
164
 * <b>Returns:</b> error message in XML format<br/><br/>
165
 * </li>
166
 * 
167
 * <li><h3>getNextRevision:</h3>		<br/>
168
 * <b>REST URL:</b>	<code>GET, [context-root]/identifier/[doc-id]?op=getnextrevision</code>   <br/>
169
 * <b>Returns:</b> message in XML format<br/><br/>
170
 * </li>
171
 * 
172
 * <li><h3>getNextObject:</h3>		<br/>
173
 * <b>REST URL:</b>	<code>GET, [context-root]/identifier?op=getnextobject&scope=[scope]</code>   <br/>
174
 * <b>Returns:</b> message in XML format<br/><br/>
175
 * </li>
176
 * 
177
 * </li>
178
 * </ul>
179
 * 
180
 */
181
public class ResourceHandler {
182

    
183
    /**HTTP Verb GET*/
184
    public static final byte GET = 1;
185
    /**HTTP Verb POST*/
186
    public static final byte POST = 2;
187
    /**HTTP Verb PUT*/
188
    public static final byte PUT = 3;
189
    /**HTTP Verb DELETE*/
190
    public static final byte DELETE = 4;
191

    
192
    /*
193
     * API Resources
194
     */
195
    private static final String RESOURCE_OBJECTS = "object";
196
    private static final String RESOURCE_META = "meta";
197
    private static final String RESOURCE_SESSION = "session";
198
    private static final String RESOURCE_IDENTIFIER = "identifier";
199
    private static final String RESOURCE_LOG = "log";
200

    
201
    /*
202
     * API Functions used as URL parameters
203
     */
204
    private static final String FUNCTION_KEYWORD = "op";
205
    private static final String FUNCTION_NAME_LOGIN = "login";
206
    private static final String FUNCTION_NAME_LOGOUT = "logout";
207
    private static final String FUNCTION_NAME_SET_ACCESS = "setaccess";
208
    private static final String FUNCTION_NAME_ISREGISTERED = "isregistered";
209
    private static final String FUNCTION_NAME_GETALLDOCS = "getalldocids";
210
    private static final String FUNCTION_NAME_GETNEXTREV = "getnextrevision";
211
    private static final String FUNCTION_NAME_GETNEXTOBJ = "getnextobject";
212
    private static final String FUNCTION_NAME_INSERT = "insert";
213
    private static final String FUNCTION_NAME_UPDATE = "update";
214
    private static final String FUNCTION_NAME_GENERATE_MISSING_SYSTEM_METADATA = "generatemissingsystemmetadata";
215

    
216
    private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
217
    
218
    private ServletContext servletContext;
219
    private Logger logMetacat;
220
    private MetacatHandler handler;
221
    private HttpServletRequest request;
222
    private HttpServletResponse response;
223
    private String username;
224
    private String password;
225
    private String sessionId;
226
    private String[] groupNames;
227

    
228
    private Hashtable<String, String[]> params;
229

    
230
    /**Initializes new instance by setting servlet context,request and response*/
231
    public ResourceHandler(ServletContext servletContext,
232
            HttpServletRequest request, HttpServletResponse response) {
233
        this.servletContext = servletContext;
234
        this.request = request;
235
        this.response = response;
236
    }
237

    
238
    /**
239
     * This function is called from REST APU servlet and handles each request to the servlet 
240
     * 
241
     * @param httpVerb (GET, POST, PUT or DELETE)
242
     */
243
    public void handle(byte httpVerb) {
244
        logMetacat = Logger.getLogger(ResourceHandler.class);
245
        try {
246
            String resource = request.getServletPath();
247
            String verb = "";
248
            
249
            System.out.println("handling verb " + httpVerb + " request with resource " + resource);
250
            boolean status = false;
251
            loadSessionData();
252

    
253
            if (resource != null) {
254
                resource = request.getServletPath().substring(1);
255

    
256
                params = new Hashtable<String, String[]>();
257
                initParams();
258

    
259
                Timer timer = new Timer();
260
                handler = new MetacatHandler(timer);
261

    
262
                if (resource.equals(RESOURCE_SESSION) && 
263
                    httpVerb == POST && 
264
                    params.get(FUNCTION_KEYWORD) != null) {
265
                    //System.out.println("function_keyword: " + params.get(FUNCTION_KEYWORD)[0]);
266
                        if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_LOGIN)) {
267
                            login();
268
                            status = true;
269
                        } else if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_LOGOUT)) {
270
                            logout();
271
                            status = true;
272
                        } else if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_SET_ACCESS)) {
273
                            setaccess();
274
                            status = true;
275
                            //System.out.println("done setting access");
276
                        }
277
                    } else if (resource.equals(RESOURCE_META)) {
278
                        if(params != null && params.get(FUNCTION_KEYWORD) != null &&
279
                           params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_GENERATE_MISSING_SYSTEM_METADATA))
280
                        { //generate system metadata for any object that is
281
                          //a) not system metadata itself
282
                          //b) does not already have a system metadata id in the systemmetadata table
283
                          //c) not a BIN object (data)
284
                            generateMissingSystemMetadata();
285
                            status = true;
286
                        }
287
                        else
288
                        {
289
                            String objectId = request.getPathInfo();
290
                            if (objectId != null && objectId.length() > 1) 
291
                            {
292
                                objectId = request.getPathInfo().substring(1);
293
                            }
294
                            getSystemMetadataObject(objectId);
295
                            status = true;
296
                        }
297
                            
298
                    } else if (resource.equals(RESOURCE_OBJECTS)) {
299
                    logMetacat.debug("D1 Rest: Starting resource processing...");
300
                    loadSessionData();
301

    
302
                    String objectId = request.getPathInfo();
303
                    if (objectId != null && objectId.length() > 1) 
304
                    {
305
                        objectId = request.getPathInfo().substring(1);
306
                    }
307
                    else
308
                    {
309
                        objectId = null;
310
                    }
311
                    
312
                    logMetacat.debug("verb:" + httpVerb);
313

    
314
                    if (httpVerb == GET) {
315
                        getObject(objectId);
316
                        status = true;
317
                    } else if (httpVerb == POST) {
318
                        putObject(objectId, FUNCTION_NAME_INSERT);
319
                        status = true;
320
                    } else if (httpVerb == PUT) {
321
                        putObject(objectId, FUNCTION_NAME_UPDATE);
322
                        status = true;
323
                    } else if (httpVerb == DELETE) {
324
                        deleteObject(objectId);
325
                        status = true;
326
                    }
327

    
328
                } else if (resource.equals(RESOURCE_IDENTIFIER)) {
329

    
330
                    String identifierId = request.getPathInfo();
331
                    if (identifierId != null && identifierId.length() > 1)
332
                        identifierId = request.getPathInfo().substring(1); //trim the slash
333

    
334
                    if (httpVerb == GET) {
335
                        String op = params.get(FUNCTION_KEYWORD)[0];
336
                        if (op.equals(FUNCTION_NAME_ISREGISTERED)) {
337
                            isRegistered(identifierId);
338
                            status = true;
339
                        } else if (op.equals(FUNCTION_NAME_GETALLDOCS)) {
340
                            getAllDocIds();
341
                            status = true;
342
                        } else if (op.equals(FUNCTION_NAME_GETNEXTREV)) {
343
                            getNextRevision(identifierId);
344
                            status = true;
345
                        } else if (op.equals(FUNCTION_NAME_GETNEXTOBJ)) {
346
                            getNextObject();
347
                            status = true;
348
                        } 
349

    
350
                    } else if (httpVerb == PUT) {
351
                        //Earthgrid API > Identifier Service > addLSID Function 
352
                        printError(
353
                                "This method is not supported by metacat.  To "
354
                                        + "add a new LSID, add a document to metacat.",
355
                                response);
356
                        status = true;
357
                    }
358

    
359
                } else if (resource.equals(RESOURCE_LOG)) {
360
                    //handle log events
361
                    if(httpVerb == GET)
362
                    {
363
                        getLog();
364
                        status = true;
365
                    }
366
                    else
367
                    {
368
                        printError("POST, PUT, DELETE is not supported for logs.", response);
369
                        status = true;
370
                    }
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
     * get the logs from the CrudService based on passed params.  Available 
387
     * params are token, fromDate, toDate, event.  See 
388
     * http://mule1.dataone.org/ArchitectureDocs/mn_api_crud.html#MN_crud.getLogRecords
389
     * for more info
390
     */
391
    private void getLog()
392
    {
393
        OutputStream out = null;
394
        try
395
        {
396
            out = response.getOutputStream();
397
            AuthToken token = new AuthToken(sessionId);
398
            String fromDateS = params.get("fromDate")[0];
399
            System.out.println("param fromDateS: " + fromDateS);
400
            Date fromDate = null;
401
            String toDateS = params.get("toDate")[0];
402
            System.out.println("param toDateS: " + toDateS);
403
            Date toDate = null;
404
            String eventS = params.get("event")[0];
405
            Event event = null;
406
            if(fromDateS != null)
407
            {
408
                //fromDate = CrudService.getInstance().parseDate(fromDateS);
409
                fromDate = dateFormat.parse(fromDateS);
410
            }
411
            if(toDateS != null)
412
            {
413
                //toDate = CrudService.getInstance().parseDate(toDateS);
414
                toDate = dateFormat.parse(toDateS);
415
            }
416
            if(eventS != null)
417
            {
418
                event = Event.convert(eventS);
419
            }
420
            System.out.println("fromDate: " + fromDate + " toDate: " + toDate);
421
            
422
            System.out.println("calling crudservice.getLogRecords");
423
            Log log = CrudService.getInstance().getLogRecords(token, fromDate, toDate, event);
424
            serializeServiceType(Log.class, log, out);
425
        }
426
        catch(Exception e)
427
        {
428
            String msg = "Could not get logs from CrudService: " + e.getMessage();
429
            ServiceFailure sf = new ServiceFailure("1490", msg);
430
            logMetacat.error(msg);
431
            e.printStackTrace();
432
            serializeException(sf, out);
433
        }
434
    }
435
    
436
    /**
437
     *  copies request parameters to a hashtable which is given as argument to native metacathandler functions  
438
     */
439
    private void initParams() {
440

    
441
        String name = null;
442
        String[] value = null;
443
        Enumeration paramlist = request.getParameterNames();
444
        while (paramlist.hasMoreElements()) {
445
            name = (String) paramlist.nextElement();
446
            value = request.getParameterValues(name);
447
            params.put(name, value);
448
        }
449
    }
450

    
451
    /**
452
     * 
453
     * Load user details of metacat session from the request 
454
     * 
455
     */
456
    private void loadSessionData()
457
      throws Exception
458
    {
459
        SessionData sessionData = RequestUtil.getSessionData(request);
460
        try
461
        {
462
            username = null;
463
            password = null;
464
            groupNames = null;
465
            sessionId = null;
466
            
467
            boolean validSession = false;
468
            SessionService ss = SessionService.getInstance();
469
            System.out.println("sessionData: " + sessionData);
470
            if(sessionData == null)
471
            {
472
                username = "public";
473
                sessionId = "0";
474
                System.out.println("sessiondata is null.  Creating a public session.");
475
                return;
476
            }
477
            
478
            System.out.println("username: " + sessionData.getUserName());
479
            System.out.println("sessionid: " + sessionData.getId());
480
            //validate the session
481
            if(ss.isSessionRegistered(sessionData.getId()) && 
482
               !(sessionData.getUserName().equals("public") || sessionData.getId().equals("0")))
483
            {
484
                validSession = true;
485
            }
486
            
487
            if(validSession)
488
            {
489
                //if the session is valid, set these variables
490
                username = sessionData.getUserName();
491
                password = sessionData.getPassword();
492
                groupNames = sessionData.getGroupNames();
493
                sessionId = sessionData.getId();
494
                System.out.println("setting sessionid to " + sessionId);
495
                System.out.println("username: " + username);
496
            }
497
            
498
            //if the session is not valid or the username is null, set
499
            //username to public
500
            if (username == null) 
501
            {
502
                System.out.println("setting username to public.");
503
                username = "public";
504
            }
505
        }
506
        catch(Exception e)
507
        {
508
            e.printStackTrace();
509
            throw new Exception("Could not load the session data: " + e.getMessage());
510
        }
511
    }
512
    
513
    /**
514
     * generate missing system metadata for any science metadata objects
515
     * that don't already have it. https://trac.dataone.org/ticket/591
516
     * 
517
     * called with POST meta/?op=generatemissingsystemmetadata
518
     */
519
    private void generateMissingSystemMetadata()
520
    {
521
        AuthToken token = new AuthToken(sessionId);
522
        CrudService.getInstance().generateMissingSystemMetadata(token);
523
    }
524

    
525
    /**
526
     *  Earthgrid API > Identifier Service > isRegistered Function : 
527
     *  calls MetacatHandler > handleIdIsRegisteredAction
528
     * @param guid
529
     * @throws IOException
530
     */
531
    private void isRegistered(String guid) throws IOException
532
    {
533
        
534
        // Look up the localId for this guid
535
        IdentifierManager im = IdentifierManager.getInstance();
536
        String localId = "";
537
        try {
538
            localId = im.getLocalId(guid);
539
        } catch (McdbDocNotFoundException e) {
540
            // TODO: Need to return the proper DataONE exception
541
        }
542
        
543
        params.put("docid", new String[] { localId });
544
        PrintWriter out = response.getWriter();
545
        handler.handleIdIsRegisteredAction(out, params, response);
546
        out.close();
547
    }
548

    
549
    /**
550
     * Earthgrid API > Identifier Service > getAllDocIds Function : 
551
     * calls MetacatHandler > handleGetAllDocidsAction
552
     * @throws IOException
553
     */
554
    private void getAllDocIds() throws IOException {
555
        PrintWriter out = response.getWriter();
556
        handler.handleGetAllDocidsAction(out, params, response);
557
        out.close();
558
    }
559

    
560
    /**
561
     * Earthgrid API > Identifier Service > getNextRevision Function : 
562
     * calls MetacatHandler > handleGetRevisionAndDocTypeAction
563
     * @param guid
564
     * @throws IOException
565
     */
566
    private void getNextRevision(String guid) throws IOException 
567
    {
568
        params.put("docid", new String[] { guid });
569
        PrintWriter out = response.getWriter();
570
        //handler.handleGetRevisionAndDocTypeAction(out, params);
571

    
572
        try {
573
            // Make sure there is a docid
574
            if (guid == null || guid.equals("")) {
575
                throw new Exception("User didn't specify docid!");
576
            }
577

    
578
            // Look up the localId for this guid
579
            IdentifierManager im = IdentifierManager.getInstance();
580
            String localId = "";
581
            try {
582
                localId = im.getLocalId(guid);
583
            } catch (McdbDocNotFoundException e) {
584
                // TODO: Need to return the proper DataONE exception
585
            }
586
           
587
            // Create a DBUtil object
588
            DBUtil dbutil = new DBUtil();
589
            // Get a rev and doctype
590
            String revAndDocType = dbutil
591
                    .getCurrentRevisionAndDocTypeForGivenDocument(localId);
592
            int revision = Integer.parseInt(revAndDocType.split(";")[0]) + 1;
593

    
594
            out.println("<?xml version=\"1.0\"?>");
595
            out.print("<next-revision>");
596
            out.print(revision);
597
            out.print("</next-revision>");
598

    
599
        } catch (Exception e) {
600
            // Handle exception
601
            out.println("<?xml version=\"1.0\"?>");
602
            out.println("<error>");
603
            out.println(e.getMessage());
604
            out.println("</error>");
605
        }
606

    
607
        out.close();
608
    }
609

    
610
    /**
611
     * Earthgrid API > Identifier Service > getNextObject Function : 
612
     * calls MetacatHandler > handleGetMaxDocidAction
613
     * @throws IOException
614
     */
615
    private void getNextObject() throws IOException {
616
        PrintWriter out = response.getWriter();
617
        handler.handleGetMaxDocidAction(out, params, response);
618
        out.close();
619
    }
620

    
621
    /**
622
     * Implements REST version of DataONE CRUD API --> get
623
     * @param guid ID of data object to be read
624
     */
625
    private void getObject(String guid) {
626
        CrudService cs = CrudService.getInstance();
627
        cs.setParamsFromRequest(request);
628
        AuthToken token = new AuthToken(sessionId);
629
        OutputStream out = null;
630
        try {
631
            out = response.getOutputStream();
632
            if(guid != null)
633
            { //get a specific document
634
                Identifier id = new Identifier();
635
                id.setValue(guid);
636
                try
637
                {
638
                    InputStream data = cs.get(token, id);
639
                    IOUtils.copyLarge(data, response.getOutputStream());
640
                }
641
                catch(InvalidToken it)
642
                {
643
                    serializeException(it, out); 
644
                }
645
                catch(ServiceFailure sf)
646
                {
647
                    serializeException(sf, out); 
648
                }
649
                catch(NotAuthorized na)
650
                {
651
                    serializeException(na, out); 
652
                }
653
                catch(NotFound nf)
654
                {
655
                    serializeException(nf, out); 
656
                }
657
                catch(NotImplemented ni)
658
                {
659
                    serializeException(ni, out); 
660
                }
661
                catch(Exception e)
662
                {
663
                    System.out.println("Error with Crud.get().  " +
664
                            "If this is an 'Exception producing data' error, " +
665
                            "go to CrudService.get() for better debugging.  " +
666
                            "Here's the error: " + e.getMessage());
667
                    e.printStackTrace();
668
                    ServiceFailure sf = new ServiceFailure("1030", 
669
                            "IO Error in ResourceHandler.getObject: " + e.getMessage());
670
                    serializeException(sf, out); 
671
                }
672
            }
673
            else
674
            { //call listObjects with specified params
675
                Date startTime = null;
676
                Date endTime = null;
677
                ObjectFormat objectFormat = null;
678
                boolean replicaStatus = false;
679
                int start = 0;
680
                int count = 1000;
681
                Enumeration paramlist = request.getParameterNames();
682
                while (paramlist.hasMoreElements()) 
683
                { //parse the params and make the crud call
684
                    String name = (String) paramlist.nextElement();
685
                    String[] value = (String[])request.getParameterValues(name);
686
                    /*for(int i=0; i<value.length; i++)
687
                    {
688
                        System.out.println("name: " + name + " value: " + value[i]);
689
                    }*/
690
                    if(name.equals("startTime") && value != null)
691
                    {
692
                        try
693
                        {
694
                          //startTime = dateFormat.parse(value[0]);
695
                            startTime = parseDateAndConvertToGMT(value[0]);
696
                        }
697
                        catch(Exception e)
698
                        {  //if we can't parse it, just don't use the startTime param
699
                            System.out.println("Could not parse startTime: " + value[0]);
700
                            startTime = null;
701
                        }
702
                    }
703
                    else if(name.equals("endTime") && value != null)
704
                    {
705
                        try
706
                        {
707
                          //endTime = dateFormat.parse(value[0]);
708
                            endTime = parseDateAndConvertToGMT(value[0]);
709
                        }
710
                        catch(Exception e)
711
                        {  //if we can't parse it, just don't use the endTime param
712
                            System.out.println("Could not parse endTime: " + value[0]);
713
                            endTime = null;
714
                        }
715
                    }
716
                    else if(name.equals("objectFormat") && value != null)
717
                    {
718
                        objectFormat = ObjectFormat.convert(value[0]);
719
                    }
720
                    else if(name.equals("replicaStatus") && value != null)
721
                    {
722
                        if(value != null && 
723
                           value.length > 0 && 
724
                           (value[0].equals("true") || value[0].equals("TRUE") || value[0].equals("YES")))
725
                        {
726
                            replicaStatus = true;
727
                        }
728
                    }
729
                    else if(name.equals("start") && value != null)
730
                    {
731
                        start = new Integer(value[0]).intValue();
732
                    }
733
                    else if(name.equals("count") && value != null)
734
                    {
735
                        count = new Integer(value[0]).intValue();
736
                    }
737
                }
738
                //make the crud call
739
                /*System.out.println("token: " + token + " startTime: " + startTime +
740
                        " endtime: " + endTime + " objectFormat: " + 
741
                        objectFormat + " replicaStatus: " + replicaStatus + 
742
                        " start: " + start + " count: " + count);
743
                */
744
                ObjectList ol = cs.listObjects(token, startTime, endTime, 
745
                        objectFormat, replicaStatus, start, count);
746
                ol = cs.listObjects(token, startTime, endTime, objectFormat, replicaStatus, start, count);
747
                
748
                StringReader sr = new StringReader(ol.toString());                
749
                out = response.getOutputStream();                
750
                // Serialize and write it to the output stream
751
                
752
                try {
753
                    serializeServiceType(ObjectList.class, ol, out);
754
                } catch (JiBXException e) {
755
                    throw new ServiceFailure("1190", "Failed to serialize ObjectList: " + e.getMessage());
756
                }
757
            }
758
        } catch (BaseException e) {
759
                serializeException(e, out);
760
        } catch (IOException e) {
761
            e.printStackTrace();
762
            ServiceFailure sf = new ServiceFailure("1030", 
763
                    "IO Error in ResourceHandler.getObject: " + e.getMessage());
764
            serializeException(sf, out); 
765
        } catch(NumberFormatException ne) {
766
            InvalidRequest ir = new InvalidRequest("1030", "Invalid format for parameter: " + ne.getMessage());
767
            serializeException(ir, out);
768
        } catch (Exception e) {
769
            e.printStackTrace();
770
            ServiceFailure sf = new ServiceFailure("1030", 
771
                    "Exception " + e.getClass().getName() + " raised while handling listObjects request: " + 
772
                    e.getMessage());
773
            serializeException(sf, out);
774
        }
775
    }
776
    
777
    /**
778
     * parse a date and return it in GMT if it ends with a 'Z'
779
     * @param date
780
     * @return
781
     * @throws ParseException
782
     */
783
    private Date parseDateAndConvertToGMT(String date) throws ParseException
784
    {
785
        System.out.println("Parsing date " + date);
786
        Date d = dateFormat.parse(date);
787
        
788
        if(date.endsWith("Z"))
789
        {
790
            Calendar lTime = Calendar.getInstance();
791
            lTime.setTime(d);
792
            Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
793
            zTime.set(Calendar.MONTH, lTime.get(Calendar.MONTH));
794
            zTime.set(Calendar.DATE, lTime.get(Calendar.DATE));
795
            zTime.set(Calendar.YEAR, lTime.get(Calendar.YEAR));
796
            zTime.set(Calendar.HOUR, lTime.get(Calendar.HOUR));
797
            zTime.set(Calendar.MINUTE, lTime.get(Calendar.MINUTE));
798
            zTime.set(Calendar.SECOND, lTime.get(Calendar.SECOND));
799
            
800
            System.out.println("date parsed to " + zTime.getTime());
801
            return zTime.getTime();
802
        }
803
        
804
        System.out.println("date parsed, but not converted. returned as " + d);
805
        return d;
806
    }
807

    
808
    /**
809
     * Implements REST version of DataONE CRUD API --> getSystemMetadata
810
     * @param guid ID of data object to be read
811
     */
812
    private void getSystemMetadataObject(String guid) {
813
        CrudService cs = CrudService.getInstance();
814
        cs.setParamsFromRequest(request);
815
        AuthToken token = new AuthToken(sessionId);
816
        OutputStream out = null;
817
        try {
818
            out = response.getOutputStream();
819
            Identifier id = new Identifier();
820
            id.setValue(guid);
821
            SystemMetadata sysmeta = cs.getSystemMetadata(token, id);
822
            
823
            // Serialize and write it to the output stream
824
            try {
825
                serializeServiceType(SystemMetadata.class, sysmeta, out);
826
            } catch (JiBXException e) {
827
                throw new ServiceFailure("1190", "Failed to serialize SystemMetadata: " + e.getMessage());
828
            }
829
        } catch (BaseException e) {
830
                serializeException(e, out);
831
        } catch (IOException e) {
832
            ServiceFailure sf = new ServiceFailure("1030", 
833
                    "Error in ResourceHandler.getSystemMetadataObject: " + e.getMessage());
834
            serializeException(sf, out);
835
        } finally {
836
            IOUtils.closeQuietly(out);
837
        }
838
    }
839
    
840
    /**
841
     * serialize an object of type to out
842
     * @param type the class of the object to serialize (i.e. SystemMetadata.class)
843
     * @param object the object to serialize
844
     * @param out the stream to serialize it to
845
     * @throws JiBXException
846
     */
847
    private void serializeServiceType(Class type, Object object, OutputStream out)
848
      throws JiBXException
849
    {
850
        IBindingFactory bfact = BindingDirectory.getFactory(type);
851
        IMarshallingContext mctx = bfact.createMarshallingContext();
852
        mctx.marshalDocument(object, "UTF-8", null, out);
853
    }
854
    
855
    /**
856
     * deserialize an object of type from is
857
     * @param type the class of the object to serialize (i.e. SystemMetadata.class)
858
     * @param is the stream to deserialize from
859
     * @throws JiBXException
860
     */
861
    private Object deserializeServiceType(Class type, InputStream is)
862
      throws JiBXException
863
    {
864
        IBindingFactory bfact = BindingDirectory.getFactory(type);
865
        IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
866
        Object o = (Object) uctx.unmarshalDocument(is, null);
867
        return o;
868
    }
869
    
870
    /**
871
     * Earthgrid API > Query Service > Query Function : translates ecogrid query document to metacat query 
872
     * then calls DBQuery > createResultDocument function and then again translate resultset to ecogrid resultset
873
     * 
874
     * NOTE:
875
     *      This is the only method that uses EcoGrid classes for its implementation.  
876
     *      It does so because it takes an EcoGrid Query as input, and outputs an
877
     *      EcoGrid ResultSet document.  These documents are parsed by the auto-generated
878
     *      EcoGrid classes from axis, and so we link to them here rather than re-inventing them.
879
     *      This creates a circular dependency, because the Metacat classes are needed
880
     *      to build the EcoGrid implementation, and the EcoGrid jars are needed to build this query()
881
     *      method.  This circularity could be resolved by moving the EcoGrid classes
882
     *      to Metacat directly.  As we transition away from EcoGrid SOAP methods in
883
     *      favor of these REST interfaces, this circular dependency can be eliminated.
884
     *        
885
     * @throws Exception
886
     */
887
    private void query() throws Exception {
888
        /*  This block commented out because of the EcoGrid circular dependency.
889
         *  For now, query will not be supported until the circularity can be
890
         *  resolved, probably by moving the ecogrid query syntax transformers
891
         *  directly into the Metacat codebase.  MBJ 2010-02-03
892
         
893
        try {
894
            EcogridQueryParser parser = new EcogridQueryParser(request
895
                    .getReader());
896
            parser.parseXML();
897
            QueryType queryType = parser.getEcogridQuery();
898
            EcogridJavaToMetacatJavaQueryTransformer queryTransformer = 
899
                new EcogridJavaToMetacatJavaQueryTransformer();
900
            QuerySpecification metacatQuery = queryTransformer
901
                    .transform(queryType);
902

    
903
            DBQuery metacat = new DBQuery();
904

    
905
            boolean useXMLIndex = (new Boolean(PropertyService
906
                    .getProperty("database.usexmlindex"))).booleanValue();
907
            String xmlquery = "query"; // we don't care the query in resultset,
908
            // the query can be anything
909
            PrintWriter out = null; // we don't want metacat result, so set out null
910

    
911
            // parameter: queryspecification, user, group, usingIndexOrNot
912
            StringBuffer result = metacat.createResultDocument(xmlquery,
913
                    metacatQuery, out, username, groupNames, useXMLIndex);
914

    
915
            // create result set transfer		
916
            String saxparser = PropertyService.getProperty("xml.saxparser");
917
            MetacatResultsetParser metacatResultsetParser = new MetacatResultsetParser(
918
                    new StringReader(result.toString()), saxparser, queryType
919
                            .getNamespace().get_value());
920
            ResultsetType records = metacatResultsetParser.getEcogridResult();
921

    
922
            System.out
923
                    .println(EcogridResultsetTransformer.toXMLString(records));
924
            response.setContentType("text/xml");
925
            out = response.getWriter();
926
            out.print(EcogridResultsetTransformer.toXMLString(records));
927

    
928
        } catch (Exception e) {
929
            e.printStackTrace();
930
        }*/
931
        response.setContentType("text/xml");
932
        PrintWriter out = response.getWriter();
933
        out.print("<error>Query operation not yet supported by Metacat.</error>");
934
        out.close();
935
    }
936
    
937
    private String streamToString(InputStream is)
938
    throws IOException
939
    {
940
        byte b[] = new byte[1024];
941
        int numread = is.read(b, 0, 1024);
942
        String response = new String();
943
        while(numread != -1)
944
        {
945
            response += new String(b, 0, numread);
946
            numread = is.read(b, 0, 1024);
947
        }
948
        return response;
949
    }
950

    
951
    private InputStream stringToStream(String s)
952
    throws IOException
953
    {
954
        ByteArrayInputStream bais = new ByteArrayInputStream(s.getBytes());
955
        return bais;
956
    }
957
    
958
    
959
    /**
960
     * Earthgrid API > Put Service >Put Function : calls MetacatHandler > handleInsertOrUpdateAction 
961
     * 
962
     * @param guid ID of data object to be inserted or updated
963
     * @throws IOException
964
     */
965
    private void putObject(String guid, String action) {
966
        logMetacat.debug("Entering putObject: " + guid + "/" + action);
967
        OutputStream out = null;
968
        try {
969
            out = response.getOutputStream();
970
        } catch (IOException e1) {
971
            logMetacat.error("Could not get the output stream for writing in putObject");
972
        }
973
        try {
974
            
975
            // Read the incoming data from its Mime Multipart encoding
976
            logMetacat.debug("Disassembling MIME multipart form");
977
            InputStream object = null;
978
            InputStream sysmeta = null;
979
            
980
            //HACK: Since mmp seems to have a bug where large object parts get truncated,
981
            //parse the stream here.  This has the disavantage of putting the
982
            //stream into memory.
983
            String s = streamToString(request.getInputStream());
984
            String searchString = "Content-Disposition: attachment; filename=systemmetadata";
985
            String endString = "------=_Part";
986
            int searchStringIndex = s.indexOf(searchString);
987
            sysmeta = new ByteArrayInputStream(
988
                    s.substring(searchStringIndex +
989
                            searchString.length(), 
990
                            s.indexOf(endString, searchStringIndex)).trim().getBytes());
991
            
992
            searchString = "Content-Disposition: attachment; filename=object";
993
            searchStringIndex = s.indexOf(searchString);
994
            object = new ByteArrayInputStream(
995
                    s.substring(searchStringIndex +
996
                            searchString.length(), 
997
                            s.indexOf(endString, searchStringIndex)).trim().getBytes());
998
            
999
            /*
1000
            //This code should work, however there seems to be a bug in part.getInputStream()
1001
            //where it does not return the entire stream.  Only about the first 6kB 
1002
            //are actually returned.
1003
            MimeMultipart mmp = new MimeMultipart(new InputStreamDataSource("message", request.getInputStream()));
1004
            logMetacat.debug("MMP created.");
1005
            
1006
            //mmp.writeTo(System.out);
1007
            for (int i = 0; i < mmp.getCount(); i++) {
1008
                BodyPart part = mmp.getBodyPart(i);
1009
                String name = part.getFileName();
1010
                logMetacat.debug("Part name is: " + name);
1011
                logMetacat.debug("Part has class name: " + part.getClass().getName());
1012
                
1013
                if (name.equals("object")) {
1014
                    object = part.getInputStream();
1015
                    try
1016
                    {
1017
                        String s = streamToString(object);
1018
                        System.out.println("doc text: " + s);
1019
                        System.out.println("size of doc text is: " + s.getBytes().length);
1020
                        object = stringToStream(s);
1021
                    }
1022
                    catch(Exception e)
1023
                    {}
1024
                    System.out.println("Found object part, size is: " + part.getSize());
1025
                } else if (name.equals("systemmetadata")) {
1026
                    sysmeta = part.getInputStream();
1027
                    try
1028
                    {
1029
                      String s = streamToString(sysmeta);
1030
                      System.out.println("system metadata part: " + s);
1031
                      sysmeta = stringToStream(s);
1032
                    }
1033
                    catch(Exception e){}
1034
                    System.out.println("system metadata part, size is " + part.getSize());
1035
                    logMetacat.debug("Found sysmeta part, size is: " + part.getSize());
1036
                } else {
1037
                    throw new InvalidRequest("1000", "Request had malformed MIME part with name: " + name);
1038
                }
1039
            }*/
1040
            
1041
            if ( action.equals(FUNCTION_NAME_INSERT)) { //handle inserts
1042

    
1043
                // Check if the objectId exists
1044
                IdentifierManager im = IdentifierManager.getInstance();
1045
                if (im.identifierExists(guid)) {
1046
                    throw new IdentifierNotUnique("1000", "Identifier is already in use: " + guid);
1047
                }
1048

    
1049
                logMetacat.debug("Commence creation...");
1050
                IBindingFactory bfact =
1051
                    BindingDirectory.getFactory(SystemMetadata.class);
1052
                IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1053
                SystemMetadata m = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
1054

    
1055
                CrudService cs = CrudService.getInstance();
1056
                AuthToken token = new AuthToken(sessionId); 
1057
                cs.setParamsFromRequest(request);
1058
                Identifier id = new Identifier();
1059
                id.setValue(guid);
1060
                cs.create(token, id, object, m);
1061
                
1062
            } else if (action.equals(FUNCTION_NAME_UPDATE)) { //handle updates
1063
                IdentifierManager im = IdentifierManager.getInstance();
1064
                CrudService cs = CrudService.getInstance();
1065
                Identifier obsoletedGuid = new Identifier();
1066
                Identifier id = new Identifier();
1067
                id.setValue(guid);
1068
                AuthToken token = new AuthToken(sessionId);
1069
                
1070
                //do some checks
1071
                if(params.get("obsoletedGuid") == null)
1072
                {
1073
                    throw new InvalidRequest("1202", "obsoletedGuid must be contained in the request parameters.");
1074
                }
1075
                //get the obsoletedGuid
1076
                String[] obsGuidS = params.get("obsoletedGuid");
1077
                obsoletedGuid.setValue(obsGuidS[0]);
1078
                
1079
                if (!im.identifierExists(obsoletedGuid.getValue())) 
1080
                {
1081
                    throw new InvalidRequest("1202", "The guid you are trying to update does not exist.");
1082
                }
1083
                
1084
                
1085
                logMetacat.debug("Commence update...");
1086
                
1087
                //get the systemmetadata
1088
                IBindingFactory bfact =
1089
                        BindingDirectory.getFactory(SystemMetadata.class);
1090
                    IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1091
                    SystemMetadata m = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
1092
                
1093
                //do the update
1094
                try
1095
                {
1096
                    cs.setParamsFromRequest(request);
1097
                    Identifier rId = cs.update(token, id, object, obsoletedGuid, m);
1098
                }
1099
                catch(NotFound e)
1100
                {
1101
                    throw new InvalidRequest("1202", "The guid you are trying to update does not exist.");
1102
                }
1103
                
1104
            } else {
1105
                throw new InvalidRequest("1000", "Operation must be create or update.");
1106
            }
1107
        } catch (NotAuthorized e) {
1108
            serializeException(e, out);
1109
        } catch (InvalidToken e) {
1110
            serializeException(e, out);
1111
        } catch (ServiceFailure e) {
1112
            serializeException(e, out);
1113
        } catch (IdentifierNotUnique e) {
1114
            serializeException(e, out);
1115
        } catch (UnsupportedType e) {
1116
            serializeException(e, out);
1117
        } catch (InsufficientResources e) {
1118
            serializeException(e, out);
1119
        } catch (InvalidSystemMetadata e) {
1120
            serializeException(e, out);
1121
        } catch (NotImplemented e) {
1122
            serializeException(e, out);
1123
        } catch (InvalidRequest e) {
1124
            serializeException(e, out);
1125
        } /*catch (MessagingException e) {
1126
            ServiceFailure sf = new ServiceFailure("1000", e.getMessage());
1127
            serializeException(sf, out);
1128
        }*/ catch (IOException e) {
1129
            ServiceFailure sf = new ServiceFailure("1000", e.getMessage());
1130
            serializeException(sf, out);
1131
        } catch (JiBXException e) {
1132
            e.printStackTrace(System.out);
1133
            InvalidSystemMetadata ism = new InvalidSystemMetadata("1080", e.getMessage());
1134
            serializeException(ism, out);
1135
        }
1136
    }
1137

    
1138
    /**
1139
     * Earthgrid API > Put Service > Delete Function : calls MetacatHandler > handleDeleteAction  
1140
     * 
1141
     * @param guid ID of data object to be deleted
1142
     * @throws IOException
1143
     */
1144
    private void deleteObject(String guid) throws IOException 
1145
    {
1146
        // Look up the localId for this global identifier
1147
        IdentifierManager im = IdentifierManager.getInstance();
1148
        String localId = "";
1149
        try {
1150
            localId = im.getLocalId(guid);
1151
        } catch (McdbDocNotFoundException e) {
1152
            // TODO: Need to return the proper DataONE exception
1153
        }
1154
        
1155
        params.put("docid", new String[] { localId });
1156
        PrintWriter out = response.getWriter();
1157
        handler.handleDeleteAction(out, params, request, response, username,
1158
                groupNames);
1159
        out.close();
1160
    }
1161
    
1162
    /**
1163
     * set the access perms on a document
1164
     * @throws IOException
1165
     */
1166
    private void setaccess() throws Exception
1167
    {
1168
        try
1169
        {
1170
            String guid = params.get("guid")[0];
1171
            Identifier id = new Identifier();
1172
            id.setValue(guid);
1173
            AuthToken token = new AuthToken(sessionId);
1174
            String principal = params.get("principal")[0];
1175
            String permission = params.get("permission")[0];
1176
            String permissionType = params.get("permissionType")[0];
1177
            String permissionOrder = params.get("permissionOrder")[0];
1178
            String setSystemMetadata = params.get("setsystemmetadata")[0];
1179
            boolean ssm = false;
1180
            if(setSystemMetadata.equals("true") || setSystemMetadata.equals("TRUE") ||
1181
                    setSystemMetadata.equals("yes"))
1182
            {
1183
                ssm = true;
1184
            }
1185
            CrudService cs = CrudService.getInstance();
1186
            cs.setAccess(token, id, principal, permission, permissionType, permissionOrder, ssm);
1187
        }
1188
        catch(Exception e)
1189
        {
1190
            printError("Error setting access in ResourceHandler: " + e.getMessage(), response);
1191
            throw e;
1192
        }
1193
    }
1194

    
1195
    /**
1196
     * Earthgrid API > Authentication Service > Login Function : calls MetacatHandler > handleLoginAction
1197
     * 
1198
     * @throws IOException
1199
     */
1200
    private void login() throws IOException {
1201
        PrintWriter out = response.getWriter();
1202
        handler.handleLoginAction(out, params, request, response);
1203
        out.close();
1204
    }
1205

    
1206
    /**
1207
     * Earthgrid API > Authentication Service > Logout Function : calls MetacatHandler > handleLogoutAction
1208
     * 
1209
     * @throws IOException
1210
     */
1211
    private void logout() throws IOException {
1212
        PrintWriter out = response.getWriter();
1213
        handler.handleLogoutAction(out, params, request, response);
1214
        out.close();
1215
    }
1216

    
1217
    /**
1218
     * Prints xml response
1219
     * @param message Message to be displayed
1220
     * @param response Servlet response that xml message will be printed 
1221
     * */
1222
    private void printError(String message, HttpServletResponse response) {
1223
        try {
1224
            PrintWriter out = response.getWriter();
1225
            response.setContentType("text/xml");
1226
            out.println("<?xml version=\"1.0\"?>");
1227
            out.println("<error>");
1228
            out.println(message);
1229
            out.println("</error>");
1230
            out.close();
1231
        } catch (IOException e) {
1232
            e.printStackTrace();
1233
        }
1234
    }
1235
    
1236
    private void serializeException(BaseException e, OutputStream out) {
1237
        // TODO: Use content negotiation to determine which return format to use
1238
        response.setContentType("text/xml");
1239
        response.setStatus(e.getCode());
1240
        try {
1241
            IOUtils.write(e.serialize(BaseException.FMT_XML), out);
1242
        } catch (IOException e1) {
1243
            logMetacat.error("Error writing exception to stream. " 
1244
                    + e1.getMessage());
1245
        }
1246
    }
1247

    
1248
}
(2-2/3)