a67a4919163272656e835a75ef90807f0b632c78
[netconf.git] / restconf / restconf-nb-bierman02 / 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 static final Logger LOG = LoggerFactory.getLogger(WebSocketClient.class);
35
36     private final URI uri;
37     private final Bootstrap bootstrap = new Bootstrap();
38     private final WebSocketClientHandler clientHandler;
39     private Channel clientChannel;
40     private final EventLoopGroup group = new NioEventLoopGroup();
41
42     public WebSocketClient(final URI uri, final IClientMessageCallback clientMessageCallback) {
43         this.uri = uri;
44         clientHandler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri,
45                 WebSocketVersion.V13, null, false, null), clientMessageCallback);
46         // last null could be replaced with DefaultHttpHeaders
47         initialize();
48     }
49
50     private void initialize() {
51
52         String protocol = uri.getScheme();
53         if (!"ws".equals(protocol)) {
54             throw new IllegalArgumentException("Unsupported protocol: " + protocol);
55         }
56
57         bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
58             @Override
59             public void initChannel(final SocketChannel ch) throws Exception {
60                 ChannelPipeline pipeline = ch.pipeline();
61                 pipeline.addLast("http-codec", new HttpClientCodec());
62                 pipeline.addLast("aggregator", new HttpObjectAggregator(8192));
63                 pipeline.addLast("ws-handler", clientHandler);
64             }
65         });
66     }
67
68     public void connect() throws InterruptedException {
69         LOG.info("WebSocket Client connecting");
70         clientChannel = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel();
71         clientHandler.handshakeFuture().sync();
72     }
73
74     public void writeAndFlush(final String message) {
75         clientChannel.writeAndFlush(new TextWebSocketFrame(message));
76     }
77
78     public void writeAndFlush(final Object message) {
79         clientChannel.writeAndFlush(message);
80     }
81
82     public void ping() {
83         clientChannel.writeAndFlush(new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] { 1, 2, 3, 4, 5, 6 })));
84     }
85
86     public void close(final String reasonText) throws InterruptedException {
87         CloseWebSocketFrame closeWebSocketFrame = new CloseWebSocketFrame(1000, reasonText);
88         clientChannel.writeAndFlush(closeWebSocketFrame);
89
90         // WebSocketClientHandler will close the connection when the server
91         // responds to the CloseWebSocketFrame.
92         clientChannel.closeFuture().sync();
93         group.shutdownGracefully();
94     }
95
96     public static void main(final String[] args) throws Exception {
97         URI uri;
98         if (args.length > 0) {
99             uri = new URI(args[0]);
100         } else {
101             uri = new URI("http://192.168.1.101:8181/opendaylight-inventory:nodes");
102         }
103         IClientMessageCallback messageCallback = new ClientMessageCallback();
104         WebSocketClient webSocketClient = new WebSocketClient(uri, messageCallback);
105         webSocketClient.connect();
106
107         while (true) {
108             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
109             String input = br.readLine();
110             if (input.equals("q")) {
111                 LOG.info("Would you like to close stream? (Y = yes, empty = yes)\n");
112                 input = br.readLine();
113                 if (input.equals("yes") || input.isEmpty()) {
114                     webSocketClient.close("opendaylight-inventory:nodes");
115                     break;
116                 }
117             }
118         }
119     }
120
121     private static class ClientMessageCallback implements IClientMessageCallback {
122         @Override
123         public void onMessageReceived(final Object message) {
124             if (message instanceof TextWebSocketFrame) {
125                 LOG.info("received message {}" + ((TextWebSocketFrame) message).text());
126             }
127         }
128     }
129
130 }