summaryrefslogtreecommitdiff
path: root/projects/net.wotonomy.web/src/main/java/net/wotonomy/web/xml/XMLRPCServlet.java
blob: a9981a43a42ecb3d223f2f5be0177b9563c181a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*
Wotonomy: OpenStep design patterns for pure Java applications.
Copyright (C) 2001 Intersect Software Corporation

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see http://www.gnu.org
*/

package net.wotonomy.web.xml;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.wotonomy.foundation.NSSelector;
import net.wotonomy.foundation.internal.WotonomyException;

/**
* A servlet that can make any java object into an XML-RPC server.
* Simply pass in the object to the constructor and XML-RPC requests
* to this servlet will call the appropriate methods and convert
* the results to an XML-RPC response. <br><br>
*
* Depending on your servlet container, it may be necessary to 
* create a simple subclass that creates your handler object
* in its constructor and then calls setHandler(). <br><br>
*
* Responses are in the specification's standard response format.<br><br>
*
* Faults are returned if any exception is thrown in the method,
* or if the specified method is not found on the object.
* The fault string is the toString value of the exception,
* and the fault code is the hasCode value of the exception. <br><br>
*
* Remember that this servlet only responds to POSTs, 
* per the XML-RPC spec.  
*/
public class XMLRPCServlet extends HttpServlet 
{
    protected Object handler;
    protected boolean synchronizing;
    private Hashtable selectorCache = new Hashtable(); // thread safe
    private boolean copyStream = false;
    
    /**
    * Default constructor initializes internal state.
    */
    public XMLRPCServlet()
    {
        handler = null;
        synchronizing = false;
    }
    
    /**
    * Constructor takes any java object and allows its methods
    * to be invoked via XMLRPC requests to this servlet.
    * Simply calls setHandler().
    */
    public XMLRPCServlet( Object aHandler )
    {
        this();
        setHandler( aHandler );
    }
    
    /**
    * Gets the object whose methods will be invoked to
    * handle incoming requests.
    */
    public Object getHandler()
    {
        return handler;
    }
    
    /**
    * Sets the object whose methods will be invoked to
    * handle incoming requests.
    */
    public void setHandler( Object aHandler )
    {
        handler = aHandler;
    }
    
    /**
    * Gets whether the servlet should synchonize on the
    * object before invoking methods on it.
    * Defaults to false.
    */
    public boolean isSynchronizing()
    {
        return synchronizing;
    }
    
    /**
    * Sets whether the servlet should synchonize on the
    * object before invoking methods on it.
    * Defaults to false.
    */
    public void setSynchronizing( boolean willSynchronize )
    {
        synchronizing = willSynchronize;
    }
    
    /**
    * Overridden to service the request.
    */
    protected void doPost(
        HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException
    {
        if ( getHandler() != null )
        {
            InputStream input = req.getInputStream();
            byte[] copyOfRequest = null;

            if ( copyStream )
            {
                ByteArrayOutputStream byteArray =
                    new ByteArrayOutputStream();
                int b;
                while ( ( b = input.read() ) != -1 )
                {
                    byteArray.write( b );
                }
                copyOfRequest = byteArray.toByteArray();
                input = new ByteArrayInputStream( copyOfRequest );
            }
            
            try
            {
                new XMLRPCDecoder().decode( input, 
                    new Receiver( this, resp ) );
            }
            catch ( WotonomyException exc )
            {
                if ( copyOfRequest != null )
                {
                    System.out.println( new String( copyOfRequest ) );
                    exc.printStackTrace();
                }
                // catches io exceptions thrown in handleRequest.
                Throwable t = exc.getWrappedThrowable();
                if ( t instanceof IOException )
                {
                    throw (IOException)t;
                }
                throw exc;
            }
        }
    }
    
    /**
    * Called by doPost after parsing an incoming request,
    * and is responsible for invoking the specified method
    * with the specified parameters on the handler object.
    * (This implementation calls getOutputStream() on the response.)
    * Override to customize the handling of the request.
    */
    protected void handleRequest( String aMethodName, 
        Object[] aParameterArray, HttpServletResponse aResponse )
    {
        OutputStream output = null;
        
        try 
        {
            output = aResponse.getOutputStream();
            aResponse.setStatus( HttpServletResponse.SC_OK ); // always 200
            aResponse.setContentType( "text/xml" );
        }
        catch ( IOException exc )
        {
            // caught in doPost
            throw new WotonomyException( exc );   
        }
        
        // get the array of types
        XMLRPCEncoder encoder = new XMLRPCEncoder();
        Class[] types = new Class[ aParameterArray.length ];
        for ( int i = 0; i < aParameterArray.length; i++ )
        {
            types[i] = aParameterArray[i].getClass();
        }
        
        //TODO: selectors should be cached if possible
        
        Object handler = getHandler();
        if ( isSynchronizing() )
        {
            synchronized ( handler )
            {
                execute( encoder, handler, output,
                    new NSSelector( aMethodName, types ), aParameterArray );
            }
        }
        else
        {
            execute( encoder, handler, output,
                new NSSelector( aMethodName, types ), aParameterArray );
        }
    }
    
    private void execute( XMLRPCEncoder anEncoder, Object aHandler, 
        OutputStream output, NSSelector aSelector, Object[] aParameterArray )
    {
        try 
        {
            Object result = 
                aSelector.invoke( aHandler, aParameterArray );
            anEncoder.encodeResponse( result, output );
        }
        catch ( Exception exc )
        {
            anEncoder.encodeFault( 
                exc.hashCode(), exc.toString(), output );
        }
    }
    
    private class Receiver implements XMLRPCReceiver
    {
        XMLRPCServlet controller;
        HttpServletResponse response;
        
        public Receiver( 
            XMLRPCServlet aController,
            HttpServletResponse aResponse )
        {
            controller = aController;
            response = aResponse;
        }
        
        public void request( 
            String aMethodName, Object[] aParameterArray )
        {
            controller.handleRequest( 
                aMethodName, aParameterArray, response );
        }
        
        public void response( 
            Object aResult ) 
        {
            // does nothing
        }
        
        public void fault( 
            int aFaultCode, String aFaultString)
        {
            // does nothing
        }
    }
}

/*
 * $Log$
 * Revision 1.1  2006/02/19 01:44:02  cgruber
 * Add xmlrpc files
 * Remove jclark and replace with dom4j and javax.xml.sax stuff
 * Re-work dependencies and imports so it all compiles.
 *
 * Revision 1.1  2006/02/16 13:22:22  cgruber
 * Check in all sources in eclipse-friendly maven-enabled packages.
 *
 * Revision 1.1  2001/02/07 19:24:28  mpowers
 * Moved XML classes to separate package.
 *
 */