aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorefiacor <fiachra.corcoran@est.tech>2019-07-25 11:05:54 +0000
committerefiacor <fiachra.corcoran@est.tech>2019-07-25 11:05:54 +0000
commitf09604a09059d6c3ecf05b253c9058c1a2e81ca2 (patch)
treead5c6e1abffdc7cf30404df8af8b9c11f8d71a0e
parentf20778ffa99aa9c6f30a0f84112a5392b259ea63 (diff)
FINAL unit test covergae commit
Change-Id: Ieb9e9d49931c253b89026ed4884edbdc8d6c6024 Issue-ID: DMAAP-1226 Signed-off-by: efiacor <fiachra.corcoran@est.tech>
-rw-r--r--datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/DeliveryTask.java2
-rw-r--r--datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeConfigManager.java18
-rw-r--r--datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryTaskTest.java48
-rw-r--r--datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/NodeConfigManagerTest.java79
-rw-r--r--datarouter-node/src/test/resources/node_test.properties103
-rwxr-xr-xdatarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProxyServlet.java38
-rw-r--r--datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/ProxyServletTest.java184
7 files changed, 415 insertions, 57 deletions
diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/DeliveryTask.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/DeliveryTask.java
index 7ed35928..193fa65e 100644
--- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/DeliveryTask.java
+++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/DeliveryTask.java
@@ -296,7 +296,7 @@ public class DeliveryTask implements Runnable, Comparable<DeliveryTask> {
* @param httpURLConnection connection used to make request
* @return AN Outpustream that can be used to send your data.
*/
- private OutputStream getOutputStream(HttpURLConnection httpURLConnection) throws IOException {
+ OutputStream getOutputStream(HttpURLConnection httpURLConnection) throws IOException {
OutputStream outputStream = null;
try {
outputStream = httpURLConnection.getOutputStream();
diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeConfigManager.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeConfigManager.java
index 786befce..00922e0a 100644
--- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeConfigManager.java
+++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeConfigManager.java
@@ -24,13 +24,18 @@
package org.onap.dmaap.datarouter.node;
+import static java.lang.System.exit;
+
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import java.io.File;
import java.io.FileInputStream;
+import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
+import java.nio.file.Files;
+import java.util.Objects;
import java.util.Properties;
import java.util.Timer;
import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
@@ -134,13 +139,12 @@ public class NodeConfigManager implements DeliveryQueueHelper {
*/
//Disable and enable protocols*/
enabledprotocols = ((drNodeProperties.getProperty("NodeHttpsProtocols")).trim()).split("\\|");
-
try {
provhost = (new URL(provurl)).getHost();
} catch (Exception e) {
NodeUtils.setIpAndFqdnForEelf(NODE_CONFIG_MANAGER);
eelfLogger.error(EelfMsgs.MESSAGE_BAD_PROV_URL, e, provurl);
- System.exit(1);
+ exit(1);
}
eelfLogger.info("NODE0303 Provisioning server is " + provhost);
eventlogurl = drNodeProperties.getProperty("LogUploadURL", "https://feeds-drtr.web.att.com/internal/logs");
@@ -151,9 +155,11 @@ public class NodeConfigManager implements DeliveryQueueHelper {
spooldir = drNodeProperties.getProperty("SpoolDir", "spool");
File fdir = new File(spooldir + "/f");
fdir.mkdirs();
- for (File junk : fdir.listFiles()) {
- if (junk.isFile()) {
- junk.delete();
+ for (File junk : Objects.requireNonNull(fdir.listFiles())) {
+ try {
+ Files.deleteIfExists(junk.toPath());
+ } catch (IOException e) {
+ eelfLogger.error("NODE0313 Failed to clear junk files from " + fdir.getPath());
}
}
logdir = drNodeProperties.getProperty("LogDir", "logs");
@@ -181,7 +187,7 @@ public class NodeConfigManager implements DeliveryQueueHelper {
NodeUtils.setIpAndFqdnForEelf(NODE_CONFIG_MANAGER);
eelfLogger.error(EelfMsgs.MESSAGE_KEYSTORE_FETCH_ERROR, ksfile);
eelfLogger.error("NODE0309 Unable to fetch canonical name from keystore file " + ksfile);
- System.exit(1);
+ exit(1);
}
eelfLogger.info("NODE0304 My certificate says my name is " + myname);
pid = new PublishId(myname);
diff --git a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryTaskTest.java b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryTaskTest.java
index a0f05779..0123c315 100644
--- a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryTaskTest.java
+++ b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryTaskTest.java
@@ -20,15 +20,9 @@
package org.onap.dmaap.datarouter.node;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.io.OutputStream;
+import java.io.ByteArrayOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@@ -42,14 +36,12 @@ import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({DeliveryTask.class})
+@PrepareForTest({URL.class})
public class DeliveryTaskTest {
@Mock
private DeliveryQueue deliveryQueue;
- private ExecutorService executorService;
-
@Before
public void setUp() throws Exception {
DestInfo destInfo = getPrivDestInfo();
@@ -57,14 +49,13 @@ public class DeliveryTaskTest {
URL url = PowerMockito.mock(URL.class);
HttpURLConnection urlConnection = PowerMockito.mock(HttpURLConnection.class);
- OutputStream outputStream = PowerMockito.mock(OutputStream.class);
- PowerMockito.whenNew(URL.class).withParameterTypes(String.class).withArguments(Mockito.anyString())
- .thenReturn(url);
- PowerMockito.when(urlConnection.getOutputStream()).thenReturn(outputStream);
- PowerMockito.when(url.openConnection()).thenReturn(urlConnection);
+ PowerMockito.whenNew(URL.class).withParameterTypes(String.class).withArguments(Mockito.anyString()).thenReturn(url);
+
+ PowerMockito.when(urlConnection.getOutputStream()).thenReturn(new ByteArrayOutputStream());
PowerMockito.when(urlConnection.getHeaderField(0)).thenReturn("PUT");
PowerMockito.when(urlConnection.getResponseCode()).thenReturn(200);
+ PowerMockito.when(url.openConnection()).thenReturn(urlConnection);
}
@After
@@ -74,8 +65,8 @@ public class DeliveryTaskTest {
@Test
public void Validate_Delivery_Task_Equals() {
- DeliveryTask task = new DeliveryTask(deliveryQueue, "123456789.test-dr-datafile");
- DeliveryTask task2 = new DeliveryTask(deliveryQueue, "123456789.test-dr-datafile");
+ DeliveryTask task = new DeliveryTask(deliveryQueue, "123456789.test-dr-node");
+ DeliveryTask task2 = new DeliveryTask(deliveryQueue, "123456789.test-dr-node");
Assert.assertEquals(task, task2);
Assert.assertEquals(task.hashCode(), task2.hashCode());
Assert.assertEquals(task.toString(), task2.toString());
@@ -91,29 +82,19 @@ public class DeliveryTaskTest {
Assert.assertEquals(task.getFileId(), task2.getFileId());
Assert.assertEquals(task.getAttempts(), task2.getAttempts());
Assert.assertEquals(task.getFollowRedirects(), task2.getFollowRedirects());
-
Assert.assertEquals(0, task.compareTo(task2));
}
@Test
- public void Validate_Delivery_Tasks_Success_For_Standard_File() throws InterruptedException {
+ public void Validate_Delivery_Tasks_Success_For_Standard_File() {
DeliveryTask task = new DeliveryTask(deliveryQueue, "123456789.test-dr-node");
- executorService = Executors.newSingleThreadExecutor();
- executorService.execute(task);
-
- executorService.shutdown();
- executorService.awaitTermination(2, TimeUnit.SECONDS);
+ task.run();
}
@Test
- public void Validate_Delivery_Tasks_Success_For_Compressed_File() throws InterruptedException {
-
+ public void Validate_Delivery_Tasks_Success_For_Compressed_File() {
DeliveryTask task = new DeliveryTask(deliveryQueue, "123456789.test-dr-node.gz");
- executorService = Executors.newSingleThreadExecutor();
- executorService.execute(task);
-
- executorService.shutdown();
- executorService.awaitTermination(2, TimeUnit.SECONDS);
+ task.run();
}
private DestInfo getPrivDestInfo() {
@@ -125,8 +106,9 @@ public class DeliveryTaskTest {
}
private DeliveryQueue mockDelvieryQueue(DestInfo destInfo) {
- DeliveryQueue mockedDeliveryQueue = mock(DeliveryQueue.class);
- when(mockedDeliveryQueue.getDestinationInfo()).thenReturn(destInfo);
+ DeliveryQueue mockedDeliveryQueue = PowerMockito.mock(DeliveryQueue.class);
+ PowerMockito.when(mockedDeliveryQueue.getDestinationInfo()).thenReturn(destInfo);
+ PowerMockito.when(mockedDeliveryQueue.getDestURL(Mockito.anyString())).thenReturn("https://dmaap-dr-node:8443/internal/publish");
return mockedDeliveryQueue;
}
diff --git a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/NodeConfigManagerTest.java b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/NodeConfigManagerTest.java
new file mode 100644
index 00000000..87c2bdf6
--- /dev/null
+++ b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/NodeConfigManagerTest.java
@@ -0,0 +1,79 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.dmaap.datarouter.node;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.URL;
+import org.apache.commons.io.FileUtils;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"javax.net.ssl.*", "javax.security.auth.x500.X500Principal"})
+@PrepareForTest({InetAddress.class, URL.class})
+public class NodeConfigManagerTest {
+
+ private NodeConfigManager nodeConfigManager = NodeConfigManager.getInstance();
+
+ @BeforeClass
+ public static void init() {
+ System.setProperty("org.onap.dmaap.datarouter.node.properties", "src/test/resources/node_test.properties");
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws IOException {
+ FileUtils.deleteDirectory(new File(System.getProperty("user.dir") + "/src/test/resources/spool"));
+ FileUtils.deleteDirectory(new File(System.getProperty("user.dir") + "/src/test/resources/logs"));
+ }
+
+ @Test
+ public void Verify_NodeConfigMan_Getters() {
+ Assert.assertEquals("legacy", nodeConfigManager.getAafInstance());
+ Assert.assertEquals("src/test/resources/spool/f", nodeConfigManager.getSpoolDir());
+ Assert.assertEquals("src/test/resources/spool", nodeConfigManager.getSpoolBase());
+ Assert.assertEquals("jks", nodeConfigManager.getKSType());
+ Assert.assertEquals(8080, nodeConfigManager.getHttpPort());
+ Assert.assertEquals(8443, nodeConfigManager.getHttpsPort());
+ Assert.assertEquals(443, nodeConfigManager.getExtHttpsPort());
+ Assert.assertEquals("dmaap-dr-node", nodeConfigManager.getMyName());
+ Assert.assertEquals("https://dmaap-dr-prov:8443/internal/logs", nodeConfigManager.getEventLogUrl());
+ Assert.assertEquals("src/test/resources/logs/events", nodeConfigManager.getEventLogPrefix());
+ Assert.assertEquals(".log", nodeConfigManager.getEventLogSuffix());
+ Assert.assertEquals("src/test/resources/logs", nodeConfigManager.getLogDir());
+ Assert.assertEquals((86400000L * 30), nodeConfigManager.getLogRetention());
+ Assert.assertEquals(new String[] {"TLSv1.1", "TLSv1.2"}, nodeConfigManager.getEnabledprotocols());
+ Assert.assertEquals("org.onap.dmaap-dr.feed", nodeConfigManager.getAafType());
+ Assert.assertEquals("publish", nodeConfigManager.getAafAction());
+ Assert.assertEquals("https://aaf-onap-test.osaaf.org:8095", nodeConfigManager.getAafURL());
+ Assert.assertFalse(nodeConfigManager.getCadiEnabled());
+ Assert.assertFalse(nodeConfigManager.isShutdown());
+ Assert.assertFalse(nodeConfigManager.isConfigured());
+ }
+
+} \ No newline at end of file
diff --git a/datarouter-node/src/test/resources/node_test.properties b/datarouter-node/src/test/resources/node_test.properties
new file mode 100644
index 00000000..9e0cd994
--- /dev/null
+++ b/datarouter-node/src/test/resources/node_test.properties
@@ -0,0 +1,103 @@
+#-------------------------------------------------------------------------------
+# ============LICENSE_START==================================================
+# * org.onap.dmaap
+# * ===========================================================================
+# * Copyright © 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====================================================
+# *
+# * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+# *
+#-------------------------------------------------------------------------------
+#
+# Configuration parameters set at startup for the DataRouter node
+#
+# URL to retrieve dynamic configuration
+ProvisioningURL = https://dmaap-dr-prov:8443/internal/prov
+#
+# URL to upload PUB/DEL/EXP logs
+LogUploadURL = https://dmaap-dr-prov:8443/internal/logs
+#
+# The port number for http as seen within the server
+IntHttpPort = 8080
+#
+# The port number for https as seen within the server
+IntHttpsPort = 8443
+#
+# The external port number for https taking port mapping into account
+ExtHttpsPort = 443
+#
+# The minimum interval between fetches of the dynamic configuration from the provisioning server
+MinProvFetchInterval = 10000
+#
+# The minimum interval between saves of the redirection data file
+MinRedirSaveInterval = 10000
+#
+# The path to the directory where log files are stored
+LogDir = src/test/resources/logs
+#
+# The retention interval (in days) for log files
+LogRetention = 30
+#
+# The path to the directories where data and meta data files are stored
+SpoolDir = src/test/resources/spool
+#
+# The path to the redirection data file
+RedirectionFile = src/test/redirections.dat
+#
+# The type of keystore for https
+KeyStoreType = jks
+#
+# The path to the keystore for https
+KeyStoreFile = aaf_certs/org.onap.dmaap-dr.jks
+#
+# The password for the https keystore
+KeyStorePassword=WGxd2P6MDo*Bi4+UdzWs{?$8
+#
+# The password for the private key in the https keystore
+KeyPassword=WGxd2P6MDo*Bi4+UdzWs{?$8
+#
+# The type of truststore for https
+TrustStoreType = jks
+#
+# The path to the truststore for https
+TrustStoreFile = aaf_certs/org.onap.dmaap-dr.trust.jks
+#
+# The password for the https truststore
+TrustStorePassword=)OBvCd{e{aWq.^mJJdX:S:1&
+#
+# The path to the file used to trigger an orderly shutdown
+QuiesceFile = etc/SHUTDOWN
+#
+# The key used to generate passwords for node to node transfers
+NodeAuthKey = Node123!
+#
+# DR_NODE DEFAULT ENABLED TLS PROTOCOLS
+NodeHttpsProtocols = TLSv1.1|TLSv1.2
+#
+# AAF type to generate permission string
+AAFType = org.onap.dmaap-dr.feed
+#
+# AAF default instance to generate permission string - default should be legacy
+AAFInstance = legacy
+#
+# AAF action to generate permission string - default should be publish
+AAFAction = publish
+#
+# AAF URL to connect to AAF server
+AafUrl = https://aaf-onap-test.osaaf.org:8095
+#
+# AAF CADI enabled flag
+CadiEnabled = false
+
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProxyServlet.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProxyServlet.java
index 75423602..e47f9fbb 100755
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProxyServlet.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProxyServlet.java
@@ -24,6 +24,8 @@
package org.onap.dmaap.datarouter.provisioning;
+import static org.onap.dmaap.datarouter.provisioning.utils.HttpServletUtils.sendResponseError;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@@ -54,8 +56,6 @@ import org.apache.http.impl.client.DefaultHttpClient;
import org.onap.dmaap.datarouter.provisioning.utils.DB;
import org.onap.dmaap.datarouter.provisioning.utils.URLUtilities;
-import static org.onap.dmaap.datarouter.provisioning.utils.HttpServletUtils.sendResponseError;
-
/**
* This class is the base class for those servlets that need to proxy their requests from the standby to active server.
* Its methods perform the proxy function to the active server. If the active server is not reachable, a 503
@@ -96,7 +96,7 @@ public class ProxyServlet extends BaseServlet {
// We are connecting with the node name, but the certificate will have the CNAME
// So we need to accept a non-matching certificate name
SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore,
- props.getProperty(Main.KEYSTORE_PASS_PROPERTY), trustStore);
+ props.getProperty(Main.KEYSTORE_PASS_PROPERTY), trustStore);
socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
sch = new Scheme("https", 443, socketFactory);
inited = true;
@@ -125,7 +125,7 @@ public class ProxyServlet extends BaseServlet {
* @param req the HTTP request
* @return true or false
*/
- protected boolean isProxyOK(final HttpServletRequest req) {
+ boolean isProxyOK(final HttpServletRequest req) {
String t = req.getQueryString();
if (t != null) {
t = t.replaceAll("&amp;", "&");
@@ -144,7 +144,7 @@ public class ProxyServlet extends BaseServlet {
*
* @return true if this server is the standby (and hence a proxy server).
*/
- public boolean isProxyServer() {
+ boolean isProxyServer() {
SynchronizerTask st = SynchronizerTask.getSynchronizer();
return st.getPodState() == SynchronizerTask.STANDBY_POD;
}
@@ -187,7 +187,7 @@ public class ProxyServlet extends BaseServlet {
*
* @return true if the proxy succeeded
*/
- public boolean doGetWithFallback(HttpServletRequest req, HttpServletResponse resp) {
+ boolean doGetWithFallback(HttpServletRequest req, HttpServletResponse resp) {
boolean rv = false;
if (inited) {
String url = buildUrl(req);
@@ -234,12 +234,8 @@ public class ProxyServlet extends BaseServlet {
// Copy request headers and request body
copyRequestHeaders(req, proxy);
- if ("POST".equals(method) || "PUT".equals(method)) {
- BasicHttpEntity body = new BasicHttpEntity();
- body.setContent(req.getInputStream());
- body.setContentLength(-1); // -1 = unknown
- proxy.setEntity(body);
- }
+
+ handlePutOrPost(req, method, proxy);
// Execute the request
HttpResponse pxyResponse = httpclient.execute(proxy);
@@ -263,6 +259,15 @@ public class ProxyServlet extends BaseServlet {
}
}
+ private void handlePutOrPost(HttpServletRequest req, String method, ProxyHttpRequest proxy) throws IOException {
+ if ("POST".equals(method) || "PUT".equals(method)) {
+ BasicHttpEntity body = new BasicHttpEntity();
+ body.setContent(req.getInputStream());
+ body.setContentLength(-1); // -1 = unknown
+ proxy.setEntity(body);
+ }
+ }
+
private String buildUrl(HttpServletRequest req) {
StringBuilder sb = new StringBuilder("https://");
sb.append(URLUtilities.getPeerPodName());
@@ -275,7 +280,6 @@ public class ProxyServlet extends BaseServlet {
}
private void copyRequestHeaders(HttpServletRequest from, HttpRequestBase to) {
- @SuppressWarnings("unchecked")
List<String> list = Collections.list(from.getHeaderNames());
for (String name : list) {
// Proxy code will add this one
@@ -285,7 +289,7 @@ public class ProxyServlet extends BaseServlet {
}
}
- private void copyResponseHeaders(HttpResponse from, HttpServletResponse to) {
+ void copyResponseHeaders(HttpResponse from, HttpServletResponse to) {
for (Header hdr : from.getAllHeaders()) {
// Don't copy Date: our Jetty will add another Date header
if (!"Date".equals(hdr.getName())) {
@@ -294,7 +298,7 @@ public class ProxyServlet extends BaseServlet {
}
}
- private void copyEntityContent(HttpResponse pxyResponse, HttpServletResponse resp) {
+ void copyEntityContent(HttpResponse pxyResponse, HttpServletResponse resp) {
HttpEntity entity = pxyResponse.getEntity();
if (entity != null) {
try (InputStream in = entity.getContent()) {
@@ -305,11 +309,11 @@ public class ProxyServlet extends BaseServlet {
}
}
- public class ProxyHttpRequest extends HttpEntityEnclosingRequestBase {
+ public static class ProxyHttpRequest extends HttpEntityEnclosingRequestBase {
private final String method;
- public ProxyHttpRequest(final String method, final String uri) {
+ ProxyHttpRequest(final String method, final String uri) {
super();
this.method = method;
setURI(URI.create(uri));
diff --git a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/ProxyServletTest.java b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/ProxyServletTest.java
new file mode 100644
index 00000000..a0442c13
--- /dev/null
+++ b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/ProxyServletTest.java
@@ -0,0 +1,184 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.dmaap.datarouter.provisioning;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.powermock.api.mockito.PowerMockito.when;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.List;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import javax.servlet.ServletConfig;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.http.Header;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.StatusLine;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.conn.scheme.Scheme;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.message.BasicHeader;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.dmaap.datarouter.provisioning.utils.URLUtilities;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+@PowerMockIgnore("javax.net.ssl.*")
+@PrepareForTest({URLUtilities.class, BaseServlet.class, Scheme.class})
+public class ProxyServletTest {
+ private static ProxyServlet proxyServlet;
+ private static EntityManagerFactory emf;
+ private static EntityManager em;
+
+ @Mock
+ private DefaultHttpClient httpClient;
+ @Mock
+ private HttpServletRequest request;
+ @Mock
+ private HttpServletResponse servletResponse;
+ @Mock
+ private CloseableHttpResponse response;
+ @Mock
+ private StatusLine statusLine;
+
+ @BeforeClass
+ public static void init() {
+ emf = Persistence.createEntityManagerFactory("dr-unit-tests");
+ em = emf.createEntityManager();
+ System.setProperty(
+ "org.onap.dmaap.datarouter.provserver.properties",
+ "src/test/resources/h2Database.properties");
+ }
+
+ @AfterClass
+ public static void tearDownClass() {
+ em.clear();
+ em.close();
+ emf.close();
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ proxyServlet = new ProxyServlet();
+ FieldUtils.writeDeclaredField(proxyServlet, "inited", true, true);
+
+ org.apache.http.conn.ssl.SSLSocketFactory sslSocketFactory = PowerMockito.mock(org.apache.http.conn.ssl.SSLSocketFactory.class);
+ Mockito.doNothing().when(sslSocketFactory).setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
+ Scheme scheme = new Scheme("http", 80, sslSocketFactory);
+ FieldUtils.writeDeclaredField(proxyServlet, "sch", scheme, true);
+
+ PowerMockito.mockStatic(BaseServlet.class);
+ PowerMockito.mockStatic(URLUtilities.class);
+ when(URLUtilities.getPeerPodName()).thenReturn("localhost");
+
+ SynchronizerTask synchronizerTask = SynchronizerTask.getSynchronizer();
+ FieldUtils.writeDeclaredField(synchronizerTask, "podState", 2, true);
+ FieldUtils.writeDeclaredStaticField(BaseServlet.class, "synctask", synchronizerTask, true);
+
+ proxyServlet.init(mock(ServletConfig.class));
+ setHeadersForValidRequest();
+ mockHttpClientForGetRequest();
+ }
+
+ @Test
+ public void Given_Request_Is_HTTP_POST_Exception_Is_Thrown() {
+ proxyServlet.doPost(request, servletResponse);
+ }
+
+ @Test
+ public void Given_Request_Is_HTTP_DELETE_Exception_Is_Thrown() {
+ proxyServlet.doDelete(request, servletResponse);
+ }
+
+ @Test
+ public void Given_Request_Is_HTTP_GET_Exception_Is_Thrown() {
+ proxyServlet.doGet(request, servletResponse);
+ }
+
+ @Test
+ public void Given_Request_Is_HTTP_PUT_Exception_Is_Thrown() {
+ proxyServlet.doPut(request, servletResponse);
+ }
+
+ @Test
+ public void Given_Request_Is_HTTP_GetWithFallBack_Exception_Is_Thrown() {
+ proxyServlet.doGetWithFallback(request, servletResponse);
+ }
+
+ @Test
+ public void Veirfy_Headers_Are_Copied() {
+ HttpResponse proxyResponse = PowerMockito.mock(HttpResponse.class);
+ Header[] headersArray = new Header[2];
+ headersArray[0] = new BasicHeader("cache-control", "public, max-age=86400");
+ headersArray[1] = new BasicHeader("content-type", "text/plain");
+ PowerMockito.when(proxyResponse.getAllHeaders()).thenReturn(headersArray);
+ proxyServlet.copyResponseHeaders(proxyResponse, servletResponse);
+ }
+
+ @Test
+ public void Veirfy_EntitiyContent_Copied() throws IOException {
+ HttpResponse proxyResponse = PowerMockito.mock(HttpResponse.class);
+ HttpEntity entity = PowerMockito.mock(HttpEntity.class);
+ PowerMockito.when(proxyResponse.getEntity()).thenReturn(entity);
+ PowerMockito.when(entity.getContent()).thenReturn(new ByteArrayInputStream("blah".getBytes()));
+ proxyServlet.copyEntityContent(proxyResponse, servletResponse);
+ }
+
+ private void setHeadersForValidRequest() {
+ List<String> headers = new ArrayList<>();
+ headers.add("Content-Type");
+ headers.add("X-DMAAP-DR-ON-BEHALF-OF");
+ headers.add("X-DMAAP-DR-META");
+ Enumeration<String> headerNames = Collections.enumeration(headers);
+ Mockito.when(request.getHeaderNames()).thenReturn(headerNames);
+ Enumeration<String> contentTypeHeader = Collections.enumeration(Collections.singletonList("text/plain"));
+ Enumeration<String> behalfHeader = Collections.enumeration(Collections.singletonList("User1"));
+ Enumeration<String> metaDataHeader = Collections.enumeration(Collections.singletonList("?#@><"));
+ Mockito.when(request.getHeaders("Content-Type")).thenReturn(contentTypeHeader);
+ Mockito.when(request.getHeaders("X-DMAAP-DR-ON-BEHALF-OF")).thenReturn(behalfHeader);
+ Mockito.when(request.getHeaders("X-DMAAP-DR-META")).thenReturn(metaDataHeader);
+ }
+
+ private void mockHttpClientForGetRequest() throws Exception {
+ PowerMockito.when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(response);
+ Mockito.when(request.getRequestURI()).thenReturn("/api");
+ Mockito.when(response.getStatusLine()).thenReturn(statusLine);
+ }
+}