Project

General

Profile

« Previous | Next » 

Revision 6541

remove old RestServlet handler -- not used now

View differences:

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

  
26
package edu.ucsb.nceas.metacat.restservice;
27

  
28
import java.io.ByteArrayInputStream;
29
import java.io.ByteArrayOutputStream;
30
import java.io.File;
31
import java.io.FileInputStream;
32
import java.io.IOException;
33
import java.io.InputStream;
34
import java.io.OutputStream;
35
import java.util.Date;
36

  
37
import junit.framework.Test;
38
import junit.framework.TestSuite;
39

  
40
import org.apache.commons.io.IOUtils;
41
import org.dataone.service.exceptions.BaseException;
42
import org.dataone.service.exceptions.InvalidSystemMetadata;
43
import org.dataone.service.exceptions.ServiceFailure;
44
import org.dataone.service.types.v1.SystemMetadata;
45
import org.jibx.runtime.BindingDirectory;
46
import org.jibx.runtime.IBindingFactory;
47
import org.jibx.runtime.IMarshallingContext;
48

  
49
import edu.ucsb.nceas.MCTestCase;
50

  
51
/**
52
 * @author berkley
53
 * class to test ResourceHandler
54
 */
55
public class ResourceHandlerTest extends MCTestCase
56
{
57
    public ResourceHandlerTest(String name)
58
    {
59
        super(name);
60
    }
61

  
62
    /**
63
     * Create a suite of tests to be run together
64
     */
65
    public static Test suite() 
66
    {
67
        TestSuite suite = new TestSuite();
68
        
69
        //suite.addTest(new ResourceHandlerTest("testFindBoundary"));        
70
        //suite.addTest(new ResourceHandlerTest("testProcessMMP"));
71
        suite.addTest(new ResourceHandlerTest("testReplicate"));
72
        return suite;
73
    }
74
    
75
    public void testReplicate()
76
    {
77
        
78
    }
79
    
80
    public void testFindBoundary()
81
    {
82
        try
83
        {
84
            File f = new File("test/testMimeInput.txt");
85
            FileInputStream fis = new FileInputStream(f);
86
            String[] s = ResourceHandler.findBoundaryString(fis);
87
            assertEquals(s[0], "--1288304583346");
88
            //System.out.println("r: " + s[1].trim());
89
            assertTrue(s[1].trim().startsWith(s[0]));
90
        }
91
        catch(Exception e)
92
        {
93
            fail("unexpected error in testFindBoundary: " + e.getMessage());
94
        }
95
    }
96
    
97
    public void testProcessMMP()
98
    {
99
        try
100
        {
101
            runTestProccessMMP("test/testMimeInput.txt", "test/testMimeInput-object.txt");
102
            runTestProccessMMP("test/testMimeInput2.txt", "test/testMimeInput2-object.txt");
103
            runTestProccessMMP("test/testMimeInput3.txt", "test/testMimeInput3-object.txt");
104
        }
105
        catch(Exception e)
106
        {
107
            e.printStackTrace();
108
            fail("Unexpected error in testProcessMMP: " + e.getMessage());
109
        }
110
        
111
    }
112
    
113
    /**
114
     * create a mime multipart message from object and sysmeta and write it to out
115
     */
116
    private void createMimeMultipart(OutputStream out, InputStream object,
117
            SystemMetadata sysmeta) throws IOException, BaseException
118
    {
119
        if (sysmeta == null) {
120
            throw new InvalidSystemMetadata("1000",
121
                    "System metadata was null.  Can't create multipart form.");
122
        }
123
        Date d = new Date();
124
        String boundary = d.getTime() + "";
125

  
126
        String mime = "MIME-Version:1.0\n";
127
        mime += "Content-type:multipart/mixed; boundary=\"" + boundary + "\"\n";
128
        boundary = "--" + boundary + "\n";
129
        mime += boundary;
130
        mime += "Content-Disposition: attachment; filename=systemmetadata\n\n";
131
        out.write(mime.getBytes());
132
        out.flush();
133
        
134
        //write the sys meta
135
        try
136
        {
137
            ByteArrayInputStream bais = serializeSystemMetadata(sysmeta);
138
            IOUtils.copy(bais, out);
139
        }
140
        catch(Exception e)
141
        {
142
            throw new ServiceFailure("1000",
143
                    "Could not serialize the system metadata to multipart: "
144
                            + e.getMessage());
145
        }
146
        
147
        out.write("\n".getBytes()); 
148

  
149
        if (object != null) 
150
        {    
151
            out.write(boundary.getBytes());
152
            out.write("Content-Disposition: attachment; filename=object\n\n".getBytes());
153
            try {
154
                mime += IOUtils.copy(object, out);
155
            } 
156
            catch (IOException ioe) 
157
            {
158
                throw new ServiceFailure("1000",
159
                        "Error serializing object to multipart: "
160
                                + ioe.getMessage());
161
            }
162
            out.write("\n".getBytes());
163
        }
164

  
165
        out.write((boundary + "--").getBytes());        
166
    }
167
    
168
    protected ByteArrayInputStream serializeSystemMetadata(SystemMetadata sysmeta)
169
        throws Exception 
170
    {
171

  
172
        ByteArrayOutputStream sysmetaOut = new ByteArrayOutputStream();
173
        serializeServiceType(SystemMetadata.class, sysmeta, sysmetaOut);
174
        ByteArrayInputStream sysmetaStream = new ByteArrayInputStream(
175
                sysmetaOut.toByteArray());
176
        return sysmetaStream;
177
    }
178
    
179
    protected void serializeServiceType(Class type, Object object,
180
            OutputStream out) throws Exception {
181
        IBindingFactory bfact = BindingDirectory.getFactory(type);
182
        IMarshallingContext mctx = bfact.createMarshallingContext();
183
        mctx.marshalDocument(object, "UTF-8", null, out);
184
    }
185
    
186
    private void runTestProccessMMP(String filename, String answerFilename)
187
        throws Exception
188
    {
189
        /*PropertyService propServ = PropertyService.getInstance("/Users/berkley/tools/tomcat/webapps/knb/WEB-INF");
190
        System.out.println("*****************************************");
191
        System.out.println("running process test on file " + filename);
192
        File f = new File(filename);
193
        File fObject = new File(answerFilename);
194
        FileInputStream fobjectis = new FileInputStream(fObject);
195
        FileInputStream fis = new FileInputStream(f);
196
        ResourceHandler rh = new ResourceHandler(null, null, null);
197
        Hashtable<String, File> h = rh.processMMP(fis);
198
        FileInputStream smFis = new FileInputStream(h.get("sysmeta"));
199
        FileInputStream objFis = new FileInputStream(h.get("object"));
200
        String sm = IOUtils.toString(smFis);
201
        String obj = IOUtils.toString(objFis);
202
        //System.out.println("sm: " + sm);
203
        //System.out.println("obj: " + obj);
204
        String fObjectStr = IOUtils.toString(fobjectis);
205
        assertTrue(fObjectStr.trim().equals(obj.trim()));
206
        assertTrue(sm.indexOf("<d1:systemMetadata") != -1);
207
        assertTrue(sm.indexOf("</d1:systemMetadata>") != -1);*/
208
    }
209
}
src/edu/ucsb/nceas/metacat/restservice/RestServlet.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 ResourceHandler object and then ResourceHandler object 
38
 * handles with request and writes approriate response. 
39
 *  
40
 *  @deprecated Only keeping this for reference in case we want to implement
41
 *  older Metacat API with REST
42
 */
43
public class RestServlet extends HttpServlet {
44

  
45
    protected Logger logMetacat;
46
    protected ResourceHandler handler;
47

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

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

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

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

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

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

  
src/edu/ucsb/nceas/metacat/restservice/ResourceHandler.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.dataone.client.MNode;
54
import org.dataone.client.ObjectFormatCache;
55
import org.dataone.client.auth.CertificateManager;
56
import org.dataone.mimemultipart.MultipartRequest;
57
import org.dataone.mimemultipart.MultipartRequestResolver;
58
import org.dataone.service.exceptions.BaseException;
59
import org.dataone.service.exceptions.IdentifierNotUnique;
60
import org.dataone.service.exceptions.InsufficientResources;
61
import org.dataone.service.exceptions.InvalidRequest;
62
import org.dataone.service.exceptions.InvalidSystemMetadata;
63
import org.dataone.service.exceptions.InvalidToken;
64
import org.dataone.service.exceptions.NotAuthorized;
65
import org.dataone.service.exceptions.NotFound;
66
import org.dataone.service.exceptions.NotImplemented;
67
import org.dataone.service.exceptions.ServiceFailure;
68
import org.dataone.service.exceptions.UnsupportedType;
69
import org.dataone.service.types.v1.AccessPolicy;
70
import org.dataone.service.types.v1.Checksum;
71
import org.dataone.service.types.v1.DescribeResponse;
72
import org.dataone.service.types.v1.Event;
73
import org.dataone.service.types.v1.Identifier;
74
import org.dataone.service.types.v1.Log;
75
import org.dataone.service.types.v1.Node;
76
import org.dataone.service.types.v1.NodeList;
77
import org.dataone.service.types.v1.NodeReference;
78
import org.dataone.service.types.v1.NodeType;
79
import org.dataone.service.types.v1.ObjectFormat;
80
import org.dataone.service.types.v1.ObjectFormatIdentifier;
81
import org.dataone.service.types.v1.ObjectFormatList;
82
import org.dataone.service.types.v1.ObjectList;
83
import org.dataone.service.types.v1.Service;
84
import org.dataone.service.types.v1.Services;
85
import org.dataone.service.types.v1.Session;
86
import org.dataone.service.types.v1.SystemMetadata;
87
import org.dataone.service.types.v1.util.ChecksumUtil;
88
import org.dataone.service.types.v1.util.NodelistUtil;
89
import org.dataone.service.util.TypeMarshaller;
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.MetacatHandler;
99
import edu.ucsb.nceas.metacat.dataone.CNodeService;
100
import edu.ucsb.nceas.metacat.dataone.MNodeService;
101
import edu.ucsb.nceas.metacat.properties.PropertyService;
102
import edu.ucsb.nceas.metacat.service.SessionService;
103
import edu.ucsb.nceas.metacat.util.RequestUtil;
104
import edu.ucsb.nceas.metacat.util.SessionData;
105
import edu.ucsb.nceas.metacat.util.SystemUtil;
106
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
107
/**
108
 * 
109
 * Implements Earthgrid REST API to Metacat <br/><br/> 
110
 * 
111
 * <ul>
112
 * <li>
113
 * <h3> EarthGrid Query Service</h3>
114
 * <ul><li>
115
 * <h3>Get & Authenticated Get:</h3> 
116
 * is equal to Metacat's read action and returns a data file having
117
 * the specified <doc-id> in the resource path. For authenticated Get service, a session id must be provided 
118
 * in the query string. <br/><br/>
119
 * 
120
 * <b>REST URL:</b> <code>GET, [context-root]/object/[doc-id]?sessionid=[sessionid] </code><br/>
121
 * <b>Returns:</b> data file <br/><br/>
122
 * </li>
123
 * 
124
 * <li>
125
 * <h3>Query & Authenticated Query:</h3> 
126
 * Metacat's equivalent is squery action but this function 
127
 * receives a Earthgrid query document and returns Earthgrid resultset document by transforming those documents
128
 * to Metacat's equivalents by the means of Metacat Implementation in Earthgrid library. For authenticated Query service 
129
 * a session id must be provided in the query string. See Earthgrid (a.k.a. Ecogrid) project for XSD files of 
130
 * query and resultset documents<br/><br/>
131
 * 
132
 * <b>REST URL:</b> <code>POST, [context-root]/object?sessionid=[sessionid]</code>    <br/>
133
 * <b>POST Data:</b> Earthgrid query document , Content-type: <code>text/xml</code><br/>
134
 * <b>Returns:</b> Earthgrid resultset document<br/><br/>
135
 * 
136
 * </li>
137
 * </ul>
138
 * 
139
 * </li>
140
 * 
141
 * <li>
142
 * <h3> EarthGrid Authentication Service</h3>
143
 * <ul><li>
144
 * <h3>Login: </h3> 
145
 * Receives username and password parameters in POST data and 
146
 * returns SessionId (in XML format) or failure message and uses MetacatHandler's handleLoginAction function<br/><br/>
147
 *  
148
 * <b>REST URL:</b> <code>POST, [context-root]/session?op=login</code> <br/>
149
 * <b>POST Data:</b> username=[username]&password=[password], Content-type: <code>application/x-www-form-urlencoded</code>
150
 * <b>Returns:</b> sessionId in XML format<br/><br/>
151
 * </li>
152
 * 
153
 * <li>
154
 * <h3>Logout: </h3> 
155
 * Receives session Id parameters in querystring and returns xml message, calls 
156
 * MetacatHandler's handleLogoutAction function<br/><br/>
157
 *  
158
 * <b>REST URL:</b> <code>GET, [context-root]/session?op=logout&sessionid=[sessionid]</code>   <br/>
159
 * <b>Returns:</b> message in XML format<br/><br/>
160
 * </li>
161
 * </ul>
162
 * 
163
 * <li>
164
 * <h3>EarthGrid Put Service</h3>
165
 * 
166
 * <ul>
167
 * <li><h3>Update/Insert: </h3>     
168
 * <br/>
169
 * <b>REST URL:</b> <code>PUT, [context-root]/object/[doc-id]?op={update|insert}&sessionid=[sessionid]</code>   <br/>
170
 * <b>POST Data:</b> document object, Content-type: <code>text/xml</code><br/>
171
 * <b>Returns:</b> message in XML format<br/><br/>
172
 * </li>
173
 * 
174
 * <li><h3>Delete: </h3>        
175
 * <br/>
176
 * <b>REST URL:</b> <code>DELETE, [context-root]/object/[doc-id]?sessionid=[sessionid]</code>   <br/>
177
 * <b>Returns:</b> message in XML format<br/><br/>
178
 * </li>
179

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

  
192
 * <li><h3>getAllDocIds:</h3>       <br/>       
193
 * <b>REST URL:</b> <code>GET, [context-root]/identifier?op=getalldocids</code>   <br/>
194
 * <b>Returns:</b> document id list in XML format<br/><br/>
195
 * </li>
196
 * 
197
 * <li><h3>addLSID Function:</h3> 
198
 * Metacat does not support this function       <br/>
199
 * <b>REST URL:</b> <code>PUT, [context-root]/identifier/[doc-id]</code>   <br/>
200
 * <b>Returns:</b> error message in XML format<br/><br/>
201
 * </li>
202
 * 
203
 * <li><h3>getNextRevision:</h3>        <br/>
204
 * <b>REST URL:</b> <code>GET, [context-root]/identifier/[doc-id]?op=getnextrevision</code>   <br/>
205
 * <b>Returns:</b> message in XML format<br/><br/>
206
 * </li>
207
 * 
208
 * <li><h3>getNextObject:</h3>      <br/>
209
 * <b>REST URL:</b> <code>GET, [context-root]/identifier?op=getnextobject&scope=[scope]</code>   <br/>
210
 * <b>Returns:</b> message in XML format<br/><br/>
211
 * </li>
212
 * 
213
 * </li>
214
 * </ul>
215
 * 
216
 * @deprecated Only keeping this for reference in case we want to continue developing
217
 * REST interface for old Metacat API
218
 */
219
public class ResourceHandler {
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 ResourceHandler(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(ResourceHandler.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
                        // removed HealthService - BRL 20110727
576
                    }
577
                    status = true;
578
                } else if(resource.equals(RESOURCE_REPLICATE)) {
579
                    System.out.println("processing replicate request");
580
                    replicate(httpVerb, request, response);
581
                    status = true;
582
                }
583
                    
584
                if (!status)
585
                {
586
                    response.setStatus(400);
587
                    printError("Incorrect parameters!", response);
588
                }
589
            } else {
590
                response.setStatus(400);
591
                printError("Incorrect resource!", response);
592
            }
593
        } catch (Exception e) {
594
            logMetacat.error(e.getClass() + ": " + e.getMessage());
595
            System.out.println("Error in ResourceHandler.handle(): " + e.getClass() + ": " + e.getMessage());
596
            e.printStackTrace();
597
        }
598
    }
599
    
600
		/**
601
     * handle the /replicate action
602
     * @param httpVerb
603
     * @param request
604
     * @param response
605
     * @throws Exception
606
     */
607
    private void replicate(int httpVerb, HttpServletRequest request, HttpServletResponse response)
608
        throws Exception
609
    {
610
        if(httpVerb == POST)
611
        {
612
            System.out.println("in POST replicate()");
613
            /*InputStream is = request.getInputStream();
614
            String input = IOUtils.toString(is);
615
            System.out.println("input: " + input);
616
            is = IOUtils.toInputStream(input);*/
617
            
618
            File tmpDir = getTempDirectory();
619
            File tmpSMFile = new File(tmpDir + 
620
                    ".sysmeta." + new Date().getTime() + ".tmp");
621
            System.out.println("temp dir: " + tmpDir.getAbsolutePath());
622
            MultipartRequestResolver mrr = new MultipartRequestResolver(
623
                    tmpDir.getAbsolutePath(), 1000000000, 0);
624
            MultipartRequest mr = mrr.resolveMultipart(request);
625
            Map<String, File> files = mr.getMultipartFiles();
626
            Iterator keys = files.keySet().iterator();
627
            while(keys.hasNext())
628
            {
629
                String key = (String)keys.next();
630
                System.out.println("files key: " + key);
631
                System.out.println("files value: " + files.get(key));
632
            }
633
            
634
            Map<String, List<String>> params = mr.getMultipartParameters();
635
            keys = params.keySet().iterator();
636
            while(keys.hasNext())
637
            {
638
                String key = (String)keys.next();
639
                System.out.println("params key: " + key);
640
                System.out.println("params value: " + params.get(key));
641
            }
642
            
643
            //File f = files.get("sysmeta");
644
            //the files are not being keyed by the part name, but rather the filename
645
            File f = files.get(files.keySet().iterator().next());
646
            
647
            System.out.println("file: " + f.getAbsolutePath());
648
            String sourceNode = params.get("sourceNode").get(0);
649
            System.out.println("sourceNode: " + sourceNode);
650
            FileInputStream fis = new FileInputStream(f);
651
            
652
            //lookup the id in the registry
653
            URL url = new URL("http://cn.dataone.org/cn/node");
654
            InputStream urlis = url.openStream();
655
            Map<String,String> m = NodelistUtil.mapNodeList(urlis);
656
            String nodeUrl = m.get(sourceNode);
657
            System.out.println("sourceNodeId: " + sourceNode);
658
            System.out.println("resolved sourceNodeUrl: " + nodeUrl);
659
            
660
            if(nodeUrl == null)
661
            {
662
                response.setStatus(500);
663
                response.getOutputStream().write(("Member Node id " + 
664
                        sourceNode + " not found in node registry.").getBytes());
665
                response.getOutputStream().close();
666
            }
667
            
668
            //respond to cn with 200/OK
669
            //String s;
670
            //s = "sysmeta: " + IOUtils.toString(fis);
671
            //s += "\n\n";
672
            response.setStatus(200);
673
            //response.getOutputStream().write(("sourceNode: " + sourceNode + "\n\n").getBytes());
674
            //response.getOutputStream().write(("s: " + s).getBytes());
675
            OutputStream out = response.getOutputStream();
676
            out.write("OK\n".getBytes());
677
            out.write(("sourceNodeId: " + sourceNode + "\n").getBytes());
678
            out.write(("sourceNodeUrl: " + nodeUrl + "\n").getBytes());
679
            out.close();
680
            
681
            //parse the systemMetadata
682
            SystemMetadata sm = (SystemMetadata)deserializeServiceType(SystemMetadata.class, fis);
683
            NodeReference nr = sm.getOriginMemberNode();
684
            nr.setValue(sourceNode);
685
            sm.setOriginMemberNode(nr);
686
            //get the document
687
            MNode mnode = new MNode(nodeUrl);
688
            //get the doc from the remote host
689
            InputStream docStream = mnode.get(session, sm.getIdentifier());
690
            File outputTmpFile = getTempFile();
691
            System.out.println("wrote xml file to " + outputTmpFile.getAbsolutePath());
692
            FileOutputStream outputTmpFileStream = new FileOutputStream(outputTmpFile);
693
            IOUtils.copy(docStream, outputTmpFileStream);
694
            
695
            //verify checksum
696
            System.out.println("verifying checksum");
697
            Checksum sourceFileChecksum = ChecksumUtil.checksum(new FileInputStream(outputTmpFile), 
698
                    sm.getChecksum().getAlgorithm());
699
            
700
            String cs1 = sm.getChecksum().getValue();
701
            String cs2 = sourceFileChecksum.getValue();
702
            System.out.println("original checksum: " + cs1);
703
            System.out.println(" created checksum: " + cs2);
704
            
705
            if(!cs1.equals(cs2))
706
            {
707
                System.out.println("ERROR: Checksums do not match!");
708
            }
709
            
710
        }
711
    }
712
    
713
    /**
714
     * create the root node registry response.  
715
     * @throws JiBXException
716
     * @throws IOException
717
     */
718
    private void createNodeResponse() 
719
        throws JiBXException, IOException
720
    {
721
        String nodeName = null;
722
        String nodeId = null;
723
        String nodeUrl = null;
724
        String nodeDesc = null;
725
        String nodeType = null;
726
        
727
        try
728
        {
729
            nodeId = PropertyService.getProperty("dataone.memberNodeId");
730
            nodeName = PropertyService.getProperty("dataone.nodeName");
731
            nodeUrl = SystemUtil.getContextURL() + "/d1/";
732
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
733
            nodeType = PropertyService.getProperty("dataone.nodeType");
734
        }
735
        catch(PropertyNotFoundException pnfe)
736
        {
737
            logMetacat.error("createNodeResponse: " +
738
                    "property not found: " + pnfe.getMessage());
739
        }
740
        
741
        NodeList nl = new NodeList();
742
        Node n = new Node();
743
        NodeReference nr = new NodeReference();
744
        nr.setValue(nodeId);
745
        n.setIdentifier(nr);
746
        n.setBaseURL(nodeUrl);
747
        n.setDescription(nodeDesc);
748
        n.setName(nodeName + " -- WAR version WARVERSION");
749
        n.setType(NodeType.convert(nodeType));
750
        
751
        //create the services
752
        Service mnCrud03 = new Service();
753
        mnCrud03.setName("Metacat MN_Crud Services Version 0.3");
754
        mnCrud03.setVersion("0.3");
755
        
756
        Service mnCrud04 = new Service();
757
        mnCrud04.setName("Metacat MN_Crud Services Version 0.4");
758
        mnCrud04.setVersion("0.4");
759
        
760
        Service mnCrud09 = new Service();
761
        mnCrud09.setName("Metacat MN_Crud Services Version 0.9");
762
        mnCrud09.setVersion("0.9");
763
        
764
        Service mnReplication03 = new Service();
765
        mnReplication03.setName("Metcat MN_Replication Version 0.3");
766
        mnReplication03.setVersion("0.3");
767
        
768
        Service mnHealth04 = new Service();
769
        mnHealth04.setName("Metacat MN_Health Version 0.4");
770
        mnHealth04.setVersion("0.4");
771
        
772
        Service mnHealth06 = new Service();
773
        mnHealth06.setName("Metacat MN_Health Version 0.6");
774
        mnHealth06.setVersion("0.6");
775
        
776
        Service mnAuthentication07 = new Service();
777
        mnAuthentication07.setName("Metacat MN_Authentication Version 0.7");
778
        mnAuthentication07.setVersion("0.7");
779
        
780
        Service mnAuthorization07 = new Service();
781
        mnAuthorization07.setName("Metacat MN_Authorization Version 0.7");
782
        mnAuthorization07.setVersion("0.7");
783
        
784
        Services ss = new Services();
785
        ss.addService(mnCrud03);
786
        ss.addService(mnCrud04);
787
        ss.addService(mnCrud09);
788
        ss.addService(mnReplication03);
789
        ss.addService(mnHealth04);
790
        ss.addService(mnHealth06);
791
        ss.addService(mnAuthentication07);
792
        ss.addService(mnAuthorization07);
793
        nl.addNode(n);
794
        response.setContentType("text/xml");
795
        response.setStatus(200);
796
        serializeServiceType(NodeList.class, nl, response.getOutputStream());
797
    }
798
    
799
    /**
800
     * MN_crud.describe()
801
     * http://mule1.dataone.org/ArchitectureDocs/mn_api_crud.html#MN_crud.describe
802
     * @param guid
803
     */
804
    private void describeObject(String guid)
805
    {
806
        Logger logMetacat = Logger.getLogger(ResourceHandler.class);
807
        OutputStream out = null;
808
        try
809
        {
810
            out = response.getOutputStream();
811
        }
812
        catch(Exception e)
813
        {
814
            logMetacat.error("Error getting output stream in ResourceHandler.describeObject: " + e.getClass() + ": " + e.getMessage());
815
            return;
816
        }
817
        response.setStatus(200);
818
        response.setContentType("text/xml");
819
        Identifier id = new Identifier();
820
        id.setValue(guid);
821
        try
822
        {
823
            DescribeResponse dr = MNodeService.getInstance().describe(session, id);
824
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SZ");
825
            response.addHeader("guid", guid);
826
            response.addHeader("checksum", dr.getDataONE_Checksum().getValue());
827
            response.addHeader("checksum_algorithm", dr.getDataONE_Checksum().getAlgorithm());
828
            response.addHeader("content_length", dr.getContent_Length() + "");
829
            response.addHeader("last_modified", dateFormat.format(dr.getLast_Modified()));
830
            response.addHeader("format", dr.getDataONE_ObjectFormatIdentifier().getValue());
831
        }
832
        catch(InvalidRequest ir)
833
        {
834
            serializeException(ir, out);
835
        }
836
        catch(NotImplemented ni)
837
        {
838
            serializeException(ni, out);
839
        }
840
        catch(NotAuthorized na)
841
        {
842
            serializeException(na, out);
843
        }
844
        catch(ServiceFailure sf)
845
        {
846
            serializeException(sf, out);
847
        }
848
        catch(NotFound nf)
849
        {
850
            serializeException(nf, out);
851
        }
852
        catch(InvalidToken it)
853
        {
854
            serializeException(it, out);
855
        }
856
    }
857
    
858
    /**
859
     * get the logs from the CrudService based on passed params.  Available 
860
     * params are token, fromDate, toDate, event.  See 
861
     * http://mule1.dataone.org/ArchitectureDocs/mn_api_crud.html#MN_crud.getLogRecords
862
     * for more info
863
     */
864
    private void getLog()
865
    {
866
        OutputStream out = null;
867
        try
868
        {
869
            out = response.getOutputStream();
870
            response.setStatus(200);
871
            response.setContentType("text/xml");
872
            String fromDateS = params.get("fromDate")[0];
873
            System.out.println("param fromDateS: " + fromDateS);
874
            Date fromDate = null;
875
            String toDateS = params.get("toDate")[0];
876
            System.out.println("param toDateS: " + toDateS);
877
            Date toDate = null;
878
            String eventS = params.get("event")[0];
879
            Event event = null;
880
            if(fromDateS != null)
881
            {
882
                //fromDate = dateFormat.parse(fromDateS);
883
                fromDate = parseDateAndConvertToGMT(fromDateS);
884
            }
885
            if(toDateS != null)
886
            {
887
                //toDate = dateFormat.parse(toDateS);
888
                toDate = parseDateAndConvertToGMT(toDateS);
889
            }
890
            if(eventS != null)
891
            {
892
                event = Event.convert(eventS);
893
            }
894
            System.out.println("fromDate: " + fromDate + " toDate: " + toDate);
895
            
896
            Integer start = null;
897
            Integer count = null;
898
            try {
899
            	start =  Integer.parseInt(params.get("start")[0]);
900
            } catch (Exception e) {
901
				logMetacat.warn("Could not parse start: " + e.getMessage());
902
			}
903
            try {
904
            	count =  Integer.parseInt(params.get("count")[0]);
905
            } catch (Exception e) {
906
				logMetacat.warn("Could not count start: " + e.getMessage());
907
			}
908
            
909
            System.out.println("calling crudservice.getLogRecords");
910
            Log log = MNodeService.getInstance().getLogRecords(session, fromDate, toDate, event, start, count);
911
            serializeServiceType(Log.class, log, out);
912
        }
913
        catch(Exception e)
914
        {
915
            String msg = "Could not get logs from CrudService: " + e.getClass() + ": " + e.getMessage();
916
            response.setStatus(500);
917
            ServiceFailure sf = new ServiceFailure("1490", msg);
918
            logMetacat.error(msg);
919
            e.printStackTrace();
920
            serializeException(sf, out);
921
        }
922
    }
923
    
924
    /**
925
     *  copies request parameters to a hashtable which is given as argument to native metacathandler functions  
926
     */
927
    protected void initParams() {
928

  
929
        String name = null;
930
        String[] value = null;
931
        Enumeration paramlist = request.getParameterNames();
932
        while (paramlist.hasMoreElements()) {
933
            name = (String) paramlist.nextElement();
934
            value = request.getParameterValues(name);
935
            params.put(name, value);
936
        }
937
    }
938

  
939
    /**
940
     * 
941
     * Load user details of metacat session from the request 
942
     * 
943
     */
944
    private void loadSessionData()
945
      throws Exception
946
    {
947
        SessionData sessionData = RequestUtil.getSessionData(request);
948
        try
949
        {
950
            username = null;
951
            password = null;
952
            groupNames = null;
953
            sessionId = null;
954
            
955
            boolean validSession = false;
956
            SessionService ss = SessionService.getInstance();
957
            System.out.println("sessionData: " + sessionData);
958
            if(sessionData == null)
959
            {
960
                username = "public";
961
                sessionId = "0";
962
                System.out.println("sessiondata is null.  Creating a public session.");
963
                return;
964
            }
965
            
966
            System.out.println("username: " + sessionData.getUserName());
967
            System.out.println("sessionid: " + sessionData.getId());
968
            //validate the session
969
            if(ss.isSessionRegistered(sessionData.getId()) && 
970
               !(sessionData.getUserName().equals("public") || sessionData.getId().equals("0")))
971
            {
972
                validSession = true;
973
            }
974
            
975
            if(validSession)
976
            {
977
                //if the session is valid, set these variables
978
                username = sessionData.getUserName();
979
                password = sessionData.getPassword();
980
                groupNames = sessionData.getGroupNames();
981
                sessionId = sessionData.getId();
982
                System.out.println("setting sessionid to " + sessionId);
983
                System.out.println("username: " + username);
984
            }
985
            
986
            //if the session is not valid or the username is null, set
987
            //username to public
988
            if (username == null) 
989
            {
990
                System.out.println("setting username to public.");
991
                username = "public";
992
            }
993
        }
994
        catch(Exception e)
995
        {
996
            e.printStackTrace();
997
            throw new Exception("Could not load the session data: " + e.getClass() + ": " + e.getMessage());
998
        }
999
    }
1000

  
1001
    /**
1002
     *  Earthgrid API > Identifier Service > isRegistered Function : 
1003
     *  calls MetacatHandler > handleIdIsRegisteredAction
1004
     * @param guid
1005
     * @throws IOException
1006
     */
1007
    private void isRegistered(String guid) throws IOException
1008
    {
1009
        
1010
        // Look up the localId for this guid
1011
        IdentifierManager im = IdentifierManager.getInstance();
1012
        String localId = "";
1013
        try {
1014
            localId = im.getLocalId(guid);
1015
        } catch (McdbDocNotFoundException e) {
1016
            // TODO: Need to return the proper DataONE exception
1017
        }
1018
        
1019
        params.put("docid", new String[] { localId });
1020
        PrintWriter out = response.getWriter();
1021
        response.setStatus(200);
1022
        response.setContentType("text/xml");
1023
        handler.handleIdIsRegisteredAction(out, params, response);
1024
        out.close();
1025
    }
1026

  
1027
    /**
1028
     * Earthgrid API > Identifier Service > getAllDocIds Function : 
1029
     * calls MetacatHandler > handleGetAllDocidsAction
1030
     * @throws IOException
1031
     */
1032
    private void getAllDocIds() throws IOException {
1033
        PrintWriter out = response.getWriter();
1034
        response.setStatus(200);
1035
        response.setContentType("text/xml");
1036
        handler.handleGetAllDocidsAction(out, params, response);
1037
        out.close();
1038
    }
1039

  
1040
    /**
1041
     * Earthgrid API > Identifier Service > getNextRevision Function : 
1042
     * calls MetacatHandler > handleGetRevisionAndDocTypeAction
1043
     * @param guid
1044
     * @throws IOException
1045
     */
1046
    private void getNextRevision(String guid) throws IOException 
1047
    {
1048
        params.put("docid", new String[] { guid });
1049
        PrintWriter out = response.getWriter();
1050
        response.setStatus(200);
1051
        response.setContentType("text/xml");
1052
        //handler.handleGetRevisionAndDocTypeAction(out, params);
1053

  
1054
        try {
1055
            // Make sure there is a docid
1056
            if (guid == null || guid.equals("")) {
1057
                throw new Exception("User didn't specify docid!");
1058
            }
1059

  
1060
            // Look up the localId for this guid
1061
            IdentifierManager im = IdentifierManager.getInstance();
1062
            String localId = "";
1063
            try {
1064
                localId = im.getLocalId(guid);
1065
            } catch (McdbDocNotFoundException e) {
1066
                // TODO: Need to return the proper DataONE exception
1067
            }
1068
           
1069
            // Create a DBUtil object
1070
            DBUtil dbutil = new DBUtil();
1071
            // Get a rev and doctype
1072
            String revAndDocType = dbutil
1073
                    .getCurrentRevisionAndDocTypeForGivenDocument(localId);
1074
            int revision = Integer.parseInt(revAndDocType.split(";")[0]) + 1;
1075

  
1076
            out.println("<?xml version=\"1.0\"?>");
1077
            out.print("<next-revision>");
1078
            out.print(revision);
1079
            out.print("</next-revision>");
1080

  
1081
        } catch (Exception e) {
1082
            // Handle exception
1083
            response.setStatus(500);
1084
            out.println("<?xml version=\"1.0\"?>");
1085
            out.println("<error>");
1086
            out.println(e.getClass() + ": " + e.getMessage());
1087
            out.println("</error>");
1088
        }
1089

  
1090
        out.close();
1091
    }
1092

  
1093
    /**
1094
     * Earthgrid API > Identifier Service > getNextObject Function : 
1095
     * calls MetacatHandler > handleGetMaxDocidAction
1096
     * @throws IOException
1097
     */
1098
    private void getNextObject() throws IOException {
1099
        PrintWriter out = response.getWriter();
1100
        response.setStatus(200);
1101
        response.setContentType("text/xml");
1102
        handler.handleGetMaxDocidAction(out, params, response);
1103
        out.close();
1104
    }
1105

  
1106
    /**
1107
     * Implements REST version of DataONE CRUD API --> get
1108
     * @param guid ID of data object to be read
1109
     */
1110
    protected void getObject(String guid) {
1111
        OutputStream out = null;
1112
        try {
1113
            out = response.getOutputStream();
1114
            response.setStatus(200);
1115
            
1116
            if(guid != null)
1117
            { //get a specific document                
1118
                Identifier id = new Identifier();
1119
                id.setValue(guid);
1120
                try
1121
                {
1122
                    
1123
                    SystemMetadata sm = MNodeService.getInstance().getSystemMetadata(session, id);
1124
                    
1125
                    //set the content type
1126
                    if(sm.getFmtid().getValue().trim().equals(
1127
                    		ObjectFormatCache.getInstance().getFormat("text/csv").getFmtid().getValue()))
1128
                    {
1129
                        response.setContentType("text/csv");
1130
                        response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".csv");
1131
                    }
1132
                    else if(sm.getFmtid().getValue().trim().equals(
1133
                    		ObjectFormatCache.getInstance().getFormat("text/plain").getFmtid().getValue()))
1134
                    {
1135
                        response.setContentType("text/plain");
1136
                        response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".txt");
1137
                    } 
1138
                    else if(sm.getFmtid().getValue().trim().equals(
1139
                    		ObjectFormatCache.getInstance().getFormat("application/octet-stream").getFmtid().getValue()))
1140
                    {
1141
                        response.setContentType("application/octet-stream");
1142
                    }
1143
                    else
1144
                    {
1145
                        response.setContentType("text/xml");
1146
                        response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".xml");
1147
                    }
1148
                    
1149
                    InputStream data = MNodeService.getInstance().get(session, id);
1150
                    IOUtils.copyLarge(data, response.getOutputStream());
1151
                }
1152
                catch(InvalidToken it)
1153
                {
1154
                    response.setStatus(500);
1155
                    serializeException(it, out); 
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff