bf54ae1e0001b8dafaf69f89c9073d6929d2d0d2
[ccsdk/apps.git] / sdnr / wireless-transport / code-Carbon-SR1 / apps / apigateway / impl / src / main / java / com / highstreet / technologies / apigateway / AaiServlet.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 import java.util.Map.Entry;
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 AaiServlet extends HttpServlet {
31
32         /**
33          *
34          */
35         private static final long serialVersionUID = 5946205120796162644L;
36         private static Logger LOG = LoggerFactory.getLogger(AaiServlet.class);
37         private static final byte[] OFFLINE_RESPONSE_BYTES = "AAI interface is offline".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 AaiServlet() {
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                 if (MyProperties.getInstance().isAAIOff()) {
89                         this.sendOffResponse(resp);
90                 } else {
91                         HttpURLConnection http = (HttpURLConnection) this.getConnection(req, "PUT");
92                         this.handleRequest(http, req, resp, "PUT");
93                         http.disconnect();
94                 }
95         }
96
97         @Override
98         protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
99                 if (MyProperties.getInstance().isAAIOff()) {
100                         this.sendOffResponse(resp);
101                 } else {
102                         HttpURLConnection http = (HttpURLConnection) this.getConnection(req, "GET");
103                         this.handleRequest(http, req, resp, "GET");
104                         http.disconnect();
105                 }
106         }
107
108         @Override
109         protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
110                 if (MyProperties.getInstance().isAAIOff()) {
111                         this.sendOffResponse(resp);
112                 } else {
113                         HttpURLConnection http = (HttpURLConnection) this.getConnection(req, "POST");
114                         this.handleRequest(http, req, resp, "POST");
115                         http.disconnect();
116                 }
117         }
118
119         @Override
120         protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
121                 if (MyProperties.getInstance().isAAIOff()) {
122                         this.sendOffResponse(resp);
123                 } else {
124                         HttpURLConnection http = (HttpURLConnection) this.getConnection(req, "DELETE");
125                         this.handleRequest(http, req, resp, "DELETE");
126                         http.disconnect();
127                 }
128
129         }
130
131         @Override
132         protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
133                 // if(MyProperties.getInstance().corsEnabled())
134                 // resp.addHeader("Access-Control-Allow-Origin","*");
135                 super.doOptions(req, resp);
136         }
137
138         private void sendOffResponse(HttpServletResponse response) {
139                 response.setStatus(200);// HTML/OK
140                 response.setHeader("Content-Type", "text/html; charset=utf-8");
141                 try {
142                         response.getOutputStream().write(OFFLINE_RESPONSE_BYTES);
143                 } catch (IOException e) {
144                         LOG.debug("problem writing offline response");
145                 }
146
147         }
148
149         private URLConnection getConnection(HttpServletRequest req, final String method) throws IOException {
150
151                 LOG.debug(method + " Request");
152                 // String query = req.getQueryString();
153                 String uri=req.getRequestURI();
154                 if(uri.startsWith("/"))
155                         uri=uri.substring(1);
156                 if(uri.startsWith("aai"))
157                         uri=uri.substring("aai".length());
158                 if(uri.startsWith("/"))
159                         uri=uri.substring(1);
160                 String base=MyProperties.getInstance().getAAIBaseUrl() ;
161                 if(!base.endsWith("/"))
162                         base+="/";
163
164                 String surl =base+uri;
165                 // if (query != null && query.length() > 0)
166                 // surl += "?" + query;
167                 LOG.debug("RemoteURL: " + surl);
168                 URL url = new URL(surl);
169                 URLConnection http = url.openConnection();
170                 ((HttpURLConnection) http).setRequestMethod(method);
171                 if (url.toString().startsWith("https")) {
172                         ((HttpsURLConnection) http).setSSLSocketFactory(sc.getSocketFactory());
173                         if (TRUSTALL) {
174                                 HostnameVerifier allHostsValid = new HostnameVerifier() {
175                                         public boolean verify(String hostname, SSLSession session) {
176                                                 return true;
177                                         }
178                                 };
179                                 ((HttpsURLConnection) http).setHostnameVerifier(allHostsValid);
180                         }
181                 }
182                 http.setDoOutput(true);
183                 // copy request headers
184                 String s = "";
185                 Enumeration<String> headers = req.getHeaderNames();
186                 while (headers.hasMoreElements()) {
187                         String h = headers.nextElement();
188                         String v = req.getHeader(h);
189                         if (h != null && h.equals("Host"))
190                                 v = url.getAuthority();
191                         s += String.format("%s:%s;", h, v);
192                         http.setRequestProperty(h, v);
193                 }
194                 Map<String,String> addHeaders=MyProperties.getInstance().getAAIHeaders();
195                 if(addHeaders!=null)
196                 {
197                         for(Entry<String,String> entry:addHeaders.entrySet())
198                         {
199                                 http.setRequestProperty(entry.getKey(), entry.getValue());
200                         }
201                 }
202                 LOG.debug("Request Headers: " + s);
203                 return http;
204         }
205
206         private void handleRequest(HttpURLConnection http, HttpServletRequest req, HttpServletResponse resp, String method)
207                         throws IOException {
208                 byte[] buffer = new byte[BUFSIZE];
209                 int len = 0, lensum = 0;
210                 // send request
211                 // Send the message to destination
212                 if (!method.equals("GET")) {
213                         try (OutputStream output = http.getOutputStream()) {
214                                 while (true) {
215                                         len = req.getInputStream().read(buffer, 0, BUFSIZE);
216                                         if (len <= 0)
217                                                 break;
218                                         lensum += len;
219                                         output.write(buffer, 0, len);
220                                 }
221                         }
222                 }
223                 LOG.debug("written " + lensum + " data out");
224                 int responseCode = ((HttpURLConnection) http).getResponseCode();
225                 // Receive answer
226                 InputStream response;
227                 if (responseCode >= 200 && responseCode < 300)
228                         response = http.getInputStream();
229                 else {
230                         response = http.getErrorStream();
231                         if (response == null)
232                                 http.getInputStream();
233                 }
234
235                 LOG.debug("ResponseCode: " + responseCode);
236                 resp.setStatus(responseCode);
237                 Map<String, List<String>> set = http.getHeaderFields();
238                 String s = "";
239                 if (set != null) {
240                         for (Map.Entry<String, List<String>> entry : set.entrySet()) {
241                                 if (entry.getKey() == null)
242                                         continue;
243                                 for (String v : entry.getValue()) {
244                                         resp.setHeader(entry.getKey(), v);
245                                         s += String.format("%s:%s;", entry.getKey(), v);
246                                 }
247
248                         }
249                 }
250                 LOG.debug("Received Headers: " + s);
251                 lensum = 0;
252                 if (response != null) {
253                         while (true) {
254                                 len = response.read(buffer, 0, BUFSIZE);
255                                 if (len <= 0)
256                                         break;
257                                 lensum += len;
258                                 resp.getOutputStream().write(buffer, 0, len);
259                         }
260                 } else
261                         LOG.debug("response is null");
262                 LOG.debug("Received " + lensum + " bytes");
263         }
264 }