diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 18:45:59 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 18:45:59 +0000 |
commit | 19fcec84d8d7d21e796c7624e521b60d28ee21ed (patch) | |
tree | 42d26aa27d1e3f7c0b8bd3fd14e7d7082f5008dc /src/jaegertracing/thrift/tutorial/js | |
parent | Initial commit. (diff) | |
download | ceph-upstream.tar.xz ceph-upstream.zip |
Adding upstream version 16.2.11+ds.upstream/16.2.11+dsupstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/jaegertracing/thrift/tutorial/js')
-rwxr-xr-x | src/jaegertracing/thrift/tutorial/js/Makefile.am | 39 | ||||
-rw-r--r-- | src/jaegertracing/thrift/tutorial/js/build.xml | 92 | ||||
-rw-r--r-- | src/jaegertracing/thrift/tutorial/js/src/Httpd.java | 299 | ||||
-rwxr-xr-x | src/jaegertracing/thrift/tutorial/js/tutorial.html | 109 |
4 files changed, 539 insertions, 0 deletions
diff --git a/src/jaegertracing/thrift/tutorial/js/Makefile.am b/src/jaegertracing/thrift/tutorial/js/Makefile.am new file mode 100755 index 000000000..3fe088842 --- /dev/null +++ b/src/jaegertracing/thrift/tutorial/js/Makefile.am @@ -0,0 +1,39 @@ +# +# 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. +# + +export CLASSPATH + +# Make sure this doesn't fail if ant is not configured. +clean-local: + ANT=$(ANT) ; if test -z "$$ANT" ; then ANT=: ; fi ; \ + $$ANT $(ANT_FLAGS) clean + +all-local: + $(ANT) $(ANT_FLAGS) compile + +check-local: all + $(ANT) $(ANT_FLAGS) test + +tutorialserver: all + $(ANT) $(ANT_FLAGS) tutorialserver + +EXTRA_DIST = \ + build.xml \ + src \ + tutorial.html diff --git a/src/jaegertracing/thrift/tutorial/js/build.xml b/src/jaegertracing/thrift/tutorial/js/build.xml new file mode 100644 index 000000000..03a6e7c64 --- /dev/null +++ b/src/jaegertracing/thrift/tutorial/js/build.xml @@ -0,0 +1,92 @@ +<!-- + 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. +--> +<project name="tutorial" default="test" basedir="."> + + <description>Thrift JavaScript Tutorial</description> + + <property name="src" location="src" /> + <property name="javasrc" location="../java/src" /> + <property name="gen" location="../java/gen-java" /> + <property name="build" location="build" /> + + <!-- the root directory, where you unpack thrift distibution (e.g. thrift-0.x.x.tar.gz) --> + <property name="thrift.dir" location="../../" /> + <!-- JavaScript tutorial depends on the java tutorial thrift handler and server infrastructure --> + <property name="thrift.java.dir" location="${thrift.dir}/lib/java" /> + + <path id="libs.classpath"> + <fileset dir="${thrift.java.dir}/build/libs"> + <include name="libthrift*.jar" /> + <exclude name="libthrift*test.jar" /> + <exclude name="libthrift*javadoc.jar" /> + <exclude name="libthrift*sources.jar" /> + </fileset> + <fileset dir="${thrift.java.dir}/build/deps"> + <include name="*.jar" /> + </fileset> + </path> + <path id="build.classpath"> + <path refid="libs.classpath" /> + <pathelement path="${gen}" /> + <pathelement path="${build}" /> + </path> + + <target name="init"> + <tstamp /> + <mkdir dir="${build}"/> + </target> + + <target name="compile" depends="init"> + <javac compiler="modern" includeantruntime="false" srcdir="${gen}" destdir="${build}" classpathref="libs.classpath" /> + <javac compiler="modern" includeantruntime="false" srcdir="${javasrc}" destdir="${build}" classpathref="build.classpath"> + <exclude name="JavaClient.java"/> + <exclude name="JavaServer.java"/> + <include name="CalculatorHandler.java"/> + </javac> + <javac compiler="modern" includeantruntime="false" srcdir="${src}" destdir="${build}" classpathref="build.classpath"> + <compilerarg value="-Xlint:all"/> + </javac> + </target> + + <target name="test" depends="tutorial" /> + + <target name="tutorial" depends="compile"> + <jar jarfile="tutorial-js.jar" basedir="${build}"/> + </target> + + <target name="tutorialserver" description="run the test server" depends="tutorial, generate"> + <java classname="Httpd" fork="true" + classpathref="build.classpath" failonerror="true"> + <arg value="../../" /> + </java> + </target> + + <target name="generate"> + <exec executable="../../compiler/cpp/thrift" failonerror="true"> + <arg line="--gen js -r ../tutorial.thrift"/> + </exec> + </target> + + <target name="clean"> + <delete dir="${build}" /> + <delete dir="gen-js"/> + <delete file="tutorial-js.jar" /> + </target> + +</project> diff --git a/src/jaegertracing/thrift/tutorial/js/src/Httpd.java b/src/jaegertracing/thrift/tutorial/js/src/Httpd.java new file mode 100644 index 000000000..4985471a7 --- /dev/null +++ b/src/jaegertracing/thrift/tutorial/js/src/Httpd.java @@ -0,0 +1,299 @@ +/* + * ==================================================================== + * 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/>. + * + */ + +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; + +// Generated code +import tutorial.*; +import shared.*; + +import java.util.HashMap; + +/** + * 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("/thrift/service/tutorial/")) { + 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, "UTF-8")); + 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 Calculator.Processor(new CalculatorHandler()); + 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/tutorial/js/tutorial.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/src/jaegertracing/thrift/tutorial/js/tutorial.html b/src/jaegertracing/thrift/tutorial/js/tutorial.html new file mode 100755 index 000000000..d020bed37 --- /dev/null +++ b/src/jaegertracing/thrift/tutorial/js/tutorial.html @@ -0,0 +1,109 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<!-- + 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. +--> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> + <title>Thrift Javascript Bindings - Tutorial Example</title> + + <script src="../../lib/js/src/thrift.js" type="text/javascript"></script> + <script src="gen-js/tutorial_types.js" type="text/javascript"></script> + <script src="gen-js/shared_types.js" type="text/javascript"></script> + <script src="gen-js/SharedService.js" type="text/javascript"></script> + <script src="gen-js/Calculator.js" type="text/javascript"></script> + + <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> + + + <script type="text/javascript" charset="utf-8"> + //<![CDATA[ + $(document).ready(function(){ + // remove pseudo child required for valid xhtml strict + $("#op").children().remove(); + // add operations to it's dropdown menu + $.each(Operation, function(key, value) { + $('#op').append($("<option></option>").attr("value",value).text(key)); + }); + + $('table.calculator').attr('width', 500); + }); + + function calc() { + var transport = new Thrift.Transport("/thrift/service/tutorial/"); + var protocol = new Thrift.Protocol(transport); + var client = new CalculatorClient(protocol); + + var work = new Work(); + work.num1 = $("#num1").val(); + work.num2 = $("#num2").val(); + work.op = $("#op").val(); + + try { + result = client.calculate(1, work); + $('#result').val(result); + $('#result').css('color', 'black'); + } catch(ouch){ + $('#result').val(ouch.why); + $('#result').css('color', 'red'); + } + } + + function auto_calc() { + if ($('#autoupdate:checked').val() !== undefined) { + calc(); + } + } + //]]> + </script> + +</head> +<body> + <h2>Thrift Javascript Bindings</h2> + <form action=""> + <table class="calculator"> + <tr> + <td>num1</td> + <td><input type="text" id="num1" value="20" onkeyup="javascript:auto_calc();"/></td> + </tr> + <tr> + <td>Operation</td> + <td><select id="op" size="1" onchange="javascript:auto_calc();"><option></option></select></td> + </tr> + <tr> + <td>num2</td> + <td><input type="text" id="num2" value="5" onkeyup="javascript:auto_calc();"/></td></tr> + <tr> + <td>result</td> + <td><input type="text" id="result" value=""/></td></tr> + <tr> + <td><input type="checkbox" id="autoupdate" checked="checked"/>autoupdate</td> + <td><input type="button" id="calculate" value="calculate" onclick="javascript:calc();"/></td> + </tr> + </table> + </form> + + <p>This Java Script example uses <a href="https://github.com/apache/thrift/blob/master/tutorial/tutorial.thrift">tutorial.thrift</a> and a Thrift server using JSON protocol and HTTP transport. + </p> + <p> + <a href="http://validator.w3.org/check/referer"><img + src="http://www.w3.org/Icons/valid-xhtml10" + alt="Valid XHTML 1.0!" height="31" width="88" /></a> + </p> +</body> +</html> |