diff options
Diffstat (limited to 'sdnr/wt/apigateway')
24 files changed, 1988 insertions, 0 deletions
diff --git a/sdnr/wt/apigateway/feature/pom.xml b/sdnr/wt/apigateway/feature/pom.xml new file mode 100644 index 000000000..f8ec8b23d --- /dev/null +++ b/sdnr/wt/apigateway/feature/pom.xml @@ -0,0 +1,70 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + * ============LICENSE_START======================================================= + * ONAP : CCSDK.feature.sdnr.wt + * ================================================================================ + * 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========================================================= + +--> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <groupId>org.onap.ccsdk.features.sdnr.wt</groupId> + <artifactId>sdnr-wt-apigateway-feature</artifactId> + <version>0.4.1-SNAPSHOT</version> + <packaging>feature</packaging> + <name>ccsdk-features-sdnr-wt :: ${project.artifactId} :: feature</name> + + <parent> + <groupId>org.onap.ccsdk.parent</groupId> + <artifactId>single-feature-parent</artifactId> + <version>1.2.1-SNAPSHOT</version> + <relativePath /> + </parent> + + <dependencyManagement> + <dependencies> + <dependency> + <groupId>org.opendaylight.mdsal.model</groupId> + <artifactId>mdsal-model-artifacts</artifactId> + <version>${odl.mdsal.model.version}</version> + <type>pom</type> + <scope>import</scope> + </dependency> + <dependency> + <groupId>org.opendaylight.controller</groupId> + <artifactId>mdsal-artifacts</artifactId> + <version>1.8.1</version> + <type>pom</type> + <scope>import</scope> + </dependency> + </dependencies> + </dependencyManagement> + + <dependencies> + + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>sdnr-wt-apigateway-provider</artifactId> + <version>${project.version}</version> + </dependency> + + </dependencies> +</project> diff --git a/sdnr/wt/apigateway/installer/pom.xml b/sdnr/wt/apigateway/installer/pom.xml new file mode 100755 index 000000000..1d1802691 --- /dev/null +++ b/sdnr/wt/apigateway/installer/pom.xml @@ -0,0 +1,115 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <groupId>org.onap.ccsdk.features.sdnr.wt</groupId> + <artifactId>sdnr-wt-apigateway-installer</artifactId> + <version>0.4.1-SNAPSHOT</version> + <packaging>pom</packaging> + <name>ccsdk-features-sdnr-wt :: ${project.artifactId}</name> + + <parent> + <groupId>org.onap.ccsdk.parent</groupId> + <artifactId>odlparent-lite</artifactId> + <version>1.2.1-SNAPSHOT</version> + </parent> + + <properties> + <application.name>sdnr-wt-apigateway</application.name> + <include.transitive.dependencies>false</include.transitive.dependencies> + </properties> + + <dependencies> + + <dependency> + <groupId>org.onap.ccsdk.features.sdnr.wt</groupId> + <artifactId>${application.name}-feature</artifactId> + <version>${project.version}</version> + <type>xml</type> + <classifier>features</classifier> + <exclusions> + <exclusion> + <groupId>*</groupId> + <artifactId>*</artifactId> + </exclusion> + </exclusions> + </dependency> + <dependency> + <groupId>org.onap.ccsdk.features.sdnr.wt</groupId> + <artifactId>${application.name}-provider</artifactId> + <version>${project.version}</version> + </dependency> + + + </dependencies> + + <build> + <plugins> + <plugin> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <id>maven-repo-zip</id> + <goals> + <goal>single</goal> + </goals> + <phase>package</phase> + <configuration> + <attach>true</attach> + <finalName>stage/${application.name}-${project.version}</finalName> + <descriptors> + <descriptor>src/assembly/assemble_mvnrepo_zip.xml</descriptor> + </descriptors> + <appendAssemblyId>true</appendAssemblyId> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-dependency-plugin</artifactId> + <executions> +<!-- <execution> --> +<!-- <id>copy-dependencies</id> --> +<!-- <goals> --> +<!-- <goal>copy-dependencies</goal> --> +<!-- </goals> --> +<!-- <phase>prepare-package</phase> --> +<!-- <configuration> --> +<!-- <transitive>true</transitive> --> +<!-- <outputDirectory>${project.build.directory}/assembly/system</outputDirectory> --> +<!-- <overWriteReleases>false</overWriteReleases> --> +<!-- <overWriteSnapshots>true</overWriteSnapshots> --> +<!-- <overWriteIfNewer>true</overWriteIfNewer> --> +<!-- <useRepositoryLayout>true</useRepositoryLayout> --> +<!-- <addParentPoms>false</addParentPoms> --> +<!-- <copyPom>false</copyPom> --> +<!-- <includeArtifactIds>sdnr-wt-apigateway-provider,${application.name}</includeArtifactIds> --> +<!-- <scope>provided</scope> --> +<!-- </configuration> --> +<!-- </execution> --> + <execution> + <id>copy-nested-dependencies</id> + <goals> + <goal>copy-dependencies</goal> + </goals> + <phase>prepare-package</phase> + <configuration> + <transitive>true</transitive> + <outputDirectory>${project.build.directory}/assembly/system</outputDirectory> + <overWriteReleases>false</overWriteReleases> + <overWriteSnapshots>true</overWriteSnapshots> + <overWriteIfNewer>true</overWriteIfNewer> + <useRepositoryLayout>true</useRepositoryLayout> + <addParentPoms>false</addParentPoms> + <copyPom>false</copyPom> + <!--<includeArtifactIds>sdnr-wt-apigateway-provider,${application.name}</includeArtifactIds>--> + <!--<scope>provided</scope>--> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> diff --git a/sdnr/wt/apigateway/installer/src/assembly/assemble_mvnrepo_zip.xml b/sdnr/wt/apigateway/installer/src/assembly/assemble_mvnrepo_zip.xml new file mode 100644 index 000000000..c4eb9aa25 --- /dev/null +++ b/sdnr/wt/apigateway/installer/src/assembly/assemble_mvnrepo_zip.xml @@ -0,0 +1,49 @@ +<!-- + ============LICENSE_START======================================================= + ONAP : CCSDK + ================================================================================ + Copyright (C) 2017 AT&T 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========================================================= + --> + +<!-- Defines how we build the .zip file which is our distribution. --> + +<assembly + xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd"> + <id>repo</id> + <formats> + <format>zip</format> + </formats> + + <!-- we want "system" and related files right at the root level + as this file is suppose to be unzip on top of a karaf + distro. --> + <includeBaseDirectory>false</includeBaseDirectory> + + <fileSets> + <fileSet> + <directory>target/assembly/</directory> + <outputDirectory>.</outputDirectory> + <excludes> + </excludes> + </fileSet> + </fileSets> + + + +</assembly> diff --git a/sdnr/wt/apigateway/pom.xml b/sdnr/wt/apigateway/pom.xml new file mode 100755 index 000000000..33ce77264 --- /dev/null +++ b/sdnr/wt/apigateway/pom.xml @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <groupId>org.onap.ccsdk.features.sdnr.wt</groupId> + <artifactId>sdnr-wt-apigateway-top</artifactId> + <version>0.4.1-SNAPSHOT</version> + <packaging>pom</packaging> + <name>ccsdk-features-sdnr-wt :: ${project.artifactId}</name> + + <parent> + <groupId>org.onap.ccsdk.parent</groupId> + <artifactId>odlparent-lite</artifactId> + <version>1.2.1-SNAPSHOT</version> + <relativePath/> + </parent> + + + <modules> + <module>feature</module> + <module>provider</module> + <module>installer</module> + </modules> + + <properties> + <feature-name>sdnr-wt-apigateway</feature-name> + </properties> +</project> diff --git a/sdnr/wt/apigateway/provider/pom.xml b/sdnr/wt/apigateway/provider/pom.xml new file mode 100644 index 000000000..d375ee5cd --- /dev/null +++ b/sdnr/wt/apigateway/provider/pom.xml @@ -0,0 +1,70 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- * ============LICENSE_START======================================================= + * ONAP : CCSDK.sdnr.wt.apigateway.provider * ================================================================================ + * 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========================================================= --> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + + <modelVersion>4.0.0</modelVersion> + + <groupId>org.onap.ccsdk.features.sdnr.wt</groupId> + <artifactId>sdnr-wt-apigateway-provider</artifactId> + <version>0.4.1-SNAPSHOT</version> + <name>ccsdk-features-sdnr-wt :: ${project.artifactId}</name> + <packaging>bundle</packaging> + <properties> + <checkstyle.skip>true</checkstyle.skip> + </properties> + <parent> + <groupId>org.onap.ccsdk.parent</groupId> + <artifactId>binding-parent</artifactId> + <version>1.2.1-SNAPSHOT</version> + <relativePath /> + </parent> + <dependencies> + <dependency> + <groupId>javax.servlet</groupId> + <artifactId>servlet-api</artifactId> + <version>2.5</version> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-simple</artifactId> + <version>1.7.25</version> + </dependency> + <dependency> + <groupId>org.json</groupId> + <artifactId>json</artifactId> + <version>20131018</version> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <version>2.23.4</version> + <scope>test</scope> + </dependency> + + </dependencies> + <build> + <plugins> + <!-- fixed bug for sonarcube --> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-surefire-plugin</artifactId> + <configuration> + <useSystemClassLoader>false</useSystemClassLoader> + </configuration> + </plugin> + </plugins> + </build> +</project> 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 new file mode 100644 index 000000000..e73d5c668 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/AaiServlet.java @@ -0,0 +1,74 @@ +/* + * ============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; + +public class AaiServlet extends BaseServlet { + + /** + * + */ + private static final long serialVersionUID = 5946205120796162644L; + private static final String OFFLINE_RESPONSE_MESSAGE = "AAI interface is offline"; + + public AaiServlet() { + super(); + } + + @Override + protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + resp.setStatus(200); + } + + @Override + protected String getOfflineResponse() { + return OFFLINE_RESPONSE_MESSAGE; + } + + @Override + protected boolean isOff() { + return MyProperties.getInstance().isAAIOff(); + } + + @Override + protected String getRemoteUrl(String uri) { + + if (uri.startsWith("/")) { + uri = uri.substring(1); + } + if (uri.startsWith("aai")) { + uri = uri.substring("aai".length()); + } + if (uri.startsWith("/")) { + uri = uri.substring(1); + } + String base = MyProperties.getInstance().getAAIBaseUrl(); + if (!base.endsWith("/")) { + base += "/"; + } + + return base + uri; + } +} 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 new file mode 100644 index 000000000..b2bc30c0e --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/BaseServlet.java @@ -0,0 +1,350 @@ +/* + * ============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 java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.StandardCharsets; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.util.Enumeration; +import java.util.List; +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; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +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; + + protected abstract String getOfflineResponse(); + + protected abstract boolean isOff(); + + protected abstract String getRemoteUrl(String uri); + + /** + * + * @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[] {}; + } + + @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()); + } + + public BaseServlet() { + try { + MyProperties.Instantiate(); + } catch (Exception e) { + LOG.error(e.getMessage()); + } + this.trysslSetup(true); + } + + 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()); + } + } + } + + 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(); + } + } + } + + @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(); + } + } + } + + @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(); + } + } + } + + @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(); + } + } + } + + private URLConnection getConnection(HttpServletRequest req, final String method) throws IOException { + + LOG.debug("{} Request", method); + String surl = this.getRemoteUrl(req.getRequestURI()); + LOG.debug("RemoteURL: {}", surl); + 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() { + + @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(); + } + } + + 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); + } + +} 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 new file mode 100644 index 000000000..9d276ffc8 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/EsServlet.java @@ -0,0 +1,67 @@ +/* + * ============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; + +public class EsServlet extends BaseServlet { + + /** + * + */ + private static final long serialVersionUID = -3996363343749995011L; + private static final String OFFLINE_RESPONSE_MESSAGE = "Database interface is offline"; + + public EsServlet() { + super(); + } + + @Override + protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (MyProperties.getInstance().corsEnabled()) { + resp.addHeader("Access-Control-Allow-Origin", "*"); + resp.addHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE"); + resp.addHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); + } + resp.setStatus(200); + } + + @Override + protected String getOfflineResponse() { + return OFFLINE_RESPONSE_MESSAGE; + } + + @Override + protected boolean isOff() { + return MyProperties.getInstance().isEsOff(); + } + + @Override + protected String getRemoteUrl(String uri) { + if (uri != null && uri.length() > 0) { + uri = uri.substring("/database".length()); + } + return MyProperties.getInstance().getEsBaseUrl() + uri; + } +} 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 new file mode 100644 index 000000000..27697930f --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/MsServlet.java @@ -0,0 +1,74 @@ +/* + * ============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.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MsServlet extends BaseServlet { + + /** + * + */ + private static final long serialVersionUID = -5361461082028405171L; + private static final String OFFLINE_RESPONSE_MESSAGE = "MediatorServer interface is offline"; + + public MsServlet() { + + super(); + } + + @Override + protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + resp.setStatus(200); + } + + @Override + protected String getOfflineResponse() { + return OFFLINE_RESPONSE_MESSAGE; + } + + @Override + protected boolean isOff() { + return true; + } + + @Override + protected String getRemoteUrl(String uri) { + String dbServerId = "0"; + if (uri == null) + uri = ""; + if (uri.length() > 0) { + uri = uri.substring("/ms".length()); + dbServerId = uri.substring(0, uri.indexOf("/")); + } + return this.getBaseUrl(dbServerId) + uri; + } + + protected String getBaseUrl(String dbServerId) { + return ""; + } +} diff --git a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/MyProperties.java b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/MyProperties.java new file mode 100644 index 000000000..3d66f526e --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/MyProperties.java @@ -0,0 +1,171 @@ +/* + * ============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.File; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.json.JSONArray; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MyProperties { + + private static Logger LOG = LoggerFactory.getLogger(MyProperties.class); + public static final String PROPFILE = "etc/apigateway.properties"; + private static final String DEFAULT_AAI_HEADERS = "[\"X-FromAppId:SDNR\",\"Authorization:Basic QUFJOkFBSQ==\"]"; + private static final String DEFAULT_CORSENABLED = "0"; + private static final String DEFAULT_TRUSTINSECURE = "0"; + private static final String DEFAULT_ESDATABASE = "http://localhost:9200"; + private static final String DEFAULT_AAI = "off"; + + @Override + public String toString() { + return "MyProperties [aaiBase=" + aaiBase + ", aaiHeaders=" + aaiHeaders + ", esBase=" + esBase + + ", trustInsecure=" + trustInsecure + ", corsEnabled=" + corsEnabled + "]"; + } + + private static MyProperties mObj; + + private String aaiBase; + private Map<String, String> aaiHeaders; + private String esBase; + + private boolean trustInsecure; + + private boolean corsEnabled; + + public boolean isAAIOff() { + return this.aaiBase == null ? true : this.aaiBase.equals("off"); + } + + public boolean isEsOff() { + return this.esBase == null ? true : this.esBase.equals("off"); + } + + public String getAAIBaseUrl() { + return this.aaiBase; + } + + public String getEsBaseUrl() { + return this.esBase; + } + + public Map<String, String> getAAIHeaders() { + return this.aaiHeaders; + } + + public boolean trustInsecure() { + return this.trustInsecure; + } + + public boolean corsEnabled() { + return this.corsEnabled; + } + + public static MyProperties Instantiate() throws IOException, NumberFormatException { + return Instantiate(new File(PROPFILE)); + } + + public static MyProperties Instantiate(File file) throws IOException, NumberFormatException { + + return Instantiate(file, false); + } + + public static MyProperties Instantiate(File file, boolean force) throws IOException, NumberFormatException { + if (mObj == null || force) { + mObj = new MyProperties(file); + LOG.debug("instantiated: {}", mObj.toString()); + } + return mObj; + } + + private MyProperties(File file) throws IOException, NumberFormatException { + this.aaiBase = "off"; + this.trustInsecure = false; + if (!file.exists()) { + this.writeDefaults(file); + } + this.load(new FileInputStream(file)); + } + + public void load(InputStream in) throws IOException, NumberFormatException { + + Properties defaultProps = new Properties(); + defaultProps.load(in); + in.close(); + + this.aaiBase = defaultProps.getProperty("aai", DEFAULT_AAI); + this.aaiHeaders = _parseHeadersMap(defaultProps.getProperty("aaiHeaders", DEFAULT_AAI_HEADERS)); + this.esBase = defaultProps.getProperty("database", DEFAULT_ESDATABASE); + this.trustInsecure = Integer.parseInt(defaultProps.getProperty("insecure", DEFAULT_TRUSTINSECURE)) == 1; + this.corsEnabled = Integer.parseInt(defaultProps.getProperty("cors", DEFAULT_CORSENABLED)) == 1; + } + + private static Map<String, String> _parseHeadersMap(String s) { + Map<String, String> r = new HashMap<>(); + try { + JSONArray a = new JSONArray(s); + if ( a.length() > 0) { + for (int i = 0; i < a.length(); i++) { + String item = a.getString(i); + String[] hlp = item.split(":"); + if (hlp.length > 1) { + r.put(hlp[0], hlp[1]); + } + } + } + } catch (Exception e) { + LOG.warn("problem loading headers map: {}",e.getMessage()); + } + return r; + } + + private String writeDefaults(File f) throws IOException { + StringBuilder sb = new StringBuilder(); + final String LR = "\n"; + FileWriter fw = new FileWriter(f); + sb.append("aai=" + DEFAULT_AAI + LR); + sb.append("aaiHeaders=" + DEFAULT_AAI_HEADERS + LR); + sb.append("database=" + DEFAULT_ESDATABASE + LR); + sb.append("insecure=" + DEFAULT_TRUSTINSECURE + LR); + sb.append("cors=" + DEFAULT_CORSENABLED); + try { + fw.write(sb.toString()); + } catch (Exception e) { + LOG.warn("problem writing default values to propertyfile {} : {}", f.getAbsolutePath() , e.getMessage()); + } finally { + fw.close(); + } + return sb.toString(); + } + + public static MyProperties getInstance() { + return mObj; + } + +} diff --git a/sdnr/wt/apigateway/provider/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/sdnr/wt/apigateway/provider/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 000000000..2bfb1aa84 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" +xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" +xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs"> + + <bean id="aaiServlet" + class="org.onap.ccsdk.features.sdnr.wt.apigateway.AaiServlet"> + </bean> + + <service interface="javax.servlet.http.HttpServlet" ref="aaiServlet"> + <service-properties> + <entry key="alias" value="/aai" /> + </service-properties> + </service> + + <bean id="esServlet" + class="org.onap.ccsdk.features.sdnr.wt.apigateway.EsServlet"> + </bean> + + <service interface="javax.servlet.http.HttpServlet" ref="esServlet"> + <service-properties> + <entry key="alias" value="/database" /> + </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/AllTests.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/AllTests.java new file mode 100644 index 000000000..a34d3cac1 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/AllTests.java @@ -0,0 +1,31 @@ +/* + * ============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.test; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ TestAaiServlet.class, TestProperties.class,TestDatabaseServlet.class, TestMediatorServerServlet.class }) +public class AllTests { + +} 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 new file mode 100644 index 000000000..fd76be7af --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestAaiServlet.java @@ -0,0 +1,76 @@ +/* + * ============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.test; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; + +import javax.servlet.ServletException; + +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.apigateway.MyProperties; +import org.onap.ccsdk.features.sdnr.wt.apigateway.test.helper.HelpAaiServlet; +import org.onap.ccsdk.features.sdnr.wt.apigateway.test.helper.HelpEsServlet; +import org.onap.ccsdk.features.sdnr.wt.apigateway.test.helper.HelpServletBase; + +public class TestAaiServlet extends HelpServletBase{ + + public TestAaiServlet() { + super("/aai",40001); + } + + @Test + public void test() throws ServletException, IOException { + + String tmpFilename = "tmp.cfg"; + File tmpFile = new File(tmpFilename); + if (tmpFile.exists()) + tmpFile.delete(); + MyProperties properties = MyProperties.Instantiate(tmpFile,true); + 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 + + "insecure=1" + LR + "cors=1"; + this.setServlet(new HelpAaiServlet()); + // test diabled message + properties.load(new ByteArrayInputStream(tmpconfigcontent.getBytes())); + 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); + + // initEsTestWebserver(port); + properties.load(new ByteArrayInputStream(tmpconfigcontent2.getBytes())); + testrequest(HTTPMETHOD_GET, query, HelpEsServlet.RESPONSE_GET, true); + testrequest(HTTPMETHOD_POST, query, HelpEsServlet.RESPONSE_POST, true); + testrequest(HTTPMETHOD_PUT, query, HelpEsServlet.RESPONSE_PUT, true); + testrequest(HTTPMETHOD_DELETE, query, HelpEsServlet.RESPONSE_DELETE, true); + testrequest(HTTPMETHOD_OPTIONS, query, "", false); + // stopTestWebserver(); + if (tmpFile.exists()) + tmpFile.delete(); + + } + +} 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 new file mode 100644 index 000000000..143766fdb --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestDatabaseServlet.java @@ -0,0 +1,81 @@ +/* + * ============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.test; + +import org.junit.Test; +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; + +import java.io.*; +import javax.servlet.ServletException; + +public class TestDatabaseServlet extends HelpServletBase{ + + public TestDatabaseServlet() { + super("/database",40002); + } + + + + final String LR = "\n"; + + + + @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 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 + + "insecure=1" + LR + "cors=1"; + this.setServlet(new HelpEsServlet()); + // test diabled message + properties.load(new ByteArrayInputStream(tmpconfigcontent.getBytes())); + 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); + + // initEsTestWebserver(port); + properties.load(new ByteArrayInputStream(tmpconfigcontent2.getBytes())); + testrequest(HTTPMETHOD_GET, query, HelpEsServlet.RESPONSE_GET, true); + testrequest(HTTPMETHOD_POST, query, HelpEsServlet.RESPONSE_POST, true); + testrequest(HTTPMETHOD_PUT, query, HelpEsServlet.RESPONSE_PUT, true); + testrequest(HTTPMETHOD_DELETE, query, HelpEsServlet.RESPONSE_DELETE, true); + testrequest(HTTPMETHOD_OPTIONS, query, "", false); + // stopTestWebserver(); + + + if (tmpFile.exists()) + tmpFile.delete(); + + + } + +} 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 new file mode 100644 index 000000000..d4197c6db --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestMediatorServerServlet.java @@ -0,0 +1,71 @@ +/* + * ============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.test; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; + +import javax.servlet.ServletException; + +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.apigateway.MyProperties; +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); + 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); + + } + +} diff --git a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestProperties.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestProperties.java new file mode 100644 index 000000000..1a63240d8 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/TestProperties.java @@ -0,0 +1,108 @@ +/* + * ============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.test; + +import static org.junit.Assert.*; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.apigateway.MyProperties; + +public class TestProperties { + + private static final boolean DEFAULT_CORSENABLED = false; + private static final boolean DEFAULT_AAIOFF = true; + private static final boolean DEFAULT_ESOFF = false; + private static final boolean DEFAULT_TRUSTINSECURE = false; + private static final String DEFAULT_AAIBASEURL = "off"; + private static Map<String, String> DEFAULT_AAIHEADERS = new HashMap<String, String>(); + private static final String DEFAULT_ESBASEURL = "http://localhost:9200"; + + private static final boolean CUSTOM_CORSENABLED = true; + private static final boolean CUSTOM_AAIOFF = false; + private static final boolean CUSTOM_ESOFF = false; + private static final boolean CUSTOM_TRUSTINSECURE = true; + private static final String CUSTOM_AAIBASEURL = "https://aai.tld:2214"; + private static Map<String, String> CUSTOM_AAIHEADERS = new HashMap<String, String>(); + private static final String CUSTOM_ESBASEURL = "http://localhost:9200"; + + private static final String LR = "\n"; + + @Test + public void test() { + final String tmpFilename = "tmp2.cfg"; + DEFAULT_AAIHEADERS.put("X-FromAppId", "SDNR"); + DEFAULT_AAIHEADERS.put("Authorization", "Basic QUFJOkFBSQ=="); + CUSTOM_AAIHEADERS.put("X-FromAppId", "SDNC"); + CUSTOM_AAIHEADERS.put("Authorization", "Basic 1234"); + final String TESTPROPERTYFILECONTENT = "aai=" + CUSTOM_AAIBASEURL + LR + "aaiHeaders=[\"X-FromAppId:" + + CUSTOM_AAIHEADERS.get("X-FromAppId") + "\",\"Authorization:" + CUSTOM_AAIHEADERS.get("Authorization") + + "\"]" + LR + "database=" + CUSTOM_ESBASEURL + LR + "insecure=" + (CUSTOM_TRUSTINSECURE ? "1" : "0") + + LR + "cors=" + (CUSTOM_CORSENABLED ? "1" : "0"); + File ftest = new File(tmpFilename); + // delete autogenerated testfile + if (ftest.exists()) + ftest.delete(); + MyProperties prop = null; + ftest = new File(tmpFilename); + try { + prop = MyProperties.Instantiate(ftest, true); + } catch (Exception e) { + fail("error instantiating properties"); + } + assertNotNull("problem without exception instantiating properties", prop); + + assertEquals("default config file was not created", true, ftest.exists()); + + // test default values + assertEquals("default value is not correct", DEFAULT_CORSENABLED, prop.corsEnabled()); + assertEquals("default value is not correct", DEFAULT_AAIOFF, prop.isAAIOff()); + assertEquals("default value is not correct", DEFAULT_ESOFF, prop.isEsOff()); + assertEquals("default value is not correct", DEFAULT_TRUSTINSECURE, prop.trustInsecure()); + assertEquals("default value is not correct", DEFAULT_AAIBASEURL, prop.getAAIBaseUrl()); + assertEquals("default value is not correct", DEFAULT_AAIHEADERS, prop.getAAIHeaders()); + assertEquals("default value is not correct", DEFAULT_ESBASEURL, prop.getEsBaseUrl()); + + try { + prop.load(new ByteArrayInputStream(TESTPROPERTYFILECONTENT.getBytes())); + } catch (Exception e) { + fail("error loading custom values into properties"); + } + + // test custom values + assertEquals("custom value is not correct", CUSTOM_CORSENABLED, prop.corsEnabled()); + assertEquals("custom value is not correct", CUSTOM_AAIOFF, prop.isAAIOff()); + assertEquals("custom value is not correct", CUSTOM_ESOFF, prop.isEsOff()); + assertEquals("custom value is not correct", CUSTOM_TRUSTINSECURE, prop.trustInsecure()); + assertEquals("custom value is not correct", CUSTOM_AAIBASEURL, prop.getAAIBaseUrl()); + assertEquals("custom value is not correct", CUSTOM_AAIHEADERS, prop.getAAIHeaders()); + assertEquals("custom value is not correct", CUSTOM_ESBASEURL, prop.getEsBaseUrl()); + + // delete autogenerated testfile + ftest.delete(); + + } + +} diff --git a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpAaiServlet.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpAaiServlet.java new file mode 100644 index 000000000..5c28c8544 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpAaiServlet.java @@ -0,0 +1,59 @@ +/* + * ============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 javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.ccsdk.features.sdnr.wt.apigateway.AaiServlet; + +public class HelpAaiServlet extends AaiServlet 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"; + + @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); + } +} diff --git a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpEsServlet.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpEsServlet.java new file mode 100644 index 000000000..a9cb06b10 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpEsServlet.java @@ -0,0 +1,59 @@ +/* + * ============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 javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.ccsdk.features.sdnr.wt.apigateway.EsServlet; + +public class HelpEsServlet extends EsServlet 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"; + + @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); + } +} 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 new file mode 100644 index 000000000..b030f6487 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpMsServlet.java @@ -0,0 +1,83 @@ +/* + * ============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 javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.ccsdk.features.sdnr.wt.apigateway.MsServlet; + +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; + } +} diff --git a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpServlet.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpServlet.java new file mode 100644 index 000000000..ea7690c75 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpServlet.java @@ -0,0 +1,53 @@ +/* + * ============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 javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.ccsdk.features.sdnr.wt.apigateway.EsServlet; + +public class HelpServlet extends EsServlet { + + @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); + } +} 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 new file mode 100644 index 000000000..30732073b --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/HelpServletBase.java @@ -0,0 +1,210 @@ +/* + * ============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 static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.StringWriter; +import java.net.InetSocketAddress; +import java.util.Enumeration; +import java.util.Map; +import java.util.Vector; +import java.util.concurrent.ExecutorService; +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"; + private IPublicServlet servlet; + private HttpServer server; + public final String HOST = "localhost"; + protected final int port; + private final String baseUri; + protected static final String LR = "\n"; + + public HelpServletBase(String baseuri, int port) { + this.baseUri=baseuri; + this.port = port; + } + private ExecutorService httpThreadPool; + + public void setServlet(IPublicServlet s) + { + this.servlet=s; + } + + protected void testrequest(String method, String data, String expectedResponse, boolean exact) { + this.testrequest(method, data, expectedResponse, exact, null); + } + + protected void testrequest(String method, String data, String expectedResponse, boolean exact, + Map<String, String> headersToCheck) { + + HttpServletRequest mockRequest = mock(HttpServletRequest.class); + HttpServletResponse mockResponse = mock(HttpServletResponse.class); + + StringWriter out = new StringWriter(); + ServletOutputStream printOut = new ServletOutputStream() { + + @Override + public void write(int arg0) throws IOException { + out.write(arg0); + } + }; + ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes()); + ServletInputStream inputStream= new ServletInputStream() { + @Override + public int read() throws IOException { + return bis.read(); + } + }; + Vector<String> headers=new Vector<String>(); + headers.addElement("Accept"); + headers.add("User-Agent"); + Enumeration<String> headerNames = headers.elements(); + try { + when(mockRequest.getRequestURI()).thenReturn(this.baseUri+"/mwtn/test"); + when(mockRequest.getHeaderNames()).thenReturn(headerNames); + when(mockRequest.getHeader("Accept")).thenReturn("application/json"); + when(mockRequest.getHeader("User-Agent")).thenReturn("Gecko abc"); + when(mockRequest.getInputStream()).thenReturn(inputStream); + when(mockResponse.getOutputStream()).thenReturn(printOut); + System.out.println("do a " + method + " request"); + if (method == HTTPMETHOD_GET) + this.servlet.doGet(mockRequest, mockResponse); + else if (method == HTTPMETHOD_POST) + this.servlet.doPost(mockRequest, mockResponse); + else if (method == HTTPMETHOD_PUT) + this.servlet.doPut(mockRequest, mockResponse); + else if (method == HTTPMETHOD_DELETE) + this.servlet.doDelete(mockRequest, mockResponse); + else if (method == HTTPMETHOD_OPTIONS) + this.servlet.doOptions(mockRequest, mockResponse); + else + fail("http request method " + method + " test not implemented"); + } catch (Exception e) { + System.err.println(e.getMessage()); + } + + verify(mockResponse).setStatus(200); + if (exact) + assertEquals(expectedResponse, out.toString()); + else + assertTrue("response not for method " + method + "correct", out.toString().contains(expectedResponse)); + // currently unable to check extra headers + if (headersToCheck != null) { + + } + } + + @Before + public void initEsTestWebserver() throws IOException { + this.server = HttpServer.create(new InetSocketAddress(this.port), 0); + this.httpThreadPool = Executors.newFixedThreadPool(5); + this.server.setExecutor(this.httpThreadPool); + this.server.createContext("/mwtn/test", new MyHandler()); + //server.createContext("/", new MyRootHandler()); + this.server.setExecutor(null); // creates a default executor + this.server.start(); + System.out.println("http server started"); + } + + @After + public void stopTestWebserver() { + if (this.server != null) { + this.server.stop(0); + this.httpThreadPool.shutdownNow(); + System.out.println("http server stopped" ); + } + } + + + + static class MyHandler implements HttpHandler { + @Override + public void handle(HttpExchange t) throws IOException { + String method = t.getRequestMethod(); + System.out.println("req method: " + method); + OutputStream os = null; + try { + if (method.equals(HTTPMETHOD_GET)) { + t.sendResponseHeaders(200, HelpEsServlet.RESPONSE_GET.length()); + os = t.getResponseBody(); + os.write(HelpEsServlet.RESPONSE_GET.getBytes()); + } else if (method.equals(HTTPMETHOD_POST)) { + t.sendResponseHeaders(200, HelpEsServlet.RESPONSE_POST.length()); + os = t.getResponseBody(); + os.write(HelpEsServlet.RESPONSE_POST.getBytes()); + } else if (method.equals(HTTPMETHOD_PUT)) { + t.sendResponseHeaders(200, HelpEsServlet.RESPONSE_PUT.length()); + os = t.getResponseBody(); + os.write(HelpEsServlet.RESPONSE_PUT.getBytes()); + } else if (method.equals(HTTPMETHOD_DELETE)) { + t.sendResponseHeaders(200, HelpEsServlet.RESPONSE_DELETE.length()); + os = t.getResponseBody(); + os.write(HelpEsServlet.RESPONSE_DELETE.getBytes()); + } else if (method.equals(HTTPMETHOD_OPTIONS)) { + t.sendResponseHeaders(200, HelpEsServlet.RESPONSE_OPTIONS.length()); + //os = t.getResponseBody(); + //os.write(RESPONSE_OPTIONS.getBytes()); + } else { + t.sendResponseHeaders(404, 0); + } + System.out.println("req handled successful"); + + } catch (Exception e) { + System.out.println(e.getMessage()); + } + finally { + if (os != null) + { + os.close(); + } + } + } + } +} diff --git a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/IPublicServlet.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/IPublicServlet.java new file mode 100644 index 000000000..4a640a35f --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/IPublicServlet.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 2017 AT&T 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 javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public interface IPublicServlet { + + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; + public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; + public void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ; + public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ; +} diff --git a/sdnr/wt/apigateway/provider/src/test/resources/log4j.properties b/sdnr/wt/apigateway/provider/src/test/resources/log4j.properties new file mode 100644 index 000000000..142663bd2 --- /dev/null +++ b/sdnr/wt/apigateway/provider/src/test/resources/log4j.properties @@ -0,0 +1,12 @@ +log4j.rootLogger=INFO, out + +log4j.logger.org.apache.camel.impl.converter=WARN +log4j.logger.org.apache.camel.management=WARN +log4j.logger.org.apache.camel.impl.DefaultPackageScanClassResolver=WARN +log4j.logger.org.springframework=ERROR + +# CONSOLE appender not used by default +log4j.appender.out=org.apache.log4j.ConsoleAppender +log4j.appender.out.layout=org.apache.log4j.PatternLayout +log4j.appender.out.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n + diff --git a/sdnr/wt/apigateway/provider/tmp3.cfg b/sdnr/wt/apigateway/provider/tmp3.cfg new file mode 100644 index 000000000..c8f5897b7 --- /dev/null +++ b/sdnr/wt/apigateway/provider/tmp3.cfg @@ -0,0 +1,5 @@ +aai=off +aaiHeaders=["X-FromAppId:SDNR","Authorization:Basic QUFJOkFBSQ=="] +database=http://localhost:9200 +insecure=0 +cors=0
\ No newline at end of file |