summaryrefslogtreecommitdiffstats
path: root/datarouter-prov
diff options
context:
space:
mode:
Diffstat (limited to 'datarouter-prov')
-rwxr-xr-xdatarouter-prov/pom.xml8
-rwxr-xr-xdatarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/BaseServlet.java7
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/DeliveryExtraRecord.java1
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/EgressRoute.java124
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Group.java136
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/IngressRoute.java266
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Insertable.java3
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/JSONable.java3
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/LOGJSONable.java3
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Loadable.java3
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/NetworkRoute.java115
-rwxr-xr-xdatarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/NodeClass.java109
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Parameters.java136
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DB.java82
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LOGJSONObject.java371
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LogfileLoader.java87
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/PurgeLogDirTask.java24
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/URLUtilities.java43
-rw-r--r--datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/InternalServletTest.java28
-rw-r--r--datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/beans/EgressRouteTest.java90
-rw-r--r--datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/beans/NetworkRouteTest.java96
-rw-r--r--datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/utils/DbTest.java61
-rwxr-xr-xdatarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/utils/LOGJSONObjectTest.java182
-rw-r--r--datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/utils/PurgeLogDirTaskTest.java87
-rwxr-xr-xdatarouter-prov/src/test/resources/META-INF/persistence.xml14
-rwxr-xr-xdatarouter-prov/src/test/resources/create.sql4
-rwxr-xr-xdatarouter-prov/src/test/resources/h2Database.properties1
-rwxr-xr-xdatarouter-prov/src/test/resources/sql_init_01.sql146
28 files changed, 1174 insertions, 1056 deletions
diff --git a/datarouter-prov/pom.xml b/datarouter-prov/pom.xml
index cbcfc71f..7a464fc0 100755
--- a/datarouter-prov/pom.xml
+++ b/datarouter-prov/pom.xml
@@ -37,7 +37,9 @@
<docker.location>${basedir}/target/${project.artifactId}</docker.location>
<datarouter.prov.image.name>${docker.image.root}${project.artifactId}</datarouter.prov.image.name>
<sonar.exclusions>**/src/main/java/org/onap/dmaap/datarouter/reports/**,
- **/src/main/java/org/onap/dmaap/authz/impl/AuthRespSupplementImpl.java</sonar.exclusions>
+ src/main/java/org/onap/dmaap/datarouter/authz/impl/AuthRespSupplementImpl.java,
+ src/main/java/org/onap/dmaap/datarouter/provisioning/Main.java,
+ src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java</sonar.exclusions>
<sonar.language>java</sonar.language>
<sonar.skip>false</sonar.skip>
</properties>
@@ -436,7 +438,9 @@
<configuration>
<excludes>
<exclude>**/src/main/java/org/onap/dmaap/datarouter/reports/**</exclude>
- <exclude>**/src/main/java/org/onap/dmaap/authz/impl/AuthRespSupplementImpl.java</exclude>
+ <exclude>src/main/java/org/onap/dmaap/datarouter/authz/impl/AuthRespSupplementImpl.java</exclude>
+ <exclude>src/main/java/org/onap/dmaap/datarouter/provisioning/Main.java</exclude>
+ <exclude>src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java</exclude>
</excludes>
</configuration>
</plugin>
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/BaseServlet.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/BaseServlet.java
index c6b1cde7..e730db4a 100755
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/BaseServlet.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/BaseServlet.java
@@ -203,10 +203,6 @@ public class BaseServlet extends HttpServlet implements ProvDataProvider {
*/
private static String[] nodes = new String[0];
/**
- * [DATARTR-27] Poke all the DR nodes : Array of nodes names and/or FQDNs.
- */
- private static String[] drnodes = new String[0];
- /**
* Array of node IP addresses.
*/
private static InetAddress[] nodeAddresses = new InetAddress[0];
@@ -566,9 +562,6 @@ public class BaseServlet extends HttpServlet implements ProvDataProvider {
}
}
- //[DATARTR-27] Poke all the DR nodes: assigning DR Nodes
- drnodes = nodes.clone();
-
//Reset Nodes arr after - removing static routing Nodes, Rally Userstory - US664862 .
List<String> filterNodes = new ArrayList<>();
for (String node : nodes) {
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/DeliveryExtraRecord.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/DeliveryExtraRecord.java
index 0e5342a6..0a5258e2 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/DeliveryExtraRecord.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/DeliveryExtraRecord.java
@@ -25,7 +25,6 @@
package org.onap.dmaap.datarouter.provisioning.beans;
import java.sql.PreparedStatement;
-import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.text.ParseException;
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/EgressRoute.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/EgressRoute.java
index e766e704..a78a9c18 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/EgressRoute.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/EgressRoute.java
@@ -24,6 +24,8 @@
package org.onap.dmaap.datarouter.provisioning.beans;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@@ -32,9 +34,6 @@ import java.sql.Statement;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
import org.json.JSONObject;
import org.onap.dmaap.datarouter.provisioning.utils.DB;
@@ -47,10 +46,22 @@ import org.onap.dmaap.datarouter.provisioning.utils.DB;
public class EgressRoute extends NodeClass implements Comparable<EgressRoute> {
private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");
- private static final String SQLEXCEPTION = "SQLException: ";
private final int subid;
private final int nodeid;
+ public EgressRoute(int subid, int nodeid) {
+ this.subid = subid;
+ this.nodeid = nodeid;
+ // Note: unlike for Feeds, it subscriptions can be removed from the tables, so it is
+ // possible that an orphan ERT entry can exist if a sub is removed.
+ // if (Subscription.getSubscriptionById(subid) == null)
+ // throw new IllegalArgumentException("No such subscription: "+subid);
+ }
+
+ public EgressRoute(int subid, String node) {
+ this(subid, lookupNodeName(node));
+ }
+
/**
* Get a set of all Egress Routes in the DB. The set is sorted according to the natural sorting order of the routes
* (based on the subscription ID in each route).
@@ -59,27 +70,30 @@ public class EgressRoute extends NodeClass implements Comparable<EgressRoute> {
*/
public static SortedSet<EgressRoute> getAllEgressRoutes() {
SortedSet<EgressRoute> set = new TreeSet<>();
- try {
- DB db = new DB();
- @SuppressWarnings("resource")
- Connection conn = db.getConnection();
+ DB db = new DB();
+ String sql = "select SUBID, NODEID from EGRESS_ROUTES";
+ try (Connection conn = db.getConnection()) {
try (Statement stmt = conn.createStatement()) {
- try (ResultSet rs = stmt.executeQuery("select SUBID, NODEID from EGRESS_ROUTES")) {
- while (rs.next()) {
- int subid = rs.getInt("SUBID");
- int nodeid = rs.getInt("NODEID");
- set.add(new EgressRoute(subid, nodeid));
- }
+ try (ResultSet rs = stmt.executeQuery(sql)) {
+ addEgressRouteToSet(set, rs);
}
+ } finally {
+ db.release(conn);
}
-
- db.release(conn);
} catch (SQLException e) {
intlogger.error("PROV0008 EgressRoute.getAllEgressRoutes: " + e.getMessage(), e);
}
return set;
}
+ private static void addEgressRouteToSet(SortedSet<EgressRoute> set, ResultSet rs) throws SQLException {
+ while (rs.next()) {
+ int subid = rs.getInt("SUBID");
+ int nodeid = rs.getInt("NODEID");
+ set.add(new EgressRoute(subid, nodeid));
+ }
+ }
+
/**
* Get a single Egress Route for the subscription <i>sub</i>.
*
@@ -88,69 +102,35 @@ public class EgressRoute extends NodeClass implements Comparable<EgressRoute> {
*/
public static EgressRoute getEgressRoute(int sub) {
EgressRoute v = null;
- PreparedStatement ps = null;
- try {
- DB db = new DB();
- @SuppressWarnings("resource")
- Connection conn = db.getConnection();
- String sql = "select NODEID from EGRESS_ROUTES where SUBID = ?";
- ps = conn.prepareStatement(sql);
+ DB db = new DB();
+ String sql = "select NODEID from EGRESS_ROUTES where SUBID = ?";
+ try (Connection conn = db.getConnection();
+ PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, sub);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
int node = rs.getInt("NODEID");
v = new EgressRoute(sub, node);
}
+ } finally {
+ db.release(conn);
}
- ps.close();
- db.release(conn);
} catch (SQLException e) {
intlogger.error("PROV0009 EgressRoute.getEgressRoute: " + e.getMessage(), e);
- } finally {
- try {
- if (ps != null) {
- ps.close();
- }
- } catch (SQLException e) {
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);
- }
}
return v;
}
- public EgressRoute(int subid, int nodeid) {
- this.subid = subid;
- this.nodeid = nodeid;
-// Note: unlike for Feeds, it subscriptions can be removed from the tables, so it is
-// possible that an orphan ERT entry can exist if a sub is removed.
-// if (Subscription.getSubscriptionById(subid) == null)
-// throw new IllegalArgumentException("No such subscription: "+subid);
- }
-
- public EgressRoute(int subid, String node) {
- this(subid, lookupNodeName(node));
- }
-
@Override
public boolean doDelete(Connection c) {
boolean rv = true;
- PreparedStatement ps = null;
- try {
- String sql = "delete from EGRESS_ROUTES where SUBID = ?";
- ps = c.prepareStatement(sql);
+ String sql = "delete from EGRESS_ROUTES where SUBID = ?";
+ try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setInt(1, subid);
ps.execute();
} catch (SQLException e) {
rv = false;
intlogger.error("PROV0007 doDelete: " + e.getMessage(), e);
- } finally {
- try {
- if (ps != null) {
- ps.close();
- }
- } catch (SQLException e) {
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);
- }
}
return rv;
}
@@ -158,11 +138,9 @@ public class EgressRoute extends NodeClass implements Comparable<EgressRoute> {
@Override
public boolean doInsert(Connection c) {
boolean rv = false;
- PreparedStatement ps = null;
- try {
+ String sql = "insert into EGRESS_ROUTES (SUBID, NODEID) values (?, ?)";
+ try (PreparedStatement ps = c.prepareStatement(sql)) {
// Create the NETWORK_ROUTES row
- String sql = "insert into EGRESS_ROUTES (SUBID, NODEID) values (?, ?)";
- ps = c.prepareStatement(sql);
ps.setInt(1, this.subid);
ps.setInt(2, this.nodeid);
ps.execute();
@@ -170,14 +148,6 @@ public class EgressRoute extends NodeClass implements Comparable<EgressRoute> {
rv = true;
} catch (SQLException e) {
intlogger.warn("PROV0005 doInsert: " + e.getMessage(), e);
- } finally {
- try {
- if (ps != null) {
- ps.close();
- }
- } catch (SQLException e) {
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);
- }
}
return rv;
}
@@ -185,24 +155,14 @@ public class EgressRoute extends NodeClass implements Comparable<EgressRoute> {
@Override
public boolean doUpdate(Connection c) {
boolean rv = true;
- PreparedStatement ps = null;
- try {
- String sql = "update EGRESS_ROUTES set NODEID = ? where SUBID = ?";
- ps = c.prepareStatement(sql);
+ String sql = "update EGRESS_ROUTES set NODEID = ? where SUBID = ?";
+ try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setInt(1, nodeid);
ps.setInt(2, subid);
ps.executeUpdate();
} catch (SQLException e) {
rv = false;
intlogger.warn("PROV0006 doUpdate: " + e.getMessage(), e);
- } finally {
- try {
- if (ps != null) {
- ps.close();
- }
- } catch (SQLException e) {
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);
- }
}
return rv;
}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Group.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Group.java
index da682d74..4d6b0ee2 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Group.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Group.java
@@ -23,16 +23,19 @@
package org.onap.dmaap.datarouter.provisioning.beans;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
import java.io.InvalidObjectException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
-import java.util.*;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.Objects;
import org.json.JSONObject;
import org.onap.dmaap.datarouter.provisioning.utils.DB;
@@ -44,8 +47,9 @@ import org.onap.dmaap.datarouter.provisioning.utils.DB;
*/
public class Group extends Syncable {
+ private static final String GROUP_ID_CONST = "groupid";
private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");
- private static int next_groupid = getMaxGroupID() + 1;
+ private static int nextGroupid = getMaxGroupID() + 1;
private static final String SQLEXCEPTION = "SQLException: ";
private int groupid;
@@ -56,6 +60,60 @@ public class Group extends Syncable {
private String members;
private Date last_mod;
+ public Group() {
+ this("", "", "");
+ }
+
+ public Group(String name, String desc, String members) {
+ this.groupid = -1;
+ this.authid = "";
+ this.name = name;
+ this.description = desc;
+ this.members = members;
+ this.classification = "";
+ this.last_mod = new Date();
+ }
+
+
+ public Group(ResultSet rs) throws SQLException {
+ this.groupid = rs.getInt("GROUPID");
+ this.authid = rs.getString("AUTHID");
+ this.name = rs.getString("NAME");
+ this.description = rs.getString("DESCRIPTION");
+ this.classification = rs.getString("CLASSIFICATION");
+ this.members = rs.getString("MEMBERS");
+ this.last_mod = rs.getDate("LAST_MOD");
+ }
+
+
+ public Group(JSONObject jo) throws InvalidObjectException {
+ this("", "", "");
+ try {
+ // The JSONObject is assumed to contain a vnd.dmaap-dr.group representation
+ this.groupid = jo.optInt(GROUP_ID_CONST, -1);
+ String gname = jo.getString("name");
+ String gdescription = jo.getString("description");
+
+ this.authid = jo.getString("authid");
+ this.name = gname;
+ this.description = gdescription;
+ this.classification = jo.getString("classification");
+ this.members = jo.getString("members");
+
+ if (gname.length() > 50) {
+ throw new InvalidObjectException("Group name is too long");
+ }
+ if (gdescription.length() > 256) {
+ throw new InvalidObjectException("Group Description is too long");
+ }
+ } catch (InvalidObjectException e) {
+ throw e;
+ } catch (Exception e) {
+ intlogger.warn("Invalid JSON: " + e.getMessage(), e);
+ throw new InvalidObjectException("Invalid JSON: " + e.getMessage());
+ }
+ }
+
public static Group getGroupMatching(Group gup) {
String sql = String.format(
@@ -82,7 +140,7 @@ public class Group extends Syncable {
return list.size() > 0 ? list.get(0) : null;
}
- public static Group getGroupByAuthId(String id) {
+ static Group getGroupByAuthId(String id) {
String sql = "select * from GROUPS where AUTHID = '" + id + "'";
List<Group> list = getGroupsForSQL(sql);
return list.size() > 0 ? list.get(0) : null;
@@ -93,7 +151,7 @@ public class Group extends Syncable {
}
private static List<Group> getGroupsForSQL(String sql) {
- List<Group> list = new ArrayList<Group>();
+ List<Group> list = new ArrayList<>();
try {
DB db = new DB();
@SuppressWarnings("resource")
@@ -113,7 +171,7 @@ public class Group extends Syncable {
return list;
}
- public static int getMaxGroupID() {
+ private static int getMaxGroupID() {
int max = 0;
try {
DB db = new DB();
@@ -133,60 +191,6 @@ public class Group extends Syncable {
return max;
}
- public Group() {
- this("", "", "");
- }
-
- public Group(String name, String desc, String members) {
- this.groupid = -1;
- this.authid = "";
- this.name = name;
- this.description = desc;
- this.members = members;
- this.classification = "";
- this.last_mod = new Date();
- }
-
-
- public Group(ResultSet rs) throws SQLException {
- this.groupid = rs.getInt("GROUPID");
- this.authid = rs.getString("AUTHID");
- this.name = rs.getString("NAME");
- this.description = rs.getString("DESCRIPTION");
- this.classification = rs.getString("CLASSIFICATION");
- this.members = rs.getString("MEMBERS");
- this.last_mod = rs.getDate("LAST_MOD");
- }
-
-
- public Group(JSONObject jo) throws InvalidObjectException {
- this("", "", "");
- try {
- // The JSONObject is assumed to contain a vnd.dmaap-dr.group representation
- this.groupid = jo.optInt("groupid", -1);
- String gname = jo.getString("name");
- String gdescription = jo.getString("description");
-
- this.authid = jo.getString("authid");
- this.name = gname;
- this.description = gdescription;
- this.classification = jo.getString("classification");
- this.members = jo.getString("members");
-
- if (gname.length() > 50) {
- throw new InvalidObjectException("Group name is too long");
- }
- if (gdescription.length() > 256) {
- throw new InvalidObjectException("Group Description is too long");
- }
- } catch (InvalidObjectException e) {
- throw e;
- } catch (Exception e) {
- intlogger.warn("Invalid JSON: " + e.getMessage(), e);
- throw new InvalidObjectException("Invalid JSON: " + e.getMessage());
- }
- }
-
public int getGroupid() {
return groupid;
}
@@ -242,7 +246,7 @@ public class Group extends Syncable {
@Override
public JSONObject asJSONObject() {
JSONObject jo = new JSONObject();
- jo.put("groupid", groupid);
+ jo.put(GROUP_ID_CONST, groupid);
jo.put("authid", authid);
jo.put("name", name);
jo.put("description", description);
@@ -259,11 +263,11 @@ public class Group extends Syncable {
try {
if (groupid == -1) {
// No feed ID assigned yet, so assign the next available one
- setGroupid(next_groupid++);
+ setGroupid(nextGroupid++);
}
// In case we insert a gropup from synchronization
- if (groupid > next_groupid) {
- next_groupid = groupid + 1;
+ if (groupid > nextGroupid) {
+ nextGroupid = groupid + 1;
}
// Create the GROUPS row
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/IngressRoute.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/IngressRoute.java
index 329e77fa..1df093df 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/IngressRoute.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/IngressRoute.java
@@ -24,6 +24,8 @@
package org.onap.dmaap.datarouter.provisioning.beans;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
@@ -31,16 +33,11 @@ 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.Set;
import java.util.SortedSet;
import java.util.TreeSet;
-
import javax.servlet.http.HttpServletRequest;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONObject;
@@ -54,6 +51,7 @@ import org.onap.dmaap.datarouter.provisioning.utils.DB;
*/
public class IngressRoute extends NodeClass implements Comparable<IngressRoute> {
+ private static final String NODESET = "NODESET";
private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");
private static final String SQLEXCEPTION = "SQLException: ";
private final int seq;
@@ -63,6 +61,52 @@ public class IngressRoute extends NodeClass implements Comparable<IngressRoute>
private int nodelist;
private SortedSet<String> nodes;
+ public IngressRoute(int seq, int feedid, String user, String subnet, Collection<String> nodes) {
+ this(seq, feedid, user, subnet);
+ this.nodelist = -1;
+ this.nodes = new TreeSet<>(nodes);
+ }
+
+ private IngressRoute(int seq, int feedid, String user, String subnet, int nodeset) {
+ this(seq, feedid, user, subnet);
+ this.nodelist = nodeset;
+ this.nodes = new TreeSet<>(readNodes());
+ }
+
+ private IngressRoute(int seq, int feedid, String user, String subnet) {
+ this.seq = seq;
+ this.feedid = feedid;
+ this.userid = (user == null) ? "-" : user;
+ this.subnet = (subnet == null) ? "-" : subnet;
+ this.nodelist = -1;
+ this.nodes = null;
+ if (Feed.getFeedById(feedid) == null) {
+ throw new IllegalArgumentException("No such feed: " + feedid);
+ }
+ if (!"-".equals(this.subnet)) {
+ SubnetMatcher sm = new SubnetMatcher(subnet);
+ if (!sm.isValid()) {
+ throw new IllegalArgumentException("Invalid subnet: " + subnet);
+ }
+ }
+ }
+
+ public IngressRoute(JSONObject jo) {
+ this.seq = jo.optInt("seq");
+ this.feedid = jo.optInt("feedid");
+ String t = jo.optString("user");
+ this.userid = "".equals(t) ? "-" : t;
+ t = jo.optString("subnet");
+ this.subnet = "".equals(t) ? "-" : t;
+ this.nodelist = -1;
+ this.nodes = new TreeSet<>();
+ JSONArray ja = jo.getJSONArray("node");
+ for (int i = 0; i < ja.length(); i++) {
+ this.nodes.add(ja.getString(i));
+ }
+ }
+
+
/**
* Get all IngressRoutes in the database, sorted in order according to their sequence field.
*
@@ -84,21 +128,14 @@ public class IngressRoute extends NodeClass implements Comparable<IngressRoute>
}
private static SortedSet<IngressRoute> getAllIngressRoutesForSQL(String sql) {
- SortedSet<IngressRoute> set = new TreeSet<IngressRoute>();
+ SortedSet<IngressRoute> set = new TreeSet<>();
try {
DB db = new DB();
@SuppressWarnings("resource")
Connection conn = db.getConnection();
try (Statement stmt = conn.createStatement()) {
try (ResultSet rs = stmt.executeQuery(sql)) {
- while (rs.next()) {
- int seq = rs.getInt("SEQUENCE");
- int feedid = rs.getInt("FEEDID");
- String user = rs.getString("USERID");
- String subnet = rs.getString("SUBNET");
- int nodeset = rs.getInt("NODESET");
- set.add(new IngressRoute(seq, feedid, user, subnet, nodeset));
- }
+ addIngressRouteToSet(set, rs);
}
}
db.release(conn);
@@ -108,12 +145,23 @@ public class IngressRoute extends NodeClass implements Comparable<IngressRoute>
return set;
}
+ private static void addIngressRouteToSet(SortedSet<IngressRoute> set, ResultSet rs) throws SQLException {
+ while (rs.next()) {
+ int seq = rs.getInt("SEQUENCE");
+ int feedid = rs.getInt("FEEDID");
+ String user = rs.getString("USERID");
+ String subnet = rs.getString("SUBNET");
+ int nodeset = rs.getInt(NODESET);
+ set.add(new IngressRoute(seq, feedid, user, subnet, nodeset));
+ }
+ }
+
/**
* Get the maximum node set ID in use in the DB.
*
* @return the integer value of the maximum
*/
- public static int getMaxNodeSetID() {
+ private static int getMaxNodeSetID() {
return getMax("select max(SETID) as MAX from NODESETS");
}
@@ -128,15 +176,12 @@ public class IngressRoute extends NodeClass implements Comparable<IngressRoute>
private static int getMax(String sql) {
int rv = 0;
- try {
- DB db = new DB();
- @SuppressWarnings("resource")
- Connection conn = db.getConnection();
- try (Statement stmt = conn.createStatement()) {
- try (ResultSet rs = stmt.executeQuery(sql)) {
- if (rs.next()) {
- rv = rs.getInt("MAX");
- }
+ DB db = new DB();
+ try (Connection conn = db.getConnection();
+ Statement stmt = conn.createStatement()) {
+ try (ResultSet rs = stmt.executeQuery(sql)) {
+ if (rs.next()) {
+ rv = rs.getInt("MAX");
}
}
db.release(conn);
@@ -147,7 +192,7 @@ public class IngressRoute extends NodeClass implements Comparable<IngressRoute>
}
/**
- * Get an Ingress Route for a particular feed ID, user, and subnet
+ * Get an Ingress Route for a particular feed ID, user, and subnet.
*
* @param feedid the Feed ID to look for
* @param user the user name to look for
@@ -156,87 +201,27 @@ public class IngressRoute extends NodeClass implements Comparable<IngressRoute>
*/
public static IngressRoute getIngressRoute(int feedid, String user, String subnet) {
IngressRoute v = null;
- PreparedStatement ps = null;
- try {
- DB db = new DB();
- @SuppressWarnings("resource")
- Connection conn = db.getConnection();
- String sql = "select SEQUENCE, NODESET from INGRESS_ROUTES where FEEDID = ? AND USERID = ? and SUBNET = ?";
- ps = conn.prepareStatement(sql);
+ DB db = new DB();
+ String sql = "select SEQUENCE, NODESET from INGRESS_ROUTES where FEEDID = ? AND USERID = ? and SUBNET = ?";
+ try (Connection conn = db.getConnection();
+ PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, feedid);
ps.setString(2, user);
ps.setString(3, subnet);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
int seq = rs.getInt("SEQUENCE");
- int nodeset = rs.getInt("NODESET");
+ int nodeset = rs.getInt(NODESET);
v = new IngressRoute(seq, feedid, user, subnet, nodeset);
}
}
- ps.close();
db.release(conn);
} catch (SQLException e) {
intlogger.error("PROV0003 getIngressRoute: " + e.getMessage(), e);
- } finally {
- try {
- if (ps != null) {
- ps.close();
- }
- } catch (SQLException e) {
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);
- }
}
return v;
}
- public IngressRoute(int seq, int feedid, String user, String subnet, Collection<String> nodes)
- throws IllegalArgumentException {
- this(seq, feedid, user, subnet);
- this.nodelist = -1;
- this.nodes = new TreeSet<String>(nodes);
- }
-
- public IngressRoute(int seq, int feedid, String user, String subnet, int nodeset)
- throws IllegalArgumentException {
- this(seq, feedid, user, subnet);
- this.nodelist = nodeset;
- this.nodes = new TreeSet<String>(readNodes());
- }
-
- private IngressRoute(int seq, int feedid, String user, String subnet)
- throws IllegalArgumentException {
- this.seq = seq;
- this.feedid = feedid;
- this.userid = (user == null) ? "-" : user;
- this.subnet = (subnet == null) ? "-" : subnet;
- this.nodelist = -1;
- this.nodes = null;
- if (Feed.getFeedById(feedid) == null) {
- throw new IllegalArgumentException("No such feed: " + feedid);
- }
- if (!this.subnet.equals("-")) {
- SubnetMatcher sm = new SubnetMatcher(subnet);
- if (!sm.isValid()) {
- throw new IllegalArgumentException("Invalid subnet: " + subnet);
- }
- }
- }
-
- public IngressRoute(JSONObject jo) {
- this.seq = jo.optInt("seq");
- this.feedid = jo.optInt("feedid");
- String t = jo.optString("user");
- this.userid = t.equals("") ? "-" : t;
- t = jo.optString("subnet");
- this.subnet = t.equals("") ? "-" : t;
- this.nodelist = -1;
- this.nodes = new TreeSet<String>();
- JSONArray ja = jo.getJSONArray("node");
- for (int i = 0; i < ja.length(); i++) {
- this.nodes.add(ja.getString(i));
- }
- }
-
/**
* Does this particular IngressRoute match a request, represented by feedid and req? To match, <i>feedid</i> must
* match the feed ID in the route, the user in the route (if specified) must match the user in the request, and the
@@ -251,10 +236,9 @@ public class IngressRoute extends NodeClass implements Comparable<IngressRoute>
if (this.feedid != feedid) {
return false;
}
-
// Get user from request and compare
// Note: we don't check the password; the node will do that
- if (userid.length() > 0 && !userid.equals("-")) {
+ if (userid.length() > 0 && !"-".equals(userid)) {
String credentials = req.getHeader("Authorization");
if (credentials == null || !credentials.startsWith("Basic ")) {
return false;
@@ -268,9 +252,8 @@ public class IngressRoute extends NodeClass implements Comparable<IngressRoute>
return false;
}
}
-
// If this route has a subnet, match it against the requester's IP addr
- if (subnet.length() > 0 && !subnet.equals("-")) {
+ if (subnet.length() > 0 && !"-".equals(subnet)) {
try {
InetAddress inet = InetAddress.getByName(req.getRemoteAddr());
SubnetMatcher sm = new SubnetMatcher(subnet);
@@ -295,7 +278,7 @@ public class IngressRoute extends NodeClass implements Comparable<IngressRoute>
private boolean valid;
/**
- * Construct a subnet matcher given a CIDR
+ * Construct a subnet matcher given a CIDR.
*
* @param subnet The CIDR to match
*/
@@ -326,18 +309,18 @@ public class IngressRoute extends NodeClass implements Comparable<IngressRoute>
}
}
- public boolean isValid() {
+ boolean isValid() {
return valid;
}
/**
- * Is the IP address in the CIDR?
+ * Is the IP address in the CIDR?.
*
* @param addr the IP address as bytes in network byte order
* @return true if the IP address matches.
*/
- public boolean matches(byte[] addr) {
- if (!valid || addr.length != sn.length) {
+ boolean matches(byte[] addr) {
+ if (!valid || (addr.length != sn.length)) {
return false;
}
for (int i = 0; i < len; i++) {
@@ -363,19 +346,12 @@ public class IngressRoute extends NodeClass implements Comparable<IngressRoute>
private Collection<String> readNodes() {
Collection<String> set = new TreeSet<>();
- try {
- DB db = new DB();
- @SuppressWarnings("resource")
- Connection conn = db.getConnection();
- String sql = "select NODEID from NODESETS where SETID = ?";
+ DB db = new DB();
+ String sql = "select NODEID from NODESETS where SETID = ?";
+ try (Connection conn = db.getConnection()) {
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, nodelist);
- try (ResultSet rs = ps.executeQuery()) {
- while (rs.next()) {
- int id = rs.getInt("NODEID");
- set.add(lookupNodeID(id));
- }
- }
+ addNodeToSet(set, ps);
}
db.release(conn);
} catch (SQLException e) {
@@ -384,6 +360,15 @@ public class IngressRoute extends NodeClass implements Comparable<IngressRoute>
return set;
}
+ private void addNodeToSet(Collection<String> set, PreparedStatement ps) throws SQLException {
+ try (ResultSet rs = ps.executeQuery()) {
+ while (rs.next()) {
+ int id = rs.getInt("NODEID");
+ set.add(lookupNodeID(id));
+ }
+ }
+ }
+
/**
* Delete the IRT route having this IngressRoutes feed ID, user ID, and subnet from the database.
*
@@ -392,72 +377,49 @@ public class IngressRoute extends NodeClass implements Comparable<IngressRoute>
@Override
public boolean doDelete(Connection c) {
boolean rv = true;
- PreparedStatement ps = null;
- try {
- ps = c.prepareStatement("delete from INGRESS_ROUTES where FEEDID = ? and USERID = ? and SUBNET = ?");
+ try (PreparedStatement ps = c.prepareStatement(
+ "delete from INGRESS_ROUTES where FEEDID = ? and USERID = ? and SUBNET = ?");
+ PreparedStatement ps2 = c.prepareStatement("delete from NODESETS where SETID = ?")) {
+ // Delete the Ingress Route
ps.setInt(1, feedid);
ps.setString(2, userid);
ps.setString(3, subnet);
ps.execute();
ps.close();
-
- ps = c.prepareStatement("delete from NODESETS where SETID = ?");
- ps.setInt(1, nodelist);
- ps.execute();
+ // Delete the NodeSet
+ ps2.setInt(1, nodelist);
+ ps2.execute();
} catch (SQLException e) {
rv = false;
intlogger.warn("PROV0007 doDelete: " + e.getMessage(), e);
- } finally {
- try {
- if (ps != null) {
- ps.close();
- }
- } catch (SQLException e) {
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);
- }
}
return rv;
}
- @SuppressWarnings("resource")
@Override
public boolean doInsert(Connection c) {
boolean rv = false;
- PreparedStatement ps = null;
- try {
+ try (PreparedStatement ps = c.prepareStatement("insert into NODESETS (SETID, NODEID) values (?,?)");
+ PreparedStatement ps2 = c.prepareStatement("insert into INGRESS_ROUTES (SEQUENCE, FEEDID, USERID,"
+ + " SUBNET, NODESET) values (?, ?, ?, ?, ?)")) {
// Create the NODESETS rows & set nodelist
- int set = getMaxNodeSetID() + 1;
- this.nodelist = set;
+ this.nodelist = getMaxNodeSetID() + 1;
for (String node : nodes) {
int id = lookupNodeName(node);
- ps = c.prepareStatement("insert into NODESETS (SETID, NODEID) values (?,?)");
ps.setInt(1, this.nodelist);
ps.setInt(2, id);
ps.execute();
- ps.close();
}
-
// Create the INGRESS_ROUTES row
- ps = c.prepareStatement(
- "insert into INGRESS_ROUTES (SEQUENCE, FEEDID, USERID, SUBNET, NODESET) values (?, ?, ?, ?, ?)");
- ps.setInt(1, this.seq);
- ps.setInt(2, this.feedid);
- ps.setString(3, this.userid);
- ps.setString(4, this.subnet);
- ps.setInt(5, this.nodelist);
- ps.execute();
- ps.close();
+ ps2.setInt(1, this.seq);
+ ps2.setInt(2, this.feedid);
+ ps2.setString(3, this.userid);
+ ps2.setString(4, this.subnet);
+ ps2.setInt(5, this.nodelist);
+ ps2.execute();
rv = true;
} catch (SQLException e) {
intlogger.warn("PROV0005 doInsert: " + e.getMessage(), e);
- } finally {
- try {
- if (ps != null) {
- ps.close();
- }
- } catch (SQLException e) {
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);
- }
}
return rv;
}
@@ -472,10 +434,10 @@ public class IngressRoute extends NodeClass implements Comparable<IngressRoute>
JSONObject jo = new JSONObject();
jo.put("feedid", feedid);
// Note: for user and subnet, null, "", and "-" are equivalent
- if (userid != null && !userid.equals("-") && !userid.equals("")) {
+ if (userid != null && !"-".equals(userid) && !"".equals(userid)) {
jo.put("user", userid);
}
- if (subnet != null && !subnet.equals("-") && !subnet.equals("")) {
+ if (subnet != null && !"-".equals(subnet) && !"".equals(subnet)) {
jo.put("subnet", subnet);
}
jo.put("seq", seq);
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Insertable.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Insertable.java
index 6a677ce3..ed0815e8 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Insertable.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Insertable.java
@@ -32,6 +32,7 @@ import java.sql.Connection;
* @author Robert Eby
* @version $Id: Insertable.java,v 1.2 2013/05/29 14:44:36 eby Exp $
*/
+@FunctionalInterface
public interface Insertable {
/**
* Insert this object into the DB.
@@ -39,5 +40,5 @@ public interface Insertable {
* @param c the JDBC Connection to use
* @return true if the INSERT succeeded, false otherwise
*/
- public boolean doInsert(Connection c);
+ boolean doInsert(Connection c);
}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/JSONable.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/JSONable.java
index 82313273..44cea0f9 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/JSONable.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/JSONable.java
@@ -32,11 +32,12 @@ import org.json.JSONObject;
* @author Robert Eby
* @version $Id: JSONable.java,v 1.1 2013/04/26 21:00:26 eby Exp $
*/
+@FunctionalInterface
public interface JSONable {
/**
* Get a JSONObject representing this object.
*
* @return the JSONObject
*/
- public JSONObject asJSONObject();
+ JSONObject asJSONObject();
}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/LOGJSONable.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/LOGJSONable.java
index 3b7add5c..24f65b16 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/LOGJSONable.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/LOGJSONable.java
@@ -32,11 +32,12 @@ import org.onap.dmaap.datarouter.provisioning.utils.LOGJSONObject;
* @author Robert Eby
* @version $Id: JSONable.java,v 1.1 2013/04/26 21:00:26 eby Exp $
*/
+@FunctionalInterface
public interface LOGJSONable {
/**
* Get a JSONObject representing this object.
*
* @return the JSONObject
*/
- public LOGJSONObject asJSONObject();
+ LOGJSONObject asJSONObject();
}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Loadable.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Loadable.java
index ae64e84d..adeaa46c 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Loadable.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Loadable.java
@@ -36,6 +36,7 @@ import org.onap.dmaap.datarouter.provisioning.utils.LogfileLoader;
* @author Robert Eby
* @version $Id: Loadable.java,v 1.2 2013/08/06 13:28:33 eby Exp $
*/
+@FunctionalInterface
public interface Loadable {
/**
* Load the 18 fields in the PreparedStatement <i>ps</i>. The fields are:
@@ -62,5 +63,5 @@ public interface Loadable {
*
* @param ps the PreparedStatement to load
*/
- public void load(PreparedStatement ps) throws SQLException;
+ void load(PreparedStatement ps) throws SQLException;
}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/NetworkRoute.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/NetworkRoute.java
index 6ac05445..fa3d4e0e 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/NetworkRoute.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/NetworkRoute.java
@@ -24,6 +24,8 @@
package org.onap.dmaap.datarouter.provisioning.beans;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@@ -32,9 +34,6 @@ import java.sql.Statement;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
import org.json.JSONObject;
import org.onap.dmaap.datarouter.provisioning.utils.DB;
@@ -52,6 +51,30 @@ public class NetworkRoute extends NodeClass implements Comparable<NetworkRoute>
private final int tonode;
private final int vianode;
+ public NetworkRoute(String fromnode, String tonode) {
+ this.fromnode = lookupNodeName(fromnode);
+ this.tonode = lookupNodeName(tonode);
+ this.vianode = -1;
+ }
+
+ public NetworkRoute(String fromnode, String tonode, String vianode) {
+ this.fromnode = lookupNodeName(fromnode);
+ this.tonode = lookupNodeName(tonode);
+ this.vianode = lookupNodeName(vianode);
+ }
+
+ public NetworkRoute(JSONObject jo) {
+ this.fromnode = lookupNodeName(jo.getString("from"));
+ this.tonode = lookupNodeName(jo.getString("to"));
+ this.vianode = lookupNodeName(jo.getString("via"));
+ }
+
+ private NetworkRoute(int fromnode, int tonode, int vianode) {
+ this.fromnode = fromnode;
+ this.tonode = tonode;
+ this.vianode = vianode;
+ }
+
/**
* Get a set of all Network Routes in the DB. The set is sorted according to the natural sorting order of the
* routes (based on the from and to node names in each route).
@@ -66,43 +89,24 @@ public class NetworkRoute extends NodeClass implements Comparable<NetworkRoute>
Connection conn = db.getConnection();
try (Statement stmt = conn.createStatement()) {
try (ResultSet rs = stmt.executeQuery("select FROMNODE, TONODE, VIANODE from NETWORK_ROUTES")) {
- while (rs.next()) {
- int fromnode = rs.getInt("FROMNODE");
- int tonode = rs.getInt("TONODE");
- int vianode = rs.getInt("VIANODE");
- set.add(new NetworkRoute(fromnode, tonode, vianode));
- }
+ addNetworkRouteToSet(set, rs);
}
+ } finally {
+ db.release(conn);
}
- db.release(conn);
} catch (SQLException e) {
intlogger.error(SQLEXCEPTION + e.getMessage(), e);
}
return set;
}
- public NetworkRoute(String fromnode, String tonode) {
- this.fromnode = lookupNodeName(fromnode);
- this.tonode = lookupNodeName(tonode);
- this.vianode = -1;
- }
-
- public NetworkRoute(String fromnode, String tonode, String vianode) {
- this.fromnode = lookupNodeName(fromnode);
- this.tonode = lookupNodeName(tonode);
- this.vianode = lookupNodeName(vianode);
- }
-
- public NetworkRoute(JSONObject jo) {
- this.fromnode = lookupNodeName(jo.getString("from"));
- this.tonode = lookupNodeName(jo.getString("to"));
- this.vianode = lookupNodeName(jo.getString("via"));
- }
-
- public NetworkRoute(int fromnode, int tonode, int vianode) {
- this.fromnode = fromnode;
- this.tonode = tonode;
- this.vianode = vianode;
+ private static void addNetworkRouteToSet(SortedSet<NetworkRoute> set, ResultSet rs) throws SQLException {
+ while (rs.next()) {
+ int fromnode = rs.getInt("FROMNODE");
+ int tonode = rs.getInt("TONODE");
+ int vianode = rs.getInt("VIANODE");
+ set.add(new NetworkRoute(fromnode, tonode, vianode));
+ }
}
public int getFromnode() {
@@ -113,27 +117,21 @@ public class NetworkRoute extends NodeClass implements Comparable<NetworkRoute>
return tonode;
}
+ public int getVianode() {
+ return vianode;
+ }
+
@Override
public boolean doDelete(Connection c) {
boolean rv = true;
- PreparedStatement ps = null;
- try {
- String sql = "delete from NETWORK_ROUTES where FROMNODE = ? AND TONODE = ?";
- ps = c.prepareStatement(sql);
+ String sql = "delete from NETWORK_ROUTES where FROMNODE = ? AND TONODE = ?";
+ try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setInt(1, fromnode);
ps.setInt(2, tonode);
ps.execute();
} catch (SQLException e) {
rv = false;
intlogger.warn("PROV0007 doDelete: " + e.getMessage(), e);
- } finally {
- try {
- if (ps != null) {
- ps.close();
- }
- } catch (SQLException e) {
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);
- }
}
return rv;
}
@@ -141,28 +139,17 @@ public class NetworkRoute extends NodeClass implements Comparable<NetworkRoute>
@Override
public boolean doInsert(Connection c) {
boolean rv = false;
+ String sql = "insert into NETWORK_ROUTES (FROMNODE, TONODE, VIANODE) values (?, ?, ?)";
if (this.vianode >= 0) {
- PreparedStatement ps = null;
- try {
+ try (PreparedStatement ps = c.prepareStatement(sql)) {
// Create the NETWORK_ROUTES row
- String sql = "insert into NETWORK_ROUTES (FROMNODE, TONODE, VIANODE) values (?, ?, ?)";
- ps = c.prepareStatement(sql);
ps.setInt(1, this.fromnode);
ps.setInt(2, this.tonode);
ps.setInt(3, this.vianode);
ps.execute();
- ps.close();
rv = true;
} catch (SQLException e) {
intlogger.warn("PROV0005 doInsert: " + e.getMessage(), e);
- } finally {
- try {
- if (ps != null) {
- ps.close();
- }
- } catch (SQLException e) {
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);
- }
}
}
return rv;
@@ -171,10 +158,8 @@ public class NetworkRoute extends NodeClass implements Comparable<NetworkRoute>
@Override
public boolean doUpdate(Connection c) {
boolean rv = true;
- PreparedStatement ps = null;
- try {
- String sql = "update NETWORK_ROUTES set VIANODE = ? where FROMNODE = ? and TONODE = ?";
- ps = c.prepareStatement(sql);
+ String sql = "update NETWORK_ROUTES set VIANODE = ? where FROMNODE = ? and TONODE = ?";
+ try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setInt(1, vianode);
ps.setInt(2, fromnode);
ps.setInt(3, tonode);
@@ -182,14 +167,6 @@ public class NetworkRoute extends NodeClass implements Comparable<NetworkRoute>
} catch (SQLException e) {
rv = false;
intlogger.warn("PROV0006 doUpdate: " + e.getMessage(), e);
- } finally {
- try {
- if (ps != null) {
- ps.close();
- }
- } catch (SQLException e) {
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);
- }
}
return rv;
}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/NodeClass.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/NodeClass.java
index f3ef5d6a..d11c20fb 100755
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/NodeClass.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/NodeClass.java
@@ -23,6 +23,8 @@
package org.onap.dmaap.datarouter.provisioning.beans;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@@ -32,9 +34,6 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
import org.onap.dmaap.datarouter.provisioning.utils.DB;
/**
@@ -45,9 +44,11 @@ import org.onap.dmaap.datarouter.provisioning.utils.DB;
*/
public abstract class NodeClass extends Syncable {
+ private static final String PROV_0005_DO_INSERT = "PROV0005 doInsert: ";
private static Map<String, Integer> map;
private static EELFLogger intLogger = EELFManager.getInstance().getLogger("InternalLog");
- public NodeClass() {
+
+ NodeClass() {
// init on first use
if (map == null) {
reload();
@@ -77,67 +78,50 @@ public abstract class NodeClass extends Syncable {
if (!map.containsKey(node)) {
intLogger.info("..adding " + node + " to NODES with index " + nextid);
map.put(node, nextid);
- PreparedStatement ps = null;
- try {
- DB db = new DB();
- @SuppressWarnings("resource")
- Connection conn = db.getConnection();
- ps = conn.prepareStatement("insert into NODES (NODEID, NAME, ACTIVE) values (?, ?, 1)");
- ps.setInt(1, nextid);
- ps.setString(2, node);
- ps.execute();
- ps.close();
- db.release(conn);
- } catch (SQLException e) {
- intLogger.error("PROV0005 doInsert: " + e.getMessage(),e);
- } finally {
- try {
- if(ps!=null){
- ps.close();
- }
- } catch (SQLException e) {
- intLogger.error("Error in closing PreparedStatement: " + e.getMessage(),e);
- }
- }
+ insertNodesToTable(nextid, node);
nextid++;
}
}
}
- public static void reload() {
- Map<String, Integer> m = new HashMap<String, Integer>();
- PreparedStatement ps = null;
+ private static void insertNodesToTable(int nextid, String node) {
+ DB db = new DB();
+ try (Connection conn = db.getConnection()) {
+ try (PreparedStatement ps = conn
+ .prepareStatement("insert into NODES (NODEID, NAME, ACTIVE) values (?, ?, 1)")) {
+ ps.setInt(1, nextid);
+ ps.setString(2, node);
+ ps.execute();
+ } finally {
+ db.release(conn);
+ }
+ } catch (SQLException e) {
+ intLogger.error(PROV_0005_DO_INSERT + e.getMessage(), e);
+ }
+ }
- try {
- DB db = new DB();
- @SuppressWarnings("resource")
- Connection conn = db.getConnection();
- String sql = "select NODEID, NAME from NODES";
- ps = conn.prepareStatement(sql);
- try(ResultSet rs = ps.executeQuery()) {
+ private static void reload() {
+ Map<String, Integer> m = new HashMap<>();
+ String sql = "select NODEID, NAME from NODES";
+ DB db = new DB();
+ try (Connection conn = db.getConnection();
+ PreparedStatement ps = conn.prepareStatement(sql)) {
+ try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
int id = rs.getInt("NODEID");
String name = rs.getString("NAME");
m.put(name, id);
}
+ } finally {
+ db.release(conn);
}
- ps.close();
- db.release(conn);
} catch (SQLException e) {
- intLogger.error("PROV0005 doInsert: " + e.getMessage(),e);
- } finally {
- try {
- if(ps!=null){
- ps.close();
- }
- } catch (SQLException e) {
- intLogger.error("PROV0005 doInsert: " + e.getMessage(),e);
- }
+ intLogger.error(PROV_0005_DO_INSERT + e.getMessage(),e);
}
map = m;
}
- public static Integer lookupNodeName(final String name) {
+ static Integer lookupNodeName(final String name) {
Integer n = map.get(name);
if (n == null) {
throw new IllegalArgumentException("Invalid node name: " + name);
@@ -146,16 +130,11 @@ public abstract class NodeClass extends Syncable {
}
public static Collection<String> lookupNodeNames(String patt) {
- Collection<String> coll = new TreeSet<String>();
+ Collection<String> coll = new TreeSet<>();
final Set<String> keyset = map.keySet();
for (String s : patt.toLowerCase().split(",")) {
if (s.endsWith("*")) {
- s = s.substring(0, s.length() - 1);
- for (String s2 : keyset) {
- if (s2.startsWith(s)) {
- coll.add(s2);
- }
- }
+ addNodeToCollection(coll, keyset, s);
} else if (keyset.contains(s)) {
coll.add(s);
} else if (keyset.contains(normalizeNodename(s))) {
@@ -167,6 +146,15 @@ public abstract class NodeClass extends Syncable {
return coll;
}
+ private static void addNodeToCollection(Collection<String> coll, Set<String> keyset, String s) {
+ s = s.substring(0, s.length() - 1);
+ for (String s2 : keyset) {
+ if (s2.startsWith(s)) {
+ coll.add(s2);
+ }
+ }
+ }
+
public static String normalizeNodename(String s) {
if (s != null && s.indexOf('.') <= 0) {
Parameters p = Parameters.getParameter(Parameters.PROV_DOMAIN);
@@ -175,17 +163,16 @@ public abstract class NodeClass extends Syncable {
s += "." + domain;
}
return s.toLowerCase();
- }
- else{
+ } else {
return s;
}
}
- protected String lookupNodeID(int n) {
- for (String s : map.keySet()) {
- if (map.get(s) == n) {
- return s;
+ String lookupNodeID(int n) {
+ for (Map.Entry<String, Integer> entry : map.entrySet()) {
+ if (entry.getValue() == n) {
+ return entry.getKey();
}
}
return null;
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Parameters.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Parameters.java
index 9e7071bb..78ed96dd 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Parameters.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Parameters.java
@@ -23,15 +23,18 @@
package org.onap.dmaap.datarouter.provisioning.beans;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
-import java.util.*;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
import org.json.JSONObject;
import org.onap.dmaap.datarouter.provisioning.utils.DB;
@@ -67,7 +70,7 @@ public class Parameters extends Syncable {
public static final String DELIVERY_RETRY_RATIO = "DELIVERY_RETRY_RATIO";
public static final String DELIVERY_MAX_AGE = "DELIVERY_MAX_AGE";
public static final String THROTTLE_FILTER = "THROTTLE_FILTER";
- public static final String STATIC_ROUTING_NODES = "STATIC_ROUTING_NODES"; //Adding new param for static Routing - Rally:US664862-1610
+ public static final String STATIC_ROUTING_NODES = "STATIC_ROUTING_NODES";
private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");
private static final String SQLEXCEPTION = "SQLException: ";
@@ -75,13 +78,23 @@ public class Parameters extends Syncable {
private String keyname;
private String value;
+ public Parameters(String k, String v) {
+ this.keyname = k;
+ this.value = v;
+ }
+
+ public Parameters(ResultSet rs) throws SQLException {
+ this.keyname = rs.getString("KEYNAME");
+ this.value = rs.getString("VALUE");
+ }
+
/**
* Get all parameters in the DB as a Map.
*
* @return the Map of keynames/values from the DB.
*/
public static Map<String, String> getParameters() {
- Map<String, String> props = new HashMap<String, String>();
+ Map<String, String> props = new HashMap<>();
for (Parameters p : getParameterCollection()) {
props.put(p.getKeyname(), p.getValue());
}
@@ -89,23 +102,20 @@ public class Parameters extends Syncable {
}
public static Collection<Parameters> getParameterCollection() {
- Collection<Parameters> coll = new ArrayList<Parameters>();
- try {
- DB db = new DB();
- @SuppressWarnings("resource")
- Connection conn = db.getConnection();
- try (Statement stmt = conn.createStatement()) {
- String sql = "select * from PARAMETERS";
- try (ResultSet rs = stmt.executeQuery(sql)) {
- while (rs.next()) {
- Parameters p = new Parameters(rs);
- coll.add(p);
- }
+ Collection<Parameters> coll = new ArrayList<>();
+ DB db = new DB();
+ String sql = "select * from PARAMETERS";
+ try (Connection conn = db.getConnection();
+ Statement stmt = conn.createStatement()) {
+ try (ResultSet rs = stmt.executeQuery(sql)) {
+ while (rs.next()) {
+ Parameters p = new Parameters(rs);
+ coll.add(p);
}
}
db.release(conn);
} catch (SQLException e) {
- intlogger.error(SQLEXCEPTION + e.getMessage());
+ intlogger.error(SQLEXCEPTION + e.getMessage(), e);
}
return coll;
}
@@ -118,40 +128,23 @@ public class Parameters extends Syncable {
*/
public static Parameters getParameter(String k) {
Parameters v = null;
- try {
- DB db = new DB();
- @SuppressWarnings("resource")
- Connection conn = db.getConnection();
- try (PreparedStatement stmt = conn
- .prepareStatement("select KEYNAME, VALUE from PARAMETERS where KEYNAME = ?")) {
- stmt.setString(1, k);
- try (ResultSet rs = stmt.executeQuery()) {
- if (rs.next()) {
- v = new Parameters(rs);
- }
+ DB db = new DB();
+ String sql = "select KEYNAME, VALUE from PARAMETERS where KEYNAME = ?";
+ try (Connection conn = db.getConnection();
+ PreparedStatement stmt = conn.prepareStatement(sql)) {
+ stmt.setString(1, k);
+ try (ResultSet rs = stmt.executeQuery()) {
+ if (rs.next()) {
+ v = new Parameters(rs);
}
}
db.release(conn);
} catch (SQLException e) {
- intlogger.error(SQLEXCEPTION + e.getMessage());
+ intlogger.error(SQLEXCEPTION + e.getMessage(), e);
}
return v;
}
- public Parameters() {
- this("", "");
- }
-
- public Parameters(String k, String v) {
- this.keyname = k;
- this.value = v;
- }
-
- public Parameters(ResultSet rs) throws SQLException {
- this.keyname = rs.getString("KEYNAME");
- this.value = rs.getString("VALUE");
- }
-
public String getKeyname() {
return keyname;
}
@@ -175,25 +168,14 @@ public class Parameters extends Syncable {
@Override
public boolean doInsert(Connection c) {
boolean rv = true;
- PreparedStatement ps = null;
- try {
- // Create the SUBSCRIPTIONS row
- String sql = "insert into PARAMETERS values (?, ?)";
- ps = c.prepareStatement(sql);
+ String sql = "insert into PARAMETERS values (?, ?)";
+ try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, getKeyname());
ps.setString(2, getValue());
ps.execute();
} catch (SQLException e) {
rv = false;
intlogger.warn("PROV0005 doInsert: " + e.getMessage(), e);
- } finally {
- try {
- if (ps != null) {
- ps.close();
- }
- } catch (SQLException e) {
- intlogger.error(SQLEXCEPTION + e.getMessage());
- }
}
return rv;
}
@@ -201,25 +183,14 @@ public class Parameters extends Syncable {
@Override
public boolean doUpdate(Connection c) {
boolean rv = true;
- PreparedStatement ps = null;
- try {
- // Update the PARAMETERS row
- String sql = "update PARAMETERS set VALUE = ? where KEYNAME = ?";
- ps = c.prepareStatement(sql);
+ String sql = "update PARAMETERS set VALUE = ? where KEYNAME = ?";
+ try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, getValue());
ps.setString(2, getKeyname());
ps.executeUpdate();
} catch (SQLException e) {
rv = false;
intlogger.warn("PROV0006 doUpdate: " + e.getMessage(),e);
- } finally {
- try {
- if (ps != null) {
- ps.close();
- }
- } catch (SQLException e) {
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);
- }
}
return rv;
}
@@ -227,24 +198,13 @@ public class Parameters extends Syncable {
@Override
public boolean doDelete(Connection c) {
boolean rv = true;
- PreparedStatement ps = null;
- try {
- // Create the SUBSCRIPTIONS row
- String sql = "delete from PARAMETERS where KEYNAME = ?";
- ps = c.prepareStatement(sql);
+ String sql = "delete from PARAMETERS where KEYNAME = ?";
+ try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, getKeyname());
ps.execute();
} catch (SQLException e) {
rv = false;
intlogger.warn("PROV0007 doDelete: " + e.getMessage(), e);
- } finally {
- try {
- if (ps != null) {
- ps.close();
- }
- } catch (SQLException e) {
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);
- }
}
return rv;
}
@@ -260,13 +220,7 @@ public class Parameters extends Syncable {
return false;
}
Parameters of = (Parameters) obj;
- if (!keyname.equals(of.keyname)) {
- return false;
- }
- if (!value.equals(of.value)) {
- return false;
- }
- return true;
+ return (!value.equals(of.value)) && (!keyname.equals(of.keyname));
}
@Override
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DB.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DB.java
index 7700a583..55b2c038 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DB.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DB.java
@@ -24,6 +24,11 @@
package org.onap.dmaap.datarouter.provisioning.utils;
+import static java.lang.System.exit;
+import static java.lang.System.getProperty;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
@@ -42,9 +47,6 @@ import java.util.Properties;
import java.util.Queue;
import java.util.Set;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-
/**
* Load the DB JDBC driver, and manage a simple pool of connections to the DB.
*
@@ -55,14 +57,14 @@ public class DB {
private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");
- private static String DB_URL;
- private static String DB_LOGIN;
- private static String DB_PASSWORD;
+ private static String dbUrl;
+ private static String dbLogin;
+ private static String dbPassword;
private static Properties props;
private static final Queue<Connection> queue = new LinkedList<>();
- private static String HTTPS_PORT;
- private static String HTTP_PORT;
+ private static String httpsPort;
+ private static String httpPort;
/**
* Construct a DB object. If this is the very first creation of this object, it will load a copy of the properties
@@ -73,22 +75,22 @@ public class DB {
if (props == null) {
props = new Properties();
try {
- props.load(new FileInputStream(System.getProperty(
+ props.load(new FileInputStream(getProperty(
"org.onap.dmaap.datarouter.provserver.properties",
"/opt/app/datartr/etc/provserver.properties")));
- String DB_DRIVER = (String) props.get("org.onap.dmaap.datarouter.db.driver");
- DB_URL = (String) props.get("org.onap.dmaap.datarouter.db.url");
- DB_LOGIN = (String) props.get("org.onap.dmaap.datarouter.db.login");
- DB_PASSWORD = (String) props.get("org.onap.dmaap.datarouter.db.password");
- HTTPS_PORT = (String) props.get("org.onap.dmaap.datarouter.provserver.https.port");
- HTTP_PORT = (String) props.get("org.onap.dmaap.datarouter.provserver.http.port");
- Class.forName(DB_DRIVER);
+ String dbDriver = (String) props.get("org.onap.dmaap.datarouter.db.driver");
+ dbUrl = (String) props.get("org.onap.dmaap.datarouter.db.url");
+ dbLogin = (String) props.get("org.onap.dmaap.datarouter.db.login");
+ dbPassword = (String) props.get("org.onap.dmaap.datarouter.db.password");
+ httpsPort = (String) props.get("org.onap.dmaap.datarouter.provserver.https.port");
+ httpPort = (String) props.get("org.onap.dmaap.datarouter.provserver.http.port");
+ Class.forName(dbDriver);
} catch (IOException e) {
intlogger.error("PROV9003 Opening properties: " + e.getMessage(), e);
- System.exit(1);
+ exit(1);
} catch (ClassNotFoundException e) {
intlogger.error("PROV9004 cannot find the DB driver: " + e);
- System.exit(1);
+ exit(1);
}
}
}
@@ -107,7 +109,6 @@ public class DB {
*
* @return the Connection
*/
- @SuppressWarnings("resource")
public Connection getConnection() throws SQLException {
Connection connection = null;
while (connection == null) {
@@ -120,7 +121,7 @@ public class DB {
do {
// Try up to 3 times to get a connection
try {
- connection = DriverManager.getConnection(DB_URL, DB_LOGIN, DB_PASSWORD);
+ connection = DriverManager.getConnection(dbUrl, dbLogin, dbPassword);
} catch (SQLException sqlEx) {
if (++n >= 3) {
throw sqlEx;
@@ -164,11 +165,11 @@ public class DB {
public static String getHttpsPort() {
- return HTTPS_PORT;
+ return httpsPort;
}
public static String getHttpPort() {
- return HTTP_PORT;
+ return httpPort;
}
/**
@@ -238,34 +239,35 @@ public class DB {
*/
private void runInitScript(Connection connection, int scriptId) {
String scriptDir = (String) props.get("org.onap.dmaap.datarouter.provserver.dbscripts");
- StringBuilder strBuilder = new StringBuilder();
- try {
- String scriptFile = String.format("%s/sql_init_%02d.sql", scriptDir, scriptId);
- if (!(new File(scriptFile)).exists()) {
- intlogger.error("PROV9005 Failed to load sql script from : " + scriptFile);
- System.exit(1);
- }
- LineNumberReader lineReader = new LineNumberReader(new FileReader(scriptFile));
+ String scriptFile = String.format("%s/sql_init_%02d.sql", scriptDir, scriptId);
+ if (!(new File(scriptFile)).exists()) {
+ intlogger.error("PROV9005 Failed to load sql script from : " + scriptFile);
+ exit(1);
+ }
+ try (LineNumberReader lineReader = new LineNumberReader(new FileReader(scriptFile));
+ Statement statement = connection.createStatement()) {
+ StringBuilder strBuilder = new StringBuilder();
String line;
while ((line = lineReader.readLine()) != null) {
if (!line.startsWith("--")) {
line = line.trim();
strBuilder.append(line);
- if (line.endsWith(";")) {
- // Execute one DDL statement
- String sql = strBuilder.toString();
- strBuilder.setLength(0);
- Statement statement = connection.createStatement();
- statement.execute(sql);
- statement.close();
- }
+ executeDdlStatement(statement, strBuilder, line);
}
}
- lineReader.close();
strBuilder.setLength(0);
} catch (Exception e) {
intlogger.error("PROV9002 Error when initializing table: " + e.getMessage(), e);
- System.exit(1);
+ exit(1);
+ }
+ }
+
+ private void executeDdlStatement(Statement statement, StringBuilder strBuilder, String line) throws SQLException {
+ if (line.endsWith(";")) {
+ // Execute one DDL statement
+ String sql = strBuilder.toString();
+ strBuilder.setLength(0);
+ statement.execute(sql);
}
}
}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LOGJSONObject.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LOGJSONObject.java
index 1140a1ce..bc1f4493 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LOGJSONObject.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LOGJSONObject.java
@@ -28,11 +28,14 @@ import com.att.eelf.configuration.EELFManager;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
-import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
-import java.util.*;
-
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONString;
@@ -93,10 +96,13 @@ import org.json.JSONTokener;
* @version 2012-12-01
*/
public class LOGJSONObject {
+
/**
* The maximum number of keys in the key pool.
*/
- private static final int keyPoolSize = 100;
+ private static final int KEY_POOL_SIZE = 100;
+ private static final String USING_DEFAULT_VALUE = "Using defaultValue: ";
+ private static final String JSON_OBJECT_CONST = "JSONObject[";
/**
* Key pooling is like string interning, but without permanently tying up
@@ -104,7 +110,7 @@ public class LOGJSONObject {
* JSONObjects will be avoided by using a key pool to manage unique key
* string objects. This is used by JSONObject.put(string, object).
*/
- private static Map<String, Object> keyPool = new LinkedHashMap<String, Object>(keyPoolSize);
+ private static Map<String, Object> keyPool = new LinkedHashMap<>(KEY_POOL_SIZE);
private static final EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");
@@ -197,7 +203,7 @@ public class LOGJSONObject {
* <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.
* <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>.
*/
- public static final Object NULL = new Null();
+ private static final Object NULL = new Null();
/**
* Construct an empty JSONObject.
@@ -290,7 +296,7 @@ public class LOGJSONObject {
* @throws JSONException
*/
public LOGJSONObject(Map<String, Object> map) {
- this.map = new LinkedHashMap<String, Object>();
+ this.map = new LinkedHashMap<>();
if (map != null) {
Iterator<Map.Entry<String, Object>> i = map.entrySet().iterator();
while (i.hasNext()) {
@@ -328,84 +334,6 @@ public class LOGJSONObject {
}
/**
- * Construct a JSONObject from an Object, using reflection to find the
- * public members. The resulting JSONObject's keys will be the strings
- * from the names array, and the values will be the field values associated
- * with those keys in the object. If a key is not found or not visible,
- * then it will not be copied into the new JSONObject.
- *
- * @param object An object that has fields that should be used to make a
- * JSONObject.
- * @param names An array of strings, the names of the fields to be obtained
- * from the object.
- */
- public LOGJSONObject(Object object, String names[]) {
- this();
- Class<? extends Object> c = object.getClass();
- for (int i = 0; i < names.length; i += 1) {
- String name = names[i];
- try {
- this.putOpt(name, c.getField(name).get(object));
- } catch (Exception ignore) {
- }
- }
- }
-
- /**
- * Construct a JSONObject from a source JSON text string.
- * This is the most commonly used JSONObject constructor.
- *
- * @param source A string beginning
- * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
- * with <code>}</code>&nbsp;<small>(right brace)</small>.
- * @throws JSONException If there is a syntax error in the source
- * string or a duplicated key.
- */
- public LOGJSONObject(String source) throws JSONException {
- this(new JSONTokener(source));
- }
-
- /**
- * Construct a JSONObject from a ResourceBundle.
- *
- * @param baseName The ResourceBundle base name.
- * @param locale The Locale to load the ResourceBundle for.
- * @throws JSONException If any JSONExceptions are detected.
- */
- public LOGJSONObject(String baseName, Locale locale) throws JSONException {
- this();
- ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,
- Thread.currentThread().getContextClassLoader());
-
-// Iterate through the keys in the bundle.
-
- Enumeration<?> keys = bundle.getKeys();
- while (keys.hasMoreElements()) {
- Object key = keys.nextElement();
- if (key instanceof String) {
-
-// Go through the path, ensuring that there is a nested JSONObject for each
-// segment except the last. Add the value using the last segment's name into
-// the deepest nested JSONObject.
-
- String[] path = ((String) key).split("\\.");
- int last = path.length - 1;
- LOGJSONObject target = this;
- for (int i = 0; i < last; i += 1) {
- String segment = path[i];
- LOGJSONObject nextTarget = target.optJSONObject(segment);
- if (nextTarget == null) {
- nextTarget = new LOGJSONObject();
- target.put(segment, nextTarget);
- }
- target = nextTarget;
- }
- target.put(path[last], bundle.getString((String) key));
- }
- }
- }
-
- /**
* Accumulate values under a key. It is similar to the put method except
* that if there is already an object stored under the key then a
* JSONArray is stored under the key to hold all of the accumulated values.
@@ -423,15 +351,15 @@ public class LOGJSONObject {
* or if the key is null.
*/
public LOGJSONObject accumulate(
- String key,
- Object value
- ) throws JSONException {
+ String key,
+ Object value
+ ) {
testValidity(value);
Object object = this.opt(key);
if (object == null) {
this.put(key, value instanceof JSONArray
- ? new JSONArray().put(value)
- : value);
+ ? new JSONArray().put(value)
+ : value);
} else if (object instanceof JSONArray) {
((JSONArray) object).put(value);
} else {
@@ -452,7 +380,7 @@ public class LOGJSONObject {
* @throws JSONException If the key is null or if the current value
* associated with the key is not a JSONArray.
*/
- public LOGJSONObject append(String key, Object value) throws JSONException {
+ public LOGJSONObject append(String key, Object value) {
testValidity(value);
Object object = this.opt(key);
if (object == null) {
@@ -460,8 +388,8 @@ public class LOGJSONObject {
} else if (object instanceof JSONArray) {
this.put(key, ((JSONArray) object).put(value));
} else {
- throw new JSONException("JSONObject[" + key +
- "] is not a JSONArray.");
+ throw new JSONException(JSON_OBJECT_CONST + key +
+ "] is not a JSONArray.");
}
return this;
}
@@ -481,8 +409,8 @@ public class LOGJSONObject {
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
- if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
- string.indexOf('E') < 0) {
+ if (string.indexOf('.') > 0 && string.indexOf('e') < 0
+ && string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
@@ -500,14 +428,14 @@ public class LOGJSONObject {
* @return The object associated with the key.
* @throws JSONException if the key is not found.
*/
- public Object get(String key) throws JSONException {
+ public Object get(String key) {
if (key == null) {
throw new JSONException("Null key.");
}
Object object = this.opt(key);
if (object == null) {
- throw new JSONException("JSONObject[" + quote(key) +
- "] not found.");
+ throw new JSONException(JSON_OBJECT_CONST + quote(key) +
+ "] not found.");
}
return object;
}
@@ -519,19 +447,19 @@ public class LOGJSONObject {
* @return The truth.
* @throws JSONException if the value is not a Boolean or the String "true" or "false".
*/
- public boolean getBoolean(String key) throws JSONException {
+ public boolean getBoolean(String key) {
Object object = this.get(key);
if (object.equals(Boolean.FALSE) ||
- (object instanceof String &&
- ((String) object).equalsIgnoreCase("false"))) {
+ (object instanceof String &&
+ "false".equalsIgnoreCase((String) object))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
- (object instanceof String &&
- ((String) object).equalsIgnoreCase("true"))) {
+ (object instanceof String &&
+ "true".equalsIgnoreCase((String) object))) {
return true;
}
- throw new JSONException("JSONObject[" + quote(key) +
- "] is not a Boolean.");
+ throw new JSONException(JSON_OBJECT_CONST + quote(key) +
+ "] is not a Boolean.");
}
/**
@@ -546,11 +474,11 @@ public class LOGJSONObject {
Object object = this.get(key);
try {
return object instanceof Number
- ? ((Number) object).doubleValue()
- : Double.parseDouble((String) object);
+ ? ((Number) object).doubleValue()
+ : Double.parseDouble((String) object);
} catch (Exception e) {
- intlogger.error("JSONObject[" + quote(key) + "] is not a number.", e);
- throw new JSONException("JSONObject[" + quote(key) + "] is not a number.");
+ intlogger.error(JSON_OBJECT_CONST + quote(key) + "] is not a number.", e);
+ throw new JSONException(JSON_OBJECT_CONST + quote(key) + "] is not a number.");
}
}
@@ -566,11 +494,11 @@ public class LOGJSONObject {
Object object = this.get(key);
try {
return object instanceof Number
- ? ((Number) object).intValue()
- : Integer.parseInt((String) object);
+ ? ((Number) object).intValue()
+ : Integer.parseInt((String) object);
} catch (Exception e) {
- intlogger.error("JSONObject[" + quote(key) + "] is not an int.", e);
- throw new JSONException("JSONObject[" + quote(key) + "] is not an int.");
+ intlogger.error(JSON_OBJECT_CONST + quote(key) + "] is not an int.", e);
+ throw new JSONException(JSON_OBJECT_CONST + quote(key) + "] is not an int.");
}
}
@@ -582,13 +510,13 @@ public class LOGJSONObject {
* @throws JSONException if the key is not found or
* if the value is not a JSONArray.
*/
- public JSONArray getJSONArray(String key) throws JSONException {
+ public JSONArray getJSONArray(String key) {
Object object = this.get(key);
if (object instanceof JSONArray) {
return (JSONArray) object;
}
- throw new JSONException("JSONObject[" + quote(key) +
- "] is not a JSONArray.");
+ throw new JSONException(JSON_OBJECT_CONST + quote(key) +
+ "] is not a JSONArray.");
}
/**
@@ -599,13 +527,13 @@ public class LOGJSONObject {
* @throws JSONException if the key is not found or
* if the value is not a JSONObject.
*/
- public LOGJSONObject getJSONObject(String key) throws JSONException {
+ public LOGJSONObject getJSONObject(String key) {
Object object = this.get(key);
if (object instanceof LOGJSONObject) {
return (LOGJSONObject) object;
}
- throw new JSONException("JSONObject[" + quote(key) +
- "] is not a JSONObject.");
+ throw new JSONException(JSON_OBJECT_CONST + quote(key) +
+ "] is not a JSONObject.");
}
/**
@@ -616,15 +544,15 @@ public class LOGJSONObject {
* @throws JSONException if the key is not found or if the value cannot
* be converted to a long.
*/
- public long getLong(String key) throws JSONException {
+ public long getLong(String key) {
Object object = this.get(key);
try {
return object instanceof Number
- ? ((Number) object).longValue()
- : Long.parseLong((String) object);
+ ? ((Number) object).longValue()
+ : Long.parseLong((String) object);
} catch (Exception e) {
- intlogger.error("JSONObject[" + quote(key) + "] is not a long.", e);
- throw new JSONException("JSONObject[" + quote(key) + "] is not a long.");
+ intlogger.error(JSON_OBJECT_CONST + quote(key) + "] is not a long.", e);
+ throw new JSONException(JSON_OBJECT_CONST + quote(key) + "] is not a long.");
}
}
@@ -636,7 +564,7 @@ public class LOGJSONObject {
public static String[] getNames(LOGJSONObject jo) {
int length = jo.length();
if (length == 0) {
- return null;
+ return new String[]{};
}
Iterator<String> iterator = jo.keys();
String[] names = new String[length];
@@ -660,8 +588,8 @@ public class LOGJSONObject {
if (object instanceof String) {
return (String) object;
}
- throw new JSONException("JSONObject[" + quote(key) +
- "] not a string.");
+ throw new JSONException(JSON_OBJECT_CONST + quote(key) +
+ "] not a string.");
}
/**
@@ -753,7 +681,7 @@ public class LOGJSONObject {
* @throws JSONException If n is a non-finite number.
*/
public static String numberToString(Number number)
- throws JSONException {
+ {
if (number == null) {
throw new JSONException("Null pointer");
}
@@ -763,7 +691,7 @@ public class LOGJSONObject {
String string = number.toString();
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
- string.indexOf('E') < 0) {
+ string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
@@ -797,7 +725,7 @@ public class LOGJSONObject {
try {
return this.getBoolean(key);
} catch (Exception e) {
- intlogger.trace("Using defaultValue: " + defaultValue, e);
+ intlogger.trace(USING_DEFAULT_VALUE + defaultValue, e);
return defaultValue;
}
}
@@ -816,7 +744,7 @@ public class LOGJSONObject {
try {
return this.getDouble(key);
} catch (Exception e) {
- intlogger.trace("Using defaultValue: " + defaultValue, e);
+ intlogger.trace(USING_DEFAULT_VALUE + defaultValue, e);
return defaultValue;
}
}
@@ -835,23 +763,11 @@ public class LOGJSONObject {
try {
return this.getInt(key);
} catch (Exception e) {
- intlogger.trace("Using defaultValue: " + defaultValue, e);
+ intlogger.trace(USING_DEFAULT_VALUE + defaultValue, e);
return defaultValue;
}
}
- /**
- * Get an optional JSONObject associated with a key.
- * It returns null if there is no such key, or if its value is not a
- * JSONObject.
- *
- * @param key A key string.
- * @return A JSONObject which is the value.
- */
- public LOGJSONObject optJSONObject(String key) {
- Object object = this.opt(key);
- return object instanceof LOGJSONObject ? (LOGJSONObject) object : null;
- }
/**
* Get an optional long value associated with a key,
@@ -885,15 +801,15 @@ public class LOGJSONObject {
}
private void populateMap(Object bean) {
- Class<? extends Object> klass = bean.getClass();
+ Class<?> klass = bean.getClass();
// If klass is a System class then set includeSuperClass to false.
boolean includeSuperClass = klass.getClassLoader() != null;
Method[] methods = includeSuperClass
- ? klass.getMethods()
- : klass.getDeclaredMethods();
+ ? klass.getMethods()
+ : klass.getDeclaredMethods();
for (int i = 0; i < methods.length; i += 1) {
try {
Method method = methods[i];
@@ -902,7 +818,7 @@ public class LOGJSONObject {
String key = "";
if (name.startsWith("get")) {
if ("getClass".equals(name) ||
- "getDeclaringClass".equals(name)) {
+ "getDeclaringClass".equals(name)) {
key = "";
} else {
key = name.substring(3);
@@ -911,13 +827,13 @@ public class LOGJSONObject {
key = name.substring(2);
}
if (key.length() > 0 &&
- Character.isUpperCase(key.charAt(0)) &&
- method.getParameterTypes().length == 0) {
+ Character.isUpperCase(key.charAt(0)) &&
+ method.getParameterTypes().length == 0) {
if (key.length() == 1) {
key = key.toLowerCase();
} else if (!Character.isUpperCase(key.charAt(1))) {
key = key.substring(0, 1).toLowerCase() +
- key.substring(1);
+ key.substring(1);
}
Object result = method.invoke(bean, (Object[]) null);
@@ -933,33 +849,6 @@ public class LOGJSONObject {
}
/**
- * Put a key/boolean pair in the JSONObject.
- *
- * @param key A key string.
- * @param value A boolean which is the value.
- * @return this.
- * @throws JSONException If the key is null.
- */
- public LOGJSONObject put(String key, boolean value) throws JSONException {
- this.put(key, value ? Boolean.TRUE : Boolean.FALSE);
- return this;
- }
-
- /**
- * Put a key/value pair in the JSONObject, where the value will be a
- * JSONArray which is produced from a Collection.
- *
- * @param key A key string.
- * @param value A Collection value.
- * @return this.
- * @throws JSONException
- */
- public LOGJSONObject put(String key, Collection<Object> value) throws JSONException {
- this.put(key, new JSONArray(value));
- return this;
- }
-
- /**
* Put a key/double pair in the JSONObject.
*
* @param key A key string.
@@ -967,7 +856,7 @@ public class LOGJSONObject {
* @return this.
* @throws JSONException If the key is null or if the number is invalid.
*/
- public LOGJSONObject put(String key, double value) throws JSONException {
+ public LOGJSONObject put(String key, double value) {
this.put(key, new Double(value));
return this;
}
@@ -980,7 +869,7 @@ public class LOGJSONObject {
* @return this.
* @throws JSONException If the key is null.
*/
- public LOGJSONObject put(String key, int value) throws JSONException {
+ public LOGJSONObject put(String key, int value) {
this.put(key, new Integer(value));
return this;
}
@@ -993,26 +882,12 @@ public class LOGJSONObject {
* @return this.
* @throws JSONException If the key is null.
*/
- public LOGJSONObject put(String key, long value) throws JSONException {
+ public LOGJSONObject put(String key, long value) {
this.put(key, new Long(value));
return this;
}
/**
- * Put a key/value pair in the JSONObject, where the value will be a
- * JSONObject which is produced from a Map.
- *
- * @param key A key string.
- * @param value A Map value.
- * @return this.
- * @throws JSONException
- */
- public LOGJSONObject put(String key, Map<String, Object> value) throws JSONException {
- this.put(key, new LOGJSONObject(value));
- return this;
- }
-
- /**
* Put a key/value pair in the JSONObject. If the value is null,
* then the key will be removed from the JSONObject if it is present.
*
@@ -1024,7 +899,7 @@ public class LOGJSONObject {
* @throws JSONException If the value is non-finite number
* or if the key is null.
*/
- public LOGJSONObject put(String key, Object value) throws JSONException {
+ public LOGJSONObject put(String key, Object value) {
String pooled;
if (key == null) {
throw new JSONException("Null key.");
@@ -1033,8 +908,8 @@ public class LOGJSONObject {
testValidity(value);
pooled = (String) keyPool.get(key);
if (pooled == null) {
- if (keyPool.size() >= keyPoolSize) {
- keyPool = new LinkedHashMap<String, Object>(keyPoolSize);
+ if (keyPool.size() >= KEY_POOL_SIZE) {
+ keyPool = new LinkedHashMap<>(KEY_POOL_SIZE);
}
keyPool.put(key, key);
} else {
@@ -1057,7 +932,7 @@ public class LOGJSONObject {
* @return his.
* @throws JSONException if the key is a duplicate
*/
- public LOGJSONObject putOnce(String key, Object value) throws JSONException {
+ public LOGJSONObject putOnce(String key, Object value) {
if (key != null && value != null) {
if (this.opt(key) != null) {
throw new JSONException("Duplicate key \"" + key + "\"");
@@ -1068,24 +943,6 @@ public class LOGJSONObject {
}
/**
- * Put a key/value pair in the JSONObject, but only if the
- * key and the value are both non-null.
- *
- * @param key A key string.
- * @param value An object which is the value. It should be of one of these
- * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
- * or the JSONObject.NULL object.
- * @return this.
- * @throws JSONException If the value is a non-finite number.
- */
- public LOGJSONObject putOpt(String key, Object value) throws JSONException {
- if (key != null && value != null) {
- this.put(key, value);
- }
- return this;
- }
-
- /**
* Produce a string in double quotes with backslash sequences in all the
* right places. A backslash will be inserted within </, producing <\/,
* allowing JSON text to be delivered in HTML. In JSON text, a string
@@ -1151,7 +1008,7 @@ public class LOGJSONObject {
break;
default:
if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
- || (c >= '\u2000' && c < '\u2100')) {
+ || (c >= '\u2000' && c < '\u2100')) {
w.write("\\u");
hhhh = Integer.toHexString(c);
w.write("0000", 0, 4 - hhhh.length());
@@ -1185,16 +1042,16 @@ public class LOGJSONObject {
*/
public static Object stringToValue(String string) {
Double d;
- if (string.equals("")) {
+ if ("".equals(string)) {
return string;
}
- if (string.equalsIgnoreCase("true")) {
+ if ("true".equalsIgnoreCase(string)) {
return Boolean.TRUE;
}
- if (string.equalsIgnoreCase("false")) {
+ if ("false".equalsIgnoreCase(string)) {
return Boolean.FALSE;
}
- if (string.equalsIgnoreCase("null")) {
+ if ("null".equalsIgnoreCase(string)) {
return LOGJSONObject.NULL;
}
@@ -1209,16 +1066,16 @@ public class LOGJSONObject {
char b = string.charAt(0);
if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {
try {
- if (string.indexOf('.') > -1 ||
- string.indexOf('e') > -1 || string.indexOf('E') > -1) {
+ if (string.indexOf('.') > -1 || string.indexOf('e') > -1
+ || string.indexOf('E') > -1) {
d = Double.valueOf(string);
if (!d.isInfinite() && !d.isNaN()) {
return d;
}
} else {
Long myLong = new Long(string);
- if (myLong.longValue() == myLong.intValue()) {
- return new Integer(myLong.intValue());
+ if (myLong == myLong.intValue()) {
+ return myLong.intValue();
} else {
return myLong;
}
@@ -1241,13 +1098,11 @@ public class LOGJSONObject {
if (o instanceof Double) {
if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
throw new JSONException(
- "JSON does not allow non-finite numbers.");
- }
- } else if (o instanceof Float) {
- if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
- throw new JSONException(
- "JSON does not allow non-finite numbers.");
+ "JSON does not allow non-finite numbers.");
}
+ } else if (o instanceof Float && (((Float) o).isInfinite() || ((Float) o).isNaN())) {
+ throw new JSONException(
+ "JSON does not allow non-finite numbers.");
}
}
}
@@ -1261,7 +1116,7 @@ public class LOGJSONObject {
* @return A JSONArray of values.
* @throws JSONException If any of the values are non-finite numbers.
*/
- public JSONArray toJSONArray(JSONArray names) throws JSONException {
+ public JSONArray toJSONArray(JSONArray names) {
if (names == null || names.length() == 0) {
return null;
}
@@ -1306,7 +1161,7 @@ public class LOGJSONObject {
* with <code>}</code>&nbsp;<small>(right brace)</small>.
* @throws JSONException If the object contains an invalid number.
*/
- public String toString(int indentFactor) throws JSONException {
+ public String toString(int indentFactor) {
StringWriter w = new StringWriter();
synchronized (w.getBuffer()) {
return this.write(w, indentFactor, 0).toString();
@@ -1336,27 +1191,27 @@ public class LOGJSONObject {
* @throws JSONException If the value is or contains an invalid number.
*/
@SuppressWarnings("unchecked")
- public static String valueToString(Object value) throws JSONException {
+ public static String valueToString(Object value) {
if (value == null) {
return "null";
}
if (value instanceof JSONString) {
- Object object;
+ String object;
try {
object = ((JSONString) value).toJSONString();
} catch (Exception e) {
throw new JSONException(e);
}
- if (object instanceof String) {
- return (String) object;
+ if (object != null) {
+ return object;
}
throw new JSONException("Bad value from toJSONString: " + object);
}
if (value instanceof Number) {
return numberToString((Number) value);
}
- if (value instanceof Boolean || value instanceof LOGJSONObject ||
- value instanceof JSONArray) {
+ if (value instanceof Boolean || value instanceof LOGJSONObject
+ || value instanceof JSONArray) {
return value.toString();
}
if (value instanceof Map) {
@@ -1390,12 +1245,12 @@ public class LOGJSONObject {
return NULL;
}
if (object instanceof LOGJSONObject || object instanceof JSONArray ||
- NULL.equals(object) || object instanceof JSONString ||
- object instanceof Byte || object instanceof Character ||
- object instanceof Short || object instanceof Integer ||
- object instanceof Long || object instanceof Boolean ||
- object instanceof Float || object instanceof Double ||
- object instanceof String) {
+ NULL.equals(object) || object instanceof JSONString ||
+ object instanceof Byte || object instanceof Character ||
+ object instanceof Short || object instanceof Integer ||
+ object instanceof Long || object instanceof Boolean ||
+ object instanceof Float || object instanceof Double ||
+ object instanceof String) {
return object;
}
@@ -1410,13 +1265,13 @@ public class LOGJSONObject {
}
Package objectPackage = object.getClass().getPackage();
String objectPackageName = objectPackage != null
- ? objectPackage.getName()
- : "";
+ ? objectPackage.getName()
+ : "";
if (
- objectPackageName.startsWith("java.") ||
- objectPackageName.startsWith("javax.") ||
- object.getClass().getClassLoader() == null
- ) {
+ objectPackageName.startsWith("java.") ||
+ objectPackageName.startsWith("javax.") ||
+ object.getClass().getClassLoader() == null
+ ) {
return object.toString();
}
return new LOGJSONObject(object);
@@ -1427,8 +1282,7 @@ public class LOGJSONObject {
}
@SuppressWarnings("unchecked")
- static final Writer writeValue(Writer writer, Object value,
- int indentFactor, int indent) throws JSONException, IOException {
+ static Writer writeValue(Writer writer, Object value, int indentFactor, int indent) throws IOException {
if (value == null) {
writer.write("null");
} else if (value instanceof LOGJSONObject) {
@@ -1438,8 +1292,7 @@ public class LOGJSONObject {
} else if (value instanceof Map) {
new LOGJSONObject((Map<String, Object>) value).write(writer, indentFactor, indent);
} else if (value instanceof Collection) {
- new JSONArray((Collection<Object>) value).write(writer, indentFactor,
- indent);
+ new JSONArray((Collection<Object>) value).write(writer, indentFactor, indent);
} else if (value.getClass().isArray()) {
new JSONArray(value).write(writer, indentFactor, indent);
} else if (value instanceof Number) {
@@ -1460,7 +1313,7 @@ public class LOGJSONObject {
return writer;
}
- static final void indent(Writer writer, int indent) throws IOException {
+ private static void indent(Writer writer, int indent) throws IOException {
for (int i = 0; i < indent; i += 1) {
writer.write(' ');
}
@@ -1476,7 +1329,7 @@ public class LOGJSONObject {
* @throws JSONException
*/
Writer write(Writer writer, int indentFactor, int indent)
- throws JSONException {
+ {
try {
boolean commanate = false;
final int length = this.length();
@@ -1508,7 +1361,7 @@ public class LOGJSONObject {
writer.write(' ');
}
writeValue(writer, this.map.get(key), indentFactor,
- newindent);
+ newindent);
commanate = true;
}
if (indentFactor > 0) {
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 c78a5b10..b48907fc 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
@@ -97,6 +97,19 @@ public class LogfileLoader extends Thread {
private long nextId;
private boolean idle;
+ private LogfileLoader() {
+ this.logger = EELFManager.getInstance().getLogger("InternalLog");
+ this.db = new DB();
+ this.spooldir = db.getProperties().getProperty("org.onap.dmaap.datarouter.provserver.spooldir");
+ this.setStart = getIdRange();
+ this.setEnd = setStart + SET_SIZE - 1;
+ this.seqSet = new RLEBitSet();
+ this.nextId = 0;
+ this.idle = false;
+ this.setDaemon(true);
+ this.setName("LogfileLoader");
+ }
+
/**
* Get the singleton LogfileLoader object, and start it if it is not running.
*
@@ -112,20 +125,6 @@ public class LogfileLoader extends Thread {
return logfileLoader;
}
-
- private LogfileLoader() {
- this.logger = EELFManager.getInstance().getLogger("InternalLog");
- this.db = new DB();
- this.spooldir = db.getProperties().getProperty("org.onap.dmaap.datarouter.provserver.spooldir");
- this.setStart = getIdRange();
- this.setEnd = setStart + SET_SIZE - 1;
- this.seqSet = new RLEBitSet();
- this.nextId = 0;
- this.idle = false;
- this.setDaemon(true);
- this.setName("LogfileLoader");
- }
-
private long getIdRange() {
long n;
if (BaseServlet.isInitialActivePOD()) {
@@ -211,7 +210,7 @@ public class LogfileLoader extends Thread {
int[] n = process(infile);
time = System.currentTimeMillis() - time;
logger.info(String.format("PROV8000 Processed %s in %d ms; %d of %d records.",
- infile.toString(), time, n[0], n[1]));
+ infile.toString(), time, n[0], n[1]));
try {
Files.delete(infile.toPath());
} catch (IOException e) {
@@ -281,7 +280,7 @@ public class LogfileLoader extends Thread {
stmt.execute("OPTIMIZE TABLE LOG_RECORDS");
}
} catch (SQLException e) {
- logger.error(e.toString());
+ logger.error("LogfileLoader.pruneRecords: " + e.getMessage(), e);
} finally {
db.release(conn);
}
@@ -289,46 +288,40 @@ public class LogfileLoader extends Thread {
return did1;
}
- long countRecords() {
+ private long countRecords() {
long count = 0;
- Connection conn = null;
- try {
- conn = db.getConnection();
- try (Statement stmt = conn.createStatement()) {
- try (ResultSet rs = stmt.executeQuery("SELECT COUNT(*) as COUNT from LOG_RECORDS")) {
- if (rs.next()) {
- count = rs.getLong("COUNT");
- }
+ try (Connection conn = db.getConnection();
+ Statement stmt = conn.createStatement()) {
+ try (ResultSet rs = stmt.executeQuery("SELECT COUNT(*) as COUNT from LOG_RECORDS")) {
+ if (rs.next()) {
+ count = rs.getLong("COUNT");
}
+ } finally {
+ db.release(conn);
}
} catch (SQLException e) {
- logger.error(e.toString());
- } finally {
- db.release(conn);
+ logger.error("LogfileLoader.countRecords: " + e.getMessage(), e);
}
return count;
}
- Map<Long, Long> getHistogram() {
+ private Map<Long, Long> getHistogram() {
Map<Long, Long> map = new HashMap<>();
- Connection conn = null;
- try {
+ try (Connection conn = db.getConnection();
+ Statement stmt = conn.createStatement()) {
logger.debug(" LOG_RECORD table histogram...");
- conn = db.getConnection();
- try (Statement stmt = conn.createStatement()) {
- try (ResultSet rs = stmt.executeQuery("SELECT FLOOR(EVENT_TIME/86400000) AS DAY, COUNT(*) AS COUNT FROM LOG_RECORDS GROUP BY DAY")) {
- while (rs.next()) {
- long day = rs.getLong("DAY");
- long cnt = rs.getLong("COUNT");
- map.put(day, cnt);
- logger.debug(" " + day + " " + cnt);
- }
+ try (ResultSet rs = stmt.executeQuery("SELECT FLOOR(EVENT_TIME/86400000) AS DAY, COUNT(*) AS COUNT FROM LOG_RECORDS GROUP BY DAY")) {
+ while (rs.next()) {
+ long day = rs.getLong("DAY");
+ long cnt = rs.getLong("COUNT");
+ map.put(day, cnt);
+ logger.debug(" " + day + " " + cnt);
}
+ } finally {
+ db.release(conn);
}
} catch (SQLException e) {
- logger.error(e.toString());
- } finally {
- db.release(conn);
+ logger.error("LogfileLoader.getHistogram: " + e.getMessage(), e);
}
return map;
}
@@ -377,9 +370,9 @@ public class LogfileLoader extends Thread {
nextId = (t == 0) ? setStart : (t - 1);
}
}
- logger.debug(String.format("initializeNextid, next ID is %d (%x)", nextId, nextId));
+ logger.debug(String.format("LogfileLoader.initializeNextid, next ID is %d (%x)", nextId, nextId));
} catch (SQLException e) {
- logger.error(e.toString());
+ logger.error("LogfileLoader.initializeNextid: " + e.getMessage(), e);
} finally {
db.release(conn);
}
@@ -393,8 +386,8 @@ public class LogfileLoader extends Thread {
Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(INSERT_SQL);
Reader r = f.getPath().endsWith(".gz")
- ? new InputStreamReader(new GZIPInputStream(new FileInputStream(f)))
- : new FileReader(f);
+ ? new InputStreamReader(new GZIPInputStream(new FileInputStream(f)))
+ : new FileReader(f);
try (LineNumberReader in = new LineNumberReader(r)) {
String line;
while ((line = in.readLine()) != null) {
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/PurgeLogDirTask.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/PurgeLogDirTask.java
index 8c67e71f..c34e9541 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/PurgeLogDirTask.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/PurgeLogDirTask.java
@@ -24,13 +24,13 @@
package org.onap.dmaap.datarouter.provisioning.utils;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
import java.io.File;
+import java.util.Objects;
import java.util.Properties;
import java.util.TimerTask;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-
/**
* This class provides a {@link TimerTask} that purges old logfiles (older than the number of days specified by the
* org.onap.dmaap.datarouter.provserver.logretention property).
@@ -50,9 +50,7 @@ public class PurgeLogDirTask extends TimerTask {
Properties p = (new DB()).getProperties();
logdir = p.getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir");
String s = p.getProperty("org.onap.dmaap.datarouter.provserver.logretention", "30");
-
this.utilsLogger = EELFManager.getInstance().getLogger("UtilsLog");
-
long n = 30;
try {
n = Long.parseLong(s);
@@ -67,15 +65,19 @@ public class PurgeLogDirTask extends TimerTask {
try {
File dir = new File(logdir);
if (dir.exists()) {
- long exptime = System.currentTimeMillis() - interval;
- for (File logfile : dir.listFiles()) {
- if (logfile.lastModified() < exptime) {
- logfile.delete();
- }
- }
+ purgeLogFiles(dir);
}
} catch (Exception e) {
utilsLogger.error("Exception: " + e.getMessage(), e);
}
}
+
+ private void purgeLogFiles(File dir) {
+ long exptime = System.currentTimeMillis() - interval;
+ for (File logfile : Objects.requireNonNull(dir.listFiles())) {
+ if (logfile.lastModified() < exptime) {
+ logfile.delete();
+ }
+ }
+ }
}
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 ffed1a1b..5813024c 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
@@ -28,7 +28,6 @@ import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import java.net.InetAddress;
import java.net.UnknownHostException;
-import java.util.Arrays;
import org.onap.dmaap.datarouter.provisioning.BaseServlet;
@@ -39,7 +38,14 @@ import org.onap.dmaap.datarouter.provisioning.BaseServlet;
* @version $Id: URLUtilities.java,v 1.2 2014/03/12 19:45:41 eby Exp $
*/
public class URLUtilities {
+
private static final EELFLogger utilsLogger = EELFManager.getInstance().getLogger("UtilsLog");
+ private static final String HTTPS = "https://";
+ private static String otherPod;
+
+ private URLUtilities() {
+ }
+
/**
* Generate the URL used to access a feed.
*
@@ -47,7 +53,7 @@ public class URLUtilities {
* @return the URL
*/
public static String generateFeedURL(int feedid) {
- return "https://" + BaseServlet.getProvName() + "/feed/" + feedid;
+ return HTTPS + BaseServlet.getProvName() + "/feed/" + feedid;
}
/**
@@ -57,7 +63,7 @@ public class URLUtilities {
* @return the URL
*/
public static String generatePublishURL(int feedid) {
- return "https://" + BaseServlet.getProvName() + "/publish/" + feedid;
+ return HTTPS + BaseServlet.getProvName() + "/publish/" + feedid;
}
/**
@@ -67,7 +73,7 @@ public class URLUtilities {
* @return the URL
*/
public static String generateSubscribeURL(int feedid) {
- return "https://" + BaseServlet.getProvName() + "/subscribe/" + feedid;
+ return HTTPS + BaseServlet.getProvName() + "/subscribe/" + feedid;
}
/**
@@ -77,7 +83,7 @@ public class URLUtilities {
* @return the URL
*/
public static String generateFeedLogURL(int feedid) {
- return "https://" + BaseServlet.getProvName() + "/feedlog/" + feedid;
+ return HTTPS + BaseServlet.getProvName() + "/feedlog/" + feedid;
}
/**
@@ -87,7 +93,7 @@ public class URLUtilities {
* @return the URL
*/
public static String generateSubscriptionURL(int subid) {
- return "https://" + BaseServlet.getProvName() + "/subs/" + subid;
+ return HTTPS + BaseServlet.getProvName() + "/subs/" + subid;
}
/**
@@ -97,7 +103,7 @@ public class URLUtilities {
* @return the URL
*/
public static String generateSubLogURL(int subid) {
- return "https://" + BaseServlet.getProvName() + "/sublog/" + subid;
+ return HTTPS + BaseServlet.getProvName() + "/sublog/" + subid;
}
/**
@@ -106,7 +112,7 @@ public class URLUtilities {
* @return the URL
*/
public static String generatePeerProvURL() {
- return "https://" + getPeerPodName() + "/internal/prov";
+ return HTTPS + getPeerPodName() + "/internal/prov";
}
/**
@@ -117,11 +123,11 @@ 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 == null || peerPodUrl.equals("")) {
+ if (peerPodUrl == null || "".equals(peerPodUrl)) {
return "";
}
- return "https://" + peerPodUrl + "/internal/drlogs/";
+ return HTTPS + peerPodUrl + "/internal/drlogs/";
}
/**
@@ -130,24 +136,21 @@ public class URLUtilities {
* @return the name
*/
public static String getPeerPodName() {
- if (other_pod == null) {
- String this_pod = "";
+ if (otherPod == null) {
+ String thisPod;
try {
- this_pod = InetAddress.getLocalHost().getHostName();
- System.out.println("this_pod: " + this_pod);
+ thisPod = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
utilsLogger.trace("UnkownHostException: " + e.getMessage(), e);
- this_pod = "";
+ thisPod = "";
}
- System.out.println("ALL PODS: " + Arrays.asList(BaseServlet.getPods()));
for (String pod : BaseServlet.getPods()) {
- if (!pod.equals(this_pod)) {
- other_pod = pod;
+ if (!pod.equals(thisPod)) {
+ otherPod = pod;
}
}
}
- return other_pod;
+ return otherPod;
}
- private static String other_pod;
}
diff --git a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/InternalServletTest.java b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/InternalServletTest.java
index edf9ef52..5239b800 100644
--- a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/InternalServletTest.java
+++ b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/InternalServletTest.java
@@ -44,6 +44,7 @@ import javax.servlet.http.HttpServletResponse;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import org.apache.commons.lang3.reflect.FieldUtils;
+import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -54,6 +55,7 @@ import org.mockito.Mock;
import org.onap.dmaap.datarouter.provisioning.beans.Deleteable;
import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
import org.onap.dmaap.datarouter.provisioning.beans.LogRecord;
+import org.onap.dmaap.datarouter.provisioning.beans.Parameters;
import org.onap.dmaap.datarouter.provisioning.beans.Updateable;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
@@ -277,6 +279,16 @@ public class InternalServletTest extends DrServletTestBase {
}
@Test
+ public void Given_Request_Is_HTTP_DELETE_With_LogRollInterval_Api_In_Endpoint_Request_Succeeds() {
+ when(request.getPathInfo()).thenReturn("/api/LOGROLL_INTERVAL");
+ internalServlet.doDelete(request, response);
+ verify(response).setStatus(eq(HttpServletResponse.SC_OK));
+ Parameters p1 = Parameters.getParameter("NODES");
+ Assert.assertEquals("{\"keyname\":\"NODES\",\"value\":\"dmaap-dr-node\"}", p1.asJSONObject().toString());
+ Assert.assertEquals("PARAM: keyname=NODES, value=dmaap-dr-node", p1.toString());
+ }
+
+ @Test
public void Given_Request_Is_HTTP_DELETE_With_Api_In_Endpoint_And_Delete_Fails_Then_Internal_Server_Error_Is_Generated()
throws Exception {
when(request.getPathInfo()).thenReturn("/api/NODES");
@@ -332,8 +344,7 @@ public class InternalServletTest extends DrServletTestBase {
}
@Test
- public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated()
- throws Exception {
+ public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated() {
when(request.getHeader("Content-Type")).thenReturn("stub_contentType");
when(request.getPathInfo()).thenReturn("/logs/");
internalServlet.doPost(request, response);
@@ -341,8 +352,7 @@ public class InternalServletTest extends DrServletTestBase {
}
@Test
- public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Encoding_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated()
- throws Exception {
+ public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Encoding_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated() {
when(request.getHeader("Content-Encoding")).thenReturn("not-supported");
when(request.getPathInfo()).thenReturn("/logs/");
internalServlet.doPost(request, response);
@@ -364,8 +374,7 @@ public class InternalServletTest extends DrServletTestBase {
}
@Test
- public void Given_Request_Is_HTTP_POST_To_Drlogs_And_Then_Unsupported_Media_Type_Response_Is_Generated()
- throws Exception {
+ public void Given_Request_Is_HTTP_POST_To_Drlogs_And_Then_Unsupported_Media_Type_Response_Is_Generated() {
when(request.getHeader("Content-Type")).thenReturn("stub_contentType");
when(request.getPathInfo()).thenReturn("/drlogs/");
internalServlet.doPost(request, response);
@@ -384,6 +393,13 @@ public class InternalServletTest extends DrServletTestBase {
}
@Test
+ public void Given_Request_Is_HTTP_POST_To_Api_And_Request_Succeeds() {
+ when(request.getPathInfo()).thenReturn("/api/NEW_PARAM?val=blah");
+ internalServlet.doPost(request, response);
+ verify(response).setStatus(eq(HttpServletResponse.SC_OK));
+ }
+
+ @Test
public void Given_Request_Is_HTTP_POST_With_Incorrect_Endpoint_Then_Not_Found_Error_Is_Generated()
throws Exception {
when(request.getPathInfo()).thenReturn("/incorrect/");
diff --git a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/beans/EgressRouteTest.java b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/beans/EgressRouteTest.java
new file mode 100644
index 00000000..7ef52ff8
--- /dev/null
+++ b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/beans/EgressRouteTest.java
@@ -0,0 +1,90 @@
+/*-
+ * ============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.beans;
+
+import java.sql.SQLException;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.onap.dmaap.datarouter.provisioning.utils.DB;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+public class EgressRouteTest {
+
+ private EgressRoute egressRoute;
+
+ 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 {
+ db = new DB();
+ egressRoute = new EgressRoute(2, 1);
+ }
+
+ @Test
+ public void Verify_NetworkRoute_Is_Added_Successfully() throws SQLException {
+ Assert.assertEquals(1, EgressRoute.getAllEgressRoutes().size());
+ egressRoute.doInsert(db.getConnection());
+ Assert.assertEquals(2, EgressRoute.getAllEgressRoutes().size());
+ egressRoute.doDelete(db.getConnection());
+ }
+
+ @Test
+ public void Verify_NetworkRoute_Is_Removed_Successfully() throws SQLException {
+ Assert.assertEquals(1, EgressRoute.getAllEgressRoutes().size());
+ EgressRoute egressRoute = new EgressRoute(1, 1);
+ egressRoute.doDelete(db.getConnection());
+ Assert.assertEquals(0, EgressRoute.getAllEgressRoutes().size());
+ }
+
+ @Test
+ public void Verify_NetworkRoute_Is_Updated_Successfully() throws SQLException {
+ EgressRoute egressRoute = new EgressRoute(1, 1);
+ EgressRoute egressRoute1 = new EgressRoute(1, 1);
+ Assert.assertEquals(egressRoute.hashCode(), egressRoute1.hashCode());
+ Assert.assertEquals(egressRoute, egressRoute1);
+ Assert.assertEquals(egressRoute.toString(), egressRoute1.toString());
+ }
+} \ No newline at end of file
diff --git a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/beans/NetworkRouteTest.java b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/beans/NetworkRouteTest.java
new file mode 100644
index 00000000..df786b55
--- /dev/null
+++ b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/beans/NetworkRouteTest.java
@@ -0,0 +1,96 @@
+/*-
+ * ============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.beans;
+
+import java.sql.SQLException;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.onap.dmaap.datarouter.provisioning.utils.DB;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+public class NetworkRouteTest {
+
+ private NetworkRoute networkRoute;
+
+ 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 {
+ db = new DB();
+ networkRoute = new NetworkRoute("node01.","node03.","node02.");
+ }
+
+ @Test
+ public void Verify_NetworkRoute_Is_Added_Successfully() throws SQLException {
+ Assert.assertEquals(1, NetworkRoute.getAllNetworkRoutes().size());
+ networkRoute.doInsert(db.getConnection());
+ Assert.assertEquals(2, NetworkRoute.getAllNetworkRoutes().size());
+ networkRoute.doDelete(db.getConnection());
+ }
+
+ @Test
+ public void Verify_NetworkRoute_Is_Removed_Successfully() throws SQLException {
+ Assert.assertEquals(1, NetworkRoute.getAllNetworkRoutes().size());
+ NetworkRoute networkRoute = new NetworkRoute("stub_from.", "stub_to.");
+ networkRoute.doDelete(db.getConnection());
+ Assert.assertEquals(0, NetworkRoute.getAllNetworkRoutes().size());
+ }
+
+ @Test
+ public void Verify_NetworkRoute_Is_Updated_Successfully() throws SQLException {
+ NetworkRoute networkRoute = new NetworkRoute("stub_from.", "stub_to.", "node02.");
+ networkRoute.doUpdate(db.getConnection());
+ //Assert.assertTrue(NetworkRoute.getAllNetworkRoutes().contains(networkRoute));
+ for (NetworkRoute net :
+ NetworkRoute.getAllNetworkRoutes()) {
+ Assert.assertEquals(5, net.getVianode());
+ }
+ NetworkRoute networkRoute1 = new NetworkRoute("stub_from.", "stub_to.", "node02.");
+ Assert.assertEquals(networkRoute.hashCode(), networkRoute1.hashCode());
+ Assert.assertEquals(networkRoute, networkRoute1);
+ Assert.assertEquals(networkRoute.toString(), networkRoute1.toString());
+ }
+} \ No newline at end of file
diff --git a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/utils/DbTest.java b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/utils/DbTest.java
new file mode 100644
index 00000000..056469a8
--- /dev/null
+++ b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/utils/DbTest.java
@@ -0,0 +1,61 @@
+/*-
+ * ============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.utils;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+public class DbTest {
+ private static EntityManagerFactory emf;
+ private static EntityManager em;
+
+ private DB db = new DB();
+
+ @BeforeClass
+ public static void init() {
+ emf = Persistence.createEntityManagerFactory("db-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();
+ }
+
+ @Test
+ public void Verify_DB_Is_Initialised_Successfully() {
+ Assert.assertTrue(db.runRetroFits());
+ }
+
+}
diff --git a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/utils/LOGJSONObjectTest.java b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/utils/LOGJSONObjectTest.java
index 4dd1b471..ae81f15d 100755
--- a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/utils/LOGJSONObjectTest.java
+++ b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/utils/LOGJSONObjectTest.java
@@ -24,6 +24,7 @@
package org.onap.dmaap.datarouter.provisioning.utils;
import java.io.CharArrayWriter;
+import java.io.IOException;
import java.io.Writer;
import org.json.JSONArray;
import org.json.JSONTokener;
@@ -50,8 +51,7 @@ public class LOGJSONObjectTest {
}
@Test
- public void Construct_JSONObject_From_A_Subset_Of_Values_From_Another_JSONObject()
- throws Exception {
+ public void Construct_JSONObject_From_A_Subset_Of_Values_From_Another_JSONObject() {
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
@@ -63,48 +63,41 @@ public class LOGJSONObjectTest {
}
@Test
- public void Construct_JSONObject_From_A_JSONTokener()
- throws Exception {
+ public void Construct_JSONObject_From_A_JSONTokener() {
JSONTokener x = new JSONTokener("{\"key1\":\"value1\",\"key3\":\"value3\"}");
LOGJSONObject logJObject = new LOGJSONObject(x);
assertThat(logJObject.toString(), is("{\"key1\":\"value1\",\"key3\":\"value3\"}"));
}
@Test
- public void Construct_JSONObject_From_A_Bean_Object_And_Populate_From_Its_Getters_And_Setters()
- throws Exception {
+ public void Construct_JSONObject_From_A_Bean_Object_And_Populate_From_Its_Getters_And_Setters() {
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
- Object bean = map;
- LOGJSONObject logJObject = new LOGJSONObject(bean);
+ LOGJSONObject logJObject = new LOGJSONObject((Object) map);
assertThat(logJObject.toString(), is("{\"empty\":false}"));
}
@Test
- public void Given_Method_Is_Accumulate_And_Value_Is_Valid_Put_Value_Into_New_JSONArray()
- throws Exception {
+ public void Given_Method_Is_Accumulate_And_Value_Is_Valid_Put_Value_Into_New_JSONArray() {
Map<String, Object> map = new HashMap<>();
map.put("key", 3);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
logJObject.accumulate(s, null);
assertThat(logJObject.get("key").toString(), is("[3,null]"));
}
@Test
- public void Given_Method_Is_Accumulate_And_Value_Is_Null_Dont_Add_Key_Value_Pair()
- throws Exception {
+ public void Given_Method_Is_Accumulate_And_Value_Is_Null_Dont_Add_Key_Value_Pair() {
String s = "key";
logJO.accumulate(s, null);
assertThat(logJO.has("key"), is(false));
}
@Test
- public void Given_Method_Is_Append_And_Value_Is_Null_Append_New_Value()
- throws Exception {
+ public void Given_Method_Is_Append_And_Value_Is_Null_Append_New_Value() {
String s = "key";
double d = 2.0;
logJO.append(s, d);
@@ -113,417 +106,334 @@ public class LOGJSONObjectTest {
@Test
- public void Given_Method_Is_DoubleToString_And_Value_Is_NaN_Return_Null()
- throws Exception {
+ public void Given_Method_Is_DoubleToString_And_Value_Is_NaN_Return_Null() {
double d = 2.0;
- assertThat(logJO.doubleToString(d), is("2"));
+ assertThat(LOGJSONObject.doubleToString(d), is("2"));
}
@Test
- public void Given_Method_Is_GetBoolean_And_Value_Is_False_Return_False()
- throws Exception {
+ public void Given_Method_Is_GetBoolean_And_Value_Is_False_Return_False() {
Map<String, Object> map = new HashMap<>();
map.put("key", false);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getBoolean(s), is(false));
}
@Test
- public void Given_Method_Is_GetBoolean_And_Value_Is_True_Return_True()
- throws Exception {
+ public void Given_Method_Is_GetBoolean_And_Value_Is_True_Return_True() {
Map<String, Object> map = new HashMap<>();
map.put("key", true);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getBoolean(s), is(true));
}
@Test
- public void Given_Method_Is_GetDouble_And_Value_Is_A_Double_Return_Value()
- throws Exception {
+ public void Given_Method_Is_GetDouble_And_Value_Is_A_Double_Return_Value() {
Map<String, Object> map = new HashMap<>();
map.put("key", 2.0);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getDouble(s), is(2.0));
}
@Test
- public void Given_Method_Is_GetInt_And_Value_Is_An_Int_Return_Value()
- throws Exception {
+ public void Given_Method_Is_GetInt_And_Value_Is_An_Int_Return_Value() {
Map<String, Object> map = new HashMap<>();
map.put("key", 3);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getInt(s), is(3));
}
@Test
- public void Given_Method_Is_GetJSONArray_And_Value_Is_A_JSONArray_Return_Value()
- throws Exception {
+ public void Given_Method_Is_GetJSONArray_And_Value_Is_A_JSONArray_Return_Value() {
JSONArray jA = new JSONArray();
Map<String, Object> map = new HashMap<>();
map.put("key", jA);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getJSONArray(s), is(jA));
}
@Test
- public void Given_Method_Is_GetJSONObject_And_Value_Is_A_JSONObject_Return_Value()
- throws Exception {
+ public void Given_Method_Is_GetJSONObject_And_Value_Is_A_JSONObject_Return_Value() {
LOGJSONObject logJObj = new LOGJSONObject();
logJObj.put("stub_key", 1);
Map<String, Object> map = new HashMap<>();
map.put("key", logJObj);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getJSONObject(s), is(logJObj));
}
@Test
- public void Given_Method_Is_GetLong_And_Value_Is_A_Long_Return_Value()
- throws Exception {
+ public void Given_Method_Is_GetLong_And_Value_Is_A_Long_Return_Value() {
long l = 5;
Map<String, Object> map = new HashMap<>();
map.put("key", l);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getLong(s), is(5L));
}
@Test
- public void Given_Method_Is_getNames_And_Value_Is_A_LOGJSONObject_Return_StringArray()
- throws Exception {
+ public void Given_Method_Is_getNames_And_Value_Is_A_LOGJSONObject_Return_StringArray() {
LOGJSONObject logJObj = new LOGJSONObject();
logJObj.put("name1", "elyk");
String[] sArray = new String[logJObj.length()];
sArray[0] = "name1";
- LOGJSONObject logJObject = new LOGJSONObject();
-
- assertThat(logJObject.getNames(logJObj), is(sArray));
+ assertThat(LOGJSONObject.getNames(logJObj), is(sArray));
}
@Test
- public void Given_Method_Is_GetString_And_Value_Is_A_String_Return_Value()
- throws Exception {
+ public void Given_Method_Is_GetString_And_Value_Is_A_String_Return_Value() {
String val = "value";
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getString(s), is("value"));
}
@Test
- public void Given_Method_Is_Increment_And_Value_Is_Null_Put_Defualt_Value()
- throws Exception {
+ public void Given_Method_Is_Increment_And_Value_Is_Null_Put_Defualt_Value() {
Map<String, Object> mapResult = new HashMap<>();
mapResult.put("key", 1);
LOGJSONObject logJObjectResult = new LOGJSONObject(mapResult);
-
String val = null;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
logJObject.increment(s);
assertThat(logJObject.get("key"), is(logJObjectResult.get("key")));
}
@Test
- public void Given_Method_Is_Increment_And_Value_Is_An_Int_Put_Value_Plus_One()
- throws Exception {
+ public void Given_Method_Is_Increment_And_Value_Is_An_Int_Put_Value_Plus_One() {
Map<String, Object> mapResult = new HashMap<>();
mapResult.put("key", 3);
LOGJSONObject logJObjectResult = new LOGJSONObject(mapResult);
-
int val = 2;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
logJObject.increment(s);
assertThat(logJObject.get("key"), is(logJObjectResult.get("key")));
}
@Test
- public void Given_Method_Is_Increment_And_Value_Is_A_Long_Put_Value_Plus_One()
- throws Exception {
+ public void Given_Method_Is_Increment_And_Value_Is_A_Long_Put_Value_Plus_One() {
Map<String, Object> mapResult = new HashMap<>();
mapResult.put("key", 4L);
LOGJSONObject logJObjectResult = new LOGJSONObject(mapResult);
-
long val = 3;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
logJObject.increment(s);
assertThat(logJObject.get("key"), is(logJObjectResult.get("key")));
}
@Test
- public void Given_Method_Is_Increment_And_Value_Is_A_Double_Put_Value_Plus_One()
- throws Exception {
+ public void Given_Method_Is_Increment_And_Value_Is_A_Double_Put_Value_Plus_One() {
Map<String, Object> mapResult = new HashMap<>();
mapResult.put("key", 5.0);
LOGJSONObject logJObjectResult = new LOGJSONObject(mapResult);
-
double val = 4.0;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
logJObject.increment(s);
assertThat(logJObject.get("key"), is(logJObjectResult.get("key")));
}
@Test
- public void Given_Method_Is_Increment_And_Value_Is_A_Float_Put_Value_Plus_One()
- throws Exception {
+ public void Given_Method_Is_Increment_And_Value_Is_A_Float_Put_Value_Plus_One() {
Map<String, Object> mapResult = new HashMap<>();
mapResult.put("key", 5.0);
LOGJSONObject logJObjectResult = new LOGJSONObject(mapResult);
-
float val = 4.0f;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
logJObject.increment(s);
assertThat(logJObject.get("key"), is(logJObjectResult.get("key")));
}
@Test
- public void Given_Method_Is_Names_And_Object_Contains_Keys_Put_Keys_Into_New_JSONArray()
- throws Exception {
+ public void Given_Method_Is_Names_And_Object_Contains_Keys_Put_Keys_Into_New_JSONArray() {
JSONArray ja = new JSONArray();
ja.put("key");
-
String val = "value";
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
- String s = "key";
assertThat(logJObject.names().get(0), is(ja.get(0)));
}
@Test
- public void Given_Method_Is_NumberToString_And_Number_is_Not_Null_Return_Reformatted_Number_As_String()
- throws Exception {
+ public void Given_Method_Is_NumberToString_And_Number_is_Not_Null_Return_Reformatted_Number_As_String() {
Number num = 3.0;
-
String val = "value";
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.numberToString(num), is("3"));
}
@Test
- public void Given_Method_Is_OptBoolean_And_Value_is_Boolean_Return_Value()
- throws Exception {
+ public void Given_Method_Is_OptBoolean_And_Value_is_Boolean_Return_Value() {
boolean val = true;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optBoolean(s, false), is(true));
}
@Test
- public void Given_Method_Is_OptBoolean_And_Value_is_Not_Boolean_Return_Default_Value()
- throws Exception {
+ public void Given_Method_Is_OptBoolean_And_Value_is_Not_Boolean_Return_Default_Value() {
String val = "not_boolean";
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optBoolean(s, false), is(false));
}
@Test
- public void Given_Method_Is_OptDouble_And_Value_is_Double_Return_Value()
- throws Exception {
+ public void Given_Method_Is_OptDouble_And_Value_is_Double_Return_Value() {
double val = 2.0;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optDouble(s, 0.0), is(2.0));
}
@Test
- public void Given_Method_Is_OptDouble_And_Value_is_Not_Double_Return_Default_Value()
- throws Exception {
+ public void Given_Method_Is_OptDouble_And_Value_is_Not_Double_Return_Default_Value() {
String val = "not_double";
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optDouble(s, 0.0), is(0.0));
}
@Test
- public void Given_Method_Is_OptInt_And_Value_is_Int_Return_Value()
- throws Exception {
+ public void Given_Method_Is_OptInt_And_Value_is_Int_Return_Value() {
int val = 1;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optInt(s, 0), is(1));
}
@Test
- public void Given_Method_Is_OptInt_And_Value_Is_Null_Return_Default_Value()
- throws Exception {
+ public void Given_Method_Is_OptInt_And_Value_Is_Null_Return_Default_Value() {
Map<String, Object> map = new HashMap<>();
map.put("key", null);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optInt(s, 0), is(0));
}
@Test
- public void Given_Method_Is_OptLong_And_Value_is_Long_Return_Value()
- throws Exception {
+ public void Given_Method_Is_OptLong_And_Value_is_Long_Return_Value() {
long val = 4;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optLong(s, 0), is(4L));
}
@Test
- public void Given_Method_Is_OptLong_And_Value_is_Not_Long_Return_Default_Value()
- throws Exception {
+ public void Given_Method_Is_OptLong_And_Value_is_Not_Long_Return_Default_Value() {
Map<String, Object> map = new HashMap<>();
map.put("key", null);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optLong(s, 0), is(0L));
}
@Test
- public void Given_Method_Is_OptString_And_Value_is_String_Return_Value()
- throws Exception {
+ public void Given_Method_Is_OptString_And_Value_is_String_Return_Value() {
String val = "value";
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optString(s, "default_value"), is("value"));
}
@Test
- public void Given_Method_Is_putOnce_And_KeyValuePair_Does_Not_Exist_In_logJObject_Put_KeyValuePair_Into_logJObject()
- throws Exception {
+ public void Given_Method_Is_putOnce_And_KeyValuePair_Does_Not_Exist_In_logJObject_Put_KeyValuePair_Into_logJObject() {
String val = "value";
Map<String, Object> map = new HashMap<>();
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.putOnce(s, val).get("key"), is("value"));
}
@Test
- public void Given_Method_Is_StringToValue_And_Value_Is_Number_Return_Number()
- throws Exception {
+ public void Given_Method_Is_StringToValue_And_Value_Is_Number_Return_Number() {
String val = "312";
Map<String, Object> map = new HashMap<>();
- LOGJSONObject logJObject = new LOGJSONObject(map);
-
- assertThat(logJObject.stringToValue(val), is(312));
+ assertThat(LOGJSONObject.stringToValue(val), is(312));
}
@Test
- public void Given_Method_Is_ToJSONArray_And_KeyValue_Exists_Return_Value_Array()
- throws Exception {
+ public void Given_Method_Is_ToJSONArray_And_KeyValue_Exists_Return_Value_Array() {
JSONArray names = new JSONArray();
Map<String, Object> map = new HashMap<>();
map.put("name", "value");
names.put("name");
LOGJSONObject logJObject = new LOGJSONObject(map);
-
assertThat(logJObject.toJSONArray(names).get(0), is("value"));
}
@Test
- public void Given_Method_Is_ValueToString_And_Value_Is_JSONArray_Return_Value_To_String()
- throws Exception {
+ public void Given_Method_Is_ValueToString_And_Value_Is_JSONArray_Return_Value_To_String() {
JSONArray val = new JSONArray();
- Map<String, Object> map = new HashMap<>();
- map.put("key", "value");
val.put("value");
- LOGJSONObject logJObject = new LOGJSONObject(map);
-
- assertThat(logJObject.valueToString(val), is("[\"value\"]"));
+ assertThat(LOGJSONObject.valueToString(val), is("[\"value\"]"));
}
@Test
- public void Given_Method_Is_writeValue_And_Value_IS_Not_Null_Return_Writer_With_Value()
- throws Exception {
+ public void Given_Method_Is_writeValue_And_Value_IS_Not_Null_Return_Writer_With_Value() throws IOException {
Writer writer = new CharArrayWriter();
String val = "value";
- Map<String, Object> map = new HashMap<>();
- map.put("key", "value");
- LOGJSONObject logJObject = new LOGJSONObject(map);
-
- assertThat(logJObject.writeValue(writer, val, 3, 1).toString(), is("\"value\""));
+ assertThat(LOGJSONObject.writeValue(writer, val, 3, 1).toString(), is("\"value\""));
}
@Test
- public void Given_Method_Is_write_And_Length_Of_logJObject_Is_One_Write_Value_With_Indent()
- throws Exception {
+ public void Given_Method_Is_write_And_Length_Of_logJObject_Is_One_Write_Value_With_Indent() {
Writer writer = new CharArrayWriter();
- String val = "value";
Map<String, Object> map = new HashMap<>();
map.put("key", "value");
LOGJSONObject logJObject = new LOGJSONObject(map);
-
assertThat(logJObject.write(writer, 3, 1).toString(), is("{\"key\": \"value\"}"));
}
@Test
- public void Given_Method_Is_write_And_Length_Of_logJObject_Is_Not_One_Or_Zero_Write_Value_With_New_Indent()
- throws Exception {
+ public void Given_Method_Is_write_And_Length_Of_logJObject_Is_Not_One_Or_Zero_Write_Value_With_New_Indent() {
Writer writer = new CharArrayWriter();
- String val = "value";
Map<String, Object> map = new HashMap<>();
map.put("key", "value");
map.put("key1", "value1");
LOGJSONObject logJObject = new LOGJSONObject(map);
-
assertThat(logJObject.write(writer, 3, 1).toString(), is("{\n \"key1\": \"value1\",\n \"key\": \"value\"\n }"));
}
}
diff --git a/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/utils/PurgeLogDirTaskTest.java b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/utils/PurgeLogDirTaskTest.java
new file mode 100644
index 00000000..604b4c0a
--- /dev/null
+++ b/datarouter-prov/src/test/java/org/onap/dmaap/datarouter/provisioning/utils/PurgeLogDirTaskTest.java
@@ -0,0 +1,87 @@
+/*-
+ * ============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.utils;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.nio.file.Files;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+public class PurgeLogDirTaskTest {
+
+ private static EntityManagerFactory emf;
+ private static EntityManager em;
+ private PurgeLogDirTask purgeLogDirTask = new PurgeLogDirTask();
+ private File testLog;
+
+ @Before
+ public void setUp() throws Exception {
+ testLog = new File(System.getProperty("user.dir") + "/src/test/resources/IN.test_prov_logs");
+ prepFile(testLog);
+ }
+
+ @After
+ public void tearDown() throws IOException {
+ Files.deleteIfExists(testLog.toPath());
+ }
+
+ @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();
+ }
+
+ @Test
+ public void Verify_Logs_Are_Purged() {
+ purgeLogDirTask.run();
+ }
+
+ private void prepFile(File logFile) {
+ try (FileWriter fileWriter = new FileWriter(logFile)) {
+ fileWriter.write("2018-08-29-10-10-10-543.|LOG|1|1|https://dmaap-dr-prov:/url/file123|POST|application/vnd.att-dr.feed|100|mockType|file123|https://dmaap-dr-prov|user123|200|1|1|200|2|2\n");
+ }
+ catch (IOException e){
+ System.out.println(e.getMessage());
+ }
+ }
+}
diff --git a/datarouter-prov/src/test/resources/META-INF/persistence.xml b/datarouter-prov/src/test/resources/META-INF/persistence.xml
index 83813e23..2cb798af 100755
--- a/datarouter-prov/src/test/resources/META-INF/persistence.xml
+++ b/datarouter-prov/src/test/resources/META-INF/persistence.xml
@@ -18,4 +18,18 @@
</properties>
</persistence-unit>
+ <persistence-unit name="db-unit-tests" transaction-type="RESOURCE_LOCAL">
+ <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
+ <properties>
+ <!-- Configuring JDBC properties -->
+ <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test1;DB_CLOSE_DELAY=-1"/>
+ <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
+ <!-- Hibernate properties -->
+ <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
+ <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
+ <property name="hibernate.format_sql" value="false"/>
+ <property name="hibernate.show_sql" value="true"/>
+
+ </properties>
+ </persistence-unit>
</persistence>
diff --git a/datarouter-prov/src/test/resources/create.sql b/datarouter-prov/src/test/resources/create.sql
index a811847c..74b63242 100755
--- a/datarouter-prov/src/test/resources/create.sql
+++ b/datarouter-prov/src/test/resources/create.sql
@@ -180,10 +180,10 @@ INSERT INTO FEEDS(FEEDID, GROUPID, NAME, VERSION, DESCRIPTION, BUSINESS_DESCRIPT
VALUES (3, 1,'DeleteableAafFeed','v0.1', 'AAF Feed3 for testing', 'AAF Feed3 for testing', 'auth_class', 'pub','self_link','publish_link','subscribe_link','log_link','*');
insert into INGRESS_ROUTES(SEQUENCE, FEEDID , USERID, SUBNET, NODESET)
-VALUES (1,1,'user',null,2);
+VALUES (1,1,'user','172.100.0.0/25',2);
insert into INGRESS_ROUTES(SEQUENCE, FEEDID , USERID, SUBNET, NODESET)
-VALUES (2,1,'user',null,2);
+VALUES (2,1,'user2',null,2);
insert into NODESETS(SETID, NODEID)
VALUES (1,1);
diff --git a/datarouter-prov/src/test/resources/h2Database.properties b/datarouter-prov/src/test/resources/h2Database.properties
index cb472419..991fadc5 100755
--- a/datarouter-prov/src/test/resources/h2Database.properties
+++ b/datarouter-prov/src/test/resources/h2Database.properties
@@ -28,6 +28,7 @@ org.onap.dmaap.datarouter.provserver.isaddressauthenabled = true
org.onap.dmaap.datarouter.provserver.https.relaxation = false
org.onap.dmaap.datarouter.provserver.accesslog.dir = unit-test-logs
org.onap.dmaap.datarouter.provserver.spooldir = src/test/resources
+org.onap.dmaap.datarouter.provserver.dbscripts = src/test/resources
org.onap.dmaap.datarouter.provserver.localhost = 127.0.0.1
org.onap.dmaap.datarouter.provserver.passwordencryption = PasswordEncryptionKey#@$%^&1234#
diff --git a/datarouter-prov/src/test/resources/sql_init_01.sql b/datarouter-prov/src/test/resources/sql_init_01.sql
new file mode 100755
index 00000000..1ac74a03
--- /dev/null
+++ b/datarouter-prov/src/test/resources/sql_init_01.sql
@@ -0,0 +1,146 @@
+CREATE TABLE FEEDS (
+ FEEDID INT UNSIGNED NOT NULL PRIMARY KEY,
+ GROUPID INT(10) UNSIGNED NOT NULL DEFAULT 0,
+ NAME VARCHAR(256) NOT NULL,
+ VERSION VARCHAR(20) NULL,
+ DESCRIPTION VARCHAR(1000),
+ BUSINESS_DESCRIPTION VARCHAR(1000) DEFAULT NULL,
+ AUTH_CLASS VARCHAR(32) NOT NULL,
+ PUBLISHER VARCHAR(8) NOT NULL,
+ SELF_LINK VARCHAR(256),
+ PUBLISH_LINK VARCHAR(256),
+ SUBSCRIBE_LINK VARCHAR(256),
+ LOG_LINK VARCHAR(256),
+ DELETED BOOLEAN DEFAULT FALSE,
+ LAST_MOD TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ SUSPENDED BOOLEAN DEFAULT FALSE,
+ CREATED_DATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ AAF_INSTANCE VARCHAR(256)
+);
+
+CREATE TABLE FEED_ENDPOINT_IDS (
+ FEEDID INT UNSIGNED NOT NULL,
+ USERID VARCHAR(60) NOT NULL,
+ PASSWORD VARCHAR(100) NOT NULL
+);
+
+CREATE TABLE FEED_ENDPOINT_ADDRS (
+ FEEDID INT UNSIGNED NOT NULL,
+ ADDR VARCHAR(44) NOT NULL
+);
+
+CREATE TABLE SUBSCRIPTIONS (
+ SUBID INT UNSIGNED NOT NULL PRIMARY KEY,
+ FEEDID INT UNSIGNED NOT NULL,
+ GROUPID INT(10) UNSIGNED NOT NULL DEFAULT 0,
+ DELIVERY_URL VARCHAR(256),
+ FOLLOW_REDIRECTS TINYINT(1) NOT NULL DEFAULT 0,
+ DELIVERY_USER VARCHAR(60),
+ DELIVERY_PASSWORD VARCHAR(100),
+ DELIVERY_USE100 BOOLEAN DEFAULT FALSE,
+ METADATA_ONLY BOOLEAN DEFAULT FALSE,
+ SUBSCRIBER VARCHAR(8) NOT NULL,
+ SELF_LINK VARCHAR(256),
+ LOG_LINK VARCHAR(256),
+ LAST_MOD TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ SUSPENDED BOOLEAN DEFAULT FALSE,
+ PRIVILEGED_SUBSCRIBER BOOLEAN DEFAULT FALSE,
+ CREATED_DATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ DECOMPRESS BOOLEAN DEFAULT FALSE,
+ AAF_INSTANCE VARCHAR(256)
+
+);
+
+CREATE TABLE PARAMETERS (
+ KEYNAME VARCHAR(32) NOT NULL PRIMARY KEY,
+ VALUE VARCHAR(4096) NOT NULL
+);
+
+CREATE TABLE LOG_RECORDS (
+ TYPE ENUM('pub', 'del', 'exp', 'pbf', 'dlx') NOT NULL,
+ EVENT_TIME BIGINT NOT NULL, /* time of the publish request */
+ PUBLISH_ID VARCHAR(64) NOT NULL, /* unique ID assigned to this publish attempt */
+ FEEDID INT UNSIGNED NOT NULL, /* pointer to feed in FEEDS */
+ REQURI VARCHAR(256) NOT NULL, /* request URI */
+ METHOD ENUM('DELETE', 'GET', 'HEAD', 'OPTIONS', 'PUT', 'POST', 'TRACE') NOT NULL, /* HTTP method */
+ CONTENT_TYPE VARCHAR(256) NOT NULL, /* content type of published file */
+ CONTENT_LENGTH BIGINT NOT NULL, /* content length of published file */
+
+ FEED_FILEID VARCHAR(256), /* file ID of published file */
+ REMOTE_ADDR VARCHAR(40), /* IP address of publishing endpoint */
+ USER VARCHAR(50), /* user name of publishing endpoint */
+ STATUS SMALLINT, /* status code returned to delivering agent */
+
+ DELIVERY_SUBID INT UNSIGNED, /* pointer to subscription in SUBSCRIPTIONS */
+ DELIVERY_FILEID VARCHAR(256), /* file ID of file being delivered */
+ RESULT SMALLINT, /* result received from subscribing agent */
+
+ ATTEMPTS INT, /* deliveries attempted */
+ REASON ENUM('notRetryable', 'retriesExhausted', 'diskFull', 'other'),
+
+ RECORD_ID BIGINT UNSIGNED NOT NULL PRIMARY KEY, /* unique ID for this record */
+ CONTENT_LENGTH_2 BIGINT,
+ FILENAME VARCHAR(256), /* Name of the file being published on DR */
+
+) ENGINE = MyISAM;
+
+CREATE TABLE INGRESS_ROUTES (
+ SEQUENCE INT UNSIGNED NOT NULL,
+ FEEDID INT UNSIGNED NOT NULL,
+ USERID VARCHAR(50),
+ SUBNET VARCHAR(44),
+ NODESET INT UNSIGNED NOT NULL
+);
+
+CREATE TABLE EGRESS_ROUTES (
+ SUBID INT UNSIGNED NOT NULL PRIMARY KEY,
+ NODEID INT UNSIGNED NOT NULL
+);
+
+CREATE TABLE NETWORK_ROUTES (
+ FROMNODE INT UNSIGNED NOT NULL,
+ TONODE INT UNSIGNED NOT NULL,
+ VIANODE INT UNSIGNED NOT NULL
+);
+
+CREATE TABLE NODESETS (
+ SETID INT UNSIGNED NOT NULL,
+ NODEID INT UNSIGNED NOT NULL
+);
+
+CREATE TABLE NODES (
+ NODEID INT UNSIGNED NOT NULL PRIMARY KEY,
+ NAME VARCHAR(255) NOT NULL,
+ ACTIVE BOOLEAN DEFAULT TRUE
+);
+
+CREATE TABLE GROUPS (
+ GROUPID INT UNSIGNED NOT NULL PRIMARY KEY,
+ AUTHID VARCHAR(100) NOT NULL,
+ NAME VARCHAR(50) NOT NULL,
+ DESCRIPTION VARCHAR(255),
+ CLASSIFICATION VARCHAR(20) NOT NULL,
+ MEMBERS TINYTEXT,
+ LAST_MOD TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);
+
+INSERT INTO PARAMETERS VALUES
+ ('ACTIVE_POD', 'dmaap-dr-prov'),
+ ('PROV_ACTIVE_NAME', 'dmaap-dr-prov'),
+ ('STANDBY_POD', ''),
+ ('PROV_NAME', 'dmaap-dr-prov'),
+ ('NODES', 'dmaap-dr-node'),
+ ('PROV_DOMAIN', ''),
+ ('DELIVERY_INIT_RETRY_INTERVAL', '10'),
+ ('DELIVERY_MAX_AGE', '86400'),
+ ('DELIVERY_MAX_RETRY_INTERVAL', '3600'),
+ ('DELIVERY_FILE_PROCESS_INTERVAL', '600'),
+ ('DELIVERY_RETRY_RATIO', '2'),
+ ('LOGROLL_INTERVAL', '30'),
+ ('PROV_AUTH_ADDRESSES', 'dmaap-dr-prov|dmaap-dr-node'),
+ ('PROV_AUTH_SUBJECTS', ''),
+ ('PROV_MAXFEED_COUNT', '10000'),
+ ('PROV_MAXSUB_COUNT', '100000'),
+ ('PROV_REQUIRE_CERT', 'false'),
+ ('PROV_REQUIRE_SECURE', 'true'),
+ ('_INT_VALUES', 'LOGROLL_INTERVAL|PROV_MAXFEED_COUNT|PROV_MAXSUB_COUNT|DELIVERY_INIT_RETRY_INTERVAL|DELIVERY_MAX_RETRY_INTERVAL|DELIVERY_RETRY_RATIO|DELIVERY_MAX_AGE|DELIVERY_FILE_PROCESS_INTERVAL'); \ No newline at end of file