THRIFT-550: Added javascript support
git-svn-id: https://svn.apache.org/repos/asf/incubator/thrift/trunk@910158 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/lib/js/test/RunTestServer.sh b/lib/js/test/RunTestServer.sh
new file mode 100755
index 0000000..574f7c5
--- /dev/null
+++ b/lib/js/test/RunTestServer.sh
@@ -0,0 +1,40 @@
+#!/bin/bash
+
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+LOG4J="../../java/build/ivy/lib/slf4j-api-1.5.8.jar:../../java/build/ivy/lib/log4j-1.2.15.jar:../../java/build/ivy/lib/slf4j-simple-1.5.8.jar"
+HTTPCORE="./httpcore-4.0.1.jar"
+
+if [ -f ${HTTPCORE} ]
+then
+ echo "compiling test..."
+else
+ echo "Missing required file ${HTTPCORE}"
+ echo "You can download this from http://archive.apache.org/dist/httpcomponents/httpcore/binary/httpcomponents-core-4.0.1-bin.tar.gz"
+ echo "Place the jar in this directory and try again."
+ exit
+fi
+
+../../../compiler/cpp/thrift --gen java ../../../test/ThriftTest.thrift
+../../../compiler/cpp/thrift --gen js ../../../test/ThriftTest.thrift
+
+javac -cp ${LOG4J}:../../java/libthrift.jar gen-java/thrift/test/*.java
+javac -cp ${LOG4J}:${HTTPCORE}:../../java/libthrift.jar:gen-java/ src/test/*.java
+java -cp ${LOG4J}:${HTTPCORE}:../../java/libthrift.jar:gen-java:src test.Httpd ../
diff --git a/lib/js/test/src/test/Httpd.java b/lib/js/test/src/test/Httpd.java
new file mode 100644
index 0000000..155a8b8
--- /dev/null
+++ b/lib/js/test/src/test/Httpd.java
@@ -0,0 +1,298 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package test;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.URLDecoder;
+import java.util.Locale;
+
+import org.apache.http.ConnectionClosedException;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpEntityEnclosingRequest;
+import org.apache.http.HttpException;
+import org.apache.http.HttpRequest;
+import org.apache.http.HttpResponse;
+import org.apache.http.HttpServerConnection;
+import org.apache.http.HttpStatus;
+import org.apache.http.MethodNotSupportedException;
+import org.apache.http.entity.ContentProducer;
+import org.apache.http.entity.EntityTemplate;
+import org.apache.http.entity.FileEntity;
+import org.apache.http.impl.DefaultHttpResponseFactory;
+import org.apache.http.impl.DefaultHttpServerConnection;
+import org.apache.http.impl.NoConnectionReuseStrategy;
+import org.apache.http.params.BasicHttpParams;
+import org.apache.http.params.CoreConnectionPNames;
+import org.apache.http.params.CoreProtocolPNames;
+import org.apache.http.params.HttpParams;
+import org.apache.http.protocol.BasicHttpContext;
+import org.apache.http.protocol.BasicHttpProcessor;
+import org.apache.http.protocol.HttpContext;
+import org.apache.http.protocol.HttpProcessor;
+import org.apache.http.protocol.HttpRequestHandler;
+import org.apache.http.protocol.HttpRequestHandlerRegistry;
+import org.apache.http.protocol.HttpService;
+import org.apache.http.util.EntityUtils;
+import org.apache.thrift.TProcessor;
+import org.apache.thrift.protocol.TJSONProtocol;
+import org.apache.thrift.protocol.TProtocol;
+import org.apache.thrift.transport.TMemoryBuffer;
+
+import thrift.test.ThriftTest;
+
+/**
+ * Basic, yet fully functional and spec compliant, HTTP/1.1 file server.
+ * <p>
+ * Please note the purpose of this application is demonstrate the usage of
+ * HttpCore APIs. It is NOT intended to demonstrate the most efficient way of
+ * building an HTTP file server.
+ *
+ *
+ */
+public class Httpd {
+
+ public static void main(String[] args) throws Exception {
+ if (args.length < 1) {
+ System.err.println("Please specify document root directory");
+ System.exit(1);
+ }
+ Thread t = new RequestListenerThread(8088, args[0]);
+ t.setDaemon(false);
+ t.start();
+ }
+
+ static class HttpFileHandler implements HttpRequestHandler {
+
+ private final String docRoot;
+
+ public HttpFileHandler(final String docRoot) {
+ super();
+ this.docRoot = docRoot;
+ }
+
+ public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException {
+
+ String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
+ if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
+ throw new MethodNotSupportedException(method + " method not supported");
+ }
+ String target = request.getRequestLine().getUri();
+
+ if (request instanceof HttpEntityEnclosingRequest && target.equals("/service")) {
+ HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
+ byte[] entityContent = EntityUtils.toByteArray(entity);
+ System.out.println("Incoming content: " + new String(entityContent));
+
+ final String output = this.thriftRequest(entityContent);
+
+ System.out.println("Outgoing content: "+output);
+
+ EntityTemplate body = new EntityTemplate(new ContentProducer() {
+
+ public void writeTo(final OutputStream outstream) throws IOException {
+ OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
+ writer.write(output);
+ writer.flush();
+ }
+
+ });
+ body.setContentType("text/html; charset=UTF-8");
+ response.setEntity(body);
+ } else {
+
+ final File file = new File(this.docRoot, URLDecoder.decode(target));
+ if (!file.exists()) {
+
+ response.setStatusCode(HttpStatus.SC_NOT_FOUND);
+ EntityTemplate body = new EntityTemplate(new ContentProducer() {
+
+ public void writeTo(final OutputStream outstream) throws IOException {
+ OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
+ writer.write("<html><body><h1>");
+ writer.write("File ");
+ writer.write(file.getPath());
+ writer.write(" not found");
+ writer.write("</h1></body></html>");
+ writer.flush();
+ }
+
+ });
+ body.setContentType("text/html; charset=UTF-8");
+ response.setEntity(body);
+ System.out.println("File " + file.getPath() + " not found");
+
+ } else if (!file.canRead() || file.isDirectory()) {
+
+ response.setStatusCode(HttpStatus.SC_FORBIDDEN);
+ EntityTemplate body = new EntityTemplate(new ContentProducer() {
+
+ public void writeTo(final OutputStream outstream) throws IOException {
+ OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
+ writer.write("<html><body><h1>");
+ writer.write("Access denied");
+ writer.write("</h1></body></html>");
+ writer.flush();
+ }
+
+ });
+ body.setContentType("text/html; charset=UTF-8");
+ response.setEntity(body);
+ System.out.println("Cannot read file " + file.getPath());
+
+ } else {
+
+ response.setStatusCode(HttpStatus.SC_OK);
+ FileEntity body = new FileEntity(file, "text/html");
+ response.setEntity(body);
+ System.out.println("Serving file " + file.getPath());
+
+ }
+ }
+ }
+
+ private String thriftRequest(byte[] input){
+ try{
+
+ //Input
+ TMemoryBuffer inbuffer = new TMemoryBuffer(input.length);
+ inbuffer.write(input);
+ TProtocol inprotocol = new TJSONProtocol(inbuffer);
+
+ //Output
+ TMemoryBuffer outbuffer = new TMemoryBuffer(100);
+ TProtocol outprotocol = new TJSONProtocol(outbuffer);
+
+ TProcessor processor = new ThriftTest.Processor(new TestHandler());
+ processor.process(inprotocol, outprotocol);
+
+ byte[] output = new byte[outbuffer.length()];
+ outbuffer.readAll(output, 0, output.length);
+
+ return new String(output,"UTF-8");
+ }catch(Throwable t){
+ return "Error:"+t.getMessage();
+ }
+
+
+ }
+
+ }
+
+ static class RequestListenerThread extends Thread {
+
+ private final ServerSocket serversocket;
+ private final HttpParams params;
+ private final HttpService httpService;
+
+ public RequestListenerThread(int port, final String docroot) throws IOException {
+ this.serversocket = new ServerSocket(port);
+ this.params = new BasicHttpParams();
+ this.params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 1000).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
+ .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
+ .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
+
+ // Set up the HTTP protocol processor
+ HttpProcessor httpproc = new BasicHttpProcessor();
+
+ // Set up request handlers
+ HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
+ reqistry.register("*", new HttpFileHandler(docroot));
+
+ // Set up the HTTP service
+ this.httpService = new HttpService(httpproc, new NoConnectionReuseStrategy(), new DefaultHttpResponseFactory());
+ this.httpService.setParams(this.params);
+ this.httpService.setHandlerResolver(reqistry);
+ }
+
+ public void run() {
+ System.out.println("Listening on port " + this.serversocket.getLocalPort());
+ System.out.println("Point your browser to http://localhost:8088/test/test.html");
+
+ while (!Thread.interrupted()) {
+ try {
+ // Set up HTTP connection
+ Socket socket = this.serversocket.accept();
+ DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
+ System.out.println("Incoming connection from " + socket.getInetAddress());
+ conn.bind(socket, this.params);
+
+ // Start worker thread
+ Thread t = new WorkerThread(this.httpService, conn);
+ t.setDaemon(true);
+ t.start();
+ } catch (InterruptedIOException ex) {
+ break;
+ } catch (IOException e) {
+ System.err.println("I/O error initialising connection thread: " + e.getMessage());
+ break;
+ }
+ }
+ }
+ }
+
+ static class WorkerThread extends Thread {
+
+ private final HttpService httpservice;
+ private final HttpServerConnection conn;
+
+ public WorkerThread(final HttpService httpservice, final HttpServerConnection conn) {
+ super();
+ this.httpservice = httpservice;
+ this.conn = conn;
+ }
+
+ public void run() {
+ System.out.println("New connection thread");
+ HttpContext context = new BasicHttpContext(null);
+ try {
+ while (!Thread.interrupted() && this.conn.isOpen()) {
+ this.httpservice.handleRequest(this.conn, context);
+ }
+ } catch (ConnectionClosedException ex) {
+ System.err.println("Client closed connection");
+ } catch (IOException ex) {
+ System.err.println("I/O error: " + ex.getMessage());
+ } catch (HttpException ex) {
+ System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
+ } finally {
+ try {
+ this.conn.shutdown();
+ } catch (IOException ignore) {
+ }
+ }
+ }
+
+ }
+
+}
diff --git a/lib/js/test/src/test/TestHandler.java b/lib/js/test/src/test/TestHandler.java
new file mode 100644
index 0000000..2eaf6c6
--- /dev/null
+++ b/lib/js/test/src/test/TestHandler.java
@@ -0,0 +1,123 @@
+package test;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.thrift.TException;
+
+import thrift.test.Insanity;
+import thrift.test.ThriftTest;
+import thrift.test.Xception;
+import thrift.test.Xception2;
+import thrift.test.Xtruct;
+import thrift.test.Xtruct2;
+import thrift.test.Numberz;
+
+public class TestHandler implements ThriftTest.Iface {
+
+ public byte testByte(byte thing) throws TException {
+ return thing;
+ }
+
+ public double testDouble(double thing) throws TException {
+ return thing;
+ }
+
+ public Numberz testEnum(Numberz thing) throws TException {
+ return thing;
+ }
+
+ public void testException(String arg) throws Xception, TException {
+ throw new Xception(1,"server test exception");
+ }
+
+ public int testI32(int thing) throws TException {
+ return thing;
+ }
+
+ public long testI64(long thing) throws TException {
+ return thing;
+ }
+
+ public Map<Long, Map<Numberz, Insanity>> testInsanity(Insanity argument) throws TException {
+ Map<Long, Map<Numberz, Insanity>> result = new HashMap<Long, Map<Numberz,Insanity>>();
+
+ result.put(Long.valueOf(1), new HashMap<Numberz,Insanity>());
+ result.get(Long.valueOf(1)).put(Numberz.ONE, argument);
+
+ result.put(Long.valueOf(2), new HashMap<Numberz,Insanity>());
+ result.get(Long.valueOf(2)).put(Numberz.ONE, argument);
+
+ return result;
+ }
+
+ public List<Integer> testList(List<Integer> thing) throws TException {
+ return thing;
+ }
+
+ public Map<Integer, Integer> testMap(Map<Integer, Integer> thing) throws TException {
+ return thing;
+ }
+
+ public Map<Integer, Map<Integer, Integer>> testMapMap(int hello) throws TException {
+ Map<Integer, Map<Integer,Integer>> result = new HashMap<Integer, Map<Integer,Integer>>();
+
+ result.put(Integer.valueOf(1), new HashMap<Integer,Integer>());
+ result.get(Integer.valueOf(1)).put(Integer.valueOf(1), Integer.valueOf(1));
+ result.get(Integer.valueOf(1)).put(Integer.valueOf(2), Integer.valueOf(2));
+ result.get(Integer.valueOf(2)).put(Integer.valueOf(1), Integer.valueOf(1));
+
+ return result;
+ }
+
+ public Xtruct testMulti(byte arg0, int arg1, long arg2, Map<Short, String> arg3, Numberz arg4, long arg5) throws TException {
+ Xtruct xtr = new Xtruct();
+
+ xtr.byte_thing = arg0;
+ xtr.i32_thing = arg1;
+ xtr.i64_thing = arg2;
+ xtr.string_thing = "server string";
+
+ return xtr;
+ }
+
+ public Xtruct testMultiException(String arg0, String arg1) throws Xception, Xception2, TException {
+ Xtruct xtr = new Xtruct();
+ xtr.setString_thing(arg0);
+ throw new Xception2(1,xtr);
+ }
+
+ public Xtruct2 testNest(Xtruct2 thing) throws TException {
+ return thing;
+ }
+
+ public void testOneway(int secondsToSleep) throws TException {
+ try{
+ Thread.sleep(secondsToSleep * 1000);
+ }catch(InterruptedException e){
+
+ }
+ }
+
+ public Set<Integer> testSet(Set<Integer> thing) throws TException {
+ return thing;
+ }
+
+ public String testString(String thing) throws TException {
+ return thing;
+ }
+
+ public Xtruct testStruct(Xtruct thing) throws TException {
+ return thing;
+ }
+
+ public long testTypedef(long thing) throws TException {
+ return thing;
+ }
+
+ public void testVoid() throws TException {
+
+ }
+}
diff --git a/lib/js/test/test.html b/lib/js/test/test.html
new file mode 100644
index 0000000..903ea40
--- /dev/null
+++ b/lib/js/test/test.html
@@ -0,0 +1,115 @@
+<html>
+<head>
+ <title>Thrift Javascript Bindings - Example</title>
+
+ <script src="/thrift.js" type="text/javascript"></script>
+ <script src="gen-js/ThriftTest_types.js" type="text/javascript"></script>
+ <script src="gen-js/ThriftTest.js" type="text/javascript"></script>
+
+ <!-- for async example -->
+ <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
+
+</head>
+<body id="body">
+
+<script language="javascript">
+
+ //create client
+ var transport = new Thrift.Transport("/service")
+ var protocol = new Thrift.Protocol(transport)
+ var client = new ThriftTest.ThriftTestClient(protocol)
+
+ //create insanity obj
+ var insanity = new ThriftTest.Insanity()
+ insanity.userMap[ThriftTest.Numberz.ONE] = 1
+ insanity.userMap[ThriftTest.Numberz.TWO] = 2
+
+ var xtr = new ThriftTest.Xtruct()
+ xtr.string_thing = 'worked'
+ insanity.xtructs.push(xtr)
+
+ var xtr2= new ThriftTest.Xtruct2()
+ xtr2.struct_thing = xtr
+
+ var list = [1,2,3]
+
+ //run tests synchronously
+
+ document.write("<h2><u>Thrift Javascript Bindings</u></h2>")
+ document.write("<h2>Synchronous Example</h2>")
+ document.write("client.testString() => "+(client.testString("works") == "works")+"<br/>")
+ document.write("client.testString(utf-8) => "+(client.testString("ae") == "ae")+"<br/>")
+ document.write("client.testDouble() => "+(client.testDouble(3.14) == 3.14)+"<br/>")
+ document.write("client.testByte() => "+(client.testByte(0x01) == 0x01)+"<br/>")
+ document.write("client.testI32() => "+(client.testI32(Math.pow(2,30)) == Math.pow(2,30))+"<br/>")
+ document.write("client.testI64() => "+(client.testI64(Math.pow(2,60)) == Math.pow(2,60))+"<br/>")
+ document.write("client.testStruct() => "+(client.testStruct(xtr).string_thing == "worked")+"<br/>")
+ document.write("client.testNest() => "+(client.testNest(xtr2).struct_thing.string_thing == "worked")+"<br/>")
+ document.write("client.testMap() => "+(client.testMap(insanity.userMap)[ThriftTest.Numberz.ONE] == 1)+"<br/>")
+ document.write("client.testList() => "+(client.testList(list).length == 3)+"<br/>")
+ document.write("client.testSet() => "+(client.testSet(list).length == 3)+"<br/>")
+ document.write("client.testEnum() => "+(client.testEnum(ThriftTest.Numberz.ONE) == ThriftTest.Numberz.ONE)+"<br/>")
+
+ document.write("client.testException() => ")
+ try{
+ client.testException("go")
+ document.write("false<br/>")
+ }catch(e){
+ document.write("true<br/>")
+ }
+
+ document.write("client.testInsanity() => ")
+ var res = client.testInsanity(insanity)
+
+ document.write((res["1"]["1"].xtructs[0].string_thing == "worked")+"<br/>")
+
+ //////////////////////////////////
+ //Run same tests asynchronously
+
+ var transport = new Thrift.Transport()
+ var protocol = new Thrift.Protocol(transport)
+ var client = new ThriftTest.ThriftTestClient(protocol)
+
+ document.write("<h2>Asynchronous Example</h2>")
+ jQuery.ajax({
+ url: "/service",
+ data: client.send_testI32(Math.pow(2,30)),
+ type: "POST",
+ cache: false,
+ success: function(res){
+ var _transport = new Thrift.Transport()
+ var _protocol = new Thrift.Protocol(_transport)
+ var _client = new ThriftTest.ThriftTestClient(_protocol)
+
+ _transport.setRecvBuffer( res )
+
+ var v = _client.recv_testI32()
+ $("#body").append("client.testI32() => "+(v == Math.pow(2,30))+"<br/>")
+
+ }
+ })
+
+ jQuery.ajax({
+ url: "/service",
+ data: client.send_testI64(Math.pow(2,60)),
+ type: "POST",
+ cache: false,
+ success: function(res){
+ var _transport = new Thrift.Transport()
+ var _protocol = new Thrift.Protocol(_transport)
+ var _client = new ThriftTest.ThriftTestClient(_protocol)
+
+ _transport.setRecvBuffer( res )
+
+ var v = _client.recv_testI64()
+ $("#body").append("client.testI64() => "+(v == Math.pow(2,60))+"<br/>")
+
+ }
+ })
+
+
+
+</script>
+
+</body>
+</html>