2 * ============LICENSE_START=======================================================
3 * ONAP : CCSDK.apps.sdnr.wt.apigateway
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=========================================================
21 package org.onap.ccsdk.features.sdnr.wt.apigateway.test.helper;
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertTrue;
25 import static org.junit.Assert.fail;
26 import static org.mockito.Mockito.mock;
27 import static org.mockito.Mockito.verify;
28 import static org.mockito.Mockito.when;
29 import com.sun.net.httpserver.HttpExchange;
30 import com.sun.net.httpserver.HttpHandler;
31 import com.sun.net.httpserver.HttpServer;
32 import java.io.IOException;
33 import java.io.OutputStream;
34 import java.net.InetSocketAddress;
35 import java.util.Enumeration;
37 import java.util.Vector;
38 import java.util.concurrent.ExecutorService;
39 import java.util.concurrent.Executors;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.servlet.http.HttpServletResponse;
42 import org.junit.After;
43 import org.junit.Before;
44 import org.onap.ccsdk.features.sdnr.wt.common.test.ServletInputStreamFromByteArrayInputStream;
45 import org.onap.ccsdk.features.sdnr.wt.common.test.ServletOutputStreamToStringWriter;
47 @SuppressWarnings("restriction")
48 public class HelpServletBase {
50 public static final String HTTPMETHOD_GET = "GET";
51 public static final String HTTPMETHOD_POST = "POST";
52 public static final String HTTPMETHOD_PUT = "PUT";
53 public static final String HTTPMETHOD_DELETE = "DELETE";
54 public static final String HTTPMETHOD_OPTIONS = "OPTIONS";
55 public static final String RESPONSE_GET = "This is the response get";
56 public static final String RESPONSE_POST = "This is the response post";
57 public static final String RESPONSE_PUT = "This is the response put";
58 public static final String RESPONSE_DELETE = "This is the response delete";
59 public static final String RESPONSE_OPTIONS = "This is the response options";
60 private IPublicServlet servlet;
61 private static HttpServer server;
62 private static ExecutorService httpThreadPool;
64 public final String HOST = "localhost";
65 protected static int testPort;
66 private final String baseUri;
67 protected static final String LR = "\n";
69 public HelpServletBase(String baseuri, int port) {
70 this.baseUri = baseuri;
74 public void setServlet(IPublicServlet s) {
78 protected void testrequest(String method, String data, String expectedResponse, boolean exact) {
79 this.testrequest("/mwtn/test", method, data, expectedResponse, exact, null);
82 protected void testrequest(String uri, String method, String data, String expectedResponse, boolean exact) {
83 this.testrequest(uri, method, data, expectedResponse, exact, null);
86 protected void testrequest(String uri, String method, String data, String expectedResponse, boolean exact,
87 Map<String, String> headersToCheck) {
89 HttpServletRequest mockRequest = mock(HttpServletRequest.class);
90 HttpServletResponse mockResponse = mock(HttpServletResponse.class);
92 ServletOutputStreamToStringWriter printOut = new ServletOutputStreamToStringWriter();
93 ServletInputStreamFromByteArrayInputStream inputStream = new ServletInputStreamFromByteArrayInputStream(data.getBytes());
94 Vector<String> headers = new Vector<String>();
95 headers.addElement("Accept");
96 headers.add("User-Agent");
97 Enumeration<String> headerNames = headers.elements();
99 when(mockRequest.getRequestURI()).thenReturn(this.baseUri + uri);
100 when(mockRequest.getHeaderNames()).thenReturn(headerNames);
101 when(mockRequest.getHeader("Accept")).thenReturn("application/json");
102 when(mockRequest.getHeader("User-Agent")).thenReturn("Gecko abc");
103 when(mockRequest.getInputStream()).thenReturn(inputStream);
104 when(mockResponse.getOutputStream()).thenReturn(printOut);
105 System.out.println("do a " + method + " request");
106 if (method == HTTPMETHOD_GET)
107 this.servlet.doGet(mockRequest, mockResponse);
108 else if (method == HTTPMETHOD_POST)
109 this.servlet.doPost(mockRequest, mockResponse);
110 else if (method == HTTPMETHOD_PUT)
111 this.servlet.doPut(mockRequest, mockResponse);
112 else if (method == HTTPMETHOD_DELETE)
113 this.servlet.doDelete(mockRequest, mockResponse);
114 else if (method == HTTPMETHOD_OPTIONS)
115 this.servlet.doOptions(mockRequest, mockResponse);
117 fail("http request method " + method + " test not implemented");
118 } catch (Exception e) {
119 System.err.println(e.getMessage());
122 verify(mockResponse).setStatus(200);
124 assertEquals(expectedResponse, printOut.getStringWriter().toString());
126 assertTrue("response not for method " + method + "correct", printOut.getStringWriter().toString().contains(expectedResponse));
127 // currently unable to check extra headers
128 if (headersToCheck != null) {
134 private void init() throws IOException {
137 initEsTestWebserver(testPort);
141 private void deinit() {
145 public static void initEsTestWebserver(int port) throws IOException {
146 initEsTestWebserver(port, "/mwtn/test");
149 public static void initEsTestWebserver(int port, String baseUri) throws IOException {
150 server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
151 httpThreadPool = Executors.newFixedThreadPool(5);
152 server.setExecutor(httpThreadPool);
153 server.createContext(baseUri, new MyHandler());
154 //server.createContext("/", new MyRootHandler());
155 server.setExecutor(null); // creates a default executor
157 System.out.println("http server started");
160 public static void stopTestWebserver() {
161 if (server != null) {
163 httpThreadPool.shutdownNow();
164 System.out.println("http server stopped");
170 public static class MyHandler implements HttpHandler {
172 public void handle(HttpExchange t) throws IOException {
173 String method = t.getRequestMethod();
174 System.out.println(String.format("req received: %s %s", method, t.getRequestURI()));
175 OutputStream os = null;
177 if (method.equals(HTTPMETHOD_GET)) {
178 t.sendResponseHeaders(200, RESPONSE_GET.length());
179 os = t.getResponseBody();
180 os.write(RESPONSE_GET.getBytes());
181 } else if (method.equals(HTTPMETHOD_POST)) {
182 t.sendResponseHeaders(200, RESPONSE_POST.length());
183 os = t.getResponseBody();
184 os.write(RESPONSE_POST.getBytes());
185 } else if (method.equals(HTTPMETHOD_PUT)) {
186 t.sendResponseHeaders(200, RESPONSE_PUT.length());
187 os = t.getResponseBody();
188 os.write(RESPONSE_PUT.getBytes());
189 } else if (method.equals(HTTPMETHOD_DELETE)) {
190 t.sendResponseHeaders(200, RESPONSE_DELETE.length());
191 os = t.getResponseBody();
192 os.write(RESPONSE_DELETE.getBytes());
193 } else if (method.equals(HTTPMETHOD_OPTIONS)) {
194 t.sendResponseHeaders(200, RESPONSE_OPTIONS.length());
195 //os = t.getResponseBody();
196 //os.write(RESPONSE_OPTIONS.getBytes());
198 t.sendResponseHeaders(404, 0);
200 System.out.println("req handled successful");
202 } catch (Exception e) {
203 System.out.println(e.getMessage());