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 public class HelpServletBase {
50 public static final String RESPONSE_GET = "This is the response get";
51 public static final String RESPONSE_POST = "This is the response post";
52 public static final String RESPONSE_PUT = "This is the response put";
53 public static final String RESPONSE_DELETE = "This is the response delete";
54 public static final String RESPONSE_OPTIONS = "This is the response options";
56 public static final String HTTPMETHOD_GET = "GET";
57 public static final String HTTPMETHOD_POST = "POST";
58 public static final String HTTPMETHOD_PUT = "PUT";
59 public static final String HTTPMETHOD_DELETE = "DELETE";
60 public static final String HTTPMETHOD_OPTIONS = "OPTIONS";
61 private IPublicServlet servlet;
62 private static HttpServer server;
63 private static ExecutorService httpThreadPool;
65 public final String HOST = "localhost";
66 protected static int testPort;
67 private final String baseUri;
68 protected static final String LR = "\n";
70 public HelpServletBase(String baseuri, int port) {
71 this.baseUri = baseuri;
75 public void setServlet(IPublicServlet s) {
79 protected void testrequest(String method, String data, String expectedResponse, boolean exact) {
80 this.testrequest("/mwtn/test", method, data, expectedResponse, exact, null);
83 protected void testrequest(String uri, String method, String data, String expectedResponse, boolean exact) {
84 this.testrequest(uri, method, data, expectedResponse, exact, null);
87 protected void testrequest(String uri, String method, String data, String expectedResponse, boolean exact,
88 Map<String, String> headersToCheck) {
90 HttpServletRequest mockRequest = mock(HttpServletRequest.class);
91 HttpServletResponse mockResponse = mock(HttpServletResponse.class);
93 ServletOutputStreamToStringWriter printOut = new ServletOutputStreamToStringWriter();
94 ServletInputStreamFromByteArrayInputStream inputStream = new ServletInputStreamFromByteArrayInputStream(data.getBytes());
95 Vector<String> headers = new Vector<String>();
96 headers.addElement("Accept");
97 headers.add("User-Agent");
98 Enumeration<String> headerNames = headers.elements();
100 when(mockRequest.getRequestURI()).thenReturn(this.baseUri + uri);
101 when(mockRequest.getHeaderNames()).thenReturn(headerNames);
102 when(mockRequest.getHeader("Accept")).thenReturn("application/json");
103 when(mockRequest.getHeader("User-Agent")).thenReturn("Gecko abc");
104 when(mockRequest.getInputStream()).thenReturn(inputStream);
105 when(mockResponse.getOutputStream()).thenReturn(printOut);
106 System.out.println("do a " + method + " request");
107 if (method == HTTPMETHOD_GET)
108 this.servlet.doGet(mockRequest, mockResponse);
109 else if (method == HTTPMETHOD_POST)
110 this.servlet.doPost(mockRequest, mockResponse);
111 else if (method == HTTPMETHOD_PUT)
112 this.servlet.doPut(mockRequest, mockResponse);
113 else if (method == HTTPMETHOD_DELETE)
114 this.servlet.doDelete(mockRequest, mockResponse);
115 else if (method == HTTPMETHOD_OPTIONS)
116 this.servlet.doOptions(mockRequest, mockResponse);
118 fail("http request method " + method + " test not implemented");
119 } catch (Exception e) {
120 System.err.println(e.getMessage());
123 verify(mockResponse).setStatus(200);
125 assertEquals(expectedResponse, printOut.getStringWriter().toString());
127 assertTrue("response not for method " + method + "correct", printOut.getStringWriter().toString().contains(expectedResponse));
128 // currently unable to check extra headers
129 if (headersToCheck != null) {
135 private void init() throws IOException {
138 initEsTestWebserver(testPort);
142 private void deinit() {
146 public static void initEsTestWebserver(int port) throws IOException {
147 initEsTestWebserver(port, "/mwtn/test");
150 public static void initEsTestWebserver(int port, String baseUri) throws IOException {
151 server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
152 httpThreadPool = Executors.newFixedThreadPool(5);
153 server.setExecutor(httpThreadPool);
154 server.createContext(baseUri, new MyHandler());
155 //server.createContext("/", new MyRootHandler());
156 server.setExecutor(null); // creates a default executor
158 System.out.println("http server started");
161 public static void stopTestWebserver() {
162 if (server != null) {
164 httpThreadPool.shutdownNow();
165 System.out.println("http server stopped");
171 public static class MyHandler implements HttpHandler {
173 public void handle(HttpExchange t) throws IOException {
174 String method = t.getRequestMethod();
175 System.out.println(String.format("req received: %s %s", method, t.getRequestURI()));
176 OutputStream os = null;
178 if (method.equals(HTTPMETHOD_GET)) {
179 t.sendResponseHeaders(200, RESPONSE_GET.length());
180 os = t.getResponseBody();
181 os.write(RESPONSE_GET.getBytes());
182 } else if (method.equals(HTTPMETHOD_POST)) {
183 t.sendResponseHeaders(200, RESPONSE_POST.length());
184 os = t.getResponseBody();
185 os.write(RESPONSE_POST.getBytes());
186 } else if (method.equals(HTTPMETHOD_PUT)) {
187 t.sendResponseHeaders(200, RESPONSE_PUT.length());
188 os = t.getResponseBody();
189 os.write(RESPONSE_PUT.getBytes());
190 } else if (method.equals(HTTPMETHOD_DELETE)) {
191 t.sendResponseHeaders(200, RESPONSE_DELETE.length());
192 os = t.getResponseBody();
193 os.write(RESPONSE_DELETE.getBytes());
194 } else if (method.equals(HTTPMETHOD_OPTIONS)) {
195 t.sendResponseHeaders(200, RESPONSE_OPTIONS.length());
196 //os = t.getResponseBody();
197 //os.write(RESPONSE_OPTIONS.getBytes());
199 t.sendResponseHeaders(404, 0);
201 System.out.println("req handled successful");
203 } catch (Exception e) {
204 System.out.println(e.getMessage());