Project

General

Profile

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

    
25
import java.io.*;
26
import java.util.*;
27

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

    
39

    
40
import org.apache.commons.httpclient.util.DateParser;
41
import org.apache.commons.io.IOUtils;
42
import org.apache.log4j.Logger;
43
import org.dataone.service.exceptions.BaseException;
44
import org.dataone.service.exceptions.IdentifierNotUnique;
45
import org.dataone.service.exceptions.InsufficientResources;
46
import org.dataone.service.exceptions.InvalidRequest;
47
import org.dataone.service.exceptions.InvalidSystemMetadata;
48
import org.dataone.service.exceptions.InvalidToken;
49
import org.dataone.service.exceptions.NotAuthorized;
50
import org.dataone.service.exceptions.NotImplemented;
51
import org.dataone.service.exceptions.ServiceFailure;
52
import org.dataone.service.exceptions.UnsupportedType;
53
import org.dataone.service.exceptions.NotFound;
54
import org.dataone.service.types.*;
55
import org.jibx.runtime.BindingDirectory;
56
import org.jibx.runtime.IBindingFactory;
57
import org.jibx.runtime.IMarshallingContext;
58
import org.jibx.runtime.IUnmarshallingContext;
59
import org.jibx.runtime.JiBXException;
60

    
61
import edu.ucsb.nceas.metacat.DBUtil;
62
import edu.ucsb.nceas.metacat.IdentifierManager;
63
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
64
import edu.ucsb.nceas.metacat.MetacatHandler;
65
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
66
import edu.ucsb.nceas.metacat.dataone.CrudService;
67
import edu.ucsb.nceas.metacat.service.SessionService;
68
import edu.ucsb.nceas.metacat.util.RequestUtil;
69
import edu.ucsb.nceas.metacat.util.SessionData;
70

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

    
144
 * </ul>
145
 * </li>
146
 * 
147
 * <li>
148
 * <h3>EarthGrid Identifier Service</h3><br/>
149
 * 
150
 * <ul>
151
 * <li><h3>isRegistered: </h3>		<br/>
152
 * <b>REST URL:</b>	<code>GET, [context-root]/identifier/[doc-id]?op=isregistered</code>   <br/>
153
 * <b>Returns:</b> message in XML format<br/><br/>
154
 * </li>
155

    
156
 * <li><h3>getAllDocIds:</h3>		<br/>		
157
 * <b>REST URL:</b>	<code>GET, [context-root]/identifier?op=getalldocids</code>   <br/>
158
 * <b>Returns:</b> document id list in XML format<br/><br/>
159
 * </li>
160
 * 
161
 * <li><h3>addLSID Function:</h3> 
162
 * Metacat does not support this function 		<br/>
163
 * <b>REST URL:</b>	<code>PUT, [context-root]/identifier/[doc-id]</code>   <br/>
164
 * <b>Returns:</b> error message in XML format<br/><br/>
165
 * </li>
166
 * 
167
 * <li><h3>getNextRevision:</h3>		<br/>
168
 * <b>REST URL:</b>	<code>GET, [context-root]/identifier/[doc-id]?op=getnextrevision</code>   <br/>
169
 * <b>Returns:</b> message in XML format<br/><br/>
170
 * </li>
171
 * 
172
 * <li><h3>getNextObject:</h3>		<br/>
173
 * <b>REST URL:</b>	<code>GET, [context-root]/identifier?op=getnextobject&scope=[scope]</code>   <br/>
174
 * <b>Returns:</b> message in XML format<br/><br/>
175
 * </li>
176
 * 
177
 * </li>
178
 * </ul>
179
 * 
180
 */
181
public class ResourceHandler {
182

    
183
    /**HTTP Verb GET*/
184
    public static final byte GET = 1;
185
    /**HTTP Verb POST*/
186
    public static final byte POST = 2;
187
    /**HTTP Verb PUT*/
188
    public static final byte PUT = 3;
189
    /**HTTP Verb DELETE*/
190
    public static final byte DELETE = 4;
191

    
192
    /*
193
     * API Resources
194
     */
195
    private static final String RESOURCE_OBJECTS = "object";
196
    private static final String RESOURCE_META = "meta";
197
    private static final String RESOURCE_SESSION = "session";
198
    private static final String RESOURCE_IDENTIFIER = "identifier";
199
    private static final String RESOURCE_LOG = "log";
200

    
201
    /*
202
     * API Functions used as URL parameters
203
     */
204
    private static final String FUNCTION_KEYWORD = "op";
205
    private static final String FUNCTION_NAME_LOGIN = "login";
206
    private static final String FUNCTION_NAME_LOGOUT = "logout";
207
    private static final String FUNCTION_NAME_SET_ACCESS = "setaccess";
208
    private static final String FUNCTION_NAME_ISREGISTERED = "isregistered";
209
    private static final String FUNCTION_NAME_GETALLDOCS = "getalldocids";
210
    private static final String FUNCTION_NAME_GETNEXTREV = "getnextrevision";
211
    private static final String FUNCTION_NAME_GETNEXTOBJ = "getnextobject";
212
    private static final String FUNCTION_NAME_INSERT = "insert";
213
    private static final String FUNCTION_NAME_UPDATE = "update";
214
    private static final String FUNCTION_NAME_GENERATE_MISSING_SYSTEM_METADATA = "generatemissingsystemmetadata";
215

    
216
    private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
217
    
218
    private ServletContext servletContext;
219
    private Logger logMetacat;
220
    private MetacatHandler handler;
221
    private HttpServletRequest request;
222
    private HttpServletResponse response;
223
    private String username;
224
    private String password;
225
    private String sessionId;
226
    private String[] groupNames;
227

    
228
    private Hashtable<String, String[]> params;
229

    
230
    /**Initializes new instance by setting servlet context,request and response*/
231
    public ResourceHandler(ServletContext servletContext,
232
            HttpServletRequest request, HttpServletResponse response) {
233
        this.servletContext = servletContext;
234
        this.request = request;
235
        this.response = response;
236
    }
237

    
238
    /**
239
     * This function is called from REST APU servlet and handles each request to the servlet 
240
     * 
241
     * @param httpVerb (GET, POST, PUT or DELETE)
242
     */
243
    public void handle(byte httpVerb) {
244
        logMetacat = Logger.getLogger(ResourceHandler.class);
245
        try {
246
            String resource = request.getServletPath();
247
            String verb = "";
248
            
249
            System.out.println("handling verb " + httpVerb + " request with resource " + resource);
250
            boolean status = false;
251
            loadSessionData();
252

    
253
            if (resource != null) {
254
            	resource = request.getServletPath().substring(1);
255

    
256
            	params = new Hashtable<String, String[]>();
257
            	initParams();
258

    
259
            	Timer timer = new Timer();
260
            	handler = new MetacatHandler(timer);
261

    
262
            	if (resource.equals(RESOURCE_SESSION) && 
263
            			httpVerb == POST && 
264
            			params.get(FUNCTION_KEYWORD) != null) {
265
            		//System.out.println("function_keyword: " + params.get(FUNCTION_KEYWORD)[0]);
266
            		if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_LOGIN)) {
267
            			login();
268
            			status = true;
269
            		} else if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_LOGOUT)) {
270
            			logout();
271
            			status = true;
272
            		} else if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_SET_ACCESS)) {
273
            			setaccess();
274
            			status = true;
275
            			//System.out.println("done setting access");
276
            		}
277
            	} else if (resource.equals(RESOURCE_META)) {
278
            		if(params != null && params.get(FUNCTION_KEYWORD) != null &&
279
            				params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_GENERATE_MISSING_SYSTEM_METADATA))
280
            		{ //generate system metadata for any object that is
281
            			//a) not system metadata itself
282
            			//b) does not already have a system metadata id in the systemmetadata table
283
            			//c) not a BIN object (data)
284
            			generateMissingSystemMetadata();
285
            			status = true;
286
            		}
287
            		else
288
            		{
289
            			String objectId = request.getPathInfo();
290
            			if (objectId != null && objectId.length() > 1) 
291
            			{
292
            				objectId = request.getPathInfo().substring(1);
293
            			}
294
            			getSystemMetadataObject(objectId);
295
            			status = true;
296
            		}
297

    
298
            	} else if (resource.equals(RESOURCE_OBJECTS)) {
299
            		logMetacat.debug("D1 Rest: Starting resource processing...");
300
            		loadSessionData();
301

    
302
            		String objectId = request.getPathInfo();
303
            		if (objectId != null && objectId.length() > 1) 
304
            		{
305
            			objectId = request.getPathInfo().substring(1);
306
            		}
307
            		else
308
            		{
309
            			objectId = null;
310
            		}
311

    
312
            		logMetacat.debug("verb:" + httpVerb);
313

    
314
            		if (httpVerb == GET) {
315
            			getObject(objectId);
316
            			status = true;
317
            		} else if (httpVerb == POST) {
318
            			putObject(objectId, FUNCTION_NAME_INSERT);
319
            			status = true;
320
            		} else if (httpVerb == PUT) {
321
            			putObject(objectId, FUNCTION_NAME_UPDATE);
322
            			status = true;
323
            		} else if (httpVerb == DELETE) {
324
            			deleteObject(objectId);
325
            			status = true;
326
            		}
327

    
328
            	} else if (resource.equals(RESOURCE_IDENTIFIER)) {
329

    
330
            		String identifierId = request.getPathInfo();
331
            		if (identifierId != null && identifierId.length() > 1)
332
            			identifierId = request.getPathInfo().substring(1); //trim the slash
333

    
334
            		if (httpVerb == GET) {
335
            			String op = params.get(FUNCTION_KEYWORD)[0];
336
            			if (op.equals(FUNCTION_NAME_ISREGISTERED)) {
337
            				isRegistered(identifierId);
338
            				status = true;
339
            			} else if (op.equals(FUNCTION_NAME_GETALLDOCS)) {
340
            				getAllDocIds();
341
            				status = true;
342
            			} else if (op.equals(FUNCTION_NAME_GETNEXTREV)) {
343
            				getNextRevision(identifierId);
344
            				status = true;
345
            			} else if (op.equals(FUNCTION_NAME_GETNEXTOBJ)) {
346
            				getNextObject();
347
            				status = true;
348
            			} 
349

    
350
            		} else if (httpVerb == PUT) {
351
            			//Earthgrid API > Identifier Service > addLSID Function 
352
            			printError(
353
            					"This method is not supported by metacat.  To "
354
            					+ "add a new LSID, add a document to metacat.",
355
            					response);
356
            			status = true;
357
            		}
358

    
359
            	} else if (resource.equals(RESOURCE_LOG)) {
360
            		//handle log events
361
            		if(httpVerb == GET)
362
            		{
363
            			getLog();
364
            			status = true;
365
            		}
366
            		else
367
            		{
368
            			printError("POST, PUT, DELETE is not supported for logs.", response);
369
            			status = true;
370
            		}
371

    
372
            	}
373

    
374
            	if (!status)
375
            		printError("Incorrect parameters!", response);
376
            } else {
377
            	printError("Incorrect resource!", response);
378
            }
379
        } catch (Exception e) {
380
        	logMetacat.error(e.getMessage());
381
        	e.printStackTrace();
382
        }
383
    }
384
    
385
    /**
386
     * get the logs from the CrudService based on passed params.  Available 
387
     * params are token, fromDate, toDate, event.  See 
388
     * http://mule1.dataone.org/ArchitectureDocs/mn_api_crud.html#MN_crud.getLogRecords
389
     * for more info
390
     */
391
    private void getLog()
392
    {
393
        OutputStream out = null;
394
        try
395
        {
396
            out = response.getOutputStream();
397
            response.setContentType("text/xml");
398
            AuthToken token = new AuthToken(sessionId);
399
            String fromDateS = params.get("fromDate")[0];
400
            System.out.println("param fromDateS: " + fromDateS);
401
            Date fromDate = null;
402
            String toDateS = params.get("toDate")[0];
403
            System.out.println("param toDateS: " + toDateS);
404
            Date toDate = null;
405
            String eventS = params.get("event")[0];
406
            Event event = null;
407
            if(fromDateS != null)
408
            {
409
                //fromDate = dateFormat.parse(fromDateS);
410
                fromDate = parseDateAndConvertToGMT(fromDateS);
411
            }
412
            if(toDateS != null)
413
            {
414
                //toDate = dateFormat.parse(toDateS);
415
                toDate = parseDateAndConvertToGMT(toDateS);
416
            }
417
            if(eventS != null)
418
            {
419
                event = Event.convert(eventS);
420
            }
421
            System.out.println("fromDate: " + fromDate + " toDate: " + toDate);
422
            
423
            System.out.println("calling crudservice.getLogRecords");
424
            Log log = CrudService.getInstance().getLogRecords(token, fromDate, toDate, event);
425
            serializeServiceType(Log.class, log, out);
426
        }
427
        catch(Exception e)
428
        {
429
            String msg = "Could not get logs from CrudService: " + e.getMessage();
430
            ServiceFailure sf = new ServiceFailure("1490", msg);
431
            logMetacat.error(msg);
432
            e.printStackTrace();
433
            serializeException(sf, out);
434
        }
435
    }
436
    
437
    /**
438
     *  copies request parameters to a hashtable which is given as argument to native metacathandler functions  
439
     */
440
    private void initParams() {
441

    
442
        String name = null;
443
        String[] value = null;
444
        Enumeration paramlist = request.getParameterNames();
445
        while (paramlist.hasMoreElements()) {
446
            name = (String) paramlist.nextElement();
447
            value = request.getParameterValues(name);
448
            params.put(name, value);
449
        }
450
    }
451

    
452
    /**
453
     * 
454
     * Load user details of metacat session from the request 
455
     * 
456
     */
457
    private void loadSessionData()
458
      throws Exception
459
    {
460
        SessionData sessionData = RequestUtil.getSessionData(request);
461
        try
462
        {
463
            username = null;
464
            password = null;
465
            groupNames = null;
466
            sessionId = null;
467
            
468
            boolean validSession = false;
469
            SessionService ss = SessionService.getInstance();
470
            System.out.println("sessionData: " + sessionData);
471
            if(sessionData == null)
472
            {
473
                username = "public";
474
                sessionId = "0";
475
                System.out.println("sessiondata is null.  Creating a public session.");
476
                return;
477
            }
478
            
479
            System.out.println("username: " + sessionData.getUserName());
480
            System.out.println("sessionid: " + sessionData.getId());
481
            //validate the session
482
            if(ss.isSessionRegistered(sessionData.getId()) && 
483
               !(sessionData.getUserName().equals("public") || sessionData.getId().equals("0")))
484
            {
485
                validSession = true;
486
            }
487
            
488
            if(validSession)
489
            {
490
                //if the session is valid, set these variables
491
                username = sessionData.getUserName();
492
                password = sessionData.getPassword();
493
                groupNames = sessionData.getGroupNames();
494
                sessionId = sessionData.getId();
495
                System.out.println("setting sessionid to " + sessionId);
496
                System.out.println("username: " + username);
497
            }
498
            
499
            //if the session is not valid or the username is null, set
500
            //username to public
501
            if (username == null) 
502
            {
503
                System.out.println("setting username to public.");
504
                username = "public";
505
            }
506
        }
507
        catch(Exception e)
508
        {
509
            e.printStackTrace();
510
            throw new Exception("Could not load the session data: " + e.getMessage());
511
        }
512
    }
513
    
514
    /**
515
     * generate missing system metadata for any science metadata objects
516
     * that don't already have it. https://trac.dataone.org/ticket/591
517
     * 
518
     * called with POST meta/?op=generatemissingsystemmetadata
519
     */
520
    private void generateMissingSystemMetadata()
521
    {
522
        AuthToken token = new AuthToken(sessionId);
523
        CrudService.getInstance().generateMissingSystemMetadata(token);
524
    }
525

    
526
    /**
527
     *  Earthgrid API > Identifier Service > isRegistered Function : 
528
     *  calls MetacatHandler > handleIdIsRegisteredAction
529
     * @param guid
530
     * @throws IOException
531
     */
532
    private void isRegistered(String guid) throws IOException
533
    {
534
        
535
        // Look up the localId for this guid
536
        IdentifierManager im = IdentifierManager.getInstance();
537
        String localId = "";
538
        try {
539
            localId = im.getLocalId(guid);
540
        } catch (McdbDocNotFoundException e) {
541
            // TODO: Need to return the proper DataONE exception
542
        }
543
        
544
        params.put("docid", new String[] { localId });
545
        PrintWriter out = response.getWriter();
546
        response.setContentType("text/xml");
547
        handler.handleIdIsRegisteredAction(out, params, response);
548
        out.close();
549
    }
550

    
551
    /**
552
     * Earthgrid API > Identifier Service > getAllDocIds Function : 
553
     * calls MetacatHandler > handleGetAllDocidsAction
554
     * @throws IOException
555
     */
556
    private void getAllDocIds() throws IOException {
557
        PrintWriter out = response.getWriter();
558
        response.setContentType("text/xml");
559
        handler.handleGetAllDocidsAction(out, params, response);
560
        out.close();
561
    }
562

    
563
    /**
564
     * Earthgrid API > Identifier Service > getNextRevision Function : 
565
     * calls MetacatHandler > handleGetRevisionAndDocTypeAction
566
     * @param guid
567
     * @throws IOException
568
     */
569
    private void getNextRevision(String guid) throws IOException 
570
    {
571
        params.put("docid", new String[] { guid });
572
        PrintWriter out = response.getWriter();
573
        response.setContentType("text/xml");
574
        //handler.handleGetRevisionAndDocTypeAction(out, params);
575

    
576
        try {
577
            // Make sure there is a docid
578
            if (guid == null || guid.equals("")) {
579
                throw new Exception("User didn't specify docid!");
580
            }
581

    
582
            // Look up the localId for this guid
583
            IdentifierManager im = IdentifierManager.getInstance();
584
            String localId = "";
585
            try {
586
                localId = im.getLocalId(guid);
587
            } catch (McdbDocNotFoundException e) {
588
                // TODO: Need to return the proper DataONE exception
589
            }
590
           
591
            // Create a DBUtil object
592
            DBUtil dbutil = new DBUtil();
593
            // Get a rev and doctype
594
            String revAndDocType = dbutil
595
                    .getCurrentRevisionAndDocTypeForGivenDocument(localId);
596
            int revision = Integer.parseInt(revAndDocType.split(";")[0]) + 1;
597

    
598
            out.println("<?xml version=\"1.0\"?>");
599
            out.print("<next-revision>");
600
            out.print(revision);
601
            out.print("</next-revision>");
602

    
603
        } catch (Exception e) {
604
            // Handle exception
605
            out.println("<?xml version=\"1.0\"?>");
606
            out.println("<error>");
607
            out.println(e.getMessage());
608
            out.println("</error>");
609
        }
610

    
611
        out.close();
612
    }
613

    
614
    /**
615
     * Earthgrid API > Identifier Service > getNextObject Function : 
616
     * calls MetacatHandler > handleGetMaxDocidAction
617
     * @throws IOException
618
     */
619
    private void getNextObject() throws IOException {
620
        PrintWriter out = response.getWriter();
621
        response.setContentType("text/xml");
622
        handler.handleGetMaxDocidAction(out, params, response);
623
        out.close();
624
    }
625

    
626
    /**
627
     * Implements REST version of DataONE CRUD API --> get
628
     * @param guid ID of data object to be read
629
     */
630
    private void getObject(String guid) {
631
        CrudService cs = CrudService.getInstance();
632
        cs.setParamsFromRequest(request);
633
        AuthToken token = new AuthToken(sessionId);
634
        OutputStream out = null;
635
        try {
636
            out = response.getOutputStream();
637
            response.setContentType("text/xml");
638
            if(guid != null)
639
            { //get a specific document                
640
                Identifier id = new Identifier();
641
                id.setValue(guid);
642
                try
643
                {
644
                    if(token == null)
645
                    {
646
                        token = new AuthToken("Public");
647
                    }
648
                    InputStream data = cs.get(token, id);
649
                    IOUtils.copyLarge(data, response.getOutputStream());
650
                }
651
                catch(InvalidToken it)
652
                {
653
                    serializeException(it, out); 
654
                }
655
                catch(ServiceFailure sf)
656
                {
657
                    serializeException(sf, out); 
658
                }
659
                catch(NotAuthorized na)
660
                {
661
                    serializeException(na, out); 
662
                }
663
                catch(NotFound nf)
664
                {
665
                    serializeException(nf, out); 
666
                }
667
                catch(NotImplemented ni)
668
                {
669
                    serializeException(ni, out); 
670
                }
671
                catch(Exception e)
672
                {
673
                    System.out.println("Error with Crud.get().  " +
674
                            "If this is an 'Exception producing data' error, " +
675
                            "go to CrudService.get() for better debugging.  " +
676
                            "Here's the error: " + e.getMessage());
677
                    e.printStackTrace();
678
                    ServiceFailure sf = new ServiceFailure("1030", 
679
                            "IO Error in ResourceHandler.getObject: " + e.getMessage());
680
                    serializeException(sf, out); 
681
                }
682
            }
683
            else
684
            { //call listObjects with specified params
685
                Date startTime = null;
686
                Date endTime = null;
687
                ObjectFormat objectFormat = null;
688
                boolean replicaStatus = false;
689
                int start = 0;
690
                int count = 1000;
691
                Enumeration paramlist = request.getParameterNames();
692
                while (paramlist.hasMoreElements()) 
693
                { //parse the params and make the crud call
694
                    String name = (String) paramlist.nextElement();
695
                    String[] value = (String[])request.getParameterValues(name);
696
                    /*for(int i=0; i<value.length; i++)
697
                    {
698
                        System.out.println("name: " + name + " value: " + value[i]);
699
                    }*/
700
                    if(name.equals("startTime") && value != null)
701
                    {
702
                        try
703
                        {
704
                          //startTime = dateFormat.parse(value[0]);
705
                            startTime = parseDateAndConvertToGMT(value[0]);
706
                        }
707
                        catch(Exception e)
708
                        {  //if we can't parse it, just don't use the startTime param
709
                            System.out.println("Could not parse startTime: " + value[0]);
710
                            startTime = null;
711
                        }
712
                    }
713
                    else if(name.equals("endTime") && value != null)
714
                    {
715
                        try
716
                        {
717
                          //endTime = dateFormat.parse(value[0]);
718
                            endTime = parseDateAndConvertToGMT(value[0]);
719
                        }
720
                        catch(Exception e)
721
                        {  //if we can't parse it, just don't use the endTime param
722
                            System.out.println("Could not parse endTime: " + value[0]);
723
                            endTime = null;
724
                        }
725
                    }
726
                    else if(name.equals("objectFormat") && value != null)
727
                    {
728
                        objectFormat = ObjectFormat.convert(value[0]);
729
                    }
730
                    else if(name.equals("replicaStatus") && value != null)
731
                    {
732
                        if(value != null && 
733
                           value.length > 0 && 
734
                           (value[0].equals("true") || value[0].equals("TRUE") || value[0].equals("YES")))
735
                        {
736
                            replicaStatus = true;
737
                        }
738
                    }
739
                    else if(name.equals("start") && value != null)
740
                    {
741
                        start = new Integer(value[0]).intValue();
742
                    }
743
                    else if(name.equals("count") && value != null)
744
                    {
745
                        count = new Integer(value[0]).intValue();
746
                    }
747
                }
748
                //make the crud call
749
                /*System.out.println("token: " + token + " startTime: " + startTime +
750
                        " endtime: " + endTime + " objectFormat: " + 
751
                        objectFormat + " replicaStatus: " + replicaStatus + 
752
                        " start: " + start + " count: " + count);
753
                */
754
                ObjectList ol = cs.listObjects(token, startTime, endTime, 
755
                        objectFormat, replicaStatus, start, count);
756
                ol = cs.listObjects(token, startTime, endTime, objectFormat, replicaStatus, start, count);
757
                
758
                StringReader sr = new StringReader(ol.toString());                
759
                out = response.getOutputStream();      
760
                response.setContentType("text/xml");
761
                // Serialize and write it to the output stream
762
                
763
                try {
764
                    serializeServiceType(ObjectList.class, ol, out);
765
                } catch (JiBXException e) {
766
                    throw new ServiceFailure("1190", "Failed to serialize ObjectList: " + e.getMessage());
767
                }
768
            }
769
        } catch (BaseException e) {
770
                serializeException(e, out);
771
        } catch (IOException e) {
772
            e.printStackTrace();
773
            ServiceFailure sf = new ServiceFailure("1030", 
774
                    "IO Error in ResourceHandler.getObject: " + e.getMessage());
775
            serializeException(sf, out); 
776
        } catch(NumberFormatException ne) {
777
            InvalidRequest ir = new InvalidRequest("1030", "Invalid format for parameter: " + ne.getMessage());
778
            serializeException(ir, out);
779
        } catch (Exception e) {
780
            e.printStackTrace();
781
            ServiceFailure sf = new ServiceFailure("1030", 
782
                    "Exception " + e.getClass().getName() + " raised while handling listObjects request: " + 
783
                    e.getMessage());
784
            serializeException(sf, out);
785
        }
786
    }
787
    
788
    /**
789
     * parse a date and return it in GMT if it ends with a 'Z'
790
     * @param date
791
     * @return
792
     * @throws ParseException
793
     */
794
    private Date parseDateAndConvertToGMT(String date) throws ParseException
795
    {
796
        try
797
        {   //the format we want
798
            return dateFormat.parse(date);
799
        }
800
        catch(java.text.ParseException pe)
801
        {   //try another legacy format
802
            DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
803
            dateFormat2.setTimeZone(TimeZone.getTimeZone("GMT-0"));
804
            return dateFormat2.parse(date);
805
        }    
806
        
807
        /*System.out.println("Parsing date " + date);
808
        Date d = dateFormat.parse(date);
809
        
810
        if(date.endsWith("Z"))
811
        {
812
            Calendar lTime = Calendar.getInstance();
813
            lTime.setTime(d);
814
            Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
815
            zTime.set(Calendar.MONTH, lTime.get(Calendar.MONTH));
816
            zTime.set(Calendar.DATE, lTime.get(Calendar.DATE));
817
            zTime.set(Calendar.YEAR, lTime.get(Calendar.YEAR));
818
            zTime.set(Calendar.HOUR, lTime.get(Calendar.HOUR));
819
            zTime.set(Calendar.MINUTE, lTime.get(Calendar.MINUTE));
820
            zTime.set(Calendar.SECOND, lTime.get(Calendar.SECOND));
821
            
822
            System.out.println("date parsed to " + zTime.getTime());
823
            return zTime.getTime();
824
        }
825
        
826
        System.out.println("date parsed, but not converted. returned as " + d);
827
        return d;*/
828
    }
829

    
830
    /**
831
     * Implements REST version of DataONE CRUD API --> getSystemMetadata
832
     * @param guid ID of data object to be read
833
     */
834
    private void getSystemMetadataObject(String guid) {
835
        CrudService cs = CrudService.getInstance();
836
        cs.setParamsFromRequest(request);
837
        AuthToken token = new AuthToken(sessionId);
838
        OutputStream out = null;
839
        try {
840
            response.setContentType("text/xml");
841
            out = response.getOutputStream();
842
            Identifier id = new Identifier();
843
            id.setValue(guid);
844
            SystemMetadata sysmeta = cs.getSystemMetadata(token, id);
845
            
846
            // Serialize and write it to the output stream
847
            try {
848
                serializeServiceType(SystemMetadata.class, sysmeta, out);
849
            } catch (JiBXException e) {
850
                throw new ServiceFailure("1190", "Failed to serialize SystemMetadata: " + e.getMessage());
851
            }
852
        } catch (BaseException e) {
853
                serializeException(e, out);
854
        } catch (IOException e) {
855
            ServiceFailure sf = new ServiceFailure("1030", 
856
                    "Error in ResourceHandler.getSystemMetadataObject: " + e.getMessage());
857
            serializeException(sf, out);
858
        } finally {
859
            IOUtils.closeQuietly(out);
860
        }
861
    }
862
    
863
    /**
864
     * serialize an object of type to out
865
     * @param type the class of the object to serialize (i.e. SystemMetadata.class)
866
     * @param object the object to serialize
867
     * @param out the stream to serialize it to
868
     * @throws JiBXException
869
     */
870
    private void serializeServiceType(Class type, Object object, OutputStream out)
871
      throws JiBXException
872
    {
873
        IBindingFactory bfact = BindingDirectory.getFactory(type);
874
        IMarshallingContext mctx = bfact.createMarshallingContext();
875
        mctx.marshalDocument(object, "UTF-8", null, out);
876
    }
877
    
878
    /**
879
     * deserialize an object of type from is
880
     * @param type the class of the object to serialize (i.e. SystemMetadata.class)
881
     * @param is the stream to deserialize from
882
     * @throws JiBXException
883
     */
884
    private Object deserializeServiceType(Class type, InputStream is)
885
      throws JiBXException
886
    {
887
        IBindingFactory bfact = BindingDirectory.getFactory(type);
888
        IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
889
        Object o = (Object) uctx.unmarshalDocument(is, null);
890
        return o;
891
    }
892
    
893
    /**
894
     * Earthgrid API > Query Service > Query Function : translates ecogrid query document to metacat query 
895
     * then calls DBQuery > createResultDocument function and then again translate resultset to ecogrid resultset
896
     * 
897
     * NOTE:
898
     *      This is the only method that uses EcoGrid classes for its implementation.  
899
     *      It does so because it takes an EcoGrid Query as input, and outputs an
900
     *      EcoGrid ResultSet document.  These documents are parsed by the auto-generated
901
     *      EcoGrid classes from axis, and so we link to them here rather than re-inventing them.
902
     *      This creates a circular dependency, because the Metacat classes are needed
903
     *      to build the EcoGrid implementation, and the EcoGrid jars are needed to build this query()
904
     *      method.  This circularity could be resolved by moving the EcoGrid classes
905
     *      to Metacat directly.  As we transition away from EcoGrid SOAP methods in
906
     *      favor of these REST interfaces, this circular dependency can be eliminated.
907
     *        
908
     * @throws Exception
909
     */
910
    private void query() throws Exception {
911
        /*  This block commented out because of the EcoGrid circular dependency.
912
         *  For now, query will not be supported until the circularity can be
913
         *  resolved, probably by moving the ecogrid query syntax transformers
914
         *  directly into the Metacat codebase.  MBJ 2010-02-03
915
         
916
        try {
917
            EcogridQueryParser parser = new EcogridQueryParser(request
918
                    .getReader());
919
            parser.parseXML();
920
            QueryType queryType = parser.getEcogridQuery();
921
            EcogridJavaToMetacatJavaQueryTransformer queryTransformer = 
922
                new EcogridJavaToMetacatJavaQueryTransformer();
923
            QuerySpecification metacatQuery = queryTransformer
924
                    .transform(queryType);
925

    
926
            DBQuery metacat = new DBQuery();
927

    
928
            boolean useXMLIndex = (new Boolean(PropertyService
929
                    .getProperty("database.usexmlindex"))).booleanValue();
930
            String xmlquery = "query"; // we don't care the query in resultset,
931
            // the query can be anything
932
            PrintWriter out = null; // we don't want metacat result, so set out null
933

    
934
            // parameter: queryspecification, user, group, usingIndexOrNot
935
            StringBuffer result = metacat.createResultDocument(xmlquery,
936
                    metacatQuery, out, username, groupNames, useXMLIndex);
937

    
938
            // create result set transfer		
939
            String saxparser = PropertyService.getProperty("xml.saxparser");
940
            MetacatResultsetParser metacatResultsetParser = new MetacatResultsetParser(
941
                    new StringReader(result.toString()), saxparser, queryType
942
                            .getNamespace().get_value());
943
            ResultsetType records = metacatResultsetParser.getEcogridResult();
944

    
945
            System.out
946
                    .println(EcogridResultsetTransformer.toXMLString(records));
947
            response.setContentType("text/xml");
948
            out = response.getWriter();
949
            out.print(EcogridResultsetTransformer.toXMLString(records));
950

    
951
        } catch (Exception e) {
952
            e.printStackTrace();
953
        }*/
954
        response.setContentType("text/xml");
955
        PrintWriter out = response.getWriter();
956
        out.print("<error>Query operation not yet supported by Metacat.</error>");
957
        out.close();
958
    }
959
    
960
    private String streamToString(InputStream is)
961
    throws IOException
962
    {
963
        byte b[] = new byte[1024];
964
        int numread = is.read(b, 0, 1024);
965
        String response = new String();
966
        while(numread != -1)
967
        {
968
            response += new String(b, 0, numread);
969
            numread = is.read(b, 0, 1024);
970
        }
971
        return response;
972
    }
973

    
974
    private InputStream stringToStream(String s)
975
    throws IOException
976
    {
977
        ByteArrayInputStream bais = new ByteArrayInputStream(s.getBytes());
978
        return bais;
979
    }
980
    
981
    
982
    /**
983
     * Earthgrid API > Put Service >Put Function : calls MetacatHandler > handleInsertOrUpdateAction 
984
     * 
985
     * @param guid ID of data object to be inserted or updated
986
     * @throws IOException
987
     */
988
    private void putObject(String guid, String action) {
989
        logMetacat.debug("Entering putObject: " + guid + "/" + action);
990
        OutputStream out = null;
991
        try {
992
            out = response.getOutputStream();
993
            response.setContentType("text/xml");
994
        } catch (IOException e1) {
995
            logMetacat.error("Could not get the output stream for writing in putObject");
996
        }
997
        try {
998
            
999
            // Read the incoming data from its Mime Multipart encoding
1000
            logMetacat.debug("Disassembling MIME multipart form");
1001
            InputStream object = null;
1002
            InputStream sysmeta = null;
1003
            
1004
            //HACK: Since mmp seems to have a bug where large object parts get truncated,
1005
            //parse the stream here.  This has the disavantage of putting the
1006
            //stream into memory.
1007
            String s = streamToString(request.getInputStream());
1008
            String searchString = "Content-Disposition: attachment; filename=systemmetadata";
1009
            String endString = "------=_Part";
1010
            int searchStringIndex = s.indexOf(searchString);
1011
            sysmeta = new ByteArrayInputStream(
1012
                    s.substring(searchStringIndex +
1013
                            searchString.length(), 
1014
                            s.indexOf(endString, searchStringIndex)).trim().getBytes());
1015
            
1016
            searchString = "Content-Disposition: attachment; filename=object";
1017
            searchStringIndex = s.indexOf(searchString);
1018
            object = new ByteArrayInputStream(
1019
                    s.substring(searchStringIndex +
1020
                            searchString.length(), 
1021
                            s.indexOf(endString, searchStringIndex)).trim().getBytes());
1022
            
1023
            /*
1024
            //This code should work, however there seems to be a bug in part.getInputStream()
1025
            //where it does not return the entire stream.  Only about the first 6kB 
1026
            //are actually returned.
1027
            MimeMultipart mmp = new MimeMultipart(new InputStreamDataSource("message", request.getInputStream()));
1028
            logMetacat.debug("MMP created.");
1029
            
1030
            //mmp.writeTo(System.out);
1031
            for (int i = 0; i < mmp.getCount(); i++) {
1032
                BodyPart part = mmp.getBodyPart(i);
1033
                String name = part.getFileName();
1034
                logMetacat.debug("Part name is: " + name);
1035
                logMetacat.debug("Part has class name: " + part.getClass().getName());
1036
                
1037
                if (name.equals("object")) {
1038
                    object = part.getInputStream();
1039
                    try
1040
                    {
1041
                        String s = streamToString(object);
1042
                        System.out.println("doc text: " + s);
1043
                        System.out.println("size of doc text is: " + s.getBytes().length);
1044
                        object = stringToStream(s);
1045
                    }
1046
                    catch(Exception e)
1047
                    {}
1048
                    System.out.println("Found object part, size is: " + part.getSize());
1049
                } else if (name.equals("systemmetadata")) {
1050
                    sysmeta = part.getInputStream();
1051
                    try
1052
                    {
1053
                      String s = streamToString(sysmeta);
1054
                      System.out.println("system metadata part: " + s);
1055
                      sysmeta = stringToStream(s);
1056
                    }
1057
                    catch(Exception e){}
1058
                    System.out.println("system metadata part, size is " + part.getSize());
1059
                    logMetacat.debug("Found sysmeta part, size is: " + part.getSize());
1060
                } else {
1061
                    throw new InvalidRequest("1000", "Request had malformed MIME part with name: " + name);
1062
                }
1063
            }*/
1064
            
1065
            if ( action.equals(FUNCTION_NAME_INSERT)) { //handle inserts
1066

    
1067
                // Check if the objectId exists
1068
                IdentifierManager im = IdentifierManager.getInstance();
1069
                if (im.identifierExists(guid)) {
1070
                    throw new IdentifierNotUnique("1000", "Identifier is already in use: " + guid);
1071
                }
1072

    
1073
                logMetacat.debug("Commence creation...");
1074
                IBindingFactory bfact =
1075
                    BindingDirectory.getFactory(SystemMetadata.class);
1076
                IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1077
                SystemMetadata m = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
1078

    
1079
                CrudService cs = CrudService.getInstance();
1080
                AuthToken token = new AuthToken(sessionId); 
1081
                cs.setParamsFromRequest(request);
1082
                Identifier id = new Identifier();
1083
                id.setValue(guid);
1084
                cs.create(token, id, object, m);
1085
                
1086
            } else if (action.equals(FUNCTION_NAME_UPDATE)) { //handle updates
1087
                IdentifierManager im = IdentifierManager.getInstance();
1088
                CrudService cs = CrudService.getInstance();
1089
                Identifier obsoletedGuid = new Identifier();
1090
                Identifier id = new Identifier();
1091
                id.setValue(guid);
1092
                AuthToken token = new AuthToken(sessionId);
1093
                
1094
                //do some checks
1095
                if(params.get("obsoletedGuid") == null)
1096
                {
1097
                    throw new InvalidRequest("1202", "obsoletedGuid must be contained in the request parameters.");
1098
                }
1099
                //get the obsoletedGuid
1100
                String[] obsGuidS = params.get("obsoletedGuid");
1101
                obsoletedGuid.setValue(obsGuidS[0]);
1102
                
1103
                if (!im.identifierExists(obsoletedGuid.getValue())) 
1104
                {
1105
                    throw new InvalidRequest("1202", "The guid you are trying to update does not exist.");
1106
                }
1107
                
1108
                
1109
                logMetacat.debug("Commence update...");
1110
                
1111
                //get the systemmetadata
1112
                IBindingFactory bfact =
1113
                        BindingDirectory.getFactory(SystemMetadata.class);
1114
                    IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1115
                    SystemMetadata m = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
1116
                
1117
                //do the update
1118
                try
1119
                {
1120
                    cs.setParamsFromRequest(request);
1121
                    Identifier rId = cs.update(token, id, object, obsoletedGuid, m);
1122
                }
1123
                catch(NotFound e)
1124
                {
1125
                    throw new InvalidRequest("1202", "The guid you are trying to update does not exist.");
1126
                }
1127
                
1128
            } else {
1129
                throw new InvalidRequest("1000", "Operation must be create or update.");
1130
            }
1131
        } catch (NotAuthorized e) {
1132
            serializeException(e, out);
1133
        } catch (InvalidToken e) {
1134
            serializeException(e, out);
1135
        } catch (ServiceFailure e) {
1136
            serializeException(e, out);
1137
        } catch (IdentifierNotUnique e) {
1138
            serializeException(e, out);
1139
        } catch (UnsupportedType e) {
1140
            serializeException(e, out);
1141
        } catch (InsufficientResources e) {
1142
            serializeException(e, out);
1143
        } catch (InvalidSystemMetadata e) {
1144
            serializeException(e, out);
1145
        } catch (NotImplemented e) {
1146
            serializeException(e, out);
1147
        } catch (InvalidRequest e) {
1148
            serializeException(e, out);
1149
        } /*catch (MessagingException e) {
1150
            ServiceFailure sf = new ServiceFailure("1000", e.getMessage());
1151
            serializeException(sf, out);
1152
        }*/ catch (IOException e) {
1153
            ServiceFailure sf = new ServiceFailure("1000", e.getMessage());
1154
            serializeException(sf, out);
1155
        } catch (JiBXException e) {
1156
            e.printStackTrace(System.out);
1157
            InvalidSystemMetadata ism = new InvalidSystemMetadata("1080", e.getMessage());
1158
            serializeException(ism, out);
1159
        }
1160
    }
1161

    
1162
    /**
1163
     * Earthgrid API > Put Service > Delete Function : calls MetacatHandler > handleDeleteAction  
1164
     * 
1165
     * @param guid ID of data object to be deleted
1166
     * @throws IOException
1167
     */
1168
    private void deleteObject(String guid) throws IOException 
1169
    {
1170
        // Look up the localId for this global identifier
1171
        IdentifierManager im = IdentifierManager.getInstance();
1172
        String localId = "";
1173
        try {
1174
            localId = im.getLocalId(guid);
1175
        } catch (McdbDocNotFoundException e) {
1176
            // TODO: Need to return the proper DataONE exception
1177
        }
1178
        
1179
        params.put("docid", new String[] { localId });
1180
        PrintWriter out = response.getWriter();
1181
        response.setContentType("text/xml");
1182
        handler.handleDeleteAction(out, params, request, response, username,
1183
                groupNames);
1184
        out.close();
1185
    }
1186
    
1187
    /**
1188
     * set the access perms on a document
1189
     * @throws IOException
1190
     */
1191
    private void setaccess() throws Exception
1192
    {
1193
        try
1194
        {
1195
            String guid = params.get("guid")[0];
1196
            Identifier id = new Identifier();
1197
            id.setValue(guid);
1198
            AuthToken token = new AuthToken(sessionId);
1199
            String principal = params.get("principal")[0];
1200
            String permission = params.get("permission")[0];
1201
            String permissionType = params.get("permissionType")[0];
1202
            String permissionOrder = params.get("permissionOrder")[0];
1203
            String setSystemMetadata = params.get("setsystemmetadata")[0];
1204
            boolean ssm = false;
1205
            if(setSystemMetadata.equals("true") || setSystemMetadata.equals("TRUE") ||
1206
                    setSystemMetadata.equals("yes"))
1207
            {
1208
                ssm = true;
1209
            }
1210
            CrudService cs = CrudService.getInstance();
1211
            cs.setAccess(token, id, principal, permission, permissionType, permissionOrder, ssm);
1212
        }
1213
        catch(Exception e)
1214
        {
1215
            printError("Error setting access in ResourceHandler: " + e.getMessage(), response);
1216
            throw e;
1217
        }
1218
    }
1219

    
1220
    /**
1221
     * Earthgrid API > Authentication Service > Login Function : calls MetacatHandler > handleLoginAction
1222
     * 
1223
     * @throws IOException
1224
     */
1225
    private void login() throws IOException {
1226
        PrintWriter out = response.getWriter();
1227
        response.setContentType("text/xml");
1228
        handler.handleLoginAction(out, params, request, response);
1229
        out.close();
1230
    }
1231

    
1232
    /**
1233
     * Earthgrid API > Authentication Service > Logout Function : calls MetacatHandler > handleLogoutAction
1234
     * 
1235
     * @throws IOException
1236
     */
1237
    private void logout() throws IOException {
1238
        PrintWriter out = response.getWriter();
1239
        response.setContentType("text/xml");
1240
        handler.handleLogoutAction(out, params, request, response);
1241
        out.close();
1242
    }
1243

    
1244
    /**
1245
     * Prints xml response
1246
     * @param message Message to be displayed
1247
     * @param response Servlet response that xml message will be printed 
1248
     * */
1249
    private void printError(String message, HttpServletResponse response) {
1250
        try {
1251
            PrintWriter out = response.getWriter();
1252
            response.setContentType("text/xml");
1253
            out.println("<?xml version=\"1.0\"?>");
1254
            out.println("<error>");
1255
            out.println(message);
1256
            out.println("</error>");
1257
            out.close();
1258
        } catch (IOException e) {
1259
            e.printStackTrace();
1260
        }
1261
    }
1262
    
1263
    private void serializeException(BaseException e, OutputStream out) {
1264
        // TODO: Use content negotiation to determine which return format to use
1265
        response.setContentType("text/xml");
1266
        response.setStatus(e.getCode());
1267
        try {
1268
            IOUtils.write(e.serialize(BaseException.FMT_XML), out);
1269
        } catch (IOException e1) {
1270
            logMetacat.error("Error writing exception to stream. " 
1271
                    + e1.getMessage());
1272
        }
1273
    }
1274

    
1275
}
(2-2/3)