2 * ============LICENSE_START=======================================================
3 * ONAP : CCSDK.apps.sdnr.wt.apigateway
4 * ================================================================================
5 * Copyright (C) 2019 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;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStream;
26 import java.net.HttpURLConnection;
28 import java.net.URLConnection;
29 import java.nio.charset.StandardCharsets;
30 import java.security.KeyManagementException;
31 import java.security.NoSuchAlgorithmException;
32 import java.util.Enumeration;
33 import java.util.List;
36 import javax.net.ssl.HostnameVerifier;
37 import javax.net.ssl.HttpsURLConnection;
38 import javax.net.ssl.SSLContext;
39 import javax.net.ssl.SSLSession;
40 import javax.net.ssl.TrustManager;
41 import javax.servlet.ServletException;
42 import javax.servlet.http.HttpServlet;
43 import javax.servlet.http.HttpServletRequest;
44 import javax.servlet.http.HttpServletResponse;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 public abstract class BaseServlet extends HttpServlet {
54 private static final long serialVersionUID = 7403047480257892794L;
55 private static Logger LOG = LoggerFactory.getLogger(BaseServlet.class);
56 private static SSLContext sc;
57 private boolean trustAll = false;
58 private static TrustManager[] trustCerts = null;
59 private static final int BUFSIZE = 2048;
61 protected abstract String getOfflineResponse();
63 protected abstract boolean isOff();
65 protected abstract String getRemoteUrl(String uri);
69 * @throws NoSuchAlgorithmException
70 * @throws KeyManagementException
72 private static void setupSslTrustAll(boolean trustall) throws NoSuchAlgorithmException, KeyManagementException {
74 sc = SSLContext.getInstance("TLSv1.2");
76 if (trustCerts == null) {
77 trustCerts = new TrustManager[] { new javax.net.ssl.X509TrustManager() {
79 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
80 return new java.security.cert.X509Certificate[] {};
84 public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
85 // do not check anything when trust all
89 public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
90 // do not check anything when trust all
95 if (trustCerts != null)
98 // Init the SSLContext with a TrustManager[] and SecureRandom()
99 sc.init(null, trustCerts, new java.security.SecureRandom());
102 public BaseServlet() {
104 MyProperties.Instantiate();
105 } catch (Exception e) {
106 LOG.error(e.getMessage());
108 this.trysslSetup(true);
111 private void trysslSetup() {
112 this.trysslSetup(false);
116 * init or deinit ssl insecure mode regarding to property
118 * @param force init independent from property
120 private void trysslSetup(boolean force) {
121 // if trustall config has changed
122 if (force || trustAll != MyProperties.getInstance().trustInsecure()) {
123 // resetup ssl config
124 trustAll = MyProperties.getInstance().trustInsecure();
126 setupSslTrustAll(trustAll);
127 } catch (Exception e) {
128 LOG.error("problem setting up SSL: {}", e.getMessage());
133 protected void sendOffResponse(HttpServletResponse response) {
134 response.setStatus(200);// HTML/OK
135 response.setHeader("Content-Type", "text/html; charset=utf-8");
137 response.getOutputStream().write(this.getOfflineResponse().getBytes(StandardCharsets.UTF_8));
138 } catch (IOException e) {
139 LOG.debug("problem writing offline response");
145 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
147 this.sendOffResponse(resp);
150 HttpURLConnection http = null;
152 http = (HttpURLConnection) this.getConnection(req, "GET");
153 } catch (IOException e) {
154 LOG.warn(e.getMessage());
158 this.handleRequest(http, req, resp, "GET");
159 } catch (IOException e) {
160 LOG.warn(e.getMessage());
168 protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
170 this.sendOffResponse(resp);
173 HttpURLConnection http = null;
175 http = (HttpURLConnection) this.getConnection(req, "PUT");
176 } catch (IOException e) {
177 LOG.warn(e.getMessage());
181 this.handleRequest(http, req, resp, "PUT");
182 } catch (IOException e) {
183 LOG.warn(e.getMessage());
191 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
193 this.sendOffResponse(resp);
196 HttpURLConnection http = null;
198 http = (HttpURLConnection) this.getConnection(req, "POST");
199 } catch (IOException e) {
200 LOG.warn(e.getMessage());
204 this.handleRequest(http, req, resp, "POST");
205 } catch (IOException e) {
206 LOG.warn(e.getMessage());
214 protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
216 this.sendOffResponse(resp);
219 HttpURLConnection http = null;
221 http = (HttpURLConnection) this.getConnection(req, "DELETE");
222 } catch (IOException e) {
223 LOG.warn(e.getMessage());
227 this.handleRequest(http, req, resp, "DELETE");
228 } catch (IOException e) {
229 LOG.warn(e.getMessage());
236 private URLConnection getConnection(HttpServletRequest req, final String method) throws IOException {
238 LOG.debug("{} Request", method);
239 String surl = this.getRemoteUrl(req.getRequestURI());
240 LOG.debug("RemoteURL: {}", surl);
241 URL url = new URL(surl);
242 URLConnection http = url.openConnection();
243 ((HttpURLConnection) http).setRequestMethod(method);
244 if (url.toString().startsWith("https")) {
245 ((HttpsURLConnection) http).setSSLSocketFactory(sc.getSocketFactory());
247 HostnameVerifier allHostsValid = new HostnameVerifier() {
250 public boolean verify(String hostname, SSLSession session) {
251 // do not verify host if trust all
255 ((HttpsURLConnection) http).setHostnameVerifier(allHostsValid);
258 http.setDoOutput(true);
259 // copy request headers
261 Enumeration<String> headers = req.getHeaderNames();
262 while (headers.hasMoreElements()) {
263 String h = headers.nextElement();
264 String v = req.getHeader(h);
265 if (h != null && h.equals("Host")) {
266 v = url.getAuthority();
268 s += String.format("%s:%s;", h, v);
269 http.setRequestProperty(h, v);
271 LOG.debug("Request Headers: {}", s);
275 private void handleRequest(HttpURLConnection http, HttpServletRequest req, HttpServletResponse resp, String method)
277 byte[] buffer = new byte[BUFSIZE];
278 int len = 0, lensum = 0;
280 // Send the message to destination
281 OutputStream output = null;
282 if (!method.equals("GET")) {
284 output = http.getOutputStream();
285 } catch (Exception e) {
286 LOG.debug("problem reading output stream: {}", e.getMessage());
289 if (output != null) {
291 len = req.getInputStream().read(buffer, 0, BUFSIZE);
296 output.write(buffer, 0, len);
299 LOG.debug("written {} data out", lensum);
300 int responseCode = http.getResponseCode();
302 InputStream response;
303 if (responseCode >= 200 && responseCode < 300) {
304 response = http.getInputStream();
306 response = http.getErrorStream();
307 if (response == null) {
308 http.getInputStream();
312 LOG.debug("ResponseCode: {}", responseCode);
313 resp.setStatus(responseCode);
314 Map<String, List<String>> set = http.getHeaderFields();
317 for (Map.Entry<String, List<String>> entry : set.entrySet()) {
318 if (entry.getKey() == null) {
321 for (String v : entry.getValue()) {
322 resp.setHeader(entry.getKey(), v);
323 s += String.format("%s:%s;", entry.getKey(), v);
325 if (MyProperties.getInstance().corsEnabled()) {
326 resp.setHeader("Access-Control-Allow-Origin", "*");
327 // resp.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
328 resp.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
333 LOG.debug("Received Headers: {}", s);
335 if (response != null) {
337 len = response.read(buffer, 0, BUFSIZE);
342 resp.getOutputStream().write(buffer, 0, len);
345 LOG.debug("response is null");
347 LOG.debug("Received {} bytes", lensum);