Merge "Reformat sdnr netconfnode-state-service to ONAP code style"
[ccsdk/features.git] / sdnr / wt / common / src / test / java / org / onap / ccsdk / features / sdnr / wt / common / test / TestBaseHttpClient.java
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
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
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  *
21  */
22 package org.onap.ccsdk.features.sdnr.wt.common.test;
23
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
28
29 import java.io.IOException;
30 import java.io.OutputStream;
31 import java.net.InetSocketAddress;
32 import java.util.HashMap;
33 import java.util.Map;
34 import java.util.concurrent.ExecutorService;
35 import java.util.concurrent.Executors;
36
37 import org.junit.AfterClass;
38 import org.junit.BeforeClass;
39 import org.junit.Test;
40 import org.onap.ccsdk.features.sdnr.wt.common.http.BaseHTTPClient;
41 import org.onap.ccsdk.features.sdnr.wt.common.http.BaseHTTPResponse;
42
43 import com.sun.net.httpserver.HttpExchange;
44 import com.sun.net.httpserver.HttpHandler;
45 import com.sun.net.httpserver.HttpServer;
46
47 @SuppressWarnings("restriction")
48 public class TestBaseHttpClient {
49
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 static final String TESTURI = "/mwtn/test";
61     private static HttpServer server;
62     private static ExecutorService httpThreadPool;
63     private static final int testPort = 54440;
64
65     @Test
66     public void test() {
67         MyHttpClient httpClient = new MyHttpClient("http://localhost:" + testPort, true);
68         Map<String, String> headers = new HashMap<String, String>();
69         headers.put("Authorization", BaseHTTPClient.getAuthorizationHeaderValue("admin", "admin"));
70         headers.put("Content-Type", "application/json");
71         BaseHTTPResponse response = null;
72         try {
73             response = httpClient.sendRequest(TESTURI, HTTPMETHOD_GET, null, headers);
74         } catch (IOException e) {
75             fail(e.getMessage());
76         }
77         assertNotNull(response);
78         assertEquals(RESPONSE_GET, response.body);
79         try {
80             response = httpClient.sendRequest(TESTURI, HTTPMETHOD_POST, "{}", headers);
81         } catch (IOException e) {
82             fail(e.getMessage());
83         }
84         assertNotNull(response);
85         assertTrue(response.isSuccess());
86         System.out.println(response.toString());
87         assertEquals(RESPONSE_POST, response.body);
88         try {
89             response = httpClient.sendRequest(TESTURI, HTTPMETHOD_PUT, "{}", headers);
90         } catch (IOException e) {
91             fail(e.getMessage());
92         }
93         assertNotNull(response);
94         assertEquals(RESPONSE_PUT, response.body);
95         try {
96             response = httpClient.sendRequest(TESTURI, HTTPMETHOD_DELETE, "{}", headers);
97         } catch (IOException e) {
98             fail(e.getMessage());
99         }
100         assertNotNull(response);
101         assertEquals(RESPONSE_DELETE, response.body);
102
103     }
104
105
106
107     @BeforeClass
108     public static void initTestWebserver() throws IOException {
109         server = HttpServer.create(new InetSocketAddress("127.0.0.1", testPort), 0);
110         httpThreadPool = Executors.newFixedThreadPool(5);
111         server.setExecutor(httpThreadPool);
112         server.createContext(TESTURI, new MyHandler());
113         //server.createContext("/", new MyRootHandler());
114         server.setExecutor(null); // creates a default executor
115         server.start();
116         System.out.println("http server started");
117     }
118
119     @AfterClass
120     public static void stopTestWebserver() {
121         System.out.println("try to stop server");
122         if (server != null) {
123             server.stop(0);
124             httpThreadPool.shutdownNow();
125             System.out.println("http server stopped");
126         }
127     }
128
129     private class MyHttpClient extends BaseHTTPClient {
130
131         public MyHttpClient(String base, boolean trustAllCerts) {
132             super(base, trustAllCerts);
133         }
134
135         @Override
136         public BaseHTTPResponse sendRequest(String uri, String method, String body, Map<String, String> headers)
137                 throws IOException {
138             return super.sendRequest(uri, method, body, headers);
139         }
140     }
141
142     public static class MyHandler implements HttpHandler {
143
144         @Override
145         public void handle(HttpExchange t) throws IOException {
146             String method = t.getRequestMethod();
147             System.out.println(String.format("req received: %s %s", method, t.getRequestURI()));
148             OutputStream os = null;
149             try {
150                 if (method.equals(HTTPMETHOD_GET)) {
151                     t.sendResponseHeaders(200, RESPONSE_GET.length());
152                     os = t.getResponseBody();
153                     os.write(RESPONSE_GET.getBytes());
154                 } else if (method.equals(HTTPMETHOD_POST)) {
155                     t.sendResponseHeaders(200, RESPONSE_POST.length());
156                     os = t.getResponseBody();
157                     os.write(RESPONSE_POST.getBytes());
158                 } else if (method.equals(HTTPMETHOD_PUT)) {
159                     t.sendResponseHeaders(200, RESPONSE_PUT.length());
160                     os = t.getResponseBody();
161                     os.write(RESPONSE_PUT.getBytes());
162                 } else if (method.equals(HTTPMETHOD_DELETE)) {
163                     t.sendResponseHeaders(200, RESPONSE_DELETE.length());
164                     os = t.getResponseBody();
165                     os.write(RESPONSE_DELETE.getBytes());
166                 } else if (method.equals(HTTPMETHOD_OPTIONS)) {
167                     t.sendResponseHeaders(200, RESPONSE_OPTIONS.length());
168                     //os = t.getResponseBody();
169                     //os.write(RESPONSE_OPTIONS.getBytes());
170                 } else {
171                     t.sendResponseHeaders(404, 0);
172                 }
173                 System.out.println("req handled successful");
174
175             } catch (Exception e) {
176                 System.out.println(e.getMessage());
177             } finally {
178                 if (os != null) {
179                     os.flush();
180                     os.close();
181                 }
182             }
183         }
184     }
185 }