summaryrefslogtreecommitdiffstats
path: root/sca-java-1.x/tags/1.6-TUSCANY-3909/binding-hessian/src/main/java/org/apache/tuscany/sca/binding/hessian/provider/HessianServiceListenerServlet.java
blob: de9b4927c6f4944b8a60b8431629780a6174c258 (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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/*
 * Copyright (c) 2001-2008 Caucho Technology, Inc.  All rights reserved.
 *
 * The Apache Software License, Version 1.1
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Caucho Technology (http://www.caucho.com/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "Hessian", "Resin", and "Caucho" must not be used to
 *    endorse or promote products derived from this software without prior
 *    written permission. For written permission, please contact
 *    info@caucho.com.
 *
 * 5. Products derived from this software may not be called "Resin"
 *    nor may "Resin" appear in their names without prior written
 *    permission of Caucho Technology.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author Scott Ferguson
 */

package org.apache.tuscany.sca.binding.hessian.provider;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tuscany.sca.interfacedef.Interface;
import org.apache.tuscany.sca.interfacedef.Operation;
import org.apache.tuscany.sca.interfacedef.java.JavaOperation;
import org.apache.tuscany.sca.invocation.Message;
import org.apache.tuscany.sca.invocation.MessageFactory;
import org.apache.tuscany.sca.runtime.RuntimeWire;

import com.caucho.hessian.io.AbstractHessianInput;
import com.caucho.hessian.io.AbstractHessianOutput;
import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.HessianOutput;
import com.caucho.hessian.io.SerializerFactory;
import com.caucho.services.server.ServiceContext;

/**
 * Servlet for serving Hessian services.
 */
public class HessianServiceListenerServlet extends GenericServlet {

    private static final Logger logger = Logger.getLogger(HessianServiceListenerServlet.class.getName());

    private Interface homeImpl;
    private RuntimeWire wire;
    private MessageFactory messageFactory;

    private SerializerFactory _serializerFactory;

    private Map<String, JavaOperation> _operationMap = new Hashtable<String, JavaOperation>();

    public HessianServiceListenerServlet(Interface homeImpl, RuntimeWire wire, MessageFactory messageFactory) {
        this.homeImpl = homeImpl;
        this.wire = wire;
        this.messageFactory = messageFactory;

        List<Operation> operations = homeImpl.getOperations();
        for (int i = 0; i < operations.size(); i++) {
            JavaOperation op = (JavaOperation)operations.get(i);
            Method method = op.getJavaMethod();
            if (_operationMap.get(method.getName()) == null)
                _operationMap.put(method.getName(), op);

            Class[] param = method.getParameterTypes();
            String mangledName = method.getName() + "__" + param.length;
            _operationMap.put(mangledName, op);
            _operationMap.put(mangleName(method, false), op);
        }
    }

    public String getServletInfo() {
        return "Tuscany Binding Hessian Servlet";
    }

    /**
     * Sets the serializer factory.
     */
    public void setSerializerFactory(SerializerFactory factory) {
        _serializerFactory = factory;
    }

    /**
     * Gets the serializer factory.
     */
    public SerializerFactory getSerializerFactory() {
        if (_serializerFactory == null)
            _serializerFactory = new SerializerFactory();

        return _serializerFactory;
    }

    /**
     * Sets the serializer send collection java type.
     */
    public void setSendCollectionType(boolean sendType) {
        getSerializerFactory().setSendCollectionType(sendType);
    }

    /**
     * Execute a request. The path-info of the request selects the bean. Once
     * the bean's selected, it will be applied.
     */
    public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;

        if (!req.getMethod().equals("POST")) {
            res.setStatus(500, "Hessian Requires POST");
            PrintWriter out = res.getWriter();
            res.setContentType("text/html");
            out.println("<h1>Hessian Requires POST</h1>");
            return;
        }

        String serviceId = req.getPathInfo();
        String objectId = req.getParameter("id");
        if (objectId == null)
            objectId = req.getParameter("ejbid");

        ServiceContext.begin(req, serviceId, objectId);

        try {
            InputStream is = request.getInputStream();
            OutputStream os = response.getOutputStream();

            Hessian2Input in = new Hessian2Input(is);
            AbstractHessianOutput out;

            SerializerFactory serializerFactory = getSerializerFactory();

            in.setSerializerFactory(serializerFactory);

            int code = in.read();

            if (code != 'c') {
                // XXX: deflate
                throw new IOException("expected 'c' in hessian input at " + code);
            }

            int major = in.read();
            int minor = in.read();

            if (major >= 2)
                out = new Hessian2Output(os);
            else
                out = new HessianOutput(os);

            out.setSerializerFactory(serializerFactory);

            invoke(in, out);

            out.close();
        } catch (RuntimeException e) {
            throw e;
        } catch (ServletException e) {
            throw e;
        } catch (Throwable e) {
            throw new ServletException(e);
        } finally {
            ServiceContext.end();
        }
    }

    private String mangleName(Method method, boolean isFull) {
        StringBuffer sb = new StringBuffer();
        sb.append(method.getName());
        Class[] params = method.getParameterTypes();
        for (int i = 0; i < params.length; i++) {
            sb.append('_');
            sb.append(mangleClass(params[i], isFull));
        }
        return sb.toString();
    }

    private String mangleClass(Class cl, boolean isFull) {
        String name = cl.getName();
        if (name.equals("boolean") || name.equals("java.lang.Boolean"))
            return "boolean";
        else if (name.equals("int") || name.equals("java.lang.Integer")
            || name.equals("short")
            || name.equals("java.lang.Short")
            || name.equals("byte")
            || name.equals("java.lang.Byte"))
            return "int";
        else if (name.equals("long") || name.equals("java.lang.Long"))
            return "long";
        else if (name.equals("float") || name.equals("java.lang.Float")
            || name.equals("double")
            || name.equals("java.lang.Double"))
            return "double";
        else if (name.equals("java.lang.String") || name.equals("com.caucho.util.CharBuffer")
            || name.equals("char")
            || name.equals("java.lang.Character")
            || name.equals("java.io.Reader"))
            return "string";
        else if (name.equals("java.util.Date") || name.equals("com.caucho.util.QDate"))
            return "date";
        else if (InputStream.class.isAssignableFrom(cl) || name.equals("[B"))
            return "binary";
        else if (cl.isArray()) {
            return "[" + mangleClass(cl.getComponentType(), isFull);
        } else if (name.equals("org.w3c.dom.Node") || name.equals("org.w3c.dom.Element")
            || name.equals("org.w3c.dom.Document"))
            return "xml";
        else if (isFull)
            return name;
        else {
            int p = name.lastIndexOf('.');
            if (p > 0)
                return name.substring(p + 1);
            else
                return name;
        }
    }

    public void invoke(AbstractHessianInput in, AbstractHessianOutput out) throws Exception {
        ServiceContext context = ServiceContext.getContext();

        // backward compatibility for some frameworks that don't read
        // the call type first
        in.skipOptionalCall();

        String header;
        while ((header = in.readHeader()) != null) {
            Object value = in.readObject();
            context.addHeader(header, value);
        }

        String methodName = in.readMethod();
        Method method = null;
        JavaOperation operation = _operationMap.get(methodName);
        if (operation != null)
            method = operation.getJavaMethod();

        if (method != null) {
        } else if ("_hessian_getAttribute".equals(methodName)) {
            String attrName = in.readString();
            in.completeCall();
            String value = null;
            if ("java.api.class".equals(attrName))
                value = homeImpl.toString();
            else if ("java.home.class".equals(attrName))
                value = homeImpl.toString();
            else if ("java.object.class".equals(attrName))
                value = homeImpl.toString();
            out.startReply();
            out.writeObject(value);
            out.completeReply();
            return;
        } else if (method == null) {
            out.startReply();
            out.writeFault("NoSuchMethodException", "The service has no method named: " + in.getMethod(), null);
            out.completeReply();
            return;
        }

        Class[] args = method.getParameterTypes();
        Object[] values = new Object[args.length];

        for (int i = 0; i < args.length; i++) {
            values[i] = in.readObject(args[i]);
        }

        Object result = null;
        try {
            Message msg = messageFactory.createMessage();
            msg.setOperation(operation);
            msg.setBody(values);
            result = wire.invoke(operation, msg);
        } catch (Throwable e) {
            while (e instanceof InvocationTargetException)
                e = ((InvocationTargetException)e).getTargetException();
            out.startReply();
            out.writeFault("ServiceException", e.getMessage(), e);
            out.completeReply();
            return;
        }

        // The complete call needs to be after the invoke to handle a
        // trailing InputStream
        in.completeCall();
        out.startReply();
        out.writeObject(result);
        out.completeReply();
        out.close();
    }

}