1 package com.highstreet.technologies.apigateway;
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.OutputStream;
6 import java.net.HttpURLConnection;
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;
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;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
30 public class EsServlet extends HttpServlet {
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;
45 * @throws NoSuchAlgorithmException
46 * @throws KeyManagementException
48 private static void setupSslTrustAll() throws NoSuchAlgorithmException, KeyManagementException {
50 sc = SSLContext.getInstance("TLSv1.2");
51 TrustManager[] trustCerts = null;
53 trustCerts = new TrustManager[] { new javax.net.ssl.X509TrustManager() {
54 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
58 public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
61 public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
66 // Init the SSLContext with a TrustManager[] and SecureRandom()
67 sc.init(null, trustCerts, new java.security.SecureRandom());
74 MyProperties.Instantiate(MyProperties.PROPFILE);
75 } catch (Exception e) {
76 LOG.error(e.getMessage());
79 TRUSTALL = MyProperties.getInstance().trustInsecure();
82 } catch (Exception e) {
83 LOG.error("error setting up SSL: " + e.getMessage());
88 protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
89 if (MyProperties.getInstance().isEsOff()) {
90 this.sendOffResponse(resp);
92 HttpURLConnection http = (HttpURLConnection) this.getConnection(req, "PUT");
93 this.handleRequest(http, req, resp, "PUT");
99 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
100 if (MyProperties.getInstance().isEsOff()) {
101 this.sendOffResponse(resp);
103 HttpURLConnection http = (HttpURLConnection) this.getConnection(req, "GET");
104 this.handleRequest(http, req, resp, "GET");
110 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
111 if (MyProperties.getInstance().isEsOff()) {
112 this.sendOffResponse(resp);
114 HttpURLConnection http = (HttpURLConnection) this.getConnection(req, "POST");
115 this.handleRequest(http, req, resp, "POST");
121 protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
122 if (MyProperties.getInstance().isEsOff()) {
123 this.sendOffResponse(resp);
125 HttpURLConnection http = (HttpURLConnection) this.getConnection(req, "DELETE");
126 this.handleRequest(http, req, resp, "DELETE");
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");
139 super.doOptions(req, resp);
142 private void sendOffResponse(HttpServletResponse response) {
143 response.setStatus(200);// HTML/OK
144 response.setHeader("Content-Type", "text/html; charset=utf-8");
146 response.getOutputStream().write(OFFLINE_RESPONSE_BYTES);
147 } catch (IOException e) {
148 LOG.debug("problem writing offline response");
153 private URLConnection getConnection(HttpServletRequest req, final String method) throws IOException {
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());
170 HostnameVerifier allHostsValid = new HostnameVerifier() {
171 public boolean verify(String hostname, SSLSession session) {
175 ((HttpsURLConnection) http).setHostnameVerifier(allHostsValid);
178 http.setDoOutput(true);
179 // copy request headers
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);
190 LOG.debug("Request Headers: " + s);
194 private void handleRequest(HttpURLConnection http, HttpServletRequest req, HttpServletResponse resp, String method)
196 byte[] buffer = new byte[BUFSIZE];
197 int len = 0, lensum = 0;
199 // Send the message to destination
200 if (!method.equals("GET")) {
201 try (OutputStream output = http.getOutputStream()) {
203 len = req.getInputStream().read(buffer, 0, BUFSIZE);
207 output.write(buffer, 0, len);
211 LOG.debug("written " + lensum + " data out");
212 int responseCode = ((HttpURLConnection) http).getResponseCode();
214 InputStream response;
215 if (responseCode >= 200 && responseCode < 300)
216 response = http.getInputStream();
218 response = http.getErrorStream();
219 if (response == null)
220 http.getInputStream();
223 LOG.debug("ResponseCode: " + responseCode);
224 resp.setStatus(responseCode);
225 Map<String, List<String>> set = http.getHeaderFields();
228 for (Map.Entry<String, List<String>> entry : set.entrySet()) {
229 if (entry.getKey() == null)
231 for (String v : entry.getValue()) {
232 resp.setHeader(entry.getKey(), v);
233 s += String.format("%s:%s;", entry.getKey(), v);
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");
243 LOG.debug("Received Headers: " + s);
245 if (response != null) {
247 len = response.read(buffer, 0, BUFSIZE);
251 resp.getOutputStream().write(buffer, 0, len);
254 LOG.debug("response is null");
255 LOG.debug("Received " + lensum + " bytes");