From ba286797752851e4d4426661fffda2f12feb7920 Mon Sep 17 00:00:00 2001 From: Trustin Lee Date: Thu, 22 May 2014 17:00:32 +0900 Subject: [PATCH] Clean up the examples Motivation: The examples have not been updated since long time ago, showing various issues fixed in this commit. Modifications: - Overall simplification to reduce LoC - Use system properties to get options instead of parsing args. - Minimize option validation - Just use System.out/err instead of Logger - Do not pass config as parameters - just access it directly - Move the main logic to main(String[]) instead of creating a new instance meaninglessly - Update netty-build-21 to make checkstyle not complain - Remove 'throws Exception' clause if possible - Line wrap at 120 (previously at 80) - Add an option to enable SSL for most examples - Use ChannelFuture.sync() instead of await() - Use System.out for the actual result. Use System.err otherwise. - Delete examples that are not very useful: - websocket/html5 - websocketx/sslserver - localecho/multithreaded - Add run-example.sh which simplifies launching an example from command line Result: Shorter and simpler examples. A user can focus more on what it actually does than miscellaneous stuff. A user can launch an example very easily. --- pom.xml | 16 +- run-example.sh | 87 + .../netty/example/discard/DiscardClient.java | 86 +- .../example/discard/DiscardClientHandler.java | 21 +- .../netty/example/discard/DiscardServer.java | 50 +- .../example/discard/DiscardServerHandler.java | 13 +- .../jboss/netty/example/echo/EchoClient.java | 89 +- .../netty/example/echo/EchoClientHandler.java | 31 +- .../jboss/netty/example/echo/EchoServer.java | 54 +- .../netty/example/echo/EchoServerHandler.java | 20 +- .../example/factorial/BigIntegerDecoder.java | 10 +- .../example/factorial/FactorialClient.java | 81 +- .../factorial/FactorialClientHandler.java | 53 +- .../FactorialClientPipelineFactory.java | 23 +- .../example/factorial/FactorialServer.java | 40 +- .../factorial/FactorialServerHandler.java | 34 +- .../FactorialServerPipelineFactory.java | 20 +- .../example/factorial/NumberEncoder.java | 7 +- .../http/file/HttpStaticFileServer.java | 43 +- .../file/HttpStaticFileServerHandler.java | 35 +- .../HttpStaticFileServerPipelineFactory.java | 2 +- .../http/helloworld/HttpHelloWorldServer.java | 35 +- .../HttpHelloWorldServerHandler.java | 5 +- .../HttpHelloWorldServerPipelineFactory.java | 18 +- .../example/http/snoop/HttpSnoopClient.java | 84 +- .../http/snoop/HttpSnoopClientHandler.java | 26 +- .../snoop/HttpSnoopClientPipelineFactory.java | 10 +- .../example/http/snoop/HttpSnoopServer.java | 35 +- .../http/snoop/HttpSnoopServerHandler.java | 25 +- .../snoop/HttpSnoopServerPipelineFactory.java | 22 +- .../tunnel/HttpTunnelingClientExample.java | 131 +- .../example/http/upload/HttpUploadClient.java | 208 +- .../http/upload/HttpUploadClientHandler.java | 28 +- .../HttpUploadClientPipelineFactory.java | 13 +- .../example/http/upload/HttpUploadServer.java | 43 +- .../http/upload/HttpUploadServerHandler.java | 201 +- .../HttpUploadServerPipelineFactory.java | 2 +- .../websocketx/autobahn/AutobahnServer.java | 33 +- .../autobahn/AutobahnServerHandler.java | 24 +- .../AutobahnServerPipelineFactory.java | 6 +- .../websocketx/client/WebSocketClient.java | 97 +- .../client/WebSocketClientHandler.java | 26 +- .../html5/CustomTextFrameHandler.java | 33 - .../websocketx/html5/WebSocketServer.java | 79 - .../html5/WebSocketServerPipelineFactory.java | 38 - .../websocketx/server/WebSocketServer.java | 42 +- .../server/WebSocketServerHandler.java | 18 +- .../WebSocketServerPipelineFactory.java | 19 +- .../sslserver/WebSocketSslServer.java | 87 - .../sslserver/WebSocketSslServerHandler.java | 152 - .../WebSocketSslServerPipelineFactory.java | 46 - .../WebSocketSslServerSslContext.java | 102 - .../websocketx/sslserver/package-info.java | 36 - .../netty/example/local/LocalExample.java | 131 +- .../local/LocalExampleMultithreaded.java | 105 - .../local/LocalServerPipelineFactory.java | 78 - .../example/localtime/LocalTimeClient.java | 115 +- .../localtime/LocalTimeClientHandler.java | 27 +- .../LocalTimeClientPipelineFactory.java | 16 +- .../example/localtime/LocalTimeProtocol.java | 2740 ++++++++++------- .../example/localtime/LocalTimeServer.java | 40 +- .../localtime/LocalTimeServerHandler.java | 24 +- .../LocalTimeServerPipelineFactory.java | 16 +- .../example/objectecho/ObjectEchoClient.java | 87 +- .../objectecho/ObjectEchoClientHandler.java | 35 +- .../example/objectecho/ObjectEchoServer.java | 49 +- .../objectecho/ObjectEchoServerHandler.java | 28 +- .../PortUnificationServer.java | 34 +- .../PortUnificationServerHandler.java | 2 +- .../netty/example/proxy/HexDumpProxy.java | 54 +- .../proxy/HexDumpProxyInboundHandler.java | 46 +- .../proxy/HexDumpProxyPipelineFactory.java | 15 +- .../example/qotm/QuoteOfTheMomentClient.java | 121 +- .../qotm/QuoteOfTheMomentClientHandler.java | 6 +- .../example/qotm/QuoteOfTheMomentServer.java | 38 +- .../qotm/QuoteOfTheMomentServerHandler.java | 10 +- .../example/securechat/SecureChatClient.java | 116 +- .../securechat/SecureChatClientHandler.java | 34 +- .../SecureChatClientPipelineFactory.java | 7 +- .../example/securechat/SecureChatServer.java | 28 +- .../securechat/SecureChatServerHandler.java | 34 +- .../SecureChatServerPipelineFactory.java | 5 +- .../netty/example/telnet/TelnetClient.java | 128 +- .../example/telnet/TelnetClientHandler.java | 22 +- .../telnet/TelnetClientPipelineFactory.java | 20 +- .../netty/example/telnet/TelnetServer.java | 40 +- .../example/telnet/TelnetServerHandler.java | 33 +- .../telnet/TelnetServerPipelineFactory.java | 20 +- .../netty/example/uptime/UptimeClient.java | 55 +- .../example/uptime/UptimeClientHandler.java | 12 +- .../resources/websocketx/html5/css/socket.css | 4 - .../resources/websocketx/html5/js/socket.js | 53 - .../resources/websocketx/html5/websocket.html | 18 - 93 files changed, 3138 insertions(+), 3847 deletions(-) create mode 100755 run-example.sh delete mode 100644 src/main/java/org/jboss/netty/example/http/websocketx/html5/CustomTextFrameHandler.java delete mode 100644 src/main/java/org/jboss/netty/example/http/websocketx/html5/WebSocketServer.java delete mode 100644 src/main/java/org/jboss/netty/example/http/websocketx/html5/WebSocketServerPipelineFactory.java delete mode 100644 src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServer.java delete mode 100644 src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServerHandler.java delete mode 100644 src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServerPipelineFactory.java delete mode 100644 src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServerSslContext.java delete mode 100644 src/main/java/org/jboss/netty/example/http/websocketx/sslserver/package-info.java delete mode 100644 src/main/java/org/jboss/netty/example/local/LocalExampleMultithreaded.java delete mode 100644 src/main/java/org/jboss/netty/example/local/LocalServerPipelineFactory.java delete mode 100644 src/test/resources/websocketx/html5/css/socket.css delete mode 100644 src/test/resources/websocketx/html5/js/socket.js delete mode 100644 src/test/resources/websocketx/html5/websocket.html diff --git a/pom.xml b/pom.xml index 6b6ff9dfa0..555b1814db 100644 --- a/pom.xml +++ b/pom.xml @@ -726,10 +726,24 @@ ${project.groupId} netty-build - 20 + 21 + + org.codehaus.mojo + exec-maven-plugin + 1.3 + + ${java.home}/bin/java + + -classpath %classpath + ${argLine.example} + ${exampleClass} + + runtime + + diff --git a/run-example.sh b/run-example.sh new file mode 100755 index 0000000000..5912592fb3 --- /dev/null +++ b/run-example.sh @@ -0,0 +1,87 @@ +#!/bin/bash -e +EXAMPLE_MAP=( + 'discard-client:org.jboss.netty.example.discard.DiscardClient' + 'discard-server:org.jboss.netty.example.discard.DiscardServer' + 'echo-client:org.jboss.netty.example.echo.EchoClient' + 'echo-server:org.jboss.netty.example.echo.EchoServer' + 'factorial-client:org.jboss.netty.example.factorial.FactorialClient' + 'factorial-server:org.jboss.netty.example.factorial.FactorialServer' + 'http-snoop-client:org.jboss.netty.example.http.snoop.HttpSnoopClient' + 'http-snoop-server:org.jboss.netty.example.http.snoop.HttpSnoopServer' + 'http-file-server:org.jboss.netty.example.http.file.HttpStaticFileServer' + 'http-helloworld-server:org.jboss.netty.example.http.helloworld.HttpHelloWorldServer' + 'http-upload-client:org.jboss.netty.example.http.upload.HttpUploadClient' + 'http-upload-server:org.jboss.netty.example.http.upload.HttpUploadServer' + 'websocket-client:org.jboss.netty.example.websocketx.client.WebSocketClient' + 'websocket-server:org.jboss.netty.example.websocketx.server.WebSocketServer' + 'localtime-client:org.jboss.netty.example.localtime.LocalTimeClient' + 'localtime-server:org.jboss.netty.example.localtime.LocalTimeServer' + 'objectecho-client:org.jboss.netty.example.objectecho.ObjectEchoClient' + 'objectecho-server:org.jboss.netty.example.objectecho.ObjectEchoServer' + 'quote-client:org.jboss.netty.example.qotm.QuoteOfTheMomentClient' + 'quote-server:org.jboss.netty.example.qotm.QuoteOfTheMomentServer' + 'securechat-client:org.jboss.netty.example.securechat.SecureChatClient' + 'securechat-server:org.jboss.netty.example.securechat.SecureChatServer' + 'telnet-client:org.jboss.netty.example.telnet.TelnetClient' + 'telnet-server:org.jboss.netty.example.telnet.TelnetServer' + 'proxy-server:org.jboss.netty.example.proxy.HexDumpProxy' + 'uptime-client:org.jboss.netty.example.uptime.UptimeClient' + 'local-transport:org.jboss.netty.example.local.LocalExample' +) + +EXAMPLE='' +EXAMPLE_CLASS='' +EXAMPLE_ARGS='-D_' +I=0 + +while [[ $# -gt 0 ]]; do + ARG="$1" + shift + if [[ "$ARG" =~ (^-.+) ]]; then + EXAMPLE_ARGS="$EXAMPLE_ARGS $ARG" + else + EXAMPLE="$ARG" + for E in "${EXAMPLE_MAP[@]}"; do + KEY="${E%%:*}" + VAL="${E##*:}" + if [[ "$EXAMPLE" == "$KEY" ]]; then + EXAMPLE_CLASS="$VAL" + break + fi + done + break + fi +done + +if [[ -z "$EXAMPLE" ]] || [[ -z "$EXAMPLE_CLASS" ]] || [[ $# -ne 0 ]]; then + echo " Usage: $0 [-D[=] ...] " >&2 + echo "Example: $0 -Dport=8443 -Dssl http-server" >&2 + echo " $0 -Dhost=127.0.0.1 -Dport=8009 echo-client" >&2 + echo >&2 + echo "Available examples:" >&2 + echo >&2 + I=0 + for E in "${EXAMPLE_MAP[@]}"; do + if [[ $I -eq 0 ]]; then + echo -n ' ' + fi + + printf '%-24s' "${E%%:*}" + ((I++)) || true + + if [[ $I -eq 2 ]]; then + I=0 + echo + fi + done >&2 + if [[ $I -ne 0 ]]; then + echo >&2 + fi + echo >&2 + exit 1 +fi + +cd "`dirname "$0"`" +echo "[INFO] Running: $EXAMPLE ($EXAMPLE_CLASS $EXAMPLE_ARGS)" +exec mvn -nsu compile exec:exec -DargLine.example="$EXAMPLE_ARGS" -DexampleClass="$EXAMPLE_CLASS" + diff --git a/src/main/java/org/jboss/netty/example/discard/DiscardClient.java b/src/main/java/org/jboss/netty/example/discard/DiscardClient.java index ab3f08c1c0..4e8581e021 100644 --- a/src/main/java/org/jboss/netty/example/discard/DiscardClient.java +++ b/src/main/java/org/jboss/netty/example/discard/DiscardClient.java @@ -15,75 +15,63 @@ */ package org.jboss.netty.example.discard; -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.InsecureTrustManagerFactory; + +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; /** * Keeps sending random data to the specified address. */ -public class DiscardClient { +public final class DiscardClient { - private final String host; - private final int port; - private final int firstMessageSize; + static final boolean SSL = System.getProperty("ssl") != null; + static final String HOST = System.getProperty("host", "127.0.0.1"); + static final int PORT = Integer.parseInt(System.getProperty("port", "8009")); + static final int SIZE = Integer.parseInt(System.getProperty("size", "256")); - public DiscardClient(String host, int port, int firstMessageSize) { - this.host = host; - this.port = port; - this.firstMessageSize = firstMessageSize; - } + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); + } else { + sslCtx = null; + } - public void run() { - // Configure the client. + // Configure the bootstrap. ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); - // Set up the pipeline factory. - bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - public ChannelPipeline getPipeline() throws Exception { - return Channels.pipeline( - new DiscardClientHandler(firstMessageSize)); - } - }); + try { + bootstrap.setPipelineFactory(new ChannelPipelineFactory() { + public ChannelPipeline getPipeline() { + ChannelPipeline p = Channels.pipeline(); + if (sslCtx != null) { + p.addLast("ssl", sslCtx.newHandler(HOST, PORT)); + } + p.addLast("discard", new DiscardClientHandler()); + return p; + } + }); - // Start the connection attempt. - ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); + // Start the connection attempt. + ChannelFuture future = bootstrap.connect(new InetSocketAddress(HOST, PORT)); - // Wait until the connection is closed or the connection attempt fails. - future.getChannel().getCloseFuture().awaitUninterruptibly(); - - // Shut down thread pools to exit. - bootstrap.releaseExternalResources(); - } - - public static void main(String[] args) throws Exception { - // Print usage if no argument is specified. - if (args.length < 2 || args.length > 3) { - System.err.println( - "Usage: " + DiscardClient.class.getSimpleName() + - " []"); - return; + // Wait until the connection is closed or the connection attempt fails. + future.getChannel().getCloseFuture().sync(); + } finally { + // Shut down thread pools to exit. + bootstrap.releaseExternalResources(); } - - // Parse options. - final String host = args[0]; - final int port = Integer.parseInt(args[1]); - final int firstMessageSize; - if (args.length == 3) { - firstMessageSize = Integer.parseInt(args[2]); - } else { - firstMessageSize = 256; - } - - new DiscardClient(host, port, firstMessageSize).run(); } } diff --git a/src/main/java/org/jboss/netty/example/discard/DiscardClientHandler.java b/src/main/java/org/jboss/netty/example/discard/DiscardClientHandler.java index 8c4bad90e7..3c76f1c224 100644 --- a/src/main/java/org/jboss/netty/example/discard/DiscardClientHandler.java +++ b/src/main/java/org/jboss/netty/example/discard/DiscardClientHandler.java @@ -15,9 +15,6 @@ */ package org.jboss.netty.example.discard; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; @@ -35,18 +32,11 @@ import org.jboss.netty.channel.WriteCompletionEvent; */ public class DiscardClientHandler extends SimpleChannelUpstreamHandler { - private static final Logger logger = Logger.getLogger( - DiscardClientHandler.class.getName()); - private long transferredBytes; private final byte[] content; - public DiscardClientHandler(int messageSize) { - if (messageSize <= 0) { - throw new IllegalArgumentException( - "messageSize: " + messageSize); - } - content = new byte[messageSize]; + public DiscardClientHandler() { + content = new byte[DiscardClient.SIZE]; } public long getTransferredBytes() { @@ -57,7 +47,7 @@ public class DiscardClientHandler extends SimpleChannelUpstreamHandler { public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { if (((ChannelStateEvent) e).getState() != ChannelState.INTEREST_OPS) { - logger.info(e.toString()); + System.err.println(e); } } @@ -90,10 +80,7 @@ public class DiscardClientHandler extends SimpleChannelUpstreamHandler { @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { // Close the connection when an exception is raised. - logger.log( - Level.WARNING, - "Unexpected exception from downstream.", - e.getCause()); + e.getCause().printStackTrace(); e.getChannel().close(); } diff --git a/src/main/java/org/jboss/netty/example/discard/DiscardServer.java b/src/main/java/org/jboss/netty/example/discard/DiscardServer.java index 4d731d09dd..0f2872d318 100644 --- a/src/main/java/org/jboss/netty/example/discard/DiscardServer.java +++ b/src/main/java/org/jboss/netty/example/discard/DiscardServer.java @@ -15,51 +15,53 @@ */ package org.jboss.netty.example.discard; -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.SelfSignedCertificate; + +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; /** * Discards any incoming data. */ -public class DiscardServer { +public final class DiscardServer { - private final int port; + static final boolean SSL = System.getProperty("ssl") != null; + static final int PORT = Integer.parseInt(System.getProperty("port", "8009")); - public DiscardServer(int port) { - this.port = port; - } + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + SelfSignedCertificate ssc = new SelfSignedCertificate(); + sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); + } else { + sslCtx = null; + } - public void run() { - // Configure the server. + // Configure the bootstrap. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); - // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - public ChannelPipeline getPipeline() throws Exception { - return Channels.pipeline(new DiscardServerHandler()); + public ChannelPipeline getPipeline() { + ChannelPipeline p = Channels.pipeline(); + if (sslCtx != null) { + p.addLast("ssl", sslCtx.newHandler()); + } + p.addLast("discard", new DiscardServerHandler()); + return p; } }); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(port)); - } - - public static void main(String[] args) throws Exception { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8080; - } - new DiscardServer(port).run(); + bootstrap.bind(new InetSocketAddress(PORT)); } } diff --git a/src/main/java/org/jboss/netty/example/discard/DiscardServerHandler.java b/src/main/java/org/jboss/netty/example/discard/DiscardServerHandler.java index c7e787ab5d..f5b1e6deeb 100644 --- a/src/main/java/org/jboss/netty/example/discard/DiscardServerHandler.java +++ b/src/main/java/org/jboss/netty/example/discard/DiscardServerHandler.java @@ -15,9 +15,6 @@ */ package org.jboss.netty.example.discard; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; @@ -31,9 +28,6 @@ import org.jboss.netty.channel.SimpleChannelUpstreamHandler; */ public class DiscardServerHandler extends SimpleChannelUpstreamHandler { - private static final Logger logger = Logger.getLogger( - DiscardServerHandler.class.getName()); - private long transferredBytes; public long getTransferredBytes() { @@ -43,7 +37,7 @@ public class DiscardServerHandler extends SimpleChannelUpstreamHandler { @Override public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { - logger.info(e.toString()); + System.err.println(e); } // Let SimpleChannelHandler call actual event handler methods below. @@ -59,10 +53,7 @@ public class DiscardServerHandler extends SimpleChannelUpstreamHandler { @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { // Close the connection when an exception is raised. - logger.log( - Level.WARNING, - "Unexpected exception from downstream.", - e.getCause()); + e.getCause().printStackTrace(); e.getChannel().close(); } } diff --git a/src/main/java/org/jboss/netty/example/echo/EchoClient.java b/src/main/java/org/jboss/netty/example/echo/EchoClient.java index 148b36df3a..090c12eaf3 100644 --- a/src/main/java/org/jboss/netty/example/echo/EchoClient.java +++ b/src/main/java/org/jboss/netty/example/echo/EchoClient.java @@ -15,15 +15,17 @@ */ package org.jboss.netty.example.echo; -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.InsecureTrustManagerFactory; + +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; /** * Sends one message when a connection is open and echoes back any received @@ -31,62 +33,51 @@ import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; * traffic between the echo client and server by sending the first message to * the server. */ -public class EchoClient { +public final class EchoClient { - private final String host; - private final int port; - private final int firstMessageSize; + static final boolean SSL = System.getProperty("ssl") != null; + static final String HOST = System.getProperty("host", "127.0.0.1"); + static final int PORT = Integer.parseInt(System.getProperty("port", "8007")); + static final int SIZE = Integer.parseInt(System.getProperty("size", "256")); - public EchoClient(String host, int port, int firstMessageSize) { - this.host = host; - this.port = port; - this.firstMessageSize = firstMessageSize; - } + public static void main(String[] args) throws Exception { + // Configure SSL.git + final SslContext sslCtx; + if (SSL) { + sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); + } else { + sslCtx = null; + } - public void run() { - // Configure the client. + // Configure the bootstrap. ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); - // Set up the pipeline factory. - bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - public ChannelPipeline getPipeline() throws Exception { - return Channels.pipeline( - new EchoClientHandler(firstMessageSize)); - } - }); + try { + bootstrap.setPipelineFactory(new ChannelPipelineFactory() { + public ChannelPipeline getPipeline() { + ChannelPipeline p = Channels.pipeline(); + if (sslCtx != null) { + p.addLast("ssl", sslCtx.newHandler(HOST, PORT)); + } + p.addLast("echo", new EchoClientHandler()); + return p; + } + }); + bootstrap.setOption("tcpNoDelay", true); + bootstrap.setOption("receiveBufferSize", 1048576); + bootstrap.setOption("sendBufferSize", 1048576); - // Start the connection attempt. - ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); + // Start the connection attempt. + ChannelFuture future = bootstrap.connect(new InetSocketAddress(HOST, PORT)); - // Wait until the connection is closed or the connection attempt fails. - future.getChannel().getCloseFuture().awaitUninterruptibly(); - - // Shut down thread pools to exit. - bootstrap.releaseExternalResources(); - } - - public static void main(String[] args) throws Exception { - // Print usage if no argument is specified. - if (args.length < 2 || args.length > 3) { - System.err.println( - "Usage: " + EchoClient.class.getSimpleName() + - " []"); - return; + // Wait until the connection is closed or the connection attempt fails. + future.getChannel().getCloseFuture().sync(); + } finally { + // Shut down thread pools to exit. + bootstrap.releaseExternalResources(); } - - // Parse options. - final String host = args[0]; - final int port = Integer.parseInt(args[1]); - final int firstMessageSize; - if (args.length == 3) { - firstMessageSize = Integer.parseInt(args[2]); - } else { - firstMessageSize = 256; - } - - new EchoClient(host, port, firstMessageSize).run(); } } diff --git a/src/main/java/org/jboss/netty/example/echo/EchoClientHandler.java b/src/main/java/org/jboss/netty/example/echo/EchoClientHandler.java index 216a4617bd..27f7835850 100644 --- a/src/main/java/org/jboss/netty/example/echo/EchoClientHandler.java +++ b/src/main/java/org/jboss/netty/example/echo/EchoClientHandler.java @@ -15,10 +15,6 @@ */ package org.jboss.netty.example.echo; -import java.util.concurrent.atomic.AtomicLong; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.ChannelHandlerContext; @@ -27,6 +23,8 @@ import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; +import java.util.concurrent.atomic.AtomicLong; + /** * Handler implementation for the echo client. It initiates the ping-pong * traffic between the echo client and server by sending the first message to @@ -34,21 +32,14 @@ import org.jboss.netty.channel.SimpleChannelUpstreamHandler; */ public class EchoClientHandler extends SimpleChannelUpstreamHandler { - private static final Logger logger = Logger.getLogger( - EchoClientHandler.class.getName()); - private final ChannelBuffer firstMessage; private final AtomicLong transferredBytes = new AtomicLong(); /** * Creates a client-side handler. */ - public EchoClientHandler(int firstMessageSize) { - if (firstMessageSize <= 0) { - throw new IllegalArgumentException( - "firstMessageSize: " + firstMessageSize); - } - firstMessage = ChannelBuffers.buffer(firstMessageSize); + public EchoClientHandler() { + firstMessage = ChannelBuffers.buffer(EchoClient.SIZE); for (int i = 0; i < firstMessage.capacity(); i ++) { firstMessage.writeByte((byte) i); } @@ -59,29 +50,23 @@ public class EchoClientHandler extends SimpleChannelUpstreamHandler { } @Override - public void channelConnected( - ChannelHandlerContext ctx, ChannelStateEvent e) { + public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) { // Send the first message. Server will not send anything here // because the firstMessage's capacity is 0. e.getChannel().write(firstMessage); } @Override - public void messageReceived( - ChannelHandlerContext ctx, MessageEvent e) { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { // Send back the received message to the remote peer. transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes()); e.getChannel().write(e.getMessage()); } @Override - public void exceptionCaught( - ChannelHandlerContext ctx, ExceptionEvent e) { + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { // Close the connection when an exception is raised. - logger.log( - Level.WARNING, - "Unexpected exception from downstream.", - e.getCause()); + e.getCause().printStackTrace(); e.getChannel().close(); } } diff --git a/src/main/java/org/jboss/netty/example/echo/EchoServer.java b/src/main/java/org/jboss/netty/example/echo/EchoServer.java index d477c0cb91..ed56e4b3eb 100644 --- a/src/main/java/org/jboss/netty/example/echo/EchoServer.java +++ b/src/main/java/org/jboss/netty/example/echo/EchoServer.java @@ -15,51 +15,57 @@ */ package org.jboss.netty.example.echo; -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.SelfSignedCertificate; + +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; /** * Echoes back any received data from a client. */ -public class EchoServer { +public final class EchoServer { - private final int port; + static final boolean SSL = System.getProperty("ssl") != null; + static final int PORT = Integer.parseInt(System.getProperty("port", "8007")); - public EchoServer(int port) { - this.port = port; - } + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + SelfSignedCertificate ssc = new SelfSignedCertificate(); + sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); + } else { + sslCtx = null; + } - public void run() { - // Configure the server. + // Configure the bootstrap. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); - // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - public ChannelPipeline getPipeline() throws Exception { - return Channels.pipeline(new EchoServerHandler()); + public ChannelPipeline getPipeline() { + ChannelPipeline p = Channels.pipeline(); + if (sslCtx != null) { + p.addLast("ssl", sslCtx.newHandler()); + } + p.addLast("echo", new EchoServerHandler()); + return p; } }); - // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(port)); - } + bootstrap.setOption("child.tcpNoDelay", true); + bootstrap.setOption("child.receiveBufferSize", 1048576); + bootstrap.setOption("child.sendBufferSize", 1048576); - public static void main(String[] args) throws Exception { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8080; - } - new EchoServer(port).run(); + // Bind and start to accept incoming connections. + bootstrap.bind(new InetSocketAddress(PORT)); } } diff --git a/src/main/java/org/jboss/netty/example/echo/EchoServerHandler.java b/src/main/java/org/jboss/netty/example/echo/EchoServerHandler.java index 389272d103..5f276176f5 100644 --- a/src/main/java/org/jboss/netty/example/echo/EchoServerHandler.java +++ b/src/main/java/org/jboss/netty/example/echo/EchoServerHandler.java @@ -15,24 +15,19 @@ */ package org.jboss.netty.example.echo; -import java.util.concurrent.atomic.AtomicLong; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; +import java.util.concurrent.atomic.AtomicLong; + /** * Handler implementation for the echo server. */ public class EchoServerHandler extends SimpleChannelUpstreamHandler { - private static final Logger logger = Logger.getLogger( - EchoServerHandler.class.getName()); - private final AtomicLong transferredBytes = new AtomicLong(); public long getTransferredBytes() { @@ -40,21 +35,16 @@ public class EchoServerHandler extends SimpleChannelUpstreamHandler { } @Override - public void messageReceived( - ChannelHandlerContext ctx, MessageEvent e) { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { // Send back the received message to the remote peer. transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes()); e.getChannel().write(e.getMessage()); } @Override - public void exceptionCaught( - ChannelHandlerContext ctx, ExceptionEvent e) { + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { // Close the connection when an exception is raised. - logger.log( - Level.WARNING, - "Unexpected exception from downstream.", - e.getCause()); + e.getCause().printStackTrace(); e.getChannel().close(); } } diff --git a/src/main/java/org/jboss/netty/example/factorial/BigIntegerDecoder.java b/src/main/java/org/jboss/netty/example/factorial/BigIntegerDecoder.java index 6e044fa879..00f15d72b1 100644 --- a/src/main/java/org/jboss/netty/example/factorial/BigIntegerDecoder.java +++ b/src/main/java/org/jboss/netty/example/factorial/BigIntegerDecoder.java @@ -15,14 +15,14 @@ */ package org.jboss.netty.example.factorial; -import java.math.BigInteger; - import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.frame.CorruptedFrameException; import org.jboss.netty.handler.codec.frame.FrameDecoder; +import java.math.BigInteger; + /** * Decodes the binary representation of a {@link BigInteger} prepended * with a magic number ('F' or 0x46) and a 32-bit integer length prefix into a @@ -32,8 +32,7 @@ import org.jboss.netty.handler.codec.frame.FrameDecoder; public class BigIntegerDecoder extends FrameDecoder { @Override - protected Object decode( - ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { + protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { // Wait until the length prefix is available. if (buffer.readableBytes() < 5) { return null; @@ -45,8 +44,7 @@ public class BigIntegerDecoder extends FrameDecoder { int magicNumber = buffer.readUnsignedByte(); if (magicNumber != 'F') { buffer.resetReaderIndex(); - throw new CorruptedFrameException( - "Invalid magic number: " + magicNumber); + throw new CorruptedFrameException("Invalid magic number: " + magicNumber); } // Wait until the whole data is available. diff --git a/src/main/java/org/jboss/netty/example/factorial/FactorialClient.java b/src/main/java/org/jboss/netty/example/factorial/FactorialClient.java index 772eb79ed4..2fd2cf4c46 100644 --- a/src/main/java/org/jboss/netty/example/factorial/FactorialClient.java +++ b/src/main/java/org/jboss/netty/example/factorial/FactorialClient.java @@ -15,76 +15,59 @@ */ package org.jboss.netty.example.factorial; -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.InsecureTrustManagerFactory; + +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; /** * Sends a sequence of integers to a {@link FactorialServer} to calculate * the factorial of the specified integer. */ -public class FactorialClient { +public final class FactorialClient { - private final String host; - private final int port; - private final int count; + static final boolean SSL = System.getProperty("ssl") != null; + static final String HOST = System.getProperty("host", "127.0.0.1"); + static final int PORT = Integer.parseInt(System.getProperty("port", "8322")); + static final int COUNT = Integer.parseInt(System.getProperty("count", "1000")); - public FactorialClient(String host, int port, int count) { - this.host = host; - this.port = port; - this.count = count; - } + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); + } else { + sslCtx = null; + } - public void run() { - // Configure the client. + // Configure the bootstrap. ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); - // Set up the event pipeline factory. - bootstrap.setPipelineFactory(new FactorialClientPipelineFactory(count)); + try { + bootstrap.setPipelineFactory(new FactorialClientPipelineFactory(sslCtx)); - // Make a new connection. - ChannelFuture connectFuture = - bootstrap.connect(new InetSocketAddress(host, port)); + // Make a new connection. + ChannelFuture connectFuture = bootstrap.connect(new InetSocketAddress(HOST, PORT)); - // Wait until the connection is made successfully. - Channel channel = connectFuture.awaitUninterruptibly().getChannel(); + // Wait until the connection is made successfully. + Channel channel = connectFuture.sync().getChannel(); - // Get the handler instance to retrieve the answer. - FactorialClientHandler handler = - (FactorialClientHandler) channel.getPipeline().getLast(); + // Get the handler instance to retrieve the answer. + FactorialClientHandler handler = (FactorialClientHandler) channel.getPipeline().getLast(); - // Print out the answer. - System.err.format( - "Factorial of %,d is: %,d", count, handler.getFactorial()); - - // Shut down all thread pools to exit. - bootstrap.releaseExternalResources(); - } - - public static void main(String[] args) throws Exception { - // Print usage if no argument is specified. - if (args.length != 3) { - System.err.println( - "Usage: " + FactorialClient.class.getSimpleName() + - " "); - return; + // Print out the answer. + System.err.format("Factorial of %,d is: %,d", COUNT, handler.getFactorial()); + } finally { + // Shut down all thread pools to exit. + bootstrap.releaseExternalResources(); } - - // Parse options. - String host = args[0]; - int port = Integer.parseInt(args[1]); - int count = Integer.parseInt(args[2]); - if (count <= 0) { - throw new IllegalArgumentException("count must be a positive integer."); - } - - new FactorialClient(host, port, count).run(); } } diff --git a/src/main/java/org/jboss/netty/example/factorial/FactorialClientHandler.java b/src/main/java/org/jboss/netty/example/factorial/FactorialClientHandler.java index 05d78660d5..ad236595dd 100644 --- a/src/main/java/org/jboss/netty/example/factorial/FactorialClientHandler.java +++ b/src/main/java/org/jboss/netty/example/factorial/FactorialClientHandler.java @@ -15,12 +15,6 @@ */ package org.jboss.netty.example.factorial; -import java.math.BigInteger; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; @@ -31,6 +25,10 @@ import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; +import java.math.BigInteger; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + /** * Handler for a client-side channel. This handler maintains stateful * information which is specific to a certain channel using member variables. @@ -40,39 +38,32 @@ import org.jboss.netty.channel.SimpleChannelUpstreamHandler; */ public class FactorialClientHandler extends SimpleChannelUpstreamHandler { - private static final Logger logger = Logger.getLogger( - FactorialClientHandler.class.getName()); - // Stateful properties private int i = 1; private int receivedMessages; - private final int count; final BlockingQueue answer = new LinkedBlockingQueue(); - public FactorialClientHandler(int count) { - this.count = count; - } - public BigInteger getFactorial() { boolean interrupted = false; - for (;;) { - try { - BigInteger factorial = answer.take(); - if (interrupted) { - Thread.currentThread().interrupt(); + try { + for (;;) { + try { + return answer.take(); + } catch (InterruptedException ignore) { + interrupted = true; } - return factorial; - } catch (InterruptedException e) { - interrupted = true; + } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); } } } @Override - public void handleUpstream( - ChannelHandlerContext ctx, ChannelEvent e) throws Exception { + public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { - logger.info(e.toString()); + System.err.println(e); } super.handleUpstream(ctx, e); } @@ -91,7 +82,7 @@ public class FactorialClientHandler extends SimpleChannelUpstreamHandler { public void messageReceived( ChannelHandlerContext ctx, final MessageEvent e) { receivedMessages ++; - if (receivedMessages == count) { + if (receivedMessages == FactorialClient.COUNT) { // Offer the answer after closing the connection. e.getChannel().close().addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { @@ -103,19 +94,15 @@ public class FactorialClientHandler extends SimpleChannelUpstreamHandler { } @Override - public void exceptionCaught( - ChannelHandlerContext ctx, ExceptionEvent e) { - logger.log( - Level.WARNING, - "Unexpected exception from downstream.", - e.getCause()); + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { + e.getCause().printStackTrace(); e.getChannel().close(); } private void sendNumbers(ChannelStateEvent e) { Channel channel = e.getChannel(); while (channel.isWritable()) { - if (i <= count) { + if (i <= FactorialClient.COUNT) { channel.write(i); i ++; } else { diff --git a/src/main/java/org/jboss/netty/example/factorial/FactorialClientPipelineFactory.java b/src/main/java/org/jboss/netty/example/factorial/FactorialClientPipelineFactory.java index 4dc7515e99..b85d1b7699 100644 --- a/src/main/java/org/jboss/netty/example/factorial/FactorialClientPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/factorial/FactorialClientPipelineFactory.java @@ -15,29 +15,34 @@ */ package org.jboss.netty.example.factorial; -import static org.jboss.netty.channel.Channels.*; - import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.compression.ZlibDecoder; import org.jboss.netty.handler.codec.compression.ZlibEncoder; import org.jboss.netty.handler.codec.compression.ZlibWrapper; +import org.jboss.netty.handler.ssl.SslContext; + +import static org.jboss.netty.channel.Channels.*; /** * Creates a newly configured {@link ChannelPipeline} for a client-side channel. */ -public class FactorialClientPipelineFactory implements - ChannelPipelineFactory { +public class FactorialClientPipelineFactory implements ChannelPipelineFactory { - private final int count; + private final SslContext sslCtx; - public FactorialClientPipelineFactory(int count) { - this.count = count; + public FactorialClientPipelineFactory(SslContext sslCtx) { + this.sslCtx = sslCtx; } - public ChannelPipeline getPipeline() throws Exception { + public ChannelPipeline getPipeline() { ChannelPipeline pipeline = pipeline(); + // Enabls SSL if necessary. + if (sslCtx != null) { + pipeline.addLast("ssl", sslCtx.newHandler(FactorialClient.HOST, FactorialClient.PORT)); + } + // Enable stream compression (you can remove these two if unnecessary) pipeline.addLast("deflater", new ZlibEncoder(ZlibWrapper.GZIP)); pipeline.addLast("inflater", new ZlibDecoder(ZlibWrapper.GZIP)); @@ -47,7 +52,7 @@ public class FactorialClientPipelineFactory implements pipeline.addLast("encoder", new NumberEncoder()); // and then business logic. - pipeline.addLast("handler", new FactorialClientHandler(count)); + pipeline.addLast("handler", new FactorialClientHandler()); return pipeline; } diff --git a/src/main/java/org/jboss/netty/example/factorial/FactorialServer.java b/src/main/java/org/jboss/netty/example/factorial/FactorialServer.java index 8de92a02ff..795a5d5353 100644 --- a/src/main/java/org/jboss/netty/example/factorial/FactorialServer.java +++ b/src/main/java/org/jboss/netty/example/factorial/FactorialServer.java @@ -15,25 +15,33 @@ */ package org.jboss.netty.example.factorial; -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.SelfSignedCertificate; + +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; /** * Receives a sequence of integers from a {@link FactorialClient} to calculate * the factorial of the specified integer. */ -public class FactorialServer { +public final class FactorialServer { - private final int port; + static final boolean SSL = System.getProperty("ssl") != null; + static final int PORT = Integer.parseInt(System.getProperty("port", "8322")); - public FactorialServer(int port) { - this.port = port; - } + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + SelfSignedCertificate ssc = new SelfSignedCertificate(); + sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); + } else { + sslCtx = null; + } - public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -41,19 +49,9 @@ public class FactorialServer { Executors.newCachedThreadPool())); // Set up the event pipeline factory. - bootstrap.setPipelineFactory(new FactorialServerPipelineFactory()); + bootstrap.setPipelineFactory(new FactorialServerPipelineFactory(sslCtx)); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(port)); - } - - public static void main(String[] args) throws Exception { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8080; - } - new FactorialServer(port).run(); + bootstrap.bind(new InetSocketAddress(PORT)); } } diff --git a/src/main/java/org/jboss/netty/example/factorial/FactorialServerHandler.java b/src/main/java/org/jboss/netty/example/factorial/FactorialServerHandler.java index 5a8c1310fe..b95b43fa38 100644 --- a/src/main/java/org/jboss/netty/example/factorial/FactorialServerHandler.java +++ b/src/main/java/org/jboss/netty/example/factorial/FactorialServerHandler.java @@ -15,11 +15,6 @@ */ package org.jboss.netty.example.factorial; -import java.math.BigInteger; -import java.util.Formatter; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelStateEvent; @@ -27,6 +22,9 @@ import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; +import java.math.BigInteger; +import java.util.Formatter; + /** * Handler for a server-side channel. This handler maintains stateful * information which is specific to a certain channel using member variables. @@ -36,26 +34,20 @@ import org.jboss.netty.channel.SimpleChannelUpstreamHandler; */ public class FactorialServerHandler extends SimpleChannelUpstreamHandler { - private static final Logger logger = Logger.getLogger( - FactorialServerHandler.class.getName()); - // Stateful properties. private int lastMultiplier = 1; private BigInteger factorial = new BigInteger(new byte[] { 1 }); @Override - public void handleUpstream( - ChannelHandlerContext ctx, ChannelEvent e) throws Exception { + public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { - logger.info(e.toString()); + System.err.println(e); } super.handleUpstream(ctx, e); } @Override - public void messageReceived( - ChannelHandlerContext ctx, MessageEvent e) { - + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { // Calculate the cumulative factorial and send it to the client. BigInteger number; if (e.getMessage() instanceof BigInteger) { @@ -69,19 +61,13 @@ public class FactorialServerHandler extends SimpleChannelUpstreamHandler { } @Override - public void channelDisconnected(ChannelHandlerContext ctx, - ChannelStateEvent e) throws Exception { - logger.info(new Formatter().format( - "Factorial of %,d is: %,d", lastMultiplier, factorial).toString()); + public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) { + System.err.println(new Formatter().format("Factorial of %,d is: %,d", lastMultiplier, factorial)); } @Override - public void exceptionCaught( - ChannelHandlerContext ctx, ExceptionEvent e) { - logger.log( - Level.WARNING, - "Unexpected exception from downstream.", - e.getCause()); + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { + e.getCause().printStackTrace(); e.getChannel().close(); } } diff --git a/src/main/java/org/jboss/netty/example/factorial/FactorialServerPipelineFactory.java b/src/main/java/org/jboss/netty/example/factorial/FactorialServerPipelineFactory.java index 4a75879c4f..57406fb94f 100644 --- a/src/main/java/org/jboss/netty/example/factorial/FactorialServerPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/factorial/FactorialServerPipelineFactory.java @@ -15,23 +15,33 @@ */ package org.jboss.netty.example.factorial; -import static org.jboss.netty.channel.Channels.*; - import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.compression.ZlibDecoder; import org.jboss.netty.handler.codec.compression.ZlibEncoder; import org.jboss.netty.handler.codec.compression.ZlibWrapper; +import org.jboss.netty.handler.ssl.SslContext; + +import static org.jboss.netty.channel.Channels.*; /** * Creates a newly configured {@link ChannelPipeline} for a server-side channel. */ -public class FactorialServerPipelineFactory implements - ChannelPipelineFactory { +public class FactorialServerPipelineFactory implements ChannelPipelineFactory { - public ChannelPipeline getPipeline() throws Exception { + private final SslContext sslCtx; + + public FactorialServerPipelineFactory(SslContext sslCtx) { + this.sslCtx = sslCtx; + } + + public ChannelPipeline getPipeline() { ChannelPipeline pipeline = pipeline(); + if (sslCtx != null) { + pipeline.addLast("ssl", sslCtx.newHandler()); + } + // Enable stream compression (you can remove these two if unnecessary) pipeline.addLast("deflater", new ZlibEncoder(ZlibWrapper.GZIP)); pipeline.addLast("inflater", new ZlibDecoder(ZlibWrapper.GZIP)); diff --git a/src/main/java/org/jboss/netty/example/factorial/NumberEncoder.java b/src/main/java/org/jboss/netty/example/factorial/NumberEncoder.java index dfe48839b8..1de5b4dbc0 100644 --- a/src/main/java/org/jboss/netty/example/factorial/NumberEncoder.java +++ b/src/main/java/org/jboss/netty/example/factorial/NumberEncoder.java @@ -15,14 +15,14 @@ */ package org.jboss.netty.example.factorial; -import java.math.BigInteger; - import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; +import java.math.BigInteger; + /** * Encodes a {@link Number} into the binary representation prepended with * a magic number ('F' or 0x46) and a 32-bit length prefix. For example, 42 @@ -31,8 +31,7 @@ import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; public class NumberEncoder extends OneToOneEncoder { @Override - protected Object encode( - ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { + protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) { if (!(msg instanceof Number)) { // Ignore what this encoder can't encode. return msg; diff --git a/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServer.java b/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServer.java index 247950d9d1..9b7525ee11 100644 --- a/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServer.java +++ b/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServer.java @@ -23,19 +23,21 @@ import org.jboss.netty.handler.ssl.util.SelfSignedCertificate; import java.net.InetSocketAddress; import java.util.concurrent.Executors; -public class HttpStaticFileServer { +public final class HttpStaticFileServer { - private static final boolean useSsl = false; // Set to true to enable SSL. + static final boolean SSL = System.getProperty("ssl") != null; + static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080")); - private final SslContext sslCtx; - private final int port; + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + SelfSignedCertificate ssc = new SelfSignedCertificate(); + sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); + } else { + sslCtx = null; + } - public HttpStaticFileServer(SslContext sslCtx, int port) { - this.sslCtx = sslCtx; - this.port = port; - } - - public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -46,25 +48,6 @@ public class HttpStaticFileServer { bootstrap.setPipelineFactory(new HttpStaticFileServerPipelineFactory(sslCtx)); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(port)); - } - - public static void main(String[] args) throws Exception { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8080; - } - - final SslContext sslCtx; - if (useSsl) { - SelfSignedCertificate ssc = new SelfSignedCertificate(); - sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); - } else { - sslCtx = null; - } - - new HttpStaticFileServer(sslCtx, port).run(); + bootstrap.bind(new InetSocketAddress(PORT)); } } diff --git a/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServerHandler.java b/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServerHandler.java index f42ad0427e..7646dba50b 100644 --- a/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServerHandler.java +++ b/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServerHandler.java @@ -102,9 +102,9 @@ import static org.jboss.netty.handler.codec.http.HttpVersion.*; */ public class HttpStaticFileServerHandler extends SimpleChannelUpstreamHandler { - public static final String HTTP_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz"; - public static final String HTTP_DATE_GMT_TIMEZONE = "GMT"; - public static final int HTTP_CACHE_SECONDS = 60; + static final String HTTP_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz"; + static final String HTTP_DATE_GMT_TIMEZONE = "GMT"; + static final int HTTP_CACHE_SECONDS = 60; @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { @@ -182,7 +182,7 @@ public class HttpStaticFileServerHandler extends SimpleChannelUpstreamHandler { public void operationProgressed( ChannelFuture future, long amount, long current, long total) { - System.out.printf("%s: %d / %d (+%d)%n", path, current, total, amount); + System.err.printf("%s: %d / %d (+%d)%n", path, current, total, amount); } }); } @@ -195,8 +195,7 @@ public class HttpStaticFileServerHandler extends SimpleChannelUpstreamHandler { } @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) - throws Exception { + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { Channel ch = e.getChannel(); Throwable cause = e.getCause(); if (cause instanceof TooLongFrameException) { @@ -240,9 +239,7 @@ public class HttpStaticFileServerHandler extends SimpleChannelUpstreamHandler { private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); - response.setContent(ChannelBuffers.copiedBuffer( - "Failure: " + status.toString() + "\r\n", - CharsetUtil.UTF_8)); + response.setContent(ChannelBuffers.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8)); // Close the connection as soon as the error message is sent. ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); @@ -250,9 +247,6 @@ public class HttpStaticFileServerHandler extends SimpleChannelUpstreamHandler { /** * When file timestamp is the same as what the browser is sending up, send a "304 Not Modified" - * - * @param ctx - * Context */ private static void sendNotModified(ChannelHandlerContext ctx) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_MODIFIED); @@ -264,9 +258,6 @@ public class HttpStaticFileServerHandler extends SimpleChannelUpstreamHandler { /** * Sets the Date header for the HTTP response - * - * @param response - * HTTP response */ private static void setDateHeader(HttpResponse response) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); @@ -279,10 +270,7 @@ public class HttpStaticFileServerHandler extends SimpleChannelUpstreamHandler { /** * Sets the Date and Cache headers for the HTTP Response * - * @param response - * HTTP response - * @param fileToCache - * file to extract content type + * @param fileToCache the file to extract content type */ private static void setDateAndCacheHeaders(HttpResponse response, File fileToCache) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); @@ -296,21 +284,16 @@ public class HttpStaticFileServerHandler extends SimpleChannelUpstreamHandler { time.add(Calendar.SECOND, HTTP_CACHE_SECONDS); response.headers().set(EXPIRES, dateFormatter.format(time.getTime())); response.headers().set(CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS); - response.headers().set( - LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified()))); + response.headers().set(LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified()))); } /** * Sets the content type header for the HTTP Response * - * @param response - * HTTP response - * @param file - * file to extract content type + * @param file the file to extract content type */ private static void setContentTypeHeader(HttpResponse response, File file) { MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap(); response.headers().set(CONTENT_TYPE, mimeTypesMap.getContentType(file.getPath())); } - } diff --git a/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServerPipelineFactory.java b/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServerPipelineFactory.java index 6f08a3ff02..333179c883 100644 --- a/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServerPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServerPipelineFactory.java @@ -33,7 +33,7 @@ public class HttpStaticFileServerPipelineFactory implements ChannelPipelineFacto this.sslCtx = sslCtx; } - public ChannelPipeline getPipeline() throws Exception { + public ChannelPipeline getPipeline() { // Create a default pipeline implementation. ChannelPipeline pipeline = pipeline(); diff --git a/src/main/java/org/jboss/netty/example/http/helloworld/HttpHelloWorldServer.java b/src/main/java/org/jboss/netty/example/http/helloworld/HttpHelloWorldServer.java index 53cb814217..4774df763c 100644 --- a/src/main/java/org/jboss/netty/example/http/helloworld/HttpHelloWorldServer.java +++ b/src/main/java/org/jboss/netty/example/http/helloworld/HttpHelloWorldServer.java @@ -17,6 +17,8 @@ package org.jboss.netty.example.http.helloworld; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.SelfSignedCertificate; import java.net.InetSocketAddress; import java.util.concurrent.Executors; @@ -25,15 +27,21 @@ import java.util.concurrent.Executors; * An HTTP server that sends back the content of the received HTTP request * in a pretty plaintext form. */ -public class HttpHelloWorldServer { +public final class HttpHelloWorldServer { - private final int port; + static final boolean SSL = System.getProperty("ssl") != null; + static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080")); - public HttpHelloWorldServer(int port) { - this.port = port; - } + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + SelfSignedCertificate ssc = new SelfSignedCertificate(); + sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); + } else { + sslCtx = null; + } - public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -44,20 +52,9 @@ public class HttpHelloWorldServer { bootstrap.setOption("child.tcpNoDelay", true); // Set up the event pipeline factory. - bootstrap.setPipelineFactory(new HttpHelloWorldServerPipelineFactory()); + bootstrap.setPipelineFactory(new HttpHelloWorldServerPipelineFactory(sslCtx)); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(port)); + bootstrap.bind(new InetSocketAddress(PORT)); } - - public static void main(String[] args) { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8080; - } - new HttpHelloWorldServer(port).run(); - } - } diff --git a/src/main/java/org/jboss/netty/example/http/helloworld/HttpHelloWorldServerHandler.java b/src/main/java/org/jboss/netty/example/http/helloworld/HttpHelloWorldServerHandler.java index 4ef8997e60..0252c5be39 100644 --- a/src/main/java/org/jboss/netty/example/http/helloworld/HttpHelloWorldServerHandler.java +++ b/src/main/java/org/jboss/netty/example/http/helloworld/HttpHelloWorldServerHandler.java @@ -38,7 +38,7 @@ public class HttpHelloWorldServerHandler extends SimpleChannelUpstreamHandler { private static final byte[] CONTENT = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' }; @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { Object msg = e.getMessage(); Channel ch = e.getChannel(); if (msg instanceof HttpRequest) { @@ -66,8 +66,7 @@ public class HttpHelloWorldServerHandler extends SimpleChannelUpstreamHandler { } @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) - throws Exception { + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { e.getCause().printStackTrace(); e.getChannel().close(); } diff --git a/src/main/java/org/jboss/netty/example/http/helloworld/HttpHelloWorldServerPipelineFactory.java b/src/main/java/org/jboss/netty/example/http/helloworld/HttpHelloWorldServerPipelineFactory.java index fe9d4ba107..3fa928b9c0 100644 --- a/src/main/java/org/jboss/netty/example/http/helloworld/HttpHelloWorldServerPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/http/helloworld/HttpHelloWorldServerPipelineFactory.java @@ -20,19 +20,25 @@ import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.http.HttpContentCompressor; import org.jboss.netty.handler.codec.http.HttpRequestDecoder; import org.jboss.netty.handler.codec.http.HttpResponseEncoder; +import org.jboss.netty.handler.ssl.SslContext; import static org.jboss.netty.channel.Channels.*; public class HttpHelloWorldServerPipelineFactory implements ChannelPipelineFactory { - public ChannelPipeline getPipeline() throws Exception { + + private final SslContext sslCtx; + + public HttpHelloWorldServerPipelineFactory(SslContext sslCtx) { + this.sslCtx = sslCtx; + } + + public ChannelPipeline getPipeline() { // Create a default pipeline implementation. ChannelPipeline pipeline = pipeline(); - // Uncomment the following line if you want HTTPS - //SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine(); - //engine.setUseClientMode(false); - //pipeline.addLast("ssl", new SslHandler(engine)); - + if (sslCtx != null) { + pipeline.addLast("ssl", sslCtx.newHandler()); + } pipeline.addLast("decoder", new HttpRequestDecoder()); // Uncomment the following line if you don't want to handle HttpChunks. //pipeline.addLast("aggregator", new HttpChunkAggregator(1048576)); diff --git a/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopClient.java b/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopClient.java index ce51f87a02..35c133d2f2 100644 --- a/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopClient.java +++ b/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopClient.java @@ -36,17 +36,14 @@ import java.util.concurrent.Executors; * A simple HTTP client that prints out the content of the HTTP response to * {@link System#out} to test {@link HttpSnoopServer}. */ -public class HttpSnoopClient { +public final class HttpSnoopClient { - private final URI uri; + static final String URL = System.getProperty("url", "http://127.0.0.1:8080/"); - public HttpSnoopClient(URI uri) { - this.uri = uri; - } - - public void run() throws Exception { + public static void main(String[] args) throws Exception { + URI uri = new URI(URL); String scheme = uri.getScheme() == null? "http" : uri.getScheme(); - String host = uri.getHost() == null? "localhost" : uri.getHost(); + String host = uri.getHost() == null? "127.0.0.1" : uri.getHost(); int port = uri.getPort(); if (port == -1) { if ("http".equalsIgnoreCase(scheme)) { @@ -76,52 +73,37 @@ public class HttpSnoopClient { Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); - // Set up the event pipeline factory. - bootstrap.setPipelineFactory(new HttpSnoopClientPipelineFactory(sslCtx)); + try { + // Set up the event pipeline factory. + bootstrap.setPipelineFactory(new HttpSnoopClientPipelineFactory(sslCtx, host, port)); - // Start the connection attempt. - ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); + // Start the connection attempt. + ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); - // Wait until the connection attempt succeeds or fails. - Channel channel = future.awaitUninterruptibly().getChannel(); - if (!future.isSuccess()) { - future.getCause().printStackTrace(); + // Wait until the connection attempt succeeds or fails. + Channel channel = future.sync().getChannel(); + + // Prepare the HTTP request. + HttpRequest request = new DefaultHttpRequest( + HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); + request.headers().set(HttpHeaders.Names.HOST, host); + request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); + request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); + + // Set some example cookies. + CookieEncoder httpCookieEncoder = new CookieEncoder(false); + httpCookieEncoder.addCookie("my-cookie", "foo"); + httpCookieEncoder.addCookie("another-cookie", "bar"); + request.headers().set(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode()); + + // Send the HTTP request. + channel.write(request); + + // Wait for the server to close the connection. + channel.getCloseFuture().sync(); + } finally { + // Shut down executor threads to exit. bootstrap.releaseExternalResources(); - return; } - - // Prepare the HTTP request. - HttpRequest request = new DefaultHttpRequest( - HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); - request.headers().set(HttpHeaders.Names.HOST, host); - request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); - request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); - - // Set some example cookies. - CookieEncoder httpCookieEncoder = new CookieEncoder(false); - httpCookieEncoder.addCookie("my-cookie", "foo"); - httpCookieEncoder.addCookie("another-cookie", "bar"); - request.headers().set(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode()); - - // Send the HTTP request. - channel.write(request); - - // Wait for the server to close the connection. - channel.getCloseFuture().awaitUninterruptibly(); - - // Shut down executor threads to exit. - bootstrap.releaseExternalResources(); - } - - public static void main(String[] args) throws Exception { - if (args.length != 1) { - System.err.println( - "Usage: " + HttpSnoopClient.class.getSimpleName() + - " "); - return; - } - - URI uri = new URI(args[0]); - new HttpSnoopClient(uri).run(); } } diff --git a/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopClientHandler.java b/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopClientHandler.java index 2a3fc6cc2e..1c1c074a32 100644 --- a/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopClientHandler.java +++ b/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopClientHandler.java @@ -28,42 +28,42 @@ public class HttpSnoopClientHandler extends SimpleChannelUpstreamHandler { private boolean readingChunks; @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { if (!readingChunks) { HttpResponse response = (HttpResponse) e.getMessage(); - System.out.println("STATUS: " + response.getStatus()); - System.out.println("VERSION: " + response.getProtocolVersion()); - System.out.println(); + System.err.println("STATUS: " + response.getStatus()); + System.err.println("VERSION: " + response.getProtocolVersion()); + System.err.println(); if (!response.headers().names().isEmpty()) { for (String name: response.headers().names()) { for (String value: response.headers().getAll(name)) { - System.out.println("HEADER: " + name + " = " + value); + System.err.println("HEADER: " + name + " = " + value); } } - System.out.println(); + System.err.println(); } if (response.isChunked()) { readingChunks = true; - System.out.println("CHUNKED CONTENT {"); + System.err.println("CHUNKED CONTENT {"); } else { ChannelBuffer content = response.getContent(); if (content.readable()) { - System.out.println("CONTENT {"); - System.out.println(content.toString(CharsetUtil.UTF_8)); - System.out.println("} END OF CONTENT"); + System.err.println("CONTENT {"); + System.err.println(content.toString(CharsetUtil.UTF_8)); + System.err.println("} END OF CONTENT"); } } } else { HttpChunk chunk = (HttpChunk) e.getMessage(); if (chunk.isLast()) { readingChunks = false; - System.out.println("} END OF CHUNKED CONTENT"); + System.err.println("} END OF CHUNKED CONTENT"); } else { - System.out.print(chunk.getContent().toString(CharsetUtil.UTF_8)); - System.out.flush(); + System.err.print(chunk.getContent().toString(CharsetUtil.UTF_8)); + System.err.flush(); } } } diff --git a/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopClientPipelineFactory.java b/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopClientPipelineFactory.java index ab5c3d1b31..1e02692ba1 100644 --- a/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopClientPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopClientPipelineFactory.java @@ -26,18 +26,22 @@ import static org.jboss.netty.channel.Channels.*; public class HttpSnoopClientPipelineFactory implements ChannelPipelineFactory { private final SslContext sslCtx; + private final String host; + private final int port; - public HttpSnoopClientPipelineFactory(SslContext sslCtx) { + public HttpSnoopClientPipelineFactory(SslContext sslCtx, String host, int port) { this.sslCtx = sslCtx; + this.host = host; + this.port = port; } - public ChannelPipeline getPipeline() throws Exception { + public ChannelPipeline getPipeline() { // Create a default pipeline implementation. ChannelPipeline pipeline = pipeline(); // Enable HTTPS if necessary. if (sslCtx != null) { - pipeline.addLast("ssl", sslCtx.newHandler()); + pipeline.addLast("ssl", sslCtx.newHandler(host, port)); } pipeline.addLast("codec", new HttpClientCodec()); diff --git a/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopServer.java b/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopServer.java index 891f563572..0bf4ea1eec 100644 --- a/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopServer.java +++ b/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopServer.java @@ -17,6 +17,8 @@ package org.jboss.netty.example.http.snoop; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.SelfSignedCertificate; import java.net.InetSocketAddress; import java.util.concurrent.Executors; @@ -25,15 +27,21 @@ import java.util.concurrent.Executors; * An HTTP server that sends back the content of the received HTTP request * in a pretty plaintext form. */ -public class HttpSnoopServer { +public final class HttpSnoopServer { - private final int port; + static final boolean SSL = System.getProperty("ssl") != null; + static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080")); - public HttpSnoopServer(int port) { - this.port = port; - } + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + SelfSignedCertificate ssc = new SelfSignedCertificate(); + sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); + } else { + sslCtx = null; + } - public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -44,20 +52,9 @@ public class HttpSnoopServer { bootstrap.setOption("child.tcpNoDelay", true); // Set up the event pipeline factory. - bootstrap.setPipelineFactory(new HttpSnoopServerPipelineFactory()); + bootstrap.setPipelineFactory(new HttpSnoopServerPipelineFactory(sslCtx)); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(port)); + bootstrap.bind(new InetSocketAddress(PORT)); } - - public static void main(String[] args) { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8080; - } - new HttpSnoopServer(port).run(); - } - } diff --git a/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopServerHandler.java b/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopServerHandler.java index 33b8e21b45..f73fd9fb4f 100644 --- a/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopServerHandler.java +++ b/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopServerHandler.java @@ -15,16 +15,6 @@ */ package org.jboss.netty.example.http.snoop; -import static org.jboss.netty.handler.codec.http.HttpHeaders.*; -import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*; -import static org.jboss.netty.handler.codec.http.HttpResponseStatus.*; -import static org.jboss.netty.handler.codec.http.HttpVersion.*; - -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.ChannelFuture; @@ -45,6 +35,16 @@ import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.http.QueryStringDecoder; import org.jboss.netty.util.CharsetUtil; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*; +import static org.jboss.netty.handler.codec.http.HttpHeaders.*; +import static org.jboss.netty.handler.codec.http.HttpResponseStatus.*; +import static org.jboss.netty.handler.codec.http.HttpVersion.*; + public class HttpSnoopServerHandler extends SimpleChannelUpstreamHandler { private HttpRequest request; @@ -53,7 +53,7 @@ public class HttpSnoopServerHandler extends SimpleChannelUpstreamHandler { private final StringBuilder buf = new StringBuilder(); @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { if (!readingChunks) { HttpRequest request = this.request = (HttpRequest) e.getMessage(); @@ -174,8 +174,7 @@ public class HttpSnoopServerHandler extends SimpleChannelUpstreamHandler { } @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) - throws Exception { + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { e.getCause().printStackTrace(); e.getChannel().close(); } diff --git a/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopServerPipelineFactory.java b/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopServerPipelineFactory.java index 03ffd286c6..8f8387f690 100644 --- a/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopServerPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopServerPipelineFactory.java @@ -15,24 +15,30 @@ */ package org.jboss.netty.example.http.snoop; -import static org.jboss.netty.channel.Channels.*; - import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.http.HttpContentCompressor; import org.jboss.netty.handler.codec.http.HttpRequestDecoder; import org.jboss.netty.handler.codec.http.HttpResponseEncoder; +import org.jboss.netty.handler.ssl.SslContext; + +import static org.jboss.netty.channel.Channels.*; public class HttpSnoopServerPipelineFactory implements ChannelPipelineFactory { - public ChannelPipeline getPipeline() throws Exception { + + private final SslContext sslCtx; + + public HttpSnoopServerPipelineFactory(SslContext sslCtx) { + this.sslCtx = sslCtx; + } + + public ChannelPipeline getPipeline() { // Create a default pipeline implementation. ChannelPipeline pipeline = pipeline(); - // Uncomment the following line if you want HTTPS - //SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine(); - //engine.setUseClientMode(false); - //pipeline.addLast("ssl", new SslHandler(engine)); - + if (sslCtx != null) { + pipeline.addLast("ssl", sslCtx.newHandler()); + } pipeline.addLast("decoder", new HttpRequestDecoder()); // Uncomment the following line if you don't want to handle HttpChunks. //pipeline.addLast("aggregator", new HttpChunkAggregator(1048576)); diff --git a/src/main/java/org/jboss/netty/example/http/tunnel/HttpTunnelingClientExample.java b/src/main/java/org/jboss/netty/example/http/tunnel/HttpTunnelingClientExample.java index 78bad2a804..b56309e918 100644 --- a/src/main/java/org/jboss/netty/example/http/tunnel/HttpTunnelingClientExample.java +++ b/src/main/java/org/jboss/netty/example/http/tunnel/HttpTunnelingClientExample.java @@ -41,88 +41,81 @@ import java.util.concurrent.Executors; * for the detailed instruction on how to deploy the server-side HTTP tunnel in * your Servlet container. */ -public class HttpTunnelingClientExample { +public final class HttpTunnelingClientExample { - private final URI uri; + static final String URL = System.getProperty("url", "http://localhost:8080/netty-tunnel"); - public HttpTunnelingClientExample(URI uri) { - this.uri = uri; - } - - public void run() throws Exception { + public static void main(String[] args) throws Exception { + URI uri = new URI(URL); String scheme = uri.getScheme() == null? "http" : uri.getScheme(); + String host = uri.getHost() == null? "127.0.0.1" : uri.getHost(); + int port = uri.getPort(); + if (port == -1) { + if ("http".equalsIgnoreCase(scheme)) { + port = 80; + } else if ("https".equalsIgnoreCase(scheme)) { + port = 443; + } + } + + if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { + System.err.println("Only HTTP(S) is supported."); + return; + } // Configure the client. ClientBootstrap b = new ClientBootstrap( new HttpTunnelingClientSocketChannelFactory( new OioClientSocketChannelFactory(Executors.newCachedThreadPool()))); - b.setPipelineFactory(new ChannelPipelineFactory() { - public ChannelPipeline getPipeline() throws Exception { - return Channels.pipeline( - new StringDecoder(), - new StringEncoder(), - new LoggingHandler(InternalLogLevel.INFO)); - } - }); + try { + b.setPipelineFactory(new ChannelPipelineFactory() { + public ChannelPipeline getPipeline() { + return Channels.pipeline( + new StringDecoder(), + new StringEncoder(), + new LoggingHandler(InternalLogLevel.INFO)); + } + }); - // Set additional options required by the HTTP tunneling transport. - b.setOption("serverName", uri.getHost()); - b.setOption("serverPath", uri.getRawPath()); + // Set additional options required by the HTTP tunneling transport. + b.setOption("serverName", uri.getHost()); + b.setOption("serverPath", uri.getRawPath()); - // Configure SSL if necessary - if ("https".equals(scheme)) { - b.setOption("sslContext", new JdkSslClientContext(InsecureTrustManagerFactory.INSTANCE).context()); - } else if (!"http".equals(scheme)) { - // Only HTTP and HTTPS are supported. - System.err.println("Only HTTP(S) is supported."); - return; - } - - // Make the connection attempt. - ChannelFuture channelFuture = b.connect( - new InetSocketAddress(uri.getHost(), uri.getPort())); - channelFuture.awaitUninterruptibly(); - - // Read commands from the stdin. - System.out.println("Enter text ('quit' to exit)"); - ChannelFuture lastWriteFuture = null; - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - for (; ;) { - String line = in.readLine(); - if (line == null || "quit".equalsIgnoreCase(line)) { - break; + // Configure SSL if necessary + if ("https".equals(scheme)) { + b.setOption("sslContext", new JdkSslClientContext(InsecureTrustManagerFactory.INSTANCE).context()); } - // Sends the received line to the server. - lastWriteFuture = channelFuture.getChannel().write(line); + // Make the connection attempt. + ChannelFuture channelFuture = b.connect(new InetSocketAddress(host, port)); + channelFuture.sync(); + + // Read commands from the stdin. + System.err.println("Enter text ('quit' to exit)"); + + ChannelFuture lastWriteFuture = null; + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + for (;;) { + String line = in.readLine(); + if (line == null || "quit".equalsIgnoreCase(line)) { + break; + } + + // Sends the received line to the server. + lastWriteFuture = channelFuture.getChannel().write(line); + } + + // Wait until all messages are flushed before closing the channel. + if (lastWriteFuture != null) { + lastWriteFuture.sync(); + } + + // Close the connection. + channelFuture.getChannel().close().sync(); + } finally { + // Shut down all threads. + b.releaseExternalResources(); } - - // Wait until all messages are flushed before closing the channel. - if (lastWriteFuture != null) { - lastWriteFuture.awaitUninterruptibly(); - } - - channelFuture.getChannel().close(); - // Wait until the connection is closed or the connection attempt fails. - channelFuture.getChannel().getCloseFuture().awaitUninterruptibly(); - - // Shut down all threads. - b.releaseExternalResources(); - } - - public static void main(String[] args) throws Exception { - if (args.length != 1) { - System.err.println( - "Usage: " + HttpTunnelingClientExample.class.getSimpleName() + - " "); - System.err.println( - "Example: " + HttpTunnelingClientExample.class.getSimpleName() + - " http://localhost:8080/netty-tunnel"); - return; - } - - URI uri = new URI(args[0]); - new HttpTunnelingClientExample(uri).run(); } } diff --git a/src/main/java/org/jboss/netty/example/http/upload/HttpUploadClient.java b/src/main/java/org/jboss/netty/example/http/upload/HttpUploadClient.java index 222a8f3a43..5f6e763cbd 100644 --- a/src/main/java/org/jboss/netty/example/http/upload/HttpUploadClient.java +++ b/src/main/java/org/jboss/netty/example/http/upload/HttpUploadClient.java @@ -31,54 +31,38 @@ import org.jboss.netty.handler.codec.http.multipart.DiskAttribute; import org.jboss.netty.handler.codec.http.multipart.DiskFileUpload; import org.jboss.netty.handler.codec.http.multipart.HttpDataFactory; import org.jboss.netty.handler.codec.http.multipart.HttpPostRequestEncoder; -import org.jboss.netty.handler.codec.http.multipart.HttpPostRequestEncoder.ErrorDataEncoderException; import org.jboss.netty.handler.codec.http.multipart.InterfaceHttpData; import org.jboss.netty.handler.ssl.SslContext; import org.jboss.netty.handler.ssl.util.SelfSignedCertificate; -import org.jboss.netty.logging.InternalLogger; -import org.jboss.netty.logging.InternalLoggerFactory; import java.io.File; +import java.io.FileNotFoundException; import java.net.InetSocketAddress; import java.net.URI; -import java.net.URISyntaxException; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.Executors; -public class HttpUploadClient { +public final class HttpUploadClient { - private static final InternalLogger logger = - InternalLoggerFactory.getInstance(HttpUploadClient.class); + static final String BASE_URL = System.getProperty("baseUrl", "http://127.0.0.1:8080/"); + static final String FILE = System.getProperty("file", "upload.txt"); - private final String baseUri; - private final String filePath; - - public HttpUploadClient(String baseUri, String filePath) { - this.baseUri = baseUri; - this.filePath = filePath; - } - - public void run() throws Exception { + public static void main(String[] args) throws Exception { String postSimple, postFile, get; - if (baseUri.endsWith("/")) { - postSimple = baseUri + "formpost"; - postFile = baseUri + "formpostmultipart"; - get = baseUri + "formget"; + if (BASE_URL.endsWith("/")) { + postSimple = BASE_URL + "formpost"; + postFile = BASE_URL + "formpostmultipart"; + get = BASE_URL + "formget"; } else { - postSimple = baseUri + "/formpost"; - postFile = baseUri + "/formpostmultipart"; - get = baseUri + "/formget"; - } - URI uriSimple; - try { - uriSimple = new URI(postSimple); - } catch (URISyntaxException e) { - logger.error("Invalid URI syntax" + e.getCause()); - return; + postSimple = BASE_URL + "/formpost"; + postFile = BASE_URL + "/formpostmultipart"; + get = BASE_URL + "/formget"; } + + URI uriSimple = new URI(postSimple); String scheme = uriSimple.getScheme() == null? "http" : uriSimple.getScheme(); - String host = uriSimple.getHost() == null? "localhost" : uriSimple.getHost(); + String host = uriSimple.getHost() == null? "127.0.0.1" : uriSimple.getHost(); int port = uriSimple.getPort(); if (port == -1) { if ("http".equalsIgnoreCase(scheme)) { @@ -89,7 +73,7 @@ public class HttpUploadClient { } if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { - logger.error("Only HTTP(S) is supported."); + System.err.println("Only HTTP(S) is supported."); return; } @@ -102,17 +86,10 @@ public class HttpUploadClient { sslCtx = null; } - URI uriFile; - try { - uriFile = new URI(postFile); - } catch (URISyntaxException e) { - logger.error("Error: " + e.getMessage()); - return; - } - File file = new File(filePath); - if (! file.canRead()) { - logger.error("A correct path is needed"); - return; + URI uriFile = new URI(postFile); + File file = new File(FILE); + if (!file.canRead()) { + throw new FileNotFoundException(FILE); } // Configure the client. @@ -121,58 +98,50 @@ public class HttpUploadClient { Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); - // Set up the event pipeline factory. - bootstrap.setPipelineFactory(new HttpUploadClientPipelineFactory(sslCtx)); + // Set up the factory: here using a mixed memory/disk based on size threshold + HttpDataFactory factory = + new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if size exceed MINSIZE - // setup the factory: here using a mixed memory/disk based on size threshold - HttpDataFactory factory = new DefaultHttpDataFactory( - DefaultHttpDataFactory.MINSIZE); // Disk if size exceed MINSIZE - DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) - DiskFileUpload.baseDirectory = null; // system temp directory - DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) - DiskAttribute.baseDirectory = null; // system temp directory + try { + // Set up the event pipeline factory. + bootstrap.setPipelineFactory(new HttpUploadClientPipelineFactory(sslCtx, host, port)); - // Simple Get form: no factory used (not usable) - List> headers = - formget(bootstrap, host, port, get, uriSimple); - if (headers == null) { + DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) + DiskFileUpload.baseDirectory = null; // system temp directory + DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) + DiskAttribute.baseDirectory = null; // system temp directory + + // Simple Get form: no factory used (not usable) + List> headers = formget(bootstrap, host, port, get, uriSimple); + + // Simple Post form: factory used for big attributes + List bodylist = formpost(bootstrap, host, port, uriSimple, file, factory, headers); + + // Multipart Post form: factory used + formpostmultipart(bootstrap, host, port, uriFile, factory, headers, bodylist); + } finally { + // Shut down executor threads to exit. + bootstrap.releaseExternalResources(); + // Really clean all temporary files if they still exist factory.cleanAllHttpDatas(); - return; } - // Simple Post form: factory used for big attributes - List bodylist = - formpost(bootstrap, host, port, uriSimple, file, factory, headers); - if (bodylist == null) { - factory.cleanAllHttpDatas(); - return; - } - // Multipart Post form: factory used - formpostmultipart(bootstrap, host, port, uriFile, factory, headers, bodylist); - - // Shut down executor threads to exit. - bootstrap.releaseExternalResources(); - // Really clean all temporary files if they still exist - factory.cleanAllHttpDatas(); } /** * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload * due to limitation on request size). + * * @return the list of headers that will be used in every example after **/ - private static List> formget(ClientBootstrap bootstrap, String host, int port, String get, - URI uriSimple) { + private static List> formget( + ClientBootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception { // XXX /formget // No use of HttpPostRequestEncoder since not a POST // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); + // Wait until the connection attempt succeeds or fails. - Channel channel = future.awaitUninterruptibly().getChannel(); - if (!future.isSuccess()) { - future.getCause().printStackTrace(); - bootstrap.releaseExternalResources(); - return null; - } + Channel channel = future.sync().getChannel(); // Prepare the HTTP request. QueryStringEncoder encoder = new QueryStringEncoder(get); @@ -185,28 +154,22 @@ public class HttpUploadClient { encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n"); encoder.addParam("Send", "Send"); - URI uriGet; - try { - uriGet = new URI(encoder.toString()); - } catch (URISyntaxException e) { - logger.error("Error: " + e.getMessage()); - bootstrap.releaseExternalResources(); - return null; - } - - HttpRequest request = new DefaultHttpRequest( - HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString()); + URI uriGet = new URI(encoder.toString()); + HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString()); request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); - request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP + ',' + - HttpHeaders.Values.DEFLATE); + request.headers().set( + HttpHeaders.Names.ACCEPT_ENCODING, + HttpHeaders.Values.GZIP + ',' + HttpHeaders.Values.DEFLATE); request.headers().set(HttpHeaders.Names.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); request.headers().set(HttpHeaders.Names.ACCEPT_LANGUAGE, "fr"); request.headers().set(HttpHeaders.Names.REFERER, uriSimple.toString()); request.headers().set(HttpHeaders.Names.USER_AGENT, "Netty Simple Http Client side"); - request.headers().set(HttpHeaders.Names.ACCEPT, + request.headers().set( + HttpHeaders.Names.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); + //connection will not close but needed // request.headers().set("Connection","keep-alive"); // request.headers().set("Keep-Alive","300"); @@ -221,7 +184,7 @@ public class HttpUploadClient { channel.write(request); // Wait for the server to close the connection. - channel.getCloseFuture().awaitUninterruptibly(); + channel.getCloseFuture().sync(); return headers; } @@ -231,24 +194,18 @@ public class HttpUploadClient { * * @return the list of HttpData object (attribute and file) to be reused on next post */ - private static List formpost(ClientBootstrap bootstrap, - String host, int port, - URI uriSimple, File file, HttpDataFactory factory, - List> headers) throws ErrorDataEncoderException { + private static List formpost( + ClientBootstrap bootstrap, + String host, int port, URI uriSimple, File file, HttpDataFactory factory, + List> headers) throws Exception { // XXX /formpost // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection attempt succeeds or fails. - Channel channel = future.awaitUninterruptibly().getChannel(); - if (!future.isSuccess()) { - future.getCause().printStackTrace(); - bootstrap.releaseExternalResources(); - return null; - } + Channel channel = future.sync().getChannel(); // Prepare the HTTP request. - HttpRequest request = new DefaultHttpRequest( - HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString()); + HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = @@ -264,6 +221,7 @@ public class HttpUploadClient { bodyRequestEncoder.addBodyAttribute("info", "first value"); bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue ���&"); bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea); + bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong); bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false); // finalize request @@ -278,7 +236,7 @@ public class HttpUploadClient { // test if request was chunked and if so, finish the write if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked() // either do it through ChunkedWriteHandler - channel.write(bodyRequestEncoder).awaitUninterruptibly(); + channel.write(bodyRequestEncoder).sync(); } // Do not clear here since we will reuse the InterfaceHttpData on the next request @@ -289,30 +247,24 @@ public class HttpUploadClient { // bodyRequestEncoder.cleanFiles(); // Wait for the server to close the connection. - channel.getCloseFuture().awaitUninterruptibly(); + channel.getCloseFuture().sync(); return bodylist; } /** * Multipart example */ - private static void formpostmultipart(ClientBootstrap bootstrap, String host, int port, - URI uriFile, HttpDataFactory factory, - List> headers, List bodylist) throws ErrorDataEncoderException { + private static void formpostmultipart( + ClientBootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory, + List> headers, List bodylist) throws Exception { // XXX /formpostmultipart // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection attempt succeeds or fails. - Channel channel = future.awaitUninterruptibly().getChannel(); - if (!future.isSuccess()) { - future.getCause().printStackTrace(); - bootstrap.releaseExternalResources(); - return; - } + Channel channel = future.sync().getChannel(); // Prepare the HTTP request. - HttpRequest request = new DefaultHttpRequest( - HttpVersion.HTTP_1_1, HttpMethod.POST, uriFile.toASCIIString()); + HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriFile.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = @@ -334,28 +286,14 @@ public class HttpUploadClient { // test if request was chunked and if so, finish the write if (bodyRequestEncoder.isChunked()) { - channel.write(bodyRequestEncoder).awaitUninterruptibly(); + channel.write(bodyRequestEncoder).sync(); } // Now no more use of file representation (and list of HttpData) bodyRequestEncoder.cleanFiles(); // Wait for the server to close the connection. - channel.getCloseFuture().awaitUninterruptibly(); - } - - public static void main(String[] args) throws Exception { - if (args.length != 2) { - logger.error( - "Usage: " + HttpUploadClient.class.getSimpleName() + - " baseURI filePath"); - return; - } - - String baseUri = args[0]; - String filePath = args[1]; - - new HttpUploadClient(baseUri, filePath).run(); + channel.getCloseFuture().sync(); } // use to simulate a small TEXTAREA field in a form diff --git a/src/main/java/org/jboss/netty/example/http/upload/HttpUploadClientHandler.java b/src/main/java/org/jboss/netty/example/http/upload/HttpUploadClientHandler.java index 6576dbfeca..fc917608c6 100644 --- a/src/main/java/org/jboss/netty/example/http/upload/HttpUploadClientHandler.java +++ b/src/main/java/org/jboss/netty/example/http/upload/HttpUploadClientHandler.java @@ -22,58 +22,52 @@ import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.codec.http.HttpChunk; import org.jboss.netty.handler.codec.http.HttpResponse; -import org.jboss.netty.logging.InternalLogger; -import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.CharsetUtil; public class HttpUploadClientHandler extends SimpleChannelUpstreamHandler { - private static final InternalLogger logger = - InternalLoggerFactory.getInstance(HttpUploadClientHandler.class); - private boolean readingChunks; @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { if (!readingChunks) { HttpResponse response = (HttpResponse) e.getMessage(); - logger.info("STATUS: " + response.getStatus()); - logger.info("VERSION: " + response.getProtocolVersion()); + System.err.println("STATUS: " + response.getStatus()); + System.err.println("VERSION: " + response.getProtocolVersion()); if (!response.headers().names().isEmpty()) { for (String name: response.headers().names()) { for (String value: response.headers().getAll(name)) { - logger.info("HEADER: " + name + " = " + value); + System.err.println("HEADER: " + name + " = " + value); } } } if (response.getStatus().getCode() == 200 && response.isChunked()) { readingChunks = true; - logger.info("CHUNKED CONTENT {"); + System.err.println("CHUNKED CONTENT {"); } else { ChannelBuffer content = response.getContent(); if (content.readable()) { - logger.info("CONTENT {"); - logger.info(content.toString(CharsetUtil.UTF_8)); - logger.info("} END OF CONTENT"); + System.err.println("CONTENT {"); + System.err.println(content.toString(CharsetUtil.UTF_8)); + System.err.println("} END OF CONTENT"); } } } else { HttpChunk chunk = (HttpChunk) e.getMessage(); if (chunk.isLast()) { readingChunks = false; - logger.info("} END OF CHUNKED CONTENT"); + System.err.println("} END OF CHUNKED CONTENT"); } else { - logger.info(chunk.getContent().toString(CharsetUtil.UTF_8)); + System.err.println(chunk.getContent().toString(CharsetUtil.UTF_8)); } } } @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) - throws Exception { + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { e.getCause().printStackTrace(); e.getChannel().close(); } diff --git a/src/main/java/org/jboss/netty/example/http/upload/HttpUploadClientPipelineFactory.java b/src/main/java/org/jboss/netty/example/http/upload/HttpUploadClientPipelineFactory.java index e18f8763a2..9cdafcd497 100644 --- a/src/main/java/org/jboss/netty/example/http/upload/HttpUploadClientPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/http/upload/HttpUploadClientPipelineFactory.java @@ -26,19 +26,24 @@ import org.jboss.netty.handler.stream.ChunkedWriteHandler; import static org.jboss.netty.channel.Channels.*; public class HttpUploadClientPipelineFactory implements ChannelPipelineFactory { - private final SslContext sslCtx; - public HttpUploadClientPipelineFactory(SslContext sslCtx) { + private final SslContext sslCtx; + private final String host; + private final int port; + + public HttpUploadClientPipelineFactory(SslContext sslCtx, String host, int port) { this.sslCtx = sslCtx; + this.host = host; + this.port = port; } - public ChannelPipeline getPipeline() throws Exception { + public ChannelPipeline getPipeline() { // Create a default pipeline implementation. ChannelPipeline pipeline = pipeline(); // Enable HTTPS if necessary. if (sslCtx != null) { - SslHandler handler = sslCtx.newHandler(); + SslHandler handler = sslCtx.newHandler(host, port); handler.setIssueHandshake(true); pipeline.addLast("ssl", handler); } diff --git a/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServer.java b/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServer.java index 577b614d02..0c54a8e574 100644 --- a/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServer.java +++ b/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServer.java @@ -23,19 +23,21 @@ import org.jboss.netty.handler.ssl.util.SelfSignedCertificate; import java.net.InetSocketAddress; import java.util.concurrent.Executors; -public class HttpUploadServer { +public final class HttpUploadServer { - private static final boolean useSsl = false; // Set to true to enable SSL. + static final boolean SSL = System.getProperty("ssl") != null; + static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080")); - private final SslContext sslCtx; - private final int port; + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + SelfSignedCertificate ssc = new SelfSignedCertificate(); + sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); + } else { + sslCtx = null; + } - public HttpUploadServer(SslContext sslCtx, int port) { - this.sslCtx = sslCtx; - this.port = port; - } - - public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -46,25 +48,6 @@ public class HttpUploadServer { bootstrap.setPipelineFactory(new HttpUploadServerPipelineFactory(sslCtx)); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(port)); - } - - public static void main(String[] args) throws Exception { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8080; - } - - SslContext sslCtx; - if (useSsl) { - SelfSignedCertificate ssc = new SelfSignedCertificate(); - sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); - } else { - sslCtx = null; - } - - new HttpUploadServer(sslCtx, port).run(); + bootstrap.bind(new InetSocketAddress(PORT)); } } diff --git a/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServerHandler.java b/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServerHandler.java index 3900539fd1..3856c81e72 100644 --- a/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServerHandler.java +++ b/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServerHandler.java @@ -50,8 +50,6 @@ import org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.Incom import org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.NotEnoughDataDecoderException; import org.jboss.netty.handler.codec.http.multipart.InterfaceHttpData; import org.jboss.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType; -import org.jboss.netty.logging.InternalLogger; -import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.CharsetUtil; import java.io.IOException; @@ -64,19 +62,9 @@ import java.util.Set; public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler { - private static final InternalLogger logger = - InternalLoggerFactory.getInstance(HttpUploadServerHandler.class); + private static final HttpDataFactory factory = + new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if size exceed MINSIZE - private HttpRequest request; - - private boolean readingChunks; - - private final StringBuilder responseContent = new StringBuilder(); - - private static final HttpDataFactory factory = new DefaultHttpDataFactory( - DefaultHttpDataFactory.MINSIZE); // Disk if size exceed MINSIZE - - private HttpPostRequestDecoder decoder; static { //To limit to roughly 5MB each attribute, including fileupload //factory.setMaxLimit(5000000); @@ -89,9 +77,13 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler { DiskAttribute.baseDirectory = null; // system temp directory } + private final StringBuilder responseContent = new StringBuilder(); + private HttpPostRequestDecoder decoder; + private HttpRequest request; + private boolean readingChunks; + @Override - public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) - throws Exception { + public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) { if (decoder != null) { decoder.cleanFiles(); } @@ -116,18 +108,13 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler { responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); responseContent.append("===================================\r\n"); - - responseContent.append("VERSION: " + - request.getProtocolVersion().getText() + "\r\n"); - - responseContent.append("REQUEST_URI: " + request.getUri() + - "\r\n\r\n"); + responseContent.append("VERSION: " + request.getProtocolVersion().getText() + "\r\n"); + responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n"); responseContent.append("\r\n\r\n"); // new method for (Entry entry: request.headers()) { - responseContent.append("HEADER: " + entry.getKey() + '=' + - entry.getValue() + "\r\n"); + responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n"); } responseContent.append("\r\n\r\n"); @@ -141,14 +128,12 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler { cookies = decoder.decode(value); } for (Cookie cookie: cookies) { - responseContent.append("COOKIE: " + cookie.toString() + "\r\n"); + responseContent.append("COOKIE: " + cookie + "\r\n"); } responseContent.append("\r\n\r\n"); - QueryStringDecoder decoderQuery = new QueryStringDecoder(request - .getUri()); - Map> uriAttributes = decoderQuery - .getParameters(); + QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri()); + Map> uriAttributes = decoderQuery.getParameters(); for (Entry> attr: uriAttributes.entrySet()) { for (String attrVal: attr.getValue()) { responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n"); @@ -174,10 +159,8 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler { return; } - responseContent.append("Is Chunked: " + request.isChunked() + - "\r\n"); - responseContent.append("IsMultipart: " + decoder.isMultipart() + - "\r\n"); + responseContent.append("Is Chunked: " + request.isChunked() + "\r\n"); + responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); if (request.isChunked()) { // Chunk version responseContent.append("Chunks: "); @@ -185,8 +168,7 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler { } else { // Not chunk version readHttpDataAllReceive(e.getChannel()); - responseContent - .append("\r\n\r\nEND OF NOT CHUNKED CONTENT\r\n"); + responseContent.append("\r\n\r\nEND OF NOT CHUNKED CONTENT\r\n"); writeResponse(e.getChannel()); } } else { @@ -249,8 +231,7 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler { } } catch (EndOfDataDecoderException e1) { // end - responseContent - .append("\r\n\r\nEND OF CONTENT CHUNK BY CHUNK\r\n\r\n"); + responseContent.append("\r\n\r\nEND OF CONTENT CHUNK BY CHUNK\r\n\r\n"); } } @@ -271,17 +252,14 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler { } if (value.length() > 100) { responseContent.append("\r\nBODY Attribute: " + - attribute.getHttpDataType().name() + ": " + - attribute.getName() + " data too long\r\n"); + attribute.getHttpDataType().name() + ": " + attribute.getName() + " data too long\r\n"); } else { - responseContent.append("\r\nBODY Attribute: " + - attribute.getHttpDataType().name() + ": " + - attribute.toString() + "\r\n"); + responseContent.append( + "\r\nBODY Attribute: " + attribute.getHttpDataType().name() + ": " + attribute + "\r\n"); } } else { - responseContent.append("\r\nBODY FileUpload: " + - data.getHttpDataType().name() + ": " + data.toString() + - "\r\n"); + responseContent.append( + "\r\nBODY FileUpload: " + data.getHttpDataType().name() + ": " + data + "\r\n"); if (data.getHttpDataType() == HttpDataType.FileUpload) { FileUpload fileUpload = (FileUpload) data; if (fileUpload.isCompleted()) { @@ -295,9 +273,8 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler { } responseContent.append("\r\n"); } else { - responseContent - .append("\tFile too long to be printed out:" + - fileUpload.length() + "\r\n"); + responseContent.append( + "\tFile too long to be printed out:" + fileUpload.length() + "\r\n"); } // fileUpload.isInMemory();// tells if the file is in Memory // or on File @@ -306,8 +283,7 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler { // decoder.removeFileUploadFromClean(fileUpload); //remove // the File of to delete file } else { - responseContent - .append("\tFile to be continued but should not!\r\n"); + responseContent.append("\tFile to be continued but should not!\r\n"); } } } @@ -315,29 +291,24 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler { private void writeResponse(Channel channel) { // Convert the response content to a ChannelBuffer. - ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseContent - .toString(), CharsetUtil.UTF_8); + ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); responseContent.setLength(0); // Decide whether to close the connection or not. - boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request - .headers().get(HttpHeaders.Names.CONNECTION)) || + boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase( + request.headers().get(HttpHeaders.Names.CONNECTION)) || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && - !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request - .headers().get(HttpHeaders.Names.CONNECTION)); + !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.headers().get(HttpHeaders.Names.CONNECTION)); // Build the response object. - HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, - HttpResponseStatus.OK); + HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.setContent(buf); - response.headers().set(HttpHeaders.Names.CONTENT_TYPE, - "text/plain; charset=UTF-8"); + response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (!close) { // There's no need to add 'Content-Length' header // if this is the last response. - response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String - .valueOf(buf.readableBytes())); + response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buf.readableBytes())); } Set cookies; @@ -353,8 +324,7 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler { CookieEncoder cookieEncoder = new CookieEncoder(true); for (Cookie cookie: cookies) { cookieEncoder.addCookie(cookie); - response.headers().add(HttpHeaders.Names.SET_COOKIE, cookieEncoder - .encode()); + response.headers().add(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); cookieEncoder = new CookieEncoder(true); } } @@ -376,8 +346,7 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler { responseContent.append(""); responseContent.append("Netty Test Form\r\n"); responseContent.append("\r\n"); - responseContent - .append(""); + responseContent.append(""); responseContent.append(""); responseContent.append(""); @@ -389,98 +358,66 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler { responseContent.append("
\r\n"); // GET - responseContent - .append("
GET FORM
"); + responseContent.append("
GET FORM
"); responseContent.append("
"); - responseContent - .append(""); + responseContent.append(""); responseContent.append(""); - responseContent - .append(""); - responseContent - .append(""); + responseContent.append(""); - responseContent - .append(""); - responseContent - .append(""); + responseContent.append(""); + responseContent.append(""); responseContent.append("
Fill with value:
Fill with value:
"); - responseContent - .append("
Fill with value:
"); + responseContent.append("
Fill with value:
Fill with value:
"); + responseContent.append("
Fill with value:
"); responseContent.append("
\r\n"); - responseContent - .append("

"); + responseContent.append("

"); // POST - responseContent - .append("
POST FORM
"); + responseContent.append("
POST FORM
"); responseContent.append("
"); - responseContent - .append(""); + responseContent.append(""); responseContent.append(""); - responseContent - .append(""); - responseContent - .append(""); + responseContent.append(""); - responseContent - .append(""); - responseContent - .append(""); + responseContent.append(""); + responseContent.append(""); responseContent.append("
Fill with value:
Fill with value:
"); - responseContent - .append("
Fill with value:
"); - responseContent - .append("
Fill with file (only file name will be transmitted):
" + - ""); + responseContent.append("
Fill with value:
Fill with value:
"); + responseContent.append("
Fill with value:
"); + responseContent.append("
Fill with file (only file name will be transmitted):
"); + responseContent.append(""); responseContent.append("
\r\n"); - responseContent - .append("

"); + responseContent.append("

"); // POST with enctype="multipart/form-data" - responseContent - .append("
POST MULTIPART FORM
"); - responseContent - .append("
"); - responseContent - .append(""); + responseContent.append("
POST MULTIPART FORM
"); + responseContent.append(""); + responseContent.append(""); responseContent.append(""); - responseContent - .append(""); - responseContent - .append(""); + responseContent.append(""); - responseContent - .append(""); - responseContent - .append(""); + responseContent.append(""); + responseContent.append(""); responseContent.append("
Fill with value:
Fill with value:
"); - responseContent - .append("
Fill with value:
"); - responseContent - .append("
Fill with file:
"); + responseContent.append("
Fill with value:
Fill with value:
"); + responseContent.append("
Fill with value:
"); + responseContent.append("
Fill with file:
"); responseContent.append("
\r\n"); - responseContent - .append("

"); + responseContent.append("

"); responseContent.append(""); responseContent.append(""); - ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseContent - .toString(), CharsetUtil.UTF_8); + ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); // Build the response object. - HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, - HttpResponseStatus.OK); + HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.setContent(buf); - response.headers().set(HttpHeaders.Names.CONTENT_TYPE, - "text/html; charset=UTF-8"); - response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buf - .readableBytes())); + response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8"); + response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buf.readableBytes())); // Write the response. e.getChannel().write(response); } @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) - throws Exception { - logger.error(responseContent.toString(), e.getCause()); + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { + e.getCause().printStackTrace(); e.getChannel().close(); } } diff --git a/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServerPipelineFactory.java b/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServerPipelineFactory.java index 8dbdcdb6a7..2612f18c77 100644 --- a/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServerPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServerPipelineFactory.java @@ -33,7 +33,7 @@ public class HttpUploadServerPipelineFactory implements ChannelPipelineFactory { this.sslCtx = sslCtx; } - public ChannelPipeline getPipeline() throws Exception { + public ChannelPipeline getPipeline() { // Create a default pipeline implementation. ChannelPipeline pipeline = pipeline(); diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/autobahn/AutobahnServer.java b/src/main/java/org/jboss/netty/example/http/websocketx/autobahn/AutobahnServer.java index 4430534507..bdba5da535 100644 --- a/src/main/java/org/jboss/netty/example/http/websocketx/autobahn/AutobahnServer.java +++ b/src/main/java/org/jboss/netty/example/http/websocketx/autobahn/AutobahnServer.java @@ -15,25 +15,26 @@ */ package org.jboss.netty.example.http.websocketx.autobahn; -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; + /** * A Web Socket echo server for running the autobahn test * suite */ -public class AutobahnServer { +public final class AutobahnServer { - private final int port; + public static void main(String[] args) { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 9000; + } - public AutobahnServer(int port) { - this.port = port; - } - - public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); @@ -46,16 +47,6 @@ public class AutobahnServer { // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(port)); - System.out.println("Web Socket Server started at port " + port); - } - - public static void main(String[] args) { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 9000; - } - new AutobahnServer(port).run(); + System.err.println("Web Socket Server started at port " + port); } } diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/autobahn/AutobahnServerHandler.java b/src/main/java/org/jboss/netty/example/http/websocketx/autobahn/AutobahnServerHandler.java index d7825d41a9..43e6ea07ff 100644 --- a/src/main/java/org/jboss/netty/example/http/websocketx/autobahn/AutobahnServerHandler.java +++ b/src/main/java/org/jboss/netty/example/http/websocketx/autobahn/AutobahnServerHandler.java @@ -15,11 +15,6 @@ */ package org.jboss.netty.example.http.websocketx.autobahn; -import static org.jboss.netty.handler.codec.http.HttpHeaders.*; -import static org.jboss.netty.handler.codec.http.HttpMethod.*; -import static org.jboss.netty.handler.codec.http.HttpResponseStatus.*; -import static org.jboss.netty.handler.codec.http.HttpVersion.*; - import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; @@ -44,6 +39,11 @@ import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.CharsetUtil; +import static org.jboss.netty.handler.codec.http.HttpHeaders.*; +import static org.jboss.netty.handler.codec.http.HttpMethod.*; +import static org.jboss.netty.handler.codec.http.HttpResponseStatus.*; +import static org.jboss.netty.handler.codec.http.HttpVersion.*; + /** * Handles handshakes and messages */ @@ -53,7 +53,7 @@ public class AutobahnServerHandler extends SimpleChannelUpstreamHandler { private WebSocketServerHandshaker handshaker; @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { Object msg = e.getMessage(); if (msg instanceof HttpRequest) { handleHttpRequest(ctx, (HttpRequest) msg); @@ -62,7 +62,7 @@ public class AutobahnServerHandler extends SimpleChannelUpstreamHandler { } } - private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) throws Exception { + private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) { // Allow only GET methods. if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN)); @@ -70,8 +70,8 @@ public class AutobahnServerHandler extends SimpleChannelUpstreamHandler { } // Handshake - WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( - getWebSocketLocation(req), null, false); + WebSocketServerHandshakerFactory wsFactory = + new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, false); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { wsFactory.sendUnsupportedWebSocketVersionResponse(ctx.getChannel()); @@ -82,8 +82,8 @@ public class AutobahnServerHandler extends SimpleChannelUpstreamHandler { private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (logger.isDebugEnabled()) { - logger.debug(String - .format("Channel %s received %s", ctx.getChannel().getId(), frame.getClass().getSimpleName())); + logger.debug(String.format( + "Channel %s received %s", ctx.getChannel().getId(), frame.getClass().getSimpleName())); } if (frame instanceof CloseWebSocketFrame) { @@ -124,7 +124,7 @@ public class AutobahnServerHandler extends SimpleChannelUpstreamHandler { } @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { e.getCause().printStackTrace(); e.getChannel().close(); } diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/autobahn/AutobahnServerPipelineFactory.java b/src/main/java/org/jboss/netty/example/http/websocketx/autobahn/AutobahnServerPipelineFactory.java index 67fd59d52f..19964d45be 100644 --- a/src/main/java/org/jboss/netty/example/http/websocketx/autobahn/AutobahnServerPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/http/websocketx/autobahn/AutobahnServerPipelineFactory.java @@ -15,18 +15,18 @@ */ package org.jboss.netty.example.http.websocketx.autobahn; -import static org.jboss.netty.channel.Channels.*; - import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.http.HttpChunkAggregator; import org.jboss.netty.handler.codec.http.HttpRequestDecoder; import org.jboss.netty.handler.codec.http.HttpResponseEncoder; +import static org.jboss.netty.channel.Channels.*; + /** */ public class AutobahnServerPipelineFactory implements ChannelPipelineFactory { - public ChannelPipeline getPipeline() throws Exception { + public ChannelPipeline getPipeline() { // Create a default pipeline implementation. ChannelPipeline pipeline = pipeline(); pipeline.addLast("decoder", new HttpRequestDecoder()); diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/client/WebSocketClient.java b/src/main/java/org/jboss/netty/example/http/websocketx/client/WebSocketClient.java index 1e15a1c470..9e79fccce1 100644 --- a/src/main/java/org/jboss/netty/example/http/websocketx/client/WebSocketClient.java +++ b/src/main/java/org/jboss/netty/example/http/websocketx/client/WebSocketClient.java @@ -36,11 +36,6 @@ //THE SOFTWARE. package org.jboss.netty.example.http.websocketx.client; -import java.net.InetSocketAddress; -import java.net.URI; -import java.util.HashMap; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; @@ -57,16 +52,53 @@ import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame; import org.jboss.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import org.jboss.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; import org.jboss.netty.handler.codec.http.websocketx.WebSocketVersion; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.SelfSignedCertificate; -public class WebSocketClient { +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Executors; - private final URI uri; +public final class WebSocketClient { - public WebSocketClient(URI uri) { - this.uri = uri; - } + static final String URL = System.getProperty("url", "ws://127.0.0.1:8080/websocket"); + + public static void main(String[] args) throws Exception { + URI uri = new URI(URL); + String scheme = uri.getScheme() == null? "http" : uri.getScheme(); + final String host = uri.getHost() == null? "127.0.0.1" : uri.getHost(); + final int port; + if (uri.getPort() == -1) { + if ("http".equalsIgnoreCase(scheme)) { + port = 80; + } else if ("https".equalsIgnoreCase(scheme)) { + port = 443; + } else { + port = -1; + } + } else { + port = uri.getPort(); + } + + if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) { + System.err.println("Only WS(S) is supported."); + return; + } + + final boolean ssl = "wss".equalsIgnoreCase(scheme); + final SslContext sslCtx; + if (ssl) { + SelfSignedCertificate ssc = new SelfSignedCertificate(); + sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); + } else { + sslCtx = null; + } + + Map customHeaders = new HashMap(); + customHeaders.put("MyHeader", "MyValue"); - public void run() throws Exception { ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( @@ -74,16 +106,7 @@ public class WebSocketClient { Executors.newCachedThreadPool())); Channel ch = null; - try { - String protocol = uri.getScheme(); - if (!"ws".equals(protocol)) { - throw new IllegalArgumentException("Unsupported protocol: " + protocol); - } - - HashMap customHeaders = new HashMap(); - customHeaders.put("MyHeader", "MyValue"); - // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. @@ -92,9 +115,12 @@ public class WebSocketClient { uri, WebSocketVersion.V13, null, false, customHeaders); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - public ChannelPipeline getPipeline() throws Exception { + public ChannelPipeline getPipeline() { ChannelPipeline pipeline = Channels.pipeline(); + if (sslCtx != null) { + pipeline.addLast("ssl", sslCtx.newHandler(host, port)); + } pipeline.addLast("decoder", new HttpResponseDecoder()); pipeline.addLast("encoder", new HttpRequestEncoder()); pipeline.addLast("ws-handler", new WebSocketClientHandler(handshaker)); @@ -102,33 +128,26 @@ public class WebSocketClient { } }); - // Connect - System.out.println("WebSocket Client connecting"); - ChannelFuture future = - bootstrap.connect( - new InetSocketAddress(uri.getHost(), uri.getPort())); - future.syncUninterruptibly(); + // Connect. + ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); + ch = future.sync().getChannel(); - ch = future.getChannel(); - handshaker.handshake(ch).syncUninterruptibly(); + handshaker.handshake(ch).sync(); // Send 10 messages and wait for responses - System.out.println("WebSocket Client sending message"); for (int i = 0; i < 1000; i++) { ch.write(new TextWebSocketFrame("Message #" + i)); } // Ping - System.out.println("WebSocket Client sending ping"); - ch.write(new PingWebSocketFrame(ChannelBuffers.copiedBuffer(new byte[]{1, 2, 3, 4, 5, 6}))); + ch.write(new PingWebSocketFrame(ChannelBuffers.wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6 }))); // Close - System.out.println("WebSocket Client sending close"); ch.write(new CloseWebSocketFrame()); // WebSocketClientHandler will close the connection when the server // responds to the CloseWebSocketFrame. - ch.getCloseFuture().awaitUninterruptibly(); + ch.getCloseFuture().sync(); } finally { if (ch != null) { ch.close(); @@ -136,14 +155,4 @@ public class WebSocketClient { bootstrap.releaseExternalResources(); } } - - public static void main(String[] args) throws Exception { - URI uri; - if (args.length > 0) { - uri = new URI(args[0]); - } else { - uri = new URI("ws://localhost:8080/websocket"); - } - new WebSocketClient(uri).run(); - } } diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/client/WebSocketClientHandler.java b/src/main/java/org/jboss/netty/example/http/websocketx/client/WebSocketClientHandler.java index f166e0f499..c5c91621e4 100644 --- a/src/main/java/org/jboss/netty/example/http/websocketx/client/WebSocketClientHandler.java +++ b/src/main/java/org/jboss/netty/example/http/websocketx/client/WebSocketClientHandler.java @@ -61,44 +61,44 @@ public class WebSocketClientHandler extends SimpleChannelUpstreamHandler { } @Override - public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { - System.out.println("WebSocket Client disconnected!"); + public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) { + System.err.println("WebSocket Client disconnected!"); } @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { Channel ch = ctx.getChannel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, (HttpResponse) e.getMessage()); - System.out.println("WebSocket Client connected!"); + System.err.println("WebSocket Client connected!"); return; } if (e.getMessage() instanceof HttpResponse) { HttpResponse response = (HttpResponse) e.getMessage(); - throw new Exception("Unexpected HttpResponse (status=" + response.getStatus() + ", content=" - + response.getContent().toString(CharsetUtil.UTF_8) + ')'); + throw new IllegalStateException( + "unexpected response (status=" + response.getStatus() + + ", content=" + response.getContent().toString(CharsetUtil.UTF_8) + ')'); } WebSocketFrame frame = (WebSocketFrame) e.getMessage(); if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; - System.out.println("WebSocket Client received message: " + textFrame.getText()); + System.err.println("WebSocket Client received message: " + textFrame.getText()); } else if (frame instanceof PongWebSocketFrame) { - System.out.println("WebSocket Client received pong"); + System.err.println("WebSocket Client received pong"); } else if (frame instanceof CloseWebSocketFrame) { - System.out.println("WebSocket Client received closing"); + System.err.println("WebSocket Client received closing"); ch.close(); } else if (frame instanceof PingWebSocketFrame) { - System.out.println("WebSocket Client received ping, response with pong"); + System.err.println("WebSocket Client received ping, response with pong"); ch.write(new PongWebSocketFrame(frame.getBinaryData())); } } @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { - final Throwable t = e.getCause(); - t.printStackTrace(); + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { + e.getCause().printStackTrace(); e.getChannel().close(); } } diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/html5/CustomTextFrameHandler.java b/src/main/java/org/jboss/netty/example/http/websocketx/html5/CustomTextFrameHandler.java deleted file mode 100644 index 468f1d2a9f..0000000000 --- a/src/main/java/org/jboss/netty/example/http/websocketx/html5/CustomTextFrameHandler.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project 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. - */ -package org.jboss.netty.example.http.websocketx.html5; - -import org.jboss.netty.channel.ChannelHandlerContext; -import org.jboss.netty.channel.MessageEvent; -import org.jboss.netty.channel.SimpleChannelHandler; -import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame; - -public class CustomTextFrameHandler extends SimpleChannelHandler { - - @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { - if (e.getMessage() instanceof TextWebSocketFrame) { - TextWebSocketFrame frame = (TextWebSocketFrame) e.getMessage(); - ctx.getChannel().write(new TextWebSocketFrame(frame.getText().toUpperCase())); - } - } - -} diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/html5/WebSocketServer.java b/src/main/java/org/jboss/netty/example/http/websocketx/html5/WebSocketServer.java deleted file mode 100644 index ab1023768a..0000000000 --- a/src/main/java/org/jboss/netty/example/http/websocketx/html5/WebSocketServer.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project 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. - */ -package org.jboss.netty.example.http.websocketx.html5; - -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - -import org.jboss.netty.bootstrap.ServerBootstrap; -import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; -import org.jboss.netty.example.http.websocketx.server.WebSocketServerPipelineFactory; - -/** - * A WebSocket Server that respondes to requests at: - * - *
- * http://localhost:8080/websocket
- * 
- * - * The example differs from many of the other examples in Netty in that is does - * not have an acomponying client. Instead a html page is provided that - * interacts with this server.
- * Open up the following file a web browser that supports WebSocket's: - * - *
- * netty/src/test/resources/websocketx/html5/websocket.html
- * 
- * - * The html page is very simple were you simply enter some text and the server - * will echo the same text back, but in uppercase. You, also see status messages - * in the "Response From Server" area when client has connected, disconnected - * etc. - * - */ -public class WebSocketServer { - - private final int port; - - public WebSocketServer(int port) { - this.port = port; - } - - public void run() { - // Configure the server. - ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory( - Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); - - // Set up the event pipeline factory. - bootstrap.setPipelineFactory(new WebSocketServerPipelineFactory()); - - // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(port)); - - System.out.println("Web socket server started at port " + port + '.'); - } - - public static void main(String[] args) { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8080; - } - new WebSocketServer(port).run(); - } - -} diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/html5/WebSocketServerPipelineFactory.java b/src/main/java/org/jboss/netty/example/http/websocketx/html5/WebSocketServerPipelineFactory.java deleted file mode 100644 index 406fa9bd2d..0000000000 --- a/src/main/java/org/jboss/netty/example/http/websocketx/html5/WebSocketServerPipelineFactory.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project 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. - */ -package org.jboss.netty.example.http.websocketx.html5; - -import static org.jboss.netty.channel.Channels.*; - -import org.jboss.netty.channel.ChannelPipeline; -import org.jboss.netty.channel.ChannelPipelineFactory; -import org.jboss.netty.handler.codec.http.HttpChunkAggregator; -import org.jboss.netty.handler.codec.http.HttpRequestDecoder; -import org.jboss.netty.handler.codec.http.HttpResponseEncoder; -import org.jboss.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; - -public class WebSocketServerPipelineFactory implements ChannelPipelineFactory { - public ChannelPipeline getPipeline() throws Exception { - // Create a default pipeline implementation. - ChannelPipeline pipeline = pipeline(); - pipeline.addLast("decoder", new HttpRequestDecoder()); - pipeline.addLast("aggregator", new HttpChunkAggregator(65536)); - pipeline.addLast("encoder", new HttpResponseEncoder()); - pipeline.addLast("handler", new WebSocketServerProtocolHandler("/websocket")); - pipeline.addLast("testFramehandler", new CustomTextFrameHandler()); - return pipeline; - } -} diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/server/WebSocketServer.java b/src/main/java/org/jboss/netty/example/http/websocketx/server/WebSocketServer.java index c067982eef..5eb0e46944 100644 --- a/src/main/java/org/jboss/netty/example/http/websocketx/server/WebSocketServer.java +++ b/src/main/java/org/jboss/netty/example/http/websocketx/server/WebSocketServer.java @@ -15,11 +15,13 @@ */ package org.jboss.netty.example.http.websocketx.server; -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.SelfSignedCertificate; + +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; /** * A HTTP server which serves Web Socket requests at: @@ -42,34 +44,30 @@ import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; */ public class WebSocketServer { - private final int port; + static final boolean SSL = System.getProperty("ssl") != null; + static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080")); - public WebSocketServer(int port) { - this.port = port; - } + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + SelfSignedCertificate ssc = new SelfSignedCertificate(); + sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); + } else { + sslCtx = null; + } - public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // Set up the event pipeline factory. - bootstrap.setPipelineFactory(new WebSocketServerPipelineFactory()); + bootstrap.setPipelineFactory(new WebSocketServerPipelineFactory(sslCtx)); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(port)); + bootstrap.bind(new InetSocketAddress(PORT)); - System.out.println("Web socket server started at port " + port + '.'); - System.out.println("Open your browser and navigate to http://localhost:" + port + '/'); - } - - public static void main(String[] args) { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8080; - } - new WebSocketServer(port).run(); + System.err.println("Web socket server started at port " + PORT + '.'); + System.err.println("Open your browser and navigate to http://localhost:" + PORT + '/'); } } diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/server/WebSocketServerHandler.java b/src/main/java/org/jboss/netty/example/http/websocketx/server/WebSocketServerHandler.java index 0ebcf3114c..6ef54bc373 100644 --- a/src/main/java/org/jboss/netty/example/http/websocketx/server/WebSocketServerHandler.java +++ b/src/main/java/org/jboss/netty/example/http/websocketx/server/WebSocketServerHandler.java @@ -33,8 +33,6 @@ import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame; import org.jboss.netty.handler.codec.http.websocketx.WebSocketFrame; import org.jboss.netty.handler.codec.http.websocketx.WebSocketServerHandshaker; import org.jboss.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory; -import org.jboss.netty.logging.InternalLogger; -import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.CharsetUtil; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*; @@ -47,14 +45,13 @@ import static org.jboss.netty.handler.codec.http.HttpVersion.*; * Handles handshakes and messages */ public class WebSocketServerHandler extends SimpleChannelUpstreamHandler { - private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketServerHandler.class); private static final String WEBSOCKET_PATH = "/websocket"; private WebSocketServerHandshaker handshaker; @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { Object msg = e.getMessage(); if (msg instanceof HttpRequest) { handleHttpRequest(ctx, (HttpRequest) msg); @@ -63,7 +60,7 @@ public class WebSocketServerHandler extends SimpleChannelUpstreamHandler { } } - private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) throws Exception { + private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) { // Allow only GET methods. if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN)); @@ -101,7 +98,6 @@ public class WebSocketServerHandler extends SimpleChannelUpstreamHandler { } private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { - // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.getChannel(), (CloseWebSocketFrame) frame); @@ -112,15 +108,13 @@ public class WebSocketServerHandler extends SimpleChannelUpstreamHandler { return; } if (!(frame instanceof TextWebSocketFrame)) { - throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() - .getName())); + throw new UnsupportedOperationException( + String.format("%s frame types not supported", frame.getClass().getName())); } // Send the uppercase string back. String request = ((TextWebSocketFrame) frame).getText(); - if (logger.isDebugEnabled()) { - logger.debug(String.format("Channel %s received %s", ctx.getChannel().getId(), request)); - } + System.err.println(String.format("Channel %s received %s", ctx.getChannel().getId(), request)); ctx.getChannel().write(new TextWebSocketFrame(request.toUpperCase())); } @@ -139,7 +133,7 @@ public class WebSocketServerHandler extends SimpleChannelUpstreamHandler { } @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { e.getCause().printStackTrace(); e.getChannel().close(); } diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/server/WebSocketServerPipelineFactory.java b/src/main/java/org/jboss/netty/example/http/websocketx/server/WebSocketServerPipelineFactory.java index 90e84e4c96..00781ae6c1 100644 --- a/src/main/java/org/jboss/netty/example/http/websocketx/server/WebSocketServerPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/http/websocketx/server/WebSocketServerPipelineFactory.java @@ -15,20 +15,29 @@ */ package org.jboss.netty.example.http.websocketx.server; -import static org.jboss.netty.channel.Channels.*; - import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; +import org.jboss.netty.channel.Channels; import org.jboss.netty.handler.codec.http.HttpChunkAggregator; import org.jboss.netty.handler.codec.http.HttpRequestDecoder; import org.jboss.netty.handler.codec.http.HttpResponseEncoder; +import org.jboss.netty.handler.ssl.SslContext; /** */ public class WebSocketServerPipelineFactory implements ChannelPipelineFactory { - public ChannelPipeline getPipeline() throws Exception { - // Create a default pipeline implementation. - ChannelPipeline pipeline = pipeline(); + + private final SslContext sslCtx; + + public WebSocketServerPipelineFactory(SslContext sslCtx) { + this.sslCtx = sslCtx; + } + + public ChannelPipeline getPipeline() { + ChannelPipeline pipeline = Channels.pipeline(); + if (sslCtx != null) { + pipeline.addLast("ssl", sslCtx.newHandler()); + } pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("aggregator", new HttpChunkAggregator(65536)); pipeline.addLast("encoder", new HttpResponseEncoder()); diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServer.java b/src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServer.java deleted file mode 100644 index dc51408609..0000000000 --- a/src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServer.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project 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. - */ -package org.jboss.netty.example.http.websocketx.sslserver; - -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - -import org.jboss.netty.bootstrap.ServerBootstrap; -import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; - -/** - * A HTTP server which serves Web Socket requests at: - * - * https://localhost:8081/websocket - * - * Open your browser at https://localhost:8081/, then the demo page will be loaded and a Web Socket connection will be - * made automatically. - * - * This server illustrates support for the different web socket specification versions and will work with: - * - *
    - *
  • Safari 5+ (draft-ietf-hybi-thewebsocketprotocol-00) - *
  • Chrome 6-13 (draft-ietf-hybi-thewebsocketprotocol-00) - *
  • Chrome 14+ (draft-ietf-hybi-thewebsocketprotocol-10) - *
  • Chrome 16+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17) - *
  • Firefox 7+ (draft-ietf-hybi-thewebsocketprotocol-10) - *
- */ -public class WebSocketSslServer { - - private final int port; - - public WebSocketSslServer(int port) { - this.port = port; - } - - public void run() { - // Configure the server. - ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory( - Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); - - // Set up the event pipeline factory. - bootstrap.setPipelineFactory(new WebSocketSslServerPipelineFactory()); - - // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(port)); - - System.out.println("Web socket server started at port " + port + '.'); - System.out.println("Open your browser and navigate to https://localhost:" + port + '/'); - } - - public static void main(String[] args) { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8443; - } - - String keyStoreFilePath = System.getProperty("keystore.file.path"); - if (keyStoreFilePath == null || keyStoreFilePath.length() == 0) { - System.out.println("ERROR: System property keystore.file.path not set. Exiting now!"); - System.exit(1); - } - - String keyStoreFilePassword = System.getProperty("keystore.file.password"); - if (keyStoreFilePassword == null || keyStoreFilePassword.length() == 0) { - System.out.println("ERROR: System property keystore.file.password not set. Exiting now!"); - System.exit(1); - } - - new WebSocketSslServer(port).run(); - } -} diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServerHandler.java b/src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServerHandler.java deleted file mode 100644 index 9c4fcd2642..0000000000 --- a/src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServerHandler.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project 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. - */ -package org.jboss.netty.example.http.websocketx.sslserver; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.jboss.netty.channel.ChannelFuture; -import org.jboss.netty.channel.ChannelFutureListener; -import org.jboss.netty.channel.ChannelHandlerContext; -import org.jboss.netty.channel.ExceptionEvent; -import org.jboss.netty.channel.MessageEvent; -import org.jboss.netty.channel.SimpleChannelUpstreamHandler; -import org.jboss.netty.example.http.websocketx.server.WebSocketServerIndexPage; -import org.jboss.netty.handler.codec.http.DefaultHttpResponse; -import org.jboss.netty.handler.codec.http.HttpRequest; -import org.jboss.netty.handler.codec.http.HttpResponse; -import org.jboss.netty.handler.codec.http.websocketx.CloseWebSocketFrame; -import org.jboss.netty.handler.codec.http.websocketx.PingWebSocketFrame; -import org.jboss.netty.handler.codec.http.websocketx.PongWebSocketFrame; -import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame; -import org.jboss.netty.handler.codec.http.websocketx.WebSocketFrame; -import org.jboss.netty.handler.codec.http.websocketx.WebSocketServerHandshaker; -import org.jboss.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory; -import org.jboss.netty.logging.InternalLogger; -import org.jboss.netty.logging.InternalLoggerFactory; -import org.jboss.netty.util.CharsetUtil; - -import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*; -import static org.jboss.netty.handler.codec.http.HttpHeaders.*; -import static org.jboss.netty.handler.codec.http.HttpMethod.*; -import static org.jboss.netty.handler.codec.http.HttpResponseStatus.*; -import static org.jboss.netty.handler.codec.http.HttpVersion.*; - -/** - * Handles handshakes and messages - */ -public class WebSocketSslServerHandler extends SimpleChannelUpstreamHandler { - private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketSslServerHandler.class); - - private static final String WEBSOCKET_PATH = "/websocket"; - - private WebSocketServerHandshaker handshaker; - - @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { - Object msg = e.getMessage(); - if (msg instanceof HttpRequest) { - handleHttpRequest(ctx, (HttpRequest) msg); - } else if (msg instanceof WebSocketFrame) { - handleWebSocketFrame(ctx, (WebSocketFrame) msg); - } - } - - private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) throws Exception { - // Allow only GET methods. - if (req.getMethod() != GET) { - sendHttpResponse(ctx, req, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN)); - return; - } - - // Send the demo page and favicon.ico - if ("/".equals(req.getUri())) { - HttpResponse res = new DefaultHttpResponse(HTTP_1_1, OK); - - ChannelBuffer content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req)); - - res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); - setContentLength(res, content.readableBytes()); - - res.setContent(content); - sendHttpResponse(ctx, req, res); - return; - } - - if ("/favicon.ico".equals(req.getUri())) { - HttpResponse res = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND); - sendHttpResponse(ctx, req, res); - return; - } - - // Handshake - WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( - getWebSocketLocation(req), null, false); - handshaker = wsFactory.newHandshaker(req); - if (handshaker == null) { - wsFactory.sendUnsupportedWebSocketVersionResponse(ctx.getChannel()); - } else { - handshaker.handshake(ctx.getChannel(), req).addListener(WebSocketServerHandshaker.HANDSHAKE_LISTENER); - } - } - - private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { - - // Check for closing frame - if (frame instanceof CloseWebSocketFrame) { - handshaker.close(ctx.getChannel(), (CloseWebSocketFrame) frame); - return; - } - if (frame instanceof PingWebSocketFrame) { - ctx.getChannel().write(new PongWebSocketFrame(frame.getBinaryData())); - return; - } - if (!(frame instanceof TextWebSocketFrame)) { - throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() - .getName())); - } - - // Send the uppercase string back. - String request = ((TextWebSocketFrame) frame).getText(); - if (logger.isDebugEnabled()) { - logger.debug(String.format("Channel %s received %s", ctx.getChannel().getId(), request)); - } - ctx.getChannel().write(new TextWebSocketFrame(request.toUpperCase())); - } - - private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) { - // Generate an error page if response status code is not OK (200). - if (res.getStatus().getCode() != 200) { - res.setContent(ChannelBuffers.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8)); - setContentLength(res, res.getContent().readableBytes()); - } - - // Send the response and close the connection if necessary. - ChannelFuture f = ctx.getChannel().write(res); - if (!isKeepAlive(req) || res.getStatus().getCode() != 200) { - f.addListener(ChannelFutureListener.CLOSE); - } - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { - e.getCause().printStackTrace(); - e.getChannel().close(); - } - - private static String getWebSocketLocation(HttpRequest req) { - return "wss://" + req.headers().get(HOST) + WEBSOCKET_PATH; - } -} diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServerPipelineFactory.java b/src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServerPipelineFactory.java deleted file mode 100644 index 4972a2b688..0000000000 --- a/src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServerPipelineFactory.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project 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. - */ -package org.jboss.netty.example.http.websocketx.sslserver; - -import static org.jboss.netty.channel.Channels.*; - -import javax.net.ssl.SSLEngine; - -import org.jboss.netty.channel.ChannelPipeline; -import org.jboss.netty.channel.ChannelPipelineFactory; -import org.jboss.netty.handler.codec.http.HttpChunkAggregator; -import org.jboss.netty.handler.codec.http.HttpRequestDecoder; -import org.jboss.netty.handler.codec.http.HttpResponseEncoder; -import org.jboss.netty.handler.ssl.SslHandler; - -/** - */ -public class WebSocketSslServerPipelineFactory implements ChannelPipelineFactory { - public ChannelPipeline getPipeline() throws Exception { - // Create a default pipeline implementation. - ChannelPipeline pipeline = pipeline(); - - SSLEngine engine = WebSocketSslServerSslContext.getInstance().getServerContext().createSSLEngine(); - engine.setUseClientMode(false); - pipeline.addLast("ssl", new SslHandler(engine)); - - pipeline.addLast("decoder", new HttpRequestDecoder()); - pipeline.addLast("aggregator", new HttpChunkAggregator(65536)); - pipeline.addLast("encoder", new HttpResponseEncoder()); - pipeline.addLast("handler", new WebSocketSslServerHandler()); - return pipeline; - } -} diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServerSslContext.java b/src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServerSslContext.java deleted file mode 100644 index ffead142dc..0000000000 --- a/src/main/java/org/jboss/netty/example/http/websocketx/sslserver/WebSocketSslServerSslContext.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project 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. - */ -package org.jboss.netty.example.http.websocketx.sslserver; - -import org.jboss.netty.logging.InternalLogger; -import org.jboss.netty.logging.InternalLoggerFactory; - -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import java.io.FileInputStream; -import java.security.KeyStore; -import java.security.Security; - -/** - * Creates a {@link SSLContext} for just server certificates. - */ -public final class WebSocketSslServerSslContext { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketSslServerSslContext.class); - private static final String PROTOCOL = "TLS"; - - private final SSLContext _serverContext; - - /** - * Returns the singleton instance for this class - */ - public static WebSocketSslServerSslContext getInstance() { - return SingletonHolder.INSTANCE; - } - - /** - * SingletonHolder is loaded on the first execution of Singleton.getInstance() or the first access to - * SingletonHolder.INSTANCE, not before. - * - * See http://en.wikipedia.org/wiki/Singleton_pattern - */ - private interface SingletonHolder { - WebSocketSslServerSslContext INSTANCE = new WebSocketSslServerSslContext(); - } - - /** - * Constructor for singleton - */ - private WebSocketSslServerSslContext() { - SSLContext serverContext = null; - try { - // Key store (Server side certificate) - String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); - if (algorithm == null) { - algorithm = "SunX509"; - } - - try { - String keyStoreFilePath = System.getProperty("keystore.file.path"); - String keyStoreFilePassword = System.getProperty("keystore.file.password"); - - KeyStore ks = KeyStore.getInstance("JKS"); - FileInputStream fin = new FileInputStream(keyStoreFilePath); - ks.load(fin, keyStoreFilePassword.toCharArray()); - - // Set up key manager factory to use our key store - // Assume key password is the same as the key store file - // password - KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); - kmf.init(ks, keyStoreFilePassword.toCharArray()); - - // Initialise the SSLContext to work with our key managers. - serverContext = SSLContext.getInstance(PROTOCOL); - serverContext.init(kmf.getKeyManagers(), null, null); - } catch (Exception e) { - throw new Error("Failed to initialize the server-side SSLContext", e); - } - } catch (Exception ex) { - if (logger.isErrorEnabled()) { - logger.error("Error initializing SslContextManager. " + ex.getMessage(), ex); - } - System.exit(1); - } finally { - _serverContext = serverContext; - } - } - - /** - * Returns the server context with server side key store - */ - public SSLContext getServerContext() { - return _serverContext; - } -} diff --git a/src/main/java/org/jboss/netty/example/http/websocketx/sslserver/package-info.java b/src/main/java/org/jboss/netty/example/http/websocketx/sslserver/package-info.java deleted file mode 100644 index 67f2f9ecb5..0000000000 --- a/src/main/java/org/jboss/netty/example/http/websocketx/sslserver/package-info.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project 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 package contains an example web socket web server with server SSL. - *

To run this example, follow the steps below: - *

- *
Step 1. Generate Your Key - *
- * {@code keytool -genkey -keystore mySrvKeystore -keyalg RSA}. - * Make sure that you set the key password to be the same the key file password. - *
Step 2. Specify your key store file and password as system properties - *
- * {@code -Dkeystore.file.path= -Dkeystore.file.password=} - *
Step 3. Run WebSocketSslServer as a Java application - *
- * Once started, you can test the web server against your browser by navigating to https://localhost:8081/ - *
- *

To find out more about setting up key stores, refer to this - * giude. - */ -package org.jboss.netty.example.http.websocketx.sslserver; - diff --git a/src/main/java/org/jboss/netty/example/local/LocalExample.java b/src/main/java/org/jboss/netty/example/local/LocalExample.java index 098e8155b4..429133fe6a 100644 --- a/src/main/java/org/jboss/netty/example/local/LocalExample.java +++ b/src/main/java/org/jboss/netty/example/local/LocalExample.java @@ -15,10 +15,6 @@ */ package org.jboss.netty.example.local; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelFuture; @@ -34,76 +30,69 @@ import org.jboss.netty.handler.codec.string.StringEncoder; import org.jboss.netty.handler.logging.LoggingHandler; import org.jboss.netty.logging.InternalLogLevel; -public class LocalExample { +import java.io.BufferedReader; +import java.io.InputStreamReader; - private final String port; +public final class LocalExample { - public LocalExample(String port) { - this.port = port; - } - - public void run() throws IOException { - // Address to bind on / connect to. - LocalAddress socketAddress = new LocalAddress(port); - - // Configure the server. - ServerBootstrap sb = new ServerBootstrap( - new DefaultLocalServerChannelFactory()); - - // Set up the default server-side event pipeline. - EchoServerHandler handler = new EchoServerHandler(); - sb.getPipeline().addLast("handler", handler); - - // Start up the server. - sb.bind(socketAddress); - - // Configure the client. - ClientBootstrap cb = new ClientBootstrap( - new DefaultLocalClientChannelFactory()); - - // Set up the client-side pipeline factory. - cb.setPipelineFactory(new ChannelPipelineFactory() { - public ChannelPipeline getPipeline() throws Exception { - return Channels.pipeline( - new StringDecoder(), - new StringEncoder(), - new LoggingHandler(InternalLogLevel.INFO)); - } - }); - - // Make the connection attempt to the server. - ChannelFuture channelFuture = cb.connect(socketAddress); - channelFuture.awaitUninterruptibly(); - - // Read commands from the stdin. - System.out.println("Enter text (quit to end)"); - ChannelFuture lastWriteFuture = null; - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - for (; ;) { - String line = in.readLine(); - if (line == null || "quit".equalsIgnoreCase(line)) { - break; - } - - // Sends the received line to the server. - lastWriteFuture = channelFuture.getChannel().write(line); - } - - // Wait until all messages are flushed before closing the channel. - if (lastWriteFuture != null) { - lastWriteFuture.awaitUninterruptibly(); - } - channelFuture.getChannel().close(); - - // Wait until the connection is closed or the connection attempt fails. - channelFuture.getChannel().getCloseFuture().awaitUninterruptibly(); - - // Release all resources used by the local transport. - cb.releaseExternalResources(); - sb.releaseExternalResources(); - } + static final String PORT = System.getProperty("port", "test_port"); public static void main(String[] args) throws Exception { - new LocalExample("1").run(); + // Address to bind on / connect to. + LocalAddress socketAddress = new LocalAddress(PORT); + + // Create the bootstraps for both client and server side. + ServerBootstrap sb = new ServerBootstrap(new DefaultLocalServerChannelFactory()); + ClientBootstrap cb = new ClientBootstrap(new DefaultLocalClientChannelFactory()); + + try { + // Set up the default server-side event pipeline. + EchoServerHandler handler = new EchoServerHandler(); + sb.getPipeline().addLast("handler", handler); + + // Start up the server. + sb.bind(socketAddress); + + // Set up the client-side pipeline factory. + cb.setPipelineFactory(new ChannelPipelineFactory() { + public ChannelPipeline getPipeline() { + return Channels.pipeline( + new StringDecoder(), + new StringEncoder(), + new LoggingHandler(InternalLogLevel.INFO)); + } + }); + + // Make the connection attempt to the server. + ChannelFuture channelFuture = cb.connect(socketAddress); + channelFuture.sync(); + + // Read commands from the stdin. + System.err.println("Enter text (quit to end)"); + ChannelFuture lastWriteFuture = null; + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + for (;;) { + String line = in.readLine(); + if (line == null || "quit".equalsIgnoreCase(line)) { + break; + } + + // Sends the received line to the server. + lastWriteFuture = channelFuture.getChannel().write(line); + } + + // Wait until all messages are flushed before closing the channel. + if (lastWriteFuture != null) { + lastWriteFuture.sync(); + } + channelFuture.getChannel().close(); + + // Wait until the connection is closed or the connection attempt fails. + channelFuture.getChannel().getCloseFuture().sync(); + } finally { + // Release all resources used by the local transport. + cb.releaseExternalResources(); + sb.releaseExternalResources(); + } } } diff --git a/src/main/java/org/jboss/netty/example/local/LocalExampleMultithreaded.java b/src/main/java/org/jboss/netty/example/local/LocalExampleMultithreaded.java deleted file mode 100644 index b41da8dd6e..0000000000 --- a/src/main/java/org/jboss/netty/example/local/LocalExampleMultithreaded.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project 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. - */ -package org.jboss.netty.example.local; - -import java.util.concurrent.TimeUnit; - -import org.jboss.netty.bootstrap.ClientBootstrap; -import org.jboss.netty.bootstrap.ServerBootstrap; -import org.jboss.netty.channel.ChannelFuture; -import org.jboss.netty.channel.ChannelPipeline; -import org.jboss.netty.channel.ChannelPipelineFactory; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.channel.local.DefaultLocalClientChannelFactory; -import org.jboss.netty.channel.local.DefaultLocalServerChannelFactory; -import org.jboss.netty.channel.local.LocalAddress; -import org.jboss.netty.handler.codec.string.StringDecoder; -import org.jboss.netty.handler.codec.string.StringEncoder; -import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; -import org.jboss.netty.handler.logging.LoggingHandler; -import org.jboss.netty.logging.InternalLogLevel; - -public class LocalExampleMultithreaded { - - private final String port; - - public LocalExampleMultithreaded(String port) { - this.port = port; - } - - public void run() { - LocalAddress socketAddress = new LocalAddress(port); - - OrderedMemoryAwareThreadPoolExecutor eventExecutor = - new OrderedMemoryAwareThreadPoolExecutor( - 5, 1000000, 10000000, 100, - TimeUnit.MILLISECONDS); - - ServerBootstrap sb = new ServerBootstrap( - new DefaultLocalServerChannelFactory()); - - sb.setPipelineFactory(new LocalServerPipelineFactory(eventExecutor)); - sb.bind(socketAddress); - - ClientBootstrap cb = new ClientBootstrap( - new DefaultLocalClientChannelFactory()); - - cb.setPipelineFactory(new ChannelPipelineFactory() { - public ChannelPipeline getPipeline() throws Exception { - return Channels.pipeline( - new StringDecoder(), - new StringEncoder(), - new LoggingHandler(InternalLogLevel.INFO)); - } - }); - - // Read commands from array - String[] commands = { "First", "Second", "Third", "quit" }; - for (int j = 0; j < 5 ; j++) { - System.err.println("Start " + j); - ChannelFuture channelFuture = cb.connect(socketAddress); - channelFuture.awaitUninterruptibly(); - if (! channelFuture.isSuccess()) { - System.err.println("CANNOT CONNECT"); - channelFuture.getCause().printStackTrace(); - break; - } - ChannelFuture lastWriteFuture = null; - for (String line: commands) { - // Sends the received line to the server. - lastWriteFuture = channelFuture.getChannel().write(line); - } - - // Wait until all messages are flushed before closing the channel. - if (lastWriteFuture != null) { - lastWriteFuture.awaitUninterruptibly(); - } - channelFuture.getChannel().close(); - // Wait until the connection is closed or the connection attempt fails. - channelFuture.getChannel().getCloseFuture().awaitUninterruptibly(); - System.err.println("End " + j); - } - - // Release all resources - cb.releaseExternalResources(); - sb.releaseExternalResources(); - eventExecutor.shutdownNow(); - } - - public static void main(String[] args) throws Exception { - new LocalExampleMultithreaded("1").run(); - } -} diff --git a/src/main/java/org/jboss/netty/example/local/LocalServerPipelineFactory.java b/src/main/java/org/jboss/netty/example/local/LocalServerPipelineFactory.java deleted file mode 100644 index 5824938d29..0000000000 --- a/src/main/java/org/jboss/netty/example/local/LocalServerPipelineFactory.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project 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. - */ -package org.jboss.netty.example.local; - -import org.jboss.netty.channel.ChannelDownstreamHandler; -import org.jboss.netty.channel.ChannelEvent; -import org.jboss.netty.channel.ChannelHandlerContext; -import org.jboss.netty.channel.ChannelPipeline; -import org.jboss.netty.channel.ChannelPipelineFactory; -import org.jboss.netty.channel.ChannelUpstreamHandler; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.channel.MessageEvent; -import org.jboss.netty.handler.codec.string.StringDecoder; -import org.jboss.netty.handler.codec.string.StringEncoder; -import org.jboss.netty.handler.execution.ExecutionHandler; - -import java.util.concurrent.Executor; - -public class LocalServerPipelineFactory implements ChannelPipelineFactory { - - private final ExecutionHandler executionHandler; - - public LocalServerPipelineFactory(Executor eventExecutor) { - executionHandler = new ExecutionHandler(eventExecutor); - } - - public ChannelPipeline getPipeline() throws Exception { - final ChannelPipeline pipeline = Channels.pipeline(); - pipeline.addLast("decoder", new StringDecoder()); - pipeline.addLast("encoder", new StringEncoder()); - pipeline.addLast("executor", executionHandler); - pipeline.addLast("handler", new EchoCloseServerHandler()); - return pipeline; - } - - static class EchoCloseServerHandler implements ChannelUpstreamHandler, ChannelDownstreamHandler { - public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) - throws Exception { - if (e instanceof MessageEvent) { - final MessageEvent evt = (MessageEvent) e; - String msg = (String) evt.getMessage(); - if ("quit".equalsIgnoreCase(msg)) { - Channels.close(e.getChannel()); - return; - } - } - ctx.sendUpstream(e); - } - - public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) { - if (e instanceof MessageEvent) { - final MessageEvent evt = (MessageEvent) e; - String msg = (String) evt.getMessage(); - if ("quit".equalsIgnoreCase(msg)) { - Channels.close(e.getChannel()); - return; - } - System.err.println("SERVER:" + msg); - // Write back - Channels.write(e.getChannel(), msg); - } - ctx.sendDownstream(e); - } - } -} diff --git a/src/main/java/org/jboss/netty/example/localtime/LocalTimeClient.java b/src/main/java/org/jboss/netty/example/localtime/LocalTimeClient.java index a36d475cd9..170b2e017a 100644 --- a/src/main/java/org/jboss/netty/example/localtime/LocalTimeClient.java +++ b/src/main/java/org/jboss/netty/example/localtime/LocalTimeClient.java @@ -19,108 +19,65 @@ import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.InsecureTrustManagerFactory; import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; +import java.util.Arrays; import java.util.List; import java.util.concurrent.Executors; -import java.util.regex.Pattern; /** * Sends a list of continent/city pairs to a {@link LocalTimeServer} to * get the local times of the specified cities. */ -public class LocalTimeClient { +public final class LocalTimeClient { - private final String host; - private final int port; - private final Collection cities; + static final boolean SSL = System.getProperty("ssl") != null; + static final String HOST = System.getProperty("host", "127.0.0.1"); + static final int PORT = Integer.parseInt(System.getProperty("port", "8463")); + static final List CITIES = Arrays.asList(System.getProperty( + "cities", "Asia/Seoul,Europe/Berlin,America/Los_Angeles").split(",")); - public LocalTimeClient(String host, int port, Collection cities) { - this.host = host; - this.port = port; - this.cities = new ArrayList(); - this.cities.addAll(cities); - } + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); + } else { + sslCtx = null; + } - public void run() { - // Set up. ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); + try { + // Configure the event pipeline factory. + bootstrap.setPipelineFactory(new LocalTimeClientPipelineFactory(sslCtx)); - // Configure the event pipeline factory. - bootstrap.setPipelineFactory(new LocalTimeClientPipelineFactory()); + // Make a new connection. + ChannelFuture connectFuture = bootstrap.connect(new InetSocketAddress(HOST, PORT)); - // Make a new connection. - ChannelFuture connectFuture = - bootstrap.connect(new InetSocketAddress(host, port)); + // Wait until the connection is made successfully. + Channel channel = connectFuture.sync().getChannel(); - // Wait until the connection is made successfully. - Channel channel = connectFuture.awaitUninterruptibly().getChannel(); + // Get the handler instance to initiate the request. + LocalTimeClientHandler handler = channel.getPipeline().get(LocalTimeClientHandler.class); - // Get the handler instance to initiate the request. - LocalTimeClientHandler handler = - channel.getPipeline().get(LocalTimeClientHandler.class); + // Request and get the response. + List response = handler.getLocalTimes(CITIES); - // Request and get the response. - List response = handler.getLocalTimes(cities); - // Close the connection. - channel.close().awaitUninterruptibly(); + // Close the connection. + channel.close().sync(); - // Shut down all thread pools to exit. - bootstrap.releaseExternalResources(); - - // Print the response at last but not least. - Iterator i1 = cities.iterator(); - Iterator i2 = response.iterator(); - while (i1.hasNext()) { - System.out.format("%28s: %s%n", i1.next(), i2.next()); - } - } - - public static void main(String[] args) throws Exception { - // Print usage if necessary. - if (args.length < 3) { - printUsage(); - return; - } - - // Parse options. - String host = args[0]; - int port = Integer.parseInt(args[1]); - Collection cities = parseCities(args, 2); - if (cities == null) { - return; - } - - new LocalTimeClient(host, port, cities).run(); - } - - private static void printUsage() { - System.err.println( - "Usage: " + LocalTimeClient.class.getSimpleName() + - " ..."); - System.err.println( - "Example: " + LocalTimeClient.class.getSimpleName() + - " localhost 8080 America/New_York Asia/Seoul"); - } - - private static final Pattern CITY_PATTERN = Pattern.compile("^[_A-Za-z]+/[_A-Za-z]+$"); - - private static List parseCities(String[] args, int offset) { - List cities = new ArrayList(); - for (int i = offset; i < args.length; i ++) { - if (!CITY_PATTERN.matcher(args[i]).matches()) { - System.err.println("Syntax error: '" + args[i] + '\''); - printUsage(); - return null; + // Print the response at last but not least. + for (int i = 0; i < CITIES.size(); i ++) { + System.out.format("%28s: %s%n", CITIES.get(i), response.get(i)); } - cities.add(args[i].trim()); + } finally { + // Shut down all thread pools to exit. + bootstrap.releaseExternalResources(); } - return cities; } } diff --git a/src/main/java/org/jboss/netty/example/localtime/LocalTimeClientHandler.java b/src/main/java/org/jboss/netty/example/localtime/LocalTimeClientHandler.java index d230ec142e..c0c882f668 100644 --- a/src/main/java/org/jboss/netty/example/localtime/LocalTimeClientHandler.java +++ b/src/main/java/org/jboss/netty/example/localtime/LocalTimeClientHandler.java @@ -34,15 +34,10 @@ import java.util.Formatter; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; -import java.util.logging.Level; -import java.util.logging.Logger; import java.util.regex.Pattern; public class LocalTimeClientHandler extends SimpleChannelUpstreamHandler { - private static final Logger logger = Logger.getLogger( - LocalTimeClientHandler.class.getName()); - private static final Pattern DELIM = Pattern.compile("/"); // Stateful properties @@ -94,35 +89,27 @@ public class LocalTimeClientHandler extends SimpleChannelUpstreamHandler { } @Override - public void handleUpstream( - ChannelHandlerContext ctx, ChannelEvent e) throws Exception { + public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { - logger.info(e.toString()); + System.err.println(e); } super.handleUpstream(ctx, e); } @Override - public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) - throws Exception { + public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { channel = e.getChannel(); super.channelOpen(ctx, e); } @Override - public void messageReceived( - ChannelHandlerContext ctx, final MessageEvent e) { - boolean offered = answer.offer((LocalTimes) e.getMessage()); - assert offered; + public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) { + answer.add((LocalTimes) e.getMessage()); } @Override - public void exceptionCaught( - ChannelHandlerContext ctx, ExceptionEvent e) { - logger.log( - Level.WARNING, - "Unexpected exception from downstream.", - e.getCause()); + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { + e.getCause().printStackTrace(); e.getChannel().close(); } } diff --git a/src/main/java/org/jboss/netty/example/localtime/LocalTimeClientPipelineFactory.java b/src/main/java/org/jboss/netty/example/localtime/LocalTimeClientPipelineFactory.java index 4b8ef516d9..185d9b1ff8 100644 --- a/src/main/java/org/jboss/netty/example/localtime/LocalTimeClientPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/localtime/LocalTimeClientPipelineFactory.java @@ -15,19 +15,29 @@ */ package org.jboss.netty.example.localtime; -import static org.jboss.netty.channel.Channels.*; - import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.protobuf.ProtobufDecoder; import org.jboss.netty.handler.codec.protobuf.ProtobufEncoder; import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; +import org.jboss.netty.handler.ssl.SslContext; + +import static org.jboss.netty.channel.Channels.*; public class LocalTimeClientPipelineFactory implements ChannelPipelineFactory { - public ChannelPipeline getPipeline() throws Exception { + private final SslContext sslCtx; + + public LocalTimeClientPipelineFactory(SslContext sslCtx) { + this.sslCtx = sslCtx; + } + + public ChannelPipeline getPipeline() { ChannelPipeline p = pipeline(); + if (sslCtx != null) { + p.addLast("ssl", sslCtx.newHandler(LocalTimeClient.HOST, LocalTimeClient.PORT)); + } p.addLast("frameDecoder", new ProtobufVarint32FrameDecoder()); p.addLast("protobufDecoder", new ProtobufDecoder(LocalTimeProtocol.LocalTimes.getDefaultInstance())); diff --git a/src/main/java/org/jboss/netty/example/localtime/LocalTimeProtocol.java b/src/main/java/org/jboss/netty/example/localtime/LocalTimeProtocol.java index aab94f4e84..83d049ade9 100644 --- a/src/main/java/org/jboss/netty/example/localtime/LocalTimeProtocol.java +++ b/src/main/java/org/jboss/netty/example/localtime/LocalTimeProtocol.java @@ -1,19 +1,3 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project 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. - */ - // Generated by the protocol buffer compiler. DO NOT EDIT! // source: src/main/java/org/jboss/netty/example/localtime/LocalTimeProtocol.proto @@ -25,31 +9,100 @@ public final class LocalTimeProtocol { public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } + /** + * Protobuf enum {@code org.jboss.netty.example.localtime.Continent} + */ public enum Continent implements com.google.protobuf.ProtocolMessageEnum { + /** + * AFRICA = 0; + */ AFRICA(0, 0), + /** + * AMERICA = 1; + */ AMERICA(1, 1), + /** + * ANTARCTICA = 2; + */ ANTARCTICA(2, 2), + /** + * ARCTIC = 3; + */ ARCTIC(3, 3), + /** + * ASIA = 4; + */ ASIA(4, 4), + /** + * ATLANTIC = 5; + */ ATLANTIC(5, 5), + /** + * AUSTRALIA = 6; + */ AUSTRALIA(6, 6), + /** + * EUROPE = 7; + */ EUROPE(7, 7), + /** + * INDIAN = 8; + */ INDIAN(8, 8), + /** + * MIDEAST = 9; + */ MIDEAST(9, 9), + /** + * PACIFIC = 10; + */ PACIFIC(10, 10), ; + /** + * AFRICA = 0; + */ public static final int AFRICA_VALUE = 0; + /** + * AMERICA = 1; + */ public static final int AMERICA_VALUE = 1; + /** + * ANTARCTICA = 2; + */ public static final int ANTARCTICA_VALUE = 2; + /** + * ARCTIC = 3; + */ public static final int ARCTIC_VALUE = 3; + /** + * ASIA = 4; + */ public static final int ASIA_VALUE = 4; + /** + * ATLANTIC = 5; + */ public static final int ATLANTIC_VALUE = 5; + /** + * AUSTRALIA = 6; + */ public static final int AUSTRALIA_VALUE = 6; + /** + * EUROPE = 7; + */ public static final int EUROPE_VALUE = 7; + /** + * INDIAN = 8; + */ public static final int INDIAN_VALUE = 8; + /** + * MIDEAST = 9; + */ public static final int MIDEAST_VALUE = 9; + /** + * PACIFIC = 10; + */ public static final int PACIFIC_VALUE = 10; @@ -97,9 +150,7 @@ public final class LocalTimeProtocol { return org.jboss.netty.example.localtime.LocalTimeProtocol.getDescriptor().getEnumTypes().get(0); } - private static final Continent[] VALUES = { - AFRICA, AMERICA, ANTARCTICA, ARCTIC, ASIA, ATLANTIC, AUSTRALIA, EUROPE, INDIAN, MIDEAST, PACIFIC, - }; + private static final Continent[] VALUES = values(); public static Continent valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { @@ -121,23 +172,68 @@ public final class LocalTimeProtocol { // @@protoc_insertion_point(enum_scope:org.jboss.netty.example.localtime.Continent) } + /** + * Protobuf enum {@code org.jboss.netty.example.localtime.DayOfWeek} + */ public enum DayOfWeek implements com.google.protobuf.ProtocolMessageEnum { + /** + * SUNDAY = 1; + */ SUNDAY(0, 1), + /** + * MONDAY = 2; + */ MONDAY(1, 2), + /** + * TUESDAY = 3; + */ TUESDAY(2, 3), + /** + * WEDNESDAY = 4; + */ WEDNESDAY(3, 4), + /** + * THURSDAY = 5; + */ THURSDAY(4, 5), + /** + * FRIDAY = 6; + */ FRIDAY(5, 6), + /** + * SATURDAY = 7; + */ SATURDAY(6, 7), ; + /** + * SUNDAY = 1; + */ public static final int SUNDAY_VALUE = 1; + /** + * MONDAY = 2; + */ public static final int MONDAY_VALUE = 2; + /** + * TUESDAY = 3; + */ public static final int TUESDAY_VALUE = 3; + /** + * WEDNESDAY = 4; + */ public static final int WEDNESDAY_VALUE = 4; + /** + * THURSDAY = 5; + */ public static final int THURSDAY_VALUE = 5; + /** + * FRIDAY = 6; + */ public static final int FRIDAY_VALUE = 6; + /** + * SATURDAY = 7; + */ public static final int SATURDAY_VALUE = 7; @@ -181,9 +277,7 @@ public final class LocalTimeProtocol { return org.jboss.netty.example.localtime.LocalTimeProtocol.getDescriptor().getEnumTypes().get(1); } - private static final DayOfWeek[] VALUES = { - SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, - }; + private static final DayOfWeek[] VALUES = values(); public static DayOfWeek valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { @@ -209,21 +303,42 @@ public final class LocalTimeProtocol { extends com.google.protobuf.MessageOrBuilder { // required .org.jboss.netty.example.localtime.Continent continent = 1; + /** + * required .org.jboss.netty.example.localtime.Continent continent = 1; + */ boolean hasContinent(); + /** + * required .org.jboss.netty.example.localtime.Continent continent = 1; + */ org.jboss.netty.example.localtime.LocalTimeProtocol.Continent getContinent(); // required string city = 2; + /** + * required string city = 2; + */ boolean hasCity(); - String getCity(); + /** + * required string city = 2; + */ + java.lang.String getCity(); + /** + * required string city = 2; + */ + com.google.protobuf.ByteString + getCityBytes(); } + /** + * Protobuf type {@code org.jboss.netty.example.localtime.Location} + */ public static final class Location extends com.google.protobuf.GeneratedMessage implements LocationOrBuilder { // Use Location.newBuilder() to construct. - private Location(Builder builder) { + private Location(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); + this.unknownFields = builder.getUnknownFields(); } - private Location(boolean noInit) {} + private Location(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Location defaultInstance; public static Location getDefaultInstance() { @@ -234,344 +349,32 @@ public final class LocalTimeProtocol { return defaultInstance; } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Location_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Location_fieldAccessorTable; - } - - private int bitField0_; - // required .org.jboss.netty.example.localtime.Continent continent = 1; - public static final int CONTINENT_FIELD_NUMBER = 1; - private org.jboss.netty.example.localtime.LocalTimeProtocol.Continent continent_; - public boolean hasContinent() { - return (bitField0_ & 0x00000001) == 0x00000001; - } - public org.jboss.netty.example.localtime.LocalTimeProtocol.Continent getContinent() { - return continent_; - } - - // required string city = 2; - public static final int CITY_FIELD_NUMBER = 2; - private java.lang.Object city_; - public boolean hasCity() { - return (bitField0_ & 0x00000002) == 0x00000002; - } - public String getCity() { - java.lang.Object ref = city_; - if (ref instanceof String) { - return (String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - if (com.google.protobuf.Internal.isValidUtf8(bs)) { - city_ = s; - } - return s; - } - } - private com.google.protobuf.ByteString getCityBytes() { - java.lang.Object ref = city_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8((String) ref); - city_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - private void initFields() { - continent_ = org.jboss.netty.example.localtime.LocalTimeProtocol.Continent.AFRICA; - city_ = ""; - } - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized != -1) { - return isInitialized == 1; - } - - if (!hasContinent()) { - memoizedIsInitialized = 0; - return false; - } - if (!hasCity()) { - memoizedIsInitialized = 0; - return false; - } - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - getSerializedSize(); - if ((bitField0_ & 0x00000001) == 0x00000001) { - output.writeEnum(1, continent_.getNumber()); - } - if ((bitField0_ & 0x00000002) == 0x00000002) { - output.writeBytes(2, getCityBytes()); - } - getUnknownFields().writeTo(output); - } - - private int memoizedSerializedSize = -1; - public int getSerializedSize() { - int size = memoizedSerializedSize; - if (size != -1) { - return size; - } - - size = 0; - if ((bitField0_ & 0x00000001) == 0x00000001) { - size += com.google.protobuf.CodedOutputStream - .computeEnumSize(1, continent_.getNumber()); - } - if ((bitField0_ & 0x00000002) == 0x00000002) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(2, getCityBytes()); - } - size += getUnknownFields().getSerializedSize(); - memoizedSerializedSize = size; - return size; - } - - private static final long serialVersionUID = 0L; + private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override - protected java.lang.Object writeReplace() - throws java.io.ObjectStreamException { - return super.writeReplace(); + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; } - - public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data).buildParsed(); - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data, extensionRegistry) - .buildParsed(); - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data).buildParsed(); - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data, extensionRegistry) - .buildParsed(); - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom(java.io.InputStream input) - throws java.io.IOException { - return newBuilder().mergeFrom(input).buildParsed(); - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return newBuilder().mergeFrom(input, extensionRegistry) - .buildParsed(); - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - Builder builder = newBuilder(); - if (builder.mergeDelimitedFrom(input)) { - return builder.buildParsed(); - } else { - return null; - } - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - Builder builder = newBuilder(); - if (builder.mergeDelimitedFrom(input, extensionRegistry)) { - return builder.buildParsed(); - } else { - return null; - } - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return newBuilder().mergeFrom(input).buildParsed(); - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( + private Location( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return newBuilder().mergeFrom(input, extensionRegistry) - .buildParsed(); - } - - public static Builder newBuilder() { return Builder.create(); } - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder(org.jboss.netty.example.localtime.LocalTimeProtocol.Location prototype) { - return newBuilder().mergeFrom(prototype); - } - public Builder toBuilder() { return newBuilder(this); } - - @java.lang.Override - protected Builder newBuilderForType( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder - implements org.jboss.netty.example.localtime.LocalTimeProtocol.LocationOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Location_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Location_fieldAccessorTable; - } - - // Construct using org.jboss.netty.example.localtime.LocalTimeProtocol.Location.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { - } - } - private static Builder create() { - return new Builder(); - } - - public Builder clear() { - super.clear(); - continent_ = org.jboss.netty.example.localtime.LocalTimeProtocol.Continent.AFRICA; - bitField0_ = bitField0_ & ~0x00000001; - city_ = ""; - bitField0_ = bitField0_ & ~0x00000002; - return this; - } - - public Builder clone() { - return create().mergeFrom(buildPartial()); - } - - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.Location.getDescriptor(); - } - - public org.jboss.netty.example.localtime.LocalTimeProtocol.Location getDefaultInstanceForType() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.Location.getDefaultInstance(); - } - - public org.jboss.netty.example.localtime.LocalTimeProtocol.Location build() { - org.jboss.netty.example.localtime.LocalTimeProtocol.Location result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - private org.jboss.netty.example.localtime.LocalTimeProtocol.Location buildParsed() - throws com.google.protobuf.InvalidProtocolBufferException { - org.jboss.netty.example.localtime.LocalTimeProtocol.Location result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException( - result).asInvalidProtocolBufferException(); - } - return result; - } - - public org.jboss.netty.example.localtime.LocalTimeProtocol.Location buildPartial() { - org.jboss.netty.example.localtime.LocalTimeProtocol.Location result = new org.jboss.netty.example.localtime.LocalTimeProtocol.Location(this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - if ((from_bitField0_ & 0x00000001) == 0x00000001) { - to_bitField0_ |= 0x00000001; - } - result.continent_ = continent_; - if ((from_bitField0_ & 0x00000002) == 0x00000002) { - to_bitField0_ |= 0x00000002; - } - result.city_ = city_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.jboss.netty.example.localtime.LocalTimeProtocol.Location) { - return mergeFrom((org.jboss.netty.example.localtime.LocalTimeProtocol.Location)other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(org.jboss.netty.example.localtime.LocalTimeProtocol.Location other) { - if (other == org.jboss.netty.example.localtime.LocalTimeProtocol.Location.getDefaultInstance()) { - return this; - } - if (other.hasContinent()) { - setContinent(other.getContinent()); - } - if (other.hasCity()) { - setCity(other.getCity()); - } - mergeUnknownFields(other.getUnknownFields()); - return this; - } - - public final boolean isInitialized() { - if (!hasContinent()) { - - return false; - } - if (!hasCity()) { - - return false; - } - return true; - } - - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder( - getUnknownFields()); - while (true) { + throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { int tag = input.readTag(); switch (tag) { case 0: - setUnknownFields(unknownFields.build()); - onChanged(); - return this; + done = true; + break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { - setUnknownFields(unknownFields.build()); - onChanged(); - return this; + done = true; } break; } @@ -593,18 +396,382 @@ public final class LocalTimeProtocol { } } } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e.getMessage()).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Location_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Location_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jboss.netty.example.localtime.LocalTimeProtocol.Location.class, org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder.class); + } + + public static com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public Location parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Location(input, extensionRegistry); + } + }; + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + private int bitField0_; + // required .org.jboss.netty.example.localtime.Continent continent = 1; + public static final int CONTINENT_FIELD_NUMBER = 1; + private org.jboss.netty.example.localtime.LocalTimeProtocol.Continent continent_; + /** + * required .org.jboss.netty.example.localtime.Continent continent = 1; + */ + public boolean hasContinent() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * required .org.jboss.netty.example.localtime.Continent continent = 1; + */ + public org.jboss.netty.example.localtime.LocalTimeProtocol.Continent getContinent() { + return continent_; + } + + // required string city = 2; + public static final int CITY_FIELD_NUMBER = 2; + private java.lang.Object city_; + /** + * required string city = 2; + */ + public boolean hasCity() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * required string city = 2; + */ + public java.lang.String getCity() { + java.lang.Object ref = city_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + city_ = s; + } + return s; + } + } + /** + * required string city = 2; + */ + public com.google.protobuf.ByteString + getCityBytes() { + java.lang.Object ref = city_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + city_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private void initFields() { + continent_ = org.jboss.netty.example.localtime.LocalTimeProtocol.Continent.AFRICA; + city_ = ""; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasContinent()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasCity()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeEnum(1, continent_.getNumber()); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, getCityBytes()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(1, continent_.getNumber()); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(2, getCityBytes()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(org.jboss.netty.example.localtime.LocalTimeProtocol.Location prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code org.jboss.netty.example.localtime.Location} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements org.jboss.netty.example.localtime.LocalTimeProtocol.LocationOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Location_descriptor; } + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Location_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jboss.netty.example.localtime.LocalTimeProtocol.Location.class, org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder.class); + } + + // Construct using org.jboss.netty.example.localtime.LocalTimeProtocol.Location.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + continent_ = org.jboss.netty.example.localtime.LocalTimeProtocol.Continent.AFRICA; + bitField0_ = (bitField0_ & ~0x00000001); + city_ = ""; + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Location_descriptor; + } + + public org.jboss.netty.example.localtime.LocalTimeProtocol.Location getDefaultInstanceForType() { + return org.jboss.netty.example.localtime.LocalTimeProtocol.Location.getDefaultInstance(); + } + + public org.jboss.netty.example.localtime.LocalTimeProtocol.Location build() { + org.jboss.netty.example.localtime.LocalTimeProtocol.Location result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.jboss.netty.example.localtime.LocalTimeProtocol.Location buildPartial() { + org.jboss.netty.example.localtime.LocalTimeProtocol.Location result = new org.jboss.netty.example.localtime.LocalTimeProtocol.Location(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.continent_ = continent_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.city_ = city_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof org.jboss.netty.example.localtime.LocalTimeProtocol.Location) { + return mergeFrom((org.jboss.netty.example.localtime.LocalTimeProtocol.Location)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(org.jboss.netty.example.localtime.LocalTimeProtocol.Location other) { + if (other == org.jboss.netty.example.localtime.LocalTimeProtocol.Location.getDefaultInstance()) return this; + if (other.hasContinent()) { + setContinent(other.getContinent()); + } + if (other.hasCity()) { + bitField0_ |= 0x00000002; + city_ = other.city_; + onChanged(); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + if (!hasContinent()) { + + return false; + } + if (!hasCity()) { + + return false; + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + org.jboss.netty.example.localtime.LocalTimeProtocol.Location parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.jboss.netty.example.localtime.LocalTimeProtocol.Location) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } private int bitField0_; // required .org.jboss.netty.example.localtime.Continent continent = 1; private org.jboss.netty.example.localtime.LocalTimeProtocol.Continent continent_ = org.jboss.netty.example.localtime.LocalTimeProtocol.Continent.AFRICA; + /** + * required .org.jboss.netty.example.localtime.Continent continent = 1; + */ public boolean hasContinent() { - return (bitField0_ & 0x00000001) == 0x00000001; + return ((bitField0_ & 0x00000001) == 0x00000001); } + /** + * required .org.jboss.netty.example.localtime.Continent continent = 1; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.Continent getContinent() { return continent_; } + /** + * required .org.jboss.netty.example.localtime.Continent continent = 1; + */ public Builder setContinent(org.jboss.netty.example.localtime.LocalTimeProtocol.Continent value) { if (value == null) { throw new NullPointerException(); @@ -614,8 +781,11 @@ public final class LocalTimeProtocol { onChanged(); return this; } + /** + * required .org.jboss.netty.example.localtime.Continent continent = 1; + */ public Builder clearContinent() { - bitField0_ = bitField0_ & ~0x00000001; + bitField0_ = (bitField0_ & ~0x00000001); continent_ = org.jboss.netty.example.localtime.LocalTimeProtocol.Continent.AFRICA; onChanged(); return this; @@ -623,20 +793,47 @@ public final class LocalTimeProtocol { // required string city = 2; private java.lang.Object city_ = ""; + /** + * required string city = 2; + */ public boolean hasCity() { - return (bitField0_ & 0x00000002) == 0x00000002; + return ((bitField0_ & 0x00000002) == 0x00000002); } - public String getCity() { + /** + * required string city = 2; + */ + public java.lang.String getCity() { java.lang.Object ref = city_; - if (!(ref instanceof String)) { - String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + if (!(ref instanceof java.lang.String)) { + java.lang.String s = ((com.google.protobuf.ByteString) ref) + .toStringUtf8(); city_ = s; return s; } else { - return (String) ref; + return (java.lang.String) ref; } } - public Builder setCity(String value) { + /** + * required string city = 2; + */ + public com.google.protobuf.ByteString + getCityBytes() { + java.lang.Object ref = city_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + city_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + * required string city = 2; + */ + public Builder setCity( + java.lang.String value) { if (value == null) { throw new NullPointerException(); } @@ -645,16 +842,27 @@ public final class LocalTimeProtocol { onChanged(); return this; } + /** + * required string city = 2; + */ public Builder clearCity() { - bitField0_ = bitField0_ & ~0x00000002; + bitField0_ = (bitField0_ & ~0x00000002); city_ = getDefaultInstance().getCity(); onChanged(); return this; } - void setCity(com.google.protobuf.ByteString value) { - bitField0_ |= 0x00000002; + /** + * required string city = 2; + */ + public Builder setCityBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; city_ = value; onChanged(); + return this; } // @@protoc_insertion_point(builder_scope:org.jboss.netty.example.localtime.Location) @@ -672,23 +880,42 @@ public final class LocalTimeProtocol { extends com.google.protobuf.MessageOrBuilder { // repeated .org.jboss.netty.example.localtime.Location location = 1; - java.util.List + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ + java.util.List getLocationList(); + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ org.jboss.netty.example.localtime.LocalTimeProtocol.Location getLocation(int index); + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ int getLocationCount(); - java.util.List + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ + java.util.List getLocationOrBuilderList(); + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ org.jboss.netty.example.localtime.LocalTimeProtocol.LocationOrBuilder getLocationOrBuilder( int index); } + /** + * Protobuf type {@code org.jboss.netty.example.localtime.Locations} + */ public static final class Locations extends com.google.protobuf.GeneratedMessage implements LocationsOrBuilder { // Use Locations.newBuilder() to construct. - private Locations(Builder builder) { + private Locations(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); + this.unknownFields = builder.getUnknownFields(); } - private Locations(boolean noInit) {} + private Locations(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Locations defaultInstance; public static Locations getDefaultInstance() { @@ -699,6 +926,58 @@ public final class LocalTimeProtocol { return defaultInstance; } + private final com.google.protobuf.UnknownFieldSet unknownFields; + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private Locations( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + location_ = new java.util.ArrayList(); + mutable_bitField0_ |= 0x00000001; + } + location_.add(input.readMessage(org.jboss.netty.example.localtime.LocalTimeProtocol.Location.PARSER, extensionRegistry)); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e.getMessage()).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + location_ = java.util.Collections.unmodifiableList(location_); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Locations_descriptor; @@ -706,25 +985,57 @@ public final class LocalTimeProtocol { protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Locations_fieldAccessorTable; + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Locations_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.class, org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.Builder.class); + } + + public static com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public Locations parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Locations(input, extensionRegistry); + } + }; + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; } // repeated .org.jboss.netty.example.localtime.Location location = 1; public static final int LOCATION_FIELD_NUMBER = 1; private java.util.List location_; + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public java.util.List getLocationList() { return location_; } - public java.util.List + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ + public java.util.List getLocationOrBuilderList() { return location_; } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public int getLocationCount() { return location_.size(); } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.Location getLocation(int index) { return location_.get(index); } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.LocationOrBuilder getLocationOrBuilder( int index) { return location_.get(index); @@ -736,9 +1047,7 @@ public final class LocalTimeProtocol { private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; - if (isInitialized != -1) { - return isInitialized == 1; - } + if (isInitialized != -1) return isInitialized == 1; for (int i = 0; i < getLocationCount(); i++) { if (!getLocation(i).isInitialized()) { @@ -762,9 +1071,7 @@ public final class LocalTimeProtocol { private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; - if (size != -1) { - return size; - } + if (size != -1) return size; size = 0; for (int i = 0; i < location_.size(); i++) { @@ -786,68 +1093,54 @@ public final class LocalTimeProtocol { public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data).buildParsed(); + return PARSER.parseFrom(data); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data, extensionRegistry) - .buildParsed(); + return PARSER.parseFrom(data, extensionRegistry); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data).buildParsed(); + return PARSER.parseFrom(data); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data, extensionRegistry) - .buildParsed(); + return PARSER.parseFrom(data, extensionRegistry); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom(java.io.InputStream input) throws java.io.IOException { - return newBuilder().mergeFrom(input).buildParsed(); + return PARSER.parseFrom(input); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { - return newBuilder().mergeFrom(input, extensionRegistry) - .buildParsed(); + return PARSER.parseFrom(input, extensionRegistry); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { - Builder builder = newBuilder(); - if (builder.mergeDelimitedFrom(input)) { - return builder.buildParsed(); - } else { - return null; - } + return PARSER.parseDelimitedFrom(input); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { - Builder builder = newBuilder(); - if (builder.mergeDelimitedFrom(input, extensionRegistry)) { - return builder.buildParsed(); - } else { - return null; - } + return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { - return newBuilder().mergeFrom(input).buildParsed(); + return PARSER.parseFrom(input); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { - return newBuilder().mergeFrom(input, extensionRegistry) - .buildParsed(); + return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } @@ -863,6 +1156,9 @@ public final class LocalTimeProtocol { Builder builder = new Builder(parent); return builder; } + /** + * Protobuf type {@code org.jboss.netty.example.localtime.Locations} + */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.jboss.netty.example.localtime.LocalTimeProtocol.LocationsOrBuilder { @@ -873,7 +1169,9 @@ public final class LocalTimeProtocol { protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Locations_fieldAccessorTable; + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Locations_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.class, org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.Builder.class); } // Construct using org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.newBuilder() @@ -881,7 +1179,8 @@ public final class LocalTimeProtocol { maybeForceBuilderInitialization(); } - private Builder(BuilderParent parent) { + private Builder( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } @@ -898,7 +1197,7 @@ public final class LocalTimeProtocol { super.clear(); if (locationBuilder_ == null) { location_ = java.util.Collections.emptyList(); - bitField0_ = bitField0_ & ~0x00000001; + bitField0_ = (bitField0_ & ~0x00000001); } else { locationBuilder_.clear(); } @@ -911,7 +1210,7 @@ public final class LocalTimeProtocol { public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.getDescriptor(); + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Locations_descriptor; } public org.jboss.netty.example.localtime.LocalTimeProtocol.Locations getDefaultInstanceForType() { @@ -926,23 +1225,13 @@ public final class LocalTimeProtocol { return result; } - private org.jboss.netty.example.localtime.LocalTimeProtocol.Locations buildParsed() - throws com.google.protobuf.InvalidProtocolBufferException { - org.jboss.netty.example.localtime.LocalTimeProtocol.Locations result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException( - result).asInvalidProtocolBufferException(); - } - return result; - } - public org.jboss.netty.example.localtime.LocalTimeProtocol.Locations buildPartial() { org.jboss.netty.example.localtime.LocalTimeProtocol.Locations result = new org.jboss.netty.example.localtime.LocalTimeProtocol.Locations(this); int from_bitField0_ = bitField0_; if (locationBuilder_ == null) { - if ((bitField0_ & 0x00000001) == 0x00000001) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { location_ = java.util.Collections.unmodifiableList(location_); - bitField0_ = bitField0_ & ~0x00000001; + bitField0_ = (bitField0_ & ~0x00000001); } result.location_ = location_; } else { @@ -962,14 +1251,12 @@ public final class LocalTimeProtocol { } public Builder mergeFrom(org.jboss.netty.example.localtime.LocalTimeProtocol.Locations other) { - if (other == org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.getDefaultInstance()) { - return this; - } + if (other == org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.getDefaultInstance()) return this; if (locationBuilder_ == null) { if (!other.location_.isEmpty()) { if (location_.isEmpty()) { location_ = other.location_; - bitField0_ = bitField0_ & ~0x00000001; + bitField0_ = (bitField0_ & ~0x00000001); } else { ensureLocationIsMutable(); location_.addAll(other.location_); @@ -982,8 +1269,8 @@ public final class LocalTimeProtocol { locationBuilder_.dispose(); locationBuilder_ = null; location_ = other.location_; - bitField0_ = bitField0_ & ~0x00000001; - locationBuilder_ = + bitField0_ = (bitField0_ & ~0x00000001); + locationBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getLocationFieldBuilder() : null; } else { @@ -991,14 +1278,14 @@ public final class LocalTimeProtocol { } } } - mergeUnknownFields(other.getUnknownFields()); + this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { for (int i = 0; i < getLocationCount(); i++) { if (!getLocation(i).isInitialized()) { - + return false; } } @@ -1009,35 +1296,19 @@ public final class LocalTimeProtocol { com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder( - getUnknownFields()); - while (true) { - int tag = input.readTag(); - switch (tag) { - case 0: - setUnknownFields(unknownFields.build()); - onChanged(); - return this; - default: { - if (!parseUnknownField(input, unknownFields, - extensionRegistry, tag)) { - setUnknownFields(unknownFields.build()); - onChanged(); - return this; - } - break; - } - case 10: { - org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder subBuilder = org.jboss.netty.example.localtime.LocalTimeProtocol.Location.newBuilder(); - input.readMessage(subBuilder, extensionRegistry); - addLocation(subBuilder.buildPartial()); - break; - } + org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.jboss.netty.example.localtime.LocalTimeProtocol.Locations) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); } } + return this; } - private int bitField0_; // repeated .org.jboss.netty.example.localtime.Location location = 1; @@ -1053,6 +1324,9 @@ public final class LocalTimeProtocol { private com.google.protobuf.RepeatedFieldBuilder< org.jboss.netty.example.localtime.LocalTimeProtocol.Location, org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder, org.jboss.netty.example.localtime.LocalTimeProtocol.LocationOrBuilder> locationBuilder_; + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public java.util.List getLocationList() { if (locationBuilder_ == null) { return java.util.Collections.unmodifiableList(location_); @@ -1060,6 +1334,9 @@ public final class LocalTimeProtocol { return locationBuilder_.getMessageList(); } } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public int getLocationCount() { if (locationBuilder_ == null) { return location_.size(); @@ -1067,6 +1344,9 @@ public final class LocalTimeProtocol { return locationBuilder_.getCount(); } } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.Location getLocation(int index) { if (locationBuilder_ == null) { return location_.get(index); @@ -1074,6 +1354,9 @@ public final class LocalTimeProtocol { return locationBuilder_.getMessage(index); } } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public Builder setLocation( int index, org.jboss.netty.example.localtime.LocalTimeProtocol.Location value) { if (locationBuilder_ == null) { @@ -1088,6 +1371,9 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public Builder setLocation( int index, org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder builderForValue) { if (locationBuilder_ == null) { @@ -1099,6 +1385,9 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public Builder addLocation(org.jboss.netty.example.localtime.LocalTimeProtocol.Location value) { if (locationBuilder_ == null) { if (value == null) { @@ -1112,6 +1401,9 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public Builder addLocation( int index, org.jboss.netty.example.localtime.LocalTimeProtocol.Location value) { if (locationBuilder_ == null) { @@ -1126,6 +1418,9 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public Builder addLocation( org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder builderForValue) { if (locationBuilder_ == null) { @@ -1137,6 +1432,9 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public Builder addLocation( int index, org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder builderForValue) { if (locationBuilder_ == null) { @@ -1148,6 +1446,9 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public Builder addAllLocation( java.lang.Iterable values) { if (locationBuilder_ == null) { @@ -1159,16 +1460,22 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public Builder clearLocation() { if (locationBuilder_ == null) { location_ = java.util.Collections.emptyList(); - bitField0_ = bitField0_ & ~0x00000001; + bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { locationBuilder_.clear(); } return this; } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public Builder removeLocation(int index) { if (locationBuilder_ == null) { ensureLocationIsMutable(); @@ -1179,10 +1486,16 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder getLocationBuilder( int index) { return getLocationFieldBuilder().getBuilder(index); } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.LocationOrBuilder getLocationOrBuilder( int index) { if (locationBuilder_ == null) { @@ -1190,7 +1503,10 @@ public final class LocalTimeProtocol { return locationBuilder_.getMessageOrBuilder(index); } } - public java.util.List + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ + public java.util.List getLocationOrBuilderList() { if (locationBuilder_ != null) { return locationBuilder_.getMessageOrBuilderList(); @@ -1198,27 +1514,36 @@ public final class LocalTimeProtocol { return java.util.Collections.unmodifiableList(location_); } } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder addLocationBuilder() { return getLocationFieldBuilder().addBuilder( org.jboss.netty.example.localtime.LocalTimeProtocol.Location.getDefaultInstance()); } + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder addLocationBuilder( int index) { return getLocationFieldBuilder().addBuilder( index, org.jboss.netty.example.localtime.LocalTimeProtocol.Location.getDefaultInstance()); } - public java.util.List + /** + * repeated .org.jboss.netty.example.localtime.Location location = 1; + */ + public java.util.List getLocationBuilderList() { return getLocationFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< - org.jboss.netty.example.localtime.LocalTimeProtocol.Location, org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder, org.jboss.netty.example.localtime.LocalTimeProtocol.LocationOrBuilder> + org.jboss.netty.example.localtime.LocalTimeProtocol.Location, org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder, org.jboss.netty.example.localtime.LocalTimeProtocol.LocationOrBuilder> getLocationFieldBuilder() { if (locationBuilder_ == null) { locationBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< org.jboss.netty.example.localtime.LocalTimeProtocol.Location, org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder, org.jboss.netty.example.localtime.LocalTimeProtocol.LocationOrBuilder>( location_, - (bitField0_ & 0x00000001) == 0x00000001, + ((bitField0_ & 0x00000001) == 0x00000001), getParentForChildren(), isClean()); location_ = null; @@ -1241,41 +1566,87 @@ public final class LocalTimeProtocol { extends com.google.protobuf.MessageOrBuilder { // required uint32 year = 1; + /** + * required uint32 year = 1; + */ boolean hasYear(); + /** + * required uint32 year = 1; + */ int getYear(); // required uint32 month = 2; + /** + * required uint32 month = 2; + */ boolean hasMonth(); + /** + * required uint32 month = 2; + */ int getMonth(); // required uint32 dayOfMonth = 4; + /** + * required uint32 dayOfMonth = 4; + */ boolean hasDayOfMonth(); + /** + * required uint32 dayOfMonth = 4; + */ int getDayOfMonth(); // required .org.jboss.netty.example.localtime.DayOfWeek dayOfWeek = 5; + /** + * required .org.jboss.netty.example.localtime.DayOfWeek dayOfWeek = 5; + */ boolean hasDayOfWeek(); + /** + * required .org.jboss.netty.example.localtime.DayOfWeek dayOfWeek = 5; + */ org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek getDayOfWeek(); // required uint32 hour = 6; + /** + * required uint32 hour = 6; + */ boolean hasHour(); + /** + * required uint32 hour = 6; + */ int getHour(); // required uint32 minute = 7; + /** + * required uint32 minute = 7; + */ boolean hasMinute(); + /** + * required uint32 minute = 7; + */ int getMinute(); // required uint32 second = 8; + /** + * required uint32 second = 8; + */ boolean hasSecond(); + /** + * required uint32 second = 8; + */ int getSecond(); } + /** + * Protobuf type {@code org.jboss.netty.example.localtime.LocalTime} + */ public static final class LocalTime extends com.google.protobuf.GeneratedMessage implements LocalTimeOrBuilder { // Use LocalTime.newBuilder() to construct. - private LocalTime(Builder builder) { + private LocalTime(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); + this.unknownFields = builder.getUnknownFields(); } - private LocalTime(boolean noInit) {} + private LocalTime(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final LocalTime defaultInstance; public static LocalTime getDefaultInstance() { @@ -1286,497 +1657,32 @@ public final class LocalTimeProtocol { return defaultInstance; } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTime_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTime_fieldAccessorTable; - } - - private int bitField0_; - // required uint32 year = 1; - public static final int YEAR_FIELD_NUMBER = 1; - private int year_; - public boolean hasYear() { - return (bitField0_ & 0x00000001) == 0x00000001; - } - public int getYear() { - return year_; - } - - // required uint32 month = 2; - public static final int MONTH_FIELD_NUMBER = 2; - private int month_; - public boolean hasMonth() { - return (bitField0_ & 0x00000002) == 0x00000002; - } - public int getMonth() { - return month_; - } - - // required uint32 dayOfMonth = 4; - public static final int DAYOFMONTH_FIELD_NUMBER = 4; - private int dayOfMonth_; - public boolean hasDayOfMonth() { - return (bitField0_ & 0x00000004) == 0x00000004; - } - public int getDayOfMonth() { - return dayOfMonth_; - } - - // required .org.jboss.netty.example.localtime.DayOfWeek dayOfWeek = 5; - public static final int DAYOFWEEK_FIELD_NUMBER = 5; - private org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek dayOfWeek_; - public boolean hasDayOfWeek() { - return (bitField0_ & 0x00000008) == 0x00000008; - } - public org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek getDayOfWeek() { - return dayOfWeek_; - } - - // required uint32 hour = 6; - public static final int HOUR_FIELD_NUMBER = 6; - private int hour_; - public boolean hasHour() { - return (bitField0_ & 0x00000010) == 0x00000010; - } - public int getHour() { - return hour_; - } - - // required uint32 minute = 7; - public static final int MINUTE_FIELD_NUMBER = 7; - private int minute_; - public boolean hasMinute() { - return (bitField0_ & 0x00000020) == 0x00000020; - } - public int getMinute() { - return minute_; - } - - // required uint32 second = 8; - public static final int SECOND_FIELD_NUMBER = 8; - private int second_; - public boolean hasSecond() { - return (bitField0_ & 0x00000040) == 0x00000040; - } - public int getSecond() { - return second_; - } - - private void initFields() { - year_ = 0; - month_ = 0; - dayOfMonth_ = 0; - dayOfWeek_ = org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek.SUNDAY; - hour_ = 0; - minute_ = 0; - second_ = 0; - } - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized != -1) { - return isInitialized == 1; - } - - if (!hasYear()) { - memoizedIsInitialized = 0; - return false; - } - if (!hasMonth()) { - memoizedIsInitialized = 0; - return false; - } - if (!hasDayOfMonth()) { - memoizedIsInitialized = 0; - return false; - } - if (!hasDayOfWeek()) { - memoizedIsInitialized = 0; - return false; - } - if (!hasHour()) { - memoizedIsInitialized = 0; - return false; - } - if (!hasMinute()) { - memoizedIsInitialized = 0; - return false; - } - if (!hasSecond()) { - memoizedIsInitialized = 0; - return false; - } - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - getSerializedSize(); - if ((bitField0_ & 0x00000001) == 0x00000001) { - output.writeUInt32(1, year_); - } - if ((bitField0_ & 0x00000002) == 0x00000002) { - output.writeUInt32(2, month_); - } - if ((bitField0_ & 0x00000004) == 0x00000004) { - output.writeUInt32(4, dayOfMonth_); - } - if ((bitField0_ & 0x00000008) == 0x00000008) { - output.writeEnum(5, dayOfWeek_.getNumber()); - } - if ((bitField0_ & 0x00000010) == 0x00000010) { - output.writeUInt32(6, hour_); - } - if ((bitField0_ & 0x00000020) == 0x00000020) { - output.writeUInt32(7, minute_); - } - if ((bitField0_ & 0x00000040) == 0x00000040) { - output.writeUInt32(8, second_); - } - getUnknownFields().writeTo(output); - } - - private int memoizedSerializedSize = -1; - public int getSerializedSize() { - int size = memoizedSerializedSize; - if (size != -1) { - return size; - } - - size = 0; - if ((bitField0_ & 0x00000001) == 0x00000001) { - size += com.google.protobuf.CodedOutputStream - .computeUInt32Size(1, year_); - } - if ((bitField0_ & 0x00000002) == 0x00000002) { - size += com.google.protobuf.CodedOutputStream - .computeUInt32Size(2, month_); - } - if ((bitField0_ & 0x00000004) == 0x00000004) { - size += com.google.protobuf.CodedOutputStream - .computeUInt32Size(4, dayOfMonth_); - } - if ((bitField0_ & 0x00000008) == 0x00000008) { - size += com.google.protobuf.CodedOutputStream - .computeEnumSize(5, dayOfWeek_.getNumber()); - } - if ((bitField0_ & 0x00000010) == 0x00000010) { - size += com.google.protobuf.CodedOutputStream - .computeUInt32Size(6, hour_); - } - if ((bitField0_ & 0x00000020) == 0x00000020) { - size += com.google.protobuf.CodedOutputStream - .computeUInt32Size(7, minute_); - } - if ((bitField0_ & 0x00000040) == 0x00000040) { - size += com.google.protobuf.CodedOutputStream - .computeUInt32Size(8, second_); - } - size += getUnknownFields().getSerializedSize(); - memoizedSerializedSize = size; - return size; - } - - private static final long serialVersionUID = 0L; + private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override - protected java.lang.Object writeReplace() - throws java.io.ObjectStreamException { - return super.writeReplace(); + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; } - - public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data).buildParsed(); - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data, extensionRegistry) - .buildParsed(); - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data).buildParsed(); - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data, extensionRegistry) - .buildParsed(); - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom(java.io.InputStream input) - throws java.io.IOException { - return newBuilder().mergeFrom(input).buildParsed(); - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return newBuilder().mergeFrom(input, extensionRegistry) - .buildParsed(); - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - Builder builder = newBuilder(); - if (builder.mergeDelimitedFrom(input)) { - return builder.buildParsed(); - } else { - return null; - } - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - Builder builder = newBuilder(); - if (builder.mergeDelimitedFrom(input, extensionRegistry)) { - return builder.buildParsed(); - } else { - return null; - } - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return newBuilder().mergeFrom(input).buildParsed(); - } - public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( + private LocalTime( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return newBuilder().mergeFrom(input, extensionRegistry) - .buildParsed(); - } - - public static Builder newBuilder() { return Builder.create(); } - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder(org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime prototype) { - return newBuilder().mergeFrom(prototype); - } - public Builder toBuilder() { return newBuilder(this); } - - @java.lang.Override - protected Builder newBuilderForType( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder - implements org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimeOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTime_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTime_fieldAccessorTable; - } - - // Construct using org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { - } - } - private static Builder create() { - return new Builder(); - } - - public Builder clear() { - super.clear(); - year_ = 0; - bitField0_ = bitField0_ & ~0x00000001; - month_ = 0; - bitField0_ = bitField0_ & ~0x00000002; - dayOfMonth_ = 0; - bitField0_ = bitField0_ & ~0x00000004; - dayOfWeek_ = org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek.SUNDAY; - bitField0_ = bitField0_ & ~0x00000008; - hour_ = 0; - bitField0_ = bitField0_ & ~0x00000010; - minute_ = 0; - bitField0_ = bitField0_ & ~0x00000020; - second_ = 0; - bitField0_ = bitField0_ & ~0x00000040; - return this; - } - - public Builder clone() { - return create().mergeFrom(buildPartial()); - } - - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.getDescriptor(); - } - - public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime getDefaultInstanceForType() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.getDefaultInstance(); - } - - public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime build() { - org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - private org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime buildParsed() - throws com.google.protobuf.InvalidProtocolBufferException { - org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException( - result).asInvalidProtocolBufferException(); - } - return result; - } - - public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime buildPartial() { - org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime result = new org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime(this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - if ((from_bitField0_ & 0x00000001) == 0x00000001) { - to_bitField0_ |= 0x00000001; - } - result.year_ = year_; - if ((from_bitField0_ & 0x00000002) == 0x00000002) { - to_bitField0_ |= 0x00000002; - } - result.month_ = month_; - if ((from_bitField0_ & 0x00000004) == 0x00000004) { - to_bitField0_ |= 0x00000004; - } - result.dayOfMonth_ = dayOfMonth_; - if ((from_bitField0_ & 0x00000008) == 0x00000008) { - to_bitField0_ |= 0x00000008; - } - result.dayOfWeek_ = dayOfWeek_; - if ((from_bitField0_ & 0x00000010) == 0x00000010) { - to_bitField0_ |= 0x00000010; - } - result.hour_ = hour_; - if ((from_bitField0_ & 0x00000020) == 0x00000020) { - to_bitField0_ |= 0x00000020; - } - result.minute_ = minute_; - if ((from_bitField0_ & 0x00000040) == 0x00000040) { - to_bitField0_ |= 0x00000040; - } - result.second_ = second_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime) { - return mergeFrom((org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime)other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime other) { - if (other == org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.getDefaultInstance()) { - return this; - } - if (other.hasYear()) { - setYear(other.getYear()); - } - if (other.hasMonth()) { - setMonth(other.getMonth()); - } - if (other.hasDayOfMonth()) { - setDayOfMonth(other.getDayOfMonth()); - } - if (other.hasDayOfWeek()) { - setDayOfWeek(other.getDayOfWeek()); - } - if (other.hasHour()) { - setHour(other.getHour()); - } - if (other.hasMinute()) { - setMinute(other.getMinute()); - } - if (other.hasSecond()) { - setSecond(other.getSecond()); - } - mergeUnknownFields(other.getUnknownFields()); - return this; - } - - public final boolean isInitialized() { - if (!hasYear()) { - - return false; - } - if (!hasMonth()) { - - return false; - } - if (!hasDayOfMonth()) { - - return false; - } - if (!hasDayOfWeek()) { - - return false; - } - if (!hasHour()) { - - return false; - } - if (!hasMinute()) { - - return false; - } - if (!hasSecond()) { - - return false; - } - return true; - } - - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder( - getUnknownFields()); - while (true) { + throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { int tag = input.readTag(); switch (tag) { case 0: - setUnknownFields(unknownFields.build()); - onChanged(); - return this; + done = true; + break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { - setUnknownFields(unknownFields.build()); - onChanged(); - return this; + done = true; } break; } @@ -1823,26 +1729,569 @@ public final class LocalTimeProtocol { } } } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e.getMessage()).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTime_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTime_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.class, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder.class); + } + + public static com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public LocalTime parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new LocalTime(input, extensionRegistry); + } + }; + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + private int bitField0_; + // required uint32 year = 1; + public static final int YEAR_FIELD_NUMBER = 1; + private int year_; + /** + * required uint32 year = 1; + */ + public boolean hasYear() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * required uint32 year = 1; + */ + public int getYear() { + return year_; + } + + // required uint32 month = 2; + public static final int MONTH_FIELD_NUMBER = 2; + private int month_; + /** + * required uint32 month = 2; + */ + public boolean hasMonth() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * required uint32 month = 2; + */ + public int getMonth() { + return month_; + } + + // required uint32 dayOfMonth = 4; + public static final int DAYOFMONTH_FIELD_NUMBER = 4; + private int dayOfMonth_; + /** + * required uint32 dayOfMonth = 4; + */ + public boolean hasDayOfMonth() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + /** + * required uint32 dayOfMonth = 4; + */ + public int getDayOfMonth() { + return dayOfMonth_; + } + + // required .org.jboss.netty.example.localtime.DayOfWeek dayOfWeek = 5; + public static final int DAYOFWEEK_FIELD_NUMBER = 5; + private org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek dayOfWeek_; + /** + * required .org.jboss.netty.example.localtime.DayOfWeek dayOfWeek = 5; + */ + public boolean hasDayOfWeek() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + /** + * required .org.jboss.netty.example.localtime.DayOfWeek dayOfWeek = 5; + */ + public org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek getDayOfWeek() { + return dayOfWeek_; + } + + // required uint32 hour = 6; + public static final int HOUR_FIELD_NUMBER = 6; + private int hour_; + /** + * required uint32 hour = 6; + */ + public boolean hasHour() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + /** + * required uint32 hour = 6; + */ + public int getHour() { + return hour_; + } + + // required uint32 minute = 7; + public static final int MINUTE_FIELD_NUMBER = 7; + private int minute_; + /** + * required uint32 minute = 7; + */ + public boolean hasMinute() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + /** + * required uint32 minute = 7; + */ + public int getMinute() { + return minute_; + } + + // required uint32 second = 8; + public static final int SECOND_FIELD_NUMBER = 8; + private int second_; + /** + * required uint32 second = 8; + */ + public boolean hasSecond() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + /** + * required uint32 second = 8; + */ + public int getSecond() { + return second_; + } + + private void initFields() { + year_ = 0; + month_ = 0; + dayOfMonth_ = 0; + dayOfWeek_ = org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek.SUNDAY; + hour_ = 0; + minute_ = 0; + second_ = 0; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasYear()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasMonth()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasDayOfMonth()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasDayOfWeek()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasHour()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasMinute()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasSecond()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeUInt32(1, year_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeUInt32(2, month_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeUInt32(4, dayOfMonth_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeEnum(5, dayOfWeek_.getNumber()); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + output.writeUInt32(6, hour_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + output.writeUInt32(7, minute_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + output.writeUInt32(8, second_); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(1, year_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(2, month_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(4, dayOfMonth_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(5, dayOfWeek_.getNumber()); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(6, hour_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(7, minute_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(8, second_); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code org.jboss.netty.example.localtime.LocalTime} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimeOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTime_descriptor; } + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTime_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.class, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder.class); + } + + // Construct using org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + year_ = 0; + bitField0_ = (bitField0_ & ~0x00000001); + month_ = 0; + bitField0_ = (bitField0_ & ~0x00000002); + dayOfMonth_ = 0; + bitField0_ = (bitField0_ & ~0x00000004); + dayOfWeek_ = org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek.SUNDAY; + bitField0_ = (bitField0_ & ~0x00000008); + hour_ = 0; + bitField0_ = (bitField0_ & ~0x00000010); + minute_ = 0; + bitField0_ = (bitField0_ & ~0x00000020); + second_ = 0; + bitField0_ = (bitField0_ & ~0x00000040); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTime_descriptor; + } + + public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime getDefaultInstanceForType() { + return org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.getDefaultInstance(); + } + + public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime build() { + org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime buildPartial() { + org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime result = new org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.year_ = year_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.month_ = month_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.dayOfMonth_ = dayOfMonth_; + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + result.dayOfWeek_ = dayOfWeek_; + if (((from_bitField0_ & 0x00000010) == 0x00000010)) { + to_bitField0_ |= 0x00000010; + } + result.hour_ = hour_; + if (((from_bitField0_ & 0x00000020) == 0x00000020)) { + to_bitField0_ |= 0x00000020; + } + result.minute_ = minute_; + if (((from_bitField0_ & 0x00000040) == 0x00000040)) { + to_bitField0_ |= 0x00000040; + } + result.second_ = second_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime) { + return mergeFrom((org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime other) { + if (other == org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.getDefaultInstance()) return this; + if (other.hasYear()) { + setYear(other.getYear()); + } + if (other.hasMonth()) { + setMonth(other.getMonth()); + } + if (other.hasDayOfMonth()) { + setDayOfMonth(other.getDayOfMonth()); + } + if (other.hasDayOfWeek()) { + setDayOfWeek(other.getDayOfWeek()); + } + if (other.hasHour()) { + setHour(other.getHour()); + } + if (other.hasMinute()) { + setMinute(other.getMinute()); + } + if (other.hasSecond()) { + setSecond(other.getSecond()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + if (!hasYear()) { + + return false; + } + if (!hasMonth()) { + + return false; + } + if (!hasDayOfMonth()) { + + return false; + } + if (!hasDayOfWeek()) { + + return false; + } + if (!hasHour()) { + + return false; + } + if (!hasMinute()) { + + return false; + } + if (!hasSecond()) { + + return false; + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } private int bitField0_; // required uint32 year = 1; private int year_ ; + /** + * required uint32 year = 1; + */ public boolean hasYear() { - return (bitField0_ & 0x00000001) == 0x00000001; + return ((bitField0_ & 0x00000001) == 0x00000001); } + /** + * required uint32 year = 1; + */ public int getYear() { return year_; } + /** + * required uint32 year = 1; + */ public Builder setYear(int value) { bitField0_ |= 0x00000001; year_ = value; onChanged(); return this; } + /** + * required uint32 year = 1; + */ public Builder clearYear() { - bitField0_ = bitField0_ & ~0x00000001; + bitField0_ = (bitField0_ & ~0x00000001); year_ = 0; onChanged(); return this; @@ -1850,20 +2299,32 @@ public final class LocalTimeProtocol { // required uint32 month = 2; private int month_ ; + /** + * required uint32 month = 2; + */ public boolean hasMonth() { - return (bitField0_ & 0x00000002) == 0x00000002; + return ((bitField0_ & 0x00000002) == 0x00000002); } + /** + * required uint32 month = 2; + */ public int getMonth() { return month_; } + /** + * required uint32 month = 2; + */ public Builder setMonth(int value) { bitField0_ |= 0x00000002; month_ = value; onChanged(); return this; } + /** + * required uint32 month = 2; + */ public Builder clearMonth() { - bitField0_ = bitField0_ & ~0x00000002; + bitField0_ = (bitField0_ & ~0x00000002); month_ = 0; onChanged(); return this; @@ -1871,20 +2332,32 @@ public final class LocalTimeProtocol { // required uint32 dayOfMonth = 4; private int dayOfMonth_ ; + /** + * required uint32 dayOfMonth = 4; + */ public boolean hasDayOfMonth() { - return (bitField0_ & 0x00000004) == 0x00000004; + return ((bitField0_ & 0x00000004) == 0x00000004); } + /** + * required uint32 dayOfMonth = 4; + */ public int getDayOfMonth() { return dayOfMonth_; } + /** + * required uint32 dayOfMonth = 4; + */ public Builder setDayOfMonth(int value) { bitField0_ |= 0x00000004; dayOfMonth_ = value; onChanged(); return this; } + /** + * required uint32 dayOfMonth = 4; + */ public Builder clearDayOfMonth() { - bitField0_ = bitField0_ & ~0x00000004; + bitField0_ = (bitField0_ & ~0x00000004); dayOfMonth_ = 0; onChanged(); return this; @@ -1892,12 +2365,21 @@ public final class LocalTimeProtocol { // required .org.jboss.netty.example.localtime.DayOfWeek dayOfWeek = 5; private org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek dayOfWeek_ = org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek.SUNDAY; + /** + * required .org.jboss.netty.example.localtime.DayOfWeek dayOfWeek = 5; + */ public boolean hasDayOfWeek() { - return (bitField0_ & 0x00000008) == 0x00000008; + return ((bitField0_ & 0x00000008) == 0x00000008); } + /** + * required .org.jboss.netty.example.localtime.DayOfWeek dayOfWeek = 5; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek getDayOfWeek() { return dayOfWeek_; } + /** + * required .org.jboss.netty.example.localtime.DayOfWeek dayOfWeek = 5; + */ public Builder setDayOfWeek(org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek value) { if (value == null) { throw new NullPointerException(); @@ -1907,8 +2389,11 @@ public final class LocalTimeProtocol { onChanged(); return this; } + /** + * required .org.jboss.netty.example.localtime.DayOfWeek dayOfWeek = 5; + */ public Builder clearDayOfWeek() { - bitField0_ = bitField0_ & ~0x00000008; + bitField0_ = (bitField0_ & ~0x00000008); dayOfWeek_ = org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek.SUNDAY; onChanged(); return this; @@ -1916,20 +2401,32 @@ public final class LocalTimeProtocol { // required uint32 hour = 6; private int hour_ ; + /** + * required uint32 hour = 6; + */ public boolean hasHour() { - return (bitField0_ & 0x00000010) == 0x00000010; + return ((bitField0_ & 0x00000010) == 0x00000010); } + /** + * required uint32 hour = 6; + */ public int getHour() { return hour_; } + /** + * required uint32 hour = 6; + */ public Builder setHour(int value) { bitField0_ |= 0x00000010; hour_ = value; onChanged(); return this; } + /** + * required uint32 hour = 6; + */ public Builder clearHour() { - bitField0_ = bitField0_ & ~0x00000010; + bitField0_ = (bitField0_ & ~0x00000010); hour_ = 0; onChanged(); return this; @@ -1937,20 +2434,32 @@ public final class LocalTimeProtocol { // required uint32 minute = 7; private int minute_ ; + /** + * required uint32 minute = 7; + */ public boolean hasMinute() { - return (bitField0_ & 0x00000020) == 0x00000020; + return ((bitField0_ & 0x00000020) == 0x00000020); } + /** + * required uint32 minute = 7; + */ public int getMinute() { return minute_; } + /** + * required uint32 minute = 7; + */ public Builder setMinute(int value) { bitField0_ |= 0x00000020; minute_ = value; onChanged(); return this; } + /** + * required uint32 minute = 7; + */ public Builder clearMinute() { - bitField0_ = bitField0_ & ~0x00000020; + bitField0_ = (bitField0_ & ~0x00000020); minute_ = 0; onChanged(); return this; @@ -1958,20 +2467,32 @@ public final class LocalTimeProtocol { // required uint32 second = 8; private int second_ ; + /** + * required uint32 second = 8; + */ public boolean hasSecond() { - return (bitField0_ & 0x00000040) == 0x00000040; + return ((bitField0_ & 0x00000040) == 0x00000040); } + /** + * required uint32 second = 8; + */ public int getSecond() { return second_; } + /** + * required uint32 second = 8; + */ public Builder setSecond(int value) { bitField0_ |= 0x00000040; second_ = value; onChanged(); return this; } + /** + * required uint32 second = 8; + */ public Builder clearSecond() { - bitField0_ = bitField0_ & ~0x00000040; + bitField0_ = (bitField0_ & ~0x00000040); second_ = 0; onChanged(); return this; @@ -1992,23 +2513,42 @@ public final class LocalTimeProtocol { extends com.google.protobuf.MessageOrBuilder { // repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; - java.util.List + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ + java.util.List getLocalTimeList(); + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime getLocalTime(int index); + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ int getLocalTimeCount(); - java.util.List + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ + java.util.List getLocalTimeOrBuilderList(); + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimeOrBuilder getLocalTimeOrBuilder( int index); } + /** + * Protobuf type {@code org.jboss.netty.example.localtime.LocalTimes} + */ public static final class LocalTimes extends com.google.protobuf.GeneratedMessage implements LocalTimesOrBuilder { // Use LocalTimes.newBuilder() to construct. - private LocalTimes(Builder builder) { + private LocalTimes(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); + this.unknownFields = builder.getUnknownFields(); } - private LocalTimes(boolean noInit) {} + private LocalTimes(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final LocalTimes defaultInstance; public static LocalTimes getDefaultInstance() { @@ -2019,6 +2559,58 @@ public final class LocalTimeProtocol { return defaultInstance; } + private final com.google.protobuf.UnknownFieldSet unknownFields; + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private LocalTimes( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + localTime_ = new java.util.ArrayList(); + mutable_bitField0_ |= 0x00000001; + } + localTime_.add(input.readMessage(org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.PARSER, extensionRegistry)); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e.getMessage()).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + localTime_ = java.util.Collections.unmodifiableList(localTime_); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTimes_descriptor; @@ -2026,25 +2618,57 @@ public final class LocalTimeProtocol { protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTimes_fieldAccessorTable; + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTimes_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.class, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.Builder.class); + } + + public static com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public LocalTimes parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new LocalTimes(input, extensionRegistry); + } + }; + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; } // repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; public static final int LOCALTIME_FIELD_NUMBER = 1; private java.util.List localTime_; + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public java.util.List getLocalTimeList() { return localTime_; } - public java.util.List + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ + public java.util.List getLocalTimeOrBuilderList() { return localTime_; } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public int getLocalTimeCount() { return localTime_.size(); } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime getLocalTime(int index) { return localTime_.get(index); } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimeOrBuilder getLocalTimeOrBuilder( int index) { return localTime_.get(index); @@ -2056,9 +2680,7 @@ public final class LocalTimeProtocol { private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; - if (isInitialized != -1) { - return isInitialized == 1; - } + if (isInitialized != -1) return isInitialized == 1; for (int i = 0; i < getLocalTimeCount(); i++) { if (!getLocalTime(i).isInitialized()) { @@ -2082,9 +2704,7 @@ public final class LocalTimeProtocol { private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; - if (size != -1) { - return size; - } + if (size != -1) return size; size = 0; for (int i = 0; i < localTime_.size(); i++) { @@ -2106,68 +2726,54 @@ public final class LocalTimeProtocol { public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data).buildParsed(); + return PARSER.parseFrom(data); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data, extensionRegistry) - .buildParsed(); + return PARSER.parseFrom(data, extensionRegistry); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data).buildParsed(); + return PARSER.parseFrom(data); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { - return newBuilder().mergeFrom(data, extensionRegistry) - .buildParsed(); + return PARSER.parseFrom(data, extensionRegistry); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom(java.io.InputStream input) throws java.io.IOException { - return newBuilder().mergeFrom(input).buildParsed(); + return PARSER.parseFrom(input); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { - return newBuilder().mergeFrom(input, extensionRegistry) - .buildParsed(); + return PARSER.parseFrom(input, extensionRegistry); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { - Builder builder = newBuilder(); - if (builder.mergeDelimitedFrom(input)) { - return builder.buildParsed(); - } else { - return null; - } + return PARSER.parseDelimitedFrom(input); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { - Builder builder = newBuilder(); - if (builder.mergeDelimitedFrom(input, extensionRegistry)) { - return builder.buildParsed(); - } else { - return null; - } + return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { - return newBuilder().mergeFrom(input).buildParsed(); + return PARSER.parseFrom(input); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { - return newBuilder().mergeFrom(input, extensionRegistry) - .buildParsed(); + return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } @@ -2183,6 +2789,9 @@ public final class LocalTimeProtocol { Builder builder = new Builder(parent); return builder; } + /** + * Protobuf type {@code org.jboss.netty.example.localtime.LocalTimes} + */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimesOrBuilder { @@ -2193,7 +2802,9 @@ public final class LocalTimeProtocol { protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTimes_fieldAccessorTable; + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTimes_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.class, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.Builder.class); } // Construct using org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.newBuilder() @@ -2201,7 +2812,8 @@ public final class LocalTimeProtocol { maybeForceBuilderInitialization(); } - private Builder(BuilderParent parent) { + private Builder( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } @@ -2218,7 +2830,7 @@ public final class LocalTimeProtocol { super.clear(); if (localTimeBuilder_ == null) { localTime_ = java.util.Collections.emptyList(); - bitField0_ = bitField0_ & ~0x00000001; + bitField0_ = (bitField0_ & ~0x00000001); } else { localTimeBuilder_.clear(); } @@ -2231,7 +2843,7 @@ public final class LocalTimeProtocol { public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.getDescriptor(); + return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTimes_descriptor; } public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes getDefaultInstanceForType() { @@ -2246,23 +2858,13 @@ public final class LocalTimeProtocol { return result; } - private org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes buildParsed() - throws com.google.protobuf.InvalidProtocolBufferException { - org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException( - result).asInvalidProtocolBufferException(); - } - return result; - } - public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes buildPartial() { org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes result = new org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes(this); int from_bitField0_ = bitField0_; if (localTimeBuilder_ == null) { - if ((bitField0_ & 0x00000001) == 0x00000001) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { localTime_ = java.util.Collections.unmodifiableList(localTime_); - bitField0_ = bitField0_ & ~0x00000001; + bitField0_ = (bitField0_ & ~0x00000001); } result.localTime_ = localTime_; } else { @@ -2282,14 +2884,12 @@ public final class LocalTimeProtocol { } public Builder mergeFrom(org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes other) { - if (other == org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.getDefaultInstance()) { - return this; - } + if (other == org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.getDefaultInstance()) return this; if (localTimeBuilder_ == null) { if (!other.localTime_.isEmpty()) { if (localTime_.isEmpty()) { localTime_ = other.localTime_; - bitField0_ = bitField0_ & ~0x00000001; + bitField0_ = (bitField0_ & ~0x00000001); } else { ensureLocalTimeIsMutable(); localTime_.addAll(other.localTime_); @@ -2302,8 +2902,8 @@ public final class LocalTimeProtocol { localTimeBuilder_.dispose(); localTimeBuilder_ = null; localTime_ = other.localTime_; - bitField0_ = bitField0_ & ~0x00000001; - localTimeBuilder_ = + bitField0_ = (bitField0_ & ~0x00000001); + localTimeBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getLocalTimeFieldBuilder() : null; } else { @@ -2311,14 +2911,14 @@ public final class LocalTimeProtocol { } } } - mergeUnknownFields(other.getUnknownFields()); + this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { for (int i = 0; i < getLocalTimeCount(); i++) { if (!getLocalTime(i).isInitialized()) { - + return false; } } @@ -2329,35 +2929,19 @@ public final class LocalTimeProtocol { com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder( - getUnknownFields()); - while (true) { - int tag = input.readTag(); - switch (tag) { - case 0: - setUnknownFields(unknownFields.build()); - onChanged(); - return this; - default: { - if (!parseUnknownField(input, unknownFields, - extensionRegistry, tag)) { - setUnknownFields(unknownFields.build()); - onChanged(); - return this; - } - break; - } - case 10: { - org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder subBuilder = org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.newBuilder(); - input.readMessage(subBuilder, extensionRegistry); - addLocalTime(subBuilder.buildPartial()); - break; - } + org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); } } + return this; } - private int bitField0_; // repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; @@ -2373,6 +2957,9 @@ public final class LocalTimeProtocol { private com.google.protobuf.RepeatedFieldBuilder< org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimeOrBuilder> localTimeBuilder_; + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public java.util.List getLocalTimeList() { if (localTimeBuilder_ == null) { return java.util.Collections.unmodifiableList(localTime_); @@ -2380,6 +2967,9 @@ public final class LocalTimeProtocol { return localTimeBuilder_.getMessageList(); } } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public int getLocalTimeCount() { if (localTimeBuilder_ == null) { return localTime_.size(); @@ -2387,6 +2977,9 @@ public final class LocalTimeProtocol { return localTimeBuilder_.getCount(); } } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime getLocalTime(int index) { if (localTimeBuilder_ == null) { return localTime_.get(index); @@ -2394,6 +2987,9 @@ public final class LocalTimeProtocol { return localTimeBuilder_.getMessage(index); } } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public Builder setLocalTime( int index, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime value) { if (localTimeBuilder_ == null) { @@ -2408,6 +3004,9 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public Builder setLocalTime( int index, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder builderForValue) { if (localTimeBuilder_ == null) { @@ -2419,6 +3018,9 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public Builder addLocalTime(org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime value) { if (localTimeBuilder_ == null) { if (value == null) { @@ -2432,6 +3034,9 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public Builder addLocalTime( int index, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime value) { if (localTimeBuilder_ == null) { @@ -2446,6 +3051,9 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public Builder addLocalTime( org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder builderForValue) { if (localTimeBuilder_ == null) { @@ -2457,6 +3065,9 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public Builder addLocalTime( int index, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder builderForValue) { if (localTimeBuilder_ == null) { @@ -2468,6 +3079,9 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public Builder addAllLocalTime( java.lang.Iterable values) { if (localTimeBuilder_ == null) { @@ -2479,16 +3093,22 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public Builder clearLocalTime() { if (localTimeBuilder_ == null) { localTime_ = java.util.Collections.emptyList(); - bitField0_ = bitField0_ & ~0x00000001; + bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { localTimeBuilder_.clear(); } return this; } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public Builder removeLocalTime(int index) { if (localTimeBuilder_ == null) { ensureLocalTimeIsMutable(); @@ -2499,10 +3119,16 @@ public final class LocalTimeProtocol { } return this; } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder getLocalTimeBuilder( int index) { return getLocalTimeFieldBuilder().getBuilder(index); } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimeOrBuilder getLocalTimeOrBuilder( int index) { if (localTimeBuilder_ == null) { @@ -2510,7 +3136,10 @@ public final class LocalTimeProtocol { return localTimeBuilder_.getMessageOrBuilder(index); } } - public java.util.List + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ + public java.util.List getLocalTimeOrBuilderList() { if (localTimeBuilder_ != null) { return localTimeBuilder_.getMessageOrBuilderList(); @@ -2518,27 +3147,36 @@ public final class LocalTimeProtocol { return java.util.Collections.unmodifiableList(localTime_); } } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder addLocalTimeBuilder() { return getLocalTimeFieldBuilder().addBuilder( org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.getDefaultInstance()); } + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder addLocalTimeBuilder( int index) { return getLocalTimeFieldBuilder().addBuilder( index, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.getDefaultInstance()); } - public java.util.List + /** + * repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; + */ + public java.util.List getLocalTimeBuilderList() { return getLocalTimeFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< - org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimeOrBuilder> + org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimeOrBuilder> getLocalTimeFieldBuilder() { if (localTimeBuilder_ == null) { localTimeBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimeOrBuilder>( localTime_, - (bitField0_ & 0x00000001) == 0x00000001, + ((bitField0_ & 0x00000001) == 0x00000001), getParentForChildren(), isClean()); localTime_ = null; @@ -2617,33 +3255,25 @@ public final class LocalTimeProtocol { internal_static_org_jboss_netty_example_localtime_Location_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_jboss_netty_example_localtime_Location_descriptor, - new java.lang.String[] { "Continent", "City", }, - org.jboss.netty.example.localtime.LocalTimeProtocol.Location.class, - org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder.class); + new java.lang.String[] { "Continent", "City", }); internal_static_org_jboss_netty_example_localtime_Locations_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_org_jboss_netty_example_localtime_Locations_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_jboss_netty_example_localtime_Locations_descriptor, - new java.lang.String[] { "Location", }, - org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.class, - org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.Builder.class); + new java.lang.String[] { "Location", }); internal_static_org_jboss_netty_example_localtime_LocalTime_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_org_jboss_netty_example_localtime_LocalTime_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_jboss_netty_example_localtime_LocalTime_descriptor, - new java.lang.String[] { "Year", "Month", "DayOfMonth", "DayOfWeek", "Hour", "Minute", "Second", }, - org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.class, - org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder.class); + new java.lang.String[] { "Year", "Month", "DayOfMonth", "DayOfWeek", "Hour", "Minute", "Second", }); internal_static_org_jboss_netty_example_localtime_LocalTimes_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_org_jboss_netty_example_localtime_LocalTimes_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_jboss_netty_example_localtime_LocalTimes_descriptor, - new java.lang.String[] { "LocalTime", }, - org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.class, - org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.Builder.class); + new java.lang.String[] { "LocalTime", }); return null; } }; diff --git a/src/main/java/org/jboss/netty/example/localtime/LocalTimeServer.java b/src/main/java/org/jboss/netty/example/localtime/LocalTimeServer.java index 7c0b9e6111..dfbfe53214 100644 --- a/src/main/java/org/jboss/netty/example/localtime/LocalTimeServer.java +++ b/src/main/java/org/jboss/netty/example/localtime/LocalTimeServer.java @@ -15,25 +15,33 @@ */ package org.jboss.netty.example.localtime; -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.SelfSignedCertificate; + +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; /** * Receives a list of continent/city pairs from a {@link LocalTimeClient} to * get the local times of the specified cities. */ -public class LocalTimeServer { +public final class LocalTimeServer { - private final int port; + static final boolean SSL = System.getProperty("ssl") != null; + static final int PORT = Integer.parseInt(System.getProperty("port", "8463")); - public LocalTimeServer(int port) { - this.port = port; - } + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + SelfSignedCertificate ssc = new SelfSignedCertificate(); + sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); + } else { + sslCtx = null; + } - public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -41,19 +49,9 @@ public class LocalTimeServer { Executors.newCachedThreadPool())); // Set up the event pipeline factory. - bootstrap.setPipelineFactory(new LocalTimeServerPipelineFactory()); + bootstrap.setPipelineFactory(new LocalTimeServerPipelineFactory(sslCtx)); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(port)); - } - - public static void main(String[] args) throws Exception { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8080; - } - new LocalTimeServer(port).run(); + bootstrap.bind(new InetSocketAddress(PORT)); } } diff --git a/src/main/java/org/jboss/netty/example/localtime/LocalTimeServerHandler.java b/src/main/java/org/jboss/netty/example/localtime/LocalTimeServerHandler.java index f2ff6a3338..8afdc47884 100644 --- a/src/main/java/org/jboss/netty/example/localtime/LocalTimeServerHandler.java +++ b/src/main/java/org/jboss/netty/example/localtime/LocalTimeServerHandler.java @@ -30,36 +30,28 @@ import org.jboss.netty.example.localtime.LocalTimeProtocol.Locations; import java.util.Calendar; import java.util.TimeZone; -import java.util.logging.Level; -import java.util.logging.Logger; import static java.util.Calendar.*; public class LocalTimeServerHandler extends SimpleChannelUpstreamHandler { - private static final Logger logger = Logger.getLogger( - LocalTimeServerHandler.class.getName()); - @Override - public void handleUpstream( - ChannelHandlerContext ctx, ChannelEvent e) throws Exception { + public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { - logger.info(e.toString()); + System.err.println(e); } super.handleUpstream(ctx, e); } @Override - public void messageReceived( - ChannelHandlerContext ctx, MessageEvent e) { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { Locations locations = (Locations) e.getMessage(); long currentTime = System.currentTimeMillis(); LocalTimes.Builder builder = LocalTimes.newBuilder(); for (Location l: locations.getLocationList()) { - TimeZone tz = TimeZone.getTimeZone( - toString(l.getContinent()) + '/' + l.getCity()); + TimeZone tz = TimeZone.getTimeZone(toString(l.getContinent()) + '/' + l.getCity()); Calendar calendar = getInstance(tz); calendar.setTimeInMillis(currentTime); @@ -77,12 +69,8 @@ public class LocalTimeServerHandler extends SimpleChannelUpstreamHandler { } @Override - public void exceptionCaught( - ChannelHandlerContext ctx, ExceptionEvent e) { - logger.log( - Level.WARNING, - "Unexpected exception from downstream.", - e.getCause()); + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { + e.getCause().printStackTrace(); e.getChannel().close(); } diff --git a/src/main/java/org/jboss/netty/example/localtime/LocalTimeServerPipelineFactory.java b/src/main/java/org/jboss/netty/example/localtime/LocalTimeServerPipelineFactory.java index 624c7acde4..eff1c3df48 100644 --- a/src/main/java/org/jboss/netty/example/localtime/LocalTimeServerPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/localtime/LocalTimeServerPipelineFactory.java @@ -15,19 +15,29 @@ */ package org.jboss.netty.example.localtime; -import static org.jboss.netty.channel.Channels.*; - import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.protobuf.ProtobufDecoder; import org.jboss.netty.handler.codec.protobuf.ProtobufEncoder; import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; +import org.jboss.netty.handler.ssl.SslContext; + +import static org.jboss.netty.channel.Channels.*; public class LocalTimeServerPipelineFactory implements ChannelPipelineFactory { - public ChannelPipeline getPipeline() throws Exception { + private final SslContext sslCtx; + + public LocalTimeServerPipelineFactory(SslContext sslCtx) { + this.sslCtx = sslCtx; + } + + public ChannelPipeline getPipeline() { ChannelPipeline p = pipeline(); + if (sslCtx != null) { + p.addLast("ssl", sslCtx.newHandler()); + } p.addLast("frameDecoder", new ProtobufVarint32FrameDecoder()); p.addLast("protobufDecoder", new ProtobufDecoder(LocalTimeProtocol.Locations.getDefaultInstance())); diff --git a/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoClient.java b/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoClient.java index 01273ed113..cd5620aa27 100644 --- a/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoClient.java +++ b/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoClient.java @@ -15,10 +15,8 @@ */ package org.jboss.netty.example.objectecho; -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ClientBootstrap; +import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; @@ -27,64 +25,61 @@ import org.jboss.netty.example.echo.EchoClient; import org.jboss.netty.handler.codec.serialization.ClassResolvers; import org.jboss.netty.handler.codec.serialization.ObjectDecoder; import org.jboss.netty.handler.codec.serialization.ObjectEncoder; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.InsecureTrustManagerFactory; + +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; /** * Modification of {@link EchoClient} which utilizes Java object serialization. */ -public class ObjectEchoClient { +public final class ObjectEchoClient { - private final String host; - private final int port; - private final int firstMessageSize; + static final boolean SSL = System.getProperty("ssl") != null; + static final String HOST = System.getProperty("host", "127.0.0.1"); + static final int PORT = Integer.parseInt(System.getProperty("port", "8007")); + static final int SIZE = Integer.parseInt(System.getProperty("size", "256")); - public ObjectEchoClient(String host, int port, int firstMessageSize) { - this.host = host; - this.port = port; - this.firstMessageSize = firstMessageSize; - } + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); + } else { + sslCtx = null; + } - public void run() { // Configure the client. ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); - // Set up the pipeline factory. - bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - public ChannelPipeline getPipeline() throws Exception { - return Channels.pipeline( - new ObjectEncoder(), - new ObjectDecoder( - ClassResolvers.cacheDisabled(getClass().getClassLoader())), - new ObjectEchoClientHandler(firstMessageSize)); - } - }); + try { + // Set up the pipeline factory. + bootstrap.setPipelineFactory(new ChannelPipelineFactory() { + public ChannelPipeline getPipeline() { + ChannelPipeline p = Channels.pipeline( + new ObjectEncoder(), + new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader())), + new ObjectEchoClientHandler(SIZE) + ); - // Start the connection attempt. - bootstrap.connect(new InetSocketAddress(host, port)); - } + if (sslCtx != null) { + p.addFirst("ssl", sslCtx.newHandler(HOST, PORT)); + } + return p; + } + }); - public static void main(String[] args) throws Exception { - // Print usage if no argument is specified. - if (args.length < 2 || args.length > 3) { - System.err.println( - "Usage: " + ObjectEchoClient.class.getSimpleName() + - " []"); - return; + // Start the connection attempt. + ChannelFuture f = bootstrap.connect(new InetSocketAddress(HOST, PORT)); + + // Wait until the connection attempt is finished and then the connection is closed. + f.sync().getChannel().getCloseFuture().sync(); + } finally { + bootstrap.releaseExternalResources(); } - - // Parse options. - final String host = args[0]; - final int port = Integer.parseInt(args[1]); - final int firstMessageSize; - - if (args.length == 3) { - firstMessageSize = Integer.parseInt(args[2]); - } else { - firstMessageSize = 256; - } - - new ObjectEchoClient(host, port, firstMessageSize).run(); } } diff --git a/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoClientHandler.java b/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoClientHandler.java index 2c868adfe9..68bcf801e2 100644 --- a/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoClientHandler.java +++ b/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoClientHandler.java @@ -15,12 +15,6 @@ */ package org.jboss.netty.example.objectecho; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicLong; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelState; @@ -29,6 +23,10 @@ import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicLong; + /** * Handler implementation for the object echo client. It initiates the * ping-pong traffic between the object echo client and server by sending the @@ -36,9 +34,6 @@ import org.jboss.netty.channel.SimpleChannelUpstreamHandler; */ public class ObjectEchoClientHandler extends SimpleChannelUpstreamHandler { - private static final Logger logger = Logger.getLogger( - ObjectEchoClientHandler.class.getName()); - private final List firstMessage; private final AtomicLong transferredMessages = new AtomicLong(); @@ -47,8 +42,7 @@ public class ObjectEchoClientHandler extends SimpleChannelUpstreamHandler { */ public ObjectEchoClientHandler(int firstMessageSize) { if (firstMessageSize <= 0) { - throw new IllegalArgumentException( - "firstMessageSize: " + firstMessageSize); + throw new IllegalArgumentException("firstMessageSize: " + firstMessageSize); } firstMessage = new ArrayList(firstMessageSize); for (int i = 0; i < firstMessageSize; i ++) { @@ -61,37 +55,30 @@ public class ObjectEchoClientHandler extends SimpleChannelUpstreamHandler { } @Override - public void handleUpstream( - ChannelHandlerContext ctx, ChannelEvent e) throws Exception { + public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent && ((ChannelStateEvent) e).getState() != ChannelState.INTEREST_OPS) { - logger.info(e.toString()); + System.err.println(e); } super.handleUpstream(ctx, e); } @Override - public void channelConnected( - ChannelHandlerContext ctx, ChannelStateEvent e) { + public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) { // Send the first message if this handler is a client-side handler. e.getChannel().write(firstMessage); } @Override - public void messageReceived( - ChannelHandlerContext ctx, MessageEvent e) { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { // Echo back the received object to the server. transferredMessages.incrementAndGet(); e.getChannel().write(e.getMessage()); } @Override - public void exceptionCaught( - ChannelHandlerContext ctx, ExceptionEvent e) { - logger.log( - Level.WARNING, - "Unexpected exception from downstream.", - e.getCause()); + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { + e.getCause().printStackTrace(); e.getChannel().close(); } } diff --git a/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoServer.java b/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoServer.java index 050b63f57b..225b39d4e8 100644 --- a/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoServer.java +++ b/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoServer.java @@ -15,9 +15,6 @@ */ package org.jboss.netty.example.objectecho; -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; @@ -27,19 +24,30 @@ import org.jboss.netty.example.echo.EchoServer; import org.jboss.netty.handler.codec.serialization.ClassResolvers; import org.jboss.netty.handler.codec.serialization.ObjectDecoder; import org.jboss.netty.handler.codec.serialization.ObjectEncoder; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.SelfSignedCertificate; + +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; /** * Modification of {@link EchoServer} which utilizes Java object serialization. */ -public class ObjectEchoServer { +public final class ObjectEchoServer { - private final int port; + static final boolean SSL = System.getProperty("ssl") != null; + static final int PORT = Integer.parseInt(System.getProperty("port", "8007")); - public ObjectEchoServer(int port) { - this.port = port; - } + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + SelfSignedCertificate ssc = new SelfSignedCertificate(); + sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); + } else { + sslCtx = null; + } - public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -48,26 +56,19 @@ public class ObjectEchoServer { // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - public ChannelPipeline getPipeline() throws Exception { - return Channels.pipeline( + public ChannelPipeline getPipeline() { + ChannelPipeline p = Channels.pipeline( new ObjectEncoder(), - new ObjectDecoder( - ClassResolvers.cacheDisabled(getClass().getClassLoader())), + new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader())), new ObjectEchoServerHandler()); + if (sslCtx != null) { + p.addFirst("ssl", sslCtx.newHandler()); + } + return p; } }); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(port)); - } - - public static void main(String[] args) throws Exception { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8080; - } - new ObjectEchoServer(port).run(); + bootstrap.bind(new InetSocketAddress(PORT)); } } diff --git a/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoServerHandler.java b/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoServerHandler.java index f127a03250..1f794950e9 100644 --- a/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoServerHandler.java +++ b/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoServerHandler.java @@ -15,10 +15,6 @@ */ package org.jboss.netty.example.objectecho; -import java.util.concurrent.atomic.AtomicLong; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelState; @@ -27,15 +23,14 @@ import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; +import java.util.concurrent.atomic.AtomicLong; + /** * Handles both client-side and server-side handler depending on which * constructor was called. */ public class ObjectEchoServerHandler extends SimpleChannelUpstreamHandler { - private static final Logger logger = Logger.getLogger( - ObjectEchoServerHandler.class.getName()); - private final AtomicLong transferredMessages = new AtomicLong(); public long getTransferredMessages() { @@ -43,30 +38,23 @@ public class ObjectEchoServerHandler extends SimpleChannelUpstreamHandler { } @Override - public void handleUpstream( - ChannelHandlerContext ctx, ChannelEvent e) throws Exception { - if (e instanceof ChannelStateEvent && - ((ChannelStateEvent) e).getState() != ChannelState.INTEREST_OPS) { - logger.info(e.toString()); + public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { + if (e instanceof ChannelStateEvent && ((ChannelStateEvent) e).getState() != ChannelState.INTEREST_OPS) { + System.err.println(e); } super.handleUpstream(ctx, e); } @Override - public void messageReceived( - ChannelHandlerContext ctx, MessageEvent e) { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { // Echo back the received object to the client. transferredMessages.incrementAndGet(); e.getChannel().write(e.getMessage()); } @Override - public void exceptionCaught( - ChannelHandlerContext ctx, ExceptionEvent e) { - logger.log( - Level.WARNING, - "Unexpected exception from downstream.", - e.getCause()); + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { + e.getCause().printStackTrace(); e.getChannel().close(); } } diff --git a/src/main/java/org/jboss/netty/example/portunification/PortUnificationServer.java b/src/main/java/org/jboss/netty/example/portunification/PortUnificationServer.java index 4d1ceef733..d04ea51393 100644 --- a/src/main/java/org/jboss/netty/example/portunification/PortUnificationServer.java +++ b/src/main/java/org/jboss/netty/example/portunification/PortUnificationServer.java @@ -33,17 +33,15 @@ import java.util.concurrent.Executors; * Because SSL and GZIP are enabled on demand, 5 combinations per protocol * are possible: none, SSL only, GZIP only, SSL + GZIP, and GZIP + SSL. */ -public class PortUnificationServer { +public final class PortUnificationServer { - private final SslContext sslCtx; - private final int port; + static final int PORT = Integer.parseInt(System.getProperty("port", "8080")); - public PortUnificationServer(SslContext sslCtx, int port) { - this.sslCtx = sslCtx; - this.port = port; - } + public static void main(String[] args) throws Exception { + // Configure SSL context + SelfSignedCertificate ssc = new SelfSignedCertificate(); + final SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); - public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -52,28 +50,12 @@ public class PortUnificationServer { // Set up the event pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - public ChannelPipeline getPipeline() throws Exception { + public ChannelPipeline getPipeline() { return Channels.pipeline(new PortUnificationServerHandler(sslCtx)); } }); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(port)); - } - - public static void main(String[] args) throws Exception { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8080; - } - - // Configure SSL context - SelfSignedCertificate ssc = new SelfSignedCertificate(); - final SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); - - // Start the server. - new PortUnificationServer(sslCtx, port).run(); + bootstrap.bind(new InetSocketAddress(PORT)); } } diff --git a/src/main/java/org/jboss/netty/example/portunification/PortUnificationServerHandler.java b/src/main/java/org/jboss/netty/example/portunification/PortUnificationServerHandler.java index 2286c2487e..3ab61c4f26 100644 --- a/src/main/java/org/jboss/netty/example/portunification/PortUnificationServerHandler.java +++ b/src/main/java/org/jboss/netty/example/portunification/PortUnificationServerHandler.java @@ -54,7 +54,7 @@ public class PortUnificationServerHandler extends FrameDecoder { } @Override - protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { + protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) { // Will use the first 5 bytes to detect a protocol. if (buffer.readableBytes() < 5) { return null; diff --git a/src/main/java/org/jboss/netty/example/proxy/HexDumpProxy.java b/src/main/java/org/jboss/netty/example/proxy/HexDumpProxy.java index f6d6567f67..da438fc467 100644 --- a/src/main/java/org/jboss/netty/example/proxy/HexDumpProxy.java +++ b/src/main/java/org/jboss/netty/example/proxy/HexDumpProxy.java @@ -15,62 +15,34 @@ */ package org.jboss.netty.example.proxy; -import java.net.InetSocketAddress; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; -public class HexDumpProxy { +import java.net.InetSocketAddress; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; - private final int localPort; - private final String remoteHost; - private final int remotePort; +public final class HexDumpProxy { - public HexDumpProxy(int localPort, String remoteHost, int remotePort) { - this.localPort = localPort; - this.remoteHost = remoteHost; - this.remotePort = remotePort; - } + static final int LOCAL_PORT = Integer.parseInt(System.getProperty("localPort", "8443")); + static final String REMOTE_HOST = System.getProperty("remoteHost", "www.google.com"); + static final int REMOTE_PORT = Integer.parseInt(System.getProperty("remotePort", "443")); - public void run() { - System.err.println( - "Proxying *:" + localPort + " to " + - remoteHost + ':' + remotePort + " ..."); + public static void main(String[] args) { + System.err.println("Proxying *:" + LOCAL_PORT + " to " + REMOTE_HOST + ':' + REMOTE_PORT + " ..."); // Configure the bootstrap. Executor executor = Executors.newCachedThreadPool(); - ServerBootstrap sb = new ServerBootstrap( - new NioServerSocketChannelFactory(executor, executor)); + ServerBootstrap sb = new ServerBootstrap(new NioServerSocketChannelFactory(executor, executor)); // Set up the event pipeline factory. - ClientSocketChannelFactory cf = - new NioClientSocketChannelFactory(executor, executor); + ClientSocketChannelFactory cf = new NioClientSocketChannelFactory(executor, executor); - sb.setPipelineFactory( - new HexDumpProxyPipelineFactory(cf, remoteHost, remotePort)); + sb.setPipelineFactory(new HexDumpProxyPipelineFactory(cf)); // Start up the server. - sb.bind(new InetSocketAddress(localPort)); - } - - public static void main(String[] args) throws Exception { - // Validate command line options. - if (args.length != 3) { - System.err.println( - "Usage: " + HexDumpProxy.class.getSimpleName() + - " "); - return; - } - - // Parse command line options. - int localPort = Integer.parseInt(args[0]); - String remoteHost = args[1]; - int remotePort = Integer.parseInt(args[2]); - - new HexDumpProxy(localPort, remoteHost, remotePort).run(); + sb.bind(new InetSocketAddress(LOCAL_PORT)); } } diff --git a/src/main/java/org/jboss/netty/example/proxy/HexDumpProxyInboundHandler.java b/src/main/java/org/jboss/netty/example/proxy/HexDumpProxyInboundHandler.java index a00065ebfb..9751a7b86c 100644 --- a/src/main/java/org/jboss/netty/example/proxy/HexDumpProxyInboundHandler.java +++ b/src/main/java/org/jboss/netty/example/proxy/HexDumpProxyInboundHandler.java @@ -15,8 +15,6 @@ */ package org.jboss.netty.example.proxy; -import java.net.InetSocketAddress; - import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; @@ -30,11 +28,11 @@ import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; +import java.net.InetSocketAddress; + public class HexDumpProxyInboundHandler extends SimpleChannelUpstreamHandler { private final ClientSocketChannelFactory cf; - private final String remoteHost; - private final int remotePort; // This lock guards against the race condition that overrides the // OP_READ flag incorrectly. @@ -43,16 +41,12 @@ public class HexDumpProxyInboundHandler extends SimpleChannelUpstreamHandler { private volatile Channel outboundChannel; - public HexDumpProxyInboundHandler( - ClientSocketChannelFactory cf, String remoteHost, int remotePort) { + public HexDumpProxyInboundHandler(ClientSocketChannelFactory cf) { this.cf = cf; - this.remoteHost = remoteHost; - this.remotePort = remotePort; } @Override - public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) - throws Exception { + public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) { // Suspend incoming traffic until connected to the remote host. final Channel inboundChannel = e.getChannel(); inboundChannel.setReadable(false); @@ -60,11 +54,11 @@ public class HexDumpProxyInboundHandler extends SimpleChannelUpstreamHandler { // Start the connection attempt. ClientBootstrap cb = new ClientBootstrap(cf); cb.getPipeline().addLast("handler", new OutboundHandler(e.getChannel())); - ChannelFuture f = cb.connect(new InetSocketAddress(remoteHost, remotePort)); + ChannelFuture f = cb.connect(new InetSocketAddress(HexDumpProxy.REMOTE_HOST, HexDumpProxy.REMOTE_PORT)); outboundChannel = f.getChannel(); f.addListener(new ChannelFutureListener() { - public void operationComplete(ChannelFuture future) throws Exception { + public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { // Connection attempt succeeded: // Begin to accept incoming traffic. @@ -78,10 +72,9 @@ public class HexDumpProxyInboundHandler extends SimpleChannelUpstreamHandler { } @Override - public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) - throws Exception { + public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) { ChannelBuffer msg = (ChannelBuffer) e.getMessage(); - //System.out.println(">>> " + ChannelBuffers.hexDump(msg)); + //System.err.println(">>> " + ChannelBuffers.hexDump(msg)); synchronized (trafficLock) { outboundChannel.write(msg); // If outboundChannel is saturated, do not read until notified in @@ -93,8 +86,7 @@ public class HexDumpProxyInboundHandler extends SimpleChannelUpstreamHandler { } @Override - public void channelInterestChanged(ChannelHandlerContext ctx, - ChannelStateEvent e) throws Exception { + public void channelInterestChanged(ChannelHandlerContext ctx, ChannelStateEvent e) { // If inboundChannel is not saturated anymore, continue accepting // the incoming traffic from the outboundChannel. synchronized (trafficLock) { @@ -107,16 +99,14 @@ public class HexDumpProxyInboundHandler extends SimpleChannelUpstreamHandler { } @Override - public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) - throws Exception { + public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) { if (outboundChannel != null) { closeOnFlush(outboundChannel); } } @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) - throws Exception { + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { e.getCause().printStackTrace(); closeOnFlush(e.getChannel()); } @@ -130,10 +120,9 @@ public class HexDumpProxyInboundHandler extends SimpleChannelUpstreamHandler { } @Override - public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) - throws Exception { + public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) { ChannelBuffer msg = (ChannelBuffer) e.getMessage(); - //System.out.println("<<< " + ChannelBuffers.hexDump(msg)); + //System.err.println("<<< " + ChannelBuffers.hexDump(msg)); synchronized (trafficLock) { inboundChannel.write(msg); // If inboundChannel is saturated, do not read until notified in @@ -145,8 +134,7 @@ public class HexDumpProxyInboundHandler extends SimpleChannelUpstreamHandler { } @Override - public void channelInterestChanged(ChannelHandlerContext ctx, - ChannelStateEvent e) throws Exception { + public void channelInterestChanged(ChannelHandlerContext ctx, ChannelStateEvent e) { // If outboundChannel is not saturated anymore, continue accepting // the incoming traffic from the inboundChannel. synchronized (trafficLock) { @@ -157,14 +145,12 @@ public class HexDumpProxyInboundHandler extends SimpleChannelUpstreamHandler { } @Override - public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) - throws Exception { + public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) { closeOnFlush(inboundChannel); } @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) - throws Exception { + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { e.getCause().printStackTrace(); closeOnFlush(e.getChannel()); } diff --git a/src/main/java/org/jboss/netty/example/proxy/HexDumpProxyPipelineFactory.java b/src/main/java/org/jboss/netty/example/proxy/HexDumpProxyPipelineFactory.java index b492394210..d93cf6006c 100644 --- a/src/main/java/org/jboss/netty/example/proxy/HexDumpProxyPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/proxy/HexDumpProxyPipelineFactory.java @@ -15,28 +15,23 @@ */ package org.jboss.netty.example.proxy; -import static org.jboss.netty.channel.Channels.*; - import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; +import static org.jboss.netty.channel.Channels.*; + public class HexDumpProxyPipelineFactory implements ChannelPipelineFactory { private final ClientSocketChannelFactory cf; - private final String remoteHost; - private final int remotePort; - public HexDumpProxyPipelineFactory( - ClientSocketChannelFactory cf, String remoteHost, int remotePort) { + public HexDumpProxyPipelineFactory(ClientSocketChannelFactory cf) { this.cf = cf; - this.remoteHost = remoteHost; - this.remotePort = remotePort; } - public ChannelPipeline getPipeline() throws Exception { + public ChannelPipeline getPipeline() { ChannelPipeline p = pipeline(); // Note the static import. - p.addLast("handler", new HexDumpProxyInboundHandler(cf, remoteHost, remotePort)); + p.addLast("handler", new HexDumpProxyInboundHandler(cf)); return p; } } diff --git a/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentClient.java b/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentClient.java index 65c56b5bd7..464c650ccc 100644 --- a/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentClient.java +++ b/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentClient.java @@ -15,91 +15,76 @@ */ package org.jboss.netty.example.qotm; -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ConnectionlessBootstrap; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.FixedReceiveBufferSizePredictorFactory; import org.jboss.netty.channel.socket.DatagramChannel; -import org.jboss.netty.channel.socket.DatagramChannelFactory; import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; import org.jboss.netty.util.CharsetUtil; +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; + /** - * A UDP broadcast client that asks for a quote of the moment (QOTM) to - * {@link QuoteOfTheMomentServer}. + * A UDP broadcast client that asks for a quote of the moment (QOTM) to {@link QuoteOfTheMomentServer}. * - * Inspired by the official Java tutorial. + * Inspired by the official + * Java tutorial. */ -public class QuoteOfTheMomentClient { +public final class QuoteOfTheMomentClient { - private final int port; - - public QuoteOfTheMomentClient(int port) { - this.port = port; - } - - public void run() { - DatagramChannelFactory f = - new NioDatagramChannelFactory(Executors.newCachedThreadPool()); - - ConnectionlessBootstrap b = new ConnectionlessBootstrap(f); - - // Configure the pipeline factory. - b.setPipelineFactory(new ChannelPipelineFactory() { - public ChannelPipeline getPipeline() throws Exception { - return Channels.pipeline( - new StringEncoder(CharsetUtil.ISO_8859_1), - new StringDecoder(CharsetUtil.ISO_8859_1), - new QuoteOfTheMomentClientHandler()); - } - }); - - // Enable broadcast - b.setOption("broadcast", "true"); - - // Allow packets as large as up to 1024 bytes (default is 768). - // You could increase or decrease this value to avoid truncated packets - // or to improve memory footprint respectively. - // - // Please also note that a large UDP packet might be truncated or - // dropped by your router no matter how you configured this option. - // In UDP, a packet is truncated or dropped if it is larger than a - // certain size, depending on router configuration. IPv4 routers - // truncate and IPv6 routers drop a large packet. That's why it is - // safe to send small packets in UDP. - b.setOption( - "receiveBufferSizePredictorFactory", - new FixedReceiveBufferSizePredictorFactory(1024)); - - DatagramChannel c = (DatagramChannel) b.bind(new InetSocketAddress(0)); - - // Broadcast the QOTM request to port 8080. - c.write("QOTM?", new InetSocketAddress("255.255.255.255", port)); - - // QuoteOfTheMomentClientHandler will close the DatagramChannel when a - // response is received. If the channel is not closed within 5 seconds, - // print an error message and quit. - if (!c.getCloseFuture().awaitUninterruptibly(5000)) { - System.err.println("QOTM request timed out."); - c.close().awaitUninterruptibly(); - } - - f.releaseExternalResources(); - } + static final int PORT = Integer.parseInt(System.getProperty("port", "7686")); public static void main(String[] args) throws Exception { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8080; + ConnectionlessBootstrap b = new ConnectionlessBootstrap( + new NioDatagramChannelFactory(Executors.newCachedThreadPool())); + + try { + // Configure the pipeline factory. + b.setPipelineFactory(new ChannelPipelineFactory() { + public ChannelPipeline getPipeline() { + return Channels.pipeline( + new StringEncoder(CharsetUtil.ISO_8859_1), + new StringDecoder(CharsetUtil.ISO_8859_1), + new QuoteOfTheMomentClientHandler()); + } + }); + + // Enable broadcast + b.setOption("broadcast", "true"); + + // Allow packets as large as up to 1024 bytes (default is 768). + // You could increase or decrease this value to avoid truncated packets + // or to improve memory footprint respectively. + // + // Please also note that a large UDP packet might be truncated or + // dropped by your router no matter how you configured this option. + // In UDP, a packet is truncated or dropped if it is larger than a + // certain size, depending on router configuration. IPv4 routers + // truncate and IPv6 routers drop a large packet. That's why it is + // safe to send small packets in UDP. + b.setOption( + "receiveBufferSizePredictorFactory", + new FixedReceiveBufferSizePredictorFactory(1024)); + + DatagramChannel c = (DatagramChannel) b.bind(new InetSocketAddress(0)); + + // Broadcast the QOTM request to port 8080. + c.write("QOTM?", new InetSocketAddress("255.255.255.255", PORT)); + + // QuoteOfTheMomentClientHandler will close the DatagramChannel when a + // response is received. If the channel is not closed within 5 seconds, + // print an error message and quit. + if (!c.getCloseFuture().await(5000)) { + System.err.println("QOTM request timed out."); + c.close().sync(); + } + } finally { + b.releaseExternalResources(); } - new QuoteOfTheMomentClient(port).run(); } } diff --git a/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentClientHandler.java b/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentClientHandler.java index 9267732fbc..e7e112f9a6 100644 --- a/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentClientHandler.java +++ b/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentClientHandler.java @@ -23,8 +23,7 @@ import org.jboss.netty.channel.SimpleChannelUpstreamHandler; public class QuoteOfTheMomentClientHandler extends SimpleChannelUpstreamHandler { @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) - throws Exception { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { String msg = (String) e.getMessage(); if (msg.startsWith("QOTM: ")) { System.out.println("Quote of the Moment: " + msg.substring(6)); @@ -33,8 +32,7 @@ public class QuoteOfTheMomentClientHandler extends SimpleChannelUpstreamHandler } @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) - throws Exception { + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { e.getCause().printStackTrace(); e.getChannel().close(); } diff --git a/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentServer.java b/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentServer.java index ad65eacd1a..5584e7940c 100644 --- a/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentServer.java +++ b/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentServer.java @@ -15,40 +15,34 @@ */ package org.jboss.netty.example.qotm; -import java.net.InetSocketAddress; - import org.jboss.netty.bootstrap.ConnectionlessBootstrap; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.FixedReceiveBufferSizePredictorFactory; -import org.jboss.netty.channel.socket.DatagramChannelFactory; import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; import org.jboss.netty.util.CharsetUtil; +import java.net.InetSocketAddress; + /** - * A UDP server that responds to the QOTM (quote of the moment) request to a - * {@link QuoteOfTheMomentClient}. + * A UDP server that responds to the QOTM (quote of the moment) request to a {@link QuoteOfTheMomentClient}. * - * Inspired by the official Java tutorial. + * Inspired by the official + * Java tutorial. */ -public class QuoteOfTheMomentServer { +public final class QuoteOfTheMomentServer { - private final int port; + private static final int PORT = Integer.parseInt(System.getProperty("port", "7686")); - public QuoteOfTheMomentServer(int port) { - this.port = port; - } - - public void run() { - DatagramChannelFactory f = new NioDatagramChannelFactory(); - ConnectionlessBootstrap b = new ConnectionlessBootstrap(f); + public static void main(String[] args) throws Exception { + ConnectionlessBootstrap b = new ConnectionlessBootstrap(new NioDatagramChannelFactory()); // Configure the pipeline factory. b.setPipelineFactory(new ChannelPipelineFactory() { - public ChannelPipeline getPipeline() throws Exception { + public ChannelPipeline getPipeline() { return Channels.pipeline( new StringEncoder(CharsetUtil.ISO_8859_1), new StringDecoder(CharsetUtil.ISO_8859_1), @@ -74,16 +68,6 @@ public class QuoteOfTheMomentServer { new FixedReceiveBufferSizePredictorFactory(1024)); // Bind to the port and start the service. - b.bind(new InetSocketAddress(port)); - } - - public static void main(String[] args) throws Exception { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8080; - } - new QuoteOfTheMomentServer(port).run(); + b.bind(new InetSocketAddress(PORT)); } } diff --git a/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentServerHandler.java b/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentServerHandler.java index 6db14003be..d48905b49b 100644 --- a/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentServerHandler.java +++ b/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentServerHandler.java @@ -15,13 +15,13 @@ */ package org.jboss.netty.example.qotm; -import java.util.Random; - import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; +import java.util.Random; + public class QuoteOfTheMomentServerHandler extends SimpleChannelUpstreamHandler { private static final Random random = new Random(); @@ -43,8 +43,7 @@ public class QuoteOfTheMomentServerHandler extends SimpleChannelUpstreamHandler } @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) - throws Exception { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { String msg = (String) e.getMessage(); if ("QOTM?".equals(msg)) { e.getChannel().write("QOTM: " + nextQuote(), e.getRemoteAddress()); @@ -52,8 +51,7 @@ public class QuoteOfTheMomentServerHandler extends SimpleChannelUpstreamHandler } @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) - throws Exception { + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { e.getCause().printStackTrace(); // We don't close the channel because we can keep serving requests. } diff --git a/src/main/java/org/jboss/netty/example/securechat/SecureChatClient.java b/src/main/java/org/jboss/netty/example/securechat/SecureChatClient.java index ff7ffcc734..05104eb706 100644 --- a/src/main/java/org/jboss/netty/example/securechat/SecureChatClient.java +++ b/src/main/java/org/jboss/netty/example/securechat/SecureChatClient.java @@ -24,7 +24,6 @@ import org.jboss.netty.handler.ssl.SslContext; import org.jboss.netty.handler.ssl.util.InsecureTrustManagerFactory; import java.io.BufferedReader; -import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.util.concurrent.Executors; @@ -32,88 +31,63 @@ import java.util.concurrent.Executors; /** * Simple SSL chat client modified from {@link TelnetClient}. */ -public class SecureChatClient { +public final class SecureChatClient { - private final SslContext sslCtx; - private final String host; - private final int port; + static final String HOST = System.getProperty("host", "127.0.0.1"); + static final int PORT = Integer.parseInt(System.getProperty("port", "8992")); - public SecureChatClient(SslContext sslCtx, String host, int port) { - this.sslCtx = sslCtx; - this.host = host; - this.port = port; - } + public static void main(String[] args) throws Exception { + + // Configure SSL. + final SslContext sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); - public void run() throws IOException { // Configure the client. ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); - // Configure the pipeline factory. - bootstrap.setPipelineFactory(new SecureChatClientPipelineFactory(sslCtx)); + try { + // Configure the pipeline factory. + bootstrap.setPipelineFactory(new SecureChatClientPipelineFactory(sslCtx)); - // Start the connection attempt. - ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); + // Start the connection attempt. + ChannelFuture future = bootstrap.connect(new InetSocketAddress(HOST, PORT)); - // Wait until the connection attempt succeeds or fails. - Channel channel = future.awaitUninterruptibly().getChannel(); - if (!future.isSuccess()) { - future.getCause().printStackTrace(); + // Wait until the connection attempt succeeds or fails. + Channel channel = future.sync().getChannel(); + + // Read commands from the stdin. + ChannelFuture lastWriteFuture = null; + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + for (;;) { + String line = in.readLine(); + if (line == null) { + break; + } + + // Sends the received line to the server. + lastWriteFuture = channel.write(line + "\r\n"); + + // If user typed the 'bye' command, wait until the server closes + // the connection. + if ("bye".equals(line.toLowerCase())) { + channel.getCloseFuture().sync(); + break; + } + } + + // Wait until all messages are flushed before closing the channel. + if (lastWriteFuture != null) { + lastWriteFuture.sync(); + } + + // Close the connection. Make sure the close operation ends because + // all I/O operations are asynchronous in Netty. + channel.close().sync(); + } finally { + // Shut down all thread pools to exit. bootstrap.releaseExternalResources(); - return; } - - // Read commands from the stdin. - ChannelFuture lastWriteFuture = null; - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - for (;;) { - String line = in.readLine(); - if (line == null) { - break; - } - - // Sends the received line to the server. - lastWriteFuture = channel.write(line + "\r\n"); - - // If user typed the 'bye' command, wait until the server closes - // the connection. - if ("bye".equals(line.toLowerCase())) { - channel.getCloseFuture().awaitUninterruptibly(); - break; - } - } - - // Wait until all messages are flushed before closing the channel. - if (lastWriteFuture != null) { - lastWriteFuture.awaitUninterruptibly(); - } - - // Close the connection. Make sure the close operation ends because - // all I/O operations are asynchronous in Netty. - channel.close().awaitUninterruptibly(); - - // Shut down all thread pools to exit. - bootstrap.releaseExternalResources(); - } - - public static void main(String[] args) throws Exception { - // Print usage if no argument is specified. - if (args.length != 2) { - System.err.println( - "Usage: " + SecureChatClient.class.getSimpleName() + - " "); - return; - } - - // Parse options. - String host = args[0]; - int port = Integer.parseInt(args[1]); - - // Configure the SSL context. - SslContext sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); - - new SecureChatClient(sslCtx, host, port).run(); } } diff --git a/src/main/java/org/jboss/netty/example/securechat/SecureChatClientHandler.java b/src/main/java/org/jboss/netty/example/securechat/SecureChatClientHandler.java index 8568f9a4dd..03c996beff 100644 --- a/src/main/java/org/jboss/netty/example/securechat/SecureChatClientHandler.java +++ b/src/main/java/org/jboss/netty/example/securechat/SecureChatClientHandler.java @@ -15,58 +15,34 @@ */ package org.jboss.netty.example.securechat; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; -import org.jboss.netty.handler.ssl.SslHandler; /** * Handles a client-side channel. */ public class SecureChatClientHandler extends SimpleChannelUpstreamHandler { - private static final Logger logger = Logger.getLogger( - SecureChatClientHandler.class.getName()); - @Override - public void handleUpstream( - ChannelHandlerContext ctx, ChannelEvent e) throws Exception { + public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { - logger.info(e.toString()); + System.err.println(e); } super.handleUpstream(ctx, e); } @Override - public void channelConnected( - ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { - // Get the SslHandler from the pipeline - // which were added in SecureChatPipelineFactory. - SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class); - - // Begin handshake. - sslHandler.handshake(); - } - - @Override - public void messageReceived( - ChannelHandlerContext ctx, MessageEvent e) { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { System.err.println(e.getMessage()); } @Override - public void exceptionCaught( - ChannelHandlerContext ctx, ExceptionEvent e) { - logger.log( - Level.WARNING, - "Unexpected exception from downstream.", - e.getCause()); + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { + e.getCause().printStackTrace(); e.getChannel().close(); } } diff --git a/src/main/java/org/jboss/netty/example/securechat/SecureChatClientPipelineFactory.java b/src/main/java/org/jboss/netty/example/securechat/SecureChatClientPipelineFactory.java index 83a6db05a6..3cb6ac2ed7 100644 --- a/src/main/java/org/jboss/netty/example/securechat/SecureChatClientPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/securechat/SecureChatClientPipelineFactory.java @@ -36,7 +36,7 @@ public class SecureChatClientPipelineFactory implements ChannelPipelineFactory { this.sslCtx = sslCtx; } - public ChannelPipeline getPipeline() throws Exception { + public ChannelPipeline getPipeline() { ChannelPipeline pipeline = pipeline(); // Add SSL handler first to encrypt and decrypt everything. @@ -44,11 +44,10 @@ public class SecureChatClientPipelineFactory implements ChannelPipelineFactory { // and accept any invalid certificates in the client side. // You will need something more complicated to identify both // and server in the real world. - pipeline.addLast("ssl", sslCtx.newHandler()); + pipeline.addLast("ssl", sslCtx.newHandler(SecureChatClient.HOST, SecureChatClient.PORT)); // On top of the SSL handler, add the text line codec. - pipeline.addLast("framer", new DelimiterBasedFrameDecoder( - 8192, Delimiters.lineDelimiter())); + pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("encoder", new StringEncoder()); diff --git a/src/main/java/org/jboss/netty/example/securechat/SecureChatServer.java b/src/main/java/org/jboss/netty/example/securechat/SecureChatServer.java index db8c62ecfd..460dac589d 100644 --- a/src/main/java/org/jboss/netty/example/securechat/SecureChatServer.java +++ b/src/main/java/org/jboss/netty/example/securechat/SecureChatServer.java @@ -27,17 +27,14 @@ import java.util.concurrent.Executors; /** * Simple SSL chat server modified from {@link TelnetServer}. */ -public class SecureChatServer { +public final class SecureChatServer { - private final SslContext sslCtx; - private final int port; + static final int PORT = Integer.parseInt(System.getProperty("port", "8992")); - public SecureChatServer(SslContext sslCtx, int port) { - this.sslCtx = sslCtx; - this.port = port; - } + public static void main(String[] args) throws Exception { + SelfSignedCertificate ssc = new SelfSignedCertificate(); + SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); - public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -48,19 +45,6 @@ public class SecureChatServer { bootstrap.setPipelineFactory(new SecureChatServerPipelineFactory(sslCtx)); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(port)); - } - - public static void main(String[] args) throws Exception { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8443; - } - - SelfSignedCertificate ssc = new SelfSignedCertificate(); - SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); - new SecureChatServer(sslCtx, port).run(); + bootstrap.bind(new InetSocketAddress(PORT)); } } diff --git a/src/main/java/org/jboss/netty/example/securechat/SecureChatServerHandler.java b/src/main/java/org/jboss/netty/example/securechat/SecureChatServerHandler.java index 199c176e9c..4b6cce59d5 100644 --- a/src/main/java/org/jboss/netty/example/securechat/SecureChatServerHandler.java +++ b/src/main/java/org/jboss/netty/example/securechat/SecureChatServerHandler.java @@ -29,32 +29,24 @@ import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.handler.ssl.SslHandler; import java.net.InetAddress; -import java.util.logging.Level; -import java.util.logging.Logger; /** * Handles a server-side channel. */ public class SecureChatServerHandler extends SimpleChannelUpstreamHandler { - private static final Logger logger = Logger.getLogger( - SecureChatServerHandler.class.getName()); - static final ChannelGroup channels = new DefaultChannelGroup(); @Override - public void handleUpstream( - ChannelHandlerContext ctx, ChannelEvent e) throws Exception { + public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { - logger.info(e.toString()); + System.err.println(e); } super.handleUpstream(ctx, e); } @Override - public void channelConnected( - ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { - + public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) { // Get the SslHandler in the current pipeline. // We added it in SecureChatPipelineFactory. final SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class); @@ -65,16 +57,14 @@ public class SecureChatServerHandler extends SimpleChannelUpstreamHandler { } @Override - public void channelDisconnected( - ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { + public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) { // Unregister the channel from the global channel list // so the channel does not receive messages anymore. channels.remove(e.getChannel()); } @Override - public void messageReceived( - ChannelHandlerContext ctx, MessageEvent e) { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { // Convert to a String first. String request = (String) e.getMessage(); @@ -96,12 +86,8 @@ public class SecureChatServerHandler extends SimpleChannelUpstreamHandler { } @Override - public void exceptionCaught( - ChannelHandlerContext ctx, ExceptionEvent e) { - logger.log( - Level.WARNING, - "Unexpected exception from downstream.", - e.getCause()); + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { + e.getCause().printStackTrace(); e.getChannel().close(); } @@ -117,11 +103,9 @@ public class SecureChatServerHandler extends SimpleChannelUpstreamHandler { if (future.isSuccess()) { // Once session is secured, send a greeting. future.getChannel().write( - "Welcome to " + InetAddress.getLocalHost().getHostName() + - " secure chat service!\n"); + "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n"); future.getChannel().write( - "Your session is protected by " + - sslHandler.getEngine().getSession().getCipherSuite() + + "Your session is protected by " + sslHandler.getEngine().getSession().getCipherSuite() + " cipher suite.\n"); // Register the channel to the global channel list diff --git a/src/main/java/org/jboss/netty/example/securechat/SecureChatServerPipelineFactory.java b/src/main/java/org/jboss/netty/example/securechat/SecureChatServerPipelineFactory.java index 5303b7bc28..fff6eedaa5 100644 --- a/src/main/java/org/jboss/netty/example/securechat/SecureChatServerPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/securechat/SecureChatServerPipelineFactory.java @@ -36,7 +36,7 @@ public class SecureChatServerPipelineFactory implements ChannelPipelineFactory { this.sslCtx = sslCtx; } - public ChannelPipeline getPipeline() throws Exception { + public ChannelPipeline getPipeline() { ChannelPipeline pipeline = pipeline(); // Add SSL handler first to encrypt and decrypt everything. @@ -47,8 +47,7 @@ public class SecureChatServerPipelineFactory implements ChannelPipelineFactory { pipeline.addLast("ssl", sslCtx.newHandler()); // On top of the SSL handler, add the text line codec. - pipeline.addLast("framer", new DelimiterBasedFrameDecoder( - 8192, Delimiters.lineDelimiter())); + pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("encoder", new StringEncoder()); diff --git a/src/main/java/org/jboss/netty/example/telnet/TelnetClient.java b/src/main/java/org/jboss/netty/example/telnet/TelnetClient.java index 4efd5cba5a..5811a76052 100644 --- a/src/main/java/org/jboss/netty/example/telnet/TelnetClient.java +++ b/src/main/java/org/jboss/netty/example/telnet/TelnetClient.java @@ -15,97 +15,83 @@ */ package org.jboss.netty.example.telnet; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.InsecureTrustManagerFactory; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; /** * Simplistic telnet client. */ -public class TelnetClient { +public final class TelnetClient { - private final String host; - private final int port; + static final boolean SSL = System.getProperty("ssl") != null; + static final String HOST = System.getProperty("host", "127.0.0.1"); + static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8992" : "8023")); - public TelnetClient(String host, int port) { - this.host = host; - this.port = port; - } + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); + } else { + sslCtx = null; + } - public void run() throws IOException { // Configure the client. ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); - // Configure the pipeline factory. - bootstrap.setPipelineFactory(new TelnetClientPipelineFactory()); + try { + // Configure the pipeline factory. + bootstrap.setPipelineFactory(new TelnetClientPipelineFactory(sslCtx)); - // Start the connection attempt. - ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); + // Start the connection attempt. + ChannelFuture future = bootstrap.connect(new InetSocketAddress(HOST, PORT)); - // Wait until the connection attempt succeeds or fails. - Channel channel = future.awaitUninterruptibly().getChannel(); - if (!future.isSuccess()) { - future.getCause().printStackTrace(); + // Wait until the connection attempt succeeds or fails. + Channel channel = future.sync().getChannel(); + + // Read commands from the stdin. + ChannelFuture lastWriteFuture = null; + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + for (;;) { + String line = in.readLine(); + if (line == null) { + break; + } + + // Sends the received line to the server. + lastWriteFuture = channel.write(line + "\r\n"); + + // If user typed the 'bye' command, wait until the server closes + // the connection. + if ("bye".equals(line.toLowerCase())) { + channel.getCloseFuture().sync(); + break; + } + } + + // Wait until all messages are flushed before closing the channel. + if (lastWriteFuture != null) { + lastWriteFuture.sync(); + } + + // Close the connection. Make sure the close operation ends because + // all I/O operations are asynchronous in Netty. + channel.close().sync(); + } finally { + // Shut down all thread pools to exit. bootstrap.releaseExternalResources(); - return; } - - // Read commands from the stdin. - ChannelFuture lastWriteFuture = null; - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - for (;;) { - String line = in.readLine(); - if (line == null) { - break; - } - - // Sends the received line to the server. - lastWriteFuture = channel.write(line + "\r\n"); - - // If user typed the 'bye' command, wait until the server closes - // the connection. - if ("bye".equals(line.toLowerCase())) { - channel.getCloseFuture().awaitUninterruptibly(); - break; - } - } - - // Wait until all messages are flushed before closing the channel. - if (lastWriteFuture != null) { - lastWriteFuture.awaitUninterruptibly(); - } - - // Close the connection. Make sure the close operation ends because - // all I/O operations are asynchronous in Netty. - channel.close().awaitUninterruptibly(); - - // Shut down all thread pools to exit. - bootstrap.releaseExternalResources(); - } - - public static void main(String[] args) throws Exception { - // Print usage if no argument is specified. - if (args.length != 2) { - System.err.println( - "Usage: " + TelnetClient.class.getSimpleName() + - " "); - return; - } - - // Parse options. - String host = args[0]; - int port = Integer.parseInt(args[1]); - - new TelnetClient(host, port).run(); } } diff --git a/src/main/java/org/jboss/netty/example/telnet/TelnetClientHandler.java b/src/main/java/org/jboss/netty/example/telnet/TelnetClientHandler.java index 37f578c70b..8505481580 100644 --- a/src/main/java/org/jboss/netty/example/telnet/TelnetClientHandler.java +++ b/src/main/java/org/jboss/netty/example/telnet/TelnetClientHandler.java @@ -15,9 +15,6 @@ */ package org.jboss.netty.example.telnet; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelStateEvent; @@ -30,32 +27,23 @@ import org.jboss.netty.channel.SimpleChannelUpstreamHandler; */ public class TelnetClientHandler extends SimpleChannelUpstreamHandler { - private static final Logger logger = Logger.getLogger( - TelnetClientHandler.class.getName()); - @Override - public void handleUpstream( - ChannelHandlerContext ctx, ChannelEvent e) throws Exception { + public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { - logger.info(e.toString()); + System.err.println(e); } super.handleUpstream(ctx, e); } @Override - public void messageReceived( - ChannelHandlerContext ctx, MessageEvent e) { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { // Print out the line received from the server. System.err.println(e.getMessage()); } @Override - public void exceptionCaught( - ChannelHandlerContext ctx, ExceptionEvent e) { - logger.log( - Level.WARNING, - "Unexpected exception from downstream.", - e.getCause()); + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { + e.getCause().printStackTrace(); e.getChannel().close(); } } diff --git a/src/main/java/org/jboss/netty/example/telnet/TelnetClientPipelineFactory.java b/src/main/java/org/jboss/netty/example/telnet/TelnetClientPipelineFactory.java index 29ac24959f..dccd11e606 100644 --- a/src/main/java/org/jboss/netty/example/telnet/TelnetClientPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/telnet/TelnetClientPipelineFactory.java @@ -15,25 +15,35 @@ */ package org.jboss.netty.example.telnet; -import static org.jboss.netty.channel.Channels.*; - import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.Delimiters; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; +import org.jboss.netty.handler.ssl.SslContext; + +import static org.jboss.netty.channel.Channels.*; /** * Creates a newly configured {@link ChannelPipeline} for a new channel. */ -public class TelnetClientPipelineFactory implements - ChannelPipelineFactory { +public class TelnetClientPipelineFactory implements ChannelPipelineFactory { - public ChannelPipeline getPipeline() throws Exception { + private final SslContext sslCtx; + + public TelnetClientPipelineFactory(SslContext sslCtx) { + this.sslCtx = sslCtx; + } + + public ChannelPipeline getPipeline() { // Create a default pipeline implementation. ChannelPipeline pipeline = pipeline(); + if (sslCtx != null) { + pipeline.addLast("ssl", sslCtx.newHandler()); + } + // Add the text line codec combination first, pipeline.addLast("framer", new DelimiterBasedFrameDecoder( 8192, Delimiters.lineDelimiter())); diff --git a/src/main/java/org/jboss/netty/example/telnet/TelnetServer.java b/src/main/java/org/jboss/netty/example/telnet/TelnetServer.java index 83cc0b970d..39f2f7a57f 100644 --- a/src/main/java/org/jboss/netty/example/telnet/TelnetServer.java +++ b/src/main/java/org/jboss/netty/example/telnet/TelnetServer.java @@ -15,24 +15,32 @@ */ package org.jboss.netty.example.telnet; -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; +import org.jboss.netty.handler.ssl.SslContext; +import org.jboss.netty.handler.ssl.util.SelfSignedCertificate; + +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; /** * Simplistic telnet server. */ -public class TelnetServer { +public final class TelnetServer { - private final int port; + static final boolean SSL = System.getProperty("ssl") != null; + static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8992" : "8023")); - public TelnetServer(int port) { - this.port = port; - } + public static void main(String[] args) throws Exception { + // Configure SSL. + final SslContext sslCtx; + if (SSL) { + SelfSignedCertificate ssc = new SelfSignedCertificate(); + sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); + } else { + sslCtx = null; + } - public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -40,19 +48,9 @@ public class TelnetServer { Executors.newCachedThreadPool())); // Configure the pipeline factory. - bootstrap.setPipelineFactory(new TelnetServerPipelineFactory()); + bootstrap.setPipelineFactory(new TelnetServerPipelineFactory(sslCtx)); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(port)); - } - - public static void main(String[] args) throws Exception { - int port; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } else { - port = 8080; - } - new TelnetServer(port).run(); + bootstrap.bind(new InetSocketAddress(PORT)); } } diff --git a/src/main/java/org/jboss/netty/example/telnet/TelnetServerHandler.java b/src/main/java/org/jboss/netty/example/telnet/TelnetServerHandler.java index 0186c3663a..12d69f8d21 100644 --- a/src/main/java/org/jboss/netty/example/telnet/TelnetServerHandler.java +++ b/src/main/java/org/jboss/netty/example/telnet/TelnetServerHandler.java @@ -15,11 +15,6 @@ */ package org.jboss.netty.example.telnet; -import java.net.InetAddress; -import java.util.Date; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; @@ -29,35 +24,31 @@ import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; +import java.net.InetAddress; +import java.util.Date; + /** * Handles a server-side channel. */ public class TelnetServerHandler extends SimpleChannelUpstreamHandler { - private static final Logger logger = Logger.getLogger( - TelnetServerHandler.class.getName()); - @Override - public void handleUpstream( - ChannelHandlerContext ctx, ChannelEvent e) throws Exception { + public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { - logger.info(e.toString()); + System.err.println(e); } super.handleUpstream(ctx, e); } @Override - public void channelConnected( - ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { + public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // Send greeting for a new connection. - e.getChannel().write( - "Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n"); + e.getChannel().write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n"); e.getChannel().write("It is " + new Date() + " now.\r\n"); } @Override - public void messageReceived( - ChannelHandlerContext ctx, MessageEvent e) { + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { // Cast to a String first. // We know it is a String because we put some codec in TelnetPipelineFactory. @@ -87,12 +78,8 @@ public class TelnetServerHandler extends SimpleChannelUpstreamHandler { } @Override - public void exceptionCaught( - ChannelHandlerContext ctx, ExceptionEvent e) { - logger.log( - Level.WARNING, - "Unexpected exception from downstream.", - e.getCause()); + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { + e.getCause().printStackTrace(); e.getChannel().close(); } } diff --git a/src/main/java/org/jboss/netty/example/telnet/TelnetServerPipelineFactory.java b/src/main/java/org/jboss/netty/example/telnet/TelnetServerPipelineFactory.java index bf8f682244..c5da7f45f3 100644 --- a/src/main/java/org/jboss/netty/example/telnet/TelnetServerPipelineFactory.java +++ b/src/main/java/org/jboss/netty/example/telnet/TelnetServerPipelineFactory.java @@ -15,25 +15,35 @@ */ package org.jboss.netty.example.telnet; -import static org.jboss.netty.channel.Channels.*; - import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.Delimiters; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; +import org.jboss.netty.handler.ssl.SslContext; + +import static org.jboss.netty.channel.Channels.*; /** * Creates a newly configured {@link ChannelPipeline} for a new channel. */ -public class TelnetServerPipelineFactory implements - ChannelPipelineFactory { +public class TelnetServerPipelineFactory implements ChannelPipelineFactory { - public ChannelPipeline getPipeline() throws Exception { + private final SslContext sslCtx; + + public TelnetServerPipelineFactory(SslContext sslCtx) { + this.sslCtx = sslCtx; + } + + public ChannelPipeline getPipeline() { // Create a default pipeline implementation. ChannelPipeline pipeline = pipeline(); + if (sslCtx != null) { + pipeline.addLast("ssl", sslCtx.newHandler()); + } + // Add the text line codec combination first, pipeline.addLast("framer", new DelimiterBasedFrameDecoder( 8192, Delimiters.lineDelimiter())); diff --git a/src/main/java/org/jboss/netty/example/uptime/UptimeClient.java b/src/main/java/org/jboss/netty/example/uptime/UptimeClient.java index a61c9d7664..6dc7742634 100644 --- a/src/main/java/org/jboss/netty/example/uptime/UptimeClient.java +++ b/src/main/java/org/jboss/netty/example/uptime/UptimeClient.java @@ -15,9 +15,6 @@ */ package org.jboss.netty.example.uptime; -import java.net.InetSocketAddress; -import java.util.concurrent.Executors; - import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelPipeline; @@ -28,29 +25,25 @@ import org.jboss.netty.handler.timeout.ReadTimeoutHandler; import org.jboss.netty.util.HashedWheelTimer; import org.jboss.netty.util.Timer; +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; + /** * Connects to a server periodically to measure and print the uptime of the * server. This example demonstrates how to implement reliable reconnection * mechanism in Netty. */ -public class UptimeClient { +public final class UptimeClient { + static final String HOST = System.getProperty("host", "127.0.0.1"); + static final int PORT = Integer.parseInt(System.getProperty("port", "8080")); // Sleep 5 seconds before a reconnection attempt. - static final int RECONNECT_DELAY = 5; - + static final int RECONNECT_DELAY = Integer.parseInt(System.getProperty("reconnectDelay", "5")); // Reconnect when the server sends nothing for 10 seconds. - private static final int READ_TIMEOUT = 10; + static final int READ_TIMEOUT = Integer.parseInt(System.getProperty("readTimeout", "10")); - private final String host; - private final int port; - - public UptimeClient(String host, int port) { - this.host = host; - this.port = port; - } - - public void run() { + public static void main(String[] args) throws Exception { // Initialize the timer that schedules subsequent reconnection attempts. final Timer timer = new HashedWheelTimer(); @@ -63,38 +56,18 @@ public class UptimeClient { // Configure the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - private final ChannelHandler timeoutHandler = - new ReadTimeoutHandler(timer, READ_TIMEOUT); - private final ChannelHandler uptimeHandler = - new UptimeClientHandler(bootstrap, timer); + private final ChannelHandler timeoutHandler = new ReadTimeoutHandler(timer, READ_TIMEOUT); + private final ChannelHandler uptimeHandler = new UptimeClientHandler(bootstrap, timer); - public ChannelPipeline getPipeline() throws Exception { - return Channels.pipeline( - timeoutHandler, uptimeHandler); + public ChannelPipeline getPipeline() { + return Channels.pipeline(timeoutHandler, uptimeHandler); } }); - bootstrap.setOption( - "remoteAddress", new InetSocketAddress(host, port)); + bootstrap.setOption("remoteAddress", new InetSocketAddress(HOST, PORT)); // Initiate the first connection attempt - the rest is handled by // UptimeClientHandler. bootstrap.connect(); } - - public static void main(String[] args) throws Exception { - // Print usage if no argument is specified. - if (args.length != 2) { - System.err.println( - "Usage: " + UptimeClient.class.getSimpleName() + - " "); - return; - } - - // Parse options. - String host = args[0]; - int port = Integer.parseInt(args[1]); - - new UptimeClient(host, port).run(); - } } diff --git a/src/main/java/org/jboss/netty/example/uptime/UptimeClientHandler.java b/src/main/java/org/jboss/netty/example/uptime/UptimeClientHandler.java index da070eb27f..d0c6bd916d 100644 --- a/src/main/java/org/jboss/netty/example/uptime/UptimeClientHandler.java +++ b/src/main/java/org/jboss/netty/example/uptime/UptimeClientHandler.java @@ -15,10 +15,6 @@ */ package org.jboss.netty.example.uptime; -import java.net.ConnectException; -import java.net.InetSocketAddress; -import java.util.concurrent.TimeUnit; - import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelStateEvent; @@ -29,6 +25,10 @@ import org.jboss.netty.util.Timeout; import org.jboss.netty.util.Timer; import org.jboss.netty.util.TimerTask; +import java.net.ConnectException; +import java.net.InetSocketAddress; +import java.util.concurrent.TimeUnit; + /** * Keep reconnecting to the server while printing out the current uptime and * connection attempt status. @@ -57,7 +57,7 @@ public class UptimeClientHandler extends SimpleChannelUpstreamHandler { public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) { println("Sleeping for: " + UptimeClient.RECONNECT_DELAY + 's'); timer.newTimeout(new TimerTask() { - public void run(Timeout timeout) throws Exception { + public void run(Timeout timeout) { println("Reconnecting to: " + getRemoteAddress()); bootstrap.connect(); } @@ -89,7 +89,7 @@ public class UptimeClientHandler extends SimpleChannelUpstreamHandler { ctx.getChannel().close(); } - void println(String msg) { + private void println(String msg) { if (startTime < 0) { System.err.format("[SERVER IS DOWN] %s%n", msg); } else { diff --git a/src/test/resources/websocketx/html5/css/socket.css b/src/test/resources/websocketx/html5/css/socket.css deleted file mode 100644 index c50fdef00e..0000000000 --- a/src/test/resources/websocketx/html5/css/socket.css +++ /dev/null @@ -1,4 +0,0 @@ -textarea { - width: 500px; - height: 300px; -} \ No newline at end of file diff --git a/src/test/resources/websocketx/html5/js/socket.js b/src/test/resources/websocketx/html5/js/socket.js deleted file mode 100644 index b6e57420c8..0000000000 --- a/src/test/resources/websocketx/html5/js/socket.js +++ /dev/null @@ -1,53 +0,0 @@ -(function() { - var Sock = function() { - var socket; - if (!window.WebSocket) { - window.WebSocket = window.MozWebSocket; - } - - if (window.WebSocket) { - socket = new WebSocket("ws://localhost:8080/websocket"); - socket.onopen = onopen; - socket.onmessage = onmessage; - socket.onclose = onclose; - } else { - alert("Your browser does not support Web Socket."); - } - - function onopen(event) { - getTextAreaElement().value = "Web Socket opened!"; - } - - function onmessage(event) { - appendTextArea(event.data); - } - - function onclose(event) { - appendTextArea("Web Socket closed"); - } - - function appendTextArea(newData) { - var el = getTextAreaElement(); - el.value = el.value + '\n' + newData; - } - - function getTextAreaElement() { - return document.getElementById('responseText'); - } - - function send(event) { - event.preventDefault(); - if (window.WebSocket) { - if (socket.readyState == WebSocket.OPEN) { - socket.send(event.target.message.value); - } else { - alert("The socket is not open."); - } - } - } - document.forms.inputform.addEventListener('submit', send, false); - } - window.addEventListener('load', function() { - new Sock(); - }, false); -})(); diff --git a/src/test/resources/websocketx/html5/websocket.html b/src/test/resources/websocketx/html5/websocket.html deleted file mode 100644 index f80d25a22c..0000000000 --- a/src/test/resources/websocketx/html5/websocket.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - Web Socket Example - - - - -

Enter a message

-
- - -
-

Repsonse from Server

- - -