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;
30 import com.sun.net.httpserver.HttpExchange;
31 import com.sun.net.httpserver.HttpHandler;
32 import com.sun.net.httpserver.HttpServer;
33 import java.io.IOException;
34 import java.io.OutputStream;
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;
41 import javax.servlet.http.HttpServletRequest;
42 import javax.servlet.http.HttpServletResponse;
43 import org.junit.After;
44 import org.junit.Before;
45 import org.onap.ccsdk.features.sdnr.wt.common.test.ServletInputStreamFromByteArrayInputStream;
46 import org.onap.ccsdk.features.sdnr.wt.common.test.ServletOutputStreamToStringWriter;
48 @SuppressWarnings("restriction")
49 public class HelpServletBase {
51 public static final String RESPONSE_GET = "This is the response get";
52 public static final String RESPONSE_POST = "This is the response post";
53 public static final String RESPONSE_PUT = "This is the response put";
54 public static final String RESPONSE_DELETE = "This is the response delete";
55 public static final String RESPONSE_OPTIONS = "This is the response options";
57 public static final String HTTPMETHOD_GET = "GET";
58 public static final String HTTPMETHOD_POST = "POST";
59 public static final String HTTPMETHOD_PUT = "PUT";
60 public static final String HTTPMETHOD_DELETE = "DELETE";
61 public static final String HTTPMETHOD_OPTIONS = "OPTIONS";
62 private IPublicServlet servlet;
63 private static HttpServer server;
64 private static ExecutorService httpThreadPool;
66 public final String HOST = "localhost";
67 protected static int testPort;
68 private final String baseUri;
69 protected static final String LR = "\n";
71 public HelpServletBase(String baseuri, int port) {
72 this.baseUri = baseuri;
76 public void setServlet(IPublicServlet s) {
80 protected void testrequest(String method, String data, String expectedResponse, boolean exact) {
81 this.testrequest("/mwtn/test", method, data, expectedResponse, exact, null);
84 protected void testrequest(String uri, String method, String data, String expectedResponse, boolean exact) {
85 this.testrequest(uri, method, data, expectedResponse, exact, null);
88 protected void testrequest(String uri, String method, String data, String expectedResponse, boolean exact,
89 Map<String, String> headersToCheck) {
91 HttpServletRequest mockRequest = mock(HttpServletRequest.class);
92 HttpServletResponse mockResponse = mock(HttpServletResponse.class);
94 ServletOutputStreamToStringWriter printOut = new ServletOutputStreamToStringWriter();
95 ServletInputStreamFromByteArrayInputStream inputStream = new ServletInputStreamFromByteArrayInputStream(data.getBytes());
96 Vector<String> headers = new Vector<String>();
97 headers.addElement("Accept");
98 headers.add("User-Agent");
99 Enumeration<String> headerNames = headers.elements();
101 when(mockRequest.getRequestURI()).thenReturn(this.baseUri + uri);
102 when(mockRequest.getHeaderNames()).thenReturn(headerNames);
103 when(mockRequest.getHeader("Accept")).thenReturn("application/json");
104 when(mockRequest.getHeader("User-Agent")).thenReturn("Gecko abc");
105 when(mockRequest.getInputStream()).thenReturn(inputStream);
106 when(mockResponse.getOutputStream()).thenReturn(printOut);
107 System.out.println("do a " + method + " request");
108 if (method == HTTPMETHOD_GET)
109 this.servlet.doGet(mockRequest, mockResponse);
110 else if (method == HTTPMETHOD_POST)
111 this.servlet.doPost(mockRequest, mockResponse);
112 else if (method == HTTPMETHOD_PUT)
113 this.servlet.doPut(mockRequest, mockResponse);
114 else if (method == HTTPMETHOD_DELETE)
115 this.servlet.doDelete(mockRequest, mockResponse);
116 else if (method == HTTPMETHOD_OPTIONS)
117 this.servlet.doOptions(mockRequest, mockResponse);
119 fail("http request method " + method + " test not implemented");
120 } catch (Exception e) {
121 System.err.println(e.getMessage());
124 verify(mockResponse).setStatus(200);
126 assertEquals(expectedResponse, printOut.getStringWriter().toString());
128 assertTrue("response not for method " + method + "correct", printOut.getStringWriter().toString().contains(expectedResponse));
129 // currently unable to check extra headers
130 if (headersToCheck != null) {
136 private void init() throws IOException {
139 initEsTestWebserver(testPort);
143 private void deinit() {
147 public static void initEsTestWebserver(int port) throws IOException {
148 initEsTestWebserver(port, "/mwtn/test");
151 public static void initEsTestWebserver(int port, String baseUri) throws IOException {
152 server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
153 httpThreadPool = Executors.newFixedThreadPool(5);
154 server.setExecutor(httpThreadPool);
155 server.createContext(baseUri, new MyHandler());
156 //server.createContext("/", new MyRootHandler());
157 server.setExecutor(null); // creates a default executor
159 System.out.println("http server started");
162 public static void stopTestWebserver() {
163 if (server != null) {
165 httpThreadPool.shutdownNow();
166 System.out.println("http server stopped");
172 public static class MyHandler implements HttpHandler {
174 public void handle(HttpExchange t) throws IOException {
175 String method = t.getRequestMethod();
176 System.out.println(String.format("req received: %s %s", method, t.getRequestURI()));
177 OutputStream os = null;
179 if (method.equals(HTTPMETHOD_GET)) {
180 t.sendResponseHeaders(200, RESPONSE_GET.length());
181 os = t.getResponseBody();
182 os.write(RESPONSE_GET.getBytes());
183 } else if (method.equals(HTTPMETHOD_POST)) {
184 t.sendResponseHeaders(200, RESPONSE_POST.length());
185 os = t.getResponseBody();
186 os.write(RESPONSE_POST.getBytes());
187 } else if (method.equals(HTTPMETHOD_PUT)) {
188 t.sendResponseHeaders(200, RESPONSE_PUT.length());
189 os = t.getResponseBody();
190 os.write(RESPONSE_PUT.getBytes());
191 } else if (method.equals(HTTPMETHOD_DELETE)) {
192 t.sendResponseHeaders(200, RESPONSE_DELETE.length());
193 os = t.getResponseBody();
194 os.write(RESPONSE_DELETE.getBytes());
195 } else if (method.equals(HTTPMETHOD_OPTIONS)) {
196 t.sendResponseHeaders(200, RESPONSE_OPTIONS.length());
197 //os = t.getResponseBody();
198 //os.write(RESPONSE_OPTIONS.getBytes());
200 t.sendResponseHeaders(404, 0);
202 System.out.println("req handled successful");
204 } catch (Exception e) {
205 System.out.println(e.getMessage());