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

    
939
        String name = null;
940
        String[] value = null;
941
        Enumeration paramlist = request.getParameterNames();
942
        while (paramlist.hasMoreElements()) {
943
            name = (String) paramlist.nextElement();
944
            value = request.getParameterValues(name);
945
            params.put(name, value);
946
        }
947
    }
948

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

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

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

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

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

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

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

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

    
1112
        out.close();
1113
    }
1114

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

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

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

    
1420
            DBQuery metacat = new DBQuery();
1421

    
1422
            boolean useXMLIndex = (new Boolean(PropertyService
1423
                    .getProperty("database.usexmlindex"))).booleanValue();
1424
            String xmlquery = "query"; // we don't care the query in resultset,
1425
            // the query can be anything
1426
            PrintWriter out = null; // we don't want metacat result, so set out null
1427

    
1428
            // parameter: queryspecification, user, group, usingIndexOrNot
1429
            StringBuffer result = metacat.createResultDocument(xmlquery,
1430
                    metacatQuery, out, username, groupNames, useXMLIndex);
1431

    
1432
            // create result set transfer       
1433
            String saxparser = PropertyService.getProperty("xml.saxparser");
1434
            MetacatResultsetParser metacatResultsetParser = new MetacatResultsetParser(
1435
                    new StringReader(result.toString()), saxparser, queryType
1436
                            .getNamespace().get_value());
1437
            ResultsetType records = metacatResultsetParser.getEcogridResult();
1438

    
1439
            System.out
1440
                    .println(EcogridResultsetTransformer.toXMLString(records));
1441
            response.setContentType("text/xml");
1442
            out = response.getWriter();
1443
            out.print(EcogridResultsetTransformer.toXMLString(records));
1444

    
1445
        } catch (Exception e) {
1446
            e.printStackTrace();
1447
        }*/
1448
        response.setContentType("text/xml");
1449
        response.setStatus(501);
1450
        PrintWriter out = response.getWriter();
1451
        out.print("<error>Query operation not yet supported by Metacat.</error>");
1452
        out.close();
1453
    }
1454
    
1455
    private String streamToString(InputStream is)
1456
    throws IOException
1457
    {
1458
        return IOUtil.toString(is);
1459
    }
1460

    
1461
    private InputStream stringToStream(String s)
1462
    throws IOException
1463
    {
1464
        ByteArrayInputStream bais = new ByteArrayInputStream(s.getBytes(MetaCatServlet.DEFAULT_ENCODING));
1465
        return bais;
1466
    }
1467
    
1468
    /**
1469
     * locate the boundary marker for an MMP
1470
     * @param is
1471
     * @return
1472
     * @throws IOException
1473
     */
1474
    protected static String[] findBoundaryString(InputStream is)
1475
        throws IOException
1476
    {
1477
        String[] endResult = new String[2];
1478
        String boundary = "";
1479
        String searchString = "boundary=";
1480
        boolean doneWithCurrentArray = false;
1481
        byte[] b = new byte[1024];
1482
        int numbytes = is.read(b, 0, 1024);
1483

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

    
1668
                // Check if the objectId exists
1669
                IdentifierManager im = IdentifierManager.getInstance();
1670
                if (im.identifierExists(guid)) {
1671
                    throw new IdentifierNotUnique("1000", "Identifier is already in use: " + guid);
1672
                }
1673

    
1674
                logMetacat.debug("Commence creation...");
1675
                IBindingFactory bfact =
1676
                    BindingDirectory.getFactory(SystemMetadata.class);
1677
                IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1678
                SystemMetadata m = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
1679

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

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

    
1872
    /**
1873
     * Earthgrid API > Authentication Service > Login Function : calls MetacatHandler > handleLoginAction
1874
     * 
1875
     * @throws IOException
1876
     */
1877
    private void login() throws IOException {
1878
        PrintWriter out = response.getWriter();
1879
        response.setStatus(200);
1880
        response.setContentType("text/xml");
1881
        handler.handleLoginAction(out, params, request, response);
1882
        out.close();
1883
    }
1884

    
1885
    /**
1886
     * Earthgrid API > Authentication Service > Logout Function : calls MetacatHandler > handleLogoutAction
1887
     * 
1888
     * @throws IOException
1889
     */
1890
    private void logout() throws IOException {
1891
        PrintWriter out = response.getWriter();
1892
        response.setStatus(200);
1893
        response.setContentType("text/xml");
1894
        handler.handleLogoutAction(out, params, request, response);
1895
        out.close();
1896
    }
1897

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

    
1955
}
(4-4/5)