diff options
author | Dan Timoney <dtimoney@att.com> | 2019-08-01 17:21:19 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@onap.org> | 2019-08-01 17:21:19 +0000 |
commit | d45b32fd84aed39798426423919115f8295813ad (patch) | |
tree | 02b399da775c0290b77581cb50a28ccb3839986e /sdnr | |
parent | 17a6cea68f83a736a19a8b4012f3df59ca597d3f (diff) | |
parent | e57b5a77c5679e512651c29a5636f00d7b9ee931 (diff) |
Merge "fix apigateway for mediatorserver routes"
Diffstat (limited to 'sdnr')
16 files changed, 958 insertions, 72 deletions
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 b2bc30c0e..06002a200 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 @@ -161,6 +161,9 @@ public abstract class BaseServlet extends HttpServlet { } http.disconnect(); } + else { + this.set404Response(resp); + } } } @@ -184,6 +187,9 @@ public abstract class BaseServlet extends HttpServlet { } http.disconnect(); } + else { + this.set404Response(resp); + } } } @@ -207,6 +213,9 @@ public abstract class BaseServlet extends HttpServlet { } http.disconnect(); } + else { + this.set404Response(resp); + } } } @@ -230,14 +239,38 @@ public abstract class BaseServlet extends HttpServlet { } http.disconnect(); } + else { + this.set404Response(resp); + } } } + private void set404Response(HttpServletResponse resp) { + resp.setStatus(404); + } + private URLConnection getConnection(HttpServletRequest req, final String method) throws IOException { - LOG.debug("{} Request", method); + 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); 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 9d276ffc8..2b5488498 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,22 +21,68 @@ 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; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class EsServlet extends BaseServlet { + public interface IRequestCallback{ + + void onRequest(String uri,String method); + } /** * */ private static final long serialVersionUID = -3996363343749995011L; 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); + } + } + + 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()) { @@ -64,4 +110,24 @@ public class EsServlet extends BaseServlet { } return MyProperties.getInstance().getEsBaseUrl() + uri; } -} + @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"); + } +} 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 index 27697930f..c0b6c99a2 100644 --- 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 @@ -25,6 +25,8 @@ 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; @@ -33,14 +35,31 @@ 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 = "/mwtn/mediator-server"; + private final DatabaseEntryProvider entryProvider; public MsServlet() { - super(); + this.entryProvider = new DatabaseEntryProvider("http://localhost:9200/",60); + EsServlet.registerRequestCallback(DATABASE_REQUEST_URI_REGEX, this.dbRequestCallback); } + 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); @@ -53,7 +72,7 @@ public class MsServlet extends BaseServlet { @Override protected boolean isOff() { - return true; + return false; } @Override @@ -62,13 +81,18 @@ public class MsServlet extends BaseServlet { if (uri == null) uri = ""; if (uri.length() > 0) { - uri = uri.substring("/ms".length()); - dbServerId = uri.substring(0, uri.indexOf("/")); + uri = uri.substring("/ms/".length()); + int idx= uri.indexOf("/"); + dbServerId = uri.substring(0,idx); + uri=uri.substring(idx); } - return this.getBaseUrl(dbServerId) + uri; + 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 ""; + 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 new file mode 100644 index 000000000..086c3c977 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/DatabaseEntryProvider.java @@ -0,0 +1,106 @@ +/* + * ============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; + } + +} 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 new file mode 100644 index 000000000..af46509e9 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/DatabaseHttpClient.java @@ -0,0 +1,83 @@ +/* + * ============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 = "/mwtn/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>(); + + 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/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/AllTests.java b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/MediatorServerInfo.java index a34d3cac1..a90b90173 100644 --- a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/AllTests.java +++ b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/MediatorServerInfo.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP : CCSDK.apps.sdnr.wt.apigateway * ================================================================================ - * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * Copyright (C) 2018 highstreet technologies GmbH Intellectual Property. * All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,14 +18,25 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.ccsdk.features.sdnr.wt.apigateway.test; +package org.onap.ccsdk.features.sdnr.wt.apigateway.database; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; +public class MediatorServerInfo { -@RunWith(Suite.class) -@SuiteClasses({ TestAaiServlet.class, TestProperties.class,TestDatabaseServlet.class, TestMediatorServerServlet.class }) -public class AllTests { + 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 new file mode 100644 index 000000000..f8f95b386 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/http/BaseHTTPClient.java @@ -0,0 +1,193 @@ +/******************************************************************************* + * ============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 final String baseUrl; + + private int timeout = DEFAULT_HTTP_TIMEOUT_MS; + private SSLContext sc = null; + + public BaseHTTPClient(String base) { + this(base, false); + } + + + 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 new file mode 100644 index 000000000..60d0a3638 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/http/BaseHTTPResponse.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * ============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/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestAaiServlet.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestAaiServlet.java index fd76be7af..0af4d69df 100644 --- a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestAaiServlet.java +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestAaiServlet.java @@ -26,6 +26,8 @@ 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.MyProperties; import org.onap.ccsdk.features.sdnr.wt.apigateway.test.helper.HelpAaiServlet; @@ -34,8 +36,9 @@ import org.onap.ccsdk.features.sdnr.wt.apigateway.test.helper.HelpServletBase; public class TestAaiServlet extends HelpServletBase{ + private static final int PORT = 40001; public TestAaiServlet() { - super("/aai",40001); + super("/aai",PORT); } @Test @@ -49,10 +52,10 @@ public class TestAaiServlet extends HelpServletBase{ String query = "{\"query\":{\"match_all\":{}}}"; String tmpconfigcontent = "aai=off" + LR + "aaiHeaders=[]" + LR + "database=off" + LR + "insecure=0" + LR + "cors=0"; - String tmpconfigcontent2 = "aai=http://" + HOST + ":" + this.port + LR + "aaiHeaders=[]" + LR + "database=off"+ LR + String tmpconfigcontent2 = "aai=http://" + HOST + ":" + PORT + LR + "aaiHeaders=[]" + LR + "database=off"+ LR + "insecure=1" + LR + "cors=1"; this.setServlet(new HelpAaiServlet()); - // test diabled message + // test disabled message properties.load(new ByteArrayInputStream(tmpconfigcontent.getBytes())); String expectedResponse = "offline"; testrequest(HTTPMETHOD_GET, query, expectedResponse, false); @@ -72,5 +75,12 @@ public class TestAaiServlet extends HelpServletBase{ tmpFile.delete(); } - + @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/TestDatabaseHttpClient.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestDatabaseHttpClient.java new file mode 100644 index 000000000..795228834 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestDatabaseHttpClient.java @@ -0,0 +1,120 @@ +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/TestDatabaseServlet.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestDatabaseServlet.java index 143766fdb..d7b4c1511 100644 --- a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestDatabaseServlet.java +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestDatabaseServlet.java @@ -20,6 +20,8 @@ */ package org.onap.ccsdk.features.sdnr.wt.apigateway.test; +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.test.helper.HelpEsServlet; @@ -30,8 +32,10 @@ import javax.servlet.ServletException; public class TestDatabaseServlet extends HelpServletBase{ + private static final int PORT = 40002; + public TestDatabaseServlet() { - super("/database",40002); + super("/database",PORT); } @@ -51,7 +55,7 @@ public class TestDatabaseServlet extends HelpServletBase{ String query = "{\"query\":{\"match_all\":{}}}"; String tmpconfigcontent = "aai=off" + LR + "aaiHeaders=[]" + LR + "database=off" + LR + "insecure=0" + LR + "cors=0"; - String tmpconfigcontent2 = "aai=off" + LR + "aaiHeaders=[]" + LR + "database=http://" + HOST + ":" + this.port + LR + String tmpconfigcontent2 = "aai=off" + LR + "aaiHeaders=[]" + LR + "database=http://" + HOST + ":" + PORT + LR + "insecure=1" + LR + "cors=1"; this.setServlet(new HelpEsServlet()); // test diabled message @@ -77,5 +81,12 @@ public class TestDatabaseServlet extends HelpServletBase{ } - + @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/TestHttpClient.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestHttpClient.java new file mode 100644 index 000000000..6e21bc133 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestHttpClient.java @@ -0,0 +1,54 @@ +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 index 7fa20f788..2a6f196bd 100644 --- 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 @@ -1,26 +1,37 @@ /* - * ============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 + * ============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 + * 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========================================================= + * 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; @@ -54,16 +65,27 @@ public class TestMediatorServerServlet extends HelpServletBase { testrequest(HTTPMETHOD_DELETE, query, expectedResponse, false); servlet.setOfflineStatus(false); - testrequest(HTTPMETHOD_GET, query, HelpMsServlet.RESPONSE_GET, true); - testrequest(HTTPMETHOD_POST, query, HelpMsServlet.RESPONSE_POST, true); - testrequest(HTTPMETHOD_PUT, query, HelpMsServlet.RESPONSE_PUT, true); - testrequest(HTTPMETHOD_DELETE, query, HelpMsServlet.RESPONSE_DELETE, true); - testrequest(HTTPMETHOD_OPTIONS, query, "", 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 new file mode 100644 index 000000000..78341dfad --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestQueryCallback.java @@ -0,0 +1,98 @@ +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 index b030f6487..344dff671 100644 --- 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 @@ -21,12 +21,14 @@ 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 { @@ -80,4 +82,7 @@ public class HelpMsServlet extends MsServlet implements IPublicServlet { protected String getBaseUrl(String dbServerId) { return this.baseurl; } + public void setMediatorEntries(Map<String, MediatorServerInfo> entries) { + this.getEntryProvider().setEntries(entries); + } } diff --git a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpServletBase.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpServletBase.java index 7b7cba239..f89ca4dcf 100644 --- a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpServletBase.java +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpServletBase.java @@ -40,37 +40,35 @@ import java.util.concurrent.Executors; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; -import org.onap.ccsdk.features.sdnr.wt.apigateway.AaiServlet; - import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; public class HelpServletBase { - protected static final String HTTPMETHOD_GET = "GET"; - protected static final String HTTPMETHOD_POST = "POST"; - protected static final String HTTPMETHOD_PUT = "PUT"; - protected static final String HTTPMETHOD_DELETE = "DELETE"; - protected static final String HTTPMETHOD_OPTIONS = "OPTIONS"; + public static final String HTTPMETHOD_GET = "GET"; + public static final String HTTPMETHOD_POST = "POST"; + public static final String HTTPMETHOD_PUT = "PUT"; + public static final String HTTPMETHOD_DELETE = "DELETE"; + public static final String HTTPMETHOD_OPTIONS = "OPTIONS"; private IPublicServlet servlet; - private HttpServer server; + private static HttpServer server; + private static ExecutorService httpThreadPool; + public final String HOST = "localhost"; - protected final int port; + protected static int testPort; private final String baseUri; protected static final String LR = "\n"; public HelpServletBase(String baseuri, int port) { this.baseUri=baseuri; - this.port = port; + testPort = port; } - private ExecutorService httpThreadPool; public void setServlet(IPublicServlet s) { @@ -78,10 +76,13 @@ public class HelpServletBase { } protected void testrequest(String method, String data, String expectedResponse, boolean exact) { - this.testrequest(method, data, expectedResponse, exact, null); + this.testrequest("/mwtn/test",method, data, expectedResponse, exact, null); + } + protected void testrequest(String uri,String method, String data, String expectedResponse, boolean exact) { + this.testrequest(uri,method, data, expectedResponse, exact, null); } - protected void testrequest(String method, String data, String expectedResponse, boolean exact, + protected void testrequest(String uri,String method, String data, String expectedResponse, boolean exact, Map<String, String> headersToCheck) { HttpServletRequest mockRequest = mock(HttpServletRequest.class); @@ -107,7 +108,7 @@ public class HelpServletBase { headers.add("User-Agent"); Enumeration<String> headerNames = headers.elements(); try { - when(mockRequest.getRequestURI()).thenReturn(this.baseUri+"/mwtn/test"); + when(mockRequest.getRequestURI()).thenReturn(this.baseUri+uri); when(mockRequest.getHeaderNames()).thenReturn(headerNames); when(mockRequest.getHeader("Accept")).thenReturn("application/json"); when(mockRequest.getHeader("User-Agent")).thenReturn("Gecko abc"); @@ -140,35 +141,46 @@ public class HelpServletBase { } } - @Before - public void initEsTestWebserver() throws IOException { - this.server = HttpServer.create(new InetSocketAddress("127.0.0.1",this.port), 0); - this.httpThreadPool = Executors.newFixedThreadPool(5); - this.server.setExecutor(this.httpThreadPool); - this.server.createContext("/mwtn/test", new MyHandler()); + private void init() throws IOException{ + + + initEsTestWebserver(testPort); + } + @After + private void deinit() { + stopTestWebserver(); + } + + public static void initEsTestWebserver(int port) throws IOException { + initEsTestWebserver(port, "/mwtn/test"); + } + public static void initEsTestWebserver(int port,String baseUri) throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0); + httpThreadPool = Executors.newFixedThreadPool(5); + server.setExecutor(httpThreadPool); + server.createContext(baseUri, new MyHandler()); //server.createContext("/", new MyRootHandler()); - this.server.setExecutor(null); // creates a default executor - this.server.start(); + server.setExecutor(null); // creates a default executor + server.start(); System.out.println("http server started"); } - @After - public void stopTestWebserver() { - if (this.server != null) { - this.server.stop(0); - this.httpThreadPool.shutdownNow(); + public static void stopTestWebserver() { + if (server != null) { + server.stop(0); + httpThreadPool.shutdownNow(); System.out.println("http server stopped" ); } } - static class MyHandler implements HttpHandler { + public static class MyHandler implements HttpHandler { @Override public void handle(HttpExchange t) throws IOException { String method = t.getRequestMethod(); - System.out.println("req method: " + method); + System.out.println(String.format("req received: %s %s" ,method,t.getRequestURI())); OutputStream os = null; try { if (method.equals(HTTPMETHOD_GET)) { |