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

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

    
1456
            DBQuery metacat = new DBQuery();
1457

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

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

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

    
1475
            System.out
1476
                    .println(EcogridResultsetTransformer.toXMLString(records));
1477
            response.setContentType("text/xml");
1478
            out = response.getWriter();
1479
            out.print(EcogridResultsetTransformer.toXMLString(records));
1480

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

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

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

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

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

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

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

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

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

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

    
1995
}
(4-4/5)