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 | |
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')
15 files changed, 325 insertions, 1454 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> diff --git a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestDatabaseHttpClient.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestDatabaseHttpClient.java deleted file mode 100644 index 791e9bad0..000000000 --- a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestDatabaseHttpClient.java +++ /dev/null @@ -1,137 +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.test; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.onap.ccsdk.features.sdnr.wt.apigateway.database.DatabaseEntryProvider; -import org.onap.ccsdk.features.sdnr.wt.apigateway.database.DatabaseHttpClient; -import org.onap.ccsdk.features.sdnr.wt.apigateway.database.MediatorServerInfo; -import org.onap.ccsdk.features.sdnr.wt.apigateway.database.http.BaseHTTPResponse; - -public class TestDatabaseHttpClient { - - private static final String ID_1="AWwscPepjf5-TrAFEdUD"; - private static final String HOSTNAME_1="http://192.168.178.89:7070"; - private static final String NAME_1="internal mediatorserver"; - private static final String ID_2="AWwscSCWjf5-TrAFEdUE"; - private static final String HOSTNAME_2="http://192.168.178.89:7071"; - private static final String NAME_2="internal mediatorserver2"; - private static final String ID_3="AWwscSCWjf5-TrAFEdsE"; - private static final String HOSTNAME_3="http://192.168.178.88:7371"; - private static final String NAME_3="test mediatorserver2"; - - private static final String RESPONSE_VALID="{\n" + - "\"took\": 3,\n" + - "\"timed_out\": false,\n" + - "\"_shards\": {\n" + - "\"total\": 5,\n" + - "\"successful\": 5,\n" + - "\"failed\": 0\n" + - "},\n" + - "\"hits\": {\n" + - "\"total\": 2,\n" + - "\"max_score\": 1,\n" + - "\"hits\": [\n" + - "{\n" + - "\"_index\": \"mwtn_v1\",\n" + - "\"_type\": \"mediator-server\",\n" + - "\"_id\": \"AWwscPepjf5-TrAFEdUD\",\n" + - "\"_score\": 1,\n" + - "\"_source\": {\n" + - "\"name\": \"internal mediatorserver\",\n" + - "\"url\": \"http://192.168.178.89:7070\"\n" + - "}\n" + - "}\n" + - ",\n" + - "{\n" + - "\"_index\": \"mwtn_v1\",\n" + - "\"_type\": \"mediator-server\",\n" + - "\"_id\": \"AWwscSCWjf5-TrAFEdUE\",\n" + - "\"_score\": 1,\n" + - "\"_source\": {\n" + - "\"name\": \"internal mediatorserver2\",\n" + - "\"url\": \"http://192.168.178.89:7071\"\n" + - "}\n" + - "}\n" + - "]\n" + - "}\n" + - "}"; - - private class PublicDatabaseHttpClient extends DatabaseHttpClient{ - - public PublicDatabaseHttpClient(String base, boolean trustAllCerts) { - super(base, trustAllCerts); - } - @Override - public BaseHTTPResponse sendRequest(String uri, String method, String body, Map<String, String> headers) { - return new BaseHTTPResponse(200, RESPONSE_VALID); - } - } - public class PublicDatabaseEntryProvider extends DatabaseEntryProvider { - - protected PublicDatabaseEntryProvider() { - super(new PublicDatabaseHttpClient("http://localhost/",false), 60); - } - - } - @Test - public void test() { - - final PublicDatabaseHttpClient client = new PublicDatabaseHttpClient("http://localhost/",false); - Map<String, MediatorServerInfo> entries = client.requestEntries(); - assertEquals("result size is not correct",2,entries.size()); - assertEquals("hostname 1 is not correct",HOSTNAME_1,entries.get(ID_1).getHost()); - assertEquals("name 1 is not correct",NAME_1,entries.get(ID_1).getName()); - assertEquals("hostname 2 is not correct",HOSTNAME_2,entries.get(ID_2).getHost()); - assertEquals("name 2 is not correct",NAME_2,entries.get(ID_2).getName()); - } - @Test - public void test2() { - final PublicDatabaseEntryProvider provider = new PublicDatabaseEntryProvider(); - boolean reloaded = provider.triggerReloadSync(); - assertTrue("data were not reloaded",reloaded); - try { - Thread.sleep(1500); - } catch (InterruptedException e) { - Thread.interrupted(); - } - - System.out.println(provider.printEntries()); - assertEquals("provider has not loaded data",HOSTNAME_1,provider.getHostUrl(ID_1)); - assertEquals("provider has not loaded data",HOSTNAME_2,provider.getHostUrl(ID_2)); - Map<String, MediatorServerInfo> entries2 = new HashMap<String,MediatorServerInfo>(); - entries2.put(ID_3, new MediatorServerInfo(NAME_3, HOSTNAME_3)); - provider.setEntries(entries2); - assertEquals("provider has not loaded data",HOSTNAME_3,provider.getHostUrl(ID_3)); - try { - provider.close(); - } catch (Exception e) { - - } - - - } -} diff --git a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestHttpClient.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestHttpClient.java deleted file mode 100644 index 18e84853a..000000000 --- a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestHttpClient.java +++ /dev/null @@ -1,71 +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.test; - -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.ccsdk.features.sdnr.wt.apigateway.database.http.BaseHTTPClient; -import org.onap.ccsdk.features.sdnr.wt.apigateway.test.helper.HelpServletBase; - -public class TestHttpClient { - - private static final int PORT =40010; - private static final String BASEURI = "/test"; - - private class TestBaseHTTPClient extends BaseHTTPClient { - public TestBaseHTTPClient() { - super(String.format("http://localhost:%s%s",PORT,BASEURI)); - } - public void doTest() { - String[] methods=new String[] {"GET","POST","PUT","DELETE"}; - Map<String, String> headers=new HashMap<String,String>(); - headers.put("Content-Type","application/json"); - headers.put("Authorization",BaseHTTPClient.getAuthorizationHeaderValue("admin","admin")); - for(String method:methods) { - try { - this.sendRequest(String.format("%s%s", BASEURI,"/abc"), method, "abddef", headers); - } catch (IOException e) { - e.printStackTrace(); - fail(String.format("problem with method %s: %s",method,e.getMessage())); - } - } - } - } - @Test - public void test() { - TestBaseHTTPClient client = new TestBaseHTTPClient(); - client.doTest(); - } - - - @Before - public void init() throws IOException{ - HelpServletBase.initEsTestWebserver(PORT); - } - @After - public void deinit() { - HelpServletBase.stopTestWebserver(); - } -} diff --git a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestMediatorServerServlet.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestMediatorServerServlet.java deleted file mode 100644 index 2a6f196bd..000000000 --- a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestMediatorServerServlet.java +++ /dev/null @@ -1,91 +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.test; - -import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.ccsdk.features.sdnr.wt.apigateway.MyProperties; -import org.onap.ccsdk.features.sdnr.wt.apigateway.database.MediatorServerInfo; -import org.onap.ccsdk.features.sdnr.wt.apigateway.test.helper.HelpMsServlet; -import org.onap.ccsdk.features.sdnr.wt.apigateway.test.helper.HelpServletBase; - -public class TestMediatorServerServlet extends HelpServletBase { - - private static final int PORT = 40004; - - public TestMediatorServerServlet() { - super("/ms", PORT); - } - - @Test - public void test() throws ServletException, IOException { - - String tmpFilename = "tmp3.cfg"; - File tmpFile = new File(tmpFilename); - if (tmpFile.exists()) { - tmpFile.delete(); - } - MyProperties.Instantiate(tmpFile, true); - String query = "{\"query\":{\"match_all\":{}}}"; - HelpMsServlet servlet = new HelpMsServlet(); - this.setServlet(servlet); - // test diabled message - servlet.setOfflineStatus(true); - servlet.setBaseUrl("http://localhost:" + PORT); - String expectedResponse = "offline"; - testrequest(HTTPMETHOD_GET, query, expectedResponse, false); - testrequest(HTTPMETHOD_POST, query, expectedResponse, false); - testrequest(HTTPMETHOD_PUT, query, expectedResponse, false); - testrequest(HTTPMETHOD_DELETE, query, expectedResponse, false); - - servlet.setOfflineStatus(false); - Map<String, MediatorServerInfo> entries = new HashMap<String,MediatorServerInfo>(); - entries.put("123", new MediatorServerInfo("1", "http://localhost:" + PORT)); - servlet.setMediatorEntries(entries); - testrequest("/123/test/abc",HTTPMETHOD_GET, query, HelpMsServlet.RESPONSE_GET, true); - testrequest("/123/test/abc",HTTPMETHOD_POST, query, HelpMsServlet.RESPONSE_POST, true); - testrequest("/123/test/abc",HTTPMETHOD_PUT, query, HelpMsServlet.RESPONSE_PUT, true); - testrequest("/123/test/abc",HTTPMETHOD_DELETE, query, HelpMsServlet.RESPONSE_DELETE, true); - testrequest("/123/test/abc",HTTPMETHOD_OPTIONS, query, "", false); - - if (tmpFile.exists()) { - tmpFile.delete(); - } - - } - @Before - public void init() throws IOException{ - HelpServletBase.initEsTestWebserver(PORT,"/test"); - } - @After - public void deinit() { - HelpServletBase.stopTestWebserver(); - } - -} diff --git a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestQueryCallback.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestQueryCallback.java deleted file mode 100644 index 3340ec66c..000000000 --- a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestQueryCallback.java +++ /dev/null @@ -1,115 +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.test; - -import static org.junit.Assert.*; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; - -import javax.servlet.ServletException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.ccsdk.features.sdnr.wt.apigateway.EsServlet.IRequestCallback; -import org.onap.ccsdk.features.sdnr.wt.apigateway.MyProperties; -import org.onap.ccsdk.features.sdnr.wt.apigateway.test.helper.HelpEsServlet; -import org.onap.ccsdk.features.sdnr.wt.apigateway.test.helper.HelpServletBase; - -public class TestQueryCallback extends HelpServletBase{ - - private static final int PORT = 40011; - - public TestQueryCallback() { - super("/database",PORT); - } - - final String LR = "\n"; - - - private boolean hasCallback=false; - - @Test - public void test() throws ServletException, IOException { - - String tmpFilename = "tmp1.cfg"; - File tmpFile = new File(tmpFilename); - if (tmpFile.exists()) - tmpFile.delete(); - MyProperties properties = MyProperties.Instantiate(tmpFile,true); - String query = "{\"query\":{\"match_all\":{}}}"; - String tmpconfigcontent2 = "aai=off" + LR + "aaiHeaders=[]" + LR + "database=http://" + HOST + ":" + PORT + LR - + "insecure=1" + LR + "cors=1"; - HelpEsServlet servlet = new HelpEsServlet(); - this.setServlet(servlet); - HelpEsServlet.registerRequestCallback("/mwtn/mediator-server", new IRequestCallback() { - - @Override - public void onRequest(String uri, String method) { - hasCallback=true; - - } - }); - properties.load(new ByteArrayInputStream(tmpconfigcontent2.getBytes())); - testrequest("/database/mwtn/mediator-server/_search",HTTPMETHOD_POST, query, HelpEsServlet.RESPONSE_POST, true); - int wait=10; - while(wait-->0) { - if(hasCallback) { - break; - } - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - Thread.interrupted(); - } - } - assertTrue("no request callback received",hasCallback); - hasCallback=false; - testrequest("/database/mwtn/mediatr-server/_search",HTTPMETHOD_POST, query, HelpEsServlet.RESPONSE_POST, true); - wait=5; - while(wait-->0) { - if(hasCallback) { - break; - } - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - Thread.interrupted(); - } - } - assertFalse("received request callback",hasCallback); - - - - if (tmpFile.exists()) - tmpFile.delete(); - - - } - @Before - public void init() throws IOException{ - HelpServletBase.initEsTestWebserver(PORT,"/database"); - } - @After - public void deinit() { - HelpServletBase.stopTestWebserver(); - } - -} diff --git a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpMsServlet.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpMsServlet.java deleted file mode 100644 index 344dff671..000000000 --- a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpMsServlet.java +++ /dev/null @@ -1,88 +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.test.helper; - -import java.io.IOException; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.onap.ccsdk.features.sdnr.wt.apigateway.MsServlet; -import org.onap.ccsdk.features.sdnr.wt.apigateway.database.MediatorServerInfo; - -public class HelpMsServlet extends MsServlet implements IPublicServlet { - - public static final String RESPONSE_GET = "This is the response get"; - public static final String RESPONSE_POST = "This is the response post"; - public static final String RESPONSE_PUT = "This is the response put"; - public static final String RESPONSE_DELETE = "This is the response delete"; - public static final String RESPONSE_OPTIONS = "This is the response options"; - private boolean offline = true; - private String baseurl; - - @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - super.doGet(req, resp); - } - - @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - super.doPost(req, resp); - } - - @Override - public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - super.doPut(req, resp); - } - - @Override - public void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - super.doOptions(req, resp); - } - - @Override - public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - super.doDelete(req, resp); - } - - public void setOfflineStatus(boolean offline) { - this.offline = offline; - } - - public void setBaseUrl(String url) { - this.baseurl = url; - } - - @Override - protected boolean isOff() { - return this.offline; - } - - @Override - protected String getBaseUrl(String dbServerId) { - return this.baseurl; - } - public void setMediatorEntries(Map<String, MediatorServerInfo> entries) { - this.getEntryProvider().setEntries(entries); - } -} |