aboutsummaryrefslogtreecommitdiffstats
path: root/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServletBase.java
blob: c163c746f9b29ece43ebbd99420336fcb52cd203 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/*
 * ============LICENSE_START=======================================================
 * ONAP : ccsdk features
 * ================================================================================
 * Copyright (C) 2018 highstreet technologies GmbH Intellectual Property.
 * All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 *
 */
package org.onap.ccsdk.features.sdnr.wt.common.test.helper;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.InetSocketAddress;
import java.util.Enumeration;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.After;
import org.junit.Before;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class HelpServletBase {

    public static final String RESPONSE_GET = "This is the response get";
    public static final String RESPONSE_POST = "This is the response post";
    public static final String RESPONSE_PUT = "This is the response put";
    public static final String RESPONSE_DELETE = "This is the response delete";
    public static final String RESPONSE_OPTIONS = "This is the response options";

    public static final String HTTPMETHOD_GET = "GET";
    public static final String HTTPMETHOD_POST = "POST";
    public static final String HTTPMETHOD_PUT = "PUT";
    public static final String HTTPMETHOD_DELETE = "DELETE";
    public static final String HTTPMETHOD_OPTIONS = "OPTIONS";
    private IPublicServlet servlet;
    private static HttpServer server;
    private static ExecutorService httpThreadPool;

    public final String HOST = "localhost";
    protected static int testPort;
    private final String baseUri;
    protected static final String LR = "\n";

    public HelpServletBase(String baseuri, int port) {
        this.baseUri = baseuri;
        testPort = port;
    }

    public void setServlet(IPublicServlet s) {
        this.servlet = s;
    }

    protected void testrequest(String method, String data, String expectedResponse, boolean exact) {
        this.testrequest("/mwtn/test", method, data, expectedResponse, exact, null);
    }

    protected void testrequest(String uri, String method, String data, String expectedResponse, boolean exact) {
        this.testrequest(uri, method, data, expectedResponse, exact, null);
    }

    protected void testrequest(String uri, String method, String data, String expectedResponse, boolean exact,
            Map<String, String> headersToCheck) {

        HttpServletRequest mockRequest = mock(HttpServletRequest.class);
        HttpServletResponse mockResponse = mock(HttpServletResponse.class);

        StringWriter out = new StringWriter();
        ServletOutputStream printOut = new ServletOutputStream() {

            @Override
            public void write(int arg0) throws IOException {
                out.write(arg0);
            }
        };
        ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes());
        ServletInputStream inputStream = new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return bis.read();
            }
        };
        Vector<String> headers = new Vector<String>();
        headers.addElement("Accept");
        headers.add("User-Agent");
        Enumeration<String> headerNames = headers.elements();
        try {
            when(mockRequest.getRequestURI()).thenReturn(this.baseUri + uri);
            when(mockRequest.getHeaderNames()).thenReturn(headerNames);
            when(mockRequest.getHeader("Accept")).thenReturn("application/json");
            when(mockRequest.getHeader("User-Agent")).thenReturn("Gecko abc");
            when(mockRequest.getInputStream()).thenReturn(inputStream);
            when(mockResponse.getOutputStream()).thenReturn(printOut);
            System.out.println("do a " + method + " request");
            if (method == HTTPMETHOD_GET)
                this.servlet.doGet(mockRequest, mockResponse);
            else if (method == HTTPMETHOD_POST)
                this.servlet.doPost(mockRequest, mockResponse);
            else if (method == HTTPMETHOD_PUT)
                this.servlet.doPut(mockRequest, mockResponse);
            else if (method == HTTPMETHOD_DELETE)
                this.servlet.doDelete(mockRequest, mockResponse);
            else if (method == HTTPMETHOD_OPTIONS)
                this.servlet.doOptions(mockRequest, mockResponse);
            else
                fail("http request method " + method + " test not implemented");
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }

        verify(mockResponse).setStatus(200);
        if (exact)
            assertEquals(expectedResponse, out.toString());
        else
            assertTrue("response not for method " + method + "correct", out.toString().contains(expectedResponse));
        // currently unable to check extra headers
        if (headersToCheck != null) {

        }
    }

    @Before
    private void init() throws IOException {


        initEsTestWebserver(testPort);
    }

    @After
    private void deinit() {
        stopTestWebserver();
    }

    public static void initEsTestWebserver(int port) throws IOException {
        initEsTestWebserver(port, "/mwtn/test");
    }

    public static void initEsTestWebserver(int port, String baseUri) throws IOException {
        server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
        httpThreadPool = Executors.newFixedThreadPool(5);
        server.setExecutor(httpThreadPool);
        server.createContext(baseUri, new MyHandler());
        //server.createContext("/", new MyRootHandler());
        server.setExecutor(null); // creates a default executor
        server.start();
        System.out.println("http server started");
    }

    public static void stopTestWebserver() {
        if (server != null) {
            server.stop(0);
            httpThreadPool.shutdownNow();
            System.out.println("http server stopped");
        }
    }



    public static class MyHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange t) throws IOException {
            String method = t.getRequestMethod();
            System.out.println(String.format("req received: %s %s", method, t.getRequestURI()));
            OutputStream os = null;
            try {
                if (method.equals(HTTPMETHOD_GET)) {
                    t.sendResponseHeaders(200, RESPONSE_GET.length());
                    os = t.getResponseBody();
                    os.write(RESPONSE_GET.getBytes());
                } else if (method.equals(HTTPMETHOD_POST)) {
                    t.sendResponseHeaders(200, RESPONSE_POST.length());
                    os = t.getResponseBody();
                    os.write(RESPONSE_POST.getBytes());
                } else if (method.equals(HTTPMETHOD_PUT)) {
                    t.sendResponseHeaders(200, RESPONSE_PUT.length());
                    os = t.getResponseBody();
                    os.write(RESPONSE_PUT.getBytes());
                } else if (method.equals(HTTPMETHOD_DELETE)) {
                    t.sendResponseHeaders(200, RESPONSE_DELETE.length());
                    os = t.getResponseBody();
                    os.write(RESPONSE_DELETE.getBytes());
                } else if (method.equals(HTTPMETHOD_OPTIONS)) {
                    t.sendResponseHeaders(200, RESPONSE_OPTIONS.length());
                    //os = t.getResponseBody();
                    //os.write(RESPONSE_OPTIONS.getBytes());
                } else {
                    t.sendResponseHeaders(404, 0);
                }
                System.out.println("req handled successful");

            } catch (Exception e) {
                System.out.println(e.getMessage());
            } finally {
                if (os != null) {
                    os.close();
                }
            }
        }
    }
}