Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2011 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.net.URL;
27
import java.util.*;
28

    
29
import javax.mail.BodyPart;
30
import javax.mail.MessagingException;
31
import javax.mail.internet.MimeMultipart;
32
import javax.servlet.ServletContext;
33
import javax.servlet.http.HttpServletRequest;
34
import javax.servlet.http.HttpServletResponse;
35
import java.text.DateFormat;
36
import java.text.ParseException;
37
import java.text.ParsePosition;
38
import java.text.SimpleDateFormat;
39

    
40

    
41
import org.apache.commons.io.IOUtils;
42
import org.apache.log4j.Logger;
43
import org.apache.maven.artifact.ant.shaded.IOUtil;
44
import org.dataone.client.MNode;
45
import org.dataone.mimemultipart.MultipartRequest;
46
import org.dataone.mimemultipart.MultipartRequestResolver;
47
import org.dataone.service.NodeListParser;
48
import org.dataone.service.exceptions.BaseException;
49
import org.dataone.service.exceptions.IdentifierNotUnique;
50
import org.dataone.service.exceptions.InsufficientResources;
51
import org.dataone.service.exceptions.InvalidRequest;
52
import org.dataone.service.exceptions.InvalidSystemMetadata;
53
import org.dataone.service.exceptions.InvalidToken;
54
import org.dataone.service.exceptions.NotAuthorized;
55
import org.dataone.service.exceptions.NotImplemented;
56
import org.dataone.service.exceptions.ServiceFailure;
57
import org.dataone.service.exceptions.UnsupportedType;
58
import org.dataone.service.exceptions.NotFound;
59
import org.dataone.service.types.*;
60
import org.dataone.service.types.util.ServiceTypeUtil;
61
import org.jibx.runtime.BindingDirectory;
62
import org.jibx.runtime.IBindingFactory;
63
import org.jibx.runtime.IMarshallingContext;
64
import org.jibx.runtime.IUnmarshallingContext;
65
import org.jibx.runtime.JiBXException;
66

    
67
import edu.ucsb.nceas.metacat.DBUtil;
68
import edu.ucsb.nceas.metacat.IdentifierManager;
69
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
70
import edu.ucsb.nceas.metacat.MetaCatServlet;
71
import edu.ucsb.nceas.metacat.MetacatHandler;
72
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
73
import edu.ucsb.nceas.metacat.dataone.CrudService;
74
import edu.ucsb.nceas.metacat.dataone.HealthService;
75
import edu.ucsb.nceas.metacat.properties.PropertyService;
76
import edu.ucsb.nceas.metacat.service.SessionService;
77
import edu.ucsb.nceas.metacat.util.RequestUtil;
78
import edu.ucsb.nceas.metacat.util.SessionData;
79
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
80

    
81
import org.dataone.service.streaming.util.StreamUtil;
82

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

    
161
 * </ul>
162
 * </li>
163
 * 
164
 * <li>
165
 * <h3>EarthGrid Identifier Service</h3><br/>
166
 * 
167
 * <ul>
168
 * <li><h3>isRegistered: </h3>      <br/>
169
 * <b>REST URL:</b> <code>GET, [context-root]/identifier/[doc-id]?op=isregistered</code>   <br/>
170
 * <b>Returns:</b> message in XML format<br/><br/>
171
 * </li>
172

    
173
 * <li><h3>getAllDocIds:</h3>       <br/>       
174
 * <b>REST URL:</b> <code>GET, [context-root]/identifier?op=getalldocids</code>   <br/>
175
 * <b>Returns:</b> document id list in XML format<br/><br/>
176
 * </li>
177
 * 
178
 * <li><h3>addLSID Function:</h3> 
179
 * Metacat does not support this function       <br/>
180
 * <b>REST URL:</b> <code>PUT, [context-root]/identifier/[doc-id]</code>   <br/>
181
 * <b>Returns:</b> error message in XML format<br/><br/>
182
 * </li>
183
 * 
184
 * <li><h3>getNextRevision:</h3>        <br/>
185
 * <b>REST URL:</b> <code>GET, [context-root]/identifier/[doc-id]?op=getnextrevision</code>   <br/>
186
 * <b>Returns:</b> message in XML format<br/><br/>
187
 * </li>
188
 * 
189
 * <li><h3>getNextObject:</h3>      <br/>
190
 * <b>REST URL:</b> <code>GET, [context-root]/identifier?op=getnextobject&scope=[scope]</code>   <br/>
191
 * <b>Returns:</b> message in XML format<br/><br/>
192
 * </li>
193
 * 
194
 * </li>
195
 * </ul>
196
 * 
197
 */
198
public class ResourceHandler {
199

    
200
    /**HTTP Verb GET*/
201
    public static final byte GET = 1;
202
    /**HTTP Verb POST*/
203
    public static final byte POST = 2;
204
    /**HTTP Verb PUT*/
205
    public static final byte PUT = 3;
206
    /**HTTP Verb DELETE*/
207
    public static final byte DELETE = 4;
208
    /**HTTP Verb HEAD*/
209
    public static final byte HEAD = 5;
210

    
211
    /*
212
     * API Resources
213
     */
214
    private static final String RESOURCE_OBJECTS = "object";
215
    private static final String RESOURCE_META = "meta";
216
    private static final String RESOURCE_SESSION = "session";
217
    private static final String RESOURCE_IDENTIFIER = "identifier";
218
    private static final String RESOURCE_LOG = "log";
219
    private static final String RESOURCE_CHECKSUM = "checksum";
220
    private static final String RESOURCE_MONITOR = "monitor";
221
    private static final String RESOURCE_BASE_URL = "d1";
222
    private static final String RESOURCE_REPLICATE = "replicate";
223

    
224
    /*
225
     * API Functions used as URL parameters
226
     */
227
    private static final String FUNCTION_KEYWORD = "op";
228
    private static final String FUNCTION_NAME_LOGIN = "login";
229
    private static final String FUNCTION_NAME_LOGOUT = "logout";
230
    private static final String FUNCTION_NAME_SET_ACCESS = "setaccess";
231
    private static final String FUNCTION_NAME_ISREGISTERED = "isregistered";
232
    private static final String FUNCTION_NAME_GETALLDOCS = "getalldocids";
233
    private static final String FUNCTION_NAME_GETNEXTREV = "getnextrevision";
234
    private static final String FUNCTION_NAME_GETNEXTOBJ = "getnextobject";
235
    private static final String FUNCTION_NAME_INSERT = "insert";
236
    private static final String FUNCTION_NAME_UPDATE = "update";
237
    private static final String FUNCTION_NAME_GENERATE_MISSING_SYSTEM_METADATA = "generatemissingsystemmetadata";
238

    
239
    private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
240
    
241
    private ServletContext servletContext;
242
    private Logger logMetacat;
243
    private MetacatHandler handler;
244
    private HttpServletRequest request;
245
    private HttpServletResponse response;
246
    private String username;
247
    private String password;
248
    private String sessionId;
249
    private String[] groupNames;
250

    
251
    private Hashtable<String, String[]> params;
252

    
253
    /**Initializes new instance by setting servlet context,request and response*/
254
    public ResourceHandler(ServletContext servletContext,
255
            HttpServletRequest request, HttpServletResponse response) {
256
        this.servletContext = servletContext;
257
        this.request = request;
258
        this.response = response;
259
    }
260

    
261
    /**
262
     * This function is called from REST APU servlet and handles each request to the servlet 
263
     * 
264
     * @param httpVerb (GET, POST, PUT or DELETE)
265
     */
266
    public void handle(byte httpVerb) {
267
        logMetacat = Logger.getLogger(ResourceHandler.class);
268
        try {
269
            String resource = request.getServletPath();
270
            if(resource.endsWith("d1/") || resource.endsWith("d1"))
271
            {
272
                resource = RESOURCE_BASE_URL;
273
            }
274
            else
275
            {
276
                //substring off the /d1/
277
                resource = resource.substring(resource.indexOf("d1/") + 3, resource.length());
278
                resource = resource.trim();
279
            }
280
            
281
            String verb = "";
282
            
283
            System.out.println("handling verb " + httpVerb + " request with resource '" + resource + "'");
284
            System.out.println("resource: '" + resource + "'");
285
            System.out.println("resource_monitor: '" + RESOURCE_MONITOR + "'");
286
            boolean status = false;
287
            loadSessionData();
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_BASE_URL)) {
299
                    //node registry response
300
                    System.out.println("Using resource 'd1' (node registry response)");
301
                    createNodeResponse();
302
                    status = true;
303
                    
304
                } else if (resource.equals(RESOURCE_SESSION) && 
305
                        httpVerb == POST && 
306
                        params.get(FUNCTION_KEYWORD) != null) {
307
                    System.out.println("Using resource 'session'");
308
                    //System.out.println("function_keyword: " + params.get(FUNCTION_KEYWORD)[0]);
309
                    if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_LOGIN)) {
310
                        login();
311
                        status = true;
312
                    } else if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_LOGOUT)) {
313
                        logout();
314
                        status = true;
315
                    } else if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_SET_ACCESS)) {
316
                        setaccess();
317
                        status = true;
318
                        System.out.println("done setting access");
319
                    }
320
                } else if (resource.equals(RESOURCE_META)) {
321
                    System.out.println("Using resource 'meta'");
322
                    if(params != null && params.get(FUNCTION_KEYWORD) != null &&
323
                            params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_GENERATE_MISSING_SYSTEM_METADATA))
324
                    { //generate system metadata for any object that is
325
                        //a) not system metadata itself
326
                        //b) does not already have a system metadata id in the systemmetadata table
327
                        //c) not a BIN object (data)
328
                        //TODO: check if we need this anymore.  Might be superceded
329
                        //by MetacatPopulator
330
                        generateMissingSystemMetadata();
331
                        status = true;
332
                    }
333
                    else
334
                    {
335
                        String objectId = request.getPathInfo();
336
                        if (objectId != null && objectId.length() > 1) 
337
                        {
338
                            objectId = request.getPathInfo().substring(1);
339
                        }
340
                        getSystemMetadataObject(objectId);
341
                        status = true;
342
                    }
343

    
344
                } else if (resource.equals(RESOURCE_OBJECTS)) {
345
                    System.out.println("Using resource 'object'");
346
                    logMetacat.debug("D1 Rest: Starting resource processing...");
347
                    loadSessionData();
348

    
349
                    String objectId = request.getPathInfo();
350
                    if (objectId != null && objectId.length() > 1) 
351
                    {
352
                        objectId = request.getPathInfo().substring(1);
353
                    }
354
                    else
355
                    {
356
                        objectId = null;
357
                    }
358
                    
359
                    System.out.println("objectId in ReasourceHandler.handle: " + objectId);
360

    
361
                    logMetacat.debug("verb:" + httpVerb);
362

    
363
                    if (httpVerb == GET) {
364
                        getObject(objectId);
365
                        status = true;
366
                    } else if (httpVerb == POST) {
367
                        putObject(objectId, FUNCTION_NAME_INSERT);
368
                        status = true;
369
                    } else if (httpVerb == PUT) {
370
                        putObject(objectId, FUNCTION_NAME_UPDATE);
371
                        status = true;
372
                    } else if (httpVerb == DELETE) {
373
                        deleteObject(objectId);
374
                        status = true;
375
                    } else if (httpVerb == HEAD) {
376
                        describeObject(objectId);
377
                        status = true;
378
                    }
379
                    
380

    
381
                } else if (resource.equals(RESOURCE_IDENTIFIER)) {
382
                    System.out.println("Using resource 'identifier'");
383
                    String identifierId = request.getPathInfo();
384
                    if (identifierId != null && identifierId.length() > 1)
385
                        identifierId = request.getPathInfo().substring(1); //trim the slash
386

    
387
                    if (httpVerb == GET) {
388
                        String op = params.get(FUNCTION_KEYWORD)[0];
389
                        if (op.equals(FUNCTION_NAME_ISREGISTERED)) {
390
                            isRegistered(identifierId);
391
                            status = true;
392
                        } else if (op.equals(FUNCTION_NAME_GETALLDOCS)) {
393
                            getAllDocIds();
394
                            status = true;
395
                        } else if (op.equals(FUNCTION_NAME_GETNEXTREV)) {
396
                            getNextRevision(identifierId);
397
                            status = true;
398
                        } else if (op.equals(FUNCTION_NAME_GETNEXTOBJ)) {
399
                            getNextObject();
400
                            status = true;
401
                        } 
402

    
403
                    } else if (httpVerb == PUT) {
404
                        //Earthgrid API > Identifier Service > addLSID Function 
405
                        response.setStatus(501);
406
                        printError(
407
                                "This method is not supported by metacat.  To "
408
                                + "add a new LSID, add a document to metacat.",
409
                                response);
410
                        status = true;
411
                    }
412

    
413
                } else if (resource.equals(RESOURCE_LOG)) {
414
                    System.out.println("Using resource 'log'");
415
                    //handle log events
416
                    if(httpVerb == GET)
417
                    {
418
                        getLog();
419
                        status = true;
420
                    }
421
                    else
422
                    {
423
                        //change to D1 spec for specifying which http methods are allowed for a resource
424
                        response.setStatus(501);
425
                        printError("POST, PUT, DELETE is not supported for logs.", response);
426
                        status = true;
427
                    }
428

    
429
                } else if(resource.equals(RESOURCE_CHECKSUM)) {
430
                    System.out.println("Using resource 'checksum'");
431
                    //handle checksum requests
432
                    if(httpVerb == GET)
433
                    {
434
                        String checksumAlgorithm = "MD5";
435
                    
436
                        String guid = request.getPathInfo();
437
                        if (guid != null && guid.length() > 1)
438
                            guid = request.getPathInfo().substring(1); //trim the slash
439
                        
440
                        Identifier guidid = new Identifier();
441
                        guidid.setValue(guid);
442
                        AuthToken token = new AuthToken(sessionId);
443
                        try
444
                        {
445
                            checksumAlgorithm = params.get("checksumAlgorithm")[0];
446
                        }
447
                        catch(Exception e)
448
                        {
449
                            //do nothing.  default to MD5
450
                        }
451
                        System.out.println("getting checksum for object " + guid +
452
                                " with algorithm " + checksumAlgorithm);
453
                        try
454
                        {
455
                            Checksum c = CrudService.getInstance().getChecksum(token, guidid, checksumAlgorithm);
456
                            System.out.println("got checksum " + c.getValue());
457
                            response.setStatus(200);
458
                            System.out.println("serializing response");
459
                            serializeServiceType(Checksum.class, c, response.getOutputStream());
460
                            System.out.println("done serializing response.");
461
                        }
462
                        catch(NotAuthorized na)
463
                        {
464
                            na.setDetail_code("1400");
465
                            serializeException(na, response.getOutputStream());
466
                        }
467
                        catch(NotFound nf)
468
                        {
469
                            nf.setDetail_code("1420");
470
                            serializeException(nf, response.getOutputStream());
471
                        }
472
                        catch(InvalidRequest ir)
473
                        {
474
                            ir.setDetail_code("1402");
475
                            serializeException(ir, response.getOutputStream());
476
                        }
477
                        catch(ServiceFailure sf)
478
                        {
479
                            sf.setDetail_code("1410");
480
                            serializeException(sf, response.getOutputStream());
481
                        }
482
                        catch(InvalidToken it)
483
                        {
484
                            it.setDetail_code("1430");
485
                            serializeException(it, response.getOutputStream());
486
                        }
487
                        status = true;
488
                    }
489
                } else if(resource.equals(RESOURCE_MONITOR)) {
490
                    //health monitoring calls
491
                    System.out.println("processing monitor request");
492
                    String pathInfo = request.getPathInfo();
493
                    if(httpVerb == GET)
494
                    {
495
                        System.out.println("verb is GET");
496
                        System.out.println("pathInfo is " + pathInfo);
497
                        pathInfo = pathInfo.substring(1);
498
                        HealthService hs = new HealthService(request, response);
499
                        if (pathInfo.toLowerCase().equals("ping")) {
500
                            System.out.println("processing ping request");
501
                            hs.ping();
502
                        } else if (pathInfo.toLowerCase().equals("status")) {
503
                            System.out.println("processing status request");
504
                            hs.getStatus();
505
                        } else if (pathInfo.toLowerCase().equals("object")) {
506
                            System.out.println("processing object request");
507
                            boolean day = false;
508
                            Identifier pid = null;
509
                            String url = null;
510
                            ObjectFormat of = null;
511
                            Date time = null;
512
                            
513
                            if(params.containsKey("day"))
514
                            {
515
                               day = true; 
516
                            }
517
                            if(params.containsKey("pid"))
518
                            {
519
                                String id = params.get("pid")[0];
520
                                pid = new Identifier();
521
                                pid.setValue(id);
522
                            }
523
                            if(params.containsKey("url"))
524
                            {
525
                                url = params.get("url")[0];
526
                            }
527
                            if(params.containsKey("format"))
528
                            {
529
                                String format = params.get("format")[0];
530
                                of = ObjectFormat.convert(format);
531
                            }
532
                            if(params.containsKey("time"))
533
                            {
534
                                String t = params.get("time")[0];
535
                                time = dateFormat.parse(t);
536
                            }
537
                            
538
                            hs.getObjectStatistics(day, pid, url, of, time);
539
                        } else if (pathInfo.toLowerCase().equals("event")) {
540
                            System.out.println("processing event request");
541
                            boolean day = false;
542
                            Identifier pid = null;
543
                            Date created = null;
544
                            ObjectFormat of = null;
545
                            Date time = null;
546
                            String ipAddress = null;
547
                            String event = null;
548
                            
549
                            if(params.containsKey("day"))
550
                            {
551
                               day = true; 
552
                            }
553
                            if(params.containsKey("pid"))
554
                            {
555
                                String id = params.get("pid")[0];
556
                                pid = new Identifier();
557
                                pid.setValue(id);
558
                            }
559
                            if(params.containsKey("created"))
560
                            {
561
                                String t = params.get("created")[0];
562
                                created = dateFormat.parse(t);
563
                            }
564
                            if(params.containsKey("format"))
565
                            {
566
                                String format = params.get("format")[0];
567
                                of = ObjectFormat.convert(format);
568
                            }
569
                            if(params.containsKey("eventtime"))
570
                            {
571
                                String t = params.get("eventtime")[0];
572
                                time = dateFormat.parse(t);
573
                            }
574
                            if(params.containsKey("ip_address"))
575
                            {
576
                                ipAddress = params.get("ip_address")[0];
577
                            }
578
                            if(params.containsKey("event"))
579
                            {
580
                                event = params.get("event")[0];
581
                            }
582
                            
583
                            hs.getOperationStatistics(day, pid, of, created, time, ipAddress, event);
584
                        }
585
                    }
586
                    status = true;
587
                } else if(resource.equals(RESOURCE_REPLICATE)) {
588
                    System.out.println("processing replicate request");
589
                    replicate(httpVerb, request, response);
590
                    status = true;
591
                }
592
                    
593
                if (!status)
594
                {
595
                    response.setStatus(400);
596
                    printError("Incorrect parameters!", response);
597
                }
598
            } else {
599
                response.setStatus(400);
600
                printError("Incorrect resource!", response);
601
            }
602
        } catch (Exception e) {
603
            logMetacat.error(e.getMessage());
604
            System.out.println("Error in ResourceHandler.handle(): " + e.getMessage());
605
            e.printStackTrace();
606
        }
607
    }
608
    
609
    /**
610
     * handle the /replicate action
611
     * @param httpVerb
612
     * @param request
613
     * @param response
614
     * @throws Exception
615
     */
616
    private void replicate(int httpVerb, HttpServletRequest request, HttpServletResponse response)
617
        throws Exception
618
    {
619
        if(httpVerb == POST)
620
        {
621
            System.out.println("in POST replicate()");
622
            /*InputStream is = request.getInputStream();
623
            String input = IOUtils.toString(is);
624
            System.out.println("input: " + input);
625
            is = IOUtils.toInputStream(input);*/
626
            
627
            File tmpDir = getTempDirectory();
628
            File tmpSMFile = new File(tmpDir + 
629
                    ".sysmeta." + new Date().getTime() + ".tmp");
630
            System.out.println("temp dir: " + tmpDir.getAbsolutePath());
631
            MultipartRequestResolver mrr = new MultipartRequestResolver(
632
                    tmpDir.getAbsolutePath(), 1000000000, 0);
633
            MultipartRequest mr = mrr.resolveMultipart(request);
634
            Map<String, File> files = mr.getMultipartFiles();
635
            Iterator keys = files.keySet().iterator();
636
            while(keys.hasNext())
637
            {
638
                String key = (String)keys.next();
639
                System.out.println("files key: " + key);
640
                System.out.println("files value: " + files.get(key));
641
            }
642
            
643
            Map<String, List<String>> params = mr.getMultipartParameters();
644
            keys = params.keySet().iterator();
645
            while(keys.hasNext())
646
            {
647
                String key = (String)keys.next();
648
                System.out.println("params key: " + key);
649
                System.out.println("params value: " + params.get(key));
650
            }
651
            
652
            //File f = files.get("sysmeta");
653
            //the files are not being keyed by the part name, but rather the filename
654
            File f = files.get(files.keySet().iterator().next());
655
            
656
            System.out.println("file: " + f.getAbsolutePath());
657
            String sourceNode = params.get("sourceNode").get(0);
658
            System.out.println("sourceNode: " + sourceNode);
659
            FileInputStream fis = new FileInputStream(f);
660
            
661
            //lookup the id in the registry
662
            URL url = new URL("http://cn.dataone.org/cn/node");
663
            InputStream urlis = url.openStream();
664
            Map<String,String> m = NodeListParser.parseNodeListFile(urlis);
665
            String nodeUrl = m.get(sourceNode);
666
            System.out.println("sourceNodeId: " + sourceNode);
667
            System.out.println("resolved sourceNodeUrl: " + nodeUrl);
668
            
669
            if(nodeUrl == null)
670
            {
671
                response.setStatus(500);
672
                response.getOutputStream().write(("Member Node id " + 
673
                        sourceNode + " not found in node registry.").getBytes());
674
                response.getOutputStream().close();
675
            }
676
            
677
            //respond to cn with 200/OK
678
            //String s;
679
            //s = "sysmeta: " + IOUtils.toString(fis);
680
            //s += "\n\n";
681
            response.setStatus(200);
682
            //response.getOutputStream().write(("sourceNode: " + sourceNode + "\n\n").getBytes());
683
            //response.getOutputStream().write(("s: " + s).getBytes());
684
            OutputStream out = response.getOutputStream();
685
            out.write("OK\n".getBytes());
686
            out.write(("sourceNodeId: " + sourceNode + "\n").getBytes());
687
            out.write(("sourceNodeUrl: " + nodeUrl + "\n").getBytes());
688
            out.close();
689
            
690
            //parse the systemMetadata
691
            SystemMetadata sm = (SystemMetadata)deserializeServiceType(SystemMetadata.class, fis);
692
            NodeReference nr = sm.getOriginMemberNode();
693
            nr.setValue(sourceNode);
694
            sm.setOriginMemberNode(nr);
695
            //get the document
696
            AuthToken token = new AuthToken(sessionId);
697
            MNode mnode = new MNode(nodeUrl);
698
            //get the doc from the remote host
699
            InputStream docStream = mnode.get(new AuthToken("public"), sm.getIdentifier());
700
            File outputTmpFile = getTempFile();
701
            System.out.println("wrote xml file to " + outputTmpFile.getAbsolutePath());
702
            FileOutputStream outputTmpFileStream = new FileOutputStream(outputTmpFile);
703
            IOUtils.copy(docStream, outputTmpFileStream);
704
            
705
            //verify checksum
706
            System.out.println("verifying checksum");
707
            Checksum sourceFileChecksum = ServiceTypeUtil.checksum(new FileInputStream(outputTmpFile), 
708
                    sm.getChecksum().getAlgorithm());
709
            
710
            String cs1 = sm.getChecksum().getValue();
711
            String cs2 = sourceFileChecksum.getValue();
712
            System.out.println("original checksum: " + cs1);
713
            System.out.println(" created checksum: " + cs2);
714
            
715
            if(!cs1.equals(cs2))
716
            {
717
                System.out.println("ERROR: Checksums do not match!");
718
            }
719
            
720
            //insert the document in local db
721
            //System.out.println("creating new doc");
722
            //CrudService.getInstance().create(token, 
723
            //        sm.getIdentifier(), new FileInputStream(outputTmpFile), sm);
724
            //call cn.setReplicationStatus(guid, COMPLETE)
725
            
726
        }
727
    }
728
    
729
    /**
730
     * create the root node registry response.  
731
     * @throws JiBXException
732
     * @throws IOException
733
     */
734
    private void createNodeResponse() 
735
        throws JiBXException, IOException
736
    {
737
        NodeList nl = new NodeList();
738
        Node n = new Node();
739
        NodeReference nr = new NodeReference();
740
        nr.setValue(request.getRequestURL().toString());
741
        n.setIdentifier(nr);
742
        n.setBaseURL(request.getRequestURL().toString());
743
        n.setDescription("Metacat DataONE Node");
744
        n.setName("Metacat WAR version WARVERSION");
745
        n.setType(NodeType.convert("mn"));
746
        
747
        //create the services
748
        Service mnCrud03 = new Service();
749
        mnCrud03.setName("Metacat MN_Crud Services Version 0.3");
750
        mnCrud03.setVersion("0.3");
751
        
752
        Service mnCrud04 = new Service();
753
        mnCrud04.setName("Metacat MN_Crud Services Version 0.4");
754
        mnCrud04.setVersion("0.4");
755
        
756
        Service mnCrud09 = new Service();
757
        mnCrud09.setName("Metacat MN_Crud Services Version 0.9");
758
        mnCrud09.setVersion("0.9");
759
        
760
        Service mnReplication03 = new Service();
761
        mnReplication03.setName("Metcat MN_Replication Version 0.3");
762
        mnReplication03.setVersion("0.3");
763
        
764
        Service mnHealth04 = new Service();
765
        mnHealth04.setName("Metacat MN_Health Version 0.4");
766
        mnHealth04.setVersion("0.4");
767
        
768
        Service mnHealth06 = new Service();
769
        mnHealth06.setName("Metacat MN_Health Version 0.6");
770
        mnHealth06.setVersion("0.6");
771
        
772
        Service mnAuthentication07 = new Service();
773
        mnAuthentication07.setName("Metacat MN_Authentication Version 0.7");
774
        mnAuthentication07.setVersion("0.7");
775
        
776
        Service mnAuthorization07 = new Service();
777
        mnAuthorization07.setName("Metacat MN_Authorization Version 0.7");
778
        mnAuthorization07.setVersion("0.7");
779
        
780
                                    //name, rest, implemented
781
        mnCrud03.addMethod(getServiceMethod("MN_crud.get()", "/object/<guid>", true));
782
        mnCrud03.addMethod(getServiceMethod("MN_crud.getSystemMetadata()", "/meta/<guid>", true));
783
        mnCrud04.addMethod(getServiceMethod("MN_crud.create()", "/object/<guid>", true));
784
        mnCrud04.addMethod(getServiceMethod("MN_crud.update()", "/object/<guid>", true));
785
        mnCrud09.addMethod(getServiceMethod("MN_crud.delete()", "/object/<guid>", true));
786
        mnCrud03.addMethod(getServiceMethod("MN_crud.describe()", "/object/<guid>", true));
787
        mnCrud03.addMethod(getServiceMethod("MN_crud.getChecksum()", "/checksum/<guid>", true));
788
        mnCrud03.addMethod(getServiceMethod("MN_crud.getLogRecords()", "/log", true));
789
        mnReplication03.addMethod(getServiceMethod("MN_replication.listObjects()", "/object", true));
790
        mnReplication03.addMethod(getServiceMethod("MN_replication.replicate()", "/object", true));
791
        mnHealth04.addMethod(getServiceMethod("MN_health.ping()", "/health/ping", false));
792
        mnHealth04.addMethod(getServiceMethod("MN_health.getObjectStatistics()", "/monitor/object/<guid>", false));
793
        mnHealth06.addMethod(getServiceMethod("MN_health.getStatus()", "/health/status", false));
794
        mnAuthentication07.addMethod(getServiceMethod("MN_authentication.login()", "/account/login", false));
795
        mnAuthentication07.addMethod(getServiceMethod("MN_authentication.logout()", "/account/logout", false));
796
        mnAuthorization07.addMethod(getServiceMethod("MN_authorization.isAuthorized()", "/isAuthorized/<guid>", false));
797
        
798
        Services ss = new Services();
799
        ss.addService(mnCrud03);
800
        ss.addService(mnCrud04);
801
        ss.addService(mnCrud09);
802
        ss.addService(mnReplication03);
803
        ss.addService(mnHealth04);
804
        ss.addService(mnHealth06);
805
        ss.addService(mnAuthentication07);
806
        ss.addService(mnAuthorization07);
807
        nl.addNode(n);
808
        response.setContentType("text/xml");
809
        response.setStatus(200);
810
        serializeServiceType(NodeList.class, nl, response.getOutputStream());
811
    }
812
    
813
    /**
814
     * MN_crud.describe()
815
     * http://mule1.dataone.org/ArchitectureDocs/mn_api_crud.html#MN_crud.describe
816
     * @param guid
817
     */
818
    private void describeObject(String guid)
819
    {
820
        Logger logMetacat = Logger.getLogger(ResourceHandler.class);
821
        OutputStream out = null;
822
        try
823
        {
824
            out = response.getOutputStream();
825
        }
826
        catch(Exception e)
827
        {
828
            logMetacat.error("Error getting output stream in ResourceHandler.describeObject: " + e.getMessage());
829
            return;
830
        }
831
        response.setStatus(200);
832
        response.setContentType("text/xml");
833
        AuthToken token = new AuthToken(sessionId);
834
        CrudService cs = CrudService.getInstance();
835
        Identifier id = new Identifier();
836
        id.setValue(guid);
837
        try
838
        {
839
            DescribeResponse dr = cs.describe(token, id);
840
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SZ");
841
            response.addHeader("guid", guid);
842
            response.addHeader("checksum", dr.getDataONE_Checksum().getValue());
843
            response.addHeader("checksum_algorithm", dr.getDataONE_Checksum().getAlgorithm().name());
844
            response.addHeader("content_length", dr.getContent_Length() + "");
845
            response.addHeader("last_modified", dateFormat.format(dr.getLast_Modified()));
846
            response.addHeader("format", dr.getDataONE_ObjectFormat().toString());
847
        }
848
        catch(InvalidRequest ir)
849
        {
850
            serializeException(ir, out);
851
        }
852
        catch(NotImplemented ni)
853
        {
854
            serializeException(ni, out);
855
        }
856
        catch(NotAuthorized na)
857
        {
858
            serializeException(na, out);
859
        }
860
        catch(ServiceFailure sf)
861
        {
862
            serializeException(sf, out);
863
        }
864
        catch(NotFound nf)
865
        {
866
            serializeException(nf, out);
867
        }
868
        catch(InvalidToken it)
869
        {
870
            serializeException(it, out);
871
        }
872
    }
873
    
874
    /**
875
     * get the logs from the CrudService based on passed params.  Available 
876
     * params are token, fromDate, toDate, event.  See 
877
     * http://mule1.dataone.org/ArchitectureDocs/mn_api_crud.html#MN_crud.getLogRecords
878
     * for more info
879
     */
880
    private void getLog()
881
    {
882
        OutputStream out = null;
883
        try
884
        {
885
            out = response.getOutputStream();
886
            response.setStatus(200);
887
            response.setContentType("text/xml");
888
            AuthToken token = new AuthToken(sessionId);
889
            String fromDateS = params.get("fromDate")[0];
890
            System.out.println("param fromDateS: " + fromDateS);
891
            Date fromDate = null;
892
            String toDateS = params.get("toDate")[0];
893
            System.out.println("param toDateS: " + toDateS);
894
            Date toDate = null;
895
            String eventS = params.get("event")[0];
896
            Event event = null;
897
            if(fromDateS != null)
898
            {
899
                //fromDate = dateFormat.parse(fromDateS);
900
                fromDate = parseDateAndConvertToGMT(fromDateS);
901
            }
902
            if(toDateS != null)
903
            {
904
                //toDate = dateFormat.parse(toDateS);
905
                toDate = parseDateAndConvertToGMT(toDateS);
906
            }
907
            if(eventS != null)
908
            {
909
                event = Event.convert(eventS);
910
            }
911
            System.out.println("fromDate: " + fromDate + " toDate: " + toDate);
912
            
913
            System.out.println("calling crudservice.getLogRecords");
914
            Log log = CrudService.getInstance().getLogRecords(token, fromDate, toDate, event);
915
            serializeServiceType(Log.class, log, out);
916
        }
917
        catch(Exception e)
918
        {
919
            String msg = "Could not get logs from CrudService: " + e.getMessage();
920
            response.setStatus(500);
921
            ServiceFailure sf = new ServiceFailure("1490", msg);
922
            logMetacat.error(msg);
923
            e.printStackTrace();
924
            serializeException(sf, out);
925
        }
926
    }
927
    
928
    /**
929
     *  copies request parameters to a hashtable which is given as argument to native metacathandler functions  
930
     */
931
    private void initParams() {
932

    
933
        String name = null;
934
        String[] value = null;
935
        Enumeration paramlist = request.getParameterNames();
936
        while (paramlist.hasMoreElements()) {
937
            name = (String) paramlist.nextElement();
938
            value = request.getParameterValues(name);
939
            params.put(name, value);
940
        }
941
    }
942

    
943
    /**
944
     * 
945
     * Load user details of metacat session from the request 
946
     * 
947
     */
948
    private void loadSessionData()
949
      throws Exception
950
    {
951
        SessionData sessionData = RequestUtil.getSessionData(request);
952
        try
953
        {
954
            username = null;
955
            password = null;
956
            groupNames = null;
957
            sessionId = null;
958
            
959
            boolean validSession = false;
960
            SessionService ss = SessionService.getInstance();
961
            System.out.println("sessionData: " + sessionData);
962
            if(sessionData == null)
963
            {
964
                username = "public";
965
                sessionId = "0";
966
                System.out.println("sessiondata is null.  Creating a public session.");
967
                return;
968
            }
969
            
970
            System.out.println("username: " + sessionData.getUserName());
971
            System.out.println("sessionid: " + sessionData.getId());
972
            //validate the session
973
            if(ss.isSessionRegistered(sessionData.getId()) && 
974
               !(sessionData.getUserName().equals("public") || sessionData.getId().equals("0")))
975
            {
976
                validSession = true;
977
            }
978
            
979
            if(validSession)
980
            {
981
                //if the session is valid, set these variables
982
                username = sessionData.getUserName();
983
                password = sessionData.getPassword();
984
                groupNames = sessionData.getGroupNames();
985
                sessionId = sessionData.getId();
986
                System.out.println("setting sessionid to " + sessionId);
987
                System.out.println("username: " + username);
988
            }
989
            
990
            //if the session is not valid or the username is null, set
991
            //username to public
992
            if (username == null) 
993
            {
994
                System.out.println("setting username to public.");
995
                username = "public";
996
            }
997
        }
998
        catch(Exception e)
999
        {
1000
            e.printStackTrace();
1001
            throw new Exception("Could not load the session data: " + e.getMessage());
1002
        }
1003
    }
1004
    
1005
    /**
1006
     * generate missing system metadata for any science metadata objects
1007
     * that don't already have it. https://trac.dataone.org/ticket/591
1008
     * 
1009
     * called with POST meta/?op=generatemissingsystemmetadata
1010
     */
1011
    private void generateMissingSystemMetadata()
1012
    {
1013
        AuthToken token = new AuthToken(sessionId);
1014
        CrudService.getInstance().generateMissingSystemMetadata(token);
1015
    }
1016

    
1017
    /**
1018
     *  Earthgrid API > Identifier Service > isRegistered Function : 
1019
     *  calls MetacatHandler > handleIdIsRegisteredAction
1020
     * @param guid
1021
     * @throws IOException
1022
     */
1023
    private void isRegistered(String guid) throws IOException
1024
    {
1025
        
1026
        // Look up the localId for this guid
1027
        IdentifierManager im = IdentifierManager.getInstance();
1028
        String localId = "";
1029
        try {
1030
            localId = im.getLocalId(guid);
1031
        } catch (McdbDocNotFoundException e) {
1032
            // TODO: Need to return the proper DataONE exception
1033
        }
1034
        
1035
        params.put("docid", new String[] { localId });
1036
        PrintWriter out = response.getWriter();
1037
        response.setStatus(200);
1038
        response.setContentType("text/xml");
1039
        handler.handleIdIsRegisteredAction(out, params, response);
1040
        out.close();
1041
    }
1042

    
1043
    /**
1044
     * Earthgrid API > Identifier Service > getAllDocIds Function : 
1045
     * calls MetacatHandler > handleGetAllDocidsAction
1046
     * @throws IOException
1047
     */
1048
    private void getAllDocIds() throws IOException {
1049
        PrintWriter out = response.getWriter();
1050
        response.setStatus(200);
1051
        response.setContentType("text/xml");
1052
        handler.handleGetAllDocidsAction(out, params, response);
1053
        out.close();
1054
    }
1055

    
1056
    /**
1057
     * Earthgrid API > Identifier Service > getNextRevision Function : 
1058
     * calls MetacatHandler > handleGetRevisionAndDocTypeAction
1059
     * @param guid
1060
     * @throws IOException
1061
     */
1062
    private void getNextRevision(String guid) throws IOException 
1063
    {
1064
        params.put("docid", new String[] { guid });
1065
        PrintWriter out = response.getWriter();
1066
        response.setStatus(200);
1067
        response.setContentType("text/xml");
1068
        //handler.handleGetRevisionAndDocTypeAction(out, params);
1069

    
1070
        try {
1071
            // Make sure there is a docid
1072
            if (guid == null || guid.equals("")) {
1073
                throw new Exception("User didn't specify docid!");
1074
            }
1075

    
1076
            // Look up the localId for this guid
1077
            IdentifierManager im = IdentifierManager.getInstance();
1078
            String localId = "";
1079
            try {
1080
                localId = im.getLocalId(guid);
1081
            } catch (McdbDocNotFoundException e) {
1082
                // TODO: Need to return the proper DataONE exception
1083
            }
1084
           
1085
            // Create a DBUtil object
1086
            DBUtil dbutil = new DBUtil();
1087
            // Get a rev and doctype
1088
            String revAndDocType = dbutil
1089
                    .getCurrentRevisionAndDocTypeForGivenDocument(localId);
1090
            int revision = Integer.parseInt(revAndDocType.split(";")[0]) + 1;
1091

    
1092
            out.println("<?xml version=\"1.0\"?>");
1093
            out.print("<next-revision>");
1094
            out.print(revision);
1095
            out.print("</next-revision>");
1096

    
1097
        } catch (Exception e) {
1098
            // Handle exception
1099
            response.setStatus(500);
1100
            out.println("<?xml version=\"1.0\"?>");
1101
            out.println("<error>");
1102
            out.println(e.getMessage());
1103
            out.println("</error>");
1104
        }
1105

    
1106
        out.close();
1107
    }
1108

    
1109
    /**
1110
     * Earthgrid API > Identifier Service > getNextObject Function : 
1111
     * calls MetacatHandler > handleGetMaxDocidAction
1112
     * @throws IOException
1113
     */
1114
    private void getNextObject() throws IOException {
1115
        PrintWriter out = response.getWriter();
1116
        response.setStatus(200);
1117
        response.setContentType("text/xml");
1118
        handler.handleGetMaxDocidAction(out, params, response);
1119
        out.close();
1120
    }
1121

    
1122
    /**
1123
     * Implements REST version of DataONE CRUD API --> get
1124
     * @param guid ID of data object to be read
1125
     */
1126
    private void getObject(String guid) {
1127
        CrudService cs = CrudService.getInstance();
1128
        cs.setParamsFromRequest(request);
1129
        AuthToken token = new AuthToken(sessionId);
1130
        OutputStream out = null;
1131
        try {
1132
            out = response.getOutputStream();
1133
            response.setStatus(200);
1134
            
1135
            if(guid != null)
1136
            { //get a specific document                
1137
                Identifier id = new Identifier();
1138
                id.setValue(guid);
1139
                try
1140
                {
1141
                    if(token == null)
1142
                    {
1143
                        token = new AuthToken("Public");
1144
                    }
1145
                    SystemMetadata sm = cs.getSystemMetadata(token, id);
1146
                    
1147
                    //set the content type
1148
                    if(sm.getObjectFormat().toString().trim().equals(ObjectFormat.TEXT_CSV.toString()))
1149
                    {
1150
                        response.setContentType("text/csv");
1151
                    }
1152
                    else if(sm.getObjectFormat().toString().trim().equals(ObjectFormat.TEXT_PLAIN.toString()))
1153
                    {
1154
                        response.setContentType("text/plain");
1155
                    } 
1156
                    else if(sm.getObjectFormat().toString().trim().equals(ObjectFormat.OCTET_STREAM.toString()))
1157
                    {
1158
                        response.setContentType("application/octet-stream");
1159
                    }
1160
                    else
1161
                    {
1162
                        response.setContentType("text/xml");
1163
                    }
1164
                    
1165
                    InputStream data = cs.get(token, id);
1166
                    IOUtils.copyLarge(data, response.getOutputStream());
1167
                }
1168
                catch(InvalidToken it)
1169
                {
1170
                    response.setStatus(500);
1171
                    serializeException(it, out); 
1172
                }
1173
                catch(ServiceFailure sf)
1174
                {
1175
                    response.setStatus(500);
1176
                    serializeException(sf, out); 
1177
                }
1178
                catch(NotAuthorized na)
1179
                {
1180
                    response.setStatus(500);
1181
                    serializeException(na, out); 
1182
                }
1183
                catch(NotFound nf)
1184
                {
1185
                    response.setStatus(500);
1186
                    serializeException(nf, out); 
1187
                }
1188
                catch(NotImplemented ni)
1189
                {
1190
                    response.setStatus(500);
1191
                    serializeException(ni, out); 
1192
                }
1193
                catch(Exception e)
1194
                {
1195
                    response.setStatus(500);
1196
                    System.out.println("Error with Crud.get().  " +
1197
                            "If this is an 'Exception producing data' error, " +
1198
                            "go to CrudService.get() for better debugging.  " +
1199
                            "Here's the error: " + e.getMessage());
1200
                    e.printStackTrace();
1201
                    ServiceFailure sf = new ServiceFailure("1030", 
1202
                            "IO Error in ResourceHandler.getObject: " + e.getMessage());
1203
                    serializeException(sf, out); 
1204
                }
1205
            }
1206
            else
1207
            { //call listObjects with specified params
1208
                Date startTime = null;
1209
                Date endTime = null;
1210
                ObjectFormat objectFormat = null;
1211
                boolean replicaStatus = false;
1212
                int start = 0;
1213
                //TODO: make the max count into a const
1214
                int count = 1000;
1215
                Enumeration paramlist = request.getParameterNames();
1216
                while (paramlist.hasMoreElements()) 
1217
                { //parse the params and make the crud call
1218
                    String name = (String) paramlist.nextElement();
1219
                    String[] value = (String[])request.getParameterValues(name);
1220
                    /*for(int i=0; i<value.length; i++)
1221
                    {
1222
                        System.out.println("name: " + name + " value: " + value[i]);
1223
                    }*/
1224
                    if(name.equals("startTime") && value != null)
1225
                    {
1226
                        try
1227
                        {
1228
                          //startTime = dateFormat.parse(value[0]);
1229
                            startTime = parseDateAndConvertToGMT(value[0]);
1230
                        }
1231
                        catch(Exception e)
1232
                        {  //if we can't parse it, just don't use the startTime param
1233
                            System.out.println("Could not parse startTime: " + value[0]);
1234
                            startTime = null;
1235
                        }
1236
                    }
1237
                    else if(name.equals("endTime") && value != null)
1238
                    {
1239
                        try
1240
                        {
1241
                          //endTime = dateFormat.parse(value[0]);
1242
                            endTime = parseDateAndConvertToGMT(value[0]);
1243
                        }
1244
                        catch(Exception e)
1245
                        {  //if we can't parse it, just don't use the endTime param
1246
                            System.out.println("Could not parse endTime: " + value[0]);
1247
                            endTime = null;
1248
                        }
1249
                    }
1250
                    else if(name.equals("objectFormat") && value != null) 
1251
                    {
1252
                        objectFormat = ObjectFormat.convert(value[0]);
1253
                    }
1254
                    else if(name.equals("replicaStatus") && value != null)
1255
                    {
1256
                        if(value != null && 
1257
                           value.length > 0 && 
1258
                           (value[0].equals("true") || value[0].equals("TRUE") || value[0].equals("YES")))
1259
                        {
1260
                            replicaStatus = true;
1261
                        }
1262
                    }
1263
                    else if(name.equals("start") && value != null)
1264
                    {
1265
                        start = new Integer(value[0]).intValue();
1266
                    }
1267
                    else if(name.equals("count") && value != null)
1268
                    {
1269
                        count = new Integer(value[0]).intValue();
1270
                    }
1271
                }
1272
                //make the crud call
1273
                System.out.println("token: " + token + " startTime: " + startTime +
1274
                        " endtime: " + endTime + " objectFormat: " + 
1275
                        objectFormat + " replicaStatus: " + replicaStatus + 
1276
                        " start: " + start + " count: " + count);
1277
               
1278
                ObjectList ol = cs.listObjects(token, startTime, endTime, 
1279
                        objectFormat, replicaStatus, start, count);
1280
                
1281
                StringReader sr = new StringReader(ol.toString());                
1282
                out = response.getOutputStream();  
1283
                response.setStatus(200);
1284
                response.setContentType("text/xml");
1285
                // Serialize and write it to the output stream
1286
                
1287
                try {
1288
                    serializeServiceType(ObjectList.class, ol, out);
1289
                } catch (JiBXException e) {
1290
                    throw new ServiceFailure("1190", "Failed to serialize ObjectList: " + e.getMessage());
1291
                }
1292
            }
1293
        } catch (BaseException e) {
1294
                response.setStatus(500);
1295
                serializeException(e, out);
1296
        } catch (IOException e) {
1297
            e.printStackTrace();
1298
            response.setStatus(500);
1299
            ServiceFailure sf = new ServiceFailure("1030", 
1300
                    "IO Error in ResourceHandler.getObject: " + e.getMessage());
1301
            serializeException(sf, out); 
1302
        } catch(NumberFormatException ne) {
1303
            response.setStatus(500);
1304
            InvalidRequest ir = new InvalidRequest("1030", "Invalid format for parameter: " + ne.getMessage());
1305
            serializeException(ir, out);
1306
        } catch (Exception e) {
1307
            e.printStackTrace();
1308
            response.setStatus(500);
1309
            ServiceFailure sf = new ServiceFailure("1030", 
1310
                    "Exception " + e.getClass().getName() + " raised while handling listObjects request: " + 
1311
                    e.getMessage());
1312
            serializeException(sf, out);
1313
        }
1314
    }
1315
    
1316
    /**
1317
     * parse a date and return it in GMT if it ends with a 'Z'
1318
     * @param date
1319
     * @return
1320
     * @throws ParseException
1321
     */
1322
    private Date parseDateAndConvertToGMT(String date) throws ParseException
1323
    {
1324
        try
1325
        {   //the format we want
1326
            return dateFormat.parse(date);
1327
        }
1328
        catch(java.text.ParseException pe)
1329
        {   //try another legacy format
1330
            DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
1331
            dateFormat2.setTimeZone(TimeZone.getTimeZone("GMT-0"));
1332
            return dateFormat2.parse(date);
1333
        }    
1334
    }
1335

    
1336
    /**
1337
     * Implements REST version of DataONE CRUD API --> getSystemMetadata
1338
     * @param guid ID of data object to be read
1339
     */
1340
    private void getSystemMetadataObject(String guid) {
1341
        CrudService cs = CrudService.getInstance();
1342
        cs.setParamsFromRequest(request);
1343
        AuthToken token = new AuthToken(sessionId);
1344
        OutputStream out = null;
1345
        try {
1346
            response.setContentType("text/xml");
1347
            response.setStatus(200);
1348
            out = response.getOutputStream();
1349
            Identifier id = new Identifier();
1350
            id.setValue(guid);
1351
            SystemMetadata sysmeta = cs.getSystemMetadata(token, id);
1352
            
1353
            // Serialize and write it to the output stream
1354
            try {
1355
                //TODO: look at the efficiency of this method.  The system metadata
1356
                //is read from metacat (in CrudService) as xml, then serialized
1357
                //to a SystemMetadat object, then returned here, then serizlized
1358
                //back to XML to be sent to the response.
1359
                serializeServiceType(SystemMetadata.class, sysmeta, out);
1360
            } catch (JiBXException e) {
1361
                throw new ServiceFailure("1190", "Failed to serialize SystemMetadata: " + e.getMessage());
1362
            }
1363
        } catch (BaseException e) {
1364
            response.setStatus(500);
1365
                serializeException(e, out);
1366
        } catch (IOException e) {
1367
            response.setStatus(500);
1368
            ServiceFailure sf = new ServiceFailure("1030", 
1369
                    "Error in ResourceHandler.getSystemMetadataObject: " + e.getMessage());
1370
            serializeException(sf, out);
1371
        } finally {
1372
            IOUtils.closeQuietly(out);
1373
        }
1374
    }
1375
    
1376
    /**
1377
     * serialize an object of type to out
1378
     * @param type the class of the object to serialize (i.e. SystemMetadata.class)
1379
     * @param object the object to serialize
1380
     * @param out the stream to serialize it to
1381
     * @throws JiBXException
1382
     */
1383
    private void serializeServiceType(Class type, Object object, OutputStream out)
1384
      throws JiBXException
1385
    {
1386
        ServiceTypeUtil.serializeServiceType(type, object, out);
1387
    }
1388
    
1389
    /**
1390
     * deserialize an object of type from is
1391
     * @param type the class of the object to serialize (i.e. SystemMetadata.class)
1392
     * @param is the stream to deserialize from
1393
     * @throws JiBXException
1394
     */
1395
    private Object deserializeServiceType(Class type, InputStream is)
1396
      throws JiBXException
1397
    {
1398
        return ServiceTypeUtil.deserializeServiceType(type, is);
1399
    }
1400
    
1401
    /**
1402
     * Earthgrid API > Query Service > Query Function : translates ecogrid query document to metacat query 
1403
     * then calls DBQuery > createResultDocument function and then again translate resultset to ecogrid resultset
1404
     * 
1405
     * NOTE:
1406
     *      This is the only method that uses EcoGrid classes for its implementation.  
1407
     *      It does so because it takes an EcoGrid Query as input, and outputs an
1408
     *      EcoGrid ResultSet document.  These documents are parsed by the auto-generated
1409
     *      EcoGrid classes from axis, and so we link to them here rather than re-inventing them.
1410
     *      This creates a circular dependency, because the Metacat classes are needed
1411
     *      to build the EcoGrid implementation, and the EcoGrid jars are needed to build this query()
1412
     *      method.  This circularity could be resolved by moving the EcoGrid classes
1413
     *      to Metacat directly.  As we transition away from EcoGrid SOAP methods in
1414
     *      favor of these REST interfaces, this circular dependency can be eliminated.
1415
     *        
1416
     * @throws Exception
1417
     */
1418
    private void query() throws Exception {
1419
        /*  This block commented out because of the EcoGrid circular dependency.
1420
         *  For now, query will not be supported until the circularity can be
1421
         *  resolved, probably by moving the ecogrid query syntax transformers
1422
         *  directly into the Metacat codebase.  MBJ 2010-02-03
1423
         
1424
        try {
1425
            EcogridQueryParser parser = new EcogridQueryParser(request
1426
                    .getReader());
1427
            parser.parseXML();
1428
            QueryType queryType = parser.getEcogridQuery();
1429
            EcogridJavaToMetacatJavaQueryTransformer queryTransformer = 
1430
                new EcogridJavaToMetacatJavaQueryTransformer();
1431
            QuerySpecification metacatQuery = queryTransformer
1432
                    .transform(queryType);
1433

    
1434
            DBQuery metacat = new DBQuery();
1435

    
1436
            boolean useXMLIndex = (new Boolean(PropertyService
1437
                    .getProperty("database.usexmlindex"))).booleanValue();
1438
            String xmlquery = "query"; // we don't care the query in resultset,
1439
            // the query can be anything
1440
            PrintWriter out = null; // we don't want metacat result, so set out null
1441

    
1442
            // parameter: queryspecification, user, group, usingIndexOrNot
1443
            StringBuffer result = metacat.createResultDocument(xmlquery,
1444
                    metacatQuery, out, username, groupNames, useXMLIndex);
1445

    
1446
            // create result set transfer       
1447
            String saxparser = PropertyService.getProperty("xml.saxparser");
1448
            MetacatResultsetParser metacatResultsetParser = new MetacatResultsetParser(
1449
                    new StringReader(result.toString()), saxparser, queryType
1450
                            .getNamespace().get_value());
1451
            ResultsetType records = metacatResultsetParser.getEcogridResult();
1452

    
1453
            System.out
1454
                    .println(EcogridResultsetTransformer.toXMLString(records));
1455
            response.setContentType("text/xml");
1456
            out = response.getWriter();
1457
            out.print(EcogridResultsetTransformer.toXMLString(records));
1458

    
1459
        } catch (Exception e) {
1460
            e.printStackTrace();
1461
        }*/
1462
        response.setContentType("text/xml");
1463
        response.setStatus(501);
1464
        PrintWriter out = response.getWriter();
1465
        out.print("<error>Query operation not yet supported by Metacat.</error>");
1466
        out.close();
1467
    }
1468
    
1469
    private String streamToString(InputStream is)
1470
    throws IOException
1471
    {
1472
        return IOUtil.toString(is);
1473
    }
1474

    
1475
    private InputStream stringToStream(String s)
1476
    throws IOException
1477
    {
1478
        ByteArrayInputStream bais = new ByteArrayInputStream(s.getBytes(MetaCatServlet.DEFAULT_ENCODING));
1479
        return bais;
1480
    }
1481
    
1482
    /**
1483
     * locate the boundary marker for an MMP
1484
     * @param is
1485
     * @return
1486
     * @throws IOException
1487
     */
1488
    protected static String[] findBoundaryString(InputStream is)
1489
        throws IOException
1490
    {
1491
        String[] endResult = new String[2];
1492
        String boundary = "";
1493
        String searchString = "boundary=";
1494
        boolean doneWithCurrentArray = false;
1495
        byte[] b = new byte[1024];
1496
        int numbytes = is.read(b, 0, 1024);
1497

    
1498
        while(numbytes != -1)
1499
        {
1500
            String s = new String(b, 0, numbytes);
1501
            int searchStringIndex = s.indexOf(searchString);
1502
            
1503
            if(s.indexOf("\"", searchStringIndex + searchString.length() + 1) == -1)
1504
            { //the end of the boundary is in the next byte array
1505
                boundary = s.substring(searchStringIndex + searchString.length() + 1, s.length());
1506
            }
1507
            else if(!boundary.startsWith("--"))
1508
            { //we can read the whole boundary from this byte array
1509
                boundary = s.substring(searchStringIndex + searchString.length() + 1, 
1510
                    s.indexOf("\"", searchStringIndex + searchString.length() + 1));
1511
                boundary = "--" + boundary;
1512
                endResult[0] = boundary;
1513
                endResult[1] = s.substring(s.indexOf("\"", searchStringIndex + searchString.length() + 1) + 1,
1514
                        s.length());
1515
                break;
1516
            }
1517
            else
1518
            { //we're now reading the 2nd byte array to get the rest of the boundary
1519
                searchString = "\"";
1520
                searchStringIndex = s.indexOf(searchString);
1521
                boundary += s.substring(0, searchStringIndex);
1522
                boundary = "--" + boundary;
1523
                endResult[0] = boundary;
1524
                endResult[1] = s.substring(s.indexOf("\"", searchStringIndex + searchString.length() + 1) + 1,
1525
                        s.length());
1526
                break;
1527
            }
1528
        }
1529
        System.out.println("boundary is: '" + boundary + "'");
1530
        return endResult;
1531
    }
1532
    
1533
    /**
1534
     * return the directory where temp files are stored
1535
     * @return
1536
     */
1537
    private static File getTempDirectory()
1538
    {
1539
        File tmpDir = null;
1540
        Logger logMetacat = Logger.getLogger(ResourceHandler.class);
1541
        try
1542
        {
1543
            tmpDir = new File(PropertyService.getProperty("application.tempDir"));
1544
        }
1545
        catch(PropertyNotFoundException pnfe)
1546
        {
1547
            logMetacat.error("ResourceHandler.writeMMPPartstoFiles: " +
1548
                    "application.tmpDir not found.  Using /tmp instead.");
1549
            tmpDir = new File("/tmp");
1550
        }
1551
        return tmpDir;
1552
    }
1553
    
1554
    /**
1555
     * return a tmp file with a given name
1556
     * @param name
1557
     * @return
1558
     */
1559
    private static File getTempFile(String name)
1560
    {
1561
        File tmpDir = getTempDirectory();
1562
        File f = new File(tmpDir, name);
1563
        return f;
1564
    }
1565
    
1566
    /**
1567
     * return a temp file with a default name
1568
     * @return
1569
     */
1570
    private static File getTempFile()
1571
    {
1572
        return getTempFile(new Date().getTime() + ".tmp");
1573
    }
1574
    
1575
    /**
1576
     * Earthgrid API > Put Service >Put Function : calls MetacatHandler > handleInsertOrUpdateAction 
1577
     * 
1578
     * @param guid ID of data object to be inserted or updated
1579
     * @throws IOException
1580
     */
1581
    private void putObject(String guid, String action) {
1582
        System.out.println("ResourceHandler: putObject with guid " + guid);
1583
        logMetacat.debug("Entering putObject: " + guid + "/" + action);
1584
        OutputStream out = null;
1585
        try {
1586
            out = response.getOutputStream();
1587
            response.setStatus(200);
1588
            response.setContentType("text/xml");
1589
        } catch (IOException e1) {
1590
            logMetacat.error("Could not get the output stream for writing in putObject");
1591
        }
1592
        try {
1593
            
1594
            // Read the incoming data from its Mime Multipart encoding
1595
            logMetacat.debug("Disassembling MIME multipart form");
1596
            InputStream object = null;
1597
            InputStream sysmeta = null;
1598
            
1599
            try
1600
            {
1601
                //String req = IOUtils.toString(request.getInputStream());
1602
                //System.out.println("request: " + req);
1603
                //InputStream reqStr = IOUtils.toInputStream(req);
1604
                InputStream reqStr = request.getInputStream();
1605
                
1606
                //handle MMP inputs
1607
                File tmpDir = getTempDirectory();
1608
                File tmpSMFile = new File(tmpDir + 
1609
                        ".sysmeta." + new Date().getTime() + ".tmp");
1610
                System.out.println("temp dir: " + tmpDir.getAbsolutePath());
1611
                MultipartRequestResolver mrr = new MultipartRequestResolver(
1612
                        tmpDir.getAbsolutePath(), 1000000000, 0);
1613
                MultipartRequest mr = mrr.resolveMultipart(request);
1614
                System.out.println("resolved multipart request");
1615
                Map<String, File> files = mr.getMultipartFiles();
1616
                if(files == null)
1617
                {
1618
                    throw new ServiceFailure("1202", "create/update must have multipart files with names 'object' and 'sysmeta'");
1619
                }
1620
                System.out.println("got multipart files");
1621
                
1622
                if(files.keySet() == null)
1623
                {
1624
                    System.out.println("No file keys in MMP request.");
1625
                    throw new ServiceFailure("1202", "No file keys found in MMP.  " +
1626
                            "create/update must have multipart files with names 'object' and 'sysmeta'");
1627
                }
1628
                Iterator keys = files.keySet().iterator();
1629
                System.out.println("iterating through multipart files: " + keys);
1630
                while(keys.hasNext())
1631
                {
1632
                    String key = (String)keys.next();
1633
                    System.out.println("files key: " + key);
1634
                    System.out.println("files value: " + files.get(key));
1635
                }
1636
                
1637
                Map<String, List<String>> params = mr.getMultipartParameters();
1638
                keys = params.keySet().iterator();
1639
                while(keys.hasNext())
1640
                {
1641
                    String key = (String)keys.next();
1642
                    System.out.println("params key: " + key);
1643
                    System.out.println("params value: " + params.get(key));
1644
                }
1645
                File smFile = files.get("sysmeta");
1646
                System.out.println("smFile: " + smFile.getAbsolutePath());
1647
                sysmeta = new FileInputStream(smFile);
1648
                File objFile = files.get("object");
1649
                System.out.println("objectfile: " + objFile.getAbsolutePath());
1650
                object = new FileInputStream(objFile);
1651
                
1652
                /*String obj = IOUtils.toString(object);
1653
                String sm = IOUtils.toString(sysmeta);
1654
                System.out.println("object: " + obj);
1655
                System.out.println("sm: " + sm);
1656
                object = IOUtils.toInputStream(obj);
1657
                sysmeta = IOUtils.toInputStream(sm);*/
1658
                
1659
            }
1660
            catch(org.apache.commons.fileupload.FileUploadException fue)
1661
            {
1662
                throw new ServiceFailure("1202", "Could not upload MMP files: " + fue.getMessage());
1663
            }
1664
            catch(IOException ioe)
1665
            {
1666
                throw new ServiceFailure("1202", 
1667
                        "IOException when processing Mime Multipart: " + ioe.getMessage());
1668
            }
1669
            catch(Exception e)
1670
            {
1671
                throw new ServiceFailure("1202", "Error handling MMP upload: " + e.getMessage());
1672
            }
1673
            
1674
            if ( action.equals(FUNCTION_NAME_INSERT)) { //handle inserts
1675

    
1676
                // Check if the objectId exists
1677
                IdentifierManager im = IdentifierManager.getInstance();
1678
                if (im.identifierExists(guid)) {
1679
                    throw new IdentifierNotUnique("1000", "Identifier is already in use: " + guid);
1680
                }
1681

    
1682
                logMetacat.debug("Commence creation...");
1683
                IBindingFactory bfact =
1684
                    BindingDirectory.getFactory(SystemMetadata.class);
1685
                IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1686
                SystemMetadata m = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
1687

    
1688
                CrudService cs = CrudService.getInstance();
1689
                AuthToken token = new AuthToken(sessionId); 
1690
                cs.setParamsFromRequest(request);
1691
                Identifier id = new Identifier();
1692
                id.setValue(guid);
1693
                System.out.println("creating object with guid " + id.getValue());
1694
                Identifier rId = cs.create(token, id, object, m);
1695
                serializeServiceType(Identifier.class, rId, out);
1696
                
1697
            } else if (action.equals(FUNCTION_NAME_UPDATE)) { //handle updates
1698
                IdentifierManager im = IdentifierManager.getInstance();
1699
                CrudService cs = CrudService.getInstance();
1700
                Identifier obsoletedGuid = new Identifier();
1701
                Identifier id = new Identifier();
1702
                id.setValue(guid);
1703
                AuthToken token = new AuthToken(sessionId);
1704
                
1705
                //do some checks
1706
                if(params.get("obsoletedGuid") == null)
1707
                {
1708
                    throw new InvalidRequest("1202", "obsoletedGuid must be contained in the request parameters.");
1709
                }
1710
                //get the obsoletedGuid
1711
                String[] obsGuidS = params.get("obsoletedGuid");
1712
                obsoletedGuid.setValue(obsGuidS[0]);
1713
                
1714
                if (!im.identifierExists(obsoletedGuid.getValue())) 
1715
                {
1716
                    throw new InvalidRequest("1202", "The guid you are trying to update does not exist.");
1717
                }
1718
                
1719
                
1720
                logMetacat.debug("Commence update...");
1721
                
1722
                //get the systemmetadata
1723
                IBindingFactory bfact =
1724
                        BindingDirectory.getFactory(SystemMetadata.class);
1725
                    IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1726
                    SystemMetadata m = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
1727
                
1728
                //do the update
1729
                try
1730
                {
1731
                    cs.setParamsFromRequest(request);
1732
                    Identifier rId = cs.update(token, id, object, obsoletedGuid, m);
1733
                    serializeServiceType(Identifier.class, rId, out);
1734
                }
1735
                catch(NotFound e)
1736
                {
1737
                    throw new InvalidRequest("1202", "The guid you are trying to update does not exist.");
1738
                }
1739
                
1740
            } else {
1741
                throw new InvalidRequest("1000", "Operation must be create or update.");
1742
            }
1743
            
1744
            //clean up the MMP files
1745
            //parts.get("systemmetadata").delete();
1746
            //parts.get("object").delete();
1747
        } catch (NotAuthorized e) {
1748
            response.setStatus(500);
1749
            serializeException(e, out);
1750
        } catch (InvalidToken e) {
1751
            response.setStatus(500);
1752
            serializeException(e, out);
1753
        } catch (ServiceFailure e) {
1754
            response.setStatus(500);
1755
            serializeException(e, out);
1756
        } catch (IdentifierNotUnique e) {
1757
            response.setStatus(500);
1758
            serializeException(e, out);
1759
        } catch (UnsupportedType e) {
1760
            response.setStatus(500);
1761
            serializeException(e, out);
1762
        } catch (InsufficientResources e) {
1763
            response.setStatus(500);
1764
            serializeException(e, out);
1765
        } catch (InvalidSystemMetadata e) {
1766
            response.setStatus(500);
1767
            serializeException(e, out);
1768
        } catch (NotImplemented e) {
1769
            response.setStatus(500);
1770
            serializeException(e, out);
1771
        } catch (InvalidRequest e) {
1772
            response.setStatus(500);
1773
            serializeException(e, out);
1774
        } /*catch (MessagingException e) {
1775
            ServiceFailure sf = new ServiceFailure("1000", e.getMessage());
1776
            serializeException(sf, out);
1777
        } catch (IOException e) {
1778
            response.setStatus(500);
1779
            ServiceFailure sf = new ServiceFailure("1000", e.getMessage());
1780
            serializeException(sf, out);
1781
        }*/ catch (JiBXException e) {
1782
            response.setStatus(500);
1783
            e.printStackTrace(System.out);
1784
            InvalidSystemMetadata ism = new InvalidSystemMetadata("1080", e.getMessage());
1785
            serializeException(ism, out);
1786
        }
1787
    }
1788

    
1789
    /**
1790
     * Handle delete 
1791
     * @param guid ID of data object to be deleted
1792
     * @throws IOException
1793
     */
1794
    private void deleteObject(String guid) throws IOException 
1795
    {
1796
        // Look up the localId for this global identifier
1797
        System.out.println("!!!!!!!!!!!!!!!!!deleting object " + guid);
1798
        IdentifierManager im = IdentifierManager.getInstance();
1799
        String localId = "";
1800
        OutputStream out = response.getOutputStream();
1801
        response.setStatus(200);
1802
        try {
1803
            localId = im.getLocalId(guid);
1804
        } catch (McdbDocNotFoundException e) {
1805
            NotFound nf = new NotFound("1340", "Document with guid " + guid + " not found.");
1806
            response.setStatus(404);
1807
            serializeException(nf, out);
1808
        }
1809
       
1810
        AuthToken token = new AuthToken(sessionId);
1811
        CrudService cs = CrudService.getInstance();
1812
        Identifier id = new Identifier();
1813
        id.setValue(guid);
1814
        try
1815
        {
1816
            System.out.println("Calling delete");
1817
            cs.delete(token, id);
1818
            serializeServiceType(Identifier.class, id, out);
1819
        } 
1820
        catch (NotAuthorized e) {
1821
            response.setStatus(500);
1822
            serializeException(e, out);
1823
        } catch (InvalidToken e) {
1824
            response.setStatus(500);
1825
            serializeException(e, out);
1826
        } catch (ServiceFailure e) {
1827
            response.setStatus(500);
1828
            serializeException(e, out);
1829
        } catch (NotImplemented e) {
1830
            response.setStatus(500);
1831
            serializeException(e, out);
1832
        } catch (InvalidRequest e) {
1833
            response.setStatus(500);
1834
            serializeException(e, out);
1835
        } catch(NotFound e) {
1836
            response.setStatus(500);
1837
            serializeException(e, out);
1838
        } catch(JiBXException e) {
1839
            response.setStatus(500);
1840
            serializeException(new ServiceFailure("1350", "JiBXException: " + e.getMessage()), out);
1841
        }
1842
        out.close();
1843
    }
1844
    
1845
    /**
1846
     * set the access perms on a document
1847
     * @throws IOException
1848
     */
1849
    private void setaccess() throws Exception
1850
    {
1851
        try
1852
        {
1853
            String guid = params.get("guid")[0];
1854
            Identifier id = new Identifier();
1855
            id.setValue(guid);
1856
            AuthToken token = new AuthToken(sessionId);
1857
            String principal = params.get("principal")[0];
1858
            String permission = params.get("permission")[0];
1859
            String permissionType = params.get("permissionType")[0];
1860
            String permissionOrder = params.get("permissionOrder")[0];
1861
            String setSystemMetadata = params.get("setsystemmetadata")[0];
1862
            boolean ssm = false;
1863
            if(setSystemMetadata.equals("true") || setSystemMetadata.equals("TRUE") ||
1864
                    setSystemMetadata.equals("yes"))
1865
            {
1866
                ssm = true;
1867
            }
1868
            CrudService cs = CrudService.getInstance();
1869
            //TODO: remove the setsystemmetadata param and set this so the systemmetadata always gets set
1870
            cs.setAccess(token, id, principal, permission, permissionType, permissionOrder, ssm);
1871
        }
1872
        catch(Exception e)
1873
        {
1874
            response.setStatus(500);
1875
            printError("Error setting access in ResourceHandler: " + e.getMessage(), response);
1876
            throw e;
1877
        }
1878
    }
1879

    
1880
    /**
1881
     * Earthgrid API > Authentication Service > Login Function : calls MetacatHandler > handleLoginAction
1882
     * 
1883
     * @throws IOException
1884
     */
1885
    private void login() throws IOException {
1886
        PrintWriter out = response.getWriter();
1887
        response.setStatus(200);
1888
        response.setContentType("text/xml");
1889
        handler.handleLoginAction(out, params, request, response);
1890
        out.close();
1891
    }
1892

    
1893
    /**
1894
     * Earthgrid API > Authentication Service > Logout Function : calls MetacatHandler > handleLogoutAction
1895
     * 
1896
     * @throws IOException
1897
     */
1898
    private void logout() throws IOException {
1899
        PrintWriter out = response.getWriter();
1900
        response.setStatus(200);
1901
        response.setContentType("text/xml");
1902
        handler.handleLogoutAction(out, params, request, response);
1903
        out.close();
1904
    }
1905

    
1906
    /**
1907
     * Prints xml response
1908
     * @param message Message to be displayed
1909
     * @param response Servlet response that xml message will be printed 
1910
     * */
1911
    private void printError(String message, HttpServletResponse response) {
1912
        try {
1913
            logMetacat.error("ResourceHandler: Printing error to servlet response: " + message);
1914
            PrintWriter out = response.getWriter();
1915
            response.setContentType("text/xml");
1916
            out.println("<?xml version=\"1.0\"?>");
1917
            out.println("<error>");
1918
            out.println(message);
1919
            out.println("</error>");
1920
            out.close();
1921
        } catch (IOException e) {
1922
            e.printStackTrace();
1923
        }
1924
    }
1925
    
1926
    /**
1927
     * serialize a D1 exception using jibx
1928
     * @param e
1929
     * @param out
1930
     */
1931
    private void serializeException(BaseException e, OutputStream out) {
1932
        // TODO: Use content negotiation to determine which return format to use
1933
        response.setContentType("text/xml");
1934
        response.setStatus(e.getCode());
1935
        
1936
        logMetacat.error("ResourceHandler: Serializing exception with code " + e.getCode() + ": " + e.getMessage());
1937
        e.printStackTrace();
1938
        
1939
        try {
1940
            IOUtils.write(e.serialize(BaseException.FMT_XML), out);
1941
        } catch (IOException e1) {
1942
            logMetacat.error("Error writing exception to stream. " 
1943
                    + e1.getMessage());
1944
        }
1945
    }
1946
    
1947
    /**
1948
     * create a new ServiceMethod declaration
1949
     * @param name
1950
     * @param rest
1951
     * @param implemented
1952
     * @return
1953
     */
1954
    private ServiceMethod getServiceMethod(String name, String rest, boolean implemented)
1955
    {
1956
        ServiceMethod sm = new ServiceMethod();
1957
        sm.setImplemented(implemented);
1958
        sm.setName(name);
1959
        sm.setRest(rest);
1960
        return sm;
1961
    }
1962

    
1963
}
(4-4/5)