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

    
36
import java.security.NoSuchAlgorithmException;
37
import java.sql.SQLException;
38
import java.text.DateFormat;
39
import java.text.ParseException;
40
import java.text.ParsePosition;
41
import java.text.SimpleDateFormat;
42

    
43

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

    
70
import edu.ucsb.nceas.metacat.AccessionNumberException;
71
import edu.ucsb.nceas.metacat.DBUtil;
72
import edu.ucsb.nceas.metacat.IdentifierManager;
73
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
74
import edu.ucsb.nceas.metacat.MetaCatServlet;
75
import edu.ucsb.nceas.metacat.MetacatHandler;
76
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
77
import edu.ucsb.nceas.metacat.dataone.CrudService;
78
import edu.ucsb.nceas.metacat.dataone.HealthService;
79
import edu.ucsb.nceas.metacat.properties.PropertyService;
80
import edu.ucsb.nceas.metacat.service.SessionService;
81
import edu.ucsb.nceas.metacat.util.RequestUtil;
82
import edu.ucsb.nceas.metacat.util.SystemUtil;
83
import edu.ucsb.nceas.metacat.util.SessionData;
84
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
85

    
86
import org.dataone.service.streaming.util.StreamUtil;
87

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

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

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

    
205
    /**HTTP Verb GET*/
206
    public static final byte GET = 1;
207
    /**HTTP Verb POST*/
208
    public static final byte POST = 2;
209
    /**HTTP Verb PUT*/
210
    public static final byte PUT = 3;
211
    /**HTTP Verb DELETE*/
212
    public static final byte DELETE = 4;
213
    /**HTTP Verb HEAD*/
214
    public static final byte HEAD = 5;
215

    
216
    /*
217
     * API Resources
218
     */
219
    private static final String RESOURCE_OBJECTS = "object";
220
    private static final String RESOURCE_META = "meta";
221
    private static final String RESOURCE_SESSION = "session";
222
    private static final String RESOURCE_IDENTIFIER = "identifier";
223
    private static final String RESOURCE_LOG = "log";
224
    private static final String RESOURCE_CHECKSUM = "checksum";
225
    private static final String RESOURCE_MONITOR = "monitor";
226
    private static final String RESOURCE_BASE_URL = "d1";
227
    private static final String RESOURCE_REPLICATE = "replicate";
228

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

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

    
256
    private Hashtable<String, String[]> params;
257

    
258
    /**Initializes new instance by setting servlet context,request and response*/
259
    public ResourceHandler(ServletContext servletContext,
260
            HttpServletRequest request, HttpServletResponse response) {
261
        this.servletContext = servletContext;
262
        this.request = request;
263
        this.response = response;
264
    }
265

    
266
    /**
267
     * This function is called from REST APU servlet and handles each request to the servlet 
268
     * 
269
     * @param httpVerb (GET, POST, PUT or DELETE)
270
     */
271
    public void handle(byte httpVerb) {
272
        logMetacat = Logger.getLogger(ResourceHandler.class);
273
        try {
274
            String resource = request.getServletPath();
275
            if(resource.endsWith("d1/") || resource.endsWith("d1"))
276
            {
277
                resource = RESOURCE_BASE_URL;
278
            }
279
            else
280
            {
281
                //substring off the /d1/
282
                resource = resource.substring(resource.indexOf("d1/") + 3, resource.length());
283
                resource = resource.trim();
284
            }
285
            
286
            String verb = "";
287
            
288
            System.out.println("handling verb " + httpVerb + " request with resource '" + resource + "'");
289
            System.out.println("resource: '" + resource + "'");
290
            System.out.println("resource_monitor: '" + RESOURCE_MONITOR + "'");
291
            boolean status = false;
292
            loadSessionData();
293

    
294
            if (resource != null) {
295
                //resource = request.getServletPath().substring(1);
296

    
297
                params = new Hashtable<String, String[]>();
298
                initParams();
299

    
300
                Timer timer = new Timer();
301
                handler = new MetacatHandler(timer);
302

    
303
                if(resource.equals(RESOURCE_BASE_URL)) {
304
                    //node registry response
305
                    System.out.println("Using resource 'd1' (node registry response)");
306
                    createNodeResponse();
307
                    status = true;
308
                    
309
                } else if (resource.equals(RESOURCE_SESSION) && 
310
                        httpVerb == POST && 
311
                        params.get(FUNCTION_KEYWORD) != null) {
312
                    System.out.println("Using resource 'session'");
313
                    //System.out.println("function_keyword: " + params.get(FUNCTION_KEYWORD)[0]);
314
                    if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_LOGIN)) {
315
                        login();
316
                        status = true;
317
                    } else if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_LOGOUT)) {
318
                        logout();
319
                        status = true;
320
                    } else if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_SET_ACCESS)) {
321
                        setaccess();
322
                        status = true;
323
                        System.out.println("done setting access");
324
                    }
325
                } else if (resource.equals(RESOURCE_META)) {
326
                    System.out.println("Using resource 'meta'");
327
                    if(params != null && params.get(FUNCTION_KEYWORD) != null &&
328
                            params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_GENERATE_MISSING_SYSTEM_METADATA))
329
                    { 
330
                        status = true;
331
                    }
332
                    else
333
                    {
334
                        String objectId = request.getPathInfo();
335
                        if (objectId != null && objectId.length() > 1) 
336
                        {
337
                            objectId = request.getPathInfo().substring(1);
338
                        }
339
                        getSystemMetadataObject(objectId);
340
                        status = true;
341
                    }
342

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

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

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

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

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

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

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

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

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

    
952
        String name = null;
953
        String[] value = null;
954
        Enumeration paramlist = request.getParameterNames();
955
        while (paramlist.hasMoreElements()) {
956
            name = (String) paramlist.nextElement();
957
            value = request.getParameterValues(name);
958
            params.put(name, value);
959
        }
960
    }
961

    
962
    /**
963
     * 
964
     * Load user details of metacat session from the request 
965
     * 
966
     */
967
    private void loadSessionData()
968
      throws Exception
969
    {
970
        SessionData sessionData = RequestUtil.getSessionData(request);
971
        try
972
        {
973
            username = null;
974
            password = null;
975
            groupNames = null;
976
            sessionId = null;
977
            
978
            boolean validSession = false;
979
            SessionService ss = SessionService.getInstance();
980
            System.out.println("sessionData: " + sessionData);
981
            if(sessionData == null)
982
            {
983
                username = "public";
984
                sessionId = "0";
985
                System.out.println("sessiondata is null.  Creating a public session.");
986
                return;
987
            }
988
            
989
            System.out.println("username: " + sessionData.getUserName());
990
            System.out.println("sessionid: " + sessionData.getId());
991
            //validate the session
992
            if(ss.isSessionRegistered(sessionData.getId()) && 
993
               !(sessionData.getUserName().equals("public") || sessionData.getId().equals("0")))
994
            {
995
                validSession = true;
996
            }
997
            
998
            if(validSession)
999
            {
1000
                //if the session is valid, set these variables
1001
                username = sessionData.getUserName();
1002
                password = sessionData.getPassword();
1003
                groupNames = sessionData.getGroupNames();
1004
                sessionId = sessionData.getId();
1005
                System.out.println("setting sessionid to " + sessionId);
1006
                System.out.println("username: " + username);
1007
            }
1008
            
1009
            //if the session is not valid or the username is null, set
1010
            //username to public
1011
            if (username == null) 
1012
            {
1013
                System.out.println("setting username to public.");
1014
                username = "public";
1015
            }
1016
        }
1017
        catch(Exception e)
1018
        {
1019
            e.printStackTrace();
1020
            throw new Exception("Could not load the session data: " + e.getClass() + ": " + e.getMessage());
1021
        }
1022
    }
1023

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

    
1050
    /**
1051
     * Earthgrid API > Identifier Service > getAllDocIds Function : 
1052
     * calls MetacatHandler > handleGetAllDocidsAction
1053
     * @throws IOException
1054
     */
1055
    private void getAllDocIds() throws IOException {
1056
        PrintWriter out = response.getWriter();
1057
        response.setStatus(200);
1058
        response.setContentType("text/xml");
1059
        handler.handleGetAllDocidsAction(out, params, response);
1060
        out.close();
1061
    }
1062

    
1063
    /**
1064
     * Earthgrid API > Identifier Service > getNextRevision Function : 
1065
     * calls MetacatHandler > handleGetRevisionAndDocTypeAction
1066
     * @param guid
1067
     * @throws IOException
1068
     */
1069
    private void getNextRevision(String guid) throws IOException 
1070
    {
1071
        params.put("docid", new String[] { guid });
1072
        PrintWriter out = response.getWriter();
1073
        response.setStatus(200);
1074
        response.setContentType("text/xml");
1075
        //handler.handleGetRevisionAndDocTypeAction(out, params);
1076

    
1077
        try {
1078
            // Make sure there is a docid
1079
            if (guid == null || guid.equals("")) {
1080
                throw new Exception("User didn't specify docid!");
1081
            }
1082

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

    
1099
            out.println("<?xml version=\"1.0\"?>");
1100
            out.print("<next-revision>");
1101
            out.print(revision);
1102
            out.print("</next-revision>");
1103

    
1104
        } catch (Exception e) {
1105
            // Handle exception
1106
            response.setStatus(500);
1107
            out.println("<?xml version=\"1.0\"?>");
1108
            out.println("<error>");
1109
            out.println(e.getClass() + ": " + e.getMessage());
1110
            out.println("</error>");
1111
        }
1112

    
1113
        out.close();
1114
    }
1115

    
1116
    /**
1117
     * Earthgrid API > Identifier Service > getNextObject Function : 
1118
     * calls MetacatHandler > handleGetMaxDocidAction
1119
     * @throws IOException
1120
     */
1121
    private void getNextObject() throws IOException {
1122
        PrintWriter out = response.getWriter();
1123
        response.setStatus(200);
1124
        response.setContentType("text/xml");
1125
        handler.handleGetMaxDocidAction(out, params, response);
1126
        out.close();
1127
    }
1128

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

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

    
1444
            DBQuery metacat = new DBQuery();
1445

    
1446
            boolean useXMLIndex = (new Boolean(PropertyService
1447
                    .getProperty("database.usexmlindex"))).booleanValue();
1448
            String xmlquery = "query"; // we don't care the query in resultset,
1449
            // the query can be anything
1450
            PrintWriter out = null; // we don't want metacat result, so set out null
1451

    
1452
            // parameter: queryspecification, user, group, usingIndexOrNot
1453
            StringBuffer result = metacat.createResultDocument(xmlquery,
1454
                    metacatQuery, out, username, groupNames, useXMLIndex);
1455

    
1456
            // create result set transfer       
1457
            String saxparser = PropertyService.getProperty("xml.saxparser");
1458
            MetacatResultsetParser metacatResultsetParser = new MetacatResultsetParser(
1459
                    new StringReader(result.toString()), saxparser, queryType
1460
                            .getNamespace().get_value());
1461
            ResultsetType records = metacatResultsetParser.getEcogridResult();
1462

    
1463
            System.out
1464
                    .println(EcogridResultsetTransformer.toXMLString(records));
1465
            response.setContentType("text/xml");
1466
            out = response.getWriter();
1467
            out.print(EcogridResultsetTransformer.toXMLString(records));
1468

    
1469
        } catch (Exception e) {
1470
            e.printStackTrace();
1471
        }*/
1472
        response.setContentType("text/xml");
1473
        response.setStatus(501);
1474
        PrintWriter out = response.getWriter();
1475
        out.print("<error>Query operation not yet supported by Metacat.</error>");
1476
        out.close();
1477
    }
1478
    
1479
    private String streamToString(InputStream is)
1480
    throws IOException
1481
    {
1482
        return IOUtil.toString(is);
1483
    }
1484

    
1485
    private InputStream stringToStream(String s)
1486
    throws IOException
1487
    {
1488
        ByteArrayInputStream bais = new ByteArrayInputStream(s.getBytes(MetaCatServlet.DEFAULT_ENCODING));
1489
        return bais;
1490
    }
1491
    
1492
    /**
1493
     * locate the boundary marker for an MMP
1494
     * @param is
1495
     * @return
1496
     * @throws IOException
1497
     */
1498
    protected static String[] findBoundaryString(InputStream is)
1499
        throws IOException
1500
    {
1501
        String[] endResult = new String[2];
1502
        String boundary = "";
1503
        String searchString = "boundary=";
1504
        boolean doneWithCurrentArray = false;
1505
        byte[] b = new byte[1024];
1506
        int numbytes = is.read(b, 0, 1024);
1507

    
1508
        while(numbytes != -1)
1509
        {
1510
            String s = new String(b, 0, numbytes);
1511
            int searchStringIndex = s.indexOf(searchString);
1512
            
1513
            if(s.indexOf("\"", searchStringIndex + searchString.length() + 1) == -1)
1514
            { //the end of the boundary is in the next byte array
1515
                boundary = s.substring(searchStringIndex + searchString.length() + 1, s.length());
1516
            }
1517
            else if(!boundary.startsWith("--"))
1518
            { //we can read the whole boundary from this byte array
1519
                boundary = s.substring(searchStringIndex + searchString.length() + 1, 
1520
                    s.indexOf("\"", searchStringIndex + searchString.length() + 1));
1521
                boundary = "--" + boundary;
1522
                endResult[0] = boundary;
1523
                endResult[1] = s.substring(s.indexOf("\"", searchStringIndex + searchString.length() + 1) + 1,
1524
                        s.length());
1525
                break;
1526
            }
1527
            else
1528
            { //we're now reading the 2nd byte array to get the rest of the boundary
1529
                searchString = "\"";
1530
                searchStringIndex = s.indexOf(searchString);
1531
                boundary += s.substring(0, searchStringIndex);
1532
                boundary = "--" + boundary;
1533
                endResult[0] = boundary;
1534
                endResult[1] = s.substring(s.indexOf("\"", searchStringIndex + searchString.length() + 1) + 1,
1535
                        s.length());
1536
                break;
1537
            }
1538
        }
1539
        System.out.println("boundary is: '" + boundary + "'");
1540
        return endResult;
1541
    }
1542
    
1543
    /**
1544
     * return the directory where temp files are stored
1545
     * @return
1546
     */
1547
    private static File getTempDirectory()
1548
    {
1549
        File tmpDir = null;
1550
        Logger logMetacat = Logger.getLogger(ResourceHandler.class);
1551
        try
1552
        {
1553
            tmpDir = new File(PropertyService.getProperty("application.tempDir"));
1554
        }
1555
        catch(PropertyNotFoundException pnfe)
1556
        {
1557
            logMetacat.error("ResourceHandler.writeMMPPartstoFiles: " +
1558
                    "application.tmpDir not found.  Using /tmp instead.");
1559
            tmpDir = new File("/tmp");
1560
        }
1561
        return tmpDir;
1562
    }
1563
    
1564
    /**
1565
     * return a tmp file with a given name
1566
     * @param name
1567
     * @return
1568
     */
1569
    private static File getTempFile(String name)
1570
    {
1571
        File tmpDir = getTempDirectory();
1572
        File f = new File(tmpDir, name);
1573
        return f;
1574
    }
1575
    
1576
    /**
1577
     * return a temp file with a default name
1578
     * @return
1579
     */
1580
    private static File getTempFile()
1581
    {
1582
        return getTempFile(new Date().getTime() + ".tmp");
1583
    }
1584
    
1585
    /**
1586
     * Earthgrid API > Put Service >Put Function : calls MetacatHandler > handleInsertOrUpdateAction 
1587
     * 
1588
     * @param guid - ID of data object to be inserted or updated.  If action is update, the pid
1589
     *               is the existing pid.  If insert, the pid is the new one
1590
     * @throws IOException
1591
     */
1592
    private void putObject(String pid, String action) {
1593
        System.out.println("ResourceHandler: putObject with pid " + pid);
1594
        logMetacat.debug("Entering putObject: " + pid + "/" + action);
1595
        OutputStream out = null;
1596
        try {
1597
            out = response.getOutputStream();
1598
            response.setStatus(200);
1599
            response.setContentType("text/xml");
1600
        } catch (IOException e1) {
1601
            logMetacat.error("Could not get the output stream for writing in putObject");
1602
        }
1603
        try {
1604
            
1605
            // Read the incoming data from its Mime Multipart encoding
1606
            logMetacat.debug("Disassembling MIME multipart form");
1607
            InputStream object = null;
1608
            InputStream sysmeta = null;
1609
            Map<String, List<String>> multipartparams;
1610
            
1611
            try
1612
            {
1613
                //String req = IOUtils.toString(request.getInputStream());
1614
                //System.out.println("request: " + req);
1615
                //InputStream reqStr = IOUtils.toInputStream(req);
1616
                InputStream reqStr = request.getInputStream();
1617
                
1618
                //handle MMP inputs
1619
                File tmpDir = getTempDirectory();
1620
                File tmpSMFile = new File(tmpDir + 
1621
                        ".sysmeta." + new Date().getTime() + ".tmp");
1622
                System.out.println("temp dir: " + tmpDir.getAbsolutePath());
1623
                MultipartRequestResolver mrr = new MultipartRequestResolver(
1624
                        tmpDir.getAbsolutePath(), 1000000000, 0);
1625
                MultipartRequest mr = mrr.resolveMultipart(request);
1626
                System.out.println("resolved multipart request");
1627
                Map<String, File> files = mr.getMultipartFiles();
1628
                if(files == null)
1629
                {
1630
                    throw new ServiceFailure("1202", "create/update must have multipart files with names 'object' and 'sysmeta'");
1631
                }
1632
                System.out.println("got multipart files");
1633
                
1634
                if(files.keySet() == null)
1635
                {
1636
                    System.out.println("No file keys in MMP request.");
1637
                    throw new ServiceFailure("1202", "No file keys found in MMP.  " +
1638
                            "create/update must have multipart files with names 'object' and 'sysmeta'");
1639
                }
1640

    
1641
		// for logging purposes, dump out the key-value pairs that constitute the request
1642
		// 3 types exist: request params, multipart params, and multipart files
1643
                Iterator it = files.keySet().iterator();
1644
                System.out.println("iterating through request parts: " + it);
1645
                while(it.hasNext())
1646
                {
1647
                    String key = (String)it.next();
1648
                    System.out.println("files key: " + key);
1649
                    System.out.println("files value: " + files.get(key));
1650
                }
1651
                
1652
                multipartparams = mr.getMultipartParameters();
1653
                it = multipartparams.keySet().iterator();
1654
                while(it.hasNext())
1655
                {
1656
                    String key = (String)it.next();
1657
                    System.out.println("multipartparams key: " + key);
1658
                    System.out.println("multipartparams value: " + multipartparams.get(key));
1659
                }
1660
                
1661
                it = params.keySet().iterator();
1662
                while(it.hasNext())
1663
                {
1664
                    String key = (String)it.next();
1665
                    System.out.println("param key: " + key);
1666
                    System.out.println("param value: " + params.get(key));
1667
                }
1668
		System.out.println("done iterating the request...");
1669

    
1670
                File smFile = files.get("sysmeta");
1671
		if (smFile == null) 
1672
		    throw new InvalidRequest("1102", "Missing the required file-part 'sysmeta' from the multipart request.");
1673
                System.out.println("smFile: " + smFile.getAbsolutePath());
1674
                sysmeta = new FileInputStream(smFile);
1675
                File objFile = files.get("object");
1676
		if (objFile == null) 
1677
		    throw new InvalidRequest("1102", "Missing the required file-part 'object' from the multipart request.");
1678

    
1679
                System.out.println("objectfile: " + objFile.getAbsolutePath());
1680
                object = new FileInputStream(objFile);
1681
                
1682
                /*String obj = IOUtils.toString(object);
1683
                String sm = IOUtils.toString(sysmeta);
1684
                System.out.println("object: " + obj);
1685
                System.out.println("sm: " + sm);
1686
                object = IOUtils.toInputStream(obj);
1687
                sysmeta = IOUtils.toInputStream(sm);*/
1688
                
1689
            }
1690
            catch(org.apache.commons.fileupload.FileUploadException fue)
1691
            {
1692
                throw new ServiceFailure("1202", "Could not upload MMP files: " + fue.getMessage());
1693
            }
1694
            catch(IOException ioe)
1695
            {
1696
                throw new ServiceFailure("1202", 
1697
                        "IOException when processing Mime Multipart: " + ioe.getMessage());
1698
            }
1699
            catch(Exception e)
1700
            {
1701
                throw new ServiceFailure("1202", "Error handling MMP upload: " + e.getClass() + ": " + e.getMessage());
1702
            }
1703
            
1704
            if ( action.equals(FUNCTION_NAME_INSERT)) { //handle inserts
1705

    
1706
                // Check if the objectId exists
1707
                IdentifierManager im = IdentifierManager.getInstance();
1708
                if (im.identifierExists(pid)) {
1709
                    throw new IdentifierNotUnique("1000", "Identifier is already in use: " + pid);
1710
                }
1711

    
1712
                logMetacat.debug("Commence creation...");
1713
                IBindingFactory bfact =
1714
                    BindingDirectory.getFactory(SystemMetadata.class);
1715
                IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1716
                SystemMetadata smd = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
1717

    
1718
                CrudService cs = CrudService.getInstance();
1719
                AuthToken token = new AuthToken(sessionId); 
1720
                cs.setParamsFromRequest(request);
1721
                Identifier id = new Identifier();
1722
                id.setValue(pid);
1723
                System.out.println("creating object with pid " + id.getValue());
1724
                Identifier rId = cs.create(token, id, object, smd);
1725
                serializeServiceType(Identifier.class, rId, out);
1726
                
1727
            } else if (action.equals(FUNCTION_NAME_UPDATE)) { //handle updates
1728

    
1729
            	// Check if the objectId exists
1730
                IdentifierManager im = IdentifierManager.getInstance();
1731
                if (!im.identifierExists(pid)) {
1732
                    throw new NotFound("1280", "The pid you are trying to update does not exist: " + pid);
1733
                }
1734
                // check that the newPid parameter was provided and it doesn't exist
1735
                if(multipartparams.get("newPid") == null)
1736
                    throw new InvalidRequest("1202", "'newPid' must be contained in the request parameters.");
1737
                String newPidString = multipartparams.get("newPid").get(0);
1738
                if (im.identifierExists(newPidString)) 
1739
                    throw new IdentifierNotUnique("1220", "Identifier is already in use: " + newPidString);
1740
               
1741
                
1742
                Identifier newPid = new Identifier();
1743
                Identifier obsoletedPid = new Identifier();
1744
                newPid.setValue(newPidString);
1745
                obsoletedPid.setValue(pid);
1746
               
1747
            	
1748
                CrudService cs = CrudService.getInstance();
1749
                AuthToken token = new AuthToken(sessionId);
1750

    
1751
                logMetacat.debug("Commence update...");
1752
                
1753
                //get the systemmetadata
1754
                IBindingFactory bfact =
1755
                	BindingDirectory.getFactory(SystemMetadata.class);
1756
                IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1757
                SystemMetadata smd = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
1758

    
1759
                cs.setParamsFromRequest(request);
1760
                Identifier rId = cs.update(token, newPid, object, obsoletedPid, smd);
1761
                serializeServiceType(Identifier.class, rId, out);
1762
            } else {
1763
                throw new InvalidRequest("1000", "Operation must be create or update.");
1764
            }
1765
            
1766
            //clean up the MMP files
1767
            //parts.get("systemmetadata").delete();
1768
            //parts.get("object").delete();
1769
        } catch (NotAuthorized e) {
1770
            response.setStatus(500);
1771
            serializeException(e, out);
1772
        } catch (InvalidToken e) {
1773
            response.setStatus(500);
1774
            serializeException(e, out);
1775
        } catch (ServiceFailure e) {
1776
            response.setStatus(500);
1777
            serializeException(e, out);
1778
        } catch (NotFound e) {
1779
            response.setStatus(500);
1780
            serializeException(e, out);
1781
        } catch (IdentifierNotUnique e) {
1782
            response.setStatus(500);
1783
            serializeException(e, out);
1784
        } catch (UnsupportedType e) {
1785
            response.setStatus(500);
1786
            serializeException(e, out);
1787
        } catch (InsufficientResources e) {
1788
            response.setStatus(500);
1789
            serializeException(e, out);
1790
        } catch (InvalidSystemMetadata e) {
1791
            response.setStatus(500);
1792
            serializeException(e, out);
1793
        } catch (NotImplemented e) {
1794
            response.setStatus(500);
1795
            serializeException(e, out);
1796
        } catch (InvalidRequest e) {
1797
            response.setStatus(500);
1798
            serializeException(e, out);
1799
        } /*catch (MessagingException e) {
1800
            ServiceFailure sf = new ServiceFailure("1000", e.getMessage());
1801
            serializeException(sf, out);
1802
        } catch (IOException e) {
1803
            response.setStatus(500);
1804
            ServiceFailure sf = new ServiceFailure("1000", e.getMessage());
1805
            serializeException(sf, out);
1806
        }*/ catch (JiBXException e) {
1807
            response.setStatus(500);
1808
            e.printStackTrace(System.out);
1809
            InvalidSystemMetadata ism = new InvalidSystemMetadata("1080", e.getMessage());
1810
            serializeException(ism, out);
1811
        }
1812
    }
1813

    
1814
    /**
1815
     * Handle delete 
1816
     * @param guid ID of data object to be deleted
1817
     * @throws IOException
1818
     */
1819
    private void deleteObject(String guid) throws IOException 
1820
    {
1821
        // Look up the localId for this global identifier
1822
        System.out.println("!!!!!!!!!!!!!!!!!deleting object " + guid);
1823
        IdentifierManager im = IdentifierManager.getInstance();
1824
        String localId = "";
1825
        OutputStream out = response.getOutputStream();
1826
        response.setStatus(200);
1827
        try {
1828
            localId = im.getLocalId(guid);
1829
        } catch (McdbDocNotFoundException e) {
1830
            NotFound nf = new NotFound("1340", "Document with guid " + guid + " not found.");
1831
            response.setStatus(404);
1832
            serializeException(nf, out);
1833
        }
1834
       
1835
        AuthToken token = new AuthToken(sessionId);
1836
        CrudService cs = CrudService.getInstance();
1837
        Identifier id = new Identifier();
1838
        id.setValue(guid);
1839
        try
1840
        {
1841
            System.out.println("Calling delete");
1842
            cs.delete(token, id);
1843
            serializeServiceType(Identifier.class, id, out);
1844
        } 
1845
        catch (NotAuthorized e) {
1846
            response.setStatus(500);
1847
            serializeException(e, out);
1848
        } catch (InvalidToken e) {
1849
            response.setStatus(500);
1850
            serializeException(e, out);
1851
        } catch (ServiceFailure e) {
1852
            response.setStatus(500);
1853
            serializeException(e, out);
1854
        } catch (NotImplemented e) {
1855
            response.setStatus(500);
1856
            serializeException(e, out);
1857
        } catch (InvalidRequest e) {
1858
            response.setStatus(500);
1859
            serializeException(e, out);
1860
        } catch(NotFound e) {
1861
            response.setStatus(500);
1862
            serializeException(e, out);
1863
        } catch(JiBXException e) {
1864
            response.setStatus(500);
1865
            serializeException(new ServiceFailure("1350", "JiBXException: " + e.getMessage()), out);
1866
        }
1867
        out.close();
1868
    }
1869
    
1870
    /**
1871
     * set the access perms on a document
1872
     * @throws IOException
1873
     */
1874
    private void setaccess() throws Exception
1875
    {
1876
        try
1877
        {
1878
            String guid = params.get("guid")[0];
1879
            Identifier id = new Identifier();
1880
            id.setValue(guid);
1881
            AuthToken token = new AuthToken(sessionId);
1882
            String principal = params.get("principal")[0];
1883
            String permission = params.get("permission")[0];
1884
            String permissionType = params.get("permissionType")[0];
1885
            String permissionOrder = params.get("permissionOrder")[0];
1886
            String setSystemMetadata = params.get("setsystemmetadata")[0];
1887
            boolean ssm = false;
1888
            if(setSystemMetadata.equals("true") || setSystemMetadata.equals("TRUE") ||
1889
                    setSystemMetadata.equals("yes"))
1890
            {
1891
                ssm = true;
1892
            }
1893
            CrudService cs = CrudService.getInstance();
1894
            //TODO: remove the setsystemmetadata param and set this so the systemmetadata always gets set
1895
            cs.setAccess(token, id, principal, permission, permissionType, permissionOrder, ssm);
1896
        }
1897
        catch(Exception e)
1898
        {
1899
            response.setStatus(500);
1900
            printError("Error setting access in ResourceHandler: " + e.getClass() + ": " + e.getMessage(), response);
1901
            throw e;
1902
        }
1903
    }
1904

    
1905
    /**
1906
     * Earthgrid API > Authentication Service > Login Function : calls MetacatHandler > handleLoginAction
1907
     * 
1908
     * @throws IOException
1909
     */
1910
    private void login() throws IOException {
1911
        PrintWriter out = response.getWriter();
1912
        response.setStatus(200);
1913
        response.setContentType("text/xml");
1914
        handler.handleLoginAction(out, params, request, response);
1915
        out.close();
1916
    }
1917

    
1918
    /**
1919
     * Earthgrid API > Authentication Service > Logout Function : calls MetacatHandler > handleLogoutAction
1920
     * 
1921
     * @throws IOException
1922
     */
1923
    private void logout() throws IOException {
1924
        PrintWriter out = response.getWriter();
1925
        response.setStatus(200);
1926
        response.setContentType("text/xml");
1927
        handler.handleLogoutAction(out, params, request, response);
1928
        out.close();
1929
    }
1930

    
1931
    /**
1932
     * Prints xml response
1933
     * @param message Message to be displayed
1934
     * @param response Servlet response that xml message will be printed 
1935
     * */
1936
    private void printError(String message, HttpServletResponse response) {
1937
        try {
1938
            logMetacat.error("ResourceHandler: Printing error to servlet response: " + message);
1939
            PrintWriter out = response.getWriter();
1940
            response.setContentType("text/xml");
1941
            out.println("<?xml version=\"1.0\"?>");
1942
            out.println("<error>");
1943
            out.println(message);
1944
            out.println("</error>");
1945
            out.close();
1946
        } catch (IOException e) {
1947
            e.printStackTrace();
1948
        }
1949
    }
1950
    
1951
    /**
1952
     * serialize a D1 exception using jibx
1953
     * @param e
1954
     * @param out
1955
     */
1956
    private void serializeException(BaseException e, OutputStream out) {
1957
        // TODO: Use content negotiation to determine which return format to use
1958
        response.setContentType("text/xml");
1959
        response.setStatus(e.getCode());
1960
        
1961
        logMetacat.error("ResourceHandler: Serializing exception with code " + e.getCode() + ": " + e.getMessage());
1962
        e.printStackTrace();
1963
        
1964
        try {
1965
            IOUtils.write(e.serialize(BaseException.FMT_XML), out);
1966
        } catch (IOException e1) {
1967
            logMetacat.error("Error writing exception to stream. " 
1968
                    + e1.getMessage());
1969
        }
1970
    }
1971
    
1972
    /**
1973
     * create a new ServiceMethod declaration
1974
     * @param name
1975
     * @param rest
1976
     * @param implemented
1977
     * @return
1978
     */
1979
    private ServiceMethod getServiceMethod(String name, String rest, boolean implemented)
1980
    {
1981
        ServiceMethod sm = new ServiceMethod();
1982
        sm.setImplemented(implemented);
1983
        sm.setName(name);
1984
        sm.setRest(rest);
1985
        return sm;
1986
    }
1987

    
1988
}
(4-4/5)