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.ByteArrayInputStream;
26
import java.io.File;
27
import java.io.FileInputStream;
28
import java.io.FileOutputStream;
29
import java.io.IOException;
30
import java.io.InputStream;
31
import java.io.OutputStream;
32
import java.io.PrintWriter;
33
import java.io.StringReader;
34
import java.net.URL;
35
import java.text.DateFormat;
36
import java.text.ParseException;
37
import java.text.SimpleDateFormat;
38
import java.util.Date;
39
import java.util.Enumeration;
40
import java.util.Hashtable;
41
import java.util.Iterator;
42
import java.util.List;
43
import java.util.Map;
44
import java.util.TimeZone;
45
import java.util.Timer;
46

    
47
import javax.servlet.ServletContext;
48
import javax.servlet.http.HttpServletRequest;
49
import javax.servlet.http.HttpServletResponse;
50

    
51
import org.apache.commons.io.IOUtils;
52
import org.apache.log4j.Logger;
53
import org.apache.maven.artifact.ant.shaded.IOUtil;
54
import org.dataone.client.MNode;
55
import org.dataone.client.ObjectFormatCache;
56
import org.dataone.client.auth.CertificateManager;
57
import org.dataone.mimemultipart.MultipartRequest;
58
import org.dataone.mimemultipart.MultipartRequestResolver;
59
import org.dataone.service.NodeListParser;
60
import org.dataone.service.exceptions.BaseException;
61
import org.dataone.service.exceptions.IdentifierNotUnique;
62
import org.dataone.service.exceptions.InsufficientResources;
63
import org.dataone.service.exceptions.InvalidRequest;
64
import org.dataone.service.exceptions.InvalidSystemMetadata;
65
import org.dataone.service.exceptions.InvalidToken;
66
import org.dataone.service.exceptions.NotAuthorized;
67
import org.dataone.service.exceptions.NotFound;
68
import org.dataone.service.exceptions.NotImplemented;
69
import org.dataone.service.exceptions.ServiceFailure;
70
import org.dataone.service.exceptions.UnsupportedType;
71
import org.dataone.service.types.AccessPolicy;
72
import org.dataone.service.types.Checksum;
73
import org.dataone.service.types.DescribeResponse;
74
import org.dataone.service.types.Event;
75
import org.dataone.service.types.Identifier;
76
import org.dataone.service.types.Log;
77
import org.dataone.service.types.Node;
78
import org.dataone.service.types.NodeList;
79
import org.dataone.service.types.NodeReference;
80
import org.dataone.service.types.NodeType;
81
import org.dataone.service.types.ObjectFormat;
82
import org.dataone.service.types.ObjectFormatIdentifier;
83
import org.dataone.service.types.ObjectFormatList;
84
import org.dataone.service.types.ObjectList;
85
import org.dataone.service.types.Service;
86
import org.dataone.service.types.Services;
87
import org.dataone.service.types.Session;
88
import org.dataone.service.types.SystemMetadata;
89
import org.dataone.service.types.util.ServiceTypeUtil;
90
import org.jibx.runtime.BindingDirectory;
91
import org.jibx.runtime.IBindingFactory;
92
import org.jibx.runtime.IUnmarshallingContext;
93
import org.jibx.runtime.JiBXException;
94

    
95
import edu.ucsb.nceas.metacat.DBUtil;
96
import edu.ucsb.nceas.metacat.IdentifierManager;
97
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
98
import edu.ucsb.nceas.metacat.MetaCatServlet;
99
import edu.ucsb.nceas.metacat.MetacatHandler;
100
import edu.ucsb.nceas.metacat.dataone.CNodeService;
101
import edu.ucsb.nceas.metacat.dataone.HealthService;
102
import edu.ucsb.nceas.metacat.dataone.MNodeService;
103
import edu.ucsb.nceas.metacat.properties.PropertyService;
104
import edu.ucsb.nceas.metacat.service.SessionService;
105
import edu.ucsb.nceas.metacat.util.RequestUtil;
106
import edu.ucsb.nceas.metacat.util.SessionData;
107
import edu.ucsb.nceas.metacat.util.SystemUtil;
108
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
109
/**
110
 * 
111
 * Implements Earthgrid REST API to Metacat <br/><br/> 
112
 * 
113
 * <ul>
114
 * <li>
115
 * <h3> EarthGrid Query Service</h3>
116
 * <ul><li>
117
 * <h3>Get & Authenticated Get:</h3> 
118
 * is equal to Metacat's read action and returns a data file having
119
 * the specified <doc-id> in the resource path. For authenticated Get service, a session id must be provided 
120
 * in the query string. <br/><br/>
121
 * 
122
 * <b>REST URL:</b> <code>GET, [context-root]/object/[doc-id]?sessionid=[sessionid] </code><br/>
123
 * <b>Returns:</b> data file <br/><br/>
124
 * </li>
125
 * 
126
 * <li>
127
 * <h3>Query & Authenticated Query:</h3> 
128
 * Metacat's equivalent is squery action but this function 
129
 * receives a Earthgrid query document and returns Earthgrid resultset document by transforming those documents
130
 * to Metacat's equivalents by the means of Metacat Implementation in Earthgrid library. For authenticated Query service 
131
 * a session id must be provided in the query string. See Earthgrid (a.k.a. Ecogrid) project for XSD files of 
132
 * query and resultset documents<br/><br/>
133
 * 
134
 * <b>REST URL:</b> <code>POST, [context-root]/object?sessionid=[sessionid]</code>    <br/>
135
 * <b>POST Data:</b> Earthgrid query document , Content-type: <code>text/xml</code><br/>
136
 * <b>Returns:</b> Earthgrid resultset document<br/><br/>
137
 * 
138
 * </li>
139
 * </ul>
140
 * 
141
 * </li>
142
 * 
143
 * <li>
144
 * <h3> EarthGrid Authentication Service</h3>
145
 * <ul><li>
146
 * <h3>Login: </h3> 
147
 * Receives username and password parameters in POST data and 
148
 * returns SessionId (in XML format) or failure message and uses MetacatHandler's handleLoginAction function<br/><br/>
149
 *  
150
 * <b>REST URL:</b> <code>POST, [context-root]/session?op=login</code> <br/>
151
 * <b>POST Data:</b> username=[username]&password=[password], Content-type: <code>application/x-www-form-urlencoded</code>
152
 * <b>Returns:</b> sessionId in XML format<br/><br/>
153
 * </li>
154
 * 
155
 * <li>
156
 * <h3>Logout: </h3> 
157
 * Receives session Id parameters in querystring and returns xml message, calls 
158
 * MetacatHandler's handleLogoutAction function<br/><br/>
159
 *  
160
 * <b>REST URL:</b> <code>GET, [context-root]/session?op=logout&sessionid=[sessionid]</code>   <br/>
161
 * <b>Returns:</b> message in XML format<br/><br/>
162
 * </li>
163
 * </ul>
164
 * 
165
 * <li>
166
 * <h3>EarthGrid Put Service</h3>
167
 * 
168
 * <ul>
169
 * <li><h3>Update/Insert: </h3>     
170
 * <br/>
171
 * <b>REST URL:</b> <code>PUT, [context-root]/object/[doc-id]?op={update|insert}&sessionid=[sessionid]</code>   <br/>
172
 * <b>POST Data:</b> document object, Content-type: <code>text/xml</code><br/>
173
 * <b>Returns:</b> message in XML format<br/><br/>
174
 * </li>
175
 * 
176
 * <li><h3>Delete: </h3>        
177
 * <br/>
178
 * <b>REST URL:</b> <code>DELETE, [context-root]/object/[doc-id]?sessionid=[sessionid]</code>   <br/>
179
 * <b>Returns:</b> message in XML format<br/><br/>
180
 * </li>
181

    
182
 * </ul>
183
 * </li>
184
 * 
185
 * <li>
186
 * <h3>EarthGrid Identifier Service</h3><br/>
187
 * 
188
 * <ul>
189
 * <li><h3>isRegistered: </h3>      <br/>
190
 * <b>REST URL:</b> <code>GET, [context-root]/identifier/[doc-id]?op=isregistered</code>   <br/>
191
 * <b>Returns:</b> message in XML format<br/><br/>
192
 * </li>
193

    
194
 * <li><h3>getAllDocIds:</h3>       <br/>       
195
 * <b>REST URL:</b> <code>GET, [context-root]/identifier?op=getalldocids</code>   <br/>
196
 * <b>Returns:</b> document id list in XML format<br/><br/>
197
 * </li>
198
 * 
199
 * <li><h3>addLSID Function:</h3> 
200
 * Metacat does not support this function       <br/>
201
 * <b>REST URL:</b> <code>PUT, [context-root]/identifier/[doc-id]</code>   <br/>
202
 * <b>Returns:</b> error message in XML format<br/><br/>
203
 * </li>
204
 * 
205
 * <li><h3>getNextRevision:</h3>        <br/>
206
 * <b>REST URL:</b> <code>GET, [context-root]/identifier/[doc-id]?op=getnextrevision</code>   <br/>
207
 * <b>Returns:</b> message in XML format<br/><br/>
208
 * </li>
209
 * 
210
 * <li><h3>getNextObject:</h3>      <br/>
211
 * <b>REST URL:</b> <code>GET, [context-root]/identifier?op=getnextobject&scope=[scope]</code>   <br/>
212
 * <b>Returns:</b> message in XML format<br/><br/>
213
 * </li>
214
 * 
215
 * </li>
216
 * </ul>
217
 * 
218
 * @deprecated Only keeping this for reference in case we want to continue developing
219
 * REST interface for old Metacat API
220
 */
221
public class ResourceHandler {
222

    
223
    /**HTTP Verb GET*/
224
    public static final byte GET = 1;
225
    /**HTTP Verb POST*/
226
    public static final byte POST = 2;
227
    /**HTTP Verb PUT*/
228
    public static final byte PUT = 3;
229
    /**HTTP Verb DELETE*/
230
    public static final byte DELETE = 4;
231
    /**HTTP Verb HEAD*/
232
    public static final byte HEAD = 5;
233

    
234
    /*
235
     * API Resources
236
     */
237
    protected static final String RESOURCE_OBJECTS = "object";
238
    protected static final String RESOURCE_FORMATS = "formats";
239
    protected static final String RESOURCE_META = "meta";
240
    protected static final String RESOURCE_SESSION = "session";
241
    protected static final String RESOURCE_IDENTIFIER = "identifier";
242
    protected static final String RESOURCE_LOG = "log";
243
    protected static final String RESOURCE_CHECKSUM = "checksum";
244
    protected static final String RESOURCE_MONITOR = "monitor";
245
    protected static final String RESOURCE_BASE_URL = "d1";
246
    protected static final String RESOURCE_REPLICATE = "replicate";
247
    
248
    protected static final String RESOURCE_IS_AUTHORIZED = "isAuthorized";
249
    protected static final String RESOURCE_ACCESS_RULES = "accessRules";
250

    
251
    /*
252
     * API Functions used as URL parameters
253
     */
254
    protected static final String FUNCTION_KEYWORD = "op";
255
    protected static final String FUNCTION_NAME_LOGIN = "login";
256
    protected static final String FUNCTION_NAME_LOGOUT = "logout";
257
    protected static final String FUNCTION_NAME_SET_ACCESS = "setaccess";
258
    protected static final String FUNCTION_NAME_ISREGISTERED = "isregistered";
259
    protected static final String FUNCTION_NAME_GETALLDOCS = "getalldocids";
260
    protected static final String FUNCTION_NAME_GETNEXTREV = "getnextrevision";
261
    protected static final String FUNCTION_NAME_GETNEXTOBJ = "getnextobject";
262
    protected static final String FUNCTION_NAME_INSERT = "insert";
263
    protected static final String FUNCTION_NAME_UPDATE = "update";
264
    protected static final String FUNCTION_NAME_GENERATE_MISSING_SYSTEM_METADATA = "generatemissingsystemmetadata";
265

    
266
    protected static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
267
    
268
    protected ServletContext servletContext;
269
    protected Logger logMetacat;
270
    protected MetacatHandler handler;
271
    protected HttpServletRequest request;
272
    protected HttpServletResponse response;
273
    protected String username;
274
    protected String password;
275
    protected String sessionId;
276
    protected String[] groupNames;
277

    
278
    protected Hashtable<String, String[]> params;
279
    
280
    // D1 certificate-based authentication
281
    protected Session session;
282

    
283
    /**Initializes new instance by setting servlet context,request and response*/
284
    public ResourceHandler(ServletContext servletContext,
285
            HttpServletRequest request, HttpServletResponse response) {
286
        this.servletContext = servletContext;
287
        this.request = request;
288
        this.response = response;
289
    }
290

    
291
    /**
292
     * This function is called from REST APU servlet and handles each request to the servlet 
293
     * 
294
     * @param httpVerb (GET, POST, PUT or DELETE)
295
     */
296
    public void handle(byte httpVerb) {
297
        logMetacat = Logger.getLogger(ResourceHandler.class);
298
        try {
299
            String resource = request.getServletPath();
300
            if(resource.endsWith("d1/") || resource.endsWith("d1"))
301
            {
302
                resource = RESOURCE_BASE_URL;
303
            }
304
            else
305
            {
306
                //substring off the /d1/
307
                resource = resource.substring(resource.indexOf("d1/") + 3, resource.length());
308
                resource = resource.trim();
309
            }
310
            
311
            String verb = "";
312
            
313
            System.out.println("handling verb " + httpVerb + " request with resource '" + resource + "'");
314
            System.out.println("resource: '" + resource + "'");
315
            System.out.println("resource_monitor: '" + RESOURCE_MONITOR + "'");
316
            boolean status = false;
317
            // load session the old way
318
            loadSessionData();
319
            
320
            // load session from certificate in request
321
            session = CertificateManager.getInstance().getSession(request);
322
            
323
            
324
            if (resource != null) {
325
                //resource = request.getServletPath().substring(1);
326

    
327
                params = new Hashtable<String, String[]>();
328
                initParams();
329

    
330
                Timer timer = new Timer();
331
                handler = new MetacatHandler(timer);
332

    
333
                if(resource.equals(RESOURCE_BASE_URL)) {
334
                    //node registry response
335
                    System.out.println("Using resource 'd1' (node registry response)");
336
                    createNodeResponse();
337
                    status = true;
338
                    
339
                } else if (resource.equals(RESOURCE_SESSION) && 
340
                        httpVerb == POST && 
341
                        params.get(FUNCTION_KEYWORD) != null) {
342
                    System.out.println("Using resource 'session'");
343
                    //System.out.println("function_keyword: " + params.get(FUNCTION_KEYWORD)[0]);
344
                    if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_LOGIN)) {
345
                        login();
346
                        status = true;
347
                    } else if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_LOGOUT)) {
348
                        logout();
349
                        status = true;
350
                    } else if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_SET_ACCESS)) {
351
                        setaccess();
352
                        status = true;
353
                        System.out.println("done setting access");
354
                    }
355
                } else if (resource.equals(RESOURCE_META)) {
356
                    System.out.println("Using resource 'meta'");
357
                    if (params != null && params.get(FUNCTION_KEYWORD) != null &&
358
                            params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_GENERATE_MISSING_SYSTEM_METADATA))
359
                    { 
360
                        status = true;
361
                    }
362
                    else
363
                    {
364
                        String objectId = request.getPathInfo();
365
                        if (objectId != null && objectId.length() > 1) 
366
                        {
367
                            objectId = request.getPathInfo().substring(1);
368
                        }
369
                        
370
                        // get
371
                        if (httpVerb == GET) {
372
	                        getSystemMetadataObject(objectId);
373
	                        status = true;
374
                        }
375
                        
376
                        // post to register system metadata
377
                        if (httpVerb == POST) {
378
                        	registerSystemMetadata(objectId);
379
                        	status = true;
380
                        }
381
                        
382
                    }
383

    
384
                } else if (resource.equals(RESOURCE_OBJECTS)) {
385
                    System.out.println("Using resource 'object'");
386
                    logMetacat.debug("D1 Rest: Starting resource processing...");
387
                    loadSessionData();
388

    
389
                    String objectId = request.getPathInfo();
390
                    if (objectId != null && objectId.length() > 1) 
391
                    {
392
                        objectId = request.getPathInfo().substring(1);
393
                    }
394
                    else
395
                    {
396
                        objectId = null;
397
                    }
398
                    
399
                    System.out.println("objectId in ReasourceHandler.handle: " + objectId);
400

    
401
                    logMetacat.debug("verb:" + httpVerb);
402

    
403
                    if (httpVerb == GET) {
404
                        getObject(objectId);
405
                        status = true;
406
                    } else if (httpVerb == POST) {
407
                        putObject(objectId, FUNCTION_NAME_INSERT);
408
                        status = true;
409
                    } else if (httpVerb == PUT) {
410
                        putObject(objectId, FUNCTION_NAME_UPDATE);
411
                        status = true;
412
                    } else if (httpVerb == DELETE) {
413
                        deleteObject(objectId);
414
                        status = true;
415
                    } else if (httpVerb == HEAD) {
416
                        describeObject(objectId);
417
                        status = true;
418
                    }
419
                    
420
                } else if (resource.equals(RESOURCE_FORMATS)) {
421
                  System.out.println("Using resource 'formats'");
422
                  
423
                  // check for a format identifier
424
                  String fmtid = request.getPathInfo();
425
                  
426
                  if ( fmtid != null && fmtid.length() > 1 ) {
427
                  	fmtid = request.getPathInfo().substring(1);
428
                  	
429
                  } else {
430
                  	fmtid = null;
431
                  	
432
                  }
433
                  
434
                  // handle each verb
435
                  if ( httpVerb == GET ) {
436
                  	if ( fmtid == null ) {
437
                      // list the formats collection
438
                  		listFormats();
439
                  		
440
                  	} else {
441
                  		// get the specified format
442
                  		getFormat(fmtid);
443

    
444
                  	}
445
                  	status = true;
446
                  
447
                  } else if ( httpVerb == PUT ) {
448
                  	status = true;
449
                  	
450
                  } else if ( httpVerb == POST ) {
451
                  	status = true;
452
                  	
453
                  } else if ( httpVerb == DELETE ) {
454
                  	status = true;
455
                  	
456
                  } else if ( httpVerb == HEAD ) {
457
                  	status = true;
458
                  	
459
                  }
460
                  
461
                } else if (resource.equals(RESOURCE_IDENTIFIER)) {
462
                    System.out.println("Using resource 'identifier'");
463
                    String identifierId = request.getPathInfo();
464
                    if (identifierId != null && identifierId.length() > 1)
465
                        identifierId = request.getPathInfo().substring(1); //trim the slash
466

    
467
                    if (httpVerb == GET) {
468
                        String op = params.get(FUNCTION_KEYWORD)[0];
469
                        if (op.equals(FUNCTION_NAME_ISREGISTERED)) {
470
                            isRegistered(identifierId);
471
                            status = true;
472
                        } else if (op.equals(FUNCTION_NAME_GETALLDOCS)) {
473
                            getAllDocIds();
474
                            status = true;
475
                        } else if (op.equals(FUNCTION_NAME_GETNEXTREV)) {
476
                            getNextRevision(identifierId);
477
                            status = true;
478
                        } else if (op.equals(FUNCTION_NAME_GETNEXTOBJ)) {
479
                            getNextObject();
480
                            status = true;
481
                        } 
482

    
483
                    } else if (httpVerb == PUT) {
484
                        //Earthgrid API > Identifier Service > addLSID Function 
485
                        response.setStatus(501);
486
                        printError(
487
                                "This method is not supported by metacat.  To "
488
                                + "add a new LSID, add a document to metacat.",
489
                                response);
490
                        status = true;
491
                    }
492

    
493
                } else if (resource.equals(RESOURCE_LOG)) {
494
                    System.out.println("Using resource 'log'");
495
                    //handle log events
496
                    if(httpVerb == GET)
497
                    {
498
                        getLog();
499
                        status = true;
500
                    }
501
                    else
502
                    {
503
                        //change to D1 spec for specifying which http methods are allowed for a resource
504
                        response.setStatus(501);
505
                        printError("POST, PUT, DELETE is not supported for logs.", response);
506
                        status = true;
507
                    }
508

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

    
1017
        String name = null;
1018
        String[] value = null;
1019
        Enumeration paramlist = request.getParameterNames();
1020
        while (paramlist.hasMoreElements()) {
1021
            name = (String) paramlist.nextElement();
1022
            value = request.getParameterValues(name);
1023
            params.put(name, value);
1024
        }
1025
    }
1026

    
1027
    /**
1028
     * 
1029
     * Load user details of metacat session from the request 
1030
     * 
1031
     */
1032
    private void loadSessionData()
1033
      throws Exception
1034
    {
1035
        SessionData sessionData = RequestUtil.getSessionData(request);
1036
        try
1037
        {
1038
            username = null;
1039
            password = null;
1040
            groupNames = null;
1041
            sessionId = null;
1042
            
1043
            boolean validSession = false;
1044
            SessionService ss = SessionService.getInstance();
1045
            System.out.println("sessionData: " + sessionData);
1046
            if(sessionData == null)
1047
            {
1048
                username = "public";
1049
                sessionId = "0";
1050
                System.out.println("sessiondata is null.  Creating a public session.");
1051
                return;
1052
            }
1053
            
1054
            System.out.println("username: " + sessionData.getUserName());
1055
            System.out.println("sessionid: " + sessionData.getId());
1056
            //validate the session
1057
            if(ss.isSessionRegistered(sessionData.getId()) && 
1058
               !(sessionData.getUserName().equals("public") || sessionData.getId().equals("0")))
1059
            {
1060
                validSession = true;
1061
            }
1062
            
1063
            if(validSession)
1064
            {
1065
                //if the session is valid, set these variables
1066
                username = sessionData.getUserName();
1067
                password = sessionData.getPassword();
1068
                groupNames = sessionData.getGroupNames();
1069
                sessionId = sessionData.getId();
1070
                System.out.println("setting sessionid to " + sessionId);
1071
                System.out.println("username: " + username);
1072
            }
1073
            
1074
            //if the session is not valid or the username is null, set
1075
            //username to public
1076
            if (username == null) 
1077
            {
1078
                System.out.println("setting username to public.");
1079
                username = "public";
1080
            }
1081
        }
1082
        catch(Exception e)
1083
        {
1084
            e.printStackTrace();
1085
            throw new Exception("Could not load the session data: " + e.getClass() + ": " + e.getMessage());
1086
        }
1087
    }
1088

    
1089
    /**
1090
     *  Earthgrid API > Identifier Service > isRegistered Function : 
1091
     *  calls MetacatHandler > handleIdIsRegisteredAction
1092
     * @param guid
1093
     * @throws IOException
1094
     */
1095
    private void isRegistered(String guid) throws IOException
1096
    {
1097
        
1098
        // Look up the localId for this guid
1099
        IdentifierManager im = IdentifierManager.getInstance();
1100
        String localId = "";
1101
        try {
1102
            localId = im.getLocalId(guid);
1103
        } catch (McdbDocNotFoundException e) {
1104
            // TODO: Need to return the proper DataONE exception
1105
        }
1106
        
1107
        params.put("docid", new String[] { localId });
1108
        PrintWriter out = response.getWriter();
1109
        response.setStatus(200);
1110
        response.setContentType("text/xml");
1111
        handler.handleIdIsRegisteredAction(out, params, response);
1112
        out.close();
1113
    }
1114

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

    
1128
    /**
1129
     * Earthgrid API > Identifier Service > getNextRevision Function : 
1130
     * calls MetacatHandler > handleGetRevisionAndDocTypeAction
1131
     * @param guid
1132
     * @throws IOException
1133
     */
1134
    private void getNextRevision(String guid) throws IOException 
1135
    {
1136
        params.put("docid", new String[] { guid });
1137
        PrintWriter out = response.getWriter();
1138
        response.setStatus(200);
1139
        response.setContentType("text/xml");
1140
        //handler.handleGetRevisionAndDocTypeAction(out, params);
1141

    
1142
        try {
1143
            // Make sure there is a docid
1144
            if (guid == null || guid.equals("")) {
1145
                throw new Exception("User didn't specify docid!");
1146
            }
1147

    
1148
            // Look up the localId for this guid
1149
            IdentifierManager im = IdentifierManager.getInstance();
1150
            String localId = "";
1151
            try {
1152
                localId = im.getLocalId(guid);
1153
            } catch (McdbDocNotFoundException e) {
1154
                // TODO: Need to return the proper DataONE exception
1155
            }
1156
           
1157
            // Create a DBUtil object
1158
            DBUtil dbutil = new DBUtil();
1159
            // Get a rev and doctype
1160
            String revAndDocType = dbutil
1161
                    .getCurrentRevisionAndDocTypeForGivenDocument(localId);
1162
            int revision = Integer.parseInt(revAndDocType.split(";")[0]) + 1;
1163

    
1164
            out.println("<?xml version=\"1.0\"?>");
1165
            out.print("<next-revision>");
1166
            out.print(revision);
1167
            out.print("</next-revision>");
1168

    
1169
        } catch (Exception e) {
1170
            // Handle exception
1171
            response.setStatus(500);
1172
            out.println("<?xml version=\"1.0\"?>");
1173
            out.println("<error>");
1174
            out.println(e.getClass() + ": " + e.getMessage());
1175
            out.println("</error>");
1176
        }
1177

    
1178
        out.close();
1179
    }
1180

    
1181
    /**
1182
     * Earthgrid API > Identifier Service > getNextObject Function : 
1183
     * calls MetacatHandler > handleGetMaxDocidAction
1184
     * @throws IOException
1185
     */
1186
    private void getNextObject() throws IOException {
1187
        PrintWriter out = response.getWriter();
1188
        response.setStatus(200);
1189
        response.setContentType("text/xml");
1190
        handler.handleGetMaxDocidAction(out, params, response);
1191
        out.close();
1192
    }
1193

    
1194
    /**
1195
     * Implements REST version of DataONE CRUD API --> get
1196
     * @param guid ID of data object to be read
1197
     */
1198
    protected void getObject(String guid) {
1199
        OutputStream out = null;
1200
        try {
1201
            out = response.getOutputStream();
1202
            response.setStatus(200);
1203
            
1204
            if(guid != null)
1205
            { //get a specific document                
1206
                Identifier id = new Identifier();
1207
                id.setValue(guid);
1208
                try
1209
                {
1210
                    
1211
                    SystemMetadata sm = MNodeService.getInstance().getSystemMetadata(session, id);
1212
                    
1213
                    //set the content type
1214
                    if(sm.getObjectFormat().getFmtid().getValue().trim().equals(
1215
                    		ObjectFormatCache.getInstance().getFormat("text/csv").getFmtid().getValue()))
1216
                    {
1217
                        response.setContentType("text/csv");
1218
                        response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".csv");
1219
                    }
1220
                    else if(sm.getObjectFormat().getFmtid().getValue().trim().equals(
1221
                    		ObjectFormatCache.getInstance().getFormat("text/plain").getFmtid().getValue()))
1222
                    {
1223
                        response.setContentType("text/plain");
1224
                        response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".txt");
1225
                    } 
1226
                    else if(sm.getObjectFormat().getFmtid().getValue().trim().equals(
1227
                    		ObjectFormatCache.getInstance().getFormat("application/octet-stream").getFmtid().getValue()))
1228
                    {
1229
                        response.setContentType("application/octet-stream");
1230
                    }
1231
                    else
1232
                    {
1233
                        response.setContentType("text/xml");
1234
                        response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".xml");
1235
                    }
1236
                    
1237
                    InputStream data = MNodeService.getInstance().get(session, id);
1238
                    IOUtils.copyLarge(data, response.getOutputStream());
1239
                }
1240
                catch(InvalidToken it)
1241
                {
1242
                    response.setStatus(500);
1243
                    serializeException(it, out); 
1244
                }
1245
                catch(ServiceFailure sf)
1246
                {
1247
                    response.setStatus(500);
1248
                    serializeException(sf, out); 
1249
                }
1250
                catch(NotAuthorized na)
1251
                {
1252
                    response.setStatus(500);
1253
                    serializeException(na, out); 
1254
                }
1255
                catch(NotFound nf)
1256
                {
1257
                    response.setStatus(500);
1258
                    serializeException(nf, out); 
1259
                }
1260
                catch(NotImplemented ni)
1261
                {
1262
                    response.setStatus(500);
1263
                    serializeException(ni, out); 
1264
                }
1265
                catch(Exception e)
1266
                {
1267
                    response.setStatus(500);
1268
                    System.out.println("Error with Crud.get().  " +
1269
                            "If this is an 'Exception producing data' error, " +
1270
                            "go to CrudService.get() for better debugging.  " +
1271
                            "Here's the error: " + e.getClass() + ": " + e.getMessage());
1272
                    e.printStackTrace();
1273
                    ServiceFailure sf = new ServiceFailure("1030", 
1274
                            "IO Error in ResourceHandler.getObject: " + e.getClass() + ": " + e.getMessage());
1275
                    serializeException(sf, out); 
1276
                }
1277
            }
1278
            else
1279
            { //call listObjects with specified params
1280
                Date startTime = null;
1281
                Date endTime = null;
1282
                ObjectFormat objectFormat = null;
1283
                boolean replicaStatus = false;
1284
                int start = 0;
1285
                //TODO: make the max count into a const
1286
                int count = 1000;
1287
                Enumeration paramlist = request.getParameterNames();
1288
                while (paramlist.hasMoreElements()) 
1289
                { //parse the params and make the crud call
1290
                    String name = (String) paramlist.nextElement();
1291
                    String[] value = (String[])request.getParameterValues(name);
1292
                    /*for(int i=0; i<value.length; i++)
1293
                    {
1294
                        System.out.println("name: " + name + " value: " + value[i]);
1295
                    }*/
1296
                    if(name.equals("startTime") && value != null)
1297
                    {
1298
                        try
1299
                        {
1300
                          //startTime = dateFormat.parse(value[0]);
1301
                            startTime = parseDateAndConvertToGMT(value[0]);
1302
                        }
1303
                        catch(Exception e)
1304
                        {  //if we can't parse it, just don't use the startTime param
1305
                            System.out.println("Could not parse startTime: " + value[0]);
1306
                            startTime = null;
1307
                        }
1308
                    }
1309
                    else if(name.equals("endTime") && value != null)
1310
                    {
1311
                        try
1312
                        {
1313
                          //endTime = dateFormat.parse(value[0]);
1314
                            endTime = parseDateAndConvertToGMT(value[0]);
1315
                        }
1316
                        catch(Exception e)
1317
                        {  //if we can't parse it, just don't use the endTime param
1318
                            System.out.println("Could not parse endTime: " + value[0]);
1319
                            endTime = null;
1320
                        }
1321
                    }
1322
                    else if(name.equals("objectFormat") && value != null) 
1323
                    {
1324
                        objectFormat = ObjectFormatCache.getInstance().getFormat(value[0]);
1325
                    }
1326
                    else if(name.equals("replicaStatus") && value != null)
1327
                    {
1328
                        if(value != null && 
1329
                           value.length > 0 && 
1330
                           (value[0].equals("true") || value[0].equals("TRUE") || value[0].equals("YES")))
1331
                        {
1332
                            replicaStatus = true;
1333
                        }
1334
                    }
1335
                    else if(name.equals("start") && value != null)
1336
                    {
1337
                        start = new Integer(value[0]).intValue();
1338
                    }
1339
                    else if(name.equals("count") && value != null)
1340
                    {
1341
                        count = new Integer(value[0]).intValue();
1342
                    }
1343
                }
1344
                //make the crud call
1345
                System.out.println("session: " + session + " startTime: " + startTime +
1346
                        " endtime: " + endTime + " objectFormat: " + 
1347
                        objectFormat + " replicaStatus: " + replicaStatus + 
1348
                        " start: " + start + " count: " + count);
1349
               
1350
                ObjectList ol = MNodeService.getInstance().listObjects(session, startTime, endTime, 
1351
                        objectFormat.getFmtid(), replicaStatus, start, count);
1352
                
1353
                StringReader sr = new StringReader(ol.toString());                
1354
                out = response.getOutputStream();  
1355
                response.setStatus(200);
1356
                response.setContentType("text/xml");
1357
                // Serialize and write it to the output stream
1358
                
1359
                try {
1360
                    serializeServiceType(ObjectList.class, ol, out);
1361
                } catch (JiBXException e) {
1362
                    throw new ServiceFailure("1190", "Failed to serialize ObjectList: " + e.getMessage());
1363
                }
1364
            }
1365
        } catch (BaseException e) {
1366
                response.setStatus(500);
1367
                serializeException(e, out);
1368
        } catch (IOException e) {
1369
            e.printStackTrace();
1370
            response.setStatus(500);
1371
            ServiceFailure sf = new ServiceFailure("1030", 
1372
                    "IO Error in ResourceHandler.getObject: " + e.getMessage());
1373
            serializeException(sf, out); 
1374
        } catch(NumberFormatException ne) {
1375
            response.setStatus(500);
1376
            InvalidRequest ir = new InvalidRequest("1030", "Invalid format for parameter: " + ne.getMessage());
1377
            serializeException(ir, out);
1378
        } catch (Exception e) {
1379
            e.printStackTrace();
1380
            response.setStatus(500);
1381
            ServiceFailure sf = new ServiceFailure("1030", 
1382
                    "Exception " + e.getClass().getName() + " raised while handling listObjects request: " + 
1383
                    e.getMessage());
1384
            serializeException(sf, out);
1385
        }
1386
    }
1387
    
1388
    /**
1389
     * parse a date and return it in GMT if it ends with a 'Z'
1390
     * @param date
1391
     * @return
1392
     * @throws ParseException
1393
     */
1394
    protected Date parseDateAndConvertToGMT(String date) throws ParseException
1395
    {
1396
        try
1397
        {   //the format we want
1398
            return dateFormat.parse(date);
1399
        }
1400
        catch(java.text.ParseException pe)
1401
        {   //try another legacy format
1402
            DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
1403
            dateFormat2.setTimeZone(TimeZone.getTimeZone("GMT-0"));
1404
            return dateFormat2.parse(date);
1405
        }    
1406
    }
1407

    
1408
    /**
1409
     * Implements REST version of DataONE CRUD API --> getSystemMetadata
1410
     * @param guid ID of data object to be read
1411
     */
1412
    protected void getSystemMetadataObject(String guid) {
1413
        OutputStream out = null;
1414
        try {
1415
            response.setContentType("text/xml");
1416
            response.setStatus(200);
1417
            out = response.getOutputStream();
1418
            Identifier id = new Identifier();
1419
            id.setValue(guid);
1420
            SystemMetadata sysmeta = MNodeService.getInstance().getSystemMetadata(session, id);
1421
            
1422
            // Serialize and write it to the output stream
1423
            try {
1424
                //TODO: look at the efficiency of this method.  The system metadata
1425
                //is read from metacat (in CrudService) as xml, then serialized
1426
                //to a SystemMetadat object, then returned here, then serizlized
1427
                //back to XML to be sent to the response.
1428
                serializeServiceType(SystemMetadata.class, sysmeta, out);
1429
            } catch (JiBXException e) {
1430
                throw new ServiceFailure("1190", "Failed to serialize SystemMetadata: " + e.getMessage());
1431
            }
1432
        } catch (BaseException e) {
1433
            response.setStatus(500);
1434
                serializeException(e, out);
1435
        } catch (IOException e) {
1436
            response.setStatus(500);
1437
            ServiceFailure sf = new ServiceFailure("1030", 
1438
                    "IO Error in ResourceHandler.getSystemMetadataObject: " + e.getMessage());
1439
            serializeException(sf, out);
1440
        } finally {
1441
            IOUtils.closeQuietly(out);
1442
        }
1443
    }
1444
    
1445
    /**
1446
     * serialize an object of type to out
1447
     * @param type the class of the object to serialize (i.e. SystemMetadata.class)
1448
     * @param object the object to serialize
1449
     * @param out the stream to serialize it to
1450
     * @throws JiBXException
1451
     */
1452
    protected void serializeServiceType(Class type, Object object, OutputStream out)
1453
      throws JiBXException
1454
    {
1455
        ServiceTypeUtil.serializeServiceType(type, object, out);
1456
    }
1457
    
1458
    /**
1459
     * deserialize an object of type from is
1460
     * @param type the class of the object to serialize (i.e. SystemMetadata.class)
1461
     * @param is the stream to deserialize from
1462
     * @throws JiBXException
1463
     */
1464
    protected Object deserializeServiceType(Class type, InputStream is)
1465
      throws JiBXException
1466
    {
1467
        return ServiceTypeUtil.deserializeServiceType(type, is);
1468
    }
1469
    
1470
    /**
1471
     * Earthgrid API > Query Service > Query Function : translates ecogrid query document to metacat query 
1472
     * then calls DBQuery > createResultDocument function and then again translate resultset to ecogrid resultset
1473
     * 
1474
     * NOTE:
1475
     *      This is the only method that uses EcoGrid classes for its implementation.  
1476
     *      It does so because it takes an EcoGrid Query as input, and outputs an
1477
     *      EcoGrid ResultSet document.  These documents are parsed by the auto-generated
1478
     *      EcoGrid classes from axis, and so we link to them here rather than re-inventing them.
1479
     *      This creates a circular dependency, because the Metacat classes are needed
1480
     *      to build the EcoGrid implementation, and the EcoGrid jars are needed to build this query()
1481
     *      method.  This circularity could be resolved by moving the EcoGrid classes
1482
     *      to Metacat directly.  As we transition away from EcoGrid SOAP methods in
1483
     *      favor of these REST interfaces, this circular dependency can be eliminated.
1484
     *        
1485
     * @throws Exception
1486
     */
1487
    private void query() throws Exception {
1488
        /*  This block commented out because of the EcoGrid circular dependency.
1489
         *  For now, query will not be supported until the circularity can be
1490
         *  resolved, probably by moving the ecogrid query syntax transformers
1491
         *  directly into the Metacat codebase.  MBJ 2010-02-03
1492
         
1493
        try {
1494
            EcogridQueryParser parser = new EcogridQueryParser(request
1495
                    .getReader());
1496
            parser.parseXML();
1497
            QueryType queryType = parser.getEcogridQuery();
1498
            EcogridJavaToMetacatJavaQueryTransformer queryTransformer = 
1499
                new EcogridJavaToMetacatJavaQueryTransformer();
1500
            QuerySpecification metacatQuery = queryTransformer
1501
                    .transform(queryType);
1502

    
1503
            DBQuery metacat = new DBQuery();
1504

    
1505
            boolean useXMLIndex = (new Boolean(PropertyService
1506
                    .getProperty("database.usexmlindex"))).booleanValue();
1507
            String xmlquery = "query"; // we don't care the query in resultset,
1508
            // the query can be anything
1509
            PrintWriter out = null; // we don't want metacat result, so set out null
1510

    
1511
            // parameter: queryspecification, user, group, usingIndexOrNot
1512
            StringBuffer result = metacat.createResultDocument(xmlquery,
1513
                    metacatQuery, out, username, groupNames, useXMLIndex);
1514

    
1515
            // create result set transfer       
1516
            String saxparser = PropertyService.getProperty("xml.saxparser");
1517
            MetacatResultsetParser metacatResultsetParser = new MetacatResultsetParser(
1518
                    new StringReader(result.toString()), saxparser, queryType
1519
                            .getNamespace().get_value());
1520
            ResultsetType records = metacatResultsetParser.getEcogridResult();
1521

    
1522
            System.out
1523
                    .println(EcogridResultsetTransformer.toXMLString(records));
1524
            response.setContentType("text/xml");
1525
            out = response.getWriter();
1526
            out.print(EcogridResultsetTransformer.toXMLString(records));
1527

    
1528
        } catch (Exception e) {
1529
            e.printStackTrace();
1530
        }*/
1531
        response.setContentType("text/xml");
1532
        response.setStatus(501);
1533
        PrintWriter out = response.getWriter();
1534
        out.print("<error>Query operation not yet supported by Metacat.</error>");
1535
        out.close();
1536
    }
1537
    
1538
    /**
1539
     * locate the boundary marker for an MMP
1540
     * @param is
1541
     * @return
1542
     * @throws IOException
1543
     */
1544
    protected static String[] findBoundaryString(InputStream is)
1545
        throws IOException
1546
    {
1547
        String[] endResult = new String[2];
1548
        String boundary = "";
1549
        String searchString = "boundary=";
1550
        boolean doneWithCurrentArray = false;
1551
        byte[] b = new byte[1024];
1552
        int numbytes = is.read(b, 0, 1024);
1553

    
1554
        while(numbytes != -1)
1555
        {
1556
            String s = new String(b, 0, numbytes);
1557
            int searchStringIndex = s.indexOf(searchString);
1558
            
1559
            if(s.indexOf("\"", searchStringIndex + searchString.length() + 1) == -1)
1560
            { //the end of the boundary is in the next byte array
1561
                boundary = s.substring(searchStringIndex + searchString.length() + 1, s.length());
1562
            }
1563
            else if(!boundary.startsWith("--"))
1564
            { //we can read the whole boundary from this byte array
1565
                boundary = s.substring(searchStringIndex + searchString.length() + 1, 
1566
                    s.indexOf("\"", searchStringIndex + searchString.length() + 1));
1567
                boundary = "--" + boundary;
1568
                endResult[0] = boundary;
1569
                endResult[1] = s.substring(s.indexOf("\"", searchStringIndex + searchString.length() + 1) + 1,
1570
                        s.length());
1571
                break;
1572
            }
1573
            else
1574
            { //we're now reading the 2nd byte array to get the rest of the boundary
1575
                searchString = "\"";
1576
                searchStringIndex = s.indexOf(searchString);
1577
                boundary += s.substring(0, searchStringIndex);
1578
                boundary = "--" + boundary;
1579
                endResult[0] = boundary;
1580
                endResult[1] = s.substring(s.indexOf("\"", searchStringIndex + searchString.length() + 1) + 1,
1581
                        s.length());
1582
                break;
1583
            }
1584
        }
1585
        System.out.println("boundary is: '" + boundary + "'");
1586
        return endResult;
1587
    }
1588
    
1589
    /**
1590
     * return the directory where temp files are stored
1591
     * @return
1592
     */
1593
    protected static File getTempDirectory()
1594
    {
1595
        File tmpDir = null;
1596
        Logger logMetacat = Logger.getLogger(ResourceHandler.class);
1597
        try
1598
        {
1599
            tmpDir = new File(PropertyService.getProperty("application.tempDir"));
1600
        }
1601
        catch(PropertyNotFoundException pnfe)
1602
        {
1603
            logMetacat.error("ResourceHandler.writeMMPPartstoFiles: " +
1604
                    "application.tmpDir not found.  Using /tmp instead.");
1605
            tmpDir = new File("/tmp");
1606
        }
1607
        return tmpDir;
1608
    }
1609
    
1610
    /**
1611
     * return a tmp file with a given name
1612
     * @param name
1613
     * @return
1614
     */
1615
    private static File getTempFile(String name)
1616
    {
1617
        File tmpDir = getTempDirectory();
1618
        File f = new File(tmpDir, name);
1619
        return f;
1620
    }
1621
    
1622
    /**
1623
     * return a temp file with a default name
1624
     * @return
1625
     */
1626
    private static File getTempFile()
1627
    {
1628
        return getTempFile(new Date().getTime() + ".tmp");
1629
    }
1630
    
1631
    /**
1632
     * Earthgrid API > Put Service >Put Function : calls MetacatHandler > handleInsertOrUpdateAction 
1633
     * 
1634
     * @param guid - ID of data object to be inserted or updated.  If action is update, the pid
1635
     *               is the existing pid.  If insert, the pid is the new one
1636
     * @throws IOException
1637
     */
1638
    protected void putObject(String pid, String action) {
1639
        System.out.println("ResourceHandler: putObject with pid " + pid);
1640
        logMetacat.debug("Entering putObject: " + pid + "/" + action);
1641
        OutputStream out = null;
1642
        try {
1643
            out = response.getOutputStream();
1644
            response.setStatus(200);
1645
            response.setContentType("text/xml");
1646
        } catch (IOException e1) {
1647
            logMetacat.error("Could not get the output stream for writing in putObject");
1648
        }
1649
        try {
1650
            
1651
            // Read the incoming data from its Mime Multipart encoding
1652
            logMetacat.debug("Disassembling MIME multipart form");
1653
            InputStream object = null;
1654
            InputStream sysmeta = null;
1655
            Map<String, List<String>> multipartparams;
1656
            
1657
            try
1658
            {
1659
                //String req = IOUtils.toString(request.getInputStream());
1660
                //System.out.println("request: " + req);
1661
                //InputStream reqStr = IOUtils.toInputStream(req);
1662
                InputStream reqStr = request.getInputStream();
1663
                
1664
                //handle MMP inputs
1665
                File tmpDir = getTempDirectory();
1666
                File tmpSMFile = new File(tmpDir + 
1667
                        ".sysmeta." + new Date().getTime() + ".tmp");
1668
                System.out.println("temp dir: " + tmpDir.getAbsolutePath());
1669
                MultipartRequestResolver mrr = new MultipartRequestResolver(
1670
                        tmpDir.getAbsolutePath(), 1000000000, 0);
1671
                MultipartRequest mr = mrr.resolveMultipart(request);
1672
                System.out.println("resolved multipart request");
1673
                Map<String, File> files = mr.getMultipartFiles();
1674
                if(files == null)
1675
                {
1676
                    throw new ServiceFailure("1202", "create/update must have multipart files with names 'object' and 'sysmeta'");
1677
                }
1678
                System.out.println("got multipart files");
1679
                
1680
                if(files.keySet() == null)
1681
                {
1682
                    System.out.println("No file keys in MMP request.");
1683
                    throw new ServiceFailure("1202", "No file keys found in MMP.  " +
1684
                            "create/update must have multipart files with names 'object' and 'sysmeta'");
1685
                }
1686

    
1687
		// for logging purposes, dump out the key-value pairs that constitute the request
1688
		// 3 types exist: request params, multipart params, and multipart files
1689
                Iterator it = files.keySet().iterator();
1690
                System.out.println("iterating through request parts: " + it);
1691
                while(it.hasNext())
1692
                {
1693
                    String key = (String)it.next();
1694
                    System.out.println("files key: " + key);
1695
                    System.out.println("files value: " + files.get(key));
1696
                }
1697
                
1698
                multipartparams = mr.getMultipartParameters();
1699
                it = multipartparams.keySet().iterator();
1700
                while(it.hasNext())
1701
                {
1702
                    String key = (String)it.next();
1703
                    System.out.println("multipartparams key: " + key);
1704
                    System.out.println("multipartparams value: " + multipartparams.get(key));
1705
                }
1706
                
1707
                it = params.keySet().iterator();
1708
                while(it.hasNext())
1709
                {
1710
                    String key = (String)it.next();
1711
                    System.out.println("param key: " + key);
1712
                    System.out.println("param value: " + params.get(key));
1713
                }
1714
		System.out.println("done iterating the request...");
1715

    
1716
                File smFile = files.get("sysmeta");
1717
		if (smFile == null) 
1718
		    throw new InvalidRequest("1102", "Missing the required file-part 'sysmeta' from the multipart request.");
1719
                System.out.println("smFile: " + smFile.getAbsolutePath());
1720
                sysmeta = new FileInputStream(smFile);
1721
                File objFile = files.get("object");
1722
		if (objFile == null) 
1723
		    throw new InvalidRequest("1102", "Missing the required file-part 'object' from the multipart request.");
1724

    
1725
                System.out.println("objectfile: " + objFile.getAbsolutePath());
1726
                object = new FileInputStream(objFile);
1727
                
1728
                /*String obj = IOUtils.toString(object);
1729
                String sm = IOUtils.toString(sysmeta);
1730
                System.out.println("object: " + obj);
1731
                System.out.println("sm: " + sm);
1732
                object = IOUtils.toInputStream(obj);
1733
                sysmeta = IOUtils.toInputStream(sm);*/
1734
                
1735
            }
1736
            catch(org.apache.commons.fileupload.FileUploadException fue)
1737
            {
1738
                throw new ServiceFailure("1202", "Could not upload MMP files: " + fue.getMessage());
1739
            }
1740
            catch(IOException ioe)
1741
            {
1742
                throw new ServiceFailure("1202", 
1743
                        "IOException when processing Mime Multipart: " + ioe.getMessage());
1744
            }
1745
            catch(Exception e)
1746
            {
1747
                throw new ServiceFailure("1202", "Error handling MMP upload: " + e.getClass() + ": " + e.getMessage());
1748
            }
1749
            
1750
            if ( action.equals(FUNCTION_NAME_INSERT)) { //handle inserts
1751

    
1752
                // Check if the objectId exists
1753
                IdentifierManager im = IdentifierManager.getInstance();
1754
                if (im.identifierExists(pid)) {
1755
                    throw new IdentifierNotUnique("1000", "Identifier is already in use: " + pid);
1756
                }
1757

    
1758
                logMetacat.debug("Commence creation...");
1759
                IBindingFactory bfact =
1760
                    BindingDirectory.getFactory(SystemMetadata.class);
1761
                IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1762
                SystemMetadata smd = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
1763

    
1764
                Identifier id = new Identifier();
1765
                id.setValue(pid);
1766
                System.out.println("creating object with pid " + id.getValue());
1767
                Identifier rId = MNodeService.getInstance().create(session, id, object, smd);
1768
                serializeServiceType(Identifier.class, rId, out);
1769
                
1770
            } else if (action.equals(FUNCTION_NAME_UPDATE)) { //handle updates
1771

    
1772
            	// Check if the objectId exists
1773
                IdentifierManager im = IdentifierManager.getInstance();
1774
                if (!im.identifierExists(pid)) {
1775
                    throw new NotFound("1280", "The pid you are trying to update does not exist: " + pid);
1776
                }
1777
                // check that the newPid parameter was provided and it doesn't exist
1778
                if(multipartparams.get("newPid") == null)
1779
                    throw new InvalidRequest("1202", "'newPid' must be contained in the request parameters.");
1780
                String newPidString = multipartparams.get("newPid").get(0);
1781
                if (im.identifierExists(newPidString)) 
1782
                    throw new IdentifierNotUnique("1220", "Identifier is already in use: " + newPidString);
1783
               
1784
                
1785
                Identifier newPid = new Identifier();
1786
                Identifier obsoletedPid = new Identifier();
1787
                newPid.setValue(newPidString);
1788
                obsoletedPid.setValue(pid);
1789
               
1790
                logMetacat.debug("Commence update...");
1791
                
1792
                //get the systemmetadata
1793
                IBindingFactory bfact =
1794
                	BindingDirectory.getFactory(SystemMetadata.class);
1795
                IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1796
                SystemMetadata smd = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
1797

    
1798
                Identifier rId = MNodeService.getInstance().update(session, newPid, object, obsoletedPid, smd);
1799
                serializeServiceType(Identifier.class, rId, out);
1800
            } else {
1801
                throw new InvalidRequest("1000", "Operation must be create or update.");
1802
            }
1803
            
1804
            //clean up the MMP files
1805
            //parts.get("systemmetadata").delete();
1806
            //parts.get("object").delete();
1807
        } catch (NotAuthorized e) {
1808
            response.setStatus(500);
1809
            serializeException(e, out);
1810
        } catch (InvalidToken e) {
1811
            response.setStatus(500);
1812
            serializeException(e, out);
1813
        } catch (ServiceFailure e) {
1814
            response.setStatus(500);
1815
            serializeException(e, out);
1816
        } catch (NotFound e) {
1817
            response.setStatus(500);
1818
            serializeException(e, out);
1819
        } catch (IdentifierNotUnique e) {
1820
            response.setStatus(500);
1821
            serializeException(e, out);
1822
        } catch (UnsupportedType e) {
1823
            response.setStatus(500);
1824
            serializeException(e, out);
1825
        } catch (InsufficientResources e) {
1826
            response.setStatus(500);
1827
            serializeException(e, out);
1828
        } catch (InvalidSystemMetadata e) {
1829
            response.setStatus(500);
1830
            serializeException(e, out);
1831
        } catch (NotImplemented e) {
1832
            response.setStatus(500);
1833
            serializeException(e, out);
1834
        } catch (InvalidRequest e) {
1835
            response.setStatus(500);
1836
            serializeException(e, out);
1837
        } /*catch (MessagingException e) {
1838
            ServiceFailure sf = new ServiceFailure("1000", e.getMessage());
1839
            serializeException(sf, out);
1840
        } catch (IOException e) {
1841
            response.setStatus(500);
1842
            ServiceFailure sf = new ServiceFailure("1000", e.getMessage());
1843
            serializeException(sf, out);
1844
        }*/ catch (JiBXException e) {
1845
            response.setStatus(500);
1846
            e.printStackTrace(System.out);
1847
            InvalidSystemMetadata ism = new InvalidSystemMetadata("1080", e.getMessage());
1848
            serializeException(ism, out);
1849
        }
1850
    }
1851

    
1852
    /**
1853
     * Handle delete 
1854
     * @param guid ID of data object to be deleted
1855
     * @throws IOException
1856
     */
1857
    private void deleteObject(String guid) throws IOException 
1858
    {
1859
        // Look up the localId for this global identifier
1860
        System.out.println("!!!!!!!!!!!!!!!!!deleting object " + guid);
1861
        IdentifierManager im = IdentifierManager.getInstance();
1862
        String localId = "";
1863
        OutputStream out = response.getOutputStream();
1864
        response.setStatus(200);
1865
        try {
1866
            localId = im.getLocalId(guid);
1867
        } catch (McdbDocNotFoundException e) {
1868
            NotFound nf = new NotFound("1340", "Document with guid " + guid + " not found.");
1869
            response.setStatus(404);
1870
            serializeException(nf, out);
1871
        }
1872
       
1873
        
1874
        Identifier id = new Identifier();
1875
        id.setValue(guid);
1876
        try
1877
        {
1878
            System.out.println("Calling delete");
1879
            MNodeService.getInstance().delete(session, id);
1880
            serializeServiceType(Identifier.class, id, out);
1881
        } 
1882
        catch (NotAuthorized e) {
1883
            response.setStatus(500);
1884
            serializeException(e, out);
1885
        } catch (InvalidToken e) {
1886
            response.setStatus(500);
1887
            serializeException(e, out);
1888
        } catch (ServiceFailure e) {
1889
            response.setStatus(500);
1890
            serializeException(e, out);
1891
        } catch (NotImplemented e) {
1892
            response.setStatus(500);
1893
            serializeException(e, out);
1894
        } catch (InvalidRequest e) {
1895
            response.setStatus(500);
1896
            serializeException(e, out);
1897
        } catch(NotFound e) {
1898
            response.setStatus(500);
1899
            serializeException(e, out);
1900
        } catch(JiBXException e) {
1901
            response.setStatus(500);
1902
            serializeException(new ServiceFailure("1350", "JiBXException: " + e.getMessage()), out);
1903
        }
1904
        out.close();
1905
    }
1906
    
1907
    /**
1908
     * set the access perms on a document
1909
     * @throws Exception
1910
     */
1911
    protected void setaccess() throws Exception
1912
    {
1913
        try
1914
        {
1915
            String guid = params.get("guid")[0];
1916
            Identifier id = new Identifier();
1917
            id.setValue(guid);
1918
            String accesspolicy = params.get("accesspolicy")[0];
1919
            AccessPolicy accessPolicy = (AccessPolicy) deserializeServiceType(AccessPolicy.class, new ByteArrayInputStream(accesspolicy.getBytes("UTF-8")));
1920
            MNodeService.getInstance().setAccessPolicy(session, id, accessPolicy);
1921
        }
1922
        catch(Exception e)
1923
        {
1924
            response.setStatus(500);
1925
            printError("Error setting access in ResourceHandler: " + e.getClass() + ": " + e.getMessage(), response);
1926
            throw e;
1927
        }
1928
    }
1929

    
1930
    /**
1931
     * Earthgrid API > Authentication Service > Login Function : calls MetacatHandler > handleLoginAction
1932
     * 
1933
     * @throws IOException
1934
     */
1935
    private void login() throws IOException {
1936
        PrintWriter out = response.getWriter();
1937
        response.setStatus(200);
1938
        response.setContentType("text/xml");
1939
        handler.handleLoginAction(out, params, request, response);
1940
        out.close();
1941
    }
1942

    
1943
    /**
1944
     * Earthgrid API > Authentication Service > Logout Function : calls MetacatHandler > handleLogoutAction
1945
     * 
1946
     * @throws IOException
1947
     */
1948
    private void logout() throws IOException {
1949
        PrintWriter out = response.getWriter();
1950
        response.setStatus(200);
1951
        response.setContentType("text/xml");
1952
        handler.handleLogoutAction(out, params, request, response);
1953
        out.close();
1954
    }
1955

    
1956
    /**
1957
     * Prints xml response
1958
     * @param message Message to be displayed
1959
     * @param response Servlet response that xml message will be printed 
1960
     * */
1961
    protected void printError(String message, HttpServletResponse response) {
1962
        try {
1963
            logMetacat.error("ResourceHandler: Printing error to servlet response: " + message);
1964
            PrintWriter out = response.getWriter();
1965
            response.setContentType("text/xml");
1966
            out.println("<?xml version=\"1.0\"?>");
1967
            out.println("<error>");
1968
            out.println(message);
1969
            out.println("</error>");
1970
            out.close();
1971
        } catch (IOException e) {
1972
            e.printStackTrace();
1973
        }
1974
    }
1975
    
1976
    /**
1977
     * serialize a D1 exception using jibx
1978
     * @param e
1979
     * @param out
1980
     */
1981
    protected void serializeException(BaseException e, OutputStream out) {
1982
        // TODO: Use content negotiation to determine which return format to use
1983
        response.setContentType("text/xml");
1984
        response.setStatus(e.getCode());
1985
        
1986
        logMetacat.error("ResourceHandler: Serializing exception with code " + e.getCode() + ": " + e.getMessage());
1987
        e.printStackTrace();
1988
        
1989
        try {
1990
            IOUtils.write(e.serialize(BaseException.FMT_XML), out);
1991
        } catch (IOException e1) {
1992
            logMetacat.error("Error writing exception to stream. " 
1993
                    + e1.getMessage());
1994
        }
1995
    }
1996

    
1997

    
1998
    /**
1999
     * List the object formats registered with the system
2000
     */
2001
		private void listFormats() {
2002
      logMetacat.debug("Entering listFormats()");
2003
      // get the response output stream
2004
      OutputStream out = null;
2005
      
2006
      try {
2007
	      out = response.getOutputStream();
2008
	      response.setStatus(200);
2009
	      response.setContentType("text/xml");
2010
	      
2011
      } catch (IOException ioe) {
2012
      	logMetacat.error("Could not get the output stream for writing" +
2013
      	  "in ResourceHandler.listFormats()");
2014
      
2015
      }
2016

    
2017
      // get the object format list
2018
      try {
2019
	      ObjectFormatList objectFormatList = CNodeService.getInstance().listFormats();
2020
	      serializeServiceType(ObjectFormatList.class, objectFormatList, out);
2021
      
2022
      } catch (InvalidRequest e) {
2023
      	response.setStatus(200);
2024
      	serializeException(e, out);
2025
      	
2026
      } catch (ServiceFailure e) {
2027
      	response.setStatus(501);
2028
      	serializeException(e, out);
2029
      
2030
      } catch (NotFound e) {
2031
      	response.setStatus(200);
2032
      	serializeException(e, out);
2033
      
2034
      } catch (InsufficientResources e) {
2035
      	response.setStatus(200);
2036
      	serializeException(e, out);
2037
      
2038
      } catch (NotImplemented e) {
2039
      	response.setStatus(200);
2040
      	serializeException(e, out);
2041
      
2042
      } catch (JiBXException jibxe) {
2043
      	response.setStatus(501);
2044
      	ServiceFailure e = 
2045
      		new ServiceFailure("4841", "Unexpected exception from the service - " + 
2046
        	                   jibxe.getClass() + ": " + jibxe.getMessage());
2047
      	serializeException(e, out);
2048
      	
2049
      }
2050
      
2051
    }
2052

    
2053
		/**
2054
     * Return the requested object format
2055
     * 
2056
     * @param fmtidStr the requested format identifier as a string
2057
     */
2058
    private void getFormat(String fmtidStr) {
2059
      logMetacat.debug("Entering listFormats()");
2060
      
2061
      // get the response output stream
2062
      OutputStream out = null;
2063
      try {
2064
	      out = response.getOutputStream();
2065
	      response.setStatus(200);
2066
	      response.setContentType("text/xml");
2067
	      
2068
      } catch (IOException ioe) {
2069
      	logMetacat.error("Could not get the output stream for writing" +
2070
      	  "in ResourceHandler.listFormats()");
2071
      
2072
      }
2073
      
2074
      ObjectFormatIdentifier fmtid = new ObjectFormatIdentifier();
2075
      fmtid.setValue(fmtidStr);
2076
      
2077
      try {
2078
      	// get the specified object format
2079
	      ObjectFormat objectFormat = CNodeService.getInstance().getFormat(fmtid);
2080
	      serializeServiceType(ObjectFormat.class, objectFormat, out);
2081

    
2082
      } catch (InvalidRequest e) {
2083
      	response.setStatus(200);
2084
      	serializeException(e, out);
2085
      
2086
      } catch (ServiceFailure e) {
2087
      	response.setStatus(501);
2088
      	serializeException(e, out);
2089
      
2090
      } catch (NotFound e) {
2091
      	response.setStatus(200);
2092
      	serializeException(e, out);
2093
      
2094
      } catch (InsufficientResources e) {
2095
      	response.setStatus(200);
2096
      	serializeException(e, out);
2097
      
2098
      } catch (NotImplemented e) {
2099
      	response.setStatus(200);
2100
      	serializeException(e, out);
2101
      
2102
      } catch (JiBXException jibxe) {
2103
      	ServiceFailure e = 
2104
      		new ServiceFailure("4841", "Unexpected exception from the service - " + 
2105
        	                   jibxe.getClass() + ": " + jibxe.getMessage());
2106
      	serializeException(e, out);
2107

    
2108
      }
2109
	    
2110
    }
2111

    
2112
    /**
2113
     * Register System Metadata without data or metadata object
2114
     * @param pid identifier for System Metadata entry
2115
     */
2116
    protected void registerSystemMetadata(String pid) {
2117
		logMetacat.debug("Entering registerSystemMetadata: " + pid);
2118
		OutputStream out = null;
2119
		try {
2120
			out = response.getOutputStream();
2121
			response.setStatus(200);
2122
			response.setContentType("text/xml");
2123
		} catch (IOException e1) {
2124
			logMetacat.error("Could not get the output stream for writing in putObject");
2125
		}
2126
		try {
2127

    
2128
			// Read the incoming data from its Mime Multipart encoding
2129
			logMetacat.debug("Disassembling MIME multipart form");
2130
			InputStream sysmeta = null;
2131
			Map<String, List<String>> multipartparams;
2132

    
2133
			try {
2134

    
2135
				// handle MMP inputs
2136
				File tmpDir = getTempDirectory();
2137

    
2138
				logMetacat.debug("temp dir: " + tmpDir.getAbsolutePath());
2139
				MultipartRequestResolver mrr = new MultipartRequestResolver(
2140
						tmpDir.getAbsolutePath(), 1000000000, 0);
2141
				MultipartRequest mr = mrr.resolveMultipart(request);
2142
				logMetacat.debug("resolved multipart request");
2143
				Map<String, File> files = mr.getMultipartFiles();
2144
				if (files == null) {
2145
					throw new ServiceFailure("1202",
2146
							"register meta must have multipart file with name 'sysmeta'");
2147
				}
2148
				logMetacat.debug("got multipart files");
2149

    
2150
				if (files.keySet() == null) {
2151
					logMetacat.error("No file keys in MMP request.");
2152
					throw new ServiceFailure(
2153
							"1202",
2154
							"No file keys found in MMP.  "
2155
									+ "register meta must have multipart file with name 'sysmeta'");
2156
				}
2157

    
2158
				// for logging purposes, dump out the key-value pairs that
2159
				// constitute the request
2160
				// 3 types exist: request params, multipart params, and
2161
				// multipart files
2162
				Iterator it = files.keySet().iterator();
2163
				logMetacat.debug("iterating through request parts: " + it);
2164
				while (it.hasNext()) {
2165
					String key = (String) it.next();
2166
					logMetacat.debug("files key: " + key);
2167
					logMetacat.debug("files value: " + files.get(key));
2168
				}
2169

    
2170
				multipartparams = mr.getMultipartParameters();
2171
				it = multipartparams.keySet().iterator();
2172
				while (it.hasNext()) {
2173
					String key = (String) it.next();
2174
					logMetacat.debug("multipartparams key: " + key);
2175
					logMetacat.debug("multipartparams value: "
2176
							+ multipartparams.get(key));
2177
				}
2178

    
2179
				it = params.keySet().iterator();
2180
				while (it.hasNext()) {
2181
					String key = (String) it.next();
2182
					logMetacat.debug("param key: " + key);
2183
					logMetacat.debug("param value: " + params.get(key));
2184
				}
2185
				logMetacat.debug("done iterating the request...");
2186

    
2187
				File smFile = files.get("sysmeta");
2188
				if (smFile == null) {
2189
					throw new InvalidRequest("1102",
2190
							"Missing the required file-part 'sysmeta' from the multipart request.");
2191
				}
2192
				logMetacat.debug("smFile: " + smFile.getAbsolutePath());
2193
				sysmeta = new FileInputStream(smFile);
2194

    
2195
			} catch (org.apache.commons.fileupload.FileUploadException fue) {
2196
				throw new ServiceFailure("1202", "Could not upload MMP files: "
2197
						+ fue.getMessage());
2198
			} catch (IOException ioe) {
2199
				throw new ServiceFailure("1202",
2200
						"IOException when processing Mime Multipart: "
2201
								+ ioe.getMessage());
2202
			} catch (Exception e) {
2203
				throw new ServiceFailure("1202", "Error handling MMP upload: "
2204
						+ e.getClass() + ": " + e.getMessage());
2205
			}
2206

    
2207
			// Check if the objectId exists
2208
			IdentifierManager im = IdentifierManager.getInstance();
2209
			if (im.identifierExists(pid)) {
2210
				throw new IdentifierNotUnique("1000",
2211
						"Identifier is already in use: " + pid);
2212
			}
2213

    
2214
			logMetacat.debug("Commence creation...");
2215
			IBindingFactory bfact = BindingDirectory
2216
					.getFactory(SystemMetadata.class);
2217
			IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
2218
			SystemMetadata systemMetadata = (SystemMetadata) uctx
2219
					.unmarshalDocument(sysmeta, null);
2220

    
2221
			Identifier guid = new Identifier();
2222
			guid.setValue(pid);
2223
			logMetacat.debug("registering system metadata with pid "
2224
					+ guid.getValue());
2225
			boolean result = CNodeService.getInstance().registerSystemMetadata(
2226
					session, guid, systemMetadata);
2227
			serializeServiceType(Boolean.class, result, out);
2228

    
2229
		} catch (NotAuthorized e) {
2230
			response.setStatus(500);
2231
			serializeException(e, out);
2232
		} catch (ServiceFailure e) {
2233
			response.setStatus(500);
2234
			serializeException(e, out);
2235
		} catch (IdentifierNotUnique e) {
2236
			response.setStatus(500);
2237
			serializeException(e, out);
2238
		} catch (NotImplemented e) {
2239
			response.setStatus(500);
2240
			serializeException(e, out);
2241
		} catch (InvalidRequest e) {
2242
			response.setStatus(500);
2243
			serializeException(e, out);
2244
		} catch (JiBXException e) {
2245
			response.setStatus(500);
2246
			e.printStackTrace(System.out);
2247
			InvalidSystemMetadata ism = new InvalidSystemMetadata("1080", e
2248
					.getMessage());
2249
			serializeException(ism, out);
2250
		} catch (InvalidSystemMetadata e) {
2251
			serializeException(e, out);
2252
    }
2253
	}
2254

    
2255
}
(10-10/11)