1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.localtime;
17
18 import org.jboss.netty.channel.ChannelEvent;
19 import org.jboss.netty.channel.ChannelHandlerContext;
20 import org.jboss.netty.channel.ChannelStateEvent;
21 import org.jboss.netty.channel.ExceptionEvent;
22 import org.jboss.netty.channel.MessageEvent;
23 import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
24 import org.jboss.netty.example.localtime.LocalTimeProtocol.Continent;
25 import org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek;
26 import org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime;
27 import org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes;
28 import org.jboss.netty.example.localtime.LocalTimeProtocol.Location;
29 import org.jboss.netty.example.localtime.LocalTimeProtocol.Locations;
30
31 import java.util.Calendar;
32 import java.util.TimeZone;
33 import java.util.logging.Level;
34 import java.util.logging.Logger;
35
36 import static java.util.Calendar.*;
37
38 public class LocalTimeServerHandler extends SimpleChannelUpstreamHandler {
39
40 private static final Logger logger = Logger.getLogger(
41 LocalTimeServerHandler.class.getName());
42
43 @Override
44 public void handleUpstream(
45 ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
46 if (e instanceof ChannelStateEvent) {
47 logger.info(e.toString());
48 }
49 super.handleUpstream(ctx, e);
50 }
51
52 @Override
53 public void messageReceived(
54 ChannelHandlerContext ctx, MessageEvent e) {
55
56 Locations locations = (Locations) e.getMessage();
57 long currentTime = System.currentTimeMillis();
58
59 LocalTimes.Builder builder = LocalTimes.newBuilder();
60 for (Location l: locations.getLocationList()) {
61 TimeZone tz = TimeZone.getTimeZone(
62 toString(l.getContinent()) + '/' + l.getCity());
63 Calendar calendar = getInstance(tz);
64 calendar.setTimeInMillis(currentTime);
65
66 builder.addLocalTime(LocalTime.newBuilder().
67 setYear(calendar.get(YEAR)).
68 setMonth(calendar.get(MONTH) + 1).
69 setDayOfMonth(calendar.get(DAY_OF_MONTH)).
70 setDayOfWeek(DayOfWeek.valueOf(calendar.get(DAY_OF_WEEK))).
71 setHour(calendar.get(HOUR_OF_DAY)).
72 setMinute(calendar.get(MINUTE)).
73 setSecond(calendar.get(SECOND)).build());
74 }
75
76 e.getChannel().write(builder.build());
77 }
78
79 @Override
80 public void exceptionCaught(
81 ChannelHandlerContext ctx, ExceptionEvent e) {
82 logger.log(
83 Level.WARNING,
84 "Unexpected exception from downstream.",
85 e.getCause());
86 e.getChannel().close();
87 }
88
89 private static String toString(Continent c) {
90 return c.name().charAt(0) + c.name().toLowerCase().substring(1);
91 }
92 }