2 * Copyright (C) 2013 EBay Software Foundation
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
8 package org.opendaylight.ovsdb.lib.jsonrpc;
10 import io.netty.handler.logging.LogLevel;
11 import io.netty.handler.logging.LoggingHandler;
12 import java.io.IOException;
13 import java.io.OutputStream;
14 import java.net.Socket;
15 import java.nio.charset.StandardCharsets;
16 import junit.framework.TestCase;
17 import org.junit.Test;
19 public class TestClient extends TestCase {
21 String serverurl = "127.0.0.1";
22 NettyBootStrapper bootstrapper = new NettyBootStrapper();
23 JsonRpcDecoder jsonRpcDecoder = new JsonRpcDecoder(100000);
25 public void setupServer() throws Exception {
26 bootstrapper.startServer(0, jsonRpcDecoder, new LoggingHandler(LogLevel.DEBUG));
29 public void shutDownServer() throws InterruptedException {
30 bootstrapper.stopServer();
34 * Testing appropriate ChannelHandler integration for JsonRpcDecoder, so that JSON strings written using an
35 * OutputStream connected to a ServerSocket of a Netty ServerBootstrap can be decoded properly.
38 public void testBasicFlow() throws Exception {
40 Socket socket = new Socket(serverurl, bootstrapper.getServerPort());
41 OutputStream outputStream = socket.getOutputStream();
45 for (int i = 0; i < records; i++) {
46 writeJson(outputStream, 1);
47 writePartialFirst(outputStream);
50 writePartialLast(outputStream);
55 assertEquals("mismatch in records processed", records * 2, jsonRpcDecoder.getRecordsRead());
58 static int counter = 0;
61 * Create and write a json string for specified number of times.
63 private static void writeJson(final OutputStream outputStream, final int times) throws IOException {
64 outputStream.write("{".getBytes(StandardCharsets.UTF_8));
65 for (int i = 0; i < times; i++) {
67 String string = ",\"key1" + counter + "\":\"planet of apes" + counter + "\", \"key2" + counter
68 + "\":{\"k1\":\"ovs-db rocks the world\"}";
69 outputStream.write(string.substring(i == 0 ? 1 : 0).getBytes(StandardCharsets.UTF_8));
71 outputStream.write("}".getBytes(StandardCharsets.UTF_8));
75 * Writes a partial JSON and flush to simulate the case where netty gets half the message and has to frame it
78 private static void writePartialFirst(final OutputStream outputStream) throws IOException {
80 String string = " {\"part" + counter + "\":";
81 outputStream.write(string.getBytes(StandardCharsets.UTF_8));
85 * Finishes the JSON started by writePartialFirst.
87 private static void writePartialLast(final OutputStream outputStream) throws IOException {
88 String string = "\"val" + counter + "\"}";
89 outputStream.write(string.getBytes(StandardCharsets.UTF_8));