diff options
author | Michael Dürre <michael.duerre@highstreet-technologies.com> | 2020-01-30 12:30:58 +0100 |
---|---|---|
committer | KAPIL SINGAL <ks220y@att.com> | 2020-01-31 20:58:11 +0000 |
commit | fb121a32b8b3431e37d2b73a63aac8055983f8f2 (patch) | |
tree | 1674d0395da57f4a92531f3d35508c58ff904f60 /sdnr/wt/apigateway/provider/src/main | |
parent | 84cf604e3f06942a62ae0478327ec6100787761e (diff) |
update apigateway
removed unused code and services
Issue-ID: SDNC-1027
Signed-off-by: Michael Dürre <michael.duerre@highstreet-technologies.com>
Change-Id: Ia126ed7fcc18331858c502409384cbc0570d6be7
Diffstat (limited to 'sdnr/wt/apigateway/provider/src/main')
10 files changed, 325 insertions, 952 deletions
diff --git a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/AaiServlet.java b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/AaiServlet.java index e73d5c668..44cad5f12 100644 --- a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/AaiServlet.java +++ b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/AaiServlet.java @@ -32,7 +32,7 @@ public class AaiServlet extends BaseServlet { */ private static final long serialVersionUID = 5946205120796162644L; private static final String OFFLINE_RESPONSE_MESSAGE = "AAI interface is offline"; - + private static boolean trustAll = false; public AaiServlet() { super(); } @@ -71,4 +71,14 @@ public class AaiServlet extends BaseServlet { return base + uri; } + + @Override + protected boolean doTrustAll() { + return trustAll; + } + + @Override + protected void trustAll(boolean trust) { + trustAll = trust; + } } diff --git a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/BaseServlet.java b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/BaseServlet.java index 06002a200..a7173df28 100644 --- a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/BaseServlet.java +++ b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/BaseServlet.java @@ -36,7 +36,6 @@ import java.util.Map; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; @@ -48,336 +47,332 @@ import org.slf4j.LoggerFactory; public abstract class BaseServlet extends HttpServlet { - /** - * - */ - private static final long serialVersionUID = 7403047480257892794L; - private static Logger LOG = LoggerFactory.getLogger(BaseServlet.class); - private static SSLContext sc; - private boolean trustAll = false; - private static TrustManager[] trustCerts = null; - private static final int BUFSIZE = 2048; + /** + * + */ + private static final long serialVersionUID = 7403047480257892794L; + private static Logger LOG = LoggerFactory.getLogger(BaseServlet.class); + private static SSLContext sc; + private static TrustManager[] trustCerts = null; + private static final int BUFSIZE = 2048; - protected abstract String getOfflineResponse(); + protected abstract String getOfflineResponse(); - protected abstract boolean isOff(); + protected abstract boolean isOff(); - protected abstract String getRemoteUrl(String uri); + protected abstract boolean doTrustAll(); + protected abstract void trustAll(boolean trust); + protected abstract String getRemoteUrl(String uri); - /** - * - * @throws NoSuchAlgorithmException - * @throws KeyManagementException - */ - private static void setupSslTrustAll(boolean trustall) throws NoSuchAlgorithmException, KeyManagementException { + /** + * + * @throws NoSuchAlgorithmException + * @throws KeyManagementException + */ + private static void setupSslTrustAll(boolean trustall) throws NoSuchAlgorithmException, KeyManagementException { - sc = SSLContext.getInstance("TLSv1.2"); - if (trustall) { - if (trustCerts == null) { - trustCerts = new TrustManager[] { new javax.net.ssl.X509TrustManager() { - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[] {}; - } + sc = SSLContext.getInstance("TLSv1.2"); + if (trustall) { + if (trustCerts == null) { + trustCerts = new TrustManager[] { new javax.net.ssl.X509TrustManager() { + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new java.security.cert.X509Certificate[] {}; + } - @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { - // do not check anything when trust all - } + @Override + public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { + // do not check anything when trust all + } - @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { - // do not check anything when trust all - } - } }; - } - } else { - if (trustCerts != null) - trustCerts = null; - } - // Init the SSLContext with a TrustManager[] and SecureRandom() - sc.init(null, trustCerts, new java.security.SecureRandom()); - } + @Override + public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { + // do not check anything when trust all + } + } }; + } + } else { + if (trustCerts != null) { + trustCerts = null; + } + } + // Init the SSLContext with a TrustManager[] and SecureRandom() + sc.init(null, trustCerts, new java.security.SecureRandom()); + } - public BaseServlet() { - try { - MyProperties.Instantiate(); - } catch (Exception e) { - LOG.error(e.getMessage()); - } - this.trysslSetup(true); - } + public BaseServlet() { + try { + MyProperties.Instantiate(); + } catch (Exception e) { + LOG.error(e.getMessage()); + } + this.trysslSetup(true); + } - private void trysslSetup() { - this.trysslSetup(false); - } + private void trysslSetup() { + this.trysslSetup(false); + } - /** - * init or deinit ssl insecure mode regarding to property - * - * @param force init independent from property - */ - private void trysslSetup(boolean force) { - // if trustall config has changed - if (force || trustAll != MyProperties.getInstance().trustInsecure()) { - // resetup ssl config - trustAll = MyProperties.getInstance().trustInsecure(); - try { - setupSslTrustAll(trustAll); - } catch (Exception e) { - LOG.error("problem setting up SSL: {}", e.getMessage()); - } - } - } + /** + * init or deinit ssl insecure mode regarding to property + * + * @param force init independent from property + */ + private void trysslSetup(boolean force) { + // if trustall config has changed + boolean trustAll = MyProperties.getInstance().trustInsecure(); + if (force || this.doTrustAll() != trustAll) { + this.trustAll(trustAll); + // resetup ssl config + try { + setupSslTrustAll(trustAll); + } catch (Exception e) { + LOG.error("problem setting up SSL: {}", e.getMessage()); + } + } + } - protected void sendOffResponse(HttpServletResponse response) { - response.setStatus(200);// HTML/OK - response.setHeader("Content-Type", "text/html; charset=utf-8"); - try { - response.getOutputStream().write(this.getOfflineResponse().getBytes(StandardCharsets.UTF_8)); - } catch (IOException e) { - LOG.debug("problem writing offline response"); - } + protected void sendOffResponse(HttpServletResponse response) { + response.setStatus(200);// HTML/OK + response.setHeader("Content-Type", "text/html; charset=utf-8"); + try { + response.getOutputStream().write(this.getOfflineResponse().getBytes(StandardCharsets.UTF_8)); + } catch (IOException e) { + LOG.debug("problem writing offline response"); + } - } + } - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - if (this.isOff()) { - this.sendOffResponse(resp); - } else { - this.trysslSetup(); - HttpURLConnection http = null; - try { - http = (HttpURLConnection) this.getConnection(req, "GET"); - } catch (IOException e) { - LOG.warn(e.getMessage()); - } - if (http != null) { - try { - this.handleRequest(http, req, resp, "GET"); - } catch (IOException e) { - LOG.warn(e.getMessage()); - } - http.disconnect(); - } - else { - this.set404Response(resp); - } - } - } + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (this.isOff()) { + this.sendOffResponse(resp); + } else { + this.trysslSetup(); + HttpURLConnection http = null; + try { + http = (HttpURLConnection) this.getConnection(req, "GET"); + } catch (IOException e) { + LOG.warn(e.getMessage()); + } + if (http != null) { + try { + this.handleRequest(http, req, resp, "GET"); + } catch (IOException e) { + LOG.warn(e.getMessage()); + } + http.disconnect(); + } + else { + this.set404Response(resp); + } + } + } - @Override - protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - if (this.isOff()) { - this.sendOffResponse(resp); - } else { - this.trysslSetup(); - HttpURLConnection http = null; - try { - http = (HttpURLConnection) this.getConnection(req, "PUT"); - } catch (IOException e) { - LOG.warn(e.getMessage()); - } - if (http != null) { - try { - this.handleRequest(http, req, resp, "PUT"); - } catch (IOException e) { - LOG.warn(e.getMessage()); - } - http.disconnect(); - } - else { - this.set404Response(resp); - } - } - } + @Override + protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (this.isOff()) { + this.sendOffResponse(resp); + } else { + this.trysslSetup(); + HttpURLConnection http = null; + try { + http = (HttpURLConnection) this.getConnection(req, "PUT"); + } catch (IOException e) { + LOG.warn(e.getMessage()); + } + if (http != null) { + try { + this.handleRequest(http, req, resp, "PUT"); + } catch (IOException e) { + LOG.warn(e.getMessage()); + } + http.disconnect(); + } + else { + this.set404Response(resp); + } + } + } - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - if (this.isOff()) { - this.sendOffResponse(resp); - } else { - this.trysslSetup(); - HttpURLConnection http = null; - try { - http = (HttpURLConnection) this.getConnection(req, "POST"); - } catch (IOException e) { - LOG.warn(e.getMessage()); - } - if (http != null) { - try { - this.handleRequest(http, req, resp, "POST"); - } catch (IOException e) { - LOG.warn(e.getMessage()); - } - http.disconnect(); - } - else { - this.set404Response(resp); - } - } - } + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (this.isOff()) { + this.sendOffResponse(resp); + } else { + this.trysslSetup(); + HttpURLConnection http = null; + try { + http = (HttpURLConnection) this.getConnection(req, "POST"); + } catch (IOException e) { + LOG.warn(e.getMessage()); + } + if (http != null) { + try { + this.handleRequest(http, req, resp, "POST"); + } catch (IOException e) { + LOG.warn(e.getMessage()); + } + http.disconnect(); + } + else { + this.set404Response(resp); + } + } + } - @Override - protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - if (this.isOff()) { - this.sendOffResponse(resp); - } else { - this.trysslSetup(); - HttpURLConnection http = null; - try { - http = (HttpURLConnection) this.getConnection(req, "DELETE"); - } catch (IOException e) { - LOG.warn(e.getMessage()); - } - if (http != null) { - try { - this.handleRequest(http, req, resp, "DELETE"); - } catch (IOException e) { - LOG.warn(e.getMessage()); - } - http.disconnect(); - } - else { - this.set404Response(resp); - } - } - } + @Override + protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (this.isOff()) { + this.sendOffResponse(resp); + } else { + this.trysslSetup(); + HttpURLConnection http = null; + try { + http = (HttpURLConnection) this.getConnection(req, "DELETE"); + } catch (IOException e) { + LOG.warn(e.getMessage()); + } + if (http != null) { + try { + this.handleRequest(http, req, resp, "DELETE"); + } catch (IOException e) { + LOG.warn(e.getMessage()); + } + http.disconnect(); + } + else { + this.set404Response(resp); + } + } + } - private void set404Response(HttpServletResponse resp) { - resp.setStatus(404); - } + private void set404Response(HttpServletResponse resp) { + resp.setStatus(404); + } - private URLConnection getConnection(HttpServletRequest req, final String method) throws IOException { + private URLConnection getConnection(HttpServletRequest req, final String method) throws IOException { - LOG.debug("{} Request to {}", method,req.getRequestURL()); - String surl = this.getRemoteUrl(req.getRequestURI()); - if(method=="GET") { - Enumeration<String> params = req.getParameterNames(); - if(params!=null) { - String param; - if(params.hasMoreElements()) { - param=params.nextElement(); - surl+="?"+param+"="+req.getParameter(param); - } - while(params.hasMoreElements()) { - param=params.nextElement(); - surl+="&"+param+"="+req.getParameter(param); - } - } - } - LOG.debug("RemoteURL: {}", surl); - if(surl==null) { - return null; - } - URL url = new URL(surl); - URLConnection http = url.openConnection(); - ((HttpURLConnection) http).setRequestMethod(method); - if (url.toString().startsWith("https")) { - ((HttpsURLConnection) http).setSSLSocketFactory(sc.getSocketFactory()); - if (trustAll) { - HostnameVerifier allHostsValid = new HostnameVerifier() { + LOG.debug("{} Request to {}", method,req.getRequestURL()); + String surl = this.getRemoteUrl(req.getRequestURI()); + if("GET".equals(method)) { + Enumeration<?> params = req.getParameterNames(); + if(params!=null) { + String param; + if(params.hasMoreElements()) { + param=(String)params.nextElement(); + surl+="?"+param+"="+req.getParameter(param); + } + while(params.hasMoreElements()) { + param=(String)params.nextElement(); + surl+="&"+param+"="+req.getParameter(param); + } + } + } + LOG.debug("RemoteURL: {}", surl); + if(surl==null) { + return null; + } + URL url = new URL(surl); + URLConnection http = url.openConnection(); + ((HttpURLConnection) http).setRequestMethod(method); + if (url.toString().startsWith("https")) { + ((HttpsURLConnection) http).setSSLSocketFactory(sc.getSocketFactory()); + if (this.doTrustAll()) { + HostnameVerifier allHostsValid = (hostname, session) -> true; + ((HttpsURLConnection) http).setHostnameVerifier(allHostsValid); + } + } + http.setDoOutput(true); + // copy request headers + String s = ""; + Enumeration<?> headers = req.getHeaderNames(); + while (headers.hasMoreElements()) { + String h = (String)headers.nextElement(); + String v = req.getHeader(h); + if (h != null && h.equals("Host")) { + v = url.getAuthority(); + } + s += String.format("%s:%s;", h, v); + http.setRequestProperty(h, v); + } + LOG.debug("Request Headers: {}", s); + return http; + } - @Override - public boolean verify(String hostname, SSLSession session) { - // do not verify host if trust all - return true; - } - }; - ((HttpsURLConnection) http).setHostnameVerifier(allHostsValid); - } - } - http.setDoOutput(true); - // copy request headers - String s = ""; - Enumeration<String> headers = req.getHeaderNames(); - while (headers.hasMoreElements()) { - String h = headers.nextElement(); - String v = req.getHeader(h); - if (h != null && h.equals("Host")) { - v = url.getAuthority(); - } - s += String.format("%s:%s;", h, v); - http.setRequestProperty(h, v); - } - LOG.debug("Request Headers: {}", s); - return http; - } + private void handleRequest(HttpURLConnection http, HttpServletRequest req, HttpServletResponse resp, String method) + throws IOException { + byte[] buffer = new byte[BUFSIZE]; + int len = 0, lensum = 0; + // send request + // Send the message to destination + OutputStream output = null; + if (!method.equals("GET")) { + try { + output = http.getOutputStream(); + } catch (Exception e) { + LOG.debug("problem reading output stream: {}", e.getMessage()); + } + } + if (output != null) { + while (true) { + len = req.getInputStream().read(buffer, 0, BUFSIZE); + if (len <= 0) { + break; + } + lensum += len; + output.write(buffer, 0, len); + } + } + LOG.debug("written {} data out", lensum); + int responseCode = http.getResponseCode(); + // Receive answer + InputStream response; + if (responseCode >= 200 && responseCode < 300) { + response = http.getInputStream(); + } else { + response = http.getErrorStream(); + if (response == null) { + http.getInputStream(); + } + } - private void handleRequest(HttpURLConnection http, HttpServletRequest req, HttpServletResponse resp, String method) - throws IOException { - byte[] buffer = new byte[BUFSIZE]; - int len = 0, lensum = 0; - // send request - // Send the message to destination - OutputStream output = null; - if (!method.equals("GET")) { - try { - output = http.getOutputStream(); - } catch (Exception e) { - LOG.debug("problem reading output stream: {}", e.getMessage()); - } - } - if (output != null) { - while (true) { - len = req.getInputStream().read(buffer, 0, BUFSIZE); - if (len <= 0) { - break; - } - lensum += len; - output.write(buffer, 0, len); - } - } - LOG.debug("written {} data out", lensum); - int responseCode = http.getResponseCode(); - // Receive answer - InputStream response; - if (responseCode >= 200 && responseCode < 300) { - response = http.getInputStream(); - } else { - response = http.getErrorStream(); - if (response == null) { - http.getInputStream(); - } - } + LOG.debug("ResponseCode: {}", responseCode); + resp.setStatus(responseCode); + Map<String, List<String>> set = http.getHeaderFields(); + String s = ""; + if (set != null) { + for (Map.Entry<String, List<String>> entry : set.entrySet()) { + if (entry.getKey() == null) { + continue; + } + for (String v : entry.getValue()) { + resp.setHeader(entry.getKey(), v); + s += String.format("%s:%s;", entry.getKey(), v); + } + if (MyProperties.getInstance().corsEnabled()) { + resp.setHeader("Access-Control-Allow-Origin", "*"); + // resp.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE"); + resp.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); + } - LOG.debug("ResponseCode: {}", responseCode); - resp.setStatus(responseCode); - Map<String, List<String>> set = http.getHeaderFields(); - String s = ""; - if (set != null) { - for (Map.Entry<String, List<String>> entry : set.entrySet()) { - if (entry.getKey() == null) { - continue; - } - for (String v : entry.getValue()) { - resp.setHeader(entry.getKey(), v); - s += String.format("%s:%s;", entry.getKey(), v); - } - if (MyProperties.getInstance().corsEnabled()) { - resp.setHeader("Access-Control-Allow-Origin", "*"); - // resp.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE"); - resp.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); - } - - } - } - LOG.debug("Received Headers: {}", s); - lensum = 0; - if (response != null) { - while (true) { - len = response.read(buffer, 0, BUFSIZE); - if (len <= 0) { - break; - } - lensum += len; - resp.getOutputStream().write(buffer, 0, len); - } - } else { - LOG.debug("response is null"); - } - LOG.debug("Received {} bytes", lensum); - } + } + } + LOG.debug("Received Headers: {}", s); + lensum = 0; + if (response != null) { + while (true) { + len = response.read(buffer, 0, BUFSIZE); + if (len <= 0) { + break; + } + lensum += len; + resp.getOutputStream().write(buffer, 0, len); + } + } else { + LOG.debug("response is null"); + } + LOG.debug("Received {} bytes", lensum); + } } diff --git a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/EsServlet.java b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/EsServlet.java index 2b5488498..f08a7fffa 100644 --- a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/EsServlet.java +++ b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/EsServlet.java @@ -21,11 +21,6 @@ package org.onap.ccsdk.features.sdnr.wt.apigateway; import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -35,10 +30,6 @@ import org.slf4j.LoggerFactory; public class EsServlet extends BaseServlet { - public interface IRequestCallback{ - - void onRequest(String uri,String method); - } /** * */ @@ -46,43 +37,12 @@ public class EsServlet extends BaseServlet { private static final String OFFLINE_RESPONSE_MESSAGE = "Database interface is offline"; private static Logger LOG = LoggerFactory.getLogger(EsServlet.class); - private static final Map<String,List<IRequestCallback>> requestCallbacks=new HashMap<String,List<IRequestCallback>>(); - - public static void registerRequestCallback(String uri,IRequestCallback callback) { - List<IRequestCallback> list=requestCallbacks.getOrDefault(uri, new ArrayList<IRequestCallback>()); - if(!list.contains(callback)) { - list.add(callback); - } - requestCallbacks.put(uri, list); - } - public static void unregisterRequestCallback(String uri,IRequestCallback callback) { - List<IRequestCallback> list=requestCallbacks.getOrDefault(uri, new ArrayList<IRequestCallback>()); - if(list.contains(callback)) { - list.remove(callback); - } - } - + private static boolean trustAll = false; public EsServlet() { super(); } - private void handleCallbacks(String uri,String method) { - - LOG.debug("try to find callbacks for uri {}",uri); - for(Entry<String,List<IRequestCallback>> entry:requestCallbacks.entrySet()) { - if(uri.contains(entry.getKey())) { - List<IRequestCallback> cblist = entry.getValue(); - if(cblist!=null && cblist.size()>0) { - LOG.debug("found at least one"); - for(IRequestCallback cb :cblist) { - cb.onRequest(uri, method); - } - } - } - - } - } @Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (MyProperties.getInstance().corsEnabled()) { @@ -113,21 +73,25 @@ public class EsServlet extends BaseServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); - this.handleCallbacks(req.getRequestURI(),"GET"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); - this.handleCallbacks(req.getRequestURI(),"POST"); } @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPut(req, resp); - this.handleCallbacks(req.getRequestURI(),"PUT"); } @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doDelete(req, resp); - this.handleCallbacks(req.getRequestURI(),"DELETE"); + } + @Override + protected boolean doTrustAll() { + return trustAll; + } + @Override + protected void trustAll(boolean trust) { + trustAll = trust; } } diff --git a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/MsServlet.java b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/MsServlet.java deleted file mode 100644 index aee7a3b09..000000000 --- a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/MsServlet.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP : CCSDK.apps.sdnr.wt.apigateway - * ================================================================================ - * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. - * All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.ccsdk.features.sdnr.wt.apigateway; - -import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.onap.ccsdk.features.sdnr.wt.apigateway.EsServlet.IRequestCallback; -import org.onap.ccsdk.features.sdnr.wt.apigateway.database.DatabaseEntryProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MsServlet extends BaseServlet { - - /** - * - */ - private static Logger LOG = LoggerFactory.getLogger(MsServlet.class); - private static final long serialVersionUID = -5361461082028405171L; - private static final String OFFLINE_RESPONSE_MESSAGE = "MediatorServer interface is offline"; - private static final String DATABASE_REQUEST_URI_REGEX = "/mediator-server/mediator-server"; - private final DatabaseEntryProvider entryProvider; - private boolean isSecure; - public void setIsSecure(boolean secure) { - if(this.isSecure!=secure) { - this.isSecure=secure; - this.entryProvider.setBaseUrl(this.getDBBaseUrl()); - } - } - public MsServlet() { - super(); - this.entryProvider = new DatabaseEntryProvider(this.getDBBaseUrl(),60); - EsServlet.registerRequestCallback(DATABASE_REQUEST_URI_REGEX, this.dbRequestCallback); - } - - private String getDBBaseUrl() { - return MyProperties.getInstance().getEsBaseUrl(); - } - - private final IRequestCallback dbRequestCallback = new IRequestCallback() { - - @Override - public void onRequest(String uri, String method) { - if(method=="POST"|| method=="PUT" || method=="DELETE") { - LOG.debug("found mediator related request. trigger update of local entries"); - MsServlet.this.entryProvider.triggerReloadSync(); - } - - } - }; - protected DatabaseEntryProvider getEntryProvider() { - return this.entryProvider; - } - @Override - protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - resp.setStatus(200); - } - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - super.doGet(req, resp); - this.isSecure=req.getScheme().equals("https"); - } - @Override - protected String getOfflineResponse() { - return OFFLINE_RESPONSE_MESSAGE; - } - - @Override - protected boolean isOff() { - return false; - } - - @Override - protected String getRemoteUrl(String uri) { - String dbServerId = "0"; - if (uri == null) - uri = ""; - if (uri.length() > 0) { - uri = uri.substring("/ms/".length()); - int idx= uri.indexOf("/"); - dbServerId = uri.substring(0,idx); - uri=uri.substring(idx); - } - LOG.debug("request for ms server with id={}",dbServerId); - String url= this.getBaseUrl(dbServerId) + uri; - LOG.debug("dest-url: {}",url); - return url; - } - - protected String getBaseUrl(String dbServerId) { - return this.entryProvider.getHostUrl(dbServerId); - } -} diff --git a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/DatabaseEntryProvider.java b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/DatabaseEntryProvider.java deleted file mode 100644 index b467e27a0..000000000 --- a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/DatabaseEntryProvider.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP : CCSDK.apps.sdnr.wt.apigateway - * ================================================================================ - * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. - * All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.ccsdk.features.sdnr.wt.apigateway.database; - -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - - -public class DatabaseEntryProvider implements AutoCloseable { - - private final DatabaseHttpClient httpClient; - private int refreshInterval; - private final Map<String, MediatorServerInfo> entries; - private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); - private boolean isRunning; - - protected DatabaseEntryProvider (DatabaseHttpClient httpClient,int refreshInterval) { - this.httpClient = httpClient; - this.refreshInterval = refreshInterval; - this.entries = new HashMap<String, MediatorServerInfo>(); - this.isRunning = false; - this.scheduler.scheduleAtFixedRate(onTick, this.refreshInterval, this.refreshInterval, TimeUnit.SECONDS); - } - public DatabaseEntryProvider(String dbBaseUri, int refreshInterval) { - - this.httpClient = new DatabaseHttpClient(dbBaseUri, false); - this.refreshInterval = refreshInterval; - this.entries = new HashMap<String, MediatorServerInfo>(); - this.isRunning = false; - this.scheduler.scheduleAtFixedRate(onTick, this.refreshInterval, this.refreshInterval, TimeUnit.SECONDS); - } - - private final Runnable onTick = new Runnable() { - - @Override - public void run() { - isRunning = true; - Map<String, MediatorServerInfo> map = DatabaseEntryProvider.this.httpClient.requestEntries(); - DatabaseEntryProvider.this.entries.putAll(map); - isRunning = false; - } - - }; - - public String getHostUrl(String dbServerId) { - MediatorServerInfo info = this.entries.getOrDefault(dbServerId, null); - return info == null ? null : info.getHost(); - } - - @Override - public void close() throws Exception { - this.scheduler.shutdown(); - } - - public boolean triggerReloadSync() { - new Thread(onTick).start(); - int i=20; - while(isRunning && i-->0) { - try { - Thread.sleep(500); - } catch (InterruptedException e) { - Thread.interrupted(); - } - } - return i>0; - } - - public void setEntries(Map<String, MediatorServerInfo> e) { - - this.entries.clear(); - this.entries.putAll(e); - } - public String printEntries() { - String s=""; - if(this.entries==null || this.entries.size()<=0) { - return "empty"; - } - for(Entry<String, MediatorServerInfo> entry:this.entries.entrySet()) { - s+=String.format("%s:%s", entry.getKey(),entry.getValue().toString()+"\n"); - } - return s; - } - public void setBaseUrl(String baseUrl) { - this.httpClient.setBaseUrl(baseUrl); - } - -} diff --git a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/DatabaseHttpClient.java b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/DatabaseHttpClient.java deleted file mode 100644 index d0f575362..000000000 --- a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/DatabaseHttpClient.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP : CCSDK.apps.sdnr.wt.apigateway - * ================================================================================ - * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. - * All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.ccsdk.features.sdnr.wt.apigateway.database; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.onap.ccsdk.features.sdnr.wt.apigateway.database.http.BaseHTTPClient; -import org.onap.ccsdk.features.sdnr.wt.apigateway.database.http.BaseHTTPResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DatabaseHttpClient extends BaseHTTPClient { - - private static Logger LOG = LoggerFactory.getLogger(DatabaseHttpClient.class); - private static final String URI = "/mediator-server/mediator-server/_search"; - private final Map<String, String> headers; - - public DatabaseHttpClient(String base, boolean trustAllCerts) { - super(base, trustAllCerts); - this.headers = this.getHeaders(); - } - - private Map<String, String> getHeaders() { - Map<String, String> h = new HashMap<String, String>(); - h.put("Content-Type", "application/json"); - return h; - } - - public Map<String, MediatorServerInfo> requestEntries() { - Map<String, MediatorServerInfo> entries = new HashMap<String, MediatorServerInfo>(); - BaseHTTPResponse response = null; - try { - response = this.sendRequest(URI, "GET", (String) null, this.headers); - } catch (IOException e) { - LOG.warn("problem reading db entries of mediator server: {}", e.getMessage()); - } - if (response != null && response.code == BaseHTTPResponse.CODE200) { - try { - JSONObject o = new JSONObject(response.body); - if (o.has("hits")) { - JSONObject hits = o.getJSONObject("hits"); - if (hits.has("hits")) { - JSONArray hitsarray = hits.getJSONArray("hits"); - if (hitsarray.length() > 0) { - for (int i = 0; i < hitsarray.length(); i++) { - JSONObject entry = hitsarray.getJSONObject(i); - entries.put(entry.getString("_id"), - new MediatorServerInfo(entry.getJSONObject("_source").getString("name"), - entry.getJSONObject("_source").getString("url"))); - } - } - - } - } - } catch (Exception e) { - LOG.warn("problem parsing response: {} | e={}", response, e.getMessage()); - } - } - return entries; - } - - -} diff --git a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/MediatorServerInfo.java b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/MediatorServerInfo.java deleted file mode 100644 index a90b90173..000000000 --- a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/MediatorServerInfo.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP : CCSDK.apps.sdnr.wt.apigateway - * ================================================================================ - * Copyright (C) 2018 highstreet technologies GmbH Intellectual Property. - * All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.ccsdk.features.sdnr.wt.apigateway.database; - -public class MediatorServerInfo { - - private final String name; - private final String url; - public MediatorServerInfo(String name,String url) { - this.name = name; - if(url.endsWith("/")) { - url=url.substring(0,url.length()-1); - } - this.url = url; - } - public String getName() { - return this.name; - } - public String getHost() { - return this.url; - } - - -} diff --git a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/http/BaseHTTPClient.java b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/http/BaseHTTPClient.java deleted file mode 100644 index 9c89eeff3..000000000 --- a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/http/BaseHTTPClient.java +++ /dev/null @@ -1,200 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================================== - * ONAP : ccsdk feature sdnr wt - * ================================================================================================= - * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. - * ================================================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - * ============LICENSE_END========================================================================== - ******************************************************************************/ -package org.onap.ccsdk.features.sdnr.wt.apigateway.database.http; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLConnection; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.util.Base64; -import java.util.Map; -import javax.annotation.Nonnull; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.KeyManager; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class BaseHTTPClient { - - private static Logger LOG = LoggerFactory.getLogger(BaseHTTPClient.class); - private static final int BUFSIZE = 1024; - private static final Charset CHARSET = StandardCharsets.UTF_8; - private static final String SSLCONTEXT = "TLSv1.2"; - private static final int DEFAULT_HTTP_TIMEOUT_MS = 30000; // in ms - - private final boolean trustAll; - private String baseUrl; - - private int timeout = DEFAULT_HTTP_TIMEOUT_MS; - private SSLContext sc = null; - - public BaseHTTPClient(String base) { - this(base, false); - } - - public void setBaseUrl(String baseUrl) { - this.baseUrl = baseUrl; - try { - sc = setupSsl(trustAll); - } catch (KeyManagementException | NoSuchAlgorithmException e) { - LOG.warn("problem ssl setup: " + e.getMessage()); - } - } - - public BaseHTTPClient(String base, boolean trustAllCerts) { - this.baseUrl = base; - this.trustAll = trustAllCerts; - try { - sc = setupSsl(trustAll); - } catch (KeyManagementException | NoSuchAlgorithmException e) { - LOG.warn("problem ssl setup: " + e.getMessage()); - } - } - - protected @Nonnull BaseHTTPResponse sendRequest(String uri, String method, String body, Map<String, String> headers) - throws IOException { - return this.sendRequest(uri, method, body != null ? body.getBytes(CHARSET) : null, headers); - } - - protected @Nonnull BaseHTTPResponse sendRequest(String uri, String method, byte[] body, Map<String, String> headers) - throws IOException { - if (uri == null) { - uri = ""; - } - String surl = this.baseUrl; - if (!surl.endsWith("/") && uri.length() > 0) { - surl += "/"; - } - if (uri.startsWith("/")) { - uri = uri.substring(1); - } - surl += uri; - LOG.debug("try to send request with url=" + this.baseUrl + uri + " as method=" + method); - LOG.trace("body:" + (body == null ? "null" : new String(body, CHARSET))); - URL url = new URL(surl); - URLConnection http = url.openConnection(); - http.setConnectTimeout(this.timeout); - if (surl.toString().startsWith("https")) { - if (sc != null) { - ((HttpsURLConnection) http).setSSLSocketFactory(sc.getSocketFactory()); - if (trustAll) { - LOG.debug("trusting all certs"); - HostnameVerifier allHostsValid = (hostname, session) -> true; - ((HttpsURLConnection) http).setHostnameVerifier(allHostsValid); - } - } else // Should never happen - { - LOG.warn("No SSL context available"); - return new BaseHTTPResponse(-1, ""); - } - } - ((HttpURLConnection) http).setRequestMethod(method); - http.setDoOutput(true); - if (headers != null && headers.size() > 0) { - for (String key : headers.keySet()) { - http.setRequestProperty(key, headers.get(key)); - LOG.trace("set http header " + key + ": " + headers.get(key)); - } - } - byte[] buffer = new byte[BUFSIZE]; - int len = 0, lensum = 0; - // send request - // Send the message to destination - if (!method.equals("GET") && body != null && body.length > 0) { - try (OutputStream output = http.getOutputStream()) { - output.write(body); - } - } - // Receive answer - int responseCode = ((HttpURLConnection) http).getResponseCode(); - String sresponse = ""; - InputStream response = null; - try { - if (responseCode >= 200 && responseCode < 300) { - response = http.getInputStream(); - } else { - response = ((HttpURLConnection) http).getErrorStream(); - if (response == null) { - response = http.getInputStream(); - } - } - if (response != null) { - while (true) { - len = response.read(buffer, 0, BUFSIZE); - if (len <= 0) { - break; - } - lensum += len; - sresponse += new String(buffer, 0, len, CHARSET); - } - } else { - LOG.debug("response is null"); - } - } catch (Exception e) { - LOG.debug("No response. ", e); - } finally { - if (response != null) { - response.close(); - } - } - LOG.debug("ResponseCode: " + responseCode); - LOG.trace("Response (len:{}): {}", String.valueOf(lensum), sresponse); - return new BaseHTTPResponse(responseCode, sresponse); - } - - public static SSLContext setupSsl(boolean trustall) throws KeyManagementException, NoSuchAlgorithmException { - - SSLContext sc = SSLContext.getInstance(SSLCONTEXT); - TrustManager[] trustCerts = null; - if (trustall) { - trustCerts = new TrustManager[] { new javax.net.ssl.X509TrustManager() { - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; - } - - @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { - } - - @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { - } - } }; - - } - KeyManager[] kms = null; - // Init the SSLContext with a TrustManager[] and SecureRandom() - sc.init(kms, trustCerts, new java.security.SecureRandom()); - return sc; - } - - public static String getAuthorizationHeaderValue(String username, String password) { - return "Basic " + new String(Base64.getEncoder().encode((username + ":" + password).getBytes())); - } - -} diff --git a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/http/BaseHTTPResponse.java b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/http/BaseHTTPResponse.java deleted file mode 100644 index 60d0a3638..000000000 --- a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/http/BaseHTTPResponse.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================================== - * ONAP : ccsdk feature sdnr wt - * ================================================================================================= - * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. - * ================================================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - * ============LICENSE_END========================================================================== - ******************************************************************************/ -package org.onap.ccsdk.features.sdnr.wt.apigateway.database.http; - -public class BaseHTTPResponse { - - public static final int CODE404 = 404; - public static final int CODE200 = 200; - public static final BaseHTTPResponse UNKNOWN = new BaseHTTPResponse(-1, ""); - public final int code; - public final String body; - - public BaseHTTPResponse(int code,String body) - { - this.code=code; - this.body=body; - } - - @Override - public String toString() { - return "BaseHTTPResponse [code=" + code + ", body=" + body + "]"; - } -} diff --git a/sdnr/wt/apigateway/provider/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/sdnr/wt/apigateway/provider/src/main/resources/org/opendaylight/blueprint/blueprint.xml index 2bfb1aa84..8184d7d11 100644 --- a/sdnr/wt/apigateway/provider/src/main/resources/OSGI-INF/blueprint/blueprint.xml +++ b/sdnr/wt/apigateway/provider/src/main/resources/org/opendaylight/blueprint/blueprint.xml @@ -24,13 +24,4 @@ xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs"> </service-properties> </service> - <bean id="msServlet" - class="org.onap.ccsdk.features.sdnr.wt.apigateway.MsServlet"> - </bean> - - <service interface="javax.servlet.http.HttpServlet" ref="msServlet"> - <service-properties> - <entry key="alias" value="/ms" /> - </service-properties> - </service> </blueprint> |