Assign image keyname and pubkey at vnf level
[ccsdk/apps.git] / sdnr / wireless-transport / code-Carbon-SR1 / apps / apigateway / impl / src / main / java / com / highstreet / technologies / apigateway / EsServlet.java
1 package com.highstreet.technologies.apigateway;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.OutputStream;
6 import java.net.HttpURLConnection;
7 import java.net.URL;
8 import java.net.URLConnection;
9 import java.nio.charset.Charset;
10 import java.nio.charset.StandardCharsets;
11 import java.security.KeyManagementException;
12 import java.security.NoSuchAlgorithmException;
13 import java.util.Enumeration;
14 import java.util.List;
15 import java.util.Map;
16
17 import javax.net.ssl.HostnameVerifier;
18 import javax.net.ssl.HttpsURLConnection;
19 import javax.net.ssl.SSLContext;
20 import javax.net.ssl.SSLSession;
21 import javax.net.ssl.TrustManager;
22 import javax.servlet.ServletException;
23 import javax.servlet.http.HttpServlet;
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpServletResponse;
26
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 public class EsServlet extends HttpServlet {
31
32         /**
33          *
34          */
35         private static final long serialVersionUID = -3996363343749995011L;
36         private static Logger LOG = LoggerFactory.getLogger(EsServlet.class);
37         private static final int BUFSIZE = 1024;
38         private static final byte[] OFFLINE_RESPONSE_BYTES = "Database interface is offline"
39                         .getBytes(StandardCharsets.UTF_8);
40         private static SSLContext sc;
41         private static boolean TRUSTALL = false;
42
43         /**
44          *
45          * @throws NoSuchAlgorithmException
46          * @throws KeyManagementException
47          */
48         private static void setupSslTrustAll() throws NoSuchAlgorithmException, KeyManagementException {
49
50                 sc = SSLContext.getInstance("TLSv1.2");
51                 TrustManager[] trustCerts = null;
52                 if (TRUSTALL) {
53                         trustCerts = new TrustManager[] { new javax.net.ssl.X509TrustManager() {
54                                 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
55                                         return null;
56                                 }
57
58                                 public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
59                                 }
60
61                                 public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
62                                 }
63                         } };
64
65                 }
66                 // Init the SSLContext with a TrustManager[] and SecureRandom()
67                 sc.init(null, trustCerts, new java.security.SecureRandom());
68
69         }
70
71         public EsServlet() {
72
73                 try {
74                         MyProperties.Instantiate(MyProperties.PROPFILE);
75                 } catch (Exception e) {
76                         LOG.error(e.getMessage());
77                 }
78
79                 TRUSTALL = MyProperties.getInstance().trustInsecure();
80                 try {
81                         setupSslTrustAll();
82                 } catch (Exception e) {
83                         LOG.error("error setting up SSL: " + e.getMessage());
84                 }
85         }
86
87         @Override
88         protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
89                 if (MyProperties.getInstance().isEsOff()) {
90                         this.sendOffResponse(resp);
91                 } else {
92                         HttpURLConnection http = (HttpURLConnection) this.getConnection(req, "PUT");
93                         this.handleRequest(http, req, resp, "PUT");
94                         http.disconnect();
95                 }
96         }
97
98         @Override
99         protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
100                 if (MyProperties.getInstance().isEsOff()) {
101                         this.sendOffResponse(resp);
102                 } else {
103                         HttpURLConnection http = (HttpURLConnection) this.getConnection(req, "GET");
104                         this.handleRequest(http, req, resp, "GET");
105                         http.disconnect();
106                 }
107         }
108
109         @Override
110         protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
111                 if (MyProperties.getInstance().isEsOff()) {
112                         this.sendOffResponse(resp);
113                 } else {
114                         HttpURLConnection http = (HttpURLConnection) this.getConnection(req, "POST");
115                         this.handleRequest(http, req, resp, "POST");
116                         http.disconnect();
117                 }
118         }
119
120         @Override
121         protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
122                 if (MyProperties.getInstance().isEsOff()) {
123                         this.sendOffResponse(resp);
124                 } else {
125                         HttpURLConnection http = (HttpURLConnection) this.getConnection(req, "DELETE");
126                         this.handleRequest(http, req, resp, "DELETE");
127                         http.disconnect();
128                 }
129
130         }
131
132         @Override
133         protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
134                 if (MyProperties.getInstance().corsEnabled()) {
135                         resp.addHeader("Access-Control-Allow-Origin", "*");
136                         resp.addHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
137                         resp.addHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
138                 }
139                 super.doOptions(req, resp);
140         }
141
142         private void sendOffResponse(HttpServletResponse response) {
143                 response.setStatus(200);// HTML/OK
144                 response.setHeader("Content-Type", "text/html; charset=utf-8");
145                 try {
146                         response.getOutputStream().write(OFFLINE_RESPONSE_BYTES);
147                 } catch (IOException e) {
148                         LOG.debug("problem writing offline response");
149                 }
150
151         }
152
153         private URLConnection getConnection(HttpServletRequest req, final String method) throws IOException {
154
155                 LOG.debug(method + " Request");
156                 // String query = req.getQueryString();
157                 String uri = req.getRequestURI();
158                 if (uri != null && uri.length() > 0)
159                         uri = uri.substring("/database".length());
160                 String surl = MyProperties.getInstance().getEsBaseUrl() + uri;
161                 // if (query != null && query.length() > 0)
162                 // surl += "?" + query;
163                 LOG.debug("RemoteURL: " + surl);
164                 URL url = new URL(surl);
165                 URLConnection http = url.openConnection();
166                 ((HttpURLConnection) http).setRequestMethod(method);
167                 if (url.toString().startsWith("https")) {
168                         ((HttpsURLConnection) http).setSSLSocketFactory(sc.getSocketFactory());
169                         if (TRUSTALL) {
170                                 HostnameVerifier allHostsValid = new HostnameVerifier() {
171                                         public boolean verify(String hostname, SSLSession session) {
172                                                 return true;
173                                         }
174                                 };
175                                 ((HttpsURLConnection) http).setHostnameVerifier(allHostsValid);
176                         }
177                 }
178                 http.setDoOutput(true);
179                 // copy request headers
180                 String s = "";
181                 Enumeration<String> headers = req.getHeaderNames();
182                 while (headers.hasMoreElements()) {
183                         String h = headers.nextElement();
184                         String v = req.getHeader(h);
185                         if (h != null && h.equals("Host"))
186                                 v = url.getAuthority();
187                         s += String.format("%s:%s;", h, v);
188                         http.setRequestProperty(h, v);
189                 }
190                 LOG.debug("Request Headers: " + s);
191                 return http;
192         }
193
194         private void handleRequest(HttpURLConnection http, HttpServletRequest req, HttpServletResponse resp, String method)
195                         throws IOException {
196                 byte[] buffer = new byte[BUFSIZE];
197                 int len = 0, lensum = 0;
198                 // send request
199                 // Send the message to destination
200                 if (!method.equals("GET")) {
201                         try (OutputStream output = http.getOutputStream()) {
202                                 while (true) {
203                                         len = req.getInputStream().read(buffer, 0, BUFSIZE);
204                                         if (len <= 0)
205                                                 break;
206                                         lensum += len;
207                                         output.write(buffer, 0, len);
208                                 }
209                         }
210                 }
211                 LOG.debug("written " + lensum + " data out");
212                 int responseCode = ((HttpURLConnection) http).getResponseCode();
213                 // Receive answer
214                 InputStream response;
215                 if (responseCode >= 200 && responseCode < 300)
216                         response = http.getInputStream();
217                 else {
218                         response = http.getErrorStream();
219                         if (response == null)
220                                 http.getInputStream();
221                 }
222
223                 LOG.debug("ResponseCode: " + responseCode);
224                 resp.setStatus(responseCode);
225                 Map<String, List<String>> set = http.getHeaderFields();
226                 String s = "";
227                 if (set != null) {
228                         for (Map.Entry<String, List<String>> entry : set.entrySet()) {
229                                 if (entry.getKey() == null)
230                                         continue;
231                                 for (String v : entry.getValue()) {
232                                         resp.setHeader(entry.getKey(), v);
233                                         s += String.format("%s:%s;", entry.getKey(), v);
234                                 }
235                                 if (MyProperties.getInstance().corsEnabled()) {
236                                         resp.setHeader("Access-Control-Allow-Origin", "*");
237                                         //resp.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
238                                         resp.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
239                                 }
240
241                         }
242                 }
243                 LOG.debug("Received Headers: " + s);
244                 lensum = 0;
245                 if (response != null) {
246                         while (true) {
247                                 len = response.read(buffer, 0, BUFSIZE);
248                                 if (len <= 0)
249                                         break;
250                                 lensum += len;
251                                 resp.getOutputStream().write(buffer, 0, len);
252                         }
253                 } else
254                         LOG.debug("response is null");
255                 LOG.debug("Received " + lensum + " bytes");
256         }
257 }