1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.factorial;
17
18 import java.math.BigInteger;
19 import java.util.Formatter;
20 import java.util.logging.Level;
21 import java.util.logging.Logger;
22
23 import org.jboss.netty.channel.ChannelEvent;
24 import org.jboss.netty.channel.ChannelHandlerContext;
25 import org.jboss.netty.channel.ChannelStateEvent;
26 import org.jboss.netty.channel.ExceptionEvent;
27 import org.jboss.netty.channel.MessageEvent;
28 import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
29
30
31
32
33
34
35
36
37 public class FactorialServerHandler extends SimpleChannelUpstreamHandler {
38
39 private static final Logger logger = Logger.getLogger(
40 FactorialServerHandler.class.getName());
41
42
43 private int lastMultiplier = 1;
44 private BigInteger factorial = new BigInteger(new byte[] { 1 });
45
46 @Override
47 public void handleUpstream(
48 ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
49 if (e instanceof ChannelStateEvent) {
50 logger.info(e.toString());
51 }
52 super.handleUpstream(ctx, e);
53 }
54
55 @Override
56 public void messageReceived(
57 ChannelHandlerContext ctx, MessageEvent e) {
58
59
60 BigInteger number;
61 if (e.getMessage() instanceof BigInteger) {
62 number = (BigInteger) e.getMessage();
63 } else {
64 number = new BigInteger(e.getMessage().toString());
65 }
66 lastMultiplier = number.intValue();
67 factorial = factorial.multiply(number);
68 e.getChannel().write(factorial);
69 }
70
71 @Override
72 public void channelDisconnected(ChannelHandlerContext ctx,
73 ChannelStateEvent e) throws Exception {
74 logger.info(new Formatter().format(
75 "Factorial of %,d is: %,d", lastMultiplier, factorial).toString());
76 }
77
78 @Override
79 public void exceptionCaught(
80 ChannelHandlerContext ctx, ExceptionEvent e) {
81 logger.log(
82 Level.WARNING,
83 "Unexpected exception from downstream.",
84 e.getCause());
85 e.getChannel().close();
86 }
87 }