<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
- <version>1.2.0</version>
+ <version>${qos.logback.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
- <version>1.2.0</version>
+ <version>${qos.logback.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<dependency>\r
<groupId>ch.qos.logback</groupId>\r
<artifactId>logback-classic</artifactId>\r
- <version>1.2.0</version>\r
+ <version>${qos.logback.version}</version>\r
<scope>compile</scope>\r
</dependency>\r
<dependency>\r
<groupId>ch.qos.logback</groupId>\r
<artifactId>logback-core</artifactId>\r
- <version>1.2.0</version>\r
+ <version>${qos.logback.version}</version>\r
<scope>compile</scope>\r
</dependency>\r
<dependency>\r
outputType = req.getParameter("output_type");\r
}\r
\r
- try {\r
-\r
- String filterQuery = this.queryGeneretor(map);\r
- eventlogger.debug("SQL Query for Statistics resultset. " + filterQuery);\r
-\r
- ResultSet rs = this.getRecordsForSQL(filterQuery);\r
+ this.getRecordsForSQL(map, outputType, out, resp);\r
\r
- if (outputType.equals("csv")) {\r
- resp.setContentType("application/octet-stream");\r
- Date date = new Date();\r
- SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY HH:mm:ss");\r
- resp.setHeader("Content-Disposition",\r
- "attachment; filename=\"result:" + dateFormat.format(date) + ".csv\"");\r
- eventlogger.info("Generating CSV file from Statistics resultset");\r
-\r
- rsToCSV(rs, out);\r
- } else {\r
- eventlogger.info("Generating JSON for Statistics resultset");\r
- this.rsToJson(rs, out);\r
- }\r
- } catch (IOException e) {\r
- eventlogger.error("IOException - Generating JSON/CSV:" + e);\r
- e.printStackTrace();\r
- } catch (JSONException e) {\r
- eventlogger.error("JSONException - executing SQL query:" + e);\r
- e.printStackTrace();\r
- } catch (SQLException e) {\r
- eventlogger.error("SQLException - executing SQL query:" + e);\r
- e.printStackTrace();\r
- } catch (ParseException e) {\r
- eventlogger.error("ParseException - executing SQL query:" + e);\r
- e.printStackTrace();\r
- }\r
}\r
\r
\r
intlogger.info("Error parsing time=" + s);\r
return -1;\r
}\r
- private ResultSet getRecordsForSQL(String sql) {\r
- intlogger.debug(sql);\r
+\r
+ private void getRecordsForSQL(Map<String, String> map, String outputType, ServletOutputStream out, HttpServletResponse resp) {\r
+ try {\r
+\r
+ String filterQuery = this.queryGeneretor(map);\r
+ eventlogger.debug("SQL Query for Statistics resultset. " + filterQuery);\r
+ intlogger.debug(filterQuery);\r
long start = System.currentTimeMillis();\r
DB db = new DB();\r
ResultSet rs = null;\r
- try (\r
- Connection conn = db.getConnection()){\r
- try(PreparedStatement pst = conn.prepareStatement(sql)){\r
- rs = pst.executeQuery();\r
+ try (Connection conn = db.getConnection()) {\r
+ try (PreparedStatement pst = conn.prepareStatement(filterQuery)) {\r
+ rs = pst.executeQuery();\r
+ if (outputType.equals("csv")) {\r
+ resp.setContentType("application/octet-stream");\r
+ Date date = new Date();\r
+ SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY HH:mm:ss");\r
+ resp.setHeader("Content-Disposition",\r
+ "attachment; filename=\"result:" + dateFormat.format(date) + ".csv\"");\r
+ eventlogger.info("Generating CSV file from Statistics resultset");\r
+\r
+ rsToCSV(rs, out);\r
+ } else {\r
+ eventlogger.info("Generating JSON for Statistics resultset");\r
+ this.rsToJson(rs, out);\r
}\r
+ }\r
} catch (SQLException e) {\r
- e.printStackTrace();\r
- }\r
- intlogger.debug("Time: " + (System.currentTimeMillis() - start) + " ms");\r
- return rs;\r
+ e.printStackTrace();\r
}\r
+ intlogger.debug("Time: " + (System.currentTimeMillis() - start) + " ms");\r
+ } catch (IOException e) {\r
+ eventlogger.error("IOException - Generating JSON/CSV:" + e);\r
+ e.printStackTrace();\r
+ } catch (JSONException e) {\r
+ eventlogger.error("JSONException - executing SQL query:" + e);\r
+ e.printStackTrace();\r
+ } catch (ParseException e) {\r
+ eventlogger.error("ParseException - executing SQL query:" + e);\r
+ e.printStackTrace();\r
+ }\r
}\r
+}\r
\r
\r
package org.onap.dmaap.datarouter.provisioning.beans;\r
\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.ArrayList;\r
-import java.util.Collection;\r
-import java.util.Date;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Set;\r
-\r
import org.apache.log4j.Logger;\r
import org.json.JSONArray;\r
import org.json.JSONObject;\r
import org.onap.dmaap.datarouter.provisioning.utils.JSONUtilities;\r
import org.onap.dmaap.datarouter.provisioning.utils.URLUtilities;\r
\r
+import java.io.InvalidObjectException;\r
+import java.sql.*;\r
+import java.util.*;\r
+import java.util.Date;\r
+\r
/**\r
* The representation of a Feed. Feeds can be retrieved from the DB, or stored/updated in the DB.\r
*\r
try {\r
DB db = new DB();\r
Connection conn = db.getConnection();\r
- Statement stmt = conn.createStatement();\r
- ResultSet rs = stmt.executeQuery("select COUNT(*) from FEEDS where FEEDID = " + id);\r
- if (rs.next()) {\r
- count = rs.getInt(1);\r
+ try(Statement stmt = conn.createStatement()) {\r
+ try(ResultSet rs = stmt.executeQuery("select COUNT(*) from FEEDS where FEEDID = " + id)) {\r
+ if (rs.next()) {\r
+ count = rs.getInt(1);\r
+ }\r
+ }\r
}\r
- rs.close();\r
- stmt.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
e.printStackTrace();\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- Statement stmt = conn.createStatement();\r
- ResultSet rs = stmt.executeQuery("select count(*) from FEEDS where DELETED = 0");\r
- if (rs.next()) {\r
- count = rs.getInt(1);\r
+ try(Statement stmt = conn.createStatement()) {\r
+ try (ResultSet rs = stmt.executeQuery("select count(*) from FEEDS where DELETED = 0")) {\r
+ if (rs.next()) {\r
+ count = rs.getInt(1);\r
+ }\r
+ }\r
}\r
- rs.close();\r
- stmt.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
intlogger.info("countActiveFeeds: " + e.getMessage());\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- Statement stmt = conn.createStatement();\r
- ResultSet rs = stmt.executeQuery("select MAX(feedid) from FEEDS");\r
- if (rs.next()) {\r
- max = rs.getInt(1);\r
+ try(Statement stmt = conn.createStatement()) {\r
+ try (ResultSet rs = stmt.executeQuery("select MAX(feedid) from FEEDS")) {\r
+ if (rs.next()) {\r
+ max = rs.getInt(1);\r
+ }\r
+ }\r
}\r
- rs.close();\r
- stmt.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
intlogger.info("getMaxFeedID: " + e.getMessage());\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- Statement stmt = conn.createStatement();\r
- ResultSet rs = stmt.executeQuery("select * from FEEDS");\r
- while (rs.next()) {\r
- Feed feed = new Feed(rs);\r
- map.put(feed.getFeedid(), feed);\r
- }\r
- rs.close();\r
+ try(Statement stmt = conn.createStatement()) {\r
+ try(ResultSet rs = stmt.executeQuery("select * from FEEDS")) {\r
+ while (rs.next()) {\r
+ Feed feed = new Feed(rs);\r
+ map.put(feed.getFeedid(), feed);\r
+ }\r
+ }\r
\r
- String sql = "select * from FEED_ENDPOINT_IDS";\r
- rs = stmt.executeQuery(sql);\r
- while (rs.next()) {\r
- int id = rs.getInt("FEEDID");\r
- Feed feed = map.get(id);\r
- if (feed != null) {\r
- FeedEndpointID epi = new FeedEndpointID(rs);\r
- Collection<FeedEndpointID> ecoll = feed.getAuthorization().getEndpoint_ids();\r
- ecoll.add(epi);\r
+ String sql = "select * from FEED_ENDPOINT_IDS";\r
+ try(ResultSet rs = stmt.executeQuery(sql)){\r
+ while (rs.next()) {\r
+ int id = rs.getInt("FEEDID");\r
+ Feed feed = map.get(id);\r
+ if (feed != null) {\r
+ FeedEndpointID epi = new FeedEndpointID(rs);\r
+ Collection<FeedEndpointID> ecoll = feed.getAuthorization().getEndpoint_ids();\r
+ ecoll.add(epi);\r
+ }\r
+ }\r
}\r
- }\r
- rs.close();\r
\r
- sql = "select * from FEED_ENDPOINT_ADDRS";\r
- rs = stmt.executeQuery(sql);\r
- while (rs.next()) {\r
- int id = rs.getInt("FEEDID");\r
- Feed feed = map.get(id);\r
- if (feed != null) {\r
- Collection<String> acoll = feed.getAuthorization().getEndpoint_addrs();\r
- acoll.add(rs.getString("ADDR"));\r
+ sql = "select * from FEED_ENDPOINT_ADDRS";\r
+ try(ResultSet rs = stmt.executeQuery(sql)) {\r
+ while (rs.next()) {\r
+ int id = rs.getInt("FEEDID");\r
+ Feed feed = map.get(id);\r
+ if (feed != null) {\r
+ Collection<String> acoll = feed.getAuthorization().getEndpoint_addrs();\r
+ acoll.add(rs.getString("ADDR"));\r
+ }\r
+ }\r
}\r
}\r
- rs.close();\r
-\r
- stmt.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
e.printStackTrace();\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- PreparedStatement ps = conn.prepareStatement(sql);\r
- if (sql.indexOf('?') >= 0)\r
- ps.setString(1, val);\r
- ResultSet rs = ps.executeQuery();\r
- while (rs.next()) {\r
- String t = rs.getString(1);\r
- list.add(t.trim());\r
+ try(PreparedStatement ps = conn.prepareStatement(sql)) {\r
+ if (sql.indexOf('?') >= 0)\r
+ ps.setString(1, val);\r
+ try(ResultSet rs = ps.executeQuery()) {\r
+ while (rs.next()) {\r
+ String t = rs.getString(1);\r
+ list.add(t.trim());\r
+ }\r
+ }\r
}\r
- rs.close();\r
- ps.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
e.printStackTrace();\r
try {\r
DB db = new DB();\r
Connection conn = db.getConnection();\r
- Statement stmt = conn.createStatement();\r
- ResultSet rs = stmt.executeQuery(sql);\r
- if (rs.next()) {\r
- feed = new Feed(rs);\r
- rs.close();\r
-\r
- sql = "select * from FEED_ENDPOINT_IDS where FEEDID = " + feed.feedid;\r
- rs = stmt.executeQuery(sql);\r
- Collection<FeedEndpointID> ecoll = feed.getAuthorization().getEndpoint_ids();\r
- while (rs.next()) {\r
- FeedEndpointID epi = new FeedEndpointID(rs);\r
- ecoll.add(epi);\r
+ try (Statement stmt = conn.createStatement()) {\r
+ try (ResultSet rs = stmt.executeQuery(sql)) {\r
+ if (rs.next()) {\r
+ feed = new Feed(rs);\r
+ }\r
}\r
- rs.close();\r
-\r
- sql = "select * from FEED_ENDPOINT_ADDRS where FEEDID = " + feed.feedid;\r
- rs = stmt.executeQuery(sql);\r
- Collection<String> acoll = feed.getAuthorization().getEndpoint_addrs();\r
- while (rs.next()) {\r
- acoll.add(rs.getString("ADDR"));\r
+ if (feed != null) {\r
+ sql = "select * from FEED_ENDPOINT_IDS where FEEDID = " + feed.feedid;\r
+ try (ResultSet rs = stmt.executeQuery(sql)) {\r
+ Collection<FeedEndpointID> ecoll = feed.getAuthorization().getEndpoint_ids();\r
+ while (rs.next()) {\r
+ FeedEndpointID epi = new FeedEndpointID(rs);\r
+ ecoll.add(epi);\r
+ }\r
+ }\r
+ sql = "select * from FEED_ENDPOINT_ADDRS where FEEDID = " + feed.feedid;\r
+ try (ResultSet rs = stmt.executeQuery(sql)) {\r
+ Collection<String> acoll = feed.getAuthorization().getEndpoint_addrs();\r
+ while (rs.next()) {\r
+ acoll.add(rs.getString("ADDR"));\r
+ }\r
+ }\r
}\r
}\r
- rs.close();\r
- stmt.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
e.printStackTrace();\r
e.printStackTrace();\r
} finally {\r
try {\r
- ps.close();\r
+ if(ps!=null) {\r
+ ps.close();\r
+ }\r
} catch (SQLException e) {\r
e.printStackTrace();\r
}\r
@Override\r
public synchronized boolean doInsert(Connection c) {\r
boolean rv = true;\r
-// PreparedStatement ps = null;\r
try {\r
if (feedid == -1) {\r
-// // Get the next feedid\r
-// String sql = "insert into FEEDS_UNIQUEID (FEEDID) values (0)";\r
-// ps = c.prepareStatement(sql, new String[] { "FEEDID" });\r
-// ps.execute();\r
-// ResultSet rs = ps.getGeneratedKeys();\r
-// rs.first();\r
-// setFeedid(rs.getInt(1));\r
- // No feed ID assigned yet, so assign the next available one\r
setFeedid(next_feedid++);\r
}\r
// In case we insert a feed from synchronization\r
// Create FEED_ENDPOINT_IDS rows\r
FeedAuthorization auth = getAuthorization();\r
String sql = "insert into FEED_ENDPOINT_IDS values (?, ?, ?)";\r
- PreparedStatement ps2 = c.prepareStatement(sql);\r
- for (FeedEndpointID fid : auth.getEndpoint_ids()) {\r
- ps2.setInt(1, feedid);\r
- ps2.setString(2, fid.getId());\r
- ps2.setString(3, fid.getPassword());\r
- ps2.executeUpdate();\r
+ try(PreparedStatement ps2 = c.prepareStatement(sql)) {\r
+ for (FeedEndpointID fid : auth.getEndpoint_ids()) {\r
+ ps2.setInt(1, feedid);\r
+ ps2.setString(2, fid.getId());\r
+ ps2.setString(3, fid.getPassword());\r
+ ps2.executeUpdate();\r
+ }\r
}\r
- ps2.close();\r
\r
// Create FEED_ENDPOINT_ADDRS rows\r
sql = "insert into FEED_ENDPOINT_ADDRS values (?, ?)";\r
- ps2 = c.prepareStatement(sql);\r
- for (String t : auth.getEndpoint_addrs()) {\r
- ps2.setInt(1, feedid);\r
- ps2.setString(2, t);\r
- ps2.executeUpdate();\r
+ try(PreparedStatement ps2 = c.prepareStatement(sql)) {\r
+ for (String t : auth.getEndpoint_addrs()) {\r
+ ps2.setInt(1, feedid);\r
+ ps2.setString(2, t);\r
+ ps2.executeUpdate();\r
+ }\r
}\r
- ps2.close();\r
\r
// Finally, create the FEEDS row\r
sql = "insert into FEEDS (FEEDID, NAME, VERSION, DESCRIPTION, AUTH_CLASS, PUBLISHER, SELF_LINK, PUBLISH_LINK, SUBSCRIBE_LINK, LOG_LINK, DELETED, SUSPENDED,BUSINESS_DESCRIPTION, GROUPID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?)";\r
- ps2 = c.prepareStatement(sql);\r
- ps2.setInt(1, feedid);\r
- ps2.setString(2, getName());\r
- ps2.setString(3, getVersion());\r
- ps2.setString(4, getDescription());\r
- ps2.setString(5, getAuthorization().getClassification());\r
- ps2.setString(6, getPublisher());\r
- ps2.setString(7, getLinks().getSelf());\r
- ps2.setString(8, getLinks().getPublish());\r
- ps2.setString(9, getLinks().getSubscribe());\r
- ps2.setString(10, getLinks().getLog());\r
- ps2.setBoolean(11, isDeleted());\r
- ps2.setBoolean(12, isSuspended());\r
- ps2.setString(13, getBusiness_description()); // New field is added - Groups feature Rally:US708102 - 1610\r
- ps2.setInt(14, groupid); //New field is added - Groups feature Rally:US708115 - 1610\r
- ps2.executeUpdate();\r
- ps2.close();\r
+ try(PreparedStatement ps2 = c.prepareStatement(sql)) {\r
+ ps2.setInt(1, feedid);\r
+ ps2.setString(2, getName());\r
+ ps2.setString(3, getVersion());\r
+ ps2.setString(4, getDescription());\r
+ ps2.setString(5, getAuthorization().getClassification());\r
+ ps2.setString(6, getPublisher());\r
+ ps2.setString(7, getLinks().getSelf());\r
+ ps2.setString(8, getLinks().getPublish());\r
+ ps2.setString(9, getLinks().getSubscribe());\r
+ ps2.setString(10, getLinks().getLog());\r
+ ps2.setBoolean(11, isDeleted());\r
+ ps2.setBoolean(12, isSuspended());\r
+ ps2.setString(13, getBusiness_description()); // New field is added - Groups feature Rally:US708102 - 1610\r
+ ps2.setInt(14, groupid); //New field is added - Groups feature Rally:US708115 - 1610\r
+ ps2.executeUpdate();\r
+ }\r
} catch (SQLException e) {\r
rv = false;\r
intlogger.warn("PROV0005 doInsert: " + e.getMessage());\r
e.printStackTrace();\r
-// } finally {\r
-// try {\r
-// ps.close();\r
-// } catch (SQLException e) {\r
-// e.printStackTrace();\r
-// }\r
}\r
return rv;\r
}\r
e.printStackTrace();\r
} finally {\r
try {\r
- ps.close();\r
+ if(ps!=null) {\r
+ ps.close();\r
+ }\r
} catch (SQLException e) {\r
e.printStackTrace();\r
}\r
public String toString() {\r
return "FEED: feedid=" + feedid + ", name=" + name + ", version=" + version;\r
}\r
+\r
+ @Override\r
+ public int hashCode() {\r
+ return Objects.hash(feedid, groupid, name, version, description, business_description, authorization, publisher, links, deleted, suspended, last_mod, created_date);\r
+ }\r
}\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.Date;\r
-import java.util.List;\r
+import java.util.*;\r
\r
import org.apache.log4j.Logger;\r
import org.json.JSONObject;\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- Statement stmt = conn.createStatement();\r
- ResultSet rs = stmt.executeQuery(sql);\r
- while (rs.next()) {\r
- Group group = new Group(rs);\r
- list.add(group);\r
+ try(Statement stmt = conn.createStatement()) {\r
+ try(ResultSet rs = stmt.executeQuery(sql)) {\r
+ while (rs.next()) {\r
+ Group group = new Group(rs);\r
+ list.add(group);\r
+ }\r
+ }\r
}\r
- rs.close();\r
- stmt.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
e.printStackTrace();\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- Statement stmt = conn.createStatement();\r
- ResultSet rs = stmt.executeQuery("select MAX(groupid) from GROUPS");\r
- if (rs.next()) {\r
- max = rs.getInt(1);\r
+ try(Statement stmt = conn.createStatement()) {\r
+ try(ResultSet rs = stmt.executeQuery("select MAX(groupid) from GROUPS")) {\r
+ if (rs.next()) {\r
+ max = rs.getInt(1);\r
+ }\r
+ }\r
}\r
- rs.close();\r
- stmt.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
intlogger.info("getMaxSubID: " + e.getMessage());\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- Statement stmt = conn.createStatement();\r
- ResultSet rs = stmt.executeQuery(sql);\r
- while (rs.next()) {\r
- int groupid = rs.getInt("groupid");\r
- //list.add(URLUtilities.generateSubscriptionURL(groupid));\r
+ try(Statement stmt = conn.createStatement()) {\r
+ try(ResultSet rs = stmt.executeQuery(sql)) {\r
+ while (rs.next()) {\r
+ int groupid = rs.getInt("groupid");\r
+\r
+ }\r
+ }\r
}\r
- rs.close();\r
- stmt.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
e.printStackTrace();\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- Statement stmt = conn.createStatement();\r
- ResultSet rs = stmt.executeQuery("select count(*) from SUBSCRIPTIONS");\r
- if (rs.next()) {\r
- count = rs.getInt(1);\r
+ try(Statement stmt = conn.createStatement()) {\r
+ try(ResultSet rs = stmt.executeQuery("select count(*) from SUBSCRIPTIONS")) {\r
+ if (rs.next()) {\r
+ count = rs.getInt(1);\r
+ }\r
+ }\r
}\r
- rs.close();\r
- stmt.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
intlogger.warn("PROV0008 countActiveSubscriptions: " + e.getMessage());\r
e.printStackTrace();\r
} finally {\r
try {\r
- ps.close();\r
+ if(ps!=null) {\r
+ ps.close();\r
+ }\r
} catch (SQLException e) {\r
e.printStackTrace();\r
}\r
e.printStackTrace();\r
} finally {\r
try {\r
- ps.close();\r
+ if(ps!=null) {\r
+ ps.close();\r
+ }\r
} catch (SQLException e) {\r
e.printStackTrace();\r
}\r
e.printStackTrace();\r
} finally {\r
try {\r
- ps.close();\r
+ if(ps!=null) {\r
+ ps.close();\r
+ }\r
} catch (SQLException e) {\r
e.printStackTrace();\r
}\r
public String toString() {\r
return "GROUP: groupid=" + groupid;\r
}\r
+\r
+ @Override\r
+ public int hashCode() {\r
+ return Objects.hash(groupid, authid, name, description, classification, members, last_mod);\r
+ }\r
}\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- Statement stmt = conn.createStatement();\r
- 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
+ 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
+ }\r
}\r
- rs.close();\r
- stmt.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
e.printStackTrace();\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- Statement stmt = conn.createStatement();\r
- ResultSet rs = stmt.executeQuery(sql);\r
- if (rs.next()) {\r
- rv = rs.getInt("MAX");\r
+ try(Statement stmt = conn.createStatement()) {\r
+ try(ResultSet rs = stmt.executeQuery(sql)) {\r
+ if (rs.next()) {\r
+ rv = rs.getInt("MAX");\r
+ }\r
+ }\r
}\r
- rs.close();\r
- stmt.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
e.printStackTrace();\r
ps.setInt(1, feedid);\r
ps.setString(2, user);\r
ps.setString(3, subnet);\r
- ResultSet rs = ps.executeQuery();\r
- if (rs.next()) {\r
- int seq = rs.getInt("SEQUENCE");\r
- int nodeset = rs.getInt("NODESET");\r
- v = new IngressRoute(seq, feedid, user, subnet, nodeset);\r
+ try(ResultSet rs = ps.executeQuery()) {\r
+ if (rs.next()) {\r
+ int seq = rs.getInt("SEQUENCE");\r
+ int nodeset = rs.getInt("NODESET");\r
+ v = new IngressRoute(seq, feedid, user, subnet, nodeset);\r
+ }\r
}\r
- rs.close();\r
ps.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
e.printStackTrace();\r
} finally {\r
try {\r
- ps.close();\r
+ if(ps!=null) {\r
+ ps.close();\r
+ }\r
} catch (SQLException e) {\r
e.printStackTrace();\r
}\r
*/\r
public static Collection<IngressRoute> getIngressRoute(int seq) {\r
Collection<IngressRoute> rv = new ArrayList<IngressRoute>();\r
- PreparedStatement ps = null;\r
try {\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
String sql = "select FEEDID, USERID, SUBNET, NODESET from INGRESS_ROUTES where SEQUENCE = ?";\r
- ps = conn.prepareStatement(sql);\r
- ps.setInt(1, seq);\r
- ResultSet rs = ps.executeQuery();\r
- while (rs.next()) {\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
- rv.add(new IngressRoute(seq, feedid, user, subnet, nodeset));\r
+ try(PreparedStatement ps = conn.prepareStatement(sql)) {\r
+ ps.setInt(1, seq);\r
+ try(ResultSet rs = ps.executeQuery()) {\r
+ while (rs.next()) {\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
+ rv.add(new IngressRoute(seq, feedid, user, subnet, nodeset));\r
+ }\r
+ }\r
}\r
- rs.close();\r
- ps.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
e.printStackTrace();\r
- } finally {\r
- try {\r
- ps.close();\r
- } catch (SQLException e) {\r
- e.printStackTrace();\r
- }\r
}\r
return rv;\r
}\r
\r
private Collection<String> readNodes() {\r
Collection<String> set = new TreeSet<String>();\r
- PreparedStatement ps = null;\r
try {\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- Statement stmt = conn.createStatement();\r
String sql = "select NODEID from NODESETS where SETID = ?";\r
- ps = conn.prepareStatement(sql);\r
- ps.setInt(1, nodelist);\r
- ResultSet rs = ps.executeQuery();\r
- while (rs.next()) {\r
- int id = rs.getInt("NODEID");\r
- set.add(lookupNodeID(id));\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
}\r
- rs.close();\r
- stmt.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
e.printStackTrace();\r
- } finally {\r
- try {\r
- ps.close();\r
- } catch (SQLException e) {\r
- e.printStackTrace();\r
- }\r
}\r
return set;\r
}\r
e.printStackTrace();\r
} finally {\r
try {\r
- ps.close();\r
+ if(ps!=null) {\r
+ ps.close();\r
+ }\r
} catch (SQLException e) {\r
e.printStackTrace();\r
}\r
e.printStackTrace();\r
} finally {\r
try {\r
- ps.close();\r
+ if(ps!=null) {\r
+ ps.close();\r
+ }\r
} catch (SQLException e) {\r
e.printStackTrace();\r
}\r
import java.sql.ResultSet;\r
import java.sql.SQLException;\r
import java.sql.Statement;\r
+import java.util.Objects;\r
import java.util.SortedSet;\r
import java.util.TreeSet;\r
\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- Statement stmt = conn.createStatement();\r
- 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
+ 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
+ }\r
}\r
- rs.close();\r
- stmt.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
e.printStackTrace();\r
e.printStackTrace();\r
} finally {\r
try {\r
- ps.close();\r
+ if(ps!=null) {\r
+ ps.close();\r
+ }\r
} catch (SQLException e) {\r
e.printStackTrace();\r
}\r
e.printStackTrace();\r
} finally {\r
try {\r
- ps.close();\r
+ if(ps!=null) {\r
+ ps.close();\r
+ }\r
} catch (SQLException e) {\r
e.printStackTrace();\r
}\r
e.printStackTrace();\r
} finally {\r
try {\r
- ps.close();\r
+ if(ps!=null) {\r
+ ps.close();\r
+ }\r
} catch (SQLException e) {\r
e.printStackTrace();\r
}\r
return (fromnode == on.fromnode) && (tonode == on.tonode) && (vianode == on.vianode);\r
}\r
\r
+ @Override\r
+ public int hashCode() {\r
+ return Objects.hash(fromnode, tonode, vianode);\r
+ }\r
+\r
@Override\r
public int compareTo(NetworkRoute o) {\r
if (this.fromnode == o.fromnode) {\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.HashMap;\r
-import java.util.Map;\r
+import java.util.*;\r
\r
import org.apache.log4j.Logger;\r
import org.json.JSONObject;\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- Statement stmt = conn.createStatement();\r
- String sql = "select * from PARAMETERS";\r
- ResultSet rs = stmt.executeQuery(sql);\r
- while (rs.next()) {\r
- Parameters p = new Parameters(rs);\r
- coll.add(p);\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
+ }\r
}\r
- rs.close();\r
- stmt.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
e.printStackTrace();\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- Statement stmt = conn.createStatement();\r
- String sql = "select KEYNAME, VALUE from PARAMETERS where KEYNAME = '" + k + "'";\r
- ResultSet rs = stmt.executeQuery(sql);\r
- if (rs.next()) {\r
- v = new Parameters(rs);\r
+ try(Statement stmt = conn.createStatement()) {\r
+ String sql = "select KEYNAME, VALUE from PARAMETERS where KEYNAME = '" + k + "'";\r
+ try(ResultSet rs = stmt.executeQuery(sql)) {\r
+ if (rs.next()) {\r
+ v = new Parameters(rs);\r
+ }\r
+ }\r
}\r
- rs.close();\r
- stmt.close();\r
db.release(conn);\r
} catch (SQLException e) {\r
e.printStackTrace();\r
e.printStackTrace();\r
} finally {\r
try {\r
- ps.close();\r
+ if(ps!=null) {\r
+ ps.close();\r
+ }\r
} catch (SQLException e) {\r
e.printStackTrace();\r
}\r
e.printStackTrace();\r
} finally {\r
try {\r
- ps.close();\r
+ if(ps!=null) {\r
+ ps.close();\r
+ }\r
} catch (SQLException e) {\r
e.printStackTrace();\r
}\r
e.printStackTrace();\r
} finally {\r
try {\r
- ps.close();\r
+ if(ps!=null) {\r
+ ps.close();\r
+ }\r
} catch (SQLException e) {\r
e.printStackTrace();\r
}\r
return true;\r
}\r
\r
+ @Override\r
+ public int hashCode() {\r
+ return Objects.hash(keyname, value);\r
+ }\r
+\r
@Override\r
public String toString() {\r
return "PARAM: keyname=" + keyname + ", value=" + value;\r
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONObject;
+import org.junit.AfterClass;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.onap.dmaap.datarouter.authz.Authorizer;
import org.onap.dmaap.datarouter.provisioning.beans.Feed;
import org.onap.dmaap.datarouter.provisioning.beans.Updateable;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
+import org.onap.dmaap.datarouter.provisioning.utils.DB;
import org.powermock.modules.junit4.PowerMockRunner;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
@RunWith(PowerMockRunner.class)
-@SuppressStaticInitializationFor("org.onap.dmaap.datarouter.provisioning.beans.Feed")
public class FeedServletTest extends DrServletTestBase {
private static FeedServlet feedServlet;
@Mock
private HttpServletResponse response;
+ private static EntityManagerFactory emf;
+ private static EntityManager em;
+ private DB db;
+
+ @BeforeClass
+ public static void init() {
+ emf = Persistence.createEntityManagerFactory("dr-unit-tests");
+ em = emf.createEntityManager();
+ System.setProperty(
+ "org.onap.dmaap.datarouter.provserver.properties",
+ "src/test/resources/h2Database.properties");
+ }
+
+ @AfterClass
+ public static void tearDownClass() {
+ em.clear();
+ em.close();
+ emf.close();
+ }
+
@Before
public void setUp() throws Exception {
- super.setUp();
feedServlet = new FeedServlet();
+ db = new DB();
setAuthoriserToReturnRequestIsAuthorized();
- setPokerToNotCreateTimersWhenDeleteFeedIsCalled();
setUpValidAuthorisedRequest();
setUpValidSecurityOnHttpRequest();
setUpValidContentHeadersAndJSONOnHttpRequest();
public void Given_Request_Is_HTTP_DELETE_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
throws Exception {
when(request.isSecure()).thenReturn(false);
- FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
feedServlet.doDelete(request, response);
verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
}
@Test
public void Given_Request_Is_HTTP_DELETE_And_Feed_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated()
throws Exception {
- setFeedToReturnInvalidFeedIdSupplied();
+ when(request.getPathInfo()).thenReturn("/123");
feedServlet.doDelete(request, response);
verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
}
@Test
public void Given_Request_Is_HTTP_DELETE_And_Delete_On_Database_Succeeds_A_NO_CONTENT_Response_Is_Generated()
throws Exception {
- FeedServlet feedServlet = new FeedServlet() {
- protected boolean doUpdate(Updateable bean) {
- return true;
- }
- };
feedServlet.doDelete(request, response);
verify(response).setStatus(eq(HttpServletResponse.SC_NO_CONTENT));
+ reinsertFeedIntoDb();
}
@Test
public void Given_Request_Is_HTTP_GET_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
throws Exception {
when(request.isSecure()).thenReturn(false);
- FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
feedServlet.doGet(request, response);
verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
}
@Test
public void Given_Request_Is_HTTP_GET_And_Feed_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated()
throws Exception {
- setFeedToReturnInvalidFeedIdSupplied();
+ when(request.getPathInfo()).thenReturn("/123");
feedServlet.doGet(request, response);
verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
}
public void Given_Request_Is_HTTP_PUT_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
throws Exception {
when(request.isSecure()).thenReturn(false);
- FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
feedServlet.doPut(request, response);
verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
}
@Test
public void Given_Request_Is_HTTP_PUT_And_Feed_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated()
throws Exception {
- setFeedToReturnInvalidFeedIdSupplied();
+ when(request.getPathInfo()).thenReturn("/123");
feedServlet.doPut(request, response);
verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
}
FeedServlet feedServlet = new FeedServlet() {
protected JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
- jo.put("name", "stub_name");
- jo.put("version", "1.0");
+ jo.put("name", "Feed1");
+ jo.put("version", "v0.1");
jo.put("authorization", JSObject);
return jo;
}
}
@Test
- public void Given_Request_Is_HTTP_PUT_And_Change_On_Feeds_Fails_A_STATUS_OK_Response_Is_Generated() throws Exception {
+ public void Given_Request_Is_HTTP_PUT_And_Change_On_Feeds_Fails_An_Internal_Server_Error_Response_Is_Generated() throws Exception {
ServletOutputStream outStream = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(outStream);
FeedServlet feedServlet = new FeedServlet() {
protected JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
- jo.put("name", "stub_name");
- jo.put("version", "1.0");
+ jo.put("name", "Feed1");
+ jo.put("version", "v0.1");
jo.put("authorization", JSObject);
return jo;
}
FeedServlet feedServlet = new FeedServlet() {
protected JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
- jo.put("name", "stub_name");
- jo.put("version", "1.0");
+ jo.put("name", "Feed1");
+ jo.put("version", "v0.1");
jo.put("authorization", JSObject);
return jo;
}
- @Override
- protected boolean doUpdate(Updateable bean) {
- return true;
- }
};
feedServlet.doPut(request, response);
verify(response).setStatus(eq(HttpServletResponse.SC_OK));
}
private void setValidPathInfoInHttpHeader() {
- when(request.getPathInfo()).thenReturn("/123");
- }
-
- private void setFeedToReturnInvalidFeedIdSupplied() {
- PowerMockito.mockStatic(Feed.class);
- PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(null);
- }
-
- private void setFeedToReturnValidFeedForSuppliedId() {
- PowerMockito.mockStatic(Feed.class);
- Feed feed = mock(Feed.class);
- PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(feed);
- when(feed.isDeleted()).thenReturn(false);
- when(feed.asJSONObject(true)).thenReturn(mock(JSONObject.class));
- when(feed.getPublisher()).thenReturn("Stub_Value");
- when(feed.getName()).thenReturn("stub_name");
- when(feed.getVersion()).thenReturn("1.0");
- when(feed.asLimitedJSONObject()).thenReturn(mock(JSONObject.class));
+ when(request.getPathInfo()).thenReturn("/1");
}
private void setAuthoriserToReturnRequestNotAuthorized() throws IllegalAccessException {
when(authResponse.isAuthorized()).thenReturn(true);
}
- private void setPokerToNotCreateTimersWhenDeleteFeedIsCalled() throws Exception {
- Poker poker = mock(Poker.class);
- FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true);
- }
-
private void setUpValidAuthorisedRequest() throws Exception {
setUpValidSecurityOnHttpRequest();
setBehalfHeader("Stub_Value");
setValidPathInfoInHttpHeader();
- setFeedToReturnValidFeedForSuppliedId();
}
private void setUpValidContentHeadersAndJSONOnHttpRequest() {
when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.feed; version=1.0");
when(request.getHeader("X-ATT-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
}
+
+ private void reinsertFeedIntoDb() throws SQLException {
+ Feed feed = new Feed("Feed1","v0.1", "First Feed for testing", "First Feed for testing");
+ feed.setFeedid(1);
+ feed.setGroupid(1);
+ feed.setDeleted(false);
+ feed.doUpdate(db.getConnection());
+ }
}
\ No newline at end of file
import java.io.File;
import java.net.InetAddress;
-import java.util.HashMap;
-import java.util.Map;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.apache.commons.lang3.reflect.FieldUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.BeforeClass;
+import org.junit.AfterClass;
import org.mockito.Mock;
-import org.onap.dmaap.datarouter.authz.AuthorizationResponse;
-import org.onap.dmaap.datarouter.authz.Authorizer;
+
import org.onap.dmaap.datarouter.provisioning.beans.Deleteable;
-import org.onap.dmaap.datarouter.provisioning.beans.Feed;
import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
import org.onap.dmaap.datarouter.provisioning.beans.LogRecord;
-import org.onap.dmaap.datarouter.provisioning.beans.NodeClass;
-import org.onap.dmaap.datarouter.provisioning.beans.Parameters;
-import org.onap.dmaap.datarouter.provisioning.beans.Subscription;
import org.onap.dmaap.datarouter.provisioning.beans.Updateable;
-import org.onap.dmaap.datarouter.provisioning.utils.LogfileLoader;
-import org.onap.dmaap.datarouter.provisioning.utils.RLEBitSet;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(LogRecord.class)
-@SuppressStaticInitializationFor({"org.onap.dmaap.datarouter.provisioning.beans.Feed",
- "org.onap.dmaap.datarouter.provisioning.beans.Parameters",
- "org.onap.dmaap.datarouter.provisioning.beans.NodeClass",
- "org.onap.dmaap.datarouter.provisioning.beans.Subscription",
- "org.onap.dmaap.datarouter.provisioning.utils.LogfileLoader"})
public class InternalServletTest extends DrServletTestBase {
-
+ private static EntityManagerFactory emf;
+ private static EntityManager em;
private InternalServlet internalServlet;
@Mock
@Mock
private HttpServletResponse response;
+ @BeforeClass
+ public static void init() {
+ emf = Persistence.createEntityManagerFactory("dr-unit-tests");
+ em = emf.createEntityManager();
+ System.setProperty(
+ "org.onap.dmaap.datarouter.provserver.properties",
+ "src/test/resources/h2Database.properties");
+ }
+
+ @AfterClass
+ public static void tearDownClass() {
+ em.clear();
+ em.close();
+ emf.close();
+ }
+
@Before
public void setUp() throws Exception {
- super.setUp();
internalServlet = new InternalServlet();
- setAuthoriserToReturnRequestIsAuthorized();
setUpValidAuthorisedRequest();
}
public void Given_Request_Is_HTTP_GET_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
throws Exception {
when(request.getRemoteAddr()).thenReturn("127.100.0.3");
- FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
-
internalServlet.doGet(request, response);
verify(response)
.sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
}
@Test
- public void Given_Request_Is_HTTP_GET_With_Halt_In_Endpoint_Request_Succeeds() throws Exception {
+ public void Given_Request_Is_HTTP_GET_With_Halt_In_Endpoint_Then_Request_Succeeds() throws Exception {
when(request.getPathInfo()).thenReturn("/halt");
when(request.isSecure()).thenReturn(false);
when(request.getRemoteAddr()).thenReturn("127.0.0.1");
}
@Test
- public void Given_Request_Is_HTTP_GET_With_FetchProv_In_Endpoint_Request_Succeeds()
+ public void Given_Request_Is_HTTP_GET_With_FetchProv_In_Endpoint_Then_Request_Succeeds()
throws Exception {
when(request.getPathInfo()).thenReturn("/fetchProv");
when(request.isSecure()).thenReturn(false);
}
@Test
- public void Given_Request_Is_HTTP_GET_With_Prov_In_Endpoint_Request_Succeeds() throws Exception {
+ public void Given_Request_Is_HTTP_GET_With_Prov_In_Endpoint_Then_Request_Succeeds() throws Exception {
when(request.getPathInfo()).thenReturn("/prov");
when(request.getQueryString()).thenReturn(null);
setPokerToNotCreateTimers();
}
@Test
- public void Given_Request_Is_HTTP_GET_With_Logs_In_Endpoint_Request_Succeeds() throws Exception {
+ public void Given_Request_Is_HTTP_GET_With_Logs_In_Endpoint_Then_Request_Succeeds() throws Exception {
when(request.getPathInfo()).thenReturn("/logs/");
ServletOutputStream outStream = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(outStream);
}
@Test
- public void Given_Request_Is_HTTP_GET_Starts_With_Logs_In_Endpoint_Request_Succeeds()
+ public void Given_Request_Is_HTTP_GET_Starts_With_Logs_In_Endpoint_Then_Request_Succeeds()
throws Exception {
when(request.getPathInfo()).thenReturn("/logs/TestFile");
internalServlet.doGet(request, response);
}
@Test
- public void Given_Request_Is_HTTP_GET_With_Api_In_Endpoint_Request_Succeeds() throws Exception {
- when(request.getPathInfo()).thenReturn("/api/Key");
- setParametersToNotContactDb(false);
+ public void Given_Request_Is_HTTP_GET_With_Api_In_Endpoint_Then_Request_Succeeds() throws Exception {
+ when(request.getPathInfo()).thenReturn("/api/DELIVERY_MAX_RETRY_INTERVAL");
ServletOutputStream outStream = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(outStream);
internalServlet.doGet(request, response);
}
@Test
- public void Given_Request_Is_HTTP_GET_With_Drlogs_In_Endpoint_Request_Succeeds()
+ public void Given_Request_Is_HTTP_GET_With_Drlogs_In_Endpoint_Then_Request_Succeeds()
throws Exception {
when(request.getPathInfo()).thenReturn("/drlogs/");
- mockLogfileLoader();
ServletOutputStream outStream = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(outStream);
internalServlet.doGet(request, response);
}
@Test
- public void Given_Request_Is_HTTP_GET_Incorrect_Endpoint_Then_No_Content_Response_Is_Generated()
+ public void Given_Request_Is_HTTP_GET_With_Incorrect_Endpoint_Then_No_Content_Response_Is_Generated()
throws Exception {
when(request.getPathInfo()).thenReturn("/incorrect/");
internalServlet.doGet(request, response);
@Test
public void Given_Request_Is_HTTP_PUT_With_Api_In_Endpoint_Request_Succeeds() throws Exception {
- when(request.getPathInfo()).thenReturn("/api/Key");
- setParametersToNotContactDb(false);
+ when(request.getPathInfo()).thenReturn("/api/NODES");
String[] values = {"V", "a", "l", "u", "e", "s"};
when(request.getParameterValues(anyString())).thenReturn(values);
internalServlet = internalServerSuccess();
setPokerToNotCreateTimers();
- mockProvisioningParametersChanged();
internalServlet.doPut(request, response);
verify(response).setStatus(eq(HttpServletResponse.SC_OK));
}
@Test
public void Given_Request_Is_HTTP_PUT_With_Api_In_Endpoint_And_Update_Fails_Then_Internal_Server_Error_Is_Generated()
throws Exception {
- when(request.getPathInfo()).thenReturn("/api/Key");
- setParametersToNotContactDb(false);
+ when(request.getPathInfo()).thenReturn("/api/NODES");
String[] values = {"V", "a", "l", "u", "e", "s"};
when(request.getParameterValues(anyString())).thenReturn(values);
internalServlet = internalServerFailure();
@Test
public void Given_Request_Is_HTTP_DELETE_With_Api_In_Endpoint_Request_Succeeds()
throws Exception {
- when(request.getPathInfo()).thenReturn("/api/Key");
- setParametersToNotContactDb(false);
+ when(request.getPathInfo()).thenReturn("/api/NODES");
String[] values = {"V", "a", "l", "u", "e", "s"};
when(request.getParameterValues(anyString())).thenReturn(values);
internalServlet = internalServerSuccess();
setPokerToNotCreateTimers();
- mockProvisioningParametersChanged();
internalServlet.doDelete(request, response);
verify(response).setStatus(eq(HttpServletResponse.SC_OK));
}
@Test
public void Given_Request_Is_HTTP_DELETE_With_Api_In_Endpoint_And_Delete_Fails_Then_Internal_Server_Error_Is_Generated()
throws Exception {
- when(request.getPathInfo()).thenReturn("/api/Key");
- setParametersToNotContactDb(false);
+ when(request.getPathInfo()).thenReturn("/api/NODES");
String[] values = {"V", "a", "l", "u", "e", "s"};
when(request.getParameterValues(anyString())).thenReturn(values);
internalServlet = internalServerFailure();
throws Exception {
when(request.getRemoteAddr()).thenReturn("127.100.0.3");
internalServlet.doPost(request, response);
- FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
verify(response)
.sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
}
@Test
public void Given_Request_Is_HTTP_POST_With_Api_In_Endpoint_Request_Succeeds() throws Exception {
- when(request.getPathInfo()).thenReturn("/api/Key");
- setParametersToNotContactDb(true);
+ when(request.getPathInfo()).thenReturn("/api/key");
String[] values = {"V", "a", "l", "u", "e", "s"};
when(request.getParameterValues(anyString())).thenReturn(values);
internalServlet = internalServerSuccess();
setPokerToNotCreateTimers();
- mockProvisioningParametersChanged();
internalServlet.doPost(request, response);
verify(response).setStatus(eq(HttpServletResponse.SC_OK));
}
public void Given_Request_Is_HTTP_POST_With_Api_In_Endpoint_And_Insert_Fails_Then_Internal_Server_Error_Is_Generated()
throws Exception {
when(request.getPathInfo()).thenReturn("/api/Key");
- setParametersToNotContactDb(true);
String[] values = {"V", "a", "l", "u", "e", "s"};
when(request.getParameterValues(anyString())).thenReturn(values);
internalServlet = internalServerFailure();
File testDir = new File("unit-test-logs/spool");
testDir.mkdirs();
testDir.deleteOnExit();
- mockLogfileLoader();
internalServlet.doPost(request, response);
verify(response).setStatus(eq(HttpServletResponse.SC_CREATED));
}
.sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
}
- private void setAuthoriserToReturnRequestIsAuthorized() throws IllegalAccessException {
- AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
- Authorizer authorizer = mock(Authorizer.class);
- FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
- when(authorizer.decide(request)).thenReturn(authResponse);
- when(authResponse.isAuthorized()).thenReturn(true);
- }
-
private void setUpValidAuthorisedRequest() throws Exception {
setUpValidSecurityOnHttpRequest();
setBehalfHeader("Stub_Value");
FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true);
}
- private void setParametersToNotContactDb(boolean isPost) {
- PowerMockito.mockStatic(Parameters.class);
- Parameters parameters = mock(Parameters.class);
- if (isPost) {
- PowerMockito.when(Parameters.getParameter(anyString())).thenReturn(null);
- } else {
- PowerMockito.when(Parameters.getParameter(anyString())).thenReturn(parameters);
- }
- }
-
private InternalServlet internalServerSuccess() {
InternalServlet internalServlet = new InternalServlet() {
};
return internalServlet;
}
-
- private void mockProvisioningParametersChanged() throws IllegalAccessException {
- PowerMockito.mockStatic(Feed.class);
- PowerMockito.mockStatic(Subscription.class);
- PowerMockito.when(Feed.countActiveFeeds()).thenReturn(0);
- PowerMockito.when(Subscription.countActiveSubscriptions()).thenReturn(0);
- Map<String, Integer> map = new HashMap<>();
- FieldUtils.writeDeclaredStaticField(NodeClass.class, "map", map, true);
- }
-
- private void mockLogfileLoader() {
- PowerMockito.mockStatic(LogfileLoader.class);
- LogfileLoader logfileLoader = mock(LogfileLoader.class);
- when(logfileLoader.getBitSet()).thenReturn(new RLEBitSet());
- PowerMockito.when(LogfileLoader.getLoader()).thenReturn(logfileLoader);
- }
}
package org.onap.dmaap.datarouter.provisioning;
import static org.hamcrest.Matchers.notNullValue;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.doCallRealMethod;
-import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
+import org.junit.AfterClass;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.onap.dmaap.datarouter.provisioning.utils.DB;
import org.powermock.modules.junit4.PowerMockRunner;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+
@RunWith(PowerMockRunner.class)
-@PrepareForTest(StatisticsServlet.class)
-public class StatisticsServletTest extends DrServletTestBase {
+public class StatisticsServletTest {
private StatisticsServlet statisticsServlet;
@Mock
private HttpServletResponse response;
+ private DB db;
+
+ private static EntityManagerFactory emf;
+ private static EntityManager em;
+
+ @BeforeClass
+ public static void init() {
+ emf = Persistence.createEntityManagerFactory("dr-unit-tests");
+ em = emf.createEntityManager();
+ System.setProperty(
+ "org.onap.dmaap.datarouter.provserver.properties",
+ "src/test/resources/h2Database.properties");
+ }
+
+ @AfterClass
+ public static void tearDownClass() {
+ em.clear();
+ em.close();
+ emf.close();
+ }
+
@Before
public void setUp() throws Exception {
- super.setUp();
statisticsServlet = new StatisticsServlet();
+ db = new DB();
buildRequestParameters();
}
@Test
public void Given_Request_Is_HTTP_GET_With_GroupId_But_No_FeedId_Parameters_Then_Request_Succeeds()
throws Exception {
+ addAliasForSubstringIndex();
ServletOutputStream outStream = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(outStream);
- statisticsServlet = PowerMockito.mock(StatisticsServlet.class);
- PowerMockito.doReturn(null).when(statisticsServlet, "getRecordsForSQL", anyString());
- PowerMockito.doCallRealMethod().when(statisticsServlet, "buildMapFromRequest", anyObject());
- PowerMockito.doCallRealMethod().when(statisticsServlet, "getTimeFromParam", anyString());
- doNothing().when(statisticsServlet).rsToCSV(anyObject(), anyObject());
- doCallRealMethod().when(statisticsServlet).doGet(request, response);
- when(statisticsServlet.getFeedIdsByGroupId(anyInt())).thenReturn(new StringBuffer("1"));
statisticsServlet.doGet(request, response);
verify(response).setStatus(eq(HttpServletResponse.SC_OK));
}
@Test
public void Given_Request_Is_HTTP_GET_With_GroupId_And_FeedId_Parameters_Then_Request_Succeeds()
throws Exception {
+ addAliasForSubstringIndex();
when(request.getParameter("feedid")).thenReturn("1");
when(request.getParameter("statusCode")).thenReturn("500");
ServletOutputStream outStream = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(outStream);
- statisticsServlet = PowerMockito.mock(StatisticsServlet.class);
- PowerMockito.doReturn(null).when(statisticsServlet, "getRecordsForSQL", anyString());
- PowerMockito.doCallRealMethod().when(statisticsServlet, "buildMapFromRequest", anyObject());
- PowerMockito.doCallRealMethod().when(statisticsServlet, "getTimeFromParam", anyString());
- doNothing().when(statisticsServlet).rsToCSV(anyObject(), anyObject());
- doCallRealMethod().when(statisticsServlet).doGet(request, response);
- doCallRealMethod().when(statisticsServlet).queryGeneretor(anyObject());
- when(statisticsServlet.getFeedIdsByGroupId(anyInt())).thenReturn(new StringBuffer("1"));
statisticsServlet.doGet(request, response);
verify(response).setStatus(eq(HttpServletResponse.SC_OK));
}
when(request.getParameter("groupid")).thenReturn("1");
when(request.getParameter("subid")).thenReturn("1");
}
+ private void addAliasForSubstringIndex() throws SQLException {
+ String sql = "CREATE ALIAS IF NOT EXISTS `SUBSTRING_INDEX`AS $$ String Function(String one, String two, String three){ return \"url\"; }$$;";
+ Connection conn = db.getConnection();
+ PreparedStatement pst = conn.prepareStatement(sql);
+ pst.execute();
+ }
}
private static EntityManager em;
private SubscriptionServlet subscriptionServlet;
private DB db;
+ private final String URL= "https://172.100.0.5";
+ private final String USER = "user1";
+ private final String PASSWORD="password1";
@Mock
private HttpServletRequest request;
};
subscriptionServlet.doPut(request, response);
verify(response).setStatus(eq(HttpServletResponse.SC_OK));
+ changeSubscriptionBackToNormal();
}
@Test
}
private void insertSubscriptionIntoDb() throws SQLException {
- Subscription subscription = new Subscription("https://172.100.0.5", "user1", "password1");
+ Subscription subscription = new Subscription(URL, USER, PASSWORD);
subscription.setSubid(1);
subscription.setSubscriber("user1");
subscription.setFeedid(1);
- SubDelivery subDelivery = new SubDelivery("https://172.100.0.5:8080", "user1", "password1", true);
+ SubDelivery subDelivery = new SubDelivery(URL, USER, PASSWORD, true);
subscription.setDelivery(subDelivery);
subscription.setGroupid(1);
subscription.setMetadataOnly(false);
subscription.setSuspended(false);
subscription.doInsert(db.getConnection());
}
+
+ private void changeSubscriptionBackToNormal() throws SQLException {
+ Subscription subscription = new Subscription("https://172.100.0.5", "user1", "password1");
+ subscription.setSubid(1);
+ subscription.setSubscriber("user1");
+ subscription.setFeedid(1);
+ SubDelivery subDelivery = new SubDelivery(URL, USER, PASSWORD, true);
+ subscription.setDelivery(subDelivery);
+ subscription.setGroupid(1);
+ subscription.setMetadataOnly(false);
+ subscription.setSuspended(false);
+ subscription.changeOwnerShip();
+ subscription.doUpdate(db.getConnection());
+ }
}
\ No newline at end of file
INSERT INTO SUBSCRIPTIONS(SUBID, FEEDID, DELIVERY_URL, DELIVERY_USER, DELIVERY_PASSWORD, SUBSCRIBER, SELF_LINK, LOG_LINK)
VALUES (23, 1, 'http://delivery_url', 'user1', 'somepassword', 'sub123', 'selflink', 'loglink');
+INSERT INTO FEED_ENDPOINT_IDS(FEEDID, USERID, PASSWORD)
+VALUES (1, 'USER', 'PASSWORD');
+
INSERT INTO FEEDS(FEEDID, GROUPID, NAME, VERSION, DESCRIPTION, BUSINESS_DESCRIPTION, AUTH_CLASS, PUBLISHER, SELF_LINK, PUBLISH_LINK, SUBSCRIBE_LINK, LOG_LINK)
VALUES (1, 1,'Feed1','v0.1', 'First Feed for testing', 'First Feed for testing', 'auth_class', 'pub','self_link','publish_link','subscribe_link','log_link');
VALUES (2,1,'user',null,2);
insert into NODESETS(SETID, NODEID)
-VALUES (2,0);
\ No newline at end of file
+VALUES (2,0);
+
+insert into LOG_RECORDS(RECORD_ID,TYPE,EVENT_TIME,PUBLISH_ID,FEEDID,REQURI,METHOD,CONTENT_TYPE,CONTENT_LENGTH,FEED_FILEID,REMOTE_ADDR,USER,STATUS,DELIVERY_SUBID,DELIVERY_FILEID,RESULT,ATTEMPTS,REASON)
+VALUES(1,'pub',2536159564422,'ID',1,'URL','GET','application/vnd.att-dr.log-list; version=1.0',100,1,'172.0.0.8','user',204,1,1,204,0,'other');
+
+CREATE ALIAS IF NOT EXISTS `SUBSTRING_INDEX` AS $$
+ String Function(String one, String two, String three){
+ return "url";
+ }
+$$;
\ No newline at end of file
org.onap.dmaap.datarouter.db.driver = org.h2.Driver
org.onap.dmaap.datarouter.db.url = jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
org.onap.dmaap.datarouter.provserver.isaddressauthenabled = true
-org.onap.dmaap.datarouter.provserver.https.relaxation = false
\ No newline at end of file
+org.onap.dmaap.datarouter.provserver.https.relaxation = false
+org.onap.dmaap.datarouter.provserver.accesslog.dir = unit-test-logs
+org.onap.dmaap.datarouter.provserver.spooldir = unit-test-logs/spool
\ No newline at end of file
<artifactId>jetty-io</artifactId>
<version>${jetty.version}</version>
</dependency>
+ <dependency>
+ <groupId>com.thoughtworks.xstream</groupId>
+ <artifactId>xstream</artifactId>
+ <version>${thoughtworks.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
+ <version>${qos.logback.version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-core</artifactId>
+ <version>${qos.logback.version}</version>
+ <scope>compile</scope>
+ </dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>1.2.17</version>
<scope>compile</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-io</artifactId>
+ <version>1.3.2</version>
+ </dependency>
</dependencies>
<profiles>
<profile>
<archive>
<manifest>
<addClasspath>true</addClasspath>
- <mainClass>org.onap.dmaap.datarouter.subscriber.Subscriber</mainClass>
+ <mainClass>org.onap.dmaap.datarouter.subscriber.SubscriberMain</mainClass>
</manifest>
</archive>
</configuration>
--- /dev/null
+/*******************************************************************************
+ * ============LICENSE_START==================================================
+ * * org.onap.dmaap
+ * * ===========================================================================
+ * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * * ===========================================================================
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ * * ============LICENSE_END====================================================
+ * *
+ * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * *
+ ******************************************************************************/
+package org.onap.dmaap.datarouter.subscriber;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.log4j.Logger;
+
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.net.URLEncoder;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+
+public class SampleSubscriberServlet extends HttpServlet {
+
+ private static Logger logger =
+ Logger.getLogger("org.onap.dmaap.datarouter.subscriber.SampleSubscriberServlet");
+ private String outputDirectory;
+ private String basicAuth;
+
+ /**
+ * Configure the SampleSubscriberServlet.
+ *
+ * <ul>
+ * <li>Login - The login expected in the Authorization header (default "LOGIN").
+ * <li>Password - The password expected in the Authorization header (default "PASSWORD").
+ * <li>outputDirectory - The directory where files are placed (default
+ * "/opt/app/subscriber/delivery").
+ * </ul>
+ */
+ @Override
+ public void init() {
+ SubscriberProps props = SubscriberProps.getInstance();
+ String login = props.getValue("org.onap.dmaap.datarouter.subscriber.auth.user", "LOGIN");
+ String password =
+ props.getValue("org.onap.dmaap.datarouter.subscriber.auth.password", "PASSWORD");
+ outputDirectory =
+ props.getValue(
+ "org.onap.dmaap.datarouter.subscriber.delivery.dir", "/opt/app/subscriber/delivery");
+ try {
+ Files.createDirectory(Paths.get(outputDirectory));
+ } catch (IOException e) {
+ logger.info("SubServlet: Failed to create delivery dir: " + e.getMessage());
+ }
+ basicAuth = "Basic " + Base64.encodeBase64String((login + ":" + password).getBytes());
+ }
+
+ @Override
+ protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
+ try {
+ common(req, resp, false);
+ } catch (IOException e) {
+ logger.info(
+ "SampleSubServlet: Failed to doPut: " + req.getRemoteAddr() + " : " + req.getPathInfo(),
+ e);
+ }
+ }
+
+ @Override
+ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
+ try {
+ common(req, resp, true);
+ } catch (IOException e) {
+ logger.info(
+ "SampleSubServlet: Failed to doDelete: "
+ + req.getRemoteAddr()
+ + " : "
+ + req.getPathInfo(),
+ e);
+ }
+ }
+ /**
+ * Process a PUT or DELETE request.
+ *
+ * <ol>
+ * <li>Verify that the request contains an Authorization header or else UNAUTHORIZED.
+ * <li>Verify that the Authorization header matches the configured Login and Password or else
+ * FORBIDDEN.
+ * <li>If the request is PUT, store the message body as a file in the configured outputDirectory
+ * directory protecting against evil characters in the received FileID. The file is created
+ * initially with its name prefixed with a ".", and once it is complete, it is renamed to
+ * remove the leading "." character.
+ * <li>If the request is DELETE, instead delete the file (if it exists) from the configured
+ * outputDirectory directory.
+ * <li>Respond with NO_CONTENT.
+ * </ol>
+ */
+ private void common(HttpServletRequest req, HttpServletResponse resp, boolean isdelete)
+ throws IOException {
+ String authHeader = req.getHeader("Authorization");
+ if (authHeader == null) {
+ logger.info(
+ "SampleSubServlet: Rejecting request with no Authorization header from "
+ + req.getRemoteAddr()
+ + ": "
+ + req.getPathInfo());
+ resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
+ return;
+ }
+ if (!basicAuth.equals(authHeader)) {
+ logger.info(
+ "SampleSubServlet: Rejecting request with incorrect Authorization header from "
+ + req.getRemoteAddr()
+ + ": "
+ + req.getPathInfo());
+ resp.sendError(HttpServletResponse.SC_FORBIDDEN);
+ return;
+ }
+ String fileid = req.getPathInfo();
+ fileid = fileid.substring(fileid.lastIndexOf('/') + 1);
+ String queryString = req.getQueryString();
+ if (queryString != null) {
+ fileid = fileid + "?" + queryString;
+ }
+ String publishid = req.getHeader("X-ATT-DR-PUBLISH-ID");
+ String filename =
+ URLEncoder.encode(fileid, "UTF-8").replaceAll("^\\.", "%2E").replaceAll("\\*", "%2A");
+ String fullPath = outputDirectory + "/" + filename;
+ String tmpPath = outputDirectory + "/." + filename;
+ try {
+ if (isdelete) {
+ Files.deleteIfExists(Paths.get(fullPath));
+ logger.info(
+ "SampleSubServlet: Received delete for file id "
+ + fileid
+ + " from "
+ + req.getRemoteAddr()
+ + " publish id "
+ + publishid
+ + " as "
+ + fullPath);
+ } else {
+ new File(tmpPath).createNewFile();
+ try (InputStream is = req.getInputStream();
+ OutputStream os = new FileOutputStream(tmpPath)) {
+ byte[] buf = new byte[65536];
+ int i;
+ while ((i = is.read(buf)) > 0) {
+ os.write(buf, 0, i);
+ }
+ }
+ Files.move(Paths.get(tmpPath), Paths.get(fullPath), StandardCopyOption.REPLACE_EXISTING);
+ logger.info(
+ "SampleSubServlet: Received file id "
+ + fileid
+ + " from "
+ + req.getRemoteAddr()
+ + " publish id "
+ + publishid
+ + " as "
+ + fullPath);
+ resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
+ }
+ resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
+ } catch (IOException ioe) {
+ Files.deleteIfExists(Paths.get(tmpPath));
+ logger.info(
+ "SampleSubServlet: Failed to process file "
+ + fullPath
+ + " from "
+ + req.getRemoteAddr()
+ + ": "
+ + req.getPathInfo());
+ throw ioe;
+ }
+ }
+}
package org.onap.dmaap.datarouter.subscriber;
import org.apache.log4j.Logger;
-import org.eclipse.jetty.servlet.*;
-import org.eclipse.jetty.util.ssl.*;
-import org.eclipse.jetty.server.*;
import org.eclipse.jetty.http.HttpVersion;
+import org.eclipse.jetty.server.*;
+import org.eclipse.jetty.servlet.ServletContextHandler;
+import org.eclipse.jetty.servlet.ServletHolder;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
-import java.io.FileInputStream;
-import java.io.IOException;
import java.util.Arrays;
-import java.util.Properties;
-
-public class Subscriber {
- private static Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.subscriber.Subscriber");
+public class SubscriberMain {
- private static final String CONTEXT_PATH = "/";
- private static final String URL_PATTERN = "/*";
-
- static Properties props;
-
- private static void loadProps() {
- if (props == null) {
- props = new Properties();
- try {
- props.load(new FileInputStream(System.getProperty(
- "org.onap.dmaap.datarouter.subscriber.properties",
- "/opt/app/subscriber/etc/subscriber.properties")));
- } catch (IOException e) {
- logger.fatal("SubServlet: Exception opening properties: " + e.getMessage());
- System.exit(1);
- }
- }
- }
+ private static Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.subscriber.SubscriberMain");
public static void main(String[] args) throws Exception {
- //Load the properties
- loadProps();
-
- int httpsPort = Integer.parseInt(props.getProperty("org.onap.dmaap.datarouter.subscriber.https.port", "8443"));
- int httpPort = Integer.parseInt(props.getProperty("org.onap.dmaap.datarouter.subscriber.http.port", "8080"));
+ SubscriberProps props = SubscriberProps.getInstance(
+ System.getProperty("org.onap.dmaap.datarouter.subscriber.properties", "subscriber.properties"));
+ int httpsPort = Integer.parseInt(props.getValue("org.onap.dmaap.datarouter.subscriber.https.port", "8443"));
+ int httpPort = Integer.parseInt(props.getValue("org.onap.dmaap.datarouter.subscriber.http.port", "8080"));
Server server = new Server();
HttpConfiguration httpConfig = new HttpConfiguration();
/*Skip SSLv3 Fixes*/
sslContextFactory.addExcludeProtocols("SSLv3");
- logger.info("Excluded protocols for Subscriber:" + Arrays.toString(sslContextFactory.getExcludeProtocols()));
+ logger.info("Excluded protocols for SubscriberMain:" + Arrays.toString(sslContextFactory.getExcludeProtocols()));
/*End of SSLv3 Fixes*/
// HTTPS Configuration
server.setConnectors(new Connector[]{ httpServerConnector });
}
ctxt = new ServletContextHandler(0);
- ctxt.setContextPath(CONTEXT_PATH);
+ ctxt.setContextPath("/");
server.setHandler(ctxt);
- ctxt.addServlet(new ServletHolder(new SubscriberServlet()), URL_PATTERN);
+ ctxt.addServlet(new ServletHolder(new SampleSubscriberServlet()), "/*");
try {
server.start();
} catch ( Exception e ) {
logger.info("Jetty failed to start. Reporting will be unavailable-"+e);
}
server.join();
- logger.info("org.onap.dmaap.datarouter.subscriber.Subscriber started-"+ server.getState());
+ logger.info("org.onap.dmaap.datarouter.subscriber.SubscriberMain started-"+ server.getState());
}
}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * ============LICENSE_START==================================================
+ * * org.onap.dmaap
+ * * ===========================================================================
+ * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * * ===========================================================================
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ * * ============LICENSE_END====================================================
+ * *
+ * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * *
+ ******************************************************************************/
+
+package org.onap.dmaap.datarouter.subscriber;
+
+import java.io.IOException;
+import java.util.Properties;
+
+public class SubscriberProps {
+
+ private static SubscriberProps instance = null;
+ private Properties properties;
+
+ private SubscriberProps(String propsPath) throws IOException{
+ properties = new Properties();
+ properties.load(getClass().getClassLoader().getResourceAsStream(propsPath));
+
+ }
+
+ public static SubscriberProps getInstance(String propsPath) {
+ if(instance == null) {
+ try {
+ instance = new SubscriberProps(propsPath);
+ } catch (IOException ioe) {
+ ioe.printStackTrace();
+ }
+ }
+ return instance;
+ }
+
+ public static SubscriberProps getInstance() {
+ return instance;
+ }
+
+ public String getValue(String key) {
+ return properties.getProperty(key);
+ }
+
+ public String getValue(String key, String defaultValue) {
+ return properties.getProperty(key, defaultValue);
+ }
+
+}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * ============LICENSE_START==================================================
- * * org.onap.dmaap
- * * ===========================================================================
- * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
- * * ===========================================================================
- * * Licensed under the Apache License, Version 2.0 (the "License");
- * * you may not use this file except in compliance with the License.
- * * You may obtain a copy of the License at
- * *
- * * http://www.apache.org/licenses/LICENSE-2.0
- * *
- * * Unless required by applicable law or agreed to in writing, software
- * * distributed under the License is distributed on an "AS IS" BASIS,
- * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * * See the License for the specific language governing permissions and
- * * limitations under the License.
- * * ============LICENSE_END====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-
-package org.onap.dmaap.datarouter.subscriber;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.log4j.Logger;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.*;
-import java.net.URLEncoder;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.nio.file.StandardCopyOption;
-import java.nio.file.attribute.PosixFilePermissions;
-
-import static org.onap.dmaap.datarouter.subscriber.Subscriber.props;
-
-public class SubscriberServlet extends HttpServlet {
-
- private static Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.subscriber.SubscriberServlet");
- private String outputDirectory;
- private String basicAuth;
-
- /**
- * Configure this subscriberservlet. Configuration parameters from config.getInitParameter() are:
- * <ul>
- * <li>Login - The login expected in the Authorization header (default "LOGIN").
- * <li>Password - The password expected in the Authorization header (default "PASSWORD").
- * <li>outputDirectory - The directory where files are placed (default "tmp").
- * </ul>
- */
- @Override
- public void init(ServletConfig config) {
- String login = props.getProperty("org.onap.dmaap.datarouter.subscriber.auth.user", "LOGIN");
- String password = props.getProperty("org.onap.dmaap.datarouter.subscriber.auth.password", "PASSWORD");
- outputDirectory = props.getProperty("org.onap.dmaap.datarouter.subscriber.delivery.dir", "/tmp");
- try {
- Files.createDirectory(Paths.get(outputDirectory), PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx")));
- } catch (IOException e) {
- logger.info("SubServlet: Failed to create delivery dir: " + e.getMessage());
- e.printStackTrace();
- }
- basicAuth = "Basic " + Base64.encodeBase64String((login + ":" + password).getBytes());
- }
-
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
- File filesPath = new File(outputDirectory);
- File[] filesArr = filesPath.listFiles();
- assert filesArr != null;
- for (File file: filesArr) {
- try (BufferedReader in = new BufferedReader(new FileReader(file))) {
- String line = in.readLine();
- while (line != null) {
- line = in.readLine();
- }
- }
- }
- }
- /**
- * Invoke common(req, resp, false).
- */
- @Override
- protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
- try {
- common(req, resp, false);
- } catch (IOException e) {
- logger.info("SubServlet: Failed to doPut: " + req.getRemoteAddr() + " : " + req.getPathInfo(), e);
- }
- }
- /**
- * Invoke common(req, resp, true).
- */
- @Override
- protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
- try {
- common(req, resp, true);
- } catch (IOException e) {
- logger.info("SubServlet: Failed to doDelete: " + req.getRemoteAddr() + " : " + req.getPathInfo(), e);
- }
- }
- /**
- * Process a PUT or DELETE request.
- * <ol>
- * <li>Verify that the request contains an Authorization header
- * or else UNAUTHORIZED.
- * <li>Verify that the Authorization header matches the configured
- * Login and Password or else FORBIDDEN.
- * <li>If the request is PUT, store the message body as a file
- * in the configured outputDirectory directory protecting against
- * evil characters in the received FileID. The file is created
- * initially with its name prefixed with a ".", and once it is complete, it is
- * renamed to remove the leading "." character.
- * <li>If the request is DELETE, instead delete the file (if it exists) from the configured outputDirectory directory.
- * <li>Respond with NO_CONTENT.
- * </ol>
- */
- private void common(HttpServletRequest req, HttpServletResponse resp, boolean isdelete) throws IOException {
- String authHeader = req.getHeader("Authorization");
- if (authHeader == null) {
- logger.info("Rejecting request with no Authorization header from " + req.getRemoteAddr() + ": " + req.getPathInfo());
- resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
- return;
- }
- if (!basicAuth.equals(authHeader)) {
- logger.info("Rejecting request with incorrect Authorization header from " + req.getRemoteAddr() + ": " + req.getPathInfo());
- resp.sendError(HttpServletResponse.SC_FORBIDDEN);
- return;
- }
- String fileid = req.getPathInfo();
- fileid = fileid.substring(fileid.lastIndexOf('/') + 1);
- String queryString = req.getQueryString();
- if (queryString != null) {
- fileid = fileid + "?" + queryString;
- }
- String publishid = req.getHeader("X-ATT-DR-PUBLISH-ID");
- String filename = URLEncoder.encode(fileid, "UTF-8").replaceAll("^\\.", "%2E").replaceAll("\\*", "%2A");
- String fullPath = outputDirectory + "/" + filename;
- String tmpPath = outputDirectory + "/." + filename;
- try {
- if (isdelete) {
- Files.deleteIfExists(Paths.get(fullPath));
- logger.info("Received delete for file id " + fileid + " from " + req.getRemoteAddr() + " publish id " + publishid + " as " + fullPath);
- } else {
- new File(tmpPath).createNewFile();
- try (InputStream is = req.getInputStream(); OutputStream os = new FileOutputStream(tmpPath)) {
- byte[] buf = new byte[65536];
- int i;
- while ((i = is.read(buf)) > 0) {
- os.write(buf, 0, i);
- }
- }
- Files.move(Paths.get(tmpPath), Paths.get(fullPath), StandardCopyOption.REPLACE_EXISTING);
- logger.info("Received file id " + fileid + " from " + req.getRemoteAddr() + " publish id " + publishid + " as " + fullPath);
- resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
- }
- resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
- } catch (IOException ioe) {
- Files.deleteIfExists(Paths.get(tmpPath));
- logger.info("Failed to process file " + fullPath + " from " + req.getRemoteAddr() + ": " + req.getPathInfo());
- throw ioe;
- }
- }
-}
for FILE in `find $LIB -name *.jar`; do
CLASSPATH=$CLASSPATH:$FILE
done
-java -classpath $CLASSPATH org.onap.dmaap.datarouter.subscriber.Subscriber
+java -classpath $CLASSPATH org.onap.dmaap.datarouter.subscriber.SubscriberMain
runner_file="$LIB/subscriber-jar-with-dependencies.jar"
echo "Starting using" $runner_file
# *
#-------------------------------------------------------------------------------
-#Subscriber properties
+#SubscriberMain properties
org.onap.dmaap.datarouter.subscriber.http.port = 7070
org.onap.dmaap.datarouter.subscriber.https.port = 7443
org.onap.dmaap.datarouter.subscriber.auth.user = LOGIN
--- /dev/null
+/*******************************************************************************
+ * ============LICENSE_START==================================================
+ * * org.onap.dmaap
+ * * ===========================================================================
+ * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * * ===========================================================================
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ * * ============LICENSE_END====================================================
+ * *
+ * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * *
+ ******************************************************************************/
+package org.onap.dmaap.datarouter.subscriber;
+
+import org.apache.commons.io.FileUtils;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import javax.servlet.ServletInputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.File;
+import java.io.IOException;
+
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.*;
+
+@RunWith(PowerMockRunner.class)
+public class SampleSubscriberServletTest {
+
+ private SampleSubscriberServlet sampleSubServlet;
+ private SubscriberProps props = SubscriberProps.getInstance();
+
+ @Mock private HttpServletRequest request;
+ @Mock private HttpServletResponse response;
+
+ @Before
+ public void setUp() {
+ props =
+ SubscriberProps.getInstance(
+ System.getProperty(
+ "org.onap.dmaap.datarouter.subscriber.properties", "testsubscriber.properties"));
+ sampleSubServlet = new SampleSubscriberServlet();
+ sampleSubServlet.init();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ FileUtils.deleteDirectory(
+ new File(props.getValue("org.onap.dmaap.datarouter.subscriber.delivery.dir")));
+ }
+
+ @Test
+ public void
+ Given_Request_Is_HTTP_PUT_And_Request_Header_Is_Null_Then_Unathorized_Response_Is_Generated()
+ throws Exception {
+ when(request.getHeader("Authorization")).thenReturn(null);
+ sampleSubServlet.doPut(request, response);
+ verify(response).sendError(eq(HttpServletResponse.SC_UNAUTHORIZED));
+ }
+
+ @Test
+ public void
+ Given_Request_Is_HTTP_PUT_And_Request_Header_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated()
+ throws Exception {
+ when(request.getHeader("Authorization")).thenReturn("Invalid Header");
+ sampleSubServlet.doPut(request, response);
+ verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN));
+ }
+
+ @Test
+ public void Given_Request_Is_HTTP_PUT_Then_Request_Succeeds() throws Exception {
+ setUpSuccessfulFlow();
+ sampleSubServlet.doPut(request, response);
+ verify(response, times(2)).setStatus(eq(HttpServletResponse.SC_NO_CONTENT));
+ }
+
+ @Test
+ public void Given_Request_Is_HTTP_DELETE_Then_Request_Succeeds() throws Exception {
+ setUpSuccessfulFlow();
+ sampleSubServlet.doDelete(request, response);
+ verify(response).setStatus(eq(HttpServletResponse.SC_NO_CONTENT));
+ }
+
+ private void setUpSuccessfulFlow() throws IOException {
+ when(request.getHeader("Authorization")).thenReturn("Basic TE9HSU46UEFTU1dPUkQ=");
+ when(request.getPathInfo()).thenReturn("/publish/1/testfile");
+ when(request.getHeader("X-ATT-DR-PUBLISH-ID")).thenReturn("1");
+ when(request.getQueryString()).thenReturn(null);
+ ServletInputStream inStream = mock(ServletInputStream.class);
+ when(request.getInputStream()).thenReturn(inStream);
+ }
+}
--- /dev/null
+#-------------------------------------------------------------------------------
+# ============LICENSE_START==================================================
+# * org.onap.dmaap
+# * ===========================================================================
+# * Copyright � 2017 AT&T Intellectual Property. All rights reserved.
+# * ===========================================================================
+# * Licensed under the Apache License, Version 2.0 (the "License");
+# * you may not use this file except in compliance with the License.
+# * You may obtain a copy of the License at
+# *
+# * http://www.apache.org/licenses/LICENSE-2.0
+# *
+# * Unless required by applicable law or agreed to in writing, software
+# * distributed under the License is distributed on an "AS IS" BASIS,
+# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# * See the License for the specific language governing permissions and
+# * limitations under the License.
+# * ============LICENSE_END====================================================
+# *
+# * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+# *
+#-------------------------------------------------------------------------------
+
+log4j.rootLogger=info,Root
+
+log4j.appender.Root=org.apache.log4j.DailyRollingFileAppender
+log4j.appender.Root.file=./logs/subscriber.log
+log4j.appender.Root.datePattern='.'yyyyMMdd
+log4j.appender.Root.append=true
+log4j.appender.Root.layout=org.apache.log4j.PatternLayout
+log4j.appender.Root.layout.ConversionPattern=%d %p %t %m%n
--- /dev/null
+#-------------------------------------------------------------------------------
+# ============LICENSE_START==================================================
+# * org.onap.dmaap
+# * ===========================================================================
+# * Copyright � 2017 AT&T Intellectual Property. All rights reserved.
+# * ===========================================================================
+# * Licensed under the Apache License, Version 2.0 (the "License");
+# * you may not use this file except in compliance with the License.
+# * You may obtain a copy of the License at
+# *
+# * http://www.apache.org/licenses/LICENSE-2.0
+# *
+# * Unless required by applicable law or agreed to in writing, software
+# * distributed under the License is distributed on an "AS IS" BASIS,
+# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# * See the License for the specific language governing permissions and
+# * limitations under the License.
+# * ============LICENSE_END====================================================
+# *
+# * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+# *
+#-------------------------------------------------------------------------------
+
+#SubscriberMain test properties
+org.onap.dmaap.datarouter.subscriber.http.port = 7070
+org.onap.dmaap.datarouter.subscriber.https.port = 7443
+org.onap.dmaap.datarouter.subscriber.auth.user = LOGIN
+org.onap.dmaap.datarouter.subscriber.auth.password = PASSWORD
+org.onap.dmaap.datarouter.subscriber.delivery.dir = tmp
+
+
<jetty.version>9.3.8.RC0</jetty.version>
<jetty.websocket.version>8.2.0.v20160908</jetty.websocket.version>
<thoughtworks.version>1.4.10</thoughtworks.version>
+ <qos.logback.version>1.2.3</qos.logback.version>
<snapshotNexusPath>/content/repositories/snapshots/</snapshotNexusPath>
<releaseNexusPath>/content/repositories/releases/</releaseNexusPath>
<stagingNexusPath>/content/repositories/staging/</stagingNexusPath>