2 * ============LICENSE_START=======================================================
3 * ONAP : ccsdk features
4 * ================================================================================
5 * Copyright (C) 2018 highstreet technologies GmbH Intellectual Property.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.ccsdk.features.sdnr.wt.common.test.helper;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
27 import static org.mockito.Mockito.mock;
28 import static org.mockito.Mockito.verify;
29 import static org.mockito.Mockito.when;
31 import java.io.ByteArrayInputStream;
32 import java.io.IOException;
33 import java.io.OutputStream;
34 import java.io.StringWriter;
35 import java.net.InetSocketAddress;
36 import java.util.Enumeration;
38 import java.util.Vector;
39 import java.util.concurrent.ExecutorService;
40 import java.util.concurrent.Executors;
42 import javax.servlet.ServletInputStream;
43 import javax.servlet.ServletOutputStream;
44 import javax.servlet.http.HttpServletRequest;
45 import javax.servlet.http.HttpServletResponse;
47 import org.junit.After;
48 import org.junit.Before;
50 import com.sun.net.httpserver.HttpExchange;
51 import com.sun.net.httpserver.HttpHandler;
52 import com.sun.net.httpserver.HttpServer;
54 @SuppressWarnings("restriction")
55 public class HelpServletBase {
57 public static final String RESPONSE_GET = "This is the response get";
58 public static final String RESPONSE_POST = "This is the response post";
59 public static final String RESPONSE_PUT = "This is the response put";
60 public static final String RESPONSE_DELETE = "This is the response delete";
61 public static final String RESPONSE_OPTIONS = "This is the response options";
63 public static final String HTTPMETHOD_GET = "GET";
64 public static final String HTTPMETHOD_POST = "POST";
65 public static final String HTTPMETHOD_PUT = "PUT";
66 public static final String HTTPMETHOD_DELETE = "DELETE";
67 public static final String HTTPMETHOD_OPTIONS = "OPTIONS";
68 private IPublicServlet servlet;
69 private static HttpServer server;
70 private static ExecutorService httpThreadPool;
72 public final String HOST = "localhost";
73 protected static int testPort;
74 private final String baseUri;
75 protected static final String LR = "\n";
77 public HelpServletBase(String baseuri, int port) {
78 this.baseUri = baseuri;
82 public void setServlet(IPublicServlet s) {
86 protected void testrequest(String method, String data, String expectedResponse, boolean exact) {
87 this.testrequest("/mwtn/test", method, data, expectedResponse, exact, null);
90 protected void testrequest(String uri, String method, String data, String expectedResponse, boolean exact) {
91 this.testrequest(uri, method, data, expectedResponse, exact, null);
94 protected void testrequest(String uri, String method, String data, String expectedResponse, boolean exact,
95 Map<String, String> headersToCheck) {
97 HttpServletRequest mockRequest = mock(HttpServletRequest.class);
98 HttpServletResponse mockResponse = mock(HttpServletResponse.class);
100 StringWriter out = new StringWriter();
101 ServletOutputStream printOut = new ServletOutputStream() {
104 public void write(int arg0) throws IOException {
108 ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes());
109 ServletInputStream inputStream = new ServletInputStream() {
111 public int read() throws IOException {
115 Vector<String> headers = new Vector<String>();
116 headers.addElement("Accept");
117 headers.add("User-Agent");
118 Enumeration<String> headerNames = headers.elements();
120 when(mockRequest.getRequestURI()).thenReturn(this.baseUri + uri);
121 when(mockRequest.getHeaderNames()).thenReturn(headerNames);
122 when(mockRequest.getHeader("Accept")).thenReturn("application/json");
123 when(mockRequest.getHeader("User-Agent")).thenReturn("Gecko abc");
124 when(mockRequest.getInputStream()).thenReturn(inputStream);
125 when(mockResponse.getOutputStream()).thenReturn(printOut);
126 System.out.println("do a " + method + " request");
127 if (method == HTTPMETHOD_GET)
128 this.servlet.doGet(mockRequest, mockResponse);
129 else if (method == HTTPMETHOD_POST)
130 this.servlet.doPost(mockRequest, mockResponse);
131 else if (method == HTTPMETHOD_PUT)
132 this.servlet.doPut(mockRequest, mockResponse);
133 else if (method == HTTPMETHOD_DELETE)
134 this.servlet.doDelete(mockRequest, mockResponse);
135 else if (method == HTTPMETHOD_OPTIONS)
136 this.servlet.doOptions(mockRequest, mockResponse);
138 fail("http request method " + method + " test not implemented");
139 } catch (Exception e) {
140 System.err.println(e.getMessage());
143 verify(mockResponse).setStatus(200);
145 assertEquals(expectedResponse, out.toString());
147 assertTrue("response not for method " + method + "correct", out.toString().contains(expectedResponse));
148 // currently unable to check extra headers
149 if (headersToCheck != null) {
155 private void init() throws IOException {
158 initEsTestWebserver(testPort);
162 private void deinit() {
166 public static void initEsTestWebserver(int port) throws IOException {
167 initEsTestWebserver(port, "/mwtn/test");
170 public static void initEsTestWebserver(int port, String baseUri) throws IOException {
171 server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
172 httpThreadPool = Executors.newFixedThreadPool(5);
173 server.setExecutor(httpThreadPool);
174 server.createContext(baseUri, new MyHandler());
175 //server.createContext("/", new MyRootHandler());
176 server.setExecutor(null); // creates a default executor
178 System.out.println("http server started");
181 public static void stopTestWebserver() {
182 if (server != null) {
184 httpThreadPool.shutdownNow();
185 System.out.println("http server stopped");
191 public static class MyHandler implements HttpHandler {
193 public void handle(HttpExchange t) throws IOException {
194 String method = t.getRequestMethod();
195 System.out.println(String.format("req received: %s %s", method, t.getRequestURI()));
196 OutputStream os = null;
198 if (method.equals(HTTPMETHOD_GET)) {
199 t.sendResponseHeaders(200, RESPONSE_GET.length());
200 os = t.getResponseBody();
201 os.write(RESPONSE_GET.getBytes());
202 } else if (method.equals(HTTPMETHOD_POST)) {
203 t.sendResponseHeaders(200, RESPONSE_POST.length());
204 os = t.getResponseBody();
205 os.write(RESPONSE_POST.getBytes());
206 } else if (method.equals(HTTPMETHOD_PUT)) {
207 t.sendResponseHeaders(200, RESPONSE_PUT.length());
208 os = t.getResponseBody();
209 os.write(RESPONSE_PUT.getBytes());
210 } else if (method.equals(HTTPMETHOD_DELETE)) {
211 t.sendResponseHeaders(200, RESPONSE_DELETE.length());
212 os = t.getResponseBody();
213 os.write(RESPONSE_DELETE.getBytes());
214 } else if (method.equals(HTTPMETHOD_OPTIONS)) {
215 t.sendResponseHeaders(200, RESPONSE_OPTIONS.length());
216 //os = t.getResponseBody();
217 //os.write(RESPONSE_OPTIONS.getBytes());
219 t.sendResponseHeaders(404, 0);
221 System.out.println("req handled successful");
223 } catch (Exception e) {
224 System.out.println(e.getMessage());