Apply style rules on whole sal-rest-connector
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / test / java / org / opendaylight / controller / sal / restconf / impl / websockets / client / WebSocketClient.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.sal.restconf.impl.websockets.client;
9
10 import io.netty.bootstrap.Bootstrap;
11 import io.netty.buffer.Unpooled;
12 import io.netty.channel.Channel;
13 import io.netty.channel.ChannelInitializer;
14 import io.netty.channel.ChannelPipeline;
15 import io.netty.channel.EventLoopGroup;
16 import io.netty.channel.nio.NioEventLoopGroup;
17 import io.netty.channel.socket.SocketChannel;
18 import io.netty.channel.socket.nio.NioSocketChannel;
19 import io.netty.handler.codec.http.HttpClientCodec;
20 import io.netty.handler.codec.http.HttpObjectAggregator;
21 import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
22 import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
23 import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
24 import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
25 import io.netty.handler.codec.http.websocketx.WebSocketVersion;
26 import java.io.BufferedReader;
27 import java.io.InputStreamReader;
28 import java.net.URI;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 public class WebSocketClient {
33
34     private final URI uri;
35     private Bootstrap bootstrap = new Bootstrap();;
36     private final WebSocketClientHandler clientHandler;
37     private static final Logger logger = LoggerFactory.getLogger(WebSocketClient.class);
38     private Channel clientChannel;
39     private final EventLoopGroup group = new NioEventLoopGroup();
40
41     public WebSocketClient(URI uri, IClientMessageCallback clientMessageCallback) {
42         this.uri = uri;
43         clientHandler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri,
44                 WebSocketVersion.V13, null, false, null), clientMessageCallback); // last
45                                                                                   // null
46                                                                                   // could
47                                                                                   // be
48                                                                                   // replaced
49                                                                                   // with
50                                                                                   // DefaultHttpHeaders
51         initialize();
52     }
53
54     private void initialize() {
55
56         String protocol = uri.getScheme();
57         if (!"http".equals(protocol)) {
58             throw new IllegalArgumentException("Unsupported protocol: " + protocol);
59         }
60
61         bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
62             @Override
63             public void initChannel(SocketChannel ch) throws Exception {
64                 ChannelPipeline pipeline = ch.pipeline();
65                 pipeline.addLast("http-codec", new HttpClientCodec());
66                 pipeline.addLast("aggregator", new HttpObjectAggregator(8192));
67                 pipeline.addLast("ws-handler", clientHandler);
68             }
69         });
70     }
71
72     public void connect() throws InterruptedException {
73         System.out.println("WebSocket Client connecting");
74         clientChannel = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel();
75         clientHandler.handshakeFuture().sync();
76     }
77
78     public void writeAndFlush(String message) {
79         clientChannel.writeAndFlush(new TextWebSocketFrame(message));
80     }
81
82     public void writeAndFlush(Object message) {
83         clientChannel.writeAndFlush(message);
84     }
85
86     public void ping() {
87         clientChannel.writeAndFlush(new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] { 1, 2, 3, 4, 5, 6 })));
88     }
89
90     public void close(String reasonText) throws InterruptedException {
91         CloseWebSocketFrame closeWebSocketFrame = new CloseWebSocketFrame(1000, reasonText);
92         clientChannel.writeAndFlush(closeWebSocketFrame);
93
94         // WebSocketClientHandler will close the connection when the server
95         // responds to the CloseWebSocketFrame.
96         clientChannel.closeFuture().sync();
97         group.shutdownGracefully();
98     }
99
100     public static void main(String[] args) throws Exception {
101         URI uri;
102         if (args.length > 0) {
103             uri = new URI(args[0]);
104         } else {
105             uri = new URI("http://192.168.1.101:8181/opendaylight-inventory:nodes");
106         }
107         IClientMessageCallback messageCallback = new ClientMessageCallback();
108         WebSocketClient webSocketClient = new WebSocketClient(uri, messageCallback);
109         webSocketClient.connect();
110
111         while (true) {
112             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
113             String input = br.readLine();
114             if (input.equals("q")) {
115                 System.out.print("Would you like to close stream? (Y = yes, empty = yes)\n");
116                 input = br.readLine();
117                 if (input.equals("yes") || input.isEmpty()) {
118                     webSocketClient.close("opendaylight-inventory:nodes");
119                     break;
120                 }
121             }
122         }
123     }
124
125     private static class ClientMessageCallback implements IClientMessageCallback {
126         @Override
127         public void onMessageReceived(Object message) {
128             if (message instanceof TextWebSocketFrame) {
129                 logger.info("received message {}" + ((TextWebSocketFrame) message).text());
130             }
131         }
132     }
133
134 }