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