<sitePath>/content/sites/site/${project.groupId}/${project.artifactId}/${project.version}</sitePath>
<docker.location>${basedir}/target/${project.artifactId}</docker.location>
<datarouter.node.image.name>${docker.image.root}${project.artifactId}</datarouter.node.image.name>
+ <sonar.exclusions>src/main/java/org/onap/dmaap/datarouter/node/NodeMain.java</sonar.exclusions>
<sonar.language>java</sonar.language>
<sonar.skip>false</sonar.skip>
</properties>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
+ <configuration>
+ <excludes>
+ <exclude>src/main/java/org/onap/dmaap/datarouter/node/NodeMain.java</exclude>
+ </excludes>
+ </configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<docker.location>${basedir}/target/${project.artifactId}</docker.location>
<datarouter.prov.image.name>${docker.image.root}${project.artifactId}</datarouter.prov.image.name>
<sonar.exclusions>**/src/main/java/org/onap/dmaap/datarouter/reports/**,
- **/src/main/java/org/onap/dmaap/authz/impl/AuthRespSupplementImpl.java</sonar.exclusions>
+ src/main/java/org/onap/dmaap/datarouter/authz/impl/AuthRespSupplementImpl.java,
+ src/main/java/org/onap/dmaap/datarouter/provisioning/Main.java,
+ src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java</sonar.exclusions>
<sonar.language>java</sonar.language>
<sonar.skip>false</sonar.skip>
</properties>
<configuration>
<excludes>
<exclude>**/src/main/java/org/onap/dmaap/datarouter/reports/**</exclude>
- <exclude>**/src/main/java/org/onap/dmaap/authz/impl/AuthRespSupplementImpl.java</exclude>
+ <exclude>src/main/java/org/onap/dmaap/datarouter/authz/impl/AuthRespSupplementImpl.java</exclude>
+ <exclude>src/main/java/org/onap/dmaap/datarouter/provisioning/Main.java</exclude>
+ <exclude>src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java</exclude>
</excludes>
</configuration>
</plugin>
* Array of nodes names and/or FQDNs.
*/
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.
*/
}
}
- //[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) {
package org.onap.dmaap.datarouter.provisioning.beans;\r
\r
import java.sql.PreparedStatement;\r
-import java.sql.ResultSet;\r
import java.sql.SQLException;\r
import java.sql.Types;\r
import java.text.ParseException;\r
\r
package org.onap.dmaap.datarouter.provisioning.beans;\r
\r
+import com.att.eelf.configuration.EELFLogger;\r
+import com.att.eelf.configuration.EELFManager;\r
import java.sql.Connection;\r
import java.sql.PreparedStatement;\r
import java.sql.ResultSet;\r
import java.util.Objects;\r
import java.util.SortedSet;\r
import java.util.TreeSet;\r
-\r
-import com.att.eelf.configuration.EELFLogger;\r
-import com.att.eelf.configuration.EELFManager;\r
import org.json.JSONObject;\r
import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
\r
public class EgressRoute extends NodeClass implements Comparable<EgressRoute> {\r
\r
private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");\r
- private static final String SQLEXCEPTION = "SQLException: ";\r
private final int subid;\r
private final int nodeid;\r
\r
+ public EgressRoute(int subid, int nodeid) {\r
+ this.subid = subid;\r
+ this.nodeid = nodeid;\r
+ // Note: unlike for Feeds, it subscriptions can be removed from the tables, so it is\r
+ // possible that an orphan ERT entry can exist if a sub is removed.\r
+ // if (Subscription.getSubscriptionById(subid) == null)\r
+ // throw new IllegalArgumentException("No such subscription: "+subid);\r
+ }\r
+\r
+ public EgressRoute(int subid, String node) {\r
+ this(subid, lookupNodeName(node));\r
+ }\r
+\r
/**\r
* Get a set of all Egress Routes in the DB. The set is sorted according to the natural sorting order of the routes\r
* (based on the subscription ID in each route).\r
*/\r
public static SortedSet<EgressRoute> getAllEgressRoutes() {\r
SortedSet<EgressRoute> set = new TreeSet<>();\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
+ DB db = new DB();\r
+ String sql = "select SUBID, NODEID from EGRESS_ROUTES";\r
+ try (Connection conn = db.getConnection()) {\r
try (Statement stmt = conn.createStatement()) {\r
- try (ResultSet rs = stmt.executeQuery("select SUBID, NODEID from EGRESS_ROUTES")) {\r
- while (rs.next()) {\r
- int subid = rs.getInt("SUBID");\r
- int nodeid = rs.getInt("NODEID");\r
- set.add(new EgressRoute(subid, nodeid));\r
- }\r
+ try (ResultSet rs = stmt.executeQuery(sql)) {\r
+ addEgressRouteToSet(set, rs);\r
}\r
+ } finally {\r
+ db.release(conn);\r
}\r
-\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.error("PROV0008 EgressRoute.getAllEgressRoutes: " + e.getMessage(), e);\r
}\r
return set;\r
}\r
\r
+ private static void addEgressRouteToSet(SortedSet<EgressRoute> set, ResultSet rs) throws SQLException {\r
+ while (rs.next()) {\r
+ int subid = rs.getInt("SUBID");\r
+ int nodeid = rs.getInt("NODEID");\r
+ set.add(new EgressRoute(subid, nodeid));\r
+ }\r
+ }\r
+\r
/**\r
* Get a single Egress Route for the subscription <i>sub</i>.\r
*\r
*/\r
public static EgressRoute getEgressRoute(int sub) {\r
EgressRoute v = null;\r
- PreparedStatement ps = null;\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- String sql = "select NODEID from EGRESS_ROUTES where SUBID = ?";\r
- ps = conn.prepareStatement(sql);\r
+ DB db = new DB();\r
+ String sql = "select NODEID from EGRESS_ROUTES where SUBID = ?";\r
+ try (Connection conn = db.getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(sql)) {\r
ps.setInt(1, sub);\r
try (ResultSet rs = ps.executeQuery()) {\r
if (rs.next()) {\r
int node = rs.getInt("NODEID");\r
v = new EgressRoute(sub, node);\r
}\r
+ } finally {\r
+ db.release(conn);\r
}\r
- ps.close();\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.error("PROV0009 EgressRoute.getEgressRoute: " + e.getMessage(), e);\r
- } finally {\r
- try {\r
- if (ps != null) {\r
- ps.close();\r
- }\r
- } catch (SQLException e) {\r
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
- }\r
}\r
return v;\r
}\r
\r
- public EgressRoute(int subid, int nodeid) {\r
- this.subid = subid;\r
- this.nodeid = nodeid;\r
-// Note: unlike for Feeds, it subscriptions can be removed from the tables, so it is\r
-// possible that an orphan ERT entry can exist if a sub is removed.\r
-// if (Subscription.getSubscriptionById(subid) == null)\r
-// throw new IllegalArgumentException("No such subscription: "+subid);\r
- }\r
-\r
- public EgressRoute(int subid, String node) {\r
- this(subid, lookupNodeName(node));\r
- }\r
-\r
@Override\r
public boolean doDelete(Connection c) {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
- String sql = "delete from EGRESS_ROUTES where SUBID = ?";\r
- ps = c.prepareStatement(sql);\r
+ String sql = "delete from EGRESS_ROUTES where SUBID = ?";\r
+ try (PreparedStatement ps = c.prepareStatement(sql)) {\r
ps.setInt(1, subid);\r
ps.execute();\r
} catch (SQLException e) {\r
rv = false;\r
intlogger.error("PROV0007 doDelete: " + e.getMessage(), e);\r
- } finally {\r
- try {\r
- if (ps != null) {\r
- ps.close();\r
- }\r
- } catch (SQLException e) {\r
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
- }\r
}\r
return rv;\r
}\r
@Override\r
public boolean doInsert(Connection c) {\r
boolean rv = false;\r
- PreparedStatement ps = null;\r
- try {\r
+ String sql = "insert into EGRESS_ROUTES (SUBID, NODEID) values (?, ?)";\r
+ try (PreparedStatement ps = c.prepareStatement(sql)) {\r
// Create the NETWORK_ROUTES row\r
- String sql = "insert into EGRESS_ROUTES (SUBID, NODEID) values (?, ?)";\r
- ps = c.prepareStatement(sql);\r
ps.setInt(1, this.subid);\r
ps.setInt(2, this.nodeid);\r
ps.execute();\r
rv = true;\r
} catch (SQLException e) {\r
intlogger.warn("PROV0005 doInsert: " + e.getMessage(), e);\r
- } finally {\r
- try {\r
- if (ps != null) {\r
- ps.close();\r
- }\r
- } catch (SQLException e) {\r
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
- }\r
}\r
return rv;\r
}\r
@Override\r
public boolean doUpdate(Connection c) {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
- String sql = "update EGRESS_ROUTES set NODEID = ? where SUBID = ?";\r
- ps = c.prepareStatement(sql);\r
+ String sql = "update EGRESS_ROUTES set NODEID = ? where SUBID = ?";\r
+ try (PreparedStatement ps = c.prepareStatement(sql)) {\r
ps.setInt(1, nodeid);\r
ps.setInt(2, subid);\r
ps.executeUpdate();\r
} catch (SQLException e) {\r
rv = false;\r
intlogger.warn("PROV0006 doUpdate: " + e.getMessage(), e);\r
- } finally {\r
- try {\r
- if (ps != null) {\r
- ps.close();\r
- }\r
- } catch (SQLException e) {\r
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
- }\r
}\r
return rv;\r
}\r
\r
package org.onap.dmaap.datarouter.provisioning.beans;\r
\r
+import com.att.eelf.configuration.EELFLogger;\r
+import com.att.eelf.configuration.EELFManager;\r
import java.io.InvalidObjectException;\r
import java.sql.Connection;\r
import java.sql.PreparedStatement;\r
import java.sql.ResultSet;\r
import java.sql.SQLException;\r
import java.sql.Statement;\r
-import java.util.*;\r
-\r
-import com.att.eelf.configuration.EELFLogger;\r
-import com.att.eelf.configuration.EELFManager;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Date;\r
+import java.util.List;\r
+import java.util.Objects;\r
import org.json.JSONObject;\r
import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
\r
*/\r
public class Group extends Syncable {\r
\r
+ private static final String GROUP_ID_CONST = "groupid";\r
private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");\r
- private static int next_groupid = getMaxGroupID() + 1;\r
+ private static int nextGroupid = getMaxGroupID() + 1;\r
private static final String SQLEXCEPTION = "SQLException: ";\r
\r
private int groupid;\r
private String members;\r
private Date last_mod;\r
\r
+ public Group() {\r
+ this("", "", "");\r
+ }\r
+\r
+ public Group(String name, String desc, String members) {\r
+ this.groupid = -1;\r
+ this.authid = "";\r
+ this.name = name;\r
+ this.description = desc;\r
+ this.members = members;\r
+ this.classification = "";\r
+ this.last_mod = new Date();\r
+ }\r
+\r
+\r
+ public Group(ResultSet rs) throws SQLException {\r
+ this.groupid = rs.getInt("GROUPID");\r
+ this.authid = rs.getString("AUTHID");\r
+ this.name = rs.getString("NAME");\r
+ this.description = rs.getString("DESCRIPTION");\r
+ this.classification = rs.getString("CLASSIFICATION");\r
+ this.members = rs.getString("MEMBERS");\r
+ this.last_mod = rs.getDate("LAST_MOD");\r
+ }\r
+\r
+\r
+ public Group(JSONObject jo) throws InvalidObjectException {\r
+ this("", "", "");\r
+ try {\r
+ // The JSONObject is assumed to contain a vnd.dmaap-dr.group representation\r
+ this.groupid = jo.optInt(GROUP_ID_CONST, -1);\r
+ String gname = jo.getString("name");\r
+ String gdescription = jo.getString("description");\r
+\r
+ this.authid = jo.getString("authid");\r
+ this.name = gname;\r
+ this.description = gdescription;\r
+ this.classification = jo.getString("classification");\r
+ this.members = jo.getString("members");\r
+\r
+ if (gname.length() > 50) {\r
+ throw new InvalidObjectException("Group name is too long");\r
+ }\r
+ if (gdescription.length() > 256) {\r
+ throw new InvalidObjectException("Group Description is too long");\r
+ }\r
+ } catch (InvalidObjectException e) {\r
+ throw e;\r
+ } catch (Exception e) {\r
+ intlogger.warn("Invalid JSON: " + e.getMessage(), e);\r
+ throw new InvalidObjectException("Invalid JSON: " + e.getMessage());\r
+ }\r
+ }\r
+\r
\r
public static Group getGroupMatching(Group gup) {\r
String sql = String.format(\r
return list.size() > 0 ? list.get(0) : null;\r
}\r
\r
- public static Group getGroupByAuthId(String id) {\r
+ static Group getGroupByAuthId(String id) {\r
String sql = "select * from GROUPS where AUTHID = '" + id + "'";\r
List<Group> list = getGroupsForSQL(sql);\r
return list.size() > 0 ? list.get(0) : null;\r
}\r
\r
private static List<Group> getGroupsForSQL(String sql) {\r
- List<Group> list = new ArrayList<Group>();\r
+ List<Group> list = new ArrayList<>();\r
try {\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
return list;\r
}\r
\r
- public static int getMaxGroupID() {\r
+ private static int getMaxGroupID() {\r
int max = 0;\r
try {\r
DB db = new DB();\r
return max;\r
}\r
\r
- public Group() {\r
- this("", "", "");\r
- }\r
-\r
- public Group(String name, String desc, String members) {\r
- this.groupid = -1;\r
- this.authid = "";\r
- this.name = name;\r
- this.description = desc;\r
- this.members = members;\r
- this.classification = "";\r
- this.last_mod = new Date();\r
- }\r
-\r
-\r
- public Group(ResultSet rs) throws SQLException {\r
- this.groupid = rs.getInt("GROUPID");\r
- this.authid = rs.getString("AUTHID");\r
- this.name = rs.getString("NAME");\r
- this.description = rs.getString("DESCRIPTION");\r
- this.classification = rs.getString("CLASSIFICATION");\r
- this.members = rs.getString("MEMBERS");\r
- this.last_mod = rs.getDate("LAST_MOD");\r
- }\r
-\r
-\r
- public Group(JSONObject jo) throws InvalidObjectException {\r
- this("", "", "");\r
- try {\r
- // The JSONObject is assumed to contain a vnd.dmaap-dr.group representation\r
- this.groupid = jo.optInt("groupid", -1);\r
- String gname = jo.getString("name");\r
- String gdescription = jo.getString("description");\r
-\r
- this.authid = jo.getString("authid");\r
- this.name = gname;\r
- this.description = gdescription;\r
- this.classification = jo.getString("classification");\r
- this.members = jo.getString("members");\r
-\r
- if (gname.length() > 50) {\r
- throw new InvalidObjectException("Group name is too long");\r
- }\r
- if (gdescription.length() > 256) {\r
- throw new InvalidObjectException("Group Description is too long");\r
- }\r
- } catch (InvalidObjectException e) {\r
- throw e;\r
- } catch (Exception e) {\r
- intlogger.warn("Invalid JSON: " + e.getMessage(), e);\r
- throw new InvalidObjectException("Invalid JSON: " + e.getMessage());\r
- }\r
- }\r
-\r
public int getGroupid() {\r
return groupid;\r
}\r
@Override\r
public JSONObject asJSONObject() {\r
JSONObject jo = new JSONObject();\r
- jo.put("groupid", groupid);\r
+ jo.put(GROUP_ID_CONST, groupid);\r
jo.put("authid", authid);\r
jo.put("name", name);\r
jo.put("description", description);\r
try {\r
if (groupid == -1) {\r
// No feed ID assigned yet, so assign the next available one\r
- setGroupid(next_groupid++);\r
+ setGroupid(nextGroupid++);\r
}\r
// In case we insert a gropup from synchronization\r
- if (groupid > next_groupid) {\r
- next_groupid = groupid + 1;\r
+ if (groupid > nextGroupid) {\r
+ nextGroupid = groupid + 1;\r
}\r
\r
// Create the GROUPS row\r
\r
package org.onap.dmaap.datarouter.provisioning.beans;\r
\r
+import com.att.eelf.configuration.EELFLogger;\r
+import com.att.eelf.configuration.EELFManager;\r
import java.net.InetAddress;\r
import java.net.UnknownHostException;\r
import java.sql.Connection;\r
import java.sql.ResultSet;\r
import java.sql.SQLException;\r
import java.sql.Statement;\r
-import java.util.ArrayList;\r
import java.util.Collection;\r
import java.util.Set;\r
import java.util.SortedSet;\r
import java.util.TreeSet;\r
-\r
import javax.servlet.http.HttpServletRequest;\r
-\r
-import com.att.eelf.configuration.EELFLogger;\r
-import com.att.eelf.configuration.EELFManager;\r
import org.apache.commons.codec.binary.Base64;\r
import org.json.JSONArray;\r
import org.json.JSONObject;\r
*/\r
public class IngressRoute extends NodeClass implements Comparable<IngressRoute> {\r
\r
+ private static final String NODESET = "NODESET";\r
private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");\r
private static final String SQLEXCEPTION = "SQLException: ";\r
private final int seq;\r
private int nodelist;\r
private SortedSet<String> nodes;\r
\r
+ public IngressRoute(int seq, int feedid, String user, String subnet, Collection<String> nodes) {\r
+ this(seq, feedid, user, subnet);\r
+ this.nodelist = -1;\r
+ this.nodes = new TreeSet<>(nodes);\r
+ }\r
+\r
+ private IngressRoute(int seq, int feedid, String user, String subnet, int nodeset) {\r
+ this(seq, feedid, user, subnet);\r
+ this.nodelist = nodeset;\r
+ this.nodes = new TreeSet<>(readNodes());\r
+ }\r
+\r
+ private IngressRoute(int seq, int feedid, String user, String subnet) {\r
+ this.seq = seq;\r
+ this.feedid = feedid;\r
+ this.userid = (user == null) ? "-" : user;\r
+ this.subnet = (subnet == null) ? "-" : subnet;\r
+ this.nodelist = -1;\r
+ this.nodes = null;\r
+ if (Feed.getFeedById(feedid) == null) {\r
+ throw new IllegalArgumentException("No such feed: " + feedid);\r
+ }\r
+ if (!"-".equals(this.subnet)) {\r
+ SubnetMatcher sm = new SubnetMatcher(subnet);\r
+ if (!sm.isValid()) {\r
+ throw new IllegalArgumentException("Invalid subnet: " + subnet);\r
+ }\r
+ }\r
+ }\r
+\r
+ public IngressRoute(JSONObject jo) {\r
+ this.seq = jo.optInt("seq");\r
+ this.feedid = jo.optInt("feedid");\r
+ String t = jo.optString("user");\r
+ this.userid = "".equals(t) ? "-" : t;\r
+ t = jo.optString("subnet");\r
+ this.subnet = "".equals(t) ? "-" : t;\r
+ this.nodelist = -1;\r
+ this.nodes = new TreeSet<>();\r
+ JSONArray ja = jo.getJSONArray("node");\r
+ for (int i = 0; i < ja.length(); i++) {\r
+ this.nodes.add(ja.getString(i));\r
+ }\r
+ }\r
+\r
+\r
/**\r
* Get all IngressRoutes in the database, sorted in order according to their sequence field.\r
*\r
}\r
\r
private static SortedSet<IngressRoute> getAllIngressRoutesForSQL(String sql) {\r
- SortedSet<IngressRoute> set = new TreeSet<IngressRoute>();\r
+ SortedSet<IngressRoute> set = new TreeSet<>();\r
try {\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
try (Statement stmt = conn.createStatement()) {\r
try (ResultSet rs = stmt.executeQuery(sql)) {\r
- while (rs.next()) {\r
- int seq = rs.getInt("SEQUENCE");\r
- int feedid = rs.getInt("FEEDID");\r
- String user = rs.getString("USERID");\r
- String subnet = rs.getString("SUBNET");\r
- int nodeset = rs.getInt("NODESET");\r
- set.add(new IngressRoute(seq, feedid, user, subnet, nodeset));\r
- }\r
+ addIngressRouteToSet(set, rs);\r
}\r
}\r
db.release(conn);\r
return set;\r
}\r
\r
+ private static void addIngressRouteToSet(SortedSet<IngressRoute> set, ResultSet rs) throws SQLException {\r
+ while (rs.next()) {\r
+ int seq = rs.getInt("SEQUENCE");\r
+ int feedid = rs.getInt("FEEDID");\r
+ String user = rs.getString("USERID");\r
+ String subnet = rs.getString("SUBNET");\r
+ int nodeset = rs.getInt(NODESET);\r
+ set.add(new IngressRoute(seq, feedid, user, subnet, nodeset));\r
+ }\r
+ }\r
+\r
/**\r
* Get the maximum node set ID in use in the DB.\r
*\r
* @return the integer value of the maximum\r
*/\r
- public static int getMaxNodeSetID() {\r
+ private static int getMaxNodeSetID() {\r
return getMax("select max(SETID) as MAX from NODESETS");\r
}\r
\r
\r
private static int getMax(String sql) {\r
int rv = 0;\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- try (Statement stmt = conn.createStatement()) {\r
- try (ResultSet rs = stmt.executeQuery(sql)) {\r
- if (rs.next()) {\r
- rv = rs.getInt("MAX");\r
- }\r
+ DB db = new DB();\r
+ try (Connection conn = db.getConnection();\r
+ Statement stmt = conn.createStatement()) {\r
+ try (ResultSet rs = stmt.executeQuery(sql)) {\r
+ if (rs.next()) {\r
+ rv = rs.getInt("MAX");\r
}\r
}\r
db.release(conn);\r
}\r
\r
/**\r
- * Get an Ingress Route for a particular feed ID, user, and subnet\r
+ * Get an Ingress Route for a particular feed ID, user, and subnet.\r
*\r
* @param feedid the Feed ID to look for\r
* @param user the user name to look for\r
*/\r
public static IngressRoute getIngressRoute(int feedid, String user, String subnet) {\r
IngressRoute v = null;\r
- PreparedStatement ps = null;\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- String sql = "select SEQUENCE, NODESET from INGRESS_ROUTES where FEEDID = ? AND USERID = ? and SUBNET = ?";\r
- ps = conn.prepareStatement(sql);\r
+ DB db = new DB();\r
+ String sql = "select SEQUENCE, NODESET from INGRESS_ROUTES where FEEDID = ? AND USERID = ? and SUBNET = ?";\r
+ try (Connection conn = db.getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(sql)) {\r
ps.setInt(1, feedid);\r
ps.setString(2, user);\r
ps.setString(3, subnet);\r
try (ResultSet rs = ps.executeQuery()) {\r
if (rs.next()) {\r
int seq = rs.getInt("SEQUENCE");\r
- int nodeset = rs.getInt("NODESET");\r
+ int nodeset = rs.getInt(NODESET);\r
v = new IngressRoute(seq, feedid, user, subnet, nodeset);\r
}\r
}\r
- ps.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
intlogger.error("PROV0003 getIngressRoute: " + e.getMessage(), e);\r
- } finally {\r
- try {\r
- if (ps != null) {\r
- ps.close();\r
- }\r
- } catch (SQLException e) {\r
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
- }\r
}\r
return v;\r
}\r
\r
- public IngressRoute(int seq, int feedid, String user, String subnet, Collection<String> nodes)\r
- throws IllegalArgumentException {\r
- this(seq, feedid, user, subnet);\r
- this.nodelist = -1;\r
- this.nodes = new TreeSet<String>(nodes);\r
- }\r
-\r
- public IngressRoute(int seq, int feedid, String user, String subnet, int nodeset)\r
- throws IllegalArgumentException {\r
- this(seq, feedid, user, subnet);\r
- this.nodelist = nodeset;\r
- this.nodes = new TreeSet<String>(readNodes());\r
- }\r
-\r
- private IngressRoute(int seq, int feedid, String user, String subnet)\r
- throws IllegalArgumentException {\r
- this.seq = seq;\r
- this.feedid = feedid;\r
- this.userid = (user == null) ? "-" : user;\r
- this.subnet = (subnet == null) ? "-" : subnet;\r
- this.nodelist = -1;\r
- this.nodes = null;\r
- if (Feed.getFeedById(feedid) == null) {\r
- throw new IllegalArgumentException("No such feed: " + feedid);\r
- }\r
- if (!this.subnet.equals("-")) {\r
- SubnetMatcher sm = new SubnetMatcher(subnet);\r
- if (!sm.isValid()) {\r
- throw new IllegalArgumentException("Invalid subnet: " + subnet);\r
- }\r
- }\r
- }\r
-\r
- public IngressRoute(JSONObject jo) {\r
- this.seq = jo.optInt("seq");\r
- this.feedid = jo.optInt("feedid");\r
- String t = jo.optString("user");\r
- this.userid = t.equals("") ? "-" : t;\r
- t = jo.optString("subnet");\r
- this.subnet = t.equals("") ? "-" : t;\r
- this.nodelist = -1;\r
- this.nodes = new TreeSet<String>();\r
- JSONArray ja = jo.getJSONArray("node");\r
- for (int i = 0; i < ja.length(); i++) {\r
- this.nodes.add(ja.getString(i));\r
- }\r
- }\r
-\r
/**\r
* Does this particular IngressRoute match a request, represented by feedid and req? To match, <i>feedid</i> must\r
* match the feed ID in the route, the user in the route (if specified) must match the user in the request, and the\r
if (this.feedid != feedid) {\r
return false;\r
}\r
-\r
// Get user from request and compare\r
// Note: we don't check the password; the node will do that\r
- if (userid.length() > 0 && !userid.equals("-")) {\r
+ if (userid.length() > 0 && !"-".equals(userid)) {\r
String credentials = req.getHeader("Authorization");\r
if (credentials == null || !credentials.startsWith("Basic ")) {\r
return false;\r
return false;\r
}\r
}\r
-\r
// If this route has a subnet, match it against the requester's IP addr\r
- if (subnet.length() > 0 && !subnet.equals("-")) {\r
+ if (subnet.length() > 0 && !"-".equals(subnet)) {\r
try {\r
InetAddress inet = InetAddress.getByName(req.getRemoteAddr());\r
SubnetMatcher sm = new SubnetMatcher(subnet);\r
private boolean valid;\r
\r
/**\r
- * Construct a subnet matcher given a CIDR\r
+ * Construct a subnet matcher given a CIDR.\r
*\r
* @param subnet The CIDR to match\r
*/\r
}\r
}\r
\r
- public boolean isValid() {\r
+ boolean isValid() {\r
return valid;\r
}\r
\r
/**\r
- * Is the IP address in the CIDR?\r
+ * Is the IP address in the CIDR?.\r
*\r
* @param addr the IP address as bytes in network byte order\r
* @return true if the IP address matches.\r
*/\r
- public boolean matches(byte[] addr) {\r
- if (!valid || addr.length != sn.length) {\r
+ boolean matches(byte[] addr) {\r
+ if (!valid || (addr.length != sn.length)) {\r
return false;\r
}\r
for (int i = 0; i < len; i++) {\r
\r
private Collection<String> readNodes() {\r
Collection<String> set = new TreeSet<>();\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- String sql = "select NODEID from NODESETS where SETID = ?";\r
+ DB db = new DB();\r
+ String sql = "select NODEID from NODESETS where SETID = ?";\r
+ try (Connection conn = db.getConnection()) {\r
try (PreparedStatement ps = conn.prepareStatement(sql)) {\r
ps.setInt(1, nodelist);\r
- try (ResultSet rs = ps.executeQuery()) {\r
- while (rs.next()) {\r
- int id = rs.getInt("NODEID");\r
- set.add(lookupNodeID(id));\r
- }\r
- }\r
+ addNodeToSet(set, ps);\r
}\r
db.release(conn);\r
} catch (SQLException e) {\r
return set;\r
}\r
\r
+ private void addNodeToSet(Collection<String> set, PreparedStatement ps) throws SQLException {\r
+ try (ResultSet rs = ps.executeQuery()) {\r
+ while (rs.next()) {\r
+ int id = rs.getInt("NODEID");\r
+ set.add(lookupNodeID(id));\r
+ }\r
+ }\r
+ }\r
+\r
/**\r
* Delete the IRT route having this IngressRoutes feed ID, user ID, and subnet from the database.\r
*\r
@Override\r
public boolean doDelete(Connection c) {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
- ps = c.prepareStatement("delete from INGRESS_ROUTES where FEEDID = ? and USERID = ? and SUBNET = ?");\r
+ try (PreparedStatement ps = c.prepareStatement(\r
+ "delete from INGRESS_ROUTES where FEEDID = ? and USERID = ? and SUBNET = ?");\r
+ PreparedStatement ps2 = c.prepareStatement("delete from NODESETS where SETID = ?")) {\r
+ // Delete the Ingress Route\r
ps.setInt(1, feedid);\r
ps.setString(2, userid);\r
ps.setString(3, subnet);\r
ps.execute();\r
ps.close();\r
-\r
- ps = c.prepareStatement("delete from NODESETS where SETID = ?");\r
- ps.setInt(1, nodelist);\r
- ps.execute();\r
+ // Delete the NodeSet\r
+ ps2.setInt(1, nodelist);\r
+ ps2.execute();\r
} catch (SQLException e) {\r
rv = false;\r
intlogger.warn("PROV0007 doDelete: " + e.getMessage(), e);\r
- } finally {\r
- try {\r
- if (ps != null) {\r
- ps.close();\r
- }\r
- } catch (SQLException e) {\r
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
- }\r
}\r
return rv;\r
}\r
\r
- @SuppressWarnings("resource")\r
@Override\r
public boolean doInsert(Connection c) {\r
boolean rv = false;\r
- PreparedStatement ps = null;\r
- try {\r
+ try (PreparedStatement ps = c.prepareStatement("insert into NODESETS (SETID, NODEID) values (?,?)");\r
+ PreparedStatement ps2 = c.prepareStatement("insert into INGRESS_ROUTES (SEQUENCE, FEEDID, USERID,"\r
+ + " SUBNET, NODESET) values (?, ?, ?, ?, ?)")) {\r
// Create the NODESETS rows & set nodelist\r
- int set = getMaxNodeSetID() + 1;\r
- this.nodelist = set;\r
+ this.nodelist = getMaxNodeSetID() + 1;\r
for (String node : nodes) {\r
int id = lookupNodeName(node);\r
- ps = c.prepareStatement("insert into NODESETS (SETID, NODEID) values (?,?)");\r
ps.setInt(1, this.nodelist);\r
ps.setInt(2, id);\r
ps.execute();\r
- ps.close();\r
}\r
-\r
// Create the INGRESS_ROUTES row\r
- ps = c.prepareStatement(\r
- "insert into INGRESS_ROUTES (SEQUENCE, FEEDID, USERID, SUBNET, NODESET) values (?, ?, ?, ?, ?)");\r
- ps.setInt(1, this.seq);\r
- ps.setInt(2, this.feedid);\r
- ps.setString(3, this.userid);\r
- ps.setString(4, this.subnet);\r
- ps.setInt(5, this.nodelist);\r
- ps.execute();\r
- ps.close();\r
+ ps2.setInt(1, this.seq);\r
+ ps2.setInt(2, this.feedid);\r
+ ps2.setString(3, this.userid);\r
+ ps2.setString(4, this.subnet);\r
+ ps2.setInt(5, this.nodelist);\r
+ ps2.execute();\r
rv = true;\r
} catch (SQLException e) {\r
intlogger.warn("PROV0005 doInsert: " + e.getMessage(), e);\r
- } finally {\r
- try {\r
- if (ps != null) {\r
- ps.close();\r
- }\r
- } catch (SQLException e) {\r
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
- }\r
}\r
return rv;\r
}\r
JSONObject jo = new JSONObject();\r
jo.put("feedid", feedid);\r
// Note: for user and subnet, null, "", and "-" are equivalent\r
- if (userid != null && !userid.equals("-") && !userid.equals("")) {\r
+ if (userid != null && !"-".equals(userid) && !"".equals(userid)) {\r
jo.put("user", userid);\r
}\r
- if (subnet != null && !subnet.equals("-") && !subnet.equals("")) {\r
+ if (subnet != null && !"-".equals(subnet) && !"".equals(subnet)) {\r
jo.put("subnet", subnet);\r
}\r
jo.put("seq", seq);\r
* @author Robert Eby\r
* @version $Id: Insertable.java,v 1.2 2013/05/29 14:44:36 eby Exp $\r
*/\r
+@FunctionalInterface\r
public interface Insertable {\r
/**\r
* Insert this object into the DB.\r
* @param c the JDBC Connection to use\r
* @return true if the INSERT succeeded, false otherwise\r
*/\r
- public boolean doInsert(Connection c);\r
+ boolean doInsert(Connection c);\r
}\r
* @author Robert Eby\r
* @version $Id: JSONable.java,v 1.1 2013/04/26 21:00:26 eby Exp $\r
*/\r
+@FunctionalInterface\r
public interface JSONable {\r
/**\r
* Get a JSONObject representing this object.\r
*\r
* @return the JSONObject\r
*/\r
- public JSONObject asJSONObject();\r
+ JSONObject asJSONObject();\r
}\r
* @author Robert Eby\r
* @version $Id: JSONable.java,v 1.1 2013/04/26 21:00:26 eby Exp $\r
*/\r
+@FunctionalInterface\r
public interface LOGJSONable {\r
/**\r
* Get a JSONObject representing this object.\r
*\r
* @return the JSONObject\r
*/\r
- public LOGJSONObject asJSONObject();\r
+ LOGJSONObject asJSONObject();\r
}\r
* @author Robert Eby\r
* @version $Id: Loadable.java,v 1.2 2013/08/06 13:28:33 eby Exp $\r
*/\r
+@FunctionalInterface\r
public interface Loadable {\r
/**\r
* Load the 18 fields in the PreparedStatement <i>ps</i>. The fields are:\r
*\r
* @param ps the PreparedStatement to load\r
*/\r
- public void load(PreparedStatement ps) throws SQLException;\r
+ void load(PreparedStatement ps) throws SQLException;\r
}\r
\r
package org.onap.dmaap.datarouter.provisioning.beans;\r
\r
+import com.att.eelf.configuration.EELFLogger;\r
+import com.att.eelf.configuration.EELFManager;\r
import java.sql.Connection;\r
import java.sql.PreparedStatement;\r
import java.sql.ResultSet;\r
import java.util.Objects;\r
import java.util.SortedSet;\r
import java.util.TreeSet;\r
-\r
-import com.att.eelf.configuration.EELFLogger;\r
-import com.att.eelf.configuration.EELFManager;\r
import org.json.JSONObject;\r
import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
\r
private final int tonode;\r
private final int vianode;\r
\r
+ public NetworkRoute(String fromnode, String tonode) {\r
+ this.fromnode = lookupNodeName(fromnode);\r
+ this.tonode = lookupNodeName(tonode);\r
+ this.vianode = -1;\r
+ }\r
+\r
+ public NetworkRoute(String fromnode, String tonode, String vianode) {\r
+ this.fromnode = lookupNodeName(fromnode);\r
+ this.tonode = lookupNodeName(tonode);\r
+ this.vianode = lookupNodeName(vianode);\r
+ }\r
+\r
+ public NetworkRoute(JSONObject jo) {\r
+ this.fromnode = lookupNodeName(jo.getString("from"));\r
+ this.tonode = lookupNodeName(jo.getString("to"));\r
+ this.vianode = lookupNodeName(jo.getString("via"));\r
+ }\r
+\r
+ private NetworkRoute(int fromnode, int tonode, int vianode) {\r
+ this.fromnode = fromnode;\r
+ this.tonode = tonode;\r
+ this.vianode = vianode;\r
+ }\r
+\r
/**\r
* Get a set of all Network Routes in the DB. The set is sorted according to the natural sorting order of the\r
* routes (based on the from and to node names in each route).\r
Connection conn = db.getConnection();\r
try (Statement stmt = conn.createStatement()) {\r
try (ResultSet rs = stmt.executeQuery("select FROMNODE, TONODE, VIANODE from NETWORK_ROUTES")) {\r
- while (rs.next()) {\r
- int fromnode = rs.getInt("FROMNODE");\r
- int tonode = rs.getInt("TONODE");\r
- int vianode = rs.getInt("VIANODE");\r
- set.add(new NetworkRoute(fromnode, tonode, vianode));\r
- }\r
+ addNetworkRouteToSet(set, rs);\r
}\r
+ } finally {\r
+ db.release(conn);\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
}\r
return set;\r
}\r
\r
- public NetworkRoute(String fromnode, String tonode) {\r
- this.fromnode = lookupNodeName(fromnode);\r
- this.tonode = lookupNodeName(tonode);\r
- this.vianode = -1;\r
- }\r
-\r
- public NetworkRoute(String fromnode, String tonode, String vianode) {\r
- this.fromnode = lookupNodeName(fromnode);\r
- this.tonode = lookupNodeName(tonode);\r
- this.vianode = lookupNodeName(vianode);\r
- }\r
-\r
- public NetworkRoute(JSONObject jo) {\r
- this.fromnode = lookupNodeName(jo.getString("from"));\r
- this.tonode = lookupNodeName(jo.getString("to"));\r
- this.vianode = lookupNodeName(jo.getString("via"));\r
- }\r
-\r
- public NetworkRoute(int fromnode, int tonode, int vianode) {\r
- this.fromnode = fromnode;\r
- this.tonode = tonode;\r
- this.vianode = vianode;\r
+ private static void addNetworkRouteToSet(SortedSet<NetworkRoute> set, ResultSet rs) throws SQLException {\r
+ while (rs.next()) {\r
+ int fromnode = rs.getInt("FROMNODE");\r
+ int tonode = rs.getInt("TONODE");\r
+ int vianode = rs.getInt("VIANODE");\r
+ set.add(new NetworkRoute(fromnode, tonode, vianode));\r
+ }\r
}\r
\r
public int getFromnode() {\r
return tonode;\r
}\r
\r
+ public int getVianode() {\r
+ return vianode;\r
+ }\r
+\r
@Override\r
public boolean doDelete(Connection c) {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
- String sql = "delete from NETWORK_ROUTES where FROMNODE = ? AND TONODE = ?";\r
- ps = c.prepareStatement(sql);\r
+ String sql = "delete from NETWORK_ROUTES where FROMNODE = ? AND TONODE = ?";\r
+ try (PreparedStatement ps = c.prepareStatement(sql)) {\r
ps.setInt(1, fromnode);\r
ps.setInt(2, tonode);\r
ps.execute();\r
} catch (SQLException e) {\r
rv = false;\r
intlogger.warn("PROV0007 doDelete: " + e.getMessage(), e);\r
- } finally {\r
- try {\r
- if (ps != null) {\r
- ps.close();\r
- }\r
- } catch (SQLException e) {\r
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
- }\r
}\r
return rv;\r
}\r
@Override\r
public boolean doInsert(Connection c) {\r
boolean rv = false;\r
+ String sql = "insert into NETWORK_ROUTES (FROMNODE, TONODE, VIANODE) values (?, ?, ?)";\r
if (this.vianode >= 0) {\r
- PreparedStatement ps = null;\r
- try {\r
+ try (PreparedStatement ps = c.prepareStatement(sql)) {\r
// Create the NETWORK_ROUTES row\r
- String sql = "insert into NETWORK_ROUTES (FROMNODE, TONODE, VIANODE) values (?, ?, ?)";\r
- ps = c.prepareStatement(sql);\r
ps.setInt(1, this.fromnode);\r
ps.setInt(2, this.tonode);\r
ps.setInt(3, this.vianode);\r
ps.execute();\r
- ps.close();\r
rv = true;\r
} catch (SQLException e) {\r
intlogger.warn("PROV0005 doInsert: " + e.getMessage(), e);\r
- } finally {\r
- try {\r
- if (ps != null) {\r
- ps.close();\r
- }\r
- } catch (SQLException e) {\r
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
- }\r
}\r
}\r
return rv;\r
@Override\r
public boolean doUpdate(Connection c) {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
- String sql = "update NETWORK_ROUTES set VIANODE = ? where FROMNODE = ? and TONODE = ?";\r
- ps = c.prepareStatement(sql);\r
+ String sql = "update NETWORK_ROUTES set VIANODE = ? where FROMNODE = ? and TONODE = ?";\r
+ try (PreparedStatement ps = c.prepareStatement(sql)) {\r
ps.setInt(1, vianode);\r
ps.setInt(2, fromnode);\r
ps.setInt(3, tonode);\r
} catch (SQLException e) {\r
rv = false;\r
intlogger.warn("PROV0006 doUpdate: " + e.getMessage(), e);\r
- } finally {\r
- try {\r
- if (ps != null) {\r
- ps.close();\r
- }\r
- } catch (SQLException e) {\r
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
- }\r
}\r
return rv;\r
}\r
\r
package org.onap.dmaap.datarouter.provisioning.beans;\r
\r
+import com.att.eelf.configuration.EELFLogger;\r
+import com.att.eelf.configuration.EELFManager;\r
import java.sql.Connection;\r
import java.sql.PreparedStatement;\r
import java.sql.ResultSet;\r
import java.util.Map;\r
import java.util.Set;\r
import java.util.TreeSet;\r
-\r
-import com.att.eelf.configuration.EELFLogger;\r
-import com.att.eelf.configuration.EELFManager;\r
import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
\r
/**\r
*/\r
public abstract class NodeClass extends Syncable {\r
\r
+ private static final String PROV_0005_DO_INSERT = "PROV0005 doInsert: ";\r
private static Map<String, Integer> map;\r
private static EELFLogger intLogger = EELFManager.getInstance().getLogger("InternalLog");\r
- public NodeClass() {\r
+\r
+ NodeClass() {\r
// init on first use\r
if (map == null) {\r
reload();\r
if (!map.containsKey(node)) {\r
intLogger.info("..adding " + node + " to NODES with index " + nextid);\r
map.put(node, nextid);\r
- PreparedStatement ps = null;\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- ps = conn.prepareStatement("insert into NODES (NODEID, NAME, ACTIVE) values (?, ?, 1)");\r
- ps.setInt(1, nextid);\r
- ps.setString(2, node);\r
- ps.execute();\r
- ps.close();\r
- db.release(conn);\r
- } catch (SQLException e) {\r
- intLogger.error("PROV0005 doInsert: " + e.getMessage(),e);\r
- } finally {\r
- try {\r
- if(ps!=null){\r
- ps.close();\r
- }\r
- } catch (SQLException e) {\r
- intLogger.error("Error in closing PreparedStatement: " + e.getMessage(),e);\r
- }\r
- }\r
+ insertNodesToTable(nextid, node);\r
nextid++;\r
}\r
}\r
}\r
\r
- public static void reload() {\r
- Map<String, Integer> m = new HashMap<String, Integer>();\r
- PreparedStatement ps = null;\r
+ private static void insertNodesToTable(int nextid, String node) {\r
+ DB db = new DB();\r
+ try (Connection conn = db.getConnection()) {\r
+ try (PreparedStatement ps = conn\r
+ .prepareStatement("insert into NODES (NODEID, NAME, ACTIVE) values (?, ?, 1)")) {\r
+ ps.setInt(1, nextid);\r
+ ps.setString(2, node);\r
+ ps.execute();\r
+ } finally {\r
+ db.release(conn);\r
+ }\r
+ } catch (SQLException e) {\r
+ intLogger.error(PROV_0005_DO_INSERT + e.getMessage(), e);\r
+ }\r
+ }\r
\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- String sql = "select NODEID, NAME from NODES";\r
- ps = conn.prepareStatement(sql);\r
- try(ResultSet rs = ps.executeQuery()) {\r
+ private static void reload() {\r
+ Map<String, Integer> m = new HashMap<>();\r
+ String sql = "select NODEID, NAME from NODES";\r
+ DB db = new DB();\r
+ try (Connection conn = db.getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(sql)) {\r
+ try (ResultSet rs = ps.executeQuery()) {\r
while (rs.next()) {\r
int id = rs.getInt("NODEID");\r
String name = rs.getString("NAME");\r
m.put(name, id);\r
}\r
+ } finally {\r
+ db.release(conn);\r
}\r
- ps.close();\r
- db.release(conn);\r
} catch (SQLException e) {\r
- intLogger.error("PROV0005 doInsert: " + e.getMessage(),e);\r
- } finally {\r
- try {\r
- if(ps!=null){\r
- ps.close();\r
- }\r
- } catch (SQLException e) {\r
- intLogger.error("PROV0005 doInsert: " + e.getMessage(),e);\r
- }\r
+ intLogger.error(PROV_0005_DO_INSERT + e.getMessage(),e);\r
}\r
map = m;\r
}\r
\r
- public static Integer lookupNodeName(final String name) {\r
+ static Integer lookupNodeName(final String name) {\r
Integer n = map.get(name);\r
if (n == null) {\r
throw new IllegalArgumentException("Invalid node name: " + name);\r
}\r
\r
public static Collection<String> lookupNodeNames(String patt) {\r
- Collection<String> coll = new TreeSet<String>();\r
+ Collection<String> coll = new TreeSet<>();\r
final Set<String> keyset = map.keySet();\r
for (String s : patt.toLowerCase().split(",")) {\r
if (s.endsWith("*")) {\r
- s = s.substring(0, s.length() - 1);\r
- for (String s2 : keyset) {\r
- if (s2.startsWith(s)) {\r
- coll.add(s2);\r
- }\r
- }\r
+ addNodeToCollection(coll, keyset, s);\r
} else if (keyset.contains(s)) {\r
coll.add(s);\r
} else if (keyset.contains(normalizeNodename(s))) {\r
return coll;\r
}\r
\r
+ private static void addNodeToCollection(Collection<String> coll, Set<String> keyset, String s) {\r
+ s = s.substring(0, s.length() - 1);\r
+ for (String s2 : keyset) {\r
+ if (s2.startsWith(s)) {\r
+ coll.add(s2);\r
+ }\r
+ }\r
+ }\r
+\r
public static String normalizeNodename(String s) {\r
if (s != null && s.indexOf('.') <= 0) {\r
Parameters p = Parameters.getParameter(Parameters.PROV_DOMAIN);\r
s += "." + domain;\r
}\r
return s.toLowerCase();\r
- }\r
- else{\r
+ } else {\r
return s;\r
}\r
\r
}\r
\r
- protected String lookupNodeID(int n) {\r
- for (String s : map.keySet()) {\r
- if (map.get(s) == n) {\r
- return s;\r
+ String lookupNodeID(int n) {\r
+ for (Map.Entry<String, Integer> entry : map.entrySet()) {\r
+ if (entry.getValue() == n) {\r
+ return entry.getKey();\r
}\r
}\r
return null;\r
\r
package org.onap.dmaap.datarouter.provisioning.beans;\r
\r
+import com.att.eelf.configuration.EELFLogger;\r
+import com.att.eelf.configuration.EELFManager;\r
import java.sql.Connection;\r
import java.sql.PreparedStatement;\r
import java.sql.ResultSet;\r
import java.sql.SQLException;\r
import java.sql.Statement;\r
-import java.util.*;\r
-\r
-import com.att.eelf.configuration.EELFLogger;\r
-import com.att.eelf.configuration.EELFManager;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+import java.util.Objects;\r
import org.json.JSONObject;\r
import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
\r
public static final String DELIVERY_RETRY_RATIO = "DELIVERY_RETRY_RATIO";\r
public static final String DELIVERY_MAX_AGE = "DELIVERY_MAX_AGE";\r
public static final String THROTTLE_FILTER = "THROTTLE_FILTER";\r
- public static final String STATIC_ROUTING_NODES = "STATIC_ROUTING_NODES"; //Adding new param for static Routing - Rally:US664862-1610\r
+ public static final String STATIC_ROUTING_NODES = "STATIC_ROUTING_NODES";\r
\r
private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");\r
private static final String SQLEXCEPTION = "SQLException: ";\r
private String keyname;\r
private String value;\r
\r
+ public Parameters(String k, String v) {\r
+ this.keyname = k;\r
+ this.value = v;\r
+ }\r
+\r
+ public Parameters(ResultSet rs) throws SQLException {\r
+ this.keyname = rs.getString("KEYNAME");\r
+ this.value = rs.getString("VALUE");\r
+ }\r
+\r
/**\r
* Get all parameters in the DB as a Map.\r
*\r
* @return the Map of keynames/values from the DB.\r
*/\r
public static Map<String, String> getParameters() {\r
- Map<String, String> props = new HashMap<String, String>();\r
+ Map<String, String> props = new HashMap<>();\r
for (Parameters p : getParameterCollection()) {\r
props.put(p.getKeyname(), p.getValue());\r
}\r
}\r
\r
public static Collection<Parameters> getParameterCollection() {\r
- Collection<Parameters> coll = new ArrayList<Parameters>();\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- try (Statement stmt = conn.createStatement()) {\r
- String sql = "select * from PARAMETERS";\r
- try (ResultSet rs = stmt.executeQuery(sql)) {\r
- while (rs.next()) {\r
- Parameters p = new Parameters(rs);\r
- coll.add(p);\r
- }\r
+ Collection<Parameters> coll = new ArrayList<>();\r
+ DB db = new DB();\r
+ String sql = "select * from PARAMETERS";\r
+ try (Connection conn = db.getConnection();\r
+ Statement stmt = conn.createStatement()) {\r
+ try (ResultSet rs = stmt.executeQuery(sql)) {\r
+ while (rs.next()) {\r
+ Parameters p = new Parameters(rs);\r
+ coll.add(p);\r
}\r
}\r
db.release(conn);\r
} catch (SQLException e) {\r
- intlogger.error(SQLEXCEPTION + e.getMessage());\r
+ intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
}\r
return coll;\r
}\r
*/\r
public static Parameters getParameter(String k) {\r
Parameters v = null;\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- try (PreparedStatement stmt = conn\r
- .prepareStatement("select KEYNAME, VALUE from PARAMETERS where KEYNAME = ?")) {\r
- stmt.setString(1, k);\r
- try (ResultSet rs = stmt.executeQuery()) {\r
- if (rs.next()) {\r
- v = new Parameters(rs);\r
- }\r
+ DB db = new DB();\r
+ String sql = "select KEYNAME, VALUE from PARAMETERS where KEYNAME = ?";\r
+ try (Connection conn = db.getConnection();\r
+ PreparedStatement stmt = conn.prepareStatement(sql)) {\r
+ stmt.setString(1, k);\r
+ try (ResultSet rs = stmt.executeQuery()) {\r
+ if (rs.next()) {\r
+ v = new Parameters(rs);\r
}\r
}\r
db.release(conn);\r
} catch (SQLException e) {\r
- intlogger.error(SQLEXCEPTION + e.getMessage());\r
+ intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
}\r
return v;\r
}\r
\r
- public Parameters() {\r
- this("", "");\r
- }\r
-\r
- public Parameters(String k, String v) {\r
- this.keyname = k;\r
- this.value = v;\r
- }\r
-\r
- public Parameters(ResultSet rs) throws SQLException {\r
- this.keyname = rs.getString("KEYNAME");\r
- this.value = rs.getString("VALUE");\r
- }\r
-\r
public String getKeyname() {\r
return keyname;\r
}\r
@Override\r
public boolean doInsert(Connection c) {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
- // Create the SUBSCRIPTIONS row\r
- String sql = "insert into PARAMETERS values (?, ?)";\r
- ps = c.prepareStatement(sql);\r
+ String sql = "insert into PARAMETERS values (?, ?)";\r
+ try (PreparedStatement ps = c.prepareStatement(sql)) {\r
ps.setString(1, getKeyname());\r
ps.setString(2, getValue());\r
ps.execute();\r
} catch (SQLException e) {\r
rv = false;\r
intlogger.warn("PROV0005 doInsert: " + e.getMessage(), e);\r
- } finally {\r
- try {\r
- if (ps != null) {\r
- ps.close();\r
- }\r
- } catch (SQLException e) {\r
- intlogger.error(SQLEXCEPTION + e.getMessage());\r
- }\r
}\r
return rv;\r
}\r
@Override\r
public boolean doUpdate(Connection c) {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
- // Update the PARAMETERS row\r
- String sql = "update PARAMETERS set VALUE = ? where KEYNAME = ?";\r
- ps = c.prepareStatement(sql);\r
+ String sql = "update PARAMETERS set VALUE = ? where KEYNAME = ?";\r
+ try (PreparedStatement ps = c.prepareStatement(sql)) {\r
ps.setString(1, getValue());\r
ps.setString(2, getKeyname());\r
ps.executeUpdate();\r
} catch (SQLException e) {\r
rv = false;\r
intlogger.warn("PROV0006 doUpdate: " + e.getMessage(),e);\r
- } finally {\r
- try {\r
- if (ps != null) {\r
- ps.close();\r
- }\r
- } catch (SQLException e) {\r
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
- }\r
}\r
return rv;\r
}\r
@Override\r
public boolean doDelete(Connection c) {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
- // Create the SUBSCRIPTIONS row\r
- String sql = "delete from PARAMETERS where KEYNAME = ?";\r
- ps = c.prepareStatement(sql);\r
+ String sql = "delete from PARAMETERS where KEYNAME = ?";\r
+ try (PreparedStatement ps = c.prepareStatement(sql)) {\r
ps.setString(1, getKeyname());\r
ps.execute();\r
} catch (SQLException e) {\r
rv = false;\r
intlogger.warn("PROV0007 doDelete: " + e.getMessage(), e);\r
- } finally {\r
- try {\r
- if (ps != null) {\r
- ps.close();\r
- }\r
- } catch (SQLException e) {\r
- intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
- }\r
}\r
return rv;\r
}\r
return false;\r
}\r
Parameters of = (Parameters) obj;\r
- if (!keyname.equals(of.keyname)) {\r
- return false;\r
- }\r
- if (!value.equals(of.value)) {\r
- return false;\r
- }\r
- return true;\r
+ return (!value.equals(of.value)) && (!keyname.equals(of.keyname));\r
}\r
\r
@Override\r
\r
package org.onap.dmaap.datarouter.provisioning.utils;\r
\r
+import static java.lang.System.exit;\r
+import static java.lang.System.getProperty;\r
+\r
+import com.att.eelf.configuration.EELFLogger;\r
+import com.att.eelf.configuration.EELFManager;\r
import java.io.File;\r
import java.io.FileInputStream;\r
import java.io.FileReader;\r
import java.util.Queue;\r
import java.util.Set;\r
\r
-import com.att.eelf.configuration.EELFLogger;\r
-import com.att.eelf.configuration.EELFManager;\r
-\r
/**\r
* Load the DB JDBC driver, and manage a simple pool of connections to the DB.\r
*\r
\r
private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");\r
\r
- private static String DB_URL;\r
- private static String DB_LOGIN;\r
- private static String DB_PASSWORD;\r
+ private static String dbUrl;\r
+ private static String dbLogin;\r
+ private static String dbPassword;\r
private static Properties props;\r
private static final Queue<Connection> queue = new LinkedList<>();\r
\r
- private static String HTTPS_PORT;\r
- private static String HTTP_PORT;\r
+ private static String httpsPort;\r
+ private static String httpPort;\r
\r
/**\r
* Construct a DB object. If this is the very first creation of this object, it will load a copy of the properties\r
if (props == null) {\r
props = new Properties();\r
try {\r
- props.load(new FileInputStream(System.getProperty(\r
+ props.load(new FileInputStream(getProperty(\r
"org.onap.dmaap.datarouter.provserver.properties",\r
"/opt/app/datartr/etc/provserver.properties")));\r
- String DB_DRIVER = (String) props.get("org.onap.dmaap.datarouter.db.driver");\r
- DB_URL = (String) props.get("org.onap.dmaap.datarouter.db.url");\r
- DB_LOGIN = (String) props.get("org.onap.dmaap.datarouter.db.login");\r
- DB_PASSWORD = (String) props.get("org.onap.dmaap.datarouter.db.password");\r
- HTTPS_PORT = (String) props.get("org.onap.dmaap.datarouter.provserver.https.port");\r
- HTTP_PORT = (String) props.get("org.onap.dmaap.datarouter.provserver.http.port");\r
- Class.forName(DB_DRIVER);\r
+ String dbDriver = (String) props.get("org.onap.dmaap.datarouter.db.driver");\r
+ dbUrl = (String) props.get("org.onap.dmaap.datarouter.db.url");\r
+ dbLogin = (String) props.get("org.onap.dmaap.datarouter.db.login");\r
+ dbPassword = (String) props.get("org.onap.dmaap.datarouter.db.password");\r
+ httpsPort = (String) props.get("org.onap.dmaap.datarouter.provserver.https.port");\r
+ httpPort = (String) props.get("org.onap.dmaap.datarouter.provserver.http.port");\r
+ Class.forName(dbDriver);\r
} catch (IOException e) {\r
intlogger.error("PROV9003 Opening properties: " + e.getMessage(), e);\r
- System.exit(1);\r
+ exit(1);\r
} catch (ClassNotFoundException e) {\r
intlogger.error("PROV9004 cannot find the DB driver: " + e);\r
- System.exit(1);\r
+ exit(1);\r
}\r
}\r
}\r
*\r
* @return the Connection\r
*/\r
- @SuppressWarnings("resource")\r
public Connection getConnection() throws SQLException {\r
Connection connection = null;\r
while (connection == null) {\r
do {\r
// Try up to 3 times to get a connection\r
try {\r
- connection = DriverManager.getConnection(DB_URL, DB_LOGIN, DB_PASSWORD);\r
+ connection = DriverManager.getConnection(dbUrl, dbLogin, dbPassword);\r
} catch (SQLException sqlEx) {\r
if (++n >= 3) {\r
throw sqlEx;\r
\r
\r
public static String getHttpsPort() {\r
- return HTTPS_PORT;\r
+ return httpsPort;\r
}\r
\r
public static String getHttpPort() {\r
- return HTTP_PORT;\r
+ return httpPort;\r
}\r
\r
/**\r
*/\r
private void runInitScript(Connection connection, int scriptId) {\r
String scriptDir = (String) props.get("org.onap.dmaap.datarouter.provserver.dbscripts");\r
- StringBuilder strBuilder = new StringBuilder();\r
- try {\r
- String scriptFile = String.format("%s/sql_init_%02d.sql", scriptDir, scriptId);\r
- if (!(new File(scriptFile)).exists()) {\r
- intlogger.error("PROV9005 Failed to load sql script from : " + scriptFile);\r
- System.exit(1);\r
- }\r
- LineNumberReader lineReader = new LineNumberReader(new FileReader(scriptFile));\r
+ String scriptFile = String.format("%s/sql_init_%02d.sql", scriptDir, scriptId);\r
+ if (!(new File(scriptFile)).exists()) {\r
+ intlogger.error("PROV9005 Failed to load sql script from : " + scriptFile);\r
+ exit(1);\r
+ }\r
+ try (LineNumberReader lineReader = new LineNumberReader(new FileReader(scriptFile));\r
+ Statement statement = connection.createStatement()) {\r
+ StringBuilder strBuilder = new StringBuilder();\r
String line;\r
while ((line = lineReader.readLine()) != null) {\r
if (!line.startsWith("--")) {\r
line = line.trim();\r
strBuilder.append(line);\r
- if (line.endsWith(";")) {\r
- // Execute one DDL statement\r
- String sql = strBuilder.toString();\r
- strBuilder.setLength(0);\r
- Statement statement = connection.createStatement();\r
- statement.execute(sql);\r
- statement.close();\r
- }\r
+ executeDdlStatement(statement, strBuilder, line);\r
}\r
}\r
- lineReader.close();\r
strBuilder.setLength(0);\r
} catch (Exception e) {\r
intlogger.error("PROV9002 Error when initializing table: " + e.getMessage(), e);\r
- System.exit(1);\r
+ exit(1);\r
+ }\r
+ }\r
+\r
+ private void executeDdlStatement(Statement statement, StringBuilder strBuilder, String line) throws SQLException {\r
+ if (line.endsWith(";")) {\r
+ // Execute one DDL statement\r
+ String sql = strBuilder.toString();\r
+ strBuilder.setLength(0);\r
+ statement.execute(sql);\r
}\r
}\r
}\r
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;
* @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
* 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");
* <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.
* @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()) {
this.populateMap(bean);
}
- /**
- * 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
* 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 {
* @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) {
} 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;
}
// 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);
}
* @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;
}
* @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.");
}
/**
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.");
}
}
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.");
}
}
* @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.");
}
/**
* @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.");
}
/**
* @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.");
}
}
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];
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.");
}
/**
* @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");
}
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);
}
try {
return this.getBoolean(key);
} catch (Exception e) {
- intlogger.trace("Using defaultValue: " + defaultValue, e);
+ intlogger.trace(USING_DEFAULT_VALUE + defaultValue, e);
return defaultValue;
}
}
try {
return this.getDouble(key);
} catch (Exception e) {
- intlogger.trace("Using defaultValue: " + defaultValue, e);
+ intlogger.trace(USING_DEFAULT_VALUE + defaultValue, e);
return defaultValue;
}
}
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,
}
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];
String key = "";
if (name.startsWith("get")) {
if ("getClass".equals(name) ||
- "getDeclaringClass".equals(name)) {
+ "getDeclaringClass".equals(name)) {
key = "";
} else {
key = name.substring(3);
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);
}
}
- /**
- * 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.
*
* @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;
}
* @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;
}
* @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.
* @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.");
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 {
* @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 + "\"");
return this;
}
- /**
- * 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 <\/,
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());
*/
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;
}
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;
}
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.");
}
}
}
* @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;
}
* 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();
* @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) {
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;
}
}
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);
}
@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) {
} 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) {
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(' ');
}
* @throws JSONException
*/
Writer write(Writer writer, int indentFactor, int indent)
- throws JSONException {
+ {
try {
boolean commanate = false;
final int length = this.length();
writer.write(' ');
}
writeValue(writer, this.map.get(key), indentFactor,
- newindent);
+ newindent);
commanate = true;
}
if (indentFactor > 0) {
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.
*
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()) {
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) {
stmt.execute("OPTIMIZE TABLE LOG_RECORDS");
}
} catch (SQLException e) {
- logger.error(e.toString());
+ logger.error("LogfileLoader.pruneRecords: " + e.getMessage(), e);
} finally {
db.release(conn);
}
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;
}
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);
}
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) {
\r
package org.onap.dmaap.datarouter.provisioning.utils;\r
\r
+import com.att.eelf.configuration.EELFLogger;\r
+import com.att.eelf.configuration.EELFManager;\r
import java.io.File;\r
+import java.util.Objects;\r
import java.util.Properties;\r
import java.util.TimerTask;\r
\r
-import com.att.eelf.configuration.EELFLogger;\r
-import com.att.eelf.configuration.EELFManager;\r
-\r
/**\r
* This class provides a {@link TimerTask} that purges old logfiles (older than the number of days specified by the\r
* org.onap.dmaap.datarouter.provserver.logretention property).\r
Properties p = (new DB()).getProperties();\r
logdir = p.getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir");\r
String s = p.getProperty("org.onap.dmaap.datarouter.provserver.logretention", "30");\r
-\r
this.utilsLogger = EELFManager.getInstance().getLogger("UtilsLog");\r
-\r
long n = 30;\r
try {\r
n = Long.parseLong(s);\r
try {\r
File dir = new File(logdir);\r
if (dir.exists()) {\r
- long exptime = System.currentTimeMillis() - interval;\r
- for (File logfile : dir.listFiles()) {\r
- if (logfile.lastModified() < exptime) {\r
- logfile.delete();\r
- }\r
- }\r
+ purgeLogFiles(dir);\r
}\r
} catch (Exception e) {\r
utilsLogger.error("Exception: " + e.getMessage(), e);\r
}\r
}\r
+\r
+ private void purgeLogFiles(File dir) {\r
+ long exptime = System.currentTimeMillis() - interval;\r
+ for (File logfile : Objects.requireNonNull(dir.listFiles())) {\r
+ if (logfile.lastModified() < exptime) {\r
+ logfile.delete();\r
+ }\r
+ }\r
+ }\r
}\r
import com.att.eelf.configuration.EELFManager;\r
import java.net.InetAddress;\r
import java.net.UnknownHostException;\r
-import java.util.Arrays;\r
\r
import org.onap.dmaap.datarouter.provisioning.BaseServlet;\r
\r
* @version $Id: URLUtilities.java,v 1.2 2014/03/12 19:45:41 eby Exp $\r
*/\r
public class URLUtilities {\r
+\r
private static final EELFLogger utilsLogger = EELFManager.getInstance().getLogger("UtilsLog");\r
+ private static final String HTTPS = "https://";\r
+ private static String otherPod;\r
+\r
+ private URLUtilities() {\r
+ }\r
+\r
/**\r
* Generate the URL used to access a feed.\r
*\r
* @return the URL\r
*/\r
public static String generateFeedURL(int feedid) {\r
- return "https://" + BaseServlet.getProvName() + "/feed/" + feedid;\r
+ return HTTPS + BaseServlet.getProvName() + "/feed/" + feedid;\r
}\r
\r
/**\r
* @return the URL\r
*/\r
public static String generatePublishURL(int feedid) {\r
- return "https://" + BaseServlet.getProvName() + "/publish/" + feedid;\r
+ return HTTPS + BaseServlet.getProvName() + "/publish/" + feedid;\r
}\r
\r
/**\r
* @return the URL\r
*/\r
public static String generateSubscribeURL(int feedid) {\r
- return "https://" + BaseServlet.getProvName() + "/subscribe/" + feedid;\r
+ return HTTPS + BaseServlet.getProvName() + "/subscribe/" + feedid;\r
}\r
\r
/**\r
* @return the URL\r
*/\r
public static String generateFeedLogURL(int feedid) {\r
- return "https://" + BaseServlet.getProvName() + "/feedlog/" + feedid;\r
+ return HTTPS + BaseServlet.getProvName() + "/feedlog/" + feedid;\r
}\r
\r
/**\r
* @return the URL\r
*/\r
public static String generateSubscriptionURL(int subid) {\r
- return "https://" + BaseServlet.getProvName() + "/subs/" + subid;\r
+ return HTTPS + BaseServlet.getProvName() + "/subs/" + subid;\r
}\r
\r
/**\r
* @return the URL\r
*/\r
public static String generateSubLogURL(int subid) {\r
- return "https://" + BaseServlet.getProvName() + "/sublog/" + subid;\r
+ return HTTPS + BaseServlet.getProvName() + "/sublog/" + subid;\r
}\r
\r
/**\r
* @return the URL\r
*/\r
public static String generatePeerProvURL() {\r
- return "https://" + getPeerPodName() + "/internal/prov";\r
+ return HTTPS + getPeerPodName() + "/internal/prov";\r
}\r
\r
/**\r
public static String generatePeerLogsURL() {\r
//Fixes for Itrack ticket - DATARTR-4#Fixing if only one Prov is configured, not to give exception to fill logs.\r
String peerPodUrl = getPeerPodName();\r
- if (peerPodUrl == null || peerPodUrl.equals("")) {\r
+ if (peerPodUrl == null || "".equals(peerPodUrl)) {\r
return "";\r
}\r
\r
- return "https://" + peerPodUrl + "/internal/drlogs/";\r
+ return HTTPS + peerPodUrl + "/internal/drlogs/";\r
}\r
\r
/**\r
* @return the name\r
*/\r
public static String getPeerPodName() {\r
- if (other_pod == null) {\r
- String this_pod = "";\r
+ if (otherPod == null) {\r
+ String thisPod;\r
try {\r
- this_pod = InetAddress.getLocalHost().getHostName();\r
- System.out.println("this_pod: " + this_pod);\r
+ thisPod = InetAddress.getLocalHost().getHostName();\r
} catch (UnknownHostException e) {\r
utilsLogger.trace("UnkownHostException: " + e.getMessage(), e);\r
- this_pod = "";\r
+ thisPod = "";\r
}\r
- System.out.println("ALL PODS: " + Arrays.asList(BaseServlet.getPods()));\r
for (String pod : BaseServlet.getPods()) {\r
- if (!pod.equals(this_pod)) {\r
- other_pod = pod;\r
+ if (!pod.equals(thisPod)) {\r
+ otherPod = pod;\r
}\r
}\r
}\r
- return other_pod;\r
+ return otherPod;\r
}\r
\r
- private static String other_pod;\r
}\r
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import org.apache.commons.lang3.reflect.FieldUtils;
+import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.dmaap.datarouter.provisioning.beans.Deleteable;
import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
import org.onap.dmaap.datarouter.provisioning.beans.LogRecord;
+import org.onap.dmaap.datarouter.provisioning.beans.Parameters;
import org.onap.dmaap.datarouter.provisioning.beans.Updateable;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
verifyEnteringExitCalled(listAppender);
}
+ @Test
+ public void Given_Request_Is_HTTP_DELETE_With_LogRollInterval_Api_In_Endpoint_Request_Succeeds() {
+ when(request.getPathInfo()).thenReturn("/api/LOGROLL_INTERVAL");
+ internalServlet.doDelete(request, response);
+ verify(response).setStatus(eq(HttpServletResponse.SC_OK));
+ Parameters p1 = Parameters.getParameter("NODES");
+ Assert.assertEquals("{\"keyname\":\"NODES\",\"value\":\"dmaap-dr-node\"}", p1.asJSONObject().toString());
+ Assert.assertEquals("PARAM: keyname=NODES, value=dmaap-dr-node", p1.toString());
+ }
+
@Test
public void Given_Request_Is_HTTP_DELETE_With_Api_In_Endpoint_And_Delete_Fails_Then_Internal_Server_Error_Is_Generated()
throws Exception {
}
@Test
- public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated()
- throws Exception {
+ public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated() {
when(request.getHeader("Content-Type")).thenReturn("stub_contentType");
when(request.getPathInfo()).thenReturn("/logs/");
internalServlet.doPost(request, response);
}
@Test
- public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Encoding_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated()
- throws Exception {
+ public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Encoding_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated() {
when(request.getHeader("Content-Encoding")).thenReturn("not-supported");
when(request.getPathInfo()).thenReturn("/logs/");
internalServlet.doPost(request, response);
}
@Test
- public void Given_Request_Is_HTTP_POST_To_Drlogs_And_Then_Unsupported_Media_Type_Response_Is_Generated()
- throws Exception {
+ public void Given_Request_Is_HTTP_POST_To_Drlogs_And_Then_Unsupported_Media_Type_Response_Is_Generated() {
when(request.getHeader("Content-Type")).thenReturn("stub_contentType");
when(request.getPathInfo()).thenReturn("/drlogs/");
internalServlet.doPost(request, response);
verify(response).setStatus(eq(HttpServletResponse.SC_OK));
}
+ @Test
+ public void Given_Request_Is_HTTP_POST_To_Api_And_Request_Succeeds() {
+ when(request.getPathInfo()).thenReturn("/api/NEW_PARAM?val=blah");
+ internalServlet.doPost(request, response);
+ verify(response).setStatus(eq(HttpServletResponse.SC_OK));
+ }
+
@Test
public void Given_Request_Is_HTTP_POST_With_Incorrect_Endpoint_Then_Not_Found_Error_Is_Generated()
throws Exception {
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.dmaap.datarouter.provisioning.beans;
+
+import java.sql.SQLException;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.onap.dmaap.datarouter.provisioning.utils.DB;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+public class EgressRouteTest {
+
+ private EgressRoute egressRoute;
+
+ private static EntityManagerFactory emf;
+ private static EntityManager em;
+ private DB db;
+
+ @BeforeClass
+ public static void init() {
+ emf = Persistence.createEntityManagerFactory("dr-unit-tests");
+ em = emf.createEntityManager();
+ System.setProperty(
+ "org.onap.dmaap.datarouter.provserver.properties",
+ "src/test/resources/h2Database.properties");
+ }
+
+ @AfterClass
+ public static void tearDownClass() {
+ em.clear();
+ em.close();
+ emf.close();
+ }
+ @Before
+ public void setUp() throws Exception {
+ db = new DB();
+ egressRoute = new EgressRoute(2, 1);
+ }
+
+ @Test
+ public void Verify_NetworkRoute_Is_Added_Successfully() throws SQLException {
+ Assert.assertEquals(1, EgressRoute.getAllEgressRoutes().size());
+ egressRoute.doInsert(db.getConnection());
+ Assert.assertEquals(2, EgressRoute.getAllEgressRoutes().size());
+ egressRoute.doDelete(db.getConnection());
+ }
+
+ @Test
+ public void Verify_NetworkRoute_Is_Removed_Successfully() throws SQLException {
+ Assert.assertEquals(1, EgressRoute.getAllEgressRoutes().size());
+ EgressRoute egressRoute = new EgressRoute(1, 1);
+ egressRoute.doDelete(db.getConnection());
+ Assert.assertEquals(0, EgressRoute.getAllEgressRoutes().size());
+ }
+
+ @Test
+ public void Verify_NetworkRoute_Is_Updated_Successfully() throws SQLException {
+ EgressRoute egressRoute = new EgressRoute(1, 1);
+ EgressRoute egressRoute1 = new EgressRoute(1, 1);
+ Assert.assertEquals(egressRoute.hashCode(), egressRoute1.hashCode());
+ Assert.assertEquals(egressRoute, egressRoute1);
+ Assert.assertEquals(egressRoute.toString(), egressRoute1.toString());
+ }
+}
\ No newline at end of file
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.dmaap.datarouter.provisioning.beans;
+
+import java.sql.SQLException;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.onap.dmaap.datarouter.provisioning.utils.DB;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+public class NetworkRouteTest {
+
+ private NetworkRoute networkRoute;
+
+ private static EntityManagerFactory emf;
+ private static EntityManager em;
+ private DB db;
+
+ @BeforeClass
+ public static void init() {
+ emf = Persistence.createEntityManagerFactory("dr-unit-tests");
+ em = emf.createEntityManager();
+ System.setProperty(
+ "org.onap.dmaap.datarouter.provserver.properties",
+ "src/test/resources/h2Database.properties");
+ }
+
+ @AfterClass
+ public static void tearDownClass() {
+ em.clear();
+ em.close();
+ emf.close();
+ }
+ @Before
+ public void setUp() throws Exception {
+ db = new DB();
+ networkRoute = new NetworkRoute("node01.","node03.","node02.");
+ }
+
+ @Test
+ public void Verify_NetworkRoute_Is_Added_Successfully() throws SQLException {
+ Assert.assertEquals(1, NetworkRoute.getAllNetworkRoutes().size());
+ networkRoute.doInsert(db.getConnection());
+ Assert.assertEquals(2, NetworkRoute.getAllNetworkRoutes().size());
+ networkRoute.doDelete(db.getConnection());
+ }
+
+ @Test
+ public void Verify_NetworkRoute_Is_Removed_Successfully() throws SQLException {
+ Assert.assertEquals(1, NetworkRoute.getAllNetworkRoutes().size());
+ NetworkRoute networkRoute = new NetworkRoute("stub_from.", "stub_to.");
+ networkRoute.doDelete(db.getConnection());
+ Assert.assertEquals(0, NetworkRoute.getAllNetworkRoutes().size());
+ }
+
+ @Test
+ public void Verify_NetworkRoute_Is_Updated_Successfully() throws SQLException {
+ NetworkRoute networkRoute = new NetworkRoute("stub_from.", "stub_to.", "node02.");
+ networkRoute.doUpdate(db.getConnection());
+ //Assert.assertTrue(NetworkRoute.getAllNetworkRoutes().contains(networkRoute));
+ for (NetworkRoute net :
+ NetworkRoute.getAllNetworkRoutes()) {
+ Assert.assertEquals(5, net.getVianode());
+ }
+ NetworkRoute networkRoute1 = new NetworkRoute("stub_from.", "stub_to.", "node02.");
+ Assert.assertEquals(networkRoute.hashCode(), networkRoute1.hashCode());
+ Assert.assertEquals(networkRoute, networkRoute1);
+ Assert.assertEquals(networkRoute.toString(), networkRoute1.toString());
+ }
+}
\ No newline at end of file
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.dmaap.datarouter.provisioning.utils;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+public class DbTest {
+ private static EntityManagerFactory emf;
+ private static EntityManager em;
+
+ private DB db = new DB();
+
+ @BeforeClass
+ public static void init() {
+ emf = Persistence.createEntityManagerFactory("db-unit-tests");
+ em = emf.createEntityManager();
+ System.setProperty(
+ "org.onap.dmaap.datarouter.provserver.properties",
+ "src/test/resources/h2Database.properties");
+ }
+
+ @AfterClass
+ public static void tearDownClass() {
+ em.clear();
+ em.close();
+ emf.close();
+ }
+
+ @Test
+ public void Verify_DB_Is_Initialised_Successfully() {
+ Assert.assertTrue(db.runRetroFits());
+ }
+
+}
package org.onap.dmaap.datarouter.provisioning.utils;
import java.io.CharArrayWriter;
+import java.io.IOException;
import java.io.Writer;
import org.json.JSONArray;
import org.json.JSONTokener;
}
@Test
- public void Construct_JSONObject_From_A_Subset_Of_Values_From_Another_JSONObject()
- throws Exception {
+ public void Construct_JSONObject_From_A_Subset_Of_Values_From_Another_JSONObject() {
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
}
@Test
- public void Construct_JSONObject_From_A_JSONTokener()
- throws Exception {
+ public void Construct_JSONObject_From_A_JSONTokener() {
JSONTokener x = new JSONTokener("{\"key1\":\"value1\",\"key3\":\"value3\"}");
LOGJSONObject logJObject = new LOGJSONObject(x);
assertThat(logJObject.toString(), is("{\"key1\":\"value1\",\"key3\":\"value3\"}"));
}
@Test
- public void Construct_JSONObject_From_A_Bean_Object_And_Populate_From_Its_Getters_And_Setters()
- throws Exception {
+ public void Construct_JSONObject_From_A_Bean_Object_And_Populate_From_Its_Getters_And_Setters() {
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
- Object bean = map;
- LOGJSONObject logJObject = new LOGJSONObject(bean);
+ LOGJSONObject logJObject = new LOGJSONObject((Object) map);
assertThat(logJObject.toString(), is("{\"empty\":false}"));
}
@Test
- public void Given_Method_Is_Accumulate_And_Value_Is_Valid_Put_Value_Into_New_JSONArray()
- throws Exception {
+ public void Given_Method_Is_Accumulate_And_Value_Is_Valid_Put_Value_Into_New_JSONArray() {
Map<String, Object> map = new HashMap<>();
map.put("key", 3);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
logJObject.accumulate(s, null);
assertThat(logJObject.get("key").toString(), is("[3,null]"));
}
@Test
- public void Given_Method_Is_Accumulate_And_Value_Is_Null_Dont_Add_Key_Value_Pair()
- throws Exception {
+ public void Given_Method_Is_Accumulate_And_Value_Is_Null_Dont_Add_Key_Value_Pair() {
String s = "key";
logJO.accumulate(s, null);
assertThat(logJO.has("key"), is(false));
}
@Test
- public void Given_Method_Is_Append_And_Value_Is_Null_Append_New_Value()
- throws Exception {
+ public void Given_Method_Is_Append_And_Value_Is_Null_Append_New_Value() {
String s = "key";
double d = 2.0;
logJO.append(s, d);
@Test
- public void Given_Method_Is_DoubleToString_And_Value_Is_NaN_Return_Null()
- throws Exception {
+ public void Given_Method_Is_DoubleToString_And_Value_Is_NaN_Return_Null() {
double d = 2.0;
- assertThat(logJO.doubleToString(d), is("2"));
+ assertThat(LOGJSONObject.doubleToString(d), is("2"));
}
@Test
- public void Given_Method_Is_GetBoolean_And_Value_Is_False_Return_False()
- throws Exception {
+ public void Given_Method_Is_GetBoolean_And_Value_Is_False_Return_False() {
Map<String, Object> map = new HashMap<>();
map.put("key", false);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getBoolean(s), is(false));
}
@Test
- public void Given_Method_Is_GetBoolean_And_Value_Is_True_Return_True()
- throws Exception {
+ public void Given_Method_Is_GetBoolean_And_Value_Is_True_Return_True() {
Map<String, Object> map = new HashMap<>();
map.put("key", true);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getBoolean(s), is(true));
}
@Test
- public void Given_Method_Is_GetDouble_And_Value_Is_A_Double_Return_Value()
- throws Exception {
+ public void Given_Method_Is_GetDouble_And_Value_Is_A_Double_Return_Value() {
Map<String, Object> map = new HashMap<>();
map.put("key", 2.0);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getDouble(s), is(2.0));
}
@Test
- public void Given_Method_Is_GetInt_And_Value_Is_An_Int_Return_Value()
- throws Exception {
+ public void Given_Method_Is_GetInt_And_Value_Is_An_Int_Return_Value() {
Map<String, Object> map = new HashMap<>();
map.put("key", 3);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getInt(s), is(3));
}
@Test
- public void Given_Method_Is_GetJSONArray_And_Value_Is_A_JSONArray_Return_Value()
- throws Exception {
+ public void Given_Method_Is_GetJSONArray_And_Value_Is_A_JSONArray_Return_Value() {
JSONArray jA = new JSONArray();
Map<String, Object> map = new HashMap<>();
map.put("key", jA);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getJSONArray(s), is(jA));
}
@Test
- public void Given_Method_Is_GetJSONObject_And_Value_Is_A_JSONObject_Return_Value()
- throws Exception {
+ public void Given_Method_Is_GetJSONObject_And_Value_Is_A_JSONObject_Return_Value() {
LOGJSONObject logJObj = new LOGJSONObject();
logJObj.put("stub_key", 1);
Map<String, Object> map = new HashMap<>();
map.put("key", logJObj);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getJSONObject(s), is(logJObj));
}
@Test
- public void Given_Method_Is_GetLong_And_Value_Is_A_Long_Return_Value()
- throws Exception {
+ public void Given_Method_Is_GetLong_And_Value_Is_A_Long_Return_Value() {
long l = 5;
Map<String, Object> map = new HashMap<>();
map.put("key", l);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getLong(s), is(5L));
}
@Test
- public void Given_Method_Is_getNames_And_Value_Is_A_LOGJSONObject_Return_StringArray()
- throws Exception {
+ public void Given_Method_Is_getNames_And_Value_Is_A_LOGJSONObject_Return_StringArray() {
LOGJSONObject logJObj = new LOGJSONObject();
logJObj.put("name1", "elyk");
String[] sArray = new String[logJObj.length()];
sArray[0] = "name1";
- LOGJSONObject logJObject = new LOGJSONObject();
-
- assertThat(logJObject.getNames(logJObj), is(sArray));
+ assertThat(LOGJSONObject.getNames(logJObj), is(sArray));
}
@Test
- public void Given_Method_Is_GetString_And_Value_Is_A_String_Return_Value()
- throws Exception {
+ public void Given_Method_Is_GetString_And_Value_Is_A_String_Return_Value() {
String val = "value";
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.getString(s), is("value"));
}
@Test
- public void Given_Method_Is_Increment_And_Value_Is_Null_Put_Defualt_Value()
- throws Exception {
+ public void Given_Method_Is_Increment_And_Value_Is_Null_Put_Defualt_Value() {
Map<String, Object> mapResult = new HashMap<>();
mapResult.put("key", 1);
LOGJSONObject logJObjectResult = new LOGJSONObject(mapResult);
-
String val = null;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
logJObject.increment(s);
assertThat(logJObject.get("key"), is(logJObjectResult.get("key")));
}
@Test
- public void Given_Method_Is_Increment_And_Value_Is_An_Int_Put_Value_Plus_One()
- throws Exception {
+ public void Given_Method_Is_Increment_And_Value_Is_An_Int_Put_Value_Plus_One() {
Map<String, Object> mapResult = new HashMap<>();
mapResult.put("key", 3);
LOGJSONObject logJObjectResult = new LOGJSONObject(mapResult);
-
int val = 2;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
logJObject.increment(s);
assertThat(logJObject.get("key"), is(logJObjectResult.get("key")));
}
@Test
- public void Given_Method_Is_Increment_And_Value_Is_A_Long_Put_Value_Plus_One()
- throws Exception {
+ public void Given_Method_Is_Increment_And_Value_Is_A_Long_Put_Value_Plus_One() {
Map<String, Object> mapResult = new HashMap<>();
mapResult.put("key", 4L);
LOGJSONObject logJObjectResult = new LOGJSONObject(mapResult);
-
long val = 3;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
logJObject.increment(s);
assertThat(logJObject.get("key"), is(logJObjectResult.get("key")));
}
@Test
- public void Given_Method_Is_Increment_And_Value_Is_A_Double_Put_Value_Plus_One()
- throws Exception {
+ public void Given_Method_Is_Increment_And_Value_Is_A_Double_Put_Value_Plus_One() {
Map<String, Object> mapResult = new HashMap<>();
mapResult.put("key", 5.0);
LOGJSONObject logJObjectResult = new LOGJSONObject(mapResult);
-
double val = 4.0;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
logJObject.increment(s);
assertThat(logJObject.get("key"), is(logJObjectResult.get("key")));
}
@Test
- public void Given_Method_Is_Increment_And_Value_Is_A_Float_Put_Value_Plus_One()
- throws Exception {
+ public void Given_Method_Is_Increment_And_Value_Is_A_Float_Put_Value_Plus_One() {
Map<String, Object> mapResult = new HashMap<>();
mapResult.put("key", 5.0);
LOGJSONObject logJObjectResult = new LOGJSONObject(mapResult);
-
float val = 4.0f;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
logJObject.increment(s);
assertThat(logJObject.get("key"), is(logJObjectResult.get("key")));
}
@Test
- public void Given_Method_Is_Names_And_Object_Contains_Keys_Put_Keys_Into_New_JSONArray()
- throws Exception {
+ public void Given_Method_Is_Names_And_Object_Contains_Keys_Put_Keys_Into_New_JSONArray() {
JSONArray ja = new JSONArray();
ja.put("key");
-
String val = "value";
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
- String s = "key";
assertThat(logJObject.names().get(0), is(ja.get(0)));
}
@Test
- public void Given_Method_Is_NumberToString_And_Number_is_Not_Null_Return_Reformatted_Number_As_String()
- throws Exception {
+ public void Given_Method_Is_NumberToString_And_Number_is_Not_Null_Return_Reformatted_Number_As_String() {
Number num = 3.0;
-
String val = "value";
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.numberToString(num), is("3"));
}
@Test
- public void Given_Method_Is_OptBoolean_And_Value_is_Boolean_Return_Value()
- throws Exception {
+ public void Given_Method_Is_OptBoolean_And_Value_is_Boolean_Return_Value() {
boolean val = true;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optBoolean(s, false), is(true));
}
@Test
- public void Given_Method_Is_OptBoolean_And_Value_is_Not_Boolean_Return_Default_Value()
- throws Exception {
+ public void Given_Method_Is_OptBoolean_And_Value_is_Not_Boolean_Return_Default_Value() {
String val = "not_boolean";
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optBoolean(s, false), is(false));
}
@Test
- public void Given_Method_Is_OptDouble_And_Value_is_Double_Return_Value()
- throws Exception {
+ public void Given_Method_Is_OptDouble_And_Value_is_Double_Return_Value() {
double val = 2.0;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optDouble(s, 0.0), is(2.0));
}
@Test
- public void Given_Method_Is_OptDouble_And_Value_is_Not_Double_Return_Default_Value()
- throws Exception {
+ public void Given_Method_Is_OptDouble_And_Value_is_Not_Double_Return_Default_Value() {
String val = "not_double";
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optDouble(s, 0.0), is(0.0));
}
@Test
- public void Given_Method_Is_OptInt_And_Value_is_Int_Return_Value()
- throws Exception {
+ public void Given_Method_Is_OptInt_And_Value_is_Int_Return_Value() {
int val = 1;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optInt(s, 0), is(1));
}
@Test
- public void Given_Method_Is_OptInt_And_Value_Is_Null_Return_Default_Value()
- throws Exception {
+ public void Given_Method_Is_OptInt_And_Value_Is_Null_Return_Default_Value() {
Map<String, Object> map = new HashMap<>();
map.put("key", null);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optInt(s, 0), is(0));
}
@Test
- public void Given_Method_Is_OptLong_And_Value_is_Long_Return_Value()
- throws Exception {
+ public void Given_Method_Is_OptLong_And_Value_is_Long_Return_Value() {
long val = 4;
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optLong(s, 0), is(4L));
}
@Test
- public void Given_Method_Is_OptLong_And_Value_is_Not_Long_Return_Default_Value()
- throws Exception {
+ public void Given_Method_Is_OptLong_And_Value_is_Not_Long_Return_Default_Value() {
Map<String, Object> map = new HashMap<>();
map.put("key", null);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optLong(s, 0), is(0L));
}
@Test
- public void Given_Method_Is_OptString_And_Value_is_String_Return_Value()
- throws Exception {
+ public void Given_Method_Is_OptString_And_Value_is_String_Return_Value() {
String val = "value";
Map<String, Object> map = new HashMap<>();
map.put("key", val);
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.optString(s, "default_value"), is("value"));
}
@Test
- public void Given_Method_Is_putOnce_And_KeyValuePair_Does_Not_Exist_In_logJObject_Put_KeyValuePair_Into_logJObject()
- throws Exception {
+ public void Given_Method_Is_putOnce_And_KeyValuePair_Does_Not_Exist_In_logJObject_Put_KeyValuePair_Into_logJObject() {
String val = "value";
Map<String, Object> map = new HashMap<>();
LOGJSONObject logJObject = new LOGJSONObject(map);
-
String s = "key";
assertThat(logJObject.putOnce(s, val).get("key"), is("value"));
}
@Test
- public void Given_Method_Is_StringToValue_And_Value_Is_Number_Return_Number()
- throws Exception {
+ public void Given_Method_Is_StringToValue_And_Value_Is_Number_Return_Number() {
String val = "312";
Map<String, Object> map = new HashMap<>();
- LOGJSONObject logJObject = new LOGJSONObject(map);
-
- assertThat(logJObject.stringToValue(val), is(312));
+ assertThat(LOGJSONObject.stringToValue(val), is(312));
}
@Test
- public void Given_Method_Is_ToJSONArray_And_KeyValue_Exists_Return_Value_Array()
- throws Exception {
+ public void Given_Method_Is_ToJSONArray_And_KeyValue_Exists_Return_Value_Array() {
JSONArray names = new JSONArray();
Map<String, Object> map = new HashMap<>();
map.put("name", "value");
names.put("name");
LOGJSONObject logJObject = new LOGJSONObject(map);
-
assertThat(logJObject.toJSONArray(names).get(0), is("value"));
}
@Test
- public void Given_Method_Is_ValueToString_And_Value_Is_JSONArray_Return_Value_To_String()
- throws Exception {
+ public void Given_Method_Is_ValueToString_And_Value_Is_JSONArray_Return_Value_To_String() {
JSONArray val = new JSONArray();
- Map<String, Object> map = new HashMap<>();
- map.put("key", "value");
val.put("value");
- LOGJSONObject logJObject = new LOGJSONObject(map);
-
- assertThat(logJObject.valueToString(val), is("[\"value\"]"));
+ assertThat(LOGJSONObject.valueToString(val), is("[\"value\"]"));
}
@Test
- public void Given_Method_Is_writeValue_And_Value_IS_Not_Null_Return_Writer_With_Value()
- throws Exception {
+ public void Given_Method_Is_writeValue_And_Value_IS_Not_Null_Return_Writer_With_Value() throws IOException {
Writer writer = new CharArrayWriter();
String val = "value";
- Map<String, Object> map = new HashMap<>();
- map.put("key", "value");
- LOGJSONObject logJObject = new LOGJSONObject(map);
-
- assertThat(logJObject.writeValue(writer, val, 3, 1).toString(), is("\"value\""));
+ assertThat(LOGJSONObject.writeValue(writer, val, 3, 1).toString(), is("\"value\""));
}
@Test
- public void Given_Method_Is_write_And_Length_Of_logJObject_Is_One_Write_Value_With_Indent()
- throws Exception {
+ public void Given_Method_Is_write_And_Length_Of_logJObject_Is_One_Write_Value_With_Indent() {
Writer writer = new CharArrayWriter();
- String val = "value";
Map<String, Object> map = new HashMap<>();
map.put("key", "value");
LOGJSONObject logJObject = new LOGJSONObject(map);
-
assertThat(logJObject.write(writer, 3, 1).toString(), is("{\"key\": \"value\"}"));
}
@Test
- public void Given_Method_Is_write_And_Length_Of_logJObject_Is_Not_One_Or_Zero_Write_Value_With_New_Indent()
- throws Exception {
+ public void Given_Method_Is_write_And_Length_Of_logJObject_Is_Not_One_Or_Zero_Write_Value_With_New_Indent() {
Writer writer = new CharArrayWriter();
- String val = "value";
Map<String, Object> map = new HashMap<>();
map.put("key", "value");
map.put("key1", "value1");
LOGJSONObject logJObject = new LOGJSONObject(map);
-
assertThat(logJObject.write(writer, 3, 1).toString(), is("{\n \"key1\": \"value1\",\n \"key\": \"value\"\n }"));
}
}
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.dmaap.datarouter.provisioning.utils;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.nio.file.Files;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+public class PurgeLogDirTaskTest {
+
+ private static EntityManagerFactory emf;
+ private static EntityManager em;
+ private PurgeLogDirTask purgeLogDirTask = new PurgeLogDirTask();
+ private File testLog;
+
+ @Before
+ public void setUp() throws Exception {
+ testLog = new File(System.getProperty("user.dir") + "/src/test/resources/IN.test_prov_logs");
+ prepFile(testLog);
+ }
+
+ @After
+ public void tearDown() throws IOException {
+ Files.deleteIfExists(testLog.toPath());
+ }
+
+ @BeforeClass
+ public static void init() {
+ emf = Persistence.createEntityManagerFactory("dr-unit-tests");
+ em = emf.createEntityManager();
+ System.setProperty(
+ "org.onap.dmaap.datarouter.provserver.properties",
+ "src/test/resources/h2Database.properties");
+ }
+
+ @AfterClass
+ public static void tearDownClass() {
+ em.clear();
+ em.close();
+ emf.close();
+ }
+
+ @Test
+ public void Verify_Logs_Are_Purged() {
+ purgeLogDirTask.run();
+ }
+
+ private void prepFile(File logFile) {
+ try (FileWriter fileWriter = new FileWriter(logFile)) {
+ fileWriter.write("2018-08-29-10-10-10-543.|LOG|1|1|https://dmaap-dr-prov:/url/file123|POST|application/vnd.att-dr.feed|100|mockType|file123|https://dmaap-dr-prov|user123|200|1|1|200|2|2\n");
+ }
+ catch (IOException e){
+ System.out.println(e.getMessage());
+ }
+ }
+}
</properties>
</persistence-unit>
+ <persistence-unit name="db-unit-tests" transaction-type="RESOURCE_LOCAL">
+ <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
+ <properties>
+ <!-- Configuring JDBC properties -->
+ <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test1;DB_CLOSE_DELAY=-1"/>
+ <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
+ <!-- Hibernate properties -->
+ <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
+ <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
+ <property name="hibernate.format_sql" value="false"/>
+ <property name="hibernate.show_sql" value="true"/>
+
+ </properties>
+ </persistence-unit>
</persistence>
VALUES (3, 1,'DeleteableAafFeed','v0.1', 'AAF Feed3 for testing', 'AAF Feed3 for testing', 'auth_class', 'pub','self_link','publish_link','subscribe_link','log_link','*');
insert into INGRESS_ROUTES(SEQUENCE, FEEDID , USERID, SUBNET, NODESET)
-VALUES (1,1,'user',null,2);
+VALUES (1,1,'user','172.100.0.0/25',2);
insert into INGRESS_ROUTES(SEQUENCE, FEEDID , USERID, SUBNET, NODESET)
-VALUES (2,1,'user',null,2);
+VALUES (2,1,'user2',null,2);
insert into NODESETS(SETID, NODEID)
VALUES (1,1);
org.onap.dmaap.datarouter.provserver.https.relaxation = false
org.onap.dmaap.datarouter.provserver.accesslog.dir = unit-test-logs
org.onap.dmaap.datarouter.provserver.spooldir = src/test/resources
+org.onap.dmaap.datarouter.provserver.dbscripts = src/test/resources
org.onap.dmaap.datarouter.provserver.localhost = 127.0.0.1
org.onap.dmaap.datarouter.provserver.passwordencryption = PasswordEncryptionKey#@$%^&1234#
--- /dev/null
+CREATE TABLE FEEDS (
+ FEEDID INT UNSIGNED NOT NULL PRIMARY KEY,
+ GROUPID INT(10) UNSIGNED NOT NULL DEFAULT 0,
+ NAME VARCHAR(256) NOT NULL,
+ VERSION VARCHAR(20) NULL,
+ DESCRIPTION VARCHAR(1000),
+ BUSINESS_DESCRIPTION VARCHAR(1000) DEFAULT NULL,
+ AUTH_CLASS VARCHAR(32) NOT NULL,
+ PUBLISHER VARCHAR(8) NOT NULL,
+ SELF_LINK VARCHAR(256),
+ PUBLISH_LINK VARCHAR(256),
+ SUBSCRIBE_LINK VARCHAR(256),
+ LOG_LINK VARCHAR(256),
+ DELETED BOOLEAN DEFAULT FALSE,
+ LAST_MOD TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ SUSPENDED BOOLEAN DEFAULT FALSE,
+ CREATED_DATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ AAF_INSTANCE VARCHAR(256)
+);
+
+CREATE TABLE FEED_ENDPOINT_IDS (
+ FEEDID INT UNSIGNED NOT NULL,
+ USERID VARCHAR(60) NOT NULL,
+ PASSWORD VARCHAR(100) NOT NULL
+);
+
+CREATE TABLE FEED_ENDPOINT_ADDRS (
+ FEEDID INT UNSIGNED NOT NULL,
+ ADDR VARCHAR(44) NOT NULL
+);
+
+CREATE TABLE SUBSCRIPTIONS (
+ SUBID INT UNSIGNED NOT NULL PRIMARY KEY,
+ FEEDID INT UNSIGNED NOT NULL,
+ GROUPID INT(10) UNSIGNED NOT NULL DEFAULT 0,
+ DELIVERY_URL VARCHAR(256),
+ FOLLOW_REDIRECTS TINYINT(1) NOT NULL DEFAULT 0,
+ DELIVERY_USER VARCHAR(60),
+ DELIVERY_PASSWORD VARCHAR(100),
+ DELIVERY_USE100 BOOLEAN DEFAULT FALSE,
+ METADATA_ONLY BOOLEAN DEFAULT FALSE,
+ SUBSCRIBER VARCHAR(8) NOT NULL,
+ SELF_LINK VARCHAR(256),
+ LOG_LINK VARCHAR(256),
+ LAST_MOD TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ SUSPENDED BOOLEAN DEFAULT FALSE,
+ PRIVILEGED_SUBSCRIBER BOOLEAN DEFAULT FALSE,
+ CREATED_DATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ DECOMPRESS BOOLEAN DEFAULT FALSE,
+ AAF_INSTANCE VARCHAR(256)
+
+);
+
+CREATE TABLE PARAMETERS (
+ KEYNAME VARCHAR(32) NOT NULL PRIMARY KEY,
+ VALUE VARCHAR(4096) NOT NULL
+);
+
+CREATE TABLE LOG_RECORDS (
+ TYPE ENUM('pub', 'del', 'exp', 'pbf', 'dlx') NOT NULL,
+ EVENT_TIME BIGINT NOT NULL, /* time of the publish request */
+ PUBLISH_ID VARCHAR(64) NOT NULL, /* unique ID assigned to this publish attempt */
+ FEEDID INT UNSIGNED NOT NULL, /* pointer to feed in FEEDS */
+ REQURI VARCHAR(256) NOT NULL, /* request URI */
+ METHOD ENUM('DELETE', 'GET', 'HEAD', 'OPTIONS', 'PUT', 'POST', 'TRACE') NOT NULL, /* HTTP method */
+ CONTENT_TYPE VARCHAR(256) NOT NULL, /* content type of published file */
+ CONTENT_LENGTH BIGINT NOT NULL, /* content length of published file */
+
+ FEED_FILEID VARCHAR(256), /* file ID of published file */
+ REMOTE_ADDR VARCHAR(40), /* IP address of publishing endpoint */
+ USER VARCHAR(50), /* user name of publishing endpoint */
+ STATUS SMALLINT, /* status code returned to delivering agent */
+
+ DELIVERY_SUBID INT UNSIGNED, /* pointer to subscription in SUBSCRIPTIONS */
+ DELIVERY_FILEID VARCHAR(256), /* file ID of file being delivered */
+ RESULT SMALLINT, /* result received from subscribing agent */
+
+ ATTEMPTS INT, /* deliveries attempted */
+ REASON ENUM('notRetryable', 'retriesExhausted', 'diskFull', 'other'),
+
+ RECORD_ID BIGINT UNSIGNED NOT NULL PRIMARY KEY, /* unique ID for this record */
+ CONTENT_LENGTH_2 BIGINT,
+ FILENAME VARCHAR(256), /* Name of the file being published on DR */
+
+) ENGINE = MyISAM;
+
+CREATE TABLE INGRESS_ROUTES (
+ SEQUENCE INT UNSIGNED NOT NULL,
+ FEEDID INT UNSIGNED NOT NULL,
+ USERID VARCHAR(50),
+ SUBNET VARCHAR(44),
+ NODESET INT UNSIGNED NOT NULL
+);
+
+CREATE TABLE EGRESS_ROUTES (
+ SUBID INT UNSIGNED NOT NULL PRIMARY KEY,
+ NODEID INT UNSIGNED NOT NULL
+);
+
+CREATE TABLE NETWORK_ROUTES (
+ FROMNODE INT UNSIGNED NOT NULL,
+ TONODE INT UNSIGNED NOT NULL,
+ VIANODE INT UNSIGNED NOT NULL
+);
+
+CREATE TABLE NODESETS (
+ SETID INT UNSIGNED NOT NULL,
+ NODEID INT UNSIGNED NOT NULL
+);
+
+CREATE TABLE NODES (
+ NODEID INT UNSIGNED NOT NULL PRIMARY KEY,
+ NAME VARCHAR(255) NOT NULL,
+ ACTIVE BOOLEAN DEFAULT TRUE
+);
+
+CREATE TABLE GROUPS (
+ GROUPID INT UNSIGNED NOT NULL PRIMARY KEY,
+ AUTHID VARCHAR(100) NOT NULL,
+ NAME VARCHAR(50) NOT NULL,
+ DESCRIPTION VARCHAR(255),
+ CLASSIFICATION VARCHAR(20) NOT NULL,
+ MEMBERS TINYTEXT,
+ LAST_MOD TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);
+
+INSERT INTO PARAMETERS VALUES
+ ('ACTIVE_POD', 'dmaap-dr-prov'),
+ ('PROV_ACTIVE_NAME', 'dmaap-dr-prov'),
+ ('STANDBY_POD', ''),
+ ('PROV_NAME', 'dmaap-dr-prov'),
+ ('NODES', 'dmaap-dr-node'),
+ ('PROV_DOMAIN', ''),
+ ('DELIVERY_INIT_RETRY_INTERVAL', '10'),
+ ('DELIVERY_MAX_AGE', '86400'),
+ ('DELIVERY_MAX_RETRY_INTERVAL', '3600'),
+ ('DELIVERY_FILE_PROCESS_INTERVAL', '600'),
+ ('DELIVERY_RETRY_RATIO', '2'),
+ ('LOGROLL_INTERVAL', '30'),
+ ('PROV_AUTH_ADDRESSES', 'dmaap-dr-prov|dmaap-dr-node'),
+ ('PROV_AUTH_SUBJECTS', ''),
+ ('PROV_MAXFEED_COUNT', '10000'),
+ ('PROV_MAXSUB_COUNT', '100000'),
+ ('PROV_REQUIRE_CERT', 'false'),
+ ('PROV_REQUIRE_SECURE', 'true'),
+ ('_INT_VALUES', 'LOGROLL_INTERVAL|PROV_MAXFEED_COUNT|PROV_MAXSUB_COUNT|DELIVERY_INIT_RETRY_INTERVAL|DELIVERY_MAX_RETRY_INTERVAL|DELIVERY_RETRY_RATIO|DELIVERY_MAX_AGE|DELIVERY_FILE_PROCESS_INTERVAL');
\ No newline at end of file
<sitePath>/content/sites/site/${project.groupId}/${project.artifactId}/${project.version}</sitePath>
<docker.location>${basedir}/target/${project.artifactId}</docker.location>
<datarouter.sub.image.name>${docker.image.root}${project.artifactId}</datarouter.sub.image.name>
+ <sonar.exclusions>src/main/java/org/onap/dmaap/datarouter/subscriber/**</sonar.exclusions>
<sonar.language>java</sonar.language>
<sonar.skip>false</sonar.skip>
</properties>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
+ <configuration>
+ <excludes>
+ <exclude>src/main/java/org/onap/dmaap/datarouter/subscriber/**</exclude>
+ </excludes>
+ </configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>