Project

General

Profile

« Previous | Next » 

Revision 6267

refactor to use D1RestServlet and D1ResourceHandler for the D1 rest interface

View differences:

src/edu/ucsb/nceas/metacat/restservice/MNResourceHandler.java
121 121
 * @author leinfelder
122 122
 *
123 123
 */
124
public class MNResourceHandler extends ResourceHandler{
124
public class MNResourceHandler extends D1ResourceHandler{
125 125

  
126 126
    // MN-specific API Resources
127 127
    protected static final String RESOURCE_MONITOR = "monitor";
......
301 301
            serializeException(be, out);
302 302
        } catch (Exception e) {
303 303
            logMetacat.error(e.getClass() + ": " + e.getMessage());
304
            System.out.println("Error in ResourceHandler.handle(): " + e.getClass() + ": " + e.getMessage());
304
            System.out.println("Error handle(): " + e.getClass() + ": " + e.getMessage());
305 305
            e.printStackTrace();
306 306
        }
307 307
    }
......
545 545
        }
546 546
        catch(Exception e)
547 547
        {
548
            logMetacat.error("Error getting output stream in ResourceHandler.describeObject: " + e.getClass() + ": " + e.getMessage());
548
            logMetacat.error("Error getting output stream in describeObject: " + e.getClass() + ": " + e.getMessage());
549 549
            return;
550 550
        }
551 551
        response.setStatus(200);
......
738 738
                            "Here's the error: " + e.getClass() + ": " + e.getMessage());
739 739
                    e.printStackTrace();
740 740
                    ServiceFailure sf = new ServiceFailure("1030", 
741
                            "IO Error in ResourceHandler.getObject: " + e.getClass() + ": " + e.getMessage());
741
                            "IO Error in getObject: " + e.getClass() + ": " + e.getMessage());
742 742
                    serializeException(sf, out); 
743 743
                }
744 744
            }
......
836 836
            e.printStackTrace();
837 837
            response.setStatus(500);
838 838
            ServiceFailure sf = new ServiceFailure("1030", 
839
                    "IO Error in ResourceHandler.getObject: " + e.getMessage());
839
                    "IO Error in getObject: " + e.getMessage());
840 840
            serializeException(sf, out); 
841 841
        } catch(NumberFormatException ne) {
842 842
            response.setStatus(500);
......
879 879
        } catch (IOException e) {
880 880
            response.setStatus(500);
881 881
            ServiceFailure sf = new ServiceFailure("1030", 
882
                    "IO Error in ResourceHandler.getSystemMetadataObject: " + e.getMessage());
882
                    "IO Error in getSystemMetadataObject: " + e.getMessage());
883 883
            serializeException(sf, out);
884 884
        } finally {
885 885
            IOUtils.closeQuietly(out);
......
983 983
     */
984 984
    @Override
985 985
    protected void putObject(String pid, String action) {
986
        System.out.println("ResourceHandler: putObject with pid " + pid);
986
        System.out.println("putObject with pid " + pid);
987 987
        logMetacat.debug("Entering putObject: " + pid + "/" + action);
988 988
        OutputStream out = null;
989 989
        try {
......
1218 1218
        catch(Exception e)
1219 1219
        {
1220 1220
            response.setStatus(500);
1221
            printError("Error setting access in ResourceHandler: " + e.getClass() + ": " + e.getMessage(), response);
1221
            printError("Error setting access: " + e.getClass() + ": " + e.getMessage(), response);
1222 1222
            throw e;
1223 1223
        }
1224 1224
    }
src/edu/ucsb/nceas/metacat/restservice/CNRestServlet.java
33 33
 * Routes CN REST service requests to the appropriate handler
34 34
 *  
35 35
 */
36
public class CNRestServlet extends RestServlet {
36
public class CNRestServlet extends D1RestServlet {
37 37
    
38 38
	/**
39
	 * Provide a CNResourceHandler subclass of ResourceHandler
39
	 * Provide a CNResourceHandler subclass of D1ResourceHandler
40 40
	 */
41 41
	@Override
42
    protected ResourceHandler createHandler(HttpServletRequest request, HttpServletResponse response) 
42
    protected D1ResourceHandler createHandler(HttpServletRequest request, HttpServletResponse response) 
43 43
    	throws ServletException, IOException {
44 44
        return new CNResourceHandler(getServletContext(), request, response);
45 45
    }
src/edu/ucsb/nceas/metacat/restservice/CNResourceHandler.java
114 114
 * @author leinfelder
115 115
 *
116 116
 */
117
public class CNResourceHandler extends ResourceHandler {
117
public class CNResourceHandler extends D1ResourceHandler {
118 118

  
119 119
	/** CN-specific operations **/
120 120
    protected static final String RESOURCE_RESERVE = "reserve";
......
515 515
                            "Here's the error: " + e.getClass() + ": " + e.getMessage());
516 516
                    e.printStackTrace();
517 517
                    ServiceFailure sf = new ServiceFailure("1030", 
518
                            "IO Error in ResourceHandler.getObject: " + e.getClass() + ": " + e.getMessage());
518
                            "IO Error in D1ResourceHandler.getObject: " + e.getClass() + ": " + e.getMessage());
519 519
                    serializeException(sf, out); 
520 520
                }
521 521
            }
......
524 524
            e.printStackTrace();
525 525
            response.setStatus(500);
526 526
            ServiceFailure sf = new ServiceFailure("1030", 
527
                    "IO Error in ResourceHandler.getObject: " + e.getMessage());
527
                    "IO Error in D1ResourceHandler.getObject: " + e.getMessage());
528 528
            serializeException(sf, out); 
529 529
        } catch(NumberFormatException ne) {
530 530
            response.setStatus(500);
......
572 572
        } catch (IOException e) {
573 573
            response.setStatus(500);
574 574
            ServiceFailure sf = new ServiceFailure("1030", 
575
                    "IO Error in ResourceHandler.getSystemMetadataObject: " + e.getMessage());
575
                    "IO Error in D1ResourceHandler.getSystemMetadataObject: " + e.getMessage());
576 576
            serializeException(sf, out);
577 577
        } finally {
578 578
            IOUtils.closeQuietly(out);
......
587 587
     * @throws IOException
588 588
     */
589 589
    protected void putObject(String pid, String action) {
590
        logMetacat.debug("ResourceHandler: putObject with pid " + pid);
590
        logMetacat.debug("putObject with pid " + pid);
591 591
        logMetacat.debug("Entering putObject: " + pid + "/" + action);
592 592
        OutputStream out = null;
593 593
        try {
......
782 782
	      
783 783
      } catch (IOException ioe) {
784 784
      	logMetacat.error("Could not get the output stream for writing" +
785
      	  "in ResourceHandler.listFormats()");
785
      	  "in D1ResourceHandler.listFormats()");
786 786
      
787 787
      }
788 788

  
......
839 839
	      
840 840
      } catch (IOException ioe) {
841 841
      	logMetacat.error("Could not get the output stream for writing" +
842
      	  "in ResourceHandler.listFormats()");
842
      	  "in D1ResourceHandler.listFormats()");
843 843
      
844 844
      }
845 845
      
src/edu/ucsb/nceas/metacat/restservice/D1RestServlet.java
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 13:28:21 +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.IOException;
26

  
27
import javax.servlet.ServletConfig;
28
import javax.servlet.ServletException;
29
import javax.servlet.http.HttpServlet;
30
import javax.servlet.http.HttpServletRequest;
31
import javax.servlet.http.HttpServletResponse;
32

  
33
import org.apache.log4j.Logger;
34

  
35
/**
36
 * Metacat implemantation of Earthgrid (Ecogrid) REST API as a servlet. In each request
37
 * REST Servlet initialize a D1ResourceHandler object and then D1ResourceHandler object 
38
 * handles with request and writes approriate response. 
39
 *  
40
 */
41
public class D1RestServlet extends HttpServlet {
42

  
43
    protected Logger logMetacat;
44
    protected D1ResourceHandler handler;
45

  
46
    /**
47
     * Subclasses should override this method to provide the appropriate handler subclass
48
     * @param request
49
     * @param response
50
     * @return
51
     * @throws ServletException
52
     * @throws IOException
53
     */
54
    protected D1ResourceHandler createHandler(HttpServletRequest request, HttpServletResponse response) 
55
		throws ServletException, IOException {
56
	    D1ResourceHandler handler = new D1ResourceHandler(getServletContext(), request, response);
57
	    return handler;
58
	}
59
    
60
    /**
61
     * Initalize servlet by setting logger
62
     */
63
    @Override
64
    public void init(ServletConfig config) throws ServletException {
65
        logMetacat = Logger.getLogger(this.getClass());
66
        super.init(config);
67
    }
68

  
69
    /** Handle "GET" method requests from HTTP clients */
70
    @Override
71
    protected void doGet(HttpServletRequest request,
72
            HttpServletResponse response) throws ServletException, IOException {
73
        System.out.println("HTTP Verb: GET");
74
        handler = createHandler(request, response);
75
        handler.handle(D1ResourceHandler.GET);
76
    }
77

  
78
    /** Handle "POST" method requests from HTTP clients */
79
    @Override
80
    protected void doPost(HttpServletRequest request,
81
            HttpServletResponse response) throws ServletException, IOException {
82
        System.out.println("HTTP Verb: POST");
83
        handler = createHandler(request, response);
84
        handler.handle(D1ResourceHandler.POST);
85
    }
86

  
87
    /** Handle "DELETE" method requests from HTTP clients */
88
    @Override
89
    protected void doDelete(HttpServletRequest request,
90
            HttpServletResponse response) throws ServletException, IOException {
91
        System.out.println("HTTP Verb: DELETE");
92
        handler = createHandler(request, response);
93
        handler.handle(D1ResourceHandler.DELETE);
94
    }
95

  
96
    /** Handle "PUT" method requests from HTTP clients */
97
    @Override
98
    protected void doPut(HttpServletRequest request,
99
            HttpServletResponse response) throws ServletException, IOException {
100
        System.out.println("HTTP Verb: PUT");
101
        handler = createHandler(request, response);
102
        handler.handle(D1ResourceHandler.PUT);
103
    }
104

  
105
    /** Handle "PUT" method requests from HTTP clients */
106
    @Override
107
    protected void doHead(HttpServletRequest request,
108
            HttpServletResponse response) throws ServletException, IOException {
109
        System.out.println("HTTP Verb: HEAD");
110
        handler = createHandler(request, response);
111
        handler.handle(D1ResourceHandler.HEAD);
112
    }
113
}
0 114

  
src/edu/ucsb/nceas/metacat/restservice/D1ResourceHandler.java
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
 */
219
public class D1ResourceHandler {
220

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

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

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

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

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

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

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

  
325
                params = new Hashtable<String, String[]>();
326
                initParams();
327

  
328
                Timer timer = new Timer();
329
                handler = new MetacatHandler(timer);
330

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

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

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

  
399
                    logMetacat.debug("verb:" + httpVerb);
400

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

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

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

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

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

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

  
1021
        String name = null;
1022
        String[] value = null;
1023
        Enumeration paramlist = request.getParameterNames();
1024
        while (paramlist.hasMoreElements()) {
1025
            name = (String) paramlist.nextElement();
1026
            value = request.getParameterValues(name);
1027
            params.put(name, value);
1028
        }
1029
    }
1030

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

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

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

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

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

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

  
1168
            out.println("<?xml version=\"1.0\"?>");
1169
            out.print("<next-revision>");
1170
            out.print(revision);
1171
            out.print("</next-revision>");
1172

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

  
1182
        out.close();
1183
    }
1184

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

  
1198
    /**
1199
     * Implements REST version of DataONE CRUD API --> get
1200
     * @param guid ID of data object to be read
1201
     */
1202
    protected void getObject(String guid) {
1203
        OutputStream out = null;
1204
        try {
1205
            out = response.getOutputStream();
1206
            response.setStatus(200);
1207
            
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff