View Javadoc

1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package org.jboss.netty.example.qotm;
17  
18  import java.util.Random;
19  
20  import org.jboss.netty.channel.ChannelHandlerContext;
21  import org.jboss.netty.channel.ExceptionEvent;
22  import org.jboss.netty.channel.MessageEvent;
23  import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
24  
25  public class QuoteOfTheMomentServerHandler extends SimpleChannelUpstreamHandler {
26  
27      private static final Random random = new Random();
28  
29      // Quotes from Mohandas K. Gandhi:
30      private static final String[] quotes = {
31          "Where there is love there is life.",
32          "First they ignore you, then they laugh at you, then they fight you, then you win.",
33          "Be the change you want to see in the world.",
34          "The weak can never forgive. Forgiveness is the attribute of the strong.",
35      };
36  
37      private static String nextQuote() {
38          int quoteId;
39          synchronized (random) {
40              quoteId = random.nextInt(quotes.length);
41          }
42          return quotes[quoteId];
43      }
44  
45      @Override
46      public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
47              throws Exception {
48          String msg = (String) e.getMessage();
49          if (msg.equals("QOTM?")) {
50              e.getChannel().write("QOTM: " + nextQuote(), e.getRemoteAddress());
51          }
52      }
53  
54      @Override
55      public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
56              throws Exception {
57          e.getCause().printStackTrace();
58          // We don't close the channel because we can keep serving requests.
59      }
60  }