diff options
author | efiacor <fiachra.corcoran@est.tech> | 2019-07-23 16:22:03 +0000 |
---|---|---|
committer | efiacor <fiachra.corcoran@est.tech> | 2019-07-23 16:22:03 +0000 |
commit | f20778ffa99aa9c6f30a0f84112a5392b259ea63 (patch) | |
tree | 7c58a50f8b327a5f7f9580dbfb97fe24532ed777 /datarouter-prov/src/main | |
parent | d6302cb0b3db8043598e8b6bc3dc5ed436f848cb (diff) |
More unit test coverage and code cleanup
Change-Id: Ie28b50803c60cc79221a5c8aa08cf029f7a8486c
Issue-ID: DMAAP-1226
Signed-off-by: efiacor <fiachra.corcoran@est.tech>
Diffstat (limited to 'datarouter-prov/src/main')
17 files changed, 603 insertions, 910 deletions
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> <small>(left brace)</small> and ending - * with <code>}</code> <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> <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;
}
|