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