Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2011 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author: Serhan AKIN $'
7
 *     '$Date: 2009-06-13 15:28:13 +0300  $'
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 2 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22
 */
23
package edu.ucsb.nceas.metacat.restservice;
24

    
25
import java.io.*;
26
import java.net.URL;
27
import java.util.*;
28

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

    
40

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
298
                if(resource.equals(RESOURCE_BASE_URL)) {
299
                    //node registry response
300
                    System.out.println("Using resource 'd1' (node registry response)");
301
                    createNodeResponse();
302
                    status = true;
303
                    
304
                } else if (resource.equals(RESOURCE_SESSION) && 
305
                        httpVerb == POST && 
306
                        params.get(FUNCTION_KEYWORD) != null) {
307
                    System.out.println("Using resource 'session'");
308
                    //System.out.println("function_keyword: " + params.get(FUNCTION_KEYWORD)[0]);
309
                    if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_LOGIN)) {
310
                        login();
311
                        status = true;
312
                    } else if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_LOGOUT)) {
313
                        logout();
314
                        status = true;
315
                    } else if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_SET_ACCESS)) {
316
                        setaccess();
317
                        status = true;
318
                        System.out.println("done setting access");
319
                    }
320
                } else if (resource.equals(RESOURCE_META)) {
321
                    System.out.println("Using resource 'meta'");
322
                    if(params != null && params.get(FUNCTION_KEYWORD) != null &&
323
                            params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_GENERATE_MISSING_SYSTEM_METADATA))
324
                    { //generate system metadata for any object that is
325
                        //a) not system metadata itself
326
                        //b) does not already have a system metadata id in the systemmetadata table
327
                        //c) not a BIN object (data)
328
                        //TODO: check if we need this anymore.  Might be superceded
329
                        //by MetacatPopulator
330
                        generateMissingSystemMetadata();
331
                        status = true;
332
                    }
333
                    else
334
                    {
335
                        String objectId = request.getPathInfo();
336
                        if (objectId != null && objectId.length() > 1) 
337
                        {
338
                            objectId = request.getPathInfo().substring(1);
339
                        }
340
                        getSystemMetadataObject(objectId);
341
                        status = true;
342
                    }
343

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

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

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

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

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

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

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

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

    
429
                } else if(resource.equals(RESOURCE_CHECKSUM)) {
430
                    System.out.println("Using resource 'checksum'");
431
                    //handle checksum requests
432
                    if(httpVerb == GET)
433
                    {
434
                        String checksumAlgorithm = "MD5";
435
                    
436
                        String guid = request.getPathInfo();
437
                        if (guid != null && guid.length() > 1)
438
                            guid = request.getPathInfo().substring(1); //trim the slash
439
                        
440
                        Identifier guidid = new Identifier();
441
                        guidid.setValue(guid);
442
                        AuthToken token = new AuthToken(sessionId);
443
                        try
444
                        {
445
                            checksumAlgorithm = params.get("checksumAlgorithm")[0];
446
                        }
447
                        catch(Exception e)
448
                        {
449
                            //do nothing.  default to MD5
450
                        }
451
                        System.out.println("getting checksum for object " + guid +
452
                                " with algorithm " + checksumAlgorithm);
453
                        try
454
                        {
455
                            Checksum c = CrudService.getInstance().getChecksum(token, guidid, checksumAlgorithm);
456
                            System.out.println("got checksum " + c.getValue());
457
                            response.setStatus(200);
458
                            System.out.println("serializing response");
459
                            serializeServiceType(Checksum.class, c, response.getOutputStream());
460
                            System.out.println("done serializing response.");
461
                        }
462
                        catch(NotAuthorized na)
463
                        {
464
                            na.setDetail_code("1400");
465
                            serializeException(na, response.getOutputStream());
466
                        }
467
                        catch(NotFound nf)
468
                        {
469
                            nf.setDetail_code("1420");
470
                            serializeException(nf, response.getOutputStream());
471
                        }
472
                        catch(InvalidRequest ir)
473
                        {
474
                            ir.setDetail_code("1402");
475
                            serializeException(ir, response.getOutputStream());
476
                        }
477
                        catch(ServiceFailure sf)
478
                        {
479
                            sf.setDetail_code("1410");
480
                            serializeException(sf, response.getOutputStream());
481
                        }
482
                        catch(InvalidToken it)
483
                        {
484
                            it.setDetail_code("1430");
485
                            serializeException(it, response.getOutputStream());
486
                        }
487
                        status = true;
488
                    }
489
                } else if(resource.equals(RESOURCE_MONITOR)) {
490
                    //health monitoring calls
491
                    System.out.println("processing monitor request");
492
                    String pathInfo = request.getPathInfo();
493
                    if(httpVerb == GET)
494
                    {
495
                        System.out.println("verb is GET");
496
                        System.out.println("pathInfo is " + pathInfo);
497
                        pathInfo = pathInfo.substring(1);
498
                        HealthService hs = new HealthService(request, response);
499
                        if (pathInfo.toLowerCase().equals("ping")) {
500
                            System.out.println("processing ping request");
501
                            hs.ping();
502
                        } else if (pathInfo.toLowerCase().equals("status")) {
503
                            System.out.println("processing status request");
504
                            hs.getStatus();
505
                        } else if (pathInfo.toLowerCase().equals("object")) {
506
                            System.out.println("processing object request");
507
                            boolean day = false;
508
                            Identifier pid = null;
509
                            String url = null;
510
                            ObjectFormat of = null;
511
                            Date time = null;
512
                            
513
                            if(params.containsKey("day"))
514
                            {
515
                               day = true; 
516
                            }
517
                            if(params.containsKey("pid"))
518
                            {
519
                                String id = params.get("pid")[0];
520
                                pid = new Identifier();
521
                                pid.setValue(id);
522
                            }
523
                            if(params.containsKey("url"))
524
                            {
525
                                url = params.get("url")[0];
526
                            }
527
                            if(params.containsKey("format"))
528
                            {
529
                                String format = params.get("format")[0];
530
                                of = ObjectFormat.convert(format);
531
                            }
532
                            if(params.containsKey("time"))
533
                            {
534
                                String t = params.get("time")[0];
535
                                time = dateFormat.parse(t);
536
                            }
537
                            
538
                            hs.getObjectStatistics(day, pid, url, of, time);
539
                        } else if (pathInfo.toLowerCase().equals("event")) {
540
                            System.out.println("processing event request");
541
                            boolean day = false;
542
                            Identifier pid = null;
543
                            Date created = null;
544
                            ObjectFormat of = null;
545
                            Date time = null;
546
                            String ipAddress = null;
547
                            String event = null;
548
                            
549
                            if(params.containsKey("day"))
550
                            {
551
                               day = true; 
552
                            }
553
                            if(params.containsKey("pid"))
554
                            {
555
                                String id = params.get("pid")[0];
556
                                pid = new Identifier();
557
                                pid.setValue(id);
558
                            }
559
                            if(params.containsKey("created"))
560
                            {
561
                                String t = params.get("created")[0];
562
                                created = dateFormat.parse(t);
563
                            }
564
                            if(params.containsKey("format"))
565
                            {
566
                                String format = params.get("format")[0];
567
                                of = ObjectFormat.convert(format);
568
                            }
569
                            if(params.containsKey("eventtime"))
570
                            {
571
                                String t = params.get("eventtime")[0];
572
                                time = dateFormat.parse(t);
573
                            }
574
                            if(params.containsKey("ip_address"))
575
                            {
576
                                ipAddress = params.get("ip_address")[0];
577
                            }
578
                            if(params.containsKey("event"))
579
                            {
580
                                event = params.get("event")[0];
581
                            }
582
                            
583
                            hs.getOperationStatistics(day, pid, of, created, time, ipAddress, event);
584
                        }
585
                    }
586
                    status = true;
587
                } else if(resource.equals(RESOURCE_REPLICATE)) {
588
                    System.out.println("processing replicate request");
589
                    replicate(httpVerb, request, response);
590
                    status = true;
591
                }
592
                    
593
                if (!status)
594
                {
595
                    response.setStatus(400);
596
                    printError("Incorrect parameters!", response);
597
                }
598
            } else {
599
                response.setStatus(400);
600
                printError("Incorrect resource!", response);
601
            }
602
        } catch (Exception e) {
603
            logMetacat.error(e.getMessage());
604
            System.out.println("Error in ResourceHandler.handle(): " + e.getMessage());
605
            e.printStackTrace();
606
        }
607
    }
608
    
609
    /**
610
     * handle the /replicate action
611
     * @param httpVerb
612
     * @param request
613
     * @param response
614
     * @throws Exception
615
     */
616
    private void replicate(int httpVerb, HttpServletRequest request, HttpServletResponse response)
617
        throws Exception
618
    {
619
        if(httpVerb == POST)
620
        {
621
            System.out.println("in POST replicate()");
622
            /*InputStream is = request.getInputStream();
623
            String input = IOUtils.toString(is);
624
            System.out.println("input: " + input);
625
            is = IOUtils.toInputStream(input);*/
626
            
627
            File tmpDir = getTempDirectory();
628
            File tmpSMFile = new File(tmpDir + 
629
                    ".sysmeta." + new Date().getTime() + ".tmp");
630
            System.out.println("temp dir: " + tmpDir.getAbsolutePath());
631
            MultipartRequestResolver mrr = new MultipartRequestResolver(
632
                    tmpDir.getAbsolutePath(), 1000000000, 0);
633
            MultipartRequest mr = mrr.resolveMultipart(request);
634
            Map<String, File> files = mr.getMultipartFiles();
635
            Iterator keys = files.keySet().iterator();
636
            while(keys.hasNext())
637
            {
638
                String key = (String)keys.next();
639
                System.out.println("files key: " + key);
640
                System.out.println("files value: " + files.get(key));
641
            }
642
            
643
            Map<String, List<String>> params = mr.getMultipartParameters();
644
            keys = params.keySet().iterator();
645
            while(keys.hasNext())
646
            {
647
                String key = (String)keys.next();
648
                System.out.println("params key: " + key);
649
                System.out.println("params value: " + params.get(key));
650
            }
651
            
652
            //File f = files.get("sysmeta");
653
            //the files are not being keyed by the part name, but rather the filename
654
            File f = files.get(files.keySet().iterator().next());
655
            
656
            System.out.println("file: " + f.getAbsolutePath());
657
            String sourceNode = params.get("sourceNode").get(0);
658
            System.out.println("sourceNode: " + sourceNode);
659
            FileInputStream fis = new FileInputStream(f);
660
            
661
            //lookup the id in the registry
662
            URL url = new URL("http://cn.dataone.org/cn/node");
663
            InputStream urlis = url.openStream();
664
            Map<String,String> m = NodeListParser.parseNodeListFile(urlis);
665
            String nodeUrl = m.get(sourceNode);
666
            System.out.println("sourceNodeId: " + sourceNode);
667
            System.out.println("resolved sourceNodeUrl: " + nodeUrl);
668
            
669
            if(nodeUrl == null)
670
            {
671
                response.setStatus(500);
672
                response.getOutputStream().write(("Member Node id " + 
673
                        sourceNode + " not found in node registry.").getBytes());
674
                response.getOutputStream().close();
675
            }
676
            
677
            //respond to cn with 200/OK
678
            //String s;
679
            //s = "sysmeta: " + IOUtils.toString(fis);
680
            //s += "\n\n";
681
            response.setStatus(200);
682
            //response.getOutputStream().write(("sourceNode: " + sourceNode + "\n\n").getBytes());
683
            //response.getOutputStream().write(("s: " + s).getBytes());
684
            OutputStream out = response.getOutputStream();
685
            out.write("OK\n".getBytes());
686
            out.write(("sourceNodeId: " + sourceNode + "\n").getBytes());
687
            out.write(("sourceNodeUrl: " + nodeUrl + "\n").getBytes());
688
            out.close();
689
            
690
            //parse the systemMetadata
691
            SystemMetadata sm = (SystemMetadata)deserializeServiceType(SystemMetadata.class, fis);
692
            NodeReference nr = sm.getOriginMemberNode();
693
            nr.setValue(sourceNode);
694
            sm.setOriginMemberNode(nr);
695
            //get the document
696
            AuthToken token = new AuthToken(sessionId);
697
            MNode mnode = new MNode(nodeUrl);
698
            //get the doc from the remote host
699
            InputStream docStream = mnode.get(new AuthToken("public"), sm.getIdentifier());
700
            File outputTmpFile = getTempFile();
701
            System.out.println("wrote xml file to " + outputTmpFile.getAbsolutePath());
702
            FileOutputStream outputTmpFileStream = new FileOutputStream(outputTmpFile);
703
            IOUtils.copy(docStream, outputTmpFileStream);
704
            
705
            //verify checksum
706
            System.out.println("verifying checksum");
707
            Checksum sourceFileChecksum = ServiceTypeUtil.checksum(new FileInputStream(outputTmpFile), 
708
                    sm.getChecksum().getAlgorithm());
709
            
710
            String cs1 = sm.getChecksum().getValue();
711
            String cs2 = sourceFileChecksum.getValue();
712
            System.out.println("original checksum: " + cs1);
713
            System.out.println(" created checksum: " + cs2);
714
            
715
            if(!cs1.equals(cs2))
716
            {
717
                System.out.println("ERROR: Checksums do not match!");
718
            }
719
            
720
            //insert the document in local db
721
            //System.out.println("creating new doc");
722
            //CrudService.getInstance().create(token, 
723
            //        sm.getIdentifier(), new FileInputStream(outputTmpFile), sm);
724
            //call cn.setReplicationStatus(guid, COMPLETE)
725
            
726
        }
727
    }
728
    
729
    /**
730
     * create the root node registry response.  
731
     * @throws JiBXException
732
     * @throws IOException
733
     */
734
    private void createNodeResponse() 
735
        throws JiBXException, IOException
736
    {
737
        String nodeName = null;
738
        String nodeId = null;
739
        String nodeUrl = null;
740
        String nodeDesc = null;
741
        
742
        try
743
        {
744
            nodeId = PropertyService.getProperty("dataone.memberNodeId");
745
            nodeName = PropertyService.getProperty("dataone.nodeName");
746
            nodeUrl = PropertyService.getProperty("application.knbSiteURL") + "/" +
747
                PropertyService.getProperty("application.context") + "/d1/";
748
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
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("mn"));
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.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.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.getMessage());
1021
        }
1022
    }
1023
    
1024
    /**
1025
     * generate missing system metadata for any science metadata objects
1026
     * that don't already have it. https://trac.dataone.org/ticket/591
1027
     * 
1028
     * called with POST meta/?op=generatemissingsystemmetadata
1029
     */
1030
    private void generateMissingSystemMetadata()
1031
    {
1032
        AuthToken token = new AuthToken(sessionId);
1033
        CrudService.getInstance().generateMissingSystemMetadata(token);
1034
    }
1035

    
1036
    /**
1037
     *  Earthgrid API > Identifier Service > isRegistered Function : 
1038
     *  calls MetacatHandler > handleIdIsRegisteredAction
1039
     * @param guid
1040
     * @throws IOException
1041
     */
1042
    private void isRegistered(String guid) throws IOException
1043
    {
1044
        
1045
        // Look up the localId for this guid
1046
        IdentifierManager im = IdentifierManager.getInstance();
1047
        String localId = "";
1048
        try {
1049
            localId = im.getLocalId(guid);
1050
        } catch (McdbDocNotFoundException e) {
1051
            // TODO: Need to return the proper DataONE exception
1052
        }
1053
        
1054
        params.put("docid", new String[] { localId });
1055
        PrintWriter out = response.getWriter();
1056
        response.setStatus(200);
1057
        response.setContentType("text/xml");
1058
        handler.handleIdIsRegisteredAction(out, params, response);
1059
        out.close();
1060
    }
1061

    
1062
    /**
1063
     * Earthgrid API > Identifier Service > getAllDocIds Function : 
1064
     * calls MetacatHandler > handleGetAllDocidsAction
1065
     * @throws IOException
1066
     */
1067
    private void getAllDocIds() throws IOException {
1068
        PrintWriter out = response.getWriter();
1069
        response.setStatus(200);
1070
        response.setContentType("text/xml");
1071
        handler.handleGetAllDocidsAction(out, params, response);
1072
        out.close();
1073
    }
1074

    
1075
    /**
1076
     * Earthgrid API > Identifier Service > getNextRevision Function : 
1077
     * calls MetacatHandler > handleGetRevisionAndDocTypeAction
1078
     * @param guid
1079
     * @throws IOException
1080
     */
1081
    private void getNextRevision(String guid) throws IOException 
1082
    {
1083
        params.put("docid", new String[] { guid });
1084
        PrintWriter out = response.getWriter();
1085
        response.setStatus(200);
1086
        response.setContentType("text/xml");
1087
        //handler.handleGetRevisionAndDocTypeAction(out, params);
1088

    
1089
        try {
1090
            // Make sure there is a docid
1091
            if (guid == null || guid.equals("")) {
1092
                throw new Exception("User didn't specify docid!");
1093
            }
1094

    
1095
            // Look up the localId for this guid
1096
            IdentifierManager im = IdentifierManager.getInstance();
1097
            String localId = "";
1098
            try {
1099
                localId = im.getLocalId(guid);
1100
            } catch (McdbDocNotFoundException e) {
1101
                // TODO: Need to return the proper DataONE exception
1102
            }
1103
           
1104
            // Create a DBUtil object
1105
            DBUtil dbutil = new DBUtil();
1106
            // Get a rev and doctype
1107
            String revAndDocType = dbutil
1108
                    .getCurrentRevisionAndDocTypeForGivenDocument(localId);
1109
            int revision = Integer.parseInt(revAndDocType.split(";")[0]) + 1;
1110

    
1111
            out.println("<?xml version=\"1.0\"?>");
1112
            out.print("<next-revision>");
1113
            out.print(revision);
1114
            out.print("</next-revision>");
1115

    
1116
        } catch (Exception e) {
1117
            // Handle exception
1118
            response.setStatus(500);
1119
            out.println("<?xml version=\"1.0\"?>");
1120
            out.println("<error>");
1121
            out.println(e.getMessage());
1122
            out.println("</error>");
1123
        }
1124

    
1125
        out.close();
1126
    }
1127

    
1128
    /**
1129
     * Earthgrid API > Identifier Service > getNextObject Function : 
1130
     * calls MetacatHandler > handleGetMaxDocidAction
1131
     * @throws IOException
1132
     */
1133
    private void getNextObject() throws IOException {
1134
        PrintWriter out = response.getWriter();
1135
        response.setStatus(200);
1136
        response.setContentType("text/xml");
1137
        handler.handleGetMaxDocidAction(out, params, response);
1138
        out.close();
1139
    }
1140

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

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

    
1453
            DBQuery metacat = new DBQuery();
1454

    
1455
            boolean useXMLIndex = (new Boolean(PropertyService
1456
                    .getProperty("database.usexmlindex"))).booleanValue();
1457
            String xmlquery = "query"; // we don't care the query in resultset,
1458
            // the query can be anything
1459
            PrintWriter out = null; // we don't want metacat result, so set out null
1460

    
1461
            // parameter: queryspecification, user, group, usingIndexOrNot
1462
            StringBuffer result = metacat.createResultDocument(xmlquery,
1463
                    metacatQuery, out, username, groupNames, useXMLIndex);
1464

    
1465
            // create result set transfer       
1466
            String saxparser = PropertyService.getProperty("xml.saxparser");
1467
            MetacatResultsetParser metacatResultsetParser = new MetacatResultsetParser(
1468
                    new StringReader(result.toString()), saxparser, queryType
1469
                            .getNamespace().get_value());
1470
            ResultsetType records = metacatResultsetParser.getEcogridResult();
1471

    
1472
            System.out
1473
                    .println(EcogridResultsetTransformer.toXMLString(records));
1474
            response.setContentType("text/xml");
1475
            out = response.getWriter();
1476
            out.print(EcogridResultsetTransformer.toXMLString(records));
1477

    
1478
        } catch (Exception e) {
1479
            e.printStackTrace();
1480
        }*/
1481
        response.setContentType("text/xml");
1482
        response.setStatus(501);
1483
        PrintWriter out = response.getWriter();
1484
        out.print("<error>Query operation not yet supported by Metacat.</error>");
1485
        out.close();
1486
    }
1487
    
1488
    private String streamToString(InputStream is)
1489
    throws IOException
1490
    {
1491
        return IOUtil.toString(is);
1492
    }
1493

    
1494
    private InputStream stringToStream(String s)
1495
    throws IOException
1496
    {
1497
        ByteArrayInputStream bais = new ByteArrayInputStream(s.getBytes(MetaCatServlet.DEFAULT_ENCODING));
1498
        return bais;
1499
    }
1500
    
1501
    /**
1502
     * locate the boundary marker for an MMP
1503
     * @param is
1504
     * @return
1505
     * @throws IOException
1506
     */
1507
    protected static String[] findBoundaryString(InputStream is)
1508
        throws IOException
1509
    {
1510
        String[] endResult = new String[2];
1511
        String boundary = "";
1512
        String searchString = "boundary=";
1513
        boolean doneWithCurrentArray = false;
1514
        byte[] b = new byte[1024];
1515
        int numbytes = is.read(b, 0, 1024);
1516

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

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

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

    
1717
                CrudService cs = CrudService.getInstance();
1718
                AuthToken token = new AuthToken(sessionId); 
1719
                cs.setParamsFromRequest(request);
1720
                Identifier id = new Identifier();
1721
                id.setValue(guid);
1722
                System.out.println("creating object with guid " + id.getValue());
1723
                Identifier rId = cs.create(token, id, object, m);
1724
                serializeServiceType(Identifier.class, rId, out);
1725
                
1726
            } else if (action.equals(FUNCTION_NAME_UPDATE)) { //handle updates
1727
                IdentifierManager im = IdentifierManager.getInstance();
1728
                CrudService cs = CrudService.getInstance();
1729
                Identifier obsoletedGuid = new Identifier();
1730
                Identifier id = new Identifier();
1731
                id.setValue(guid);
1732
                AuthToken token = new AuthToken(sessionId);
1733
                
1734
                //do some checks
1735
                if(mutlipartparams.get("obsoletedGuid") == null)
1736
                {
1737
                    throw new InvalidRequest("1202", "obsoletedGuid must be contained in the request parameters.");
1738
                }
1739
                //get the obsoletedGuid
1740
                String obsGuidS = mutlipartparams.get("obsoletedGuid").get(0);
1741
                obsoletedGuid.setValue(obsGuidS);
1742
                
1743
                if (!im.identifierExists(obsoletedGuid.getValue())) 
1744
                {
1745
                    throw new InvalidRequest("1202", "The guid you are trying to update does not exist.");
1746
                }
1747
                
1748
                
1749
                logMetacat.debug("Commence update...");
1750
                
1751
                //get the systemmetadata
1752
                IBindingFactory bfact =
1753
                        BindingDirectory.getFactory(SystemMetadata.class);
1754
                    IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1755
                    SystemMetadata m = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
1756
                
1757
                //do the update
1758
                try
1759
                {
1760
                    cs.setParamsFromRequest(request);
1761
                    Identifier rId = cs.update(token, id, object, obsoletedGuid, m);
1762
                    serializeServiceType(Identifier.class, rId, out);
1763
                }
1764
                catch(NotFound e)
1765
                {
1766
                    throw new InvalidRequest("1202", "The guid you are trying to update does not exist.");
1767
                }
1768
                
1769
            } else {
1770
                throw new InvalidRequest("1000", "Operation must be create or update.");
1771
            }
1772
            
1773
            //clean up the MMP files
1774
            //parts.get("systemmetadata").delete();
1775
            //parts.get("object").delete();
1776
        } catch (NotAuthorized e) {
1777
            response.setStatus(500);
1778
            serializeException(e, out);
1779
        } catch (InvalidToken e) {
1780
            response.setStatus(500);
1781
            serializeException(e, out);
1782
        } catch (ServiceFailure e) {
1783
            response.setStatus(500);
1784
            serializeException(e, out);
1785
        } catch (IdentifierNotUnique e) {
1786
            response.setStatus(500);
1787
            serializeException(e, out);
1788
        } catch (UnsupportedType e) {
1789
            response.setStatus(500);
1790
            serializeException(e, out);
1791
        } catch (InsufficientResources e) {
1792
            response.setStatus(500);
1793
            serializeException(e, out);
1794
        } catch (InvalidSystemMetadata e) {
1795
            response.setStatus(500);
1796
            serializeException(e, out);
1797
        } catch (NotImplemented e) {
1798
            response.setStatus(500);
1799
            serializeException(e, out);
1800
        } catch (InvalidRequest e) {
1801
            response.setStatus(500);
1802
            serializeException(e, out);
1803
        } /*catch (MessagingException e) {
1804
            ServiceFailure sf = new ServiceFailure("1000", e.getMessage());
1805
            serializeException(sf, out);
1806
        } catch (IOException e) {
1807
            response.setStatus(500);
1808
            ServiceFailure sf = new ServiceFailure("1000", e.getMessage());
1809
            serializeException(sf, out);
1810
        }*/ catch (JiBXException e) {
1811
            response.setStatus(500);
1812
            e.printStackTrace(System.out);
1813
            InvalidSystemMetadata ism = new InvalidSystemMetadata("1080", e.getMessage());
1814
            serializeException(ism, out);
1815
        }
1816
    }
1817

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

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

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

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

    
1992
}
(4-4/5)