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.localtime;
17  
18  import org.jboss.netty.bootstrap.ClientBootstrap;
19  import org.jboss.netty.channel.Channel;
20  import org.jboss.netty.channel.ChannelFuture;
21  import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
22  
23  import java.net.InetSocketAddress;
24  import java.util.ArrayList;
25  import java.util.Collection;
26  import java.util.Iterator;
27  import java.util.List;
28  import java.util.concurrent.Executors;
29  import java.util.regex.Pattern;
30  
31  /**
32   * Sends a list of continent/city pairs to a {@link LocalTimeServer} to
33   * get the local times of the specified cities.
34   */
35  public class LocalTimeClient {
36  
37      private final String host;
38      private final int port;
39      private final Collection<String> cities;
40  
41      public LocalTimeClient(String host, int port, Collection<String> cities) {
42          this.host = host;
43          this.port = port;
44          this.cities = new ArrayList<String>();
45          this.cities.addAll(cities);
46      }
47  
48      public void run() {
49          // Set up.
50          ClientBootstrap bootstrap = new ClientBootstrap(
51                  new NioClientSocketChannelFactory(
52                          Executors.newCachedThreadPool(),
53                          Executors.newCachedThreadPool()));
54  
55          // Configure the event pipeline factory.
56          bootstrap.setPipelineFactory(new LocalTimeClientPipelineFactory());
57  
58          // Make a new connection.
59          ChannelFuture connectFuture =
60              bootstrap.connect(new InetSocketAddress(host, port));
61  
62          // Wait until the connection is made successfully.
63          Channel channel = connectFuture.awaitUninterruptibly().getChannel();
64  
65          // Get the handler instance to initiate the request.
66          LocalTimeClientHandler handler =
67              channel.getPipeline().get(LocalTimeClientHandler.class);
68  
69          // Request and get the response.
70          List<String> response = handler.getLocalTimes(cities);
71          // Close the connection.
72          channel.close().awaitUninterruptibly();
73  
74          // Shut down all thread pools to exit.
75          bootstrap.releaseExternalResources();
76  
77          // Print the response at last but not least.
78          Iterator<String> i1 = cities.iterator();
79          Iterator<String> i2 = response.iterator();
80          while (i1.hasNext()) {
81              System.out.format("%28s: %s%n", i1.next(), i2.next());
82          }
83      }
84  
85      public static void main(String[] args) throws Exception {
86          // Print usage if necessary.
87          if (args.length < 3) {
88              printUsage();
89              return;
90          }
91  
92          // Parse options.
93          String host = args[0];
94          int port = Integer.parseInt(args[1]);
95          Collection<String> cities = parseCities(args, 2);
96          if (cities == null) {
97              return;
98          }
99  
100         new LocalTimeClient(host, port, cities).run();
101     }
102 
103     private static void printUsage() {
104         System.err.println(
105                 "Usage: " + LocalTimeClient.class.getSimpleName() +
106                 " <host> <port> <continent/city_name> ...");
107         System.err.println(
108                 "Example: " + LocalTimeClient.class.getSimpleName() +
109                 " localhost 8080 America/New_York Asia/Seoul");
110     }
111 
112     private static final Pattern CITY_PATTERN = Pattern.compile("^[_A-Za-z]+/[_A-Za-z]+$");
113 
114     private static List<String> parseCities(String[] args, int offset) {
115         List<String> cities = new ArrayList<String>();
116         for (int i = offset; i < args.length; i ++) {
117             if (!CITY_PATTERN.matcher(args[i]).matches()) {
118                 System.err.println("Syntax error: '" + args[i] + '\'');
119                 printUsage();
120                 return null;
121             }
122             cities.add(args[i].trim());
123         }
124         return cities;
125     }
126 }