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.ByteArrayOutputStream;
26
import java.io.IOException;
27
import java.io.InputStream;
28
import java.io.OutputStream;
29
import java.io.PrintWriter;
30
import java.util.Enumeration;
31
import java.util.Hashtable;
32
import java.util.Timer;
33

    
34
import javax.mail.BodyPart;
35
import javax.mail.MessagingException;
36
import javax.mail.internet.MimeMultipart;
37
import javax.servlet.ServletContext;
38
import javax.servlet.http.HttpServletRequest;
39
import javax.servlet.http.HttpServletResponse;
40

    
41
import org.apache.commons.io.IOUtils;
42
import org.apache.log4j.Logger;
43
import org.dataone.service.exceptions.BaseException;
44
import org.dataone.service.exceptions.IdentifierNotUnique;
45
import org.dataone.service.exceptions.InsufficientResources;
46
import org.dataone.service.exceptions.InvalidRequest;
47
import org.dataone.service.exceptions.InvalidSystemMetadata;
48
import org.dataone.service.exceptions.InvalidToken;
49
import org.dataone.service.exceptions.NotAuthorized;
50
import org.dataone.service.exceptions.NotImplemented;
51
import org.dataone.service.exceptions.ServiceFailure;
52
import org.dataone.service.exceptions.UnsupportedType;
53
import org.dataone.service.exceptions.NotFound;
54
import org.dataone.service.types.AuthToken;
55
import org.dataone.service.types.Identifier;
56
import org.dataone.service.types.SystemMetadata;
57
import org.jibx.runtime.BindingDirectory;
58
import org.jibx.runtime.IBindingFactory;
59
import org.jibx.runtime.IMarshallingContext;
60
import org.jibx.runtime.IUnmarshallingContext;
61
import org.jibx.runtime.JiBXException;
62

    
63
import edu.ucsb.nceas.metacat.DBUtil;
64
import edu.ucsb.nceas.metacat.IdentifierManager;
65
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
66
import edu.ucsb.nceas.metacat.MetacatHandler;
67
import edu.ucsb.nceas.metacat.dataone.CrudService;
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

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

    
213
    private ServletContext servletContext;
214
    private Logger logMetacat;
215
    private MetacatHandler handler;
216
    private HttpServletRequest request;
217
    private HttpServletResponse response;
218
    private String username;
219
    private String password;
220
    private String sessionId;
221
    private String[] groupNames;
222

    
223
    private Hashtable<String, String[]> params;
224

    
225
    /**Initializes new instance by setting servlet context,request and response*/
226
    public ResourceHandler(ServletContext servletContext,
227
            HttpServletRequest request, HttpServletResponse response) {
228
        this.servletContext = servletContext;
229
        this.request = request;
230
        this.response = response;
231
    }
232

    
233
    /**
234
     *  copies request parameters to a hashtable which is given as argument to native metacathandler functions  
235
     */
236
    private void initParams() {
237

    
238
        String name = null;
239
        String[] value = null;
240
        Enumeration paramlist = request.getParameterNames();
241
        while (paramlist.hasMoreElements()) {
242
            name = (String) paramlist.nextElement();
243
            value = request.getParameterValues(name);
244
            System.out.println("adding param: " + name + " = " + value);
245
            params.put(name, value);
246
        }
247

    
248
    }
249

    
250
    /**
251
     * 
252
     * Load user details of metacat session from the request 
253
     * 
254
     */
255
    private void loadSessionData() {
256
        SessionData sessionData = RequestUtil.getSessionData(request);
257

    
258
        // TODO: validate the session before allowing these values to be set
259
        username = sessionData.getUserName();
260
        password = sessionData.getPassword();
261
        groupNames = sessionData.getGroupNames();
262
        sessionId = sessionData.getId();
263

    
264
        if (username == null) {
265
            username = "public";
266
        }
267
    }
268

    
269
    /**
270
     * This function is called from REST APU servlet and handles each request to the servlet 
271
     * 
272
     * @param httpVerb (GET, POST, PUT or DELETE)
273
     */
274
    public void handle(byte httpVerb) {
275
        logMetacat = Logger.getLogger(ResourceHandler.class);
276
        try {
277
            String resource = request.getServletPath();
278
            String verb = "";
279
            switch (httpVerb)
280
            {
281
                case GET:    verb = "GET";
282
                case POST:   verb = "POST";
283
                case PUT:    verb = "PUT";
284
                case DELETE: verb = "DELETE";
285
            }
286
            System.out.println("handling " + verb + " request with resource " + resource);
287
            boolean status = false;
288

    
289
            if (resource != null) {
290
                resource = request.getServletPath().substring(1);
291

    
292
                params = new Hashtable<String, String[]>();
293
                initParams();
294

    
295
                Timer timer = new Timer();
296
                handler = new MetacatHandler(timer);
297

    
298
                if (resource.equals(RESOURCE_SESSION) && 
299
                    httpVerb == POST && 
300
                    params.get(FUNCTION_KEYWORD) != null) {
301
                
302
                        if (params.get(FUNCTION_KEYWORD)[0]
303
                                .equals(FUNCTION_NAME_LOGIN)) {
304
                            login();
305
                            status = true;
306
                        } else if (params.get(FUNCTION_KEYWORD)[0]
307
                                .equals(FUNCTION_NAME_LOGOUT)) {
308
                            logout();
309
                            status = true;
310
                        }
311
                    } else if (resource.equals(RESOURCE_META)) {
312
                        loadSessionData();
313
                        String objectId = request.getPathInfo();
314
                        if (objectId != null && objectId.length() > 1) 
315
                        {
316
                            objectId = request.getPathInfo().substring(1);
317
                        }
318
                        getSystemMetadataObject(objectId);
319
                        status = true;
320
                            
321
                    } else if (resource.equals(RESOURCE_OBJECTS)) {
322
                    logMetacat.debug("D1 Rest: Starting resource processing...");
323
                    loadSessionData();
324

    
325
                    String objectId = request.getPathInfo();
326
                    if (objectId != null && objectId.length() > 1) 
327
                    {
328
                        objectId = request.getPathInfo().substring(1);
329
                    }
330
                    
331
                    logMetacat.debug("verb:" + httpVerb);
332

    
333
                    if (httpVerb == GET) {
334
                        getObject(objectId);
335
                        status = true;
336
                    } else if (httpVerb == POST) {
337
                        putObject(objectId, FUNCTION_NAME_INSERT);
338
                        status = true;
339
                    } else if (httpVerb == PUT) {
340
                        putObject(objectId, FUNCTION_NAME_UPDATE);
341
                        status = true;
342
                    } else if (httpVerb == DELETE) {
343
                        deleteObject(objectId);
344
                        status = true;
345
                    }
346

    
347
                } else if (resource.equals(RESOURCE_IDENTIFIER)) {
348

    
349
                    String identifierId = request.getPathInfo();
350
                    if (identifierId != null && identifierId.length() > 1)
351
                        identifierId = request.getPathInfo().substring(1); //trim the slash
352

    
353
                    if (httpVerb == GET) {
354
                        String op = params.get(FUNCTION_KEYWORD)[0];
355
                        if (op.equals(FUNCTION_NAME_ISREGISTERED)) {
356
                            isRegistered(identifierId);
357
                            status = true;
358
                        } else if (op.equals(FUNCTION_NAME_GETALLDOCS)) {
359
                            getAllDocIds();
360
                            status = true;
361
                        } else if (op.equals(FUNCTION_NAME_GETNEXTREV)) {
362
                            getNextRevision(identifierId);
363
                            status = true;
364
                        } else if (op.equals(FUNCTION_NAME_GETNEXTOBJ)) {
365
                            getNextObject();
366
                            status = true;
367
                        }
368

    
369
                    } else if (httpVerb == PUT) {
370
                        //Earthgrid API > Identifier Service > addLSID Function 
371
                        printError(
372
                                "This method is not supported by metacat.  To "
373
                                        + "add a new LSID, add a document to metacat.",
374
                                response);
375
                        status = true;
376
                    }
377

    
378
                }
379
                if (!status)
380
                    printError("Incorrect parameters!", response);
381
            } else {
382
                printError("Incorrect resource!", response);
383
            }
384
        } catch (Exception e) {
385
            logMetacat.error(e.getMessage());
386
            e.printStackTrace();
387
        }
388
    }
389

    
390
    /**
391
     *  Earthgrid API > Identifier Service > isRegistered Function : calls MetacatHandler > handleIdIsRegisteredAction
392
     * @param guid
393
     * @throws IOException
394
     */
395
    private void isRegistered(String guid) throws IOException
396
    {
397
        
398
        // Look up the localId for this guid
399
        IdentifierManager im = IdentifierManager.getInstance();
400
        String localId = "";
401
        try {
402
            localId = im.getLocalId(guid);
403
        } catch (McdbDocNotFoundException e) {
404
            // TODO: Need to return the proper DataONE exception
405
        }
406
        
407
        params.put("docid", new String[] { localId });
408
        PrintWriter out = response.getWriter();
409
        handler.handleIdIsRegisteredAction(out, params, response);
410
        out.close();
411
    }
412

    
413
    /**
414
     * Earthgrid API > Identifier Service > getAllDocIds Function : calls MetacatHandler > handleGetAllDocidsAction
415
     * @throws IOException
416
     */
417
    private void getAllDocIds() throws IOException {
418
        PrintWriter out = response.getWriter();
419
        handler.handleGetAllDocidsAction(out, params, response);
420
        out.close();
421
    }
422

    
423
    /**
424
     * Earthgrid API > Identifier Service > getNextRevision Function : calls MetacatHandler > handleGetRevisionAndDocTypeAction
425
     * @param guid
426
     * @throws IOException
427
     */
428
    private void getNextRevision(String guid) throws IOException 
429
    {
430
        params.put("docid", new String[] { guid });
431
        PrintWriter out = response.getWriter();
432
        //handler.handleGetRevisionAndDocTypeAction(out, params);
433

    
434
        try {
435
            // Make sure there is a docid
436
            if (guid == null || guid.equals("")) {
437
                throw new Exception("User didn't specify docid!");
438
            }
439

    
440
            // Look up the localId for this guid
441
            IdentifierManager im = IdentifierManager.getInstance();
442
            String localId = "";
443
            try {
444
                localId = im.getLocalId(guid);
445
            } catch (McdbDocNotFoundException e) {
446
                // TODO: Need to return the proper DataONE exception
447
            }
448
           
449
            // Create a DBUtil object
450
            DBUtil dbutil = new DBUtil();
451
            // Get a rev and doctype
452
            String revAndDocType = dbutil
453
                    .getCurrentRevisionAndDocTypeForGivenDocument(localId);
454
            int revision = Integer.parseInt(revAndDocType.split(";")[0]) + 1;
455

    
456
            out.println("<?xml version=\"1.0\"?>");
457
            out.print("<next-revision>");
458
            out.print(revision);
459
            out.print("</next-revision>");
460

    
461
        } catch (Exception e) {
462
            // Handle exception
463
            out.println("<?xml version=\"1.0\"?>");
464
            out.println("<error>");
465
            out.println(e.getMessage());
466
            out.println("</error>");
467
        }
468

    
469
        out.close();
470
    }
471

    
472
    /**
473
     * Earthgrid API > Identifier Service > getNextObject Function : calls MetacatHandler > handleGetMaxDocidAction
474
     * @throws IOException
475
     */
476
    private void getNextObject() throws IOException {
477
        PrintWriter out = response.getWriter();
478
        handler.handleGetMaxDocidAction(out, params, response);
479
        out.close();
480
    }
481

    
482
    /**
483
     * Implements REST version of DataONE CRUD API --> get
484
     * @param guid ID of data object to be read
485
     */
486
    private void getObject(String guid) {
487
      //hack...fix this
488
        //CrudService cs = new CrudService(servletContext, request, response);
489
        CrudService cs = CrudService.getInstance();
490
        cs.setParamsFromRequest(request);
491
        AuthToken token = null;
492
        OutputStream out = null;
493
        try {
494
            out = response.getOutputStream();
495
            Identifier id = new Identifier();
496
            id.setValue(guid);
497
            InputStream data = cs.get(token, id);
498
            IOUtils.copyLarge(data, response.getOutputStream());
499
        } catch (BaseException e) {
500
                serializeException(e, out);
501
        } catch (IOException e) {
502
            ServiceFailure sf = new ServiceFailure(1030, e.getMessage());
503
            serializeException(sf, out);
504
        }
505
    }
506

    
507
    /**
508
     * Implements REST version of DataONE CRUD API --> getSystemMetadata
509
     * @param guid ID of data object to be read
510
     */
511
    private void getSystemMetadataObject(String guid) {
512
        CrudService cs = CrudService.getInstance();
513
        cs.setParamsFromRequest(request);
514
        AuthToken token = null;
515
        OutputStream out = null;
516
        try {
517
            out = response.getOutputStream();
518
            Identifier id = new Identifier();
519
            id.setValue(guid);
520
            SystemMetadata sysmeta = cs.getSystemMetadata(token, id);
521
            
522
            // Serialize and write it to the output stream
523
            try {
524
                IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
525
                IMarshallingContext mctx = bfact.createMarshallingContext();
526
                mctx.marshalDocument(sysmeta, "UTF-8", null, out);
527
            } catch (JiBXException e) {
528
                throw new ServiceFailure(1190, "Failed to serialize SystemMetadata: " + e.getMessage());
529
            }
530
        } catch (BaseException e) {
531
                serializeException(e, out);
532
        } catch (IOException e) {
533
            ServiceFailure sf = new ServiceFailure(1030, e.getMessage());
534
            serializeException(sf, out);
535
        } finally {
536
            IOUtils.closeQuietly(out);
537
        }
538
    }
539
    
540
    /**
541
     * Earthgrid API > Query Service > Query Function : translates ecogrid query document to metacat query 
542
     * then calls DBQuery > createResultDocument function and then again translate resultset to ecogrid resultset
543
     * 
544
     * NOTE:
545
     *      This is the only method that uses EcoGrid classes for its implementation.  
546
     *      It does so because it takes an EcoGrid Query as input, and outputs an
547
     *      EcoGrid ResultSet document.  These documents are parsed by the auto-generated
548
     *      EcoGrid classes from axis, and so we link to them here rather than re-inventing them.
549
     *      This creates a circular dependency, because the Metacat classes are needed
550
     *      to build the EcoGrid implementation, and the EcoGrid jars are needed to build this query()
551
     *      method.  This circularity could be resolved by moving the EcoGrid classes
552
     *      to Metacat directly.  As we transition away from EcoGrid SOAP methods in
553
     *      favor of these REST interfaces, this circular dependency can be eliminated.
554
     *        
555
     * @throws Exception
556
     */
557
    private void query() throws Exception {
558
        /*  This block commented out because of the EcoGrid circular dependency.
559
         *  For now, query will not be supported until the circularity can be
560
         *  resolved, probably by moving the ecogrid query syntax transformers
561
         *  directly into the Metacat codebase.  MBJ 2010-02-03
562
         
563
        try {
564
            EcogridQueryParser parser = new EcogridQueryParser(request
565
                    .getReader());
566
            parser.parseXML();
567
            QueryType queryType = parser.getEcogridQuery();
568
            EcogridJavaToMetacatJavaQueryTransformer queryTransformer = 
569
                new EcogridJavaToMetacatJavaQueryTransformer();
570
            QuerySpecification metacatQuery = queryTransformer
571
                    .transform(queryType);
572

    
573
            DBQuery metacat = new DBQuery();
574

    
575
            boolean useXMLIndex = (new Boolean(PropertyService
576
                    .getProperty("database.usexmlindex"))).booleanValue();
577
            String xmlquery = "query"; // we don't care the query in resultset,
578
            // the query can be anything
579
            PrintWriter out = null; // we don't want metacat result, so set out null
580

    
581
            // parameter: queryspecification, user, group, usingIndexOrNot
582
            StringBuffer result = metacat.createResultDocument(xmlquery,
583
                    metacatQuery, out, username, groupNames, useXMLIndex);
584

    
585
            // create result set transfer		
586
            String saxparser = PropertyService.getProperty("xml.saxparser");
587
            MetacatResultsetParser metacatResultsetParser = new MetacatResultsetParser(
588
                    new StringReader(result.toString()), saxparser, queryType
589
                            .getNamespace().get_value());
590
            ResultsetType records = metacatResultsetParser.getEcogridResult();
591

    
592
            System.out
593
                    .println(EcogridResultsetTransformer.toXMLString(records));
594
            response.setContentType("text/xml");
595
            out = response.getWriter();
596
            out.print(EcogridResultsetTransformer.toXMLString(records));
597

    
598
        } catch (Exception e) {
599
            e.printStackTrace();
600
        }*/
601
        response.setContentType("text/xml");
602
        PrintWriter out = response.getWriter();
603
        out.print("<error>Query operation not yet supported by Metacat.</error>");
604
        out.close();
605
    }
606
    
607
    /**
608
     * Earthgrid API > Put Service >Put Function : calls MetacatHandler > handleInsertOrUpdateAction 
609
     * 
610
     * @param guid ID of data object to be inserted or updated
611
     * @throws IOException
612
     */
613
    private void putObject(String guid, String action) {
614
        logMetacat.debug("Entering putObject: " + guid + "/" + action);
615
        
616
        // TODO: This function lacks proper handling of authz and authn, so it
617
        // seems that anyone can insert or update; interacts with 
618
        // loadSessionData(), which doesn't validate the session
619
        
620
        // Get an output stream for handling errors; this should really be passed in as
621
        // a parameter
622
        OutputStream out = null;
623
        try {
624
            out = response.getOutputStream();
625
        } catch (IOException e1) {
626
            logMetacat.error("Could not get the output stream for writing in putObject");
627
        }
628
        try {
629
            
630
            // Read the incoming data from its Mime Multipart encoding
631
            logMetacat.debug("Disassembling MIME multipart form");
632
            InputStream object = null;
633
            InputStream sysmeta = null;
634
            MimeMultipart mmp = new MimeMultipart(new InputStreamDataSource("message", request.getInputStream()));
635
            logMetacat.debug("MMP created.");
636
            mmp.writeTo(System.out);
637
            for (int i = 0; i < mmp.getCount(); i++) {
638
                BodyPart part = mmp.getBodyPart(i);
639
                String name = part.getFileName();
640
                logMetacat.debug("Part name is: " + name);
641
                logMetacat.debug("Part has class name: " + part.getClass().getName());
642
                if (name.equals("object")) {
643
                    object = part.getInputStream();
644
                    logMetacat.debug("Found object part, size is: " + part.getSize());
645
                } else if (name.equals("systemmetadata")) {
646
                    sysmeta = part.getInputStream();
647
                    logMetacat.debug("Found sysmeta part, size is: " + part.getSize());
648
                } else {
649
                    throw new InvalidRequest(1000, "Request had malformed MIME part with name: " + name);
650
                }
651
            }
652
            
653
            if ( action.equals(FUNCTION_NAME_INSERT)) { //handle inserts
654

    
655
                // Check if the objectId exists
656
                IdentifierManager im = IdentifierManager.getInstance();
657
                if (im.identifierExists(guid)) {
658
                    throw new IdentifierNotUnique(1000, "Identifier is already in use: " + guid);
659
                }
660

    
661
                // TODO: access control -- should be in CrudService et al. I think
662
                //if (username != null && !username.equals("public")) {
663
                if (username != null) {
664
                    logMetacat.debug("Commence creation...");
665
                    AuthToken token = null;
666
                    IBindingFactory bfact =
667
                        BindingDirectory.getFactory(SystemMetadata.class);
668
                    IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
669
                    SystemMetadata m = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
670
                    
671
                    CrudService cs = CrudService.getInstance();
672
                    cs.setParamsFromRequest(request);
673
                    Identifier id = new Identifier();
674
                    id.setValue(guid);
675
                    cs.create(token, id, object, m);
676

    
677
                } else {
678
                    logMetacat.debug("Unauthorized to create.");
679
                    throw new NotAuthorized(1000, "Permission denied for user " + username);
680
                }
681
            } else if (action.equals(FUNCTION_NAME_UPDATE)) { //handle updates
682
                IdentifierManager im = IdentifierManager.getInstance();
683
                CrudService cs = CrudService.getInstance();
684
                Identifier obsoletedGuid = new Identifier();
685
                Identifier id = new Identifier();
686
                id.setValue(guid);
687
                AuthToken token = null;
688
                
689
                //do some checks
690
                if(params.get("obsoletedGuid") == null)
691
                {
692
                    throw new InvalidRequest(1202, "obsoletedGuid must be contained in the request parameters.");
693
                }
694
                //get the obsoletedGuid
695
                String[] obsGuidS = params.get("obsoletedGuid");
696
                obsoletedGuid.setValue(obsGuidS[0]);
697
                
698
                if (!im.identifierExists(obsoletedGuid.getValue())) 
699
                {
700
                    throw new InvalidRequest(1202, "The guid you are trying to update does not exist.");
701
                }
702
                
703
                
704
                logMetacat.debug("Commence update...");
705
                
706
                //get the systemmetadata
707
                IBindingFactory bfact =
708
                        BindingDirectory.getFactory(SystemMetadata.class);
709
                    IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
710
                    SystemMetadata m = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
711
                
712
                //do the update
713
                try
714
                {
715
                    cs.setParamsFromRequest(request);
716
                    Identifier rId = cs.update(token, id, object, obsoletedGuid, m);
717
                }
718
                catch(NotFound e)
719
                {
720
                    throw new InvalidRequest(1202, "The guid you are trying to update does not exist.");
721
                }
722
                
723
            } else {
724
                throw new InvalidRequest(1000, "Operation must be create or update.");
725
            }
726
        } catch (NotAuthorized e) {
727
            serializeException(e, out);
728
        } catch (InvalidToken e) {
729
            serializeException(e, out);
730
        } catch (ServiceFailure e) {
731
            serializeException(e, out);
732
        } catch (IdentifierNotUnique e) {
733
            serializeException(e, out);
734
        } catch (UnsupportedType e) {
735
            serializeException(e, out);
736
        } catch (InsufficientResources e) {
737
            serializeException(e, out);
738
        } catch (InvalidSystemMetadata e) {
739
            serializeException(e, out);
740
        } catch (NotImplemented e) {
741
            serializeException(e, out);
742
        } catch (InvalidRequest e) {
743
            serializeException(e, out);
744
        } catch (MessagingException e) {
745
            ServiceFailure sf = new ServiceFailure(1000, e.getMessage());
746
            serializeException(sf, out);
747
        } catch (IOException e) {
748
            ServiceFailure sf = new ServiceFailure(1000, e.getMessage());
749
            serializeException(sf, out);
750
        } catch (JiBXException e) {
751
            e.printStackTrace(System.out);
752
            InvalidSystemMetadata ism = new InvalidSystemMetadata(1080, e.getMessage());
753
            serializeException(ism, out);
754
        }
755
    }
756

    
757
    /**
758
     * Earthgrid API > Put Service > Delete Function : calls MetacatHandler > handleDeleteAction  
759
     * 
760
     * @param guid ID of data object to be deleted
761
     * @throws IOException
762
     */
763
    private void deleteObject(String guid) throws IOException 
764
    {
765
        // Look up the localId for this global identifier
766
        IdentifierManager im = IdentifierManager.getInstance();
767
        String localId = "";
768
        try {
769
            localId = im.getLocalId(guid);
770
        } catch (McdbDocNotFoundException e) {
771
            // TODO: Need to return the proper DataONE exception
772
        }
773
        
774
        params.put("docid", new String[] { localId });
775
        PrintWriter out = response.getWriter();
776
        handler.handleDeleteAction(out, params, request, response, username,
777
                groupNames);
778
        out.close();
779
    }
780

    
781
    /**
782
     * Earthgrid API > Authentication Service > Login Function : calls MetacatHandler > handleLoginAction
783
     * 
784
     * @throws IOException
785
     */
786
    private void login() throws IOException {
787
        PrintWriter out = response.getWriter();
788
        handler.handleLoginAction(out, params, request, response);
789
        out.close();
790
    }
791

    
792
    /**
793
     * Earthgrid API > Authentication Service > Logout Function : calls MetacatHandler > handleLogoutAction
794
     * 
795
     * @throws IOException
796
     */
797
    private void logout() throws IOException {
798
        PrintWriter out = response.getWriter();
799
        handler.handleLogoutAction(out, params, request, response);
800
        out.close();
801
    }
802

    
803
    /**
804
     * Prints xml response
805
     * @param message Message to be displayed
806
     * @param response Servlet response that xml message will be printed 
807
     * */
808
    private void printError(String message, HttpServletResponse response) {
809
        try {
810
            PrintWriter out = response.getWriter();
811
            response.setContentType("text/xml");
812
            out.println("<?xml version=\"1.0\"?>");
813
            out.println("<error>");
814
            out.println(message);
815
            out.println("</error>");
816
            out.close();
817
        } catch (IOException e) {
818
            e.printStackTrace();
819
        }
820
    }
821

    
822
    private void serializeException(BaseException e, OutputStream out) {
823
        // TODO: Use content negotiation to determine which return format to use
824
        response.setContentType("text/xml");
825
        response.setStatus(e.getCode());
826
        try {
827
            IOUtils.write(e.serialize(BaseException.FMT_XML), out);
828
        } catch (IOException e1) {
829
            logMetacat.error("Error writing exception to stream. " 
830
                    + e1.getMessage());
831
        }
832
    }
833

    
834
}
(2-2/3)