aboutsummaryrefslogtreecommitdiffstats
path: root/sdnr/wt/apigateway/provider/src/main
diff options
context:
space:
mode:
Diffstat (limited to 'sdnr/wt/apigateway/provider/src/main')
-rw-r--r--sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/BaseServlet.java35
-rw-r--r--sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/EsServlet.java70
-rw-r--r--sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/MsServlet.java38
-rw-r--r--sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/DatabaseEntryProvider.java106
-rw-r--r--sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/DatabaseHttpClient.java83
-rw-r--r--sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/MediatorServerInfo.java42
-rw-r--r--sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/http/BaseHTTPClient.java193
-rw-r--r--sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/http/BaseHTTPResponse.java38
8 files changed, 595 insertions, 10 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/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
new file mode 100644
index 000000000..a90b90173
--- /dev/null
+++ b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/database/MediatorServerInfo.java
@@ -0,0 +1,42 @@
+/*
+ * ============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
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 + "]";
+ }
+}