diff options
Diffstat (limited to 'datarouter-prov')
13 files changed, 430 insertions, 375 deletions
diff --git a/datarouter-prov/pom.xml b/datarouter-prov/pom.xml index 9ccbb55c..c9c0c2ff 100755 --- a/datarouter-prov/pom.xml +++ b/datarouter-prov/pom.xml @@ -43,6 +43,21 @@ </properties>
<dependencies>
<dependency>
+ <groupId>dom4j</groupId>
+ <artifactId>dom4j</artifactId>
+ <version>${dom4j.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>commons-codec</groupId>
+ <artifactId>commons-codec</artifactId>
+ <version>${commons-codec.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ <version>${google.guava.version}</version>
+ </dependency>
+ <dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${qos.logback.version}</version>
@@ -67,7 +82,7 @@ <dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
- <version>1.5.1</version>
+ <version>${javax.mail-api.version}</version>
</dependency>
<dependency>
<groupId>com.att.eelf</groupId>
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/StatisticsServlet.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/StatisticsServlet.java index 33bf3a35..4917402c 100755 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/StatisticsServlet.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/StatisticsServlet.java @@ -180,39 +180,8 @@ public class StatisticsServlet extends BaseServlet { outputType = req.getParameter("output_type");
}
- try {
-
- String filterQuery = this.queryGeneretor(map);
- eventlogger.debug("SQL Query for Statistics resultset. " + filterQuery);
-
- ResultSet rs = this.getRecordsForSQL(filterQuery);
+ this.getRecordsForSQL(map, outputType, out, resp);
- if (outputType.equals("csv")) {
- resp.setContentType("application/octet-stream");
- Date date = new Date();
- SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY HH:mm:ss");
- resp.setHeader("Content-Disposition",
- "attachment; filename=\"result:" + dateFormat.format(date) + ".csv\"");
- eventlogger.info("Generating CSV file from Statistics resultset");
-
- rsToCSV(rs, out);
- } else {
- eventlogger.info("Generating JSON for Statistics resultset");
- this.rsToJson(rs, out);
- }
- } catch (IOException e) {
- eventlogger.error("IOException - Generating JSON/CSV:" + e);
- e.printStackTrace();
- } catch (JSONException e) {
- eventlogger.error("JSONException - executing SQL query:" + e);
- e.printStackTrace();
- } catch (SQLException e) {
- eventlogger.error("SQLException - executing SQL query:" + e);
- e.printStackTrace();
- } catch (ParseException e) {
- eventlogger.error("ParseException - executing SQL query:" + e);
- e.printStackTrace();
- }
}
@@ -565,21 +534,47 @@ public class StatisticsServlet extends BaseServlet { intlogger.info("Error parsing time=" + s);
return -1;
}
- private ResultSet getRecordsForSQL(String sql) {
- intlogger.debug(sql);
+
+ private void getRecordsForSQL(Map<String, String> map, String outputType, ServletOutputStream out, HttpServletResponse resp) {
+ try {
+
+ String filterQuery = this.queryGeneretor(map);
+ eventlogger.debug("SQL Query for Statistics resultset. " + filterQuery);
+ intlogger.debug(filterQuery);
long start = System.currentTimeMillis();
DB db = new DB();
ResultSet rs = null;
- try (
- Connection conn = db.getConnection()){
- try(PreparedStatement pst = conn.prepareStatement(sql)){
- rs = pst.executeQuery();
+ try (Connection conn = db.getConnection()) {
+ try (PreparedStatement pst = conn.prepareStatement(filterQuery)) {
+ rs = pst.executeQuery();
+ if (outputType.equals("csv")) {
+ resp.setContentType("application/octet-stream");
+ Date date = new Date();
+ SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY HH:mm:ss");
+ resp.setHeader("Content-Disposition",
+ "attachment; filename=\"result:" + dateFormat.format(date) + ".csv\"");
+ eventlogger.info("Generating CSV file from Statistics resultset");
+
+ rsToCSV(rs, out);
+ } else {
+ eventlogger.info("Generating JSON for Statistics resultset");
+ this.rsToJson(rs, out);
}
+ }
} catch (SQLException e) {
- e.printStackTrace();
- }
- intlogger.debug("Time: " + (System.currentTimeMillis() - start) + " ms");
- return rs;
+ e.printStackTrace();
}
+ intlogger.debug("Time: " + (System.currentTimeMillis() - start) + " ms");
+ } catch (IOException e) {
+ eventlogger.error("IOException - Generating JSON/CSV:" + e);
+ e.printStackTrace();
+ } catch (JSONException e) {
+ eventlogger.error("JSONException - executing SQL query:" + e);
+ e.printStackTrace();
+ } catch (ParseException e) {
+ eventlogger.error("ParseException - executing SQL query:" + e);
+ e.printStackTrace();
+ }
}
+}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Subscription.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Subscription.java index 027d859c..1333b55e 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Subscription.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Subscription.java @@ -29,18 +29,13 @@ import java.sql.PreparedStatement; import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
+import java.util.*;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.onap.dmaap.datarouter.provisioning.utils.DB;
import org.onap.dmaap.datarouter.provisioning.utils.URLUtilities;
-import java.util.Properties;
-
/**
* The representation of a Subscription. Subscriptions can be retrieved from the DB, or stored/updated in the DB.
*
@@ -93,14 +88,14 @@ public class Subscription extends Syncable { DB db = new DB();
@SuppressWarnings("resource")
Connection conn = db.getConnection();
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery(sql);
- while (rs.next()) {
- Subscription sub = new Subscription(rs);
- list.add(sub);
+ try(Statement stmt = conn.createStatement()) {
+ try(ResultSet rs = stmt.executeQuery(sql)) {
+ while (rs.next()) {
+ Subscription sub = new Subscription(rs);
+ list.add(sub);
+ }
+ }
}
- rs.close();
- stmt.close();
db.release(conn);
} catch (SQLException e) {
e.printStackTrace();
@@ -114,13 +109,13 @@ public class Subscription extends Syncable { DB db = new DB();
@SuppressWarnings("resource")
Connection conn = db.getConnection();
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery("select MAX(subid) from SUBSCRIPTIONS");
- if (rs.next()) {
- max = rs.getInt(1);
+ try(Statement stmt = conn.createStatement()) {
+ try(ResultSet rs = stmt.executeQuery("select MAX(subid) from SUBSCRIPTIONS")) {
+ if (rs.next()) {
+ max = rs.getInt(1);
+ }
+ }
}
- rs.close();
- stmt.close();
db.release(conn);
} catch (SQLException e) {
intlogger.info("getMaxSubID: " + e.getMessage());
@@ -136,14 +131,14 @@ public class Subscription extends Syncable { DB db = new DB();
@SuppressWarnings("resource")
Connection conn = db.getConnection();
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery(sql);
- while (rs.next()) {
- int subid = rs.getInt("SUBID");
- list.add(URLUtilities.generateSubscriptionURL(subid));
+ try(Statement stmt = conn.createStatement()) {
+ try(ResultSet rs = stmt.executeQuery(sql)) {
+ while (rs.next()) {
+ int subid = rs.getInt("SUBID");
+ list.add(URLUtilities.generateSubscriptionURL(subid));
+ }
+ }
}
- rs.close();
- stmt.close();
db.release(conn);
} catch (SQLException e) {
e.printStackTrace();
@@ -162,13 +157,13 @@ public class Subscription extends Syncable { DB db = new DB();
@SuppressWarnings("resource")
Connection conn = db.getConnection();
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery("select count(*) from SUBSCRIPTIONS");
- if (rs.next()) {
- count = rs.getInt(1);
+ try(Statement stmt = conn.createStatement()) {
+ try(ResultSet rs = stmt.executeQuery("select count(*) from SUBSCRIPTIONS")) {
+ if (rs.next()) {
+ count = rs.getInt(1);
+ }
+ }
}
- rs.close();
- stmt.close();
db.release(conn);
} catch (SQLException e) {
intlogger.warn("PROV0008 countActiveSubscriptions: " + e.getMessage());
@@ -391,11 +386,6 @@ public class Subscription extends Syncable { ps.setInt(10, groupid); //New field is added - Groups feature Rally:US708115 - 1610
ps.execute();
ps.close();
-// ResultSet rs = ps.getGeneratedKeys();
-// rs.first();
-// setSubid(rs.getInt(1)); // side effect - sets the link URLs
-// ps.close();
-
// Update the row to set the URLs
sql = "update SUBSCRIPTIONS set SELF_LINK = ?, LOG_LINK = ? where SUBID = ?";
ps = c.prepareStatement(sql);
@@ -410,7 +400,9 @@ public class Subscription extends Syncable { e.printStackTrace();
} finally {
try {
- ps.close();
+ if(ps!=null) {
+ ps.close();
+ }
} catch (SQLException e) {
e.printStackTrace();
}
@@ -440,7 +432,9 @@ public class Subscription extends Syncable { e.printStackTrace();
} finally {
try {
- ps.close();
+ if(ps!=null) {
+ ps.close();
+ }
} catch (SQLException e) {
e.printStackTrace();
}
@@ -473,7 +467,9 @@ public class Subscription extends Syncable { e.printStackTrace();
} finally {
try {
- ps.close();
+ if(ps!=null) {
+ ps.close();
+ }
} catch (SQLException e) {
e.printStackTrace();
}
@@ -497,7 +493,9 @@ public class Subscription extends Syncable { e.printStackTrace();
} finally {
try {
- ps.close();
+ if(ps!=null) {
+ ps.close();
+ }
} catch (SQLException e) {
e.printStackTrace();
}
@@ -535,6 +533,11 @@ public class Subscription extends Syncable { }
@Override
+ public int hashCode() {
+ return Objects.hash(subid, feedid, groupid, delivery, metadataOnly, subscriber, links, suspended, last_mod, created_date);
+ }
+
+ @Override
public String toString() {
return "SUB: subid=" + subid + ", feedid=" + feedid;
}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java index 1bbf4460..af8bd6d3 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java @@ -339,8 +339,11 @@ public class DRRouteCLI { sb.append("Egress Routing Table\n");
sb.append(String.format("%s Node\n", ext("SubID", cw1)));
for (int i = 0; i < subs.length; i++) {
- String node = ert.getString(subs[i]);
- sb.append(String.format("%s %s\n", ext(subs[i], cw1), node));
+ if(ert!=null&&ert.length()!=0) {
+ String node = ert.getString(subs[i]);
+ sb.append(String.format("%s %s\n", ext(subs[i], cw1), node));
+ }
+
}
}
if (tbl.startsWith("al") || tbl.startsWith("ne")) {
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LogfileLoader.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LogfileLoader.java index 8975f161..110c63de 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LogfileLoader.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LogfileLoader.java @@ -188,6 +188,7 @@ public class LogfileLoader extends Thread { try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
}
idle = false;
} else {
@@ -332,26 +333,25 @@ public class LogfileLoader extends Thread { Connection conn = null;
try {
conn = db.getConnection();
- Statement stmt = conn.createStatement();
- // Build a bitset of all records in the LOG_RECORDS table
- // We need to run this SELECT in stages, because otherwise we run out of memory!
RLEBitSet nbs = new RLEBitSet();
- final long stepsize = 6000000L;
- boolean go_again = true;
- for (long i = 0; go_again; i += stepsize) {
- String sql = String.format("select RECORD_ID from LOG_RECORDS LIMIT %d,%d", i, stepsize);
- try(ResultSet rs = stmt.executeQuery(sql)) {
- go_again = false;
- while (rs.next()) {
- long n = rs.getLong("RECORD_ID");
- nbs.set(n);
- go_again = true;
+ try(Statement stmt = conn.createStatement()) {
+ // Build a bitset of all records in the LOG_RECORDS table
+ // We need to run this SELECT in stages, because otherwise we run out of memory!
+ final long stepsize = 6000000L;
+ boolean go_again = true;
+ for (long i = 0; go_again; i += stepsize) {
+ String sql = String.format("select RECORD_ID from LOG_RECORDS LIMIT %d,%d", i, stepsize);
+ try (ResultSet rs = stmt.executeQuery(sql)) {
+ go_again = false;
+ while (rs.next()) {
+ long n = rs.getLong("RECORD_ID");
+ nbs.set(n);
+ go_again = true;
+ }
}
}
}
- stmt.close();
seq_set = nbs;
-
// Compare with the range for this server
// Determine the next ID for this set of record IDs
RLEBitSet tbs = (RLEBitSet) nbs.clone();
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/URLUtilities.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/URLUtilities.java index b58ab5a0..4576bd26 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/URLUtilities.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/URLUtilities.java @@ -115,7 +115,7 @@ public class URLUtilities { public static String generatePeerLogsURL() {
//Fixes for Itrack ticket - DATARTR-4#Fixing if only one Prov is configured, not to give exception to fill logs.
String peerPodUrl = getPeerPodName();
- if (peerPodUrl.equals("") || peerPodUrl.equals(null)) {
+ if (peerPodUrl.equals("") || peerPodUrl==null) {
return "";
}
diff --git a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/FeedServletTest.java b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/FeedServletTest.java index cb8a28da..78ac0939 100755 --- a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/FeedServletTest.java +++ b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/FeedServletTest.java @@ -26,7 +26,9 @@ import org.apache.commons.lang3.reflect.FieldUtils; import org.jetbrains.annotations.NotNull; import org.json.JSONArray; import org.json.JSONObject; +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; @@ -34,14 +36,17 @@ import org.onap.dmaap.datarouter.authz.AuthorizationResponse; import org.onap.dmaap.datarouter.authz.Authorizer; import org.onap.dmaap.datarouter.provisioning.beans.Feed; import org.onap.dmaap.datarouter.provisioning.beans.Updateable; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; +import org.onap.dmaap.datarouter.provisioning.utils.DB; import org.powermock.modules.junit4.PowerMockRunner; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.sql.SQLException; import java.util.HashSet; import java.util.Set; @@ -51,7 +56,6 @@ import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER; @RunWith(PowerMockRunner.class) -@SuppressStaticInitializationFor("org.onap.dmaap.datarouter.provisioning.beans.Feed") public class FeedServletTest extends DrServletTestBase { private static FeedServlet feedServlet; @@ -61,12 +65,31 @@ public class FeedServletTest extends DrServletTestBase { @Mock private HttpServletResponse response; + private static EntityManagerFactory emf; + private static EntityManager em; + private DB db; + + @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 { - super.setUp(); feedServlet = new FeedServlet(); + db = new DB(); setAuthoriserToReturnRequestIsAuthorized(); - setPokerToNotCreateTimersWhenDeleteFeedIsCalled(); setUpValidAuthorisedRequest(); setUpValidSecurityOnHttpRequest(); setUpValidContentHeadersAndJSONOnHttpRequest(); @@ -76,7 +99,6 @@ public class FeedServletTest extends DrServletTestBase { public void Given_Request_Is_HTTP_DELETE_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated() throws Exception { when(request.isSecure()).thenReturn(false); - FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true); feedServlet.doDelete(request, response); verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class))); } @@ -103,7 +125,7 @@ public class FeedServletTest extends DrServletTestBase { @Test public void Given_Request_Is_HTTP_DELETE_And_Feed_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception { - setFeedToReturnInvalidFeedIdSupplied(); + when(request.getPathInfo()).thenReturn("/123"); feedServlet.doDelete(request, response); verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class))); } @@ -135,20 +157,15 @@ public class FeedServletTest extends DrServletTestBase { @Test public void Given_Request_Is_HTTP_DELETE_And_Delete_On_Database_Succeeds_A_NO_CONTENT_Response_Is_Generated() throws Exception { - FeedServlet feedServlet = new FeedServlet() { - protected boolean doUpdate(Updateable bean) { - return true; - } - }; feedServlet.doDelete(request, response); verify(response).setStatus(eq(HttpServletResponse.SC_NO_CONTENT)); + reinsertFeedIntoDb(); } @Test public void Given_Request_Is_HTTP_GET_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated() throws Exception { when(request.isSecure()).thenReturn(false); - FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true); feedServlet.doGet(request, response); verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class))); } @@ -174,7 +191,7 @@ public class FeedServletTest extends DrServletTestBase { @Test public void Given_Request_Is_HTTP_GET_And_Feed_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception { - setFeedToReturnInvalidFeedIdSupplied(); + when(request.getPathInfo()).thenReturn("/123"); feedServlet.doGet(request, response); verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class))); } @@ -202,7 +219,6 @@ public class FeedServletTest extends DrServletTestBase { public void Given_Request_Is_HTTP_PUT_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated() throws Exception { when(request.isSecure()).thenReturn(false); - FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true); feedServlet.doPut(request, response); verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class))); } @@ -228,7 +244,7 @@ public class FeedServletTest extends DrServletTestBase { @Test public void Given_Request_Is_HTTP_PUT_And_Feed_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception { - setFeedToReturnInvalidFeedIdSupplied(); + when(request.getPathInfo()).thenReturn("/123"); feedServlet.doPut(request, response); verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class))); } @@ -319,8 +335,8 @@ public class FeedServletTest extends DrServletTestBase { FeedServlet feedServlet = new FeedServlet() { protected JSONObject getJSONfromInput(HttpServletRequest req) { JSONObject jo = new JSONObject(); - jo.put("name", "stub_name"); - jo.put("version", "1.0"); + jo.put("name", "Feed1"); + jo.put("version", "v0.1"); jo.put("authorization", JSObject); return jo; } @@ -331,7 +347,7 @@ public class FeedServletTest extends DrServletTestBase { } @Test - public void Given_Request_Is_HTTP_PUT_And_Change_On_Feeds_Fails_A_STATUS_OK_Response_Is_Generated() throws Exception { + public void Given_Request_Is_HTTP_PUT_And_Change_On_Feeds_Fails_An_Internal_Server_Error_Response_Is_Generated() throws Exception { ServletOutputStream outStream = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(outStream); @@ -339,8 +355,8 @@ public class FeedServletTest extends DrServletTestBase { FeedServlet feedServlet = new FeedServlet() { protected JSONObject getJSONfromInput(HttpServletRequest req) { JSONObject jo = new JSONObject(); - jo.put("name", "stub_name"); - jo.put("version", "1.0"); + jo.put("name", "Feed1"); + jo.put("version", "v0.1"); jo.put("authorization", JSObject); return jo; } @@ -362,16 +378,12 @@ public class FeedServletTest extends DrServletTestBase { FeedServlet feedServlet = new FeedServlet() { protected JSONObject getJSONfromInput(HttpServletRequest req) { JSONObject jo = new JSONObject(); - jo.put("name", "stub_name"); - jo.put("version", "1.0"); + jo.put("name", "Feed1"); + jo.put("version", "v0.1"); jo.put("authorization", JSObject); return jo; } - @Override - protected boolean doUpdate(Updateable bean) { - return true; - } }; feedServlet.doPut(request, response); verify(response).setStatus(eq(HttpServletResponse.SC_OK)); @@ -416,24 +428,7 @@ public class FeedServletTest extends DrServletTestBase { } private void setValidPathInfoInHttpHeader() { - when(request.getPathInfo()).thenReturn("/123"); - } - - private void setFeedToReturnInvalidFeedIdSupplied() { - PowerMockito.mockStatic(Feed.class); - PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(null); - } - - private void setFeedToReturnValidFeedForSuppliedId() { - PowerMockito.mockStatic(Feed.class); - Feed feed = mock(Feed.class); - PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(feed); - when(feed.isDeleted()).thenReturn(false); - when(feed.asJSONObject(true)).thenReturn(mock(JSONObject.class)); - when(feed.getPublisher()).thenReturn("Stub_Value"); - when(feed.getName()).thenReturn("stub_name"); - when(feed.getVersion()).thenReturn("1.0"); - when(feed.asLimitedJSONObject()).thenReturn(mock(JSONObject.class)); + when(request.getPathInfo()).thenReturn("/1"); } private void setAuthoriserToReturnRequestNotAuthorized() throws IllegalAccessException { @@ -452,20 +447,22 @@ public class FeedServletTest extends DrServletTestBase { when(authResponse.isAuthorized()).thenReturn(true); } - private void setPokerToNotCreateTimersWhenDeleteFeedIsCalled() throws Exception { - Poker poker = mock(Poker.class); - FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true); - } - private void setUpValidAuthorisedRequest() throws Exception { setUpValidSecurityOnHttpRequest(); setBehalfHeader("Stub_Value"); setValidPathInfoInHttpHeader(); - setFeedToReturnValidFeedForSuppliedId(); } private void setUpValidContentHeadersAndJSONOnHttpRequest() { when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.feed; version=1.0"); when(request.getHeader("X-ATT-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup"); } + + private void reinsertFeedIntoDb() throws SQLException { + Feed feed = new Feed("Feed1","v0.1", "First Feed for testing", "First Feed for testing"); + feed.setFeedid(1); + feed.setGroupid(1); + feed.setDeleted(false); + feed.doUpdate(db.getConnection()); + } }
\ No newline at end of file diff --git a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/RouteServletTest.java b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/RouteServletTest.java index f1082ba3..226dae04 100755 --- a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/RouteServletTest.java +++ b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/RouteServletTest.java @@ -23,21 +23,21 @@ package org.onap.dmaap.datarouter.provisioning; -import org.apache.commons.lang3.reflect.FieldUtils; -import org.json.JSONObject; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +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.onap.dmaap.datarouter.provisioning.beans.*; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.util.SortedSet; -import java.util.TreeSet; + import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Matchers.*; import static org.mockito.Mockito.mock; @@ -45,12 +45,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(PowerMockRunner.class) -@SuppressStaticInitializationFor({"org.onap.dmaap.datarouter.provisioning.beans.IngressRoute", - "org.onap.dmaap.datarouter.provisioning.beans.EgressRoute", - "org.onap.dmaap.datarouter.provisioning.beans.NodeClass", - "org.onap.dmaap.datarouter.provisioning.beans.NetworkRoute"}) -public class RouteServletTest extends DrServletTestBase -{ +public class RouteServletTest { + + private static EntityManagerFactory emf; + private static EntityManager em; private RouteServlet routeServlet; @Mock @@ -59,53 +57,55 @@ public class RouteServletTest extends DrServletTestBase @Mock private HttpServletResponse response; + @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 { - super.setUp(); - setPokerToNotCreateTimersWhenDeleteFeedIsCalled(); - setRouteToReturnValid(); routeServlet = new RouteServlet(); } @Test - public void Given_Request_Is_HTTP_DELETE_And_Is_Not_Authorized() throws Exception { - FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true); + public void Given_Request_Is_HTTP_DELETE_And_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated() + throws Exception { + when(request.getRemoteAddr()).thenReturn("stub_addr"); routeServlet.doDelete(request, response); verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class))); } @Test - public void Given_Request_Is_HTTP_DELETE_And_Ingress_Route_Does_Not_Exist_In_Path() throws Exception { + public void Given_Request_Is_HTTP_DELETE_And_Ingress_Route_Does_Not_Exist_In_Path_Then_Route_Does_Not_Exist_Is_Returned() + throws Exception { when(request.getPathInfo()).thenReturn("/ingress/3/internal/route/"); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doDelete(request, response); verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class))); } @Test - public void Given_Request_Is_HTTP_DELETE_And_Ingress_Path_Contains_Invalid_FeedID() throws Exception { + public void Given_Request_Is_HTTP_DELETE_And_Ingress_Path_Contains_Invalid_FeedID_Then_Feed_Not_Found_Is_Returned() + throws Exception { when(request.getPathInfo()).thenReturn("/ingress/feedID/internal/route/"); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doDelete(request, response); verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class))); } @Test - public void Given_Request_Is_HTTP_DELETE_And_Ingress_Path_Contains_Invalid_Sequence_Number() throws Exception { + public void Given_Request_Is_HTTP_DELETE_And_Ingress_Path_Contains_Invalid_Sequence_Number_Then_Invalid_Sequence_Is_Returned() + throws Exception { when(request.getPathInfo()).thenReturn("/ingress/feedID/"); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doDelete(request, response); verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class))); } @@ -113,11 +113,6 @@ public class RouteServletTest extends DrServletTestBase @Test public void Given_Request_Is_HTTP_DELETE_And_Ingress_Path_Contains_Invalid_Number_Of_Arguments() throws Exception { when(request.getPathInfo()).thenReturn("/ingress/"); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doDelete(request, response); verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class))); } @@ -125,11 +120,6 @@ public class RouteServletTest extends DrServletTestBase @Test public void Given_Request_Is_HTTP_DELETE_And_Egress_Route_Does_Not_Exist_In_Path() throws Exception { when(request.getPathInfo()).thenReturn("/egress/3"); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doDelete(request, response); verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class))); } @@ -137,11 +127,6 @@ public class RouteServletTest extends DrServletTestBase @Test public void Given_Request_Is_HTTP_DELETE_And_Egress_Path_Contains_Invalid_SubID() throws Exception { when(request.getPathInfo()).thenReturn("/egress/subID"); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doDelete(request, response); verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class))); } @@ -149,11 +134,6 @@ public class RouteServletTest extends DrServletTestBase @Test public void Given_Request_Is_HTTP_DELETE_And_Egress_Path_Contains_Invalid_Number_Of_Arguments() throws Exception { when(request.getPathInfo()).thenReturn("/egress/"); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doDelete(request, response); verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class))); } @@ -161,37 +141,20 @@ public class RouteServletTest extends DrServletTestBase @Test public void Given_Request_Is_HTTP_DELETE_And_Network_Path_Contains_Invalid_Number_Of_Arguments() throws Exception { when(request.getPathInfo()).thenReturn("/network/"); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doDelete(request, response); verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class))); } @Test - public void Given_Request_Is_HTTP_DELETE_And_Deletable_Is_Null() throws Exception { + public void Given_Request_Is_HTTP_DELETE_And_Deletable_Is_Null_Then_Bad_Url_Is_Returned() throws Exception { when(request.getPathInfo()).thenReturn("/route/"); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - - @Override - protected boolean doDelete(Deleteable bean) { - return true; - } - }; routeServlet.doDelete(request, response); verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class))); } @Test public void Given_Request_Is_HTTP_DELETE_And_Fails() throws Exception { - when(request.getPathInfo()).thenReturn("/network/subID/route"); - PowerMockito.mockStatic(NodeClass.class); - PowerMockito.when(NodeClass.normalizeNodename(anyString())).thenReturn("stub_val"); + when(request.getPathInfo()).thenReturn("/network/node01/node02"); RouteServlet routeServlet = new RouteServlet() { protected boolean isAuthorizedForInternal(HttpServletRequest req) { return true; @@ -203,12 +166,13 @@ public class RouteServletTest extends DrServletTestBase } }; routeServlet.doDelete(request, response); - verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), argThat(notNullValue(String.class))); + verify(response) + .sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), argThat(notNullValue(String.class))); } @Test public void Given_Request_Is_HTTP_GET_And_Is_Not_Authorized() throws Exception { - FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true); + when(request.getRemoteAddr()).thenReturn("stub_addr"); routeServlet.doGet(request, response); verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class))); } @@ -216,11 +180,6 @@ public class RouteServletTest extends DrServletTestBase @Test public void Given_Request_Is_HTTP_GET_And_Path_Does_Not_Start_With_Valid_Route() throws Exception { when(request.getPathInfo()).thenReturn("/route/"); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doGet(request, response); verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class))); } @@ -229,14 +188,8 @@ public class RouteServletTest extends DrServletTestBase @Test public void Given_Request_Is_HTTP_GET_And_Path_Equals_Ingress_And_Get_Succeeds() throws Exception { when(request.getPathInfo()).thenReturn("/ingress/"); - when(request.getRemoteAddr()).thenReturn("stub_addr"); ServletOutputStream outStream = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(outStream); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doGet(request, response); verify(response).setStatus(eq(HttpServletResponse.SC_OK)); } @@ -244,14 +197,8 @@ public class RouteServletTest extends DrServletTestBase @Test public void Given_Request_Is_HTTP_GET_And_Path_Equals_Egress_And_Get_Succeeds() throws Exception { when(request.getPathInfo()).thenReturn("/egress/"); - when(request.getRemoteAddr()).thenReturn("stub_addr"); ServletOutputStream outStream = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(outStream); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doGet(request, response); verify(response).setStatus(eq(HttpServletResponse.SC_OK)); } @@ -259,32 +206,21 @@ public class RouteServletTest extends DrServletTestBase @Test public void Given_Request_Is_HTTP_GET_And_Ingress_Path_Equals_Network_And_Get_Succeeds() throws Exception { when(request.getPathInfo()).thenReturn("/network/"); - when(request.getRemoteAddr()).thenReturn("stub_addr"); ServletOutputStream outStream = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(outStream); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doGet(request, response); verify(response).setStatus(eq(HttpServletResponse.SC_OK)); } @Test public void Given_Request_Is_HTTP_PUT_And_Is_Not_Authorized() throws Exception { - FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true); + when(request.getRemoteAddr()).thenReturn("stub_addr"); routeServlet.doPut(request, response); verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class))); } @Test public void Given_Request_Is_HTTP_PUT_And_Contains_Bad_URL() throws Exception { - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doPut(request, response); verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class))); } @@ -292,55 +228,38 @@ public class RouteServletTest extends DrServletTestBase @Test public void Given_Request_Is_HTTP_POST_And_Is_Not_Authorized() throws Exception { - FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true); + when(request.getRemoteAddr()).thenReturn("stub_addr"); routeServlet.doPost(request, response); verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class))); } @Test - public void Given_Request_Is_HTTP_POST_And_Ingress_Path_Starts_With_Ingress_And_Contains_Invalid_Arguments() throws Exception { + public void Given_Request_Is_HTTP_POST_And_Ingress_Path_Starts_With_Ingress_And_Contains_Invalid_Arguments() + throws Exception { when(request.getPathInfo()).thenReturn("/ingress/"); - when(request.getRemoteAddr()).thenReturn("stub_addr"); when(request.getParameter("feed")).thenReturn("3"); when(request.getParameter("user")).thenReturn(null); when(request.getParameter("subnet")).thenReturn(null); when(request.getParameter("nodepatt")).thenReturn(null); when(request.getParameter("seq")).thenReturn(null); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doPost(request, response); verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class))); } @Test - public void Given_Request_Is_HTTP_POST_And_Path_Starts_With_Egress_And_EgressRoute_Already_Exists() throws Exception { + public void Given_Request_Is_HTTP_POST_And_Path_Starts_With_Egress_And_EgressRoute_Already_Exists() + throws Exception { when(request.getPathInfo()).thenReturn("/egress/"); - when(request.getRemoteAddr()).thenReturn("stub_addr"); - when(request.getParameter("sub")).thenReturn("3"); - EgressRoute e = mock(EgressRoute.class); - PowerMockito.when(EgressRoute.getEgressRoute(anyInt())).thenReturn(e); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; + when(request.getParameter("sub")).thenReturn("1"); routeServlet.doPost(request, response); verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class))); } @Test - public void Given_Request_Is_HTTP_POST_And_Path_Starts_With_Egress_And_Contains_Invalid_Arguments() throws Exception { + public void Given_Request_Is_HTTP_POST_And_Path_Starts_With_Egress_And_Contains_Invalid_Arguments() + throws Exception { when(request.getPathInfo()).thenReturn("/egress/"); - when(request.getRemoteAddr()).thenReturn("stub_addr"); when(request.getParameter("sub")).thenReturn("3"); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doPost(request, response); verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class))); } @@ -348,12 +267,6 @@ public class RouteServletTest extends DrServletTestBase @Test public void Given_Request_Is_HTTP_POST_And_Path_Starts_With_Network_And_Is_Missing_Arguments() throws Exception { when(request.getPathInfo()).thenReturn("/network/"); - when(request.getRemoteAddr()).thenReturn("stub_addr"); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doPost(request, response); verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class))); } @@ -361,20 +274,9 @@ public class RouteServletTest extends DrServletTestBase @Test public void Given_Request_Is_HTTP_POST_And_Path_Starts_With_Network_And_Route_Already_Exists() throws Exception { when(request.getPathInfo()).thenReturn("/network/"); - when(request.getRemoteAddr()).thenReturn("stub_addr"); when(request.getParameter("from")).thenReturn("stub_from"); when(request.getParameter("to")).thenReturn("stub_to"); when(request.getParameter("via")).thenReturn("stub_via"); - PowerMockito.mockStatic(NodeClass.class); - PowerMockito.when(NodeClass.normalizeNodename(anyString())).thenReturn("stub_val"); - SortedSet<NetworkRoute> networkSet = new TreeSet(); - networkSet.add(mock(NetworkRoute.class)); - PowerMockito.when(NetworkRoute.getAllNetworkRoutes()).thenReturn(networkSet); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doPost(request, response); verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class))); } @@ -382,17 +284,9 @@ public class RouteServletTest extends DrServletTestBase @Test public void Given_Request_Is_HTTP_POST_And_Path_URL_Is_Null() throws Exception { when(request.getPathInfo()).thenReturn("/route/"); - when(request.getRemoteAddr()).thenReturn("stub_addr"); when(request.getParameter("from")).thenReturn("stub_from"); when(request.getParameter("to")).thenReturn("stub_to"); when(request.getParameter("via")).thenReturn("stub_via"); - PowerMockito.mockStatic(NodeClass.class); - PowerMockito.when(NodeClass.normalizeNodename(anyString())).thenReturn("stub_val"); - RouteServlet routeServlet = new RouteServlet() { - protected boolean isAuthorizedForInternal(HttpServletRequest req) { - return true; - } - }; routeServlet.doPost(request, response); verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class))); } @@ -400,12 +294,9 @@ public class RouteServletTest extends DrServletTestBase @Test public void Given_Request_Is_HTTP_POST_And_Fails() throws Exception { when(request.getPathInfo()).thenReturn("/network/"); - when(request.getRemoteAddr()).thenReturn("stub_addr"); - when(request.getParameter("from")).thenReturn("stub_from"); - when(request.getParameter("to")).thenReturn("stub_to"); - when(request.getParameter("via")).thenReturn("stub_via"); - PowerMockito.mockStatic(NodeClass.class); - PowerMockito.when(NodeClass.normalizeNodename(anyString())).thenReturn("stub_val"); + when(request.getParameter("from")).thenReturn("node01"); + when(request.getParameter("to")).thenReturn("node02"); + when(request.getParameter("via")).thenReturn("node03"); RouteServlet routeServlet = new RouteServlet() { protected boolean isAuthorizedForInternal(HttpServletRequest req) { return true; @@ -416,39 +307,9 @@ public class RouteServletTest extends DrServletTestBase return false; } }; - routeServlet.doPost(request, response); - verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), argThat(notNullValue(String.class))); - } - private void setRouteToReturnValid() throws IllegalAccessException { - PowerMockito.mockStatic(IngressRoute.class); - PowerMockito.when(IngressRoute.getIngressRoute(anyInt(), anyString(), anyString())).thenReturn(null); - SortedSet<IngressRoute> ingressSet = new TreeSet(); - IngressRoute ingressRoute = mock(IngressRoute.class); - JSONObject joIngress = mock(JSONObject.class); - when(joIngress.toString()).thenReturn("{}"); - when(ingressRoute.asJSONObject()).thenReturn(joIngress); - ingressSet.add(ingressRoute); - PowerMockito.when(IngressRoute.getAllIngressRoutes()).thenReturn(ingressSet); - - PowerMockito.mockStatic(EgressRoute.class); - PowerMockito.when(EgressRoute.getEgressRoute(anyInt())).thenReturn(null); - SortedSet<EgressRoute> egressSet = new TreeSet(); - EgressRoute egressRoute = mock(EgressRoute.class); - JSONObject joEgress = mock(JSONObject.class); - when(joEgress.toString()).thenReturn("{}"); - when(egressRoute.asJSONObject()).thenReturn(joEgress); - egressSet.add(egressRoute); - PowerMockito.when(EgressRoute.getAllEgressRoutes()).thenReturn(egressSet); - - PowerMockito.mockStatic(NetworkRoute.class); - SortedSet<NetworkRoute> networkSet = new TreeSet(); - PowerMockito.when(NetworkRoute.getAllNetworkRoutes()).thenReturn(networkSet); - - } - - private void setPokerToNotCreateTimersWhenDeleteFeedIsCalled() throws Exception { - Poker poker = mock(Poker.class); - FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true); + routeServlet.doPost(request, response); + verify(response) + .sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), argThat(notNullValue(String.class))); } } diff --git a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/StatisticsServletTest.java b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/StatisticsServletTest.java index 0babdc47..64d13e94 100755 --- a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/StatisticsServletTest.java +++ b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/StatisticsServletTest.java @@ -23,32 +23,35 @@ package org.onap.dmaap.datarouter.provisioning; import static org.hamcrest.Matchers.notNullValue; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doCallRealMethod; -import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + +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.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; +import org.onap.dmaap.datarouter.provisioning.utils.DB; import org.powermock.modules.junit4.PowerMockRunner; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + @RunWith(PowerMockRunner.class) -@PrepareForTest(StatisticsServlet.class) -public class StatisticsServletTest extends DrServletTestBase { +public class StatisticsServletTest { private StatisticsServlet statisticsServlet; @@ -58,10 +61,31 @@ public class StatisticsServletTest extends DrServletTestBase { @Mock private HttpServletResponse response; + private DB db; + + private static EntityManagerFactory emf; + private static EntityManager em; + + @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 { - super.setUp(); statisticsServlet = new StatisticsServlet(); + db = new DB(); buildRequestParameters(); } @@ -101,15 +125,9 @@ public class StatisticsServletTest extends DrServletTestBase { @Test public void Given_Request_Is_HTTP_GET_With_GroupId_But_No_FeedId_Parameters_Then_Request_Succeeds() throws Exception { + addAliasForSubstringIndex(); ServletOutputStream outStream = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(outStream); - statisticsServlet = PowerMockito.mock(StatisticsServlet.class); - PowerMockito.doReturn(null).when(statisticsServlet, "getRecordsForSQL", anyString()); - PowerMockito.doCallRealMethod().when(statisticsServlet, "buildMapFromRequest", anyObject()); - PowerMockito.doCallRealMethod().when(statisticsServlet, "getTimeFromParam", anyString()); - doNothing().when(statisticsServlet).rsToCSV(anyObject(), anyObject()); - doCallRealMethod().when(statisticsServlet).doGet(request, response); - when(statisticsServlet.getFeedIdsByGroupId(anyInt())).thenReturn(new StringBuffer("1")); statisticsServlet.doGet(request, response); verify(response).setStatus(eq(HttpServletResponse.SC_OK)); } @@ -117,18 +135,11 @@ public class StatisticsServletTest extends DrServletTestBase { @Test public void Given_Request_Is_HTTP_GET_With_GroupId_And_FeedId_Parameters_Then_Request_Succeeds() throws Exception { + addAliasForSubstringIndex(); when(request.getParameter("feedid")).thenReturn("1"); when(request.getParameter("statusCode")).thenReturn("500"); ServletOutputStream outStream = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(outStream); - statisticsServlet = PowerMockito.mock(StatisticsServlet.class); - PowerMockito.doReturn(null).when(statisticsServlet, "getRecordsForSQL", anyString()); - PowerMockito.doCallRealMethod().when(statisticsServlet, "buildMapFromRequest", anyObject()); - PowerMockito.doCallRealMethod().when(statisticsServlet, "getTimeFromParam", anyString()); - doNothing().when(statisticsServlet).rsToCSV(anyObject(), anyObject()); - doCallRealMethod().when(statisticsServlet).doGet(request, response); - doCallRealMethod().when(statisticsServlet).queryGeneretor(anyObject()); - when(statisticsServlet.getFeedIdsByGroupId(anyInt())).thenReturn(new StringBuffer("1")); statisticsServlet.doGet(request, response); verify(response).setStatus(eq(HttpServletResponse.SC_OK)); } @@ -147,4 +158,10 @@ public class StatisticsServletTest extends DrServletTestBase { when(request.getParameter("groupid")).thenReturn("1"); when(request.getParameter("subid")).thenReturn("1"); } + private void addAliasForSubstringIndex() throws SQLException { + String sql = "CREATE ALIAS IF NOT EXISTS `SUBSTRING_INDEX`AS $$ String Function(String one, String two, String three){ return \"url\"; }$$;"; + Connection conn = db.getConnection(); + PreparedStatement pst = conn.prepareStatement(sql); + pst.execute(); + } } diff --git a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/SubscriptionServletTest.java b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/SubscriptionServletTest.java index d2e3ccc0..472be512 100755 --- a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/SubscriptionServletTest.java +++ b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/SubscriptionServletTest.java @@ -62,6 +62,9 @@ public class SubscriptionServletTest { private static EntityManager em; private SubscriptionServlet subscriptionServlet; private DB db; + private final String URL= "https://172.100.0.5"; + private final String USER = "user1"; + private final String PASSWORD="password1"; @Mock private HttpServletRequest request; @@ -324,6 +327,7 @@ public class SubscriptionServletTest { }; subscriptionServlet.doPut(request, response); verify(response).setStatus(eq(HttpServletResponse.SC_OK)); + changeSubscriptionBackToNormal(); } @Test @@ -475,15 +479,29 @@ public class SubscriptionServletTest { } private void insertSubscriptionIntoDb() throws SQLException { - Subscription subscription = new Subscription("https://172.100.0.5", "user1", "password1"); + Subscription subscription = new Subscription(URL, USER, PASSWORD); subscription.setSubid(1); subscription.setSubscriber("user1"); subscription.setFeedid(1); - SubDelivery subDelivery = new SubDelivery("https://172.100.0.5:8080", "user1", "password1", true); + SubDelivery subDelivery = new SubDelivery(URL, USER, PASSWORD, true); subscription.setDelivery(subDelivery); subscription.setGroupid(1); subscription.setMetadataOnly(false); subscription.setSuspended(false); subscription.doInsert(db.getConnection()); } + + private void changeSubscriptionBackToNormal() throws SQLException { + Subscription subscription = new Subscription("https://172.100.0.5", "user1", "password1"); + subscription.setSubid(1); + subscription.setSubscriber("user1"); + subscription.setFeedid(1); + SubDelivery subDelivery = new SubDelivery(URL, USER, PASSWORD, true); + subscription.setDelivery(subDelivery); + subscription.setGroupid(1); + subscription.setMetadataOnly(false); + subscription.setSuspended(false); + subscription.changeOwnerShip(); + subscription.doUpdate(db.getConnection()); + } }
\ No newline at end of file diff --git a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/beans/FeedTest.java b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/beans/FeedTest.java new file mode 100644 index 00000000..907aa93b --- /dev/null +++ b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/beans/FeedTest.java @@ -0,0 +1,117 @@ +/******************************************************************************* + * ============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. + * * + ******************************************************************************/ +package org.onap.dmaap.datarouter.provisioning.beans; + +import org.json.JSONObject; +import org.junit.*; +import org.junit.runner.RunWith; +import org.onap.dmaap.datarouter.provisioning.utils.DB; +import org.powermock.modules.junit4.PowerMockRunner; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import java.io.InvalidObjectException; +import java.sql.SQLException; +import java.util.List; + +@RunWith(PowerMockRunner.class) +public class FeedTest { + private static EntityManagerFactory emf; + private static EntityManager em; + private Feed feed; + private DB db; + + @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 { + db = new DB(); + feed = new Feed("Feed1","v0.1", "First Feed for testing", "First Feed for testing"); + feed.setFeedid(1); + feed.setGroupid(1); + feed.setPublisher("pub"); + feed.setDeleted(false); + } + + @Test + public void Given_getFilteredFeedUrlList_With_Name_Then_Method_Returns_Self_Links() { + List<String> list= feed.getFilteredFeedUrlList("name","Feed1"); + Assert.assertEquals("self_link",list.get(0)); + } + + @Test + public void Given_getFilteredFeedUrlList_With_Publ_Then_Method_Returns_Self_Links() { + List<String> list= feed.getFilteredFeedUrlList("publ","pub"); + Assert.assertEquals("self_link",list.get(0)); + } + + @Test + public void Given_getFilteredFeedUrlList_With_Subs_Then_Method_Returns_Self_Links() { + List<String> list= feed.getFilteredFeedUrlList("subs","sub123"); + Assert.assertEquals("self_link",list.get(0)); + } + + @Test + public void Given_doDelete_Succeeds_Then_doInsert_To_Put_Feed_Back_And_Bool_Is_True() throws SQLException, InvalidObjectException { + Boolean bool = feed.doDelete(db.getConnection()); + Assert.assertEquals(true, bool); + JSONObject jo = new JSONObject(); + jo.put("self","self_link"); + jo.put("publish","publish_link"); + jo.put("subscribe","subscribe_link"); + jo.put("log","log_link"); + feed.setLinks(new FeedLinks(jo)); + bool = feed.doInsert(db.getConnection()); + Assert.assertEquals(true, bool); + } + + @Test + public void Validate_ChaneOwnerShip_Returns_True() + { + Boolean bool = feed.changeOwnerShip(); + Assert.assertEquals(true, bool); + } + + @Test + public void Given_Feeds_Are_Equal_Then_Equals_Returns_True() + { + Feed feed2 = feed; + Boolean bool = feed.equals(feed2); + Assert.assertEquals(true, bool); + } +}
\ No newline at end of file diff --git a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/beans/GroupTest.java b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/beans/GroupTest.java index 91d72af7..b785fdc2 100644 --- a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/beans/GroupTest.java +++ b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/beans/GroupTest.java @@ -23,7 +23,9 @@ package org.onap.dmaap.datarouter.provisioning.beans; import org.junit.*; +import org.junit.runner.RunWith; import org.onap.dmaap.datarouter.provisioning.utils.DB; +import org.powermock.modules.junit4.PowerMockRunner; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; @@ -32,6 +34,7 @@ import java.util.Collection; import java.util.Date; import java.util.List; +@RunWith(PowerMockRunner.class) public class GroupTest { private static EntityManagerFactory emf; private static EntityManager em; diff --git a/datarouter-prov/src/test/resources/create.sql b/datarouter-prov/src/test/resources/create.sql index c72c42a1..cd87dde0 100755 --- a/datarouter-prov/src/test/resources/create.sql +++ b/datarouter-prov/src/test/resources/create.sql @@ -151,6 +151,9 @@ VALUES (1, 1, 'https://172.100.0.5:8080', 'user1', 'password1', true, false, 'us INSERT INTO SUBSCRIPTIONS(SUBID, FEEDID, DELIVERY_URL, DELIVERY_USER, DELIVERY_PASSWORD, SUBSCRIBER, SELF_LINK, LOG_LINK) VALUES (23, 1, 'http://delivery_url', 'user1', 'somepassword', 'sub123', 'selflink', 'loglink'); +INSERT INTO FEED_ENDPOINT_IDS(FEEDID, USERID, PASSWORD) +VALUES (1, 'USER', 'PASSWORD'); + INSERT INTO FEEDS(FEEDID, GROUPID, NAME, VERSION, DESCRIPTION, BUSINESS_DESCRIPTION, AUTH_CLASS, PUBLISHER, SELF_LINK, PUBLISH_LINK, SUBSCRIBE_LINK, LOG_LINK) VALUES (1, 1,'Feed1','v0.1', 'First Feed for testing', 'First Feed for testing', 'auth_class', 'pub','self_link','publish_link','subscribe_link','log_link'); @@ -161,4 +164,27 @@ insert into INGRESS_ROUTES(SEQUENCE, FEEDID , USERID, SUBNET, NODESET) VALUES (2,1,'user',null,2); insert into NODESETS(SETID, NODEID) -VALUES (2,0);
\ No newline at end of file +VALUES (2,2); + +insert into LOG_RECORDS(RECORD_ID,TYPE,EVENT_TIME,PUBLISH_ID,FEEDID,REQURI,METHOD,CONTENT_TYPE,CONTENT_LENGTH,FEED_FILEID,REMOTE_ADDR,USER,STATUS,DELIVERY_SUBID,DELIVERY_FILEID,RESULT,ATTEMPTS,REASON) +VALUES(1,'pub',2536159564422,'ID',1,'URL','GET','application/vnd.att-dr.log-list; version=1.0',100,1,'172.0.0.8','user',204,1,1,204,0,'other'); + +CREATE ALIAS IF NOT EXISTS `SUBSTRING_INDEX` AS $$ + String Function(String one, String two, String three){ + return "url"; + } +$$; + +insert into NETWORK_ROUTES(FROMNODE, TONODE, VIANODE) +VALUES (1, 3, 2); + +insert into NODES(NODEID, NAME) values + (1, 'stub_from.'), + (2, 'stub_via.'), + (3, 'stub_to.'), + (4, 'node01.'), + (5, 'node02.'), + (6, 'node03.') +; +insert into EGRESS_ROUTES(SUBID, NODEID) values (1, 1); + |