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.StandardCharsets;
10 import java.security.KeyManagementException;
11 import java.security.NoSuchAlgorithmException;
12 import java.util.Enumeration;
13 import java.util.List;
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;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
29 public class MSServlet extends HttpServlet {
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;
44 * @throws NoSuchAlgorithmException
45 * @throws KeyManagementException
47 private static void setupSslTrustAll() throws NoSuchAlgorithmException, KeyManagementException {
49 sc = SSLContext.getInstance("TLSv1.2");
50 TrustManager[] trustCerts = null;
52 trustCerts = new TrustManager[] { new javax.net.ssl.X509TrustManager() {
53 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
57 public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
60 public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
65 // Init the SSLContext with a TrustManager[] and SecureRandom()
66 sc.init(null, trustCerts, new java.security.SecureRandom());
73 MyProperties.Instantiate(MyProperties.PROPFILE);
74 } catch (Exception e) {
75 LOG.error(e.getMessage());
78 TRUSTALL = MyProperties.getInstance().trustInsecure();
81 } catch (Exception e) {
82 LOG.error("error setting up SSL: " + e.getMessage());
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");
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");
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");
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");
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);
126 private void sendOffResponse(HttpServletResponse response) {
127 response.setStatus(200);// HTML/OK
128 response.setHeader("Content-Type", "text/html; charset=utf-8");
130 response.getOutputStream().write(OFFLINE_RESPONSE_BYTES);
131 } catch (IOException e) {
132 LOG.debug("problem writing offline response");
137 public String getBaseUrl(long id) {
138 return "http://mediatorsnmp.fritz.box:7070";
141 private URLConnection getConnection(HttpServletRequest req, final String method) throws IOException {
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());
151 id = Long.parseLong(uri.substring(0, uri.indexOf("/")));
152 uri = uri.substring(uri.indexOf("/"));
153 } catch (Exception err) {
154 LOG.debug(err.getMessage());
157 String surl = this.getBaseUrl(id) + uri;
158 if (query != null && query.length() > 0)
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());
167 HostnameVerifier allHostsValid = new HostnameVerifier() {
168 public boolean verify(String hostname, SSLSession session) {
172 ((HttpsURLConnection) http).setHostnameVerifier(allHostsValid);
175 http.setDoOutput(true);
176 // copy request headers
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);
187 LOG.debug("Request Headers: " + s);
190 LOG.debug("no ms id found");
196 private void handleRequest(HttpURLConnection http, HttpServletRequest req, HttpServletResponse resp, String method)
199 LOG.debug("nothing to answer");
202 byte[] buffer = new byte[BUFSIZE];
203 int len = 0, lensum = 0;
205 // Send the message to destination
206 if (!method.equals("GET")) {
207 try (OutputStream output = http.getOutputStream()) {
209 len = req.getInputStream().read(buffer, 0, BUFSIZE);
213 output.write(buffer, 0, len);
217 LOG.debug("written " + lensum + " data out");
218 int responseCode = ((HttpURLConnection) http).getResponseCode();
220 InputStream response;
221 if (responseCode >= 200 && responseCode < 300)
222 response = http.getInputStream();
224 response = http.getErrorStream();
225 if (response == null)
226 http.getInputStream();
229 LOG.debug("ResponseCode: " + responseCode);
230 resp.setStatus(responseCode);
231 Map<String, List<String>> set = http.getHeaderFields();
234 for (Map.Entry<String, List<String>> entry : set.entrySet()) {
235 if (entry.getKey() == null)
237 for (String v : entry.getValue()) {
238 resp.setHeader(entry.getKey(), v);
239 s += String.format("%s:%s;", entry.getKey(), v);
244 LOG.debug("Received Headers: " + s);
246 if (response != null) {
248 len = response.read(buffer, 0, BUFSIZE);
252 resp.getOutputStream().write(buffer, 0, len);
255 LOG.debug("response is null");
256 LOG.debug("Received " + lensum + " bytes");