1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.worldclock;
17
18 import io.netty.channel.ChannelHandlerContext;
19 import io.netty.channel.SimpleChannelInboundHandler;
20 import io.netty.example.worldclock.WorldClockProtocol.Continent;
21 import io.netty.example.worldclock.WorldClockProtocol.DayOfWeek;
22 import io.netty.example.worldclock.WorldClockProtocol.LocalTime;
23 import io.netty.example.worldclock.WorldClockProtocol.LocalTimes;
24 import io.netty.example.worldclock.WorldClockProtocol.Location;
25 import io.netty.example.worldclock.WorldClockProtocol.Locations;
26
27 import java.util.Calendar;
28 import java.util.TimeZone;
29
30 import static java.util.Calendar.*;
31
32 public class WorldClockServerHandler extends SimpleChannelInboundHandler<Locations> {
33
34 @Override
35 public void channelRead0(ChannelHandlerContext ctx, Locations locations) throws Exception {
36 long currentTime = System.currentTimeMillis();
37
38 LocalTimes.Builder builder = LocalTimes.newBuilder();
39 for (Location l: locations.getLocationList()) {
40 TimeZone tz = TimeZone.getTimeZone(
41 toString(l.getContinent()) + '/' + l.getCity());
42 Calendar calendar = getInstance(tz);
43 calendar.setTimeInMillis(currentTime);
44
45 builder.addLocalTime(LocalTime.newBuilder().
46 setYear(calendar.get(YEAR)).
47 setMonth(calendar.get(MONTH) + 1).
48 setDayOfMonth(calendar.get(DAY_OF_MONTH)).
49 setDayOfWeek(DayOfWeek.valueOf(calendar.get(DAY_OF_WEEK))).
50 setHour(calendar.get(HOUR_OF_DAY)).
51 setMinute(calendar.get(MINUTE)).
52 setSecond(calendar.get(SECOND)).build());
53 }
54
55 ctx.write(builder.build());
56 }
57
58 @Override
59 public void channelReadComplete(ChannelHandlerContext ctx) {
60 ctx.flush();
61 }
62
63 @Override
64 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
65 cause.printStackTrace();
66 ctx.close();
67 }
68
69 private static String toString(Continent c) {
70 return c.name().charAt(0) + c.name().toLowerCase().substring(1);
71 }
72 }