<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
- <version>2.3.0</version>
+ <version>2.5.0</version>
</dependency>
<dependency>
- <groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-library</artifactId>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-dbcp2</artifactId>
+ <version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<archive>
<manifest>
<addClasspath>true</addClasspath>
- <mainClass>org.onap.dmaap.datarouter.provisioning.Main</mainClass>
+ <mainClass>org.onap.dmaap.datarouter.provisioning.ProvRunner</mainClass>
</manifest>
</archive>
</configuration>
* permit/deny decision for the request and (after R1) supplemental information related to the response in the form\r
* of advice and obligations.\r
*/\r
- public AuthorizationResponse decide(HttpServletRequest request);\r
+ AuthorizationResponse decide(HttpServletRequest request);\r
\r
/**\r
* Determine if the API request carried in the <code>request</code> parameter,with additional attributes provided in\r
* permit/deny decision for the request and (after R1) supplemental information related to the response\r
* in the form of advice and obligations.\r
*/\r
- public AuthorizationResponse decide(HttpServletRequest request, Map<String,String> additionalAttrs);\r
+ AuthorizationResponse decide(HttpServletRequest request, Map<String,String> additionalAttrs);\r
}\r
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.DB;
import org.onap.dmaap.datarouter.provisioning.utils.PasswordProcessor;
+import org.onap.dmaap.datarouter.provisioning.utils.Poker;
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;
+import org.onap.dmaap.datarouter.provisioning.utils.SynchronizerTask;
import org.onap.dmaap.datarouter.provisioning.utils.ThrottleFilter;
import org.slf4j.MDC;
public static final String SUBFULL_CONTENT_TYPE = "application/vnd.dmaap-dr.subscription-full; version=2.0";
static final String SUBLIST_CONTENT_TYPE = "application/vnd.dmaap-dr.subscription-list; version=1.0";
-
//Adding groups functionality, ...1610
static final String GROUP_BASECONTENT_TYPE = "application/vnd.dmaap-dr.group";
static final String GROUP_CONTENT_TYPE = "application/vnd.dmaap-dr.group; version=2.0";
static final String GROUPFULL_CONTENT_TYPE = "application/vnd.dmaap-dr.group-full; version=2.0";
public static final String GROUPLIST_CONTENT_TYPE = "application/vnd.dmaap-dr.fegrouped-list; version=1.0";
-
public static final String LOGLIST_CONTENT_TYPE = "application/vnd.dmaap-dr.log-list; version=1.0";
public static final String PROVFULL_CONTENT_TYPE1 = "application/vnd.dmaap-dr.provfeed-full; version=1.0";
public static final String PROVFULL_CONTENT_TYPE2 = "application/vnd.dmaap-dr.provfeed-full; version=2.0";
public static final String CERT_ATTRIBUTE = "javax.servlet.request.X509Certificate";
static final String DB_PROBLEM_MSG = "There has been a problem with the DB. It is suggested you "
- + "try the operation again.";
+ + "try the operation again.";
private static final int DEFAULT_MAX_FEEDS = 10000;
private static final int DEFAULT_MAX_SUBS = 100000;
public static final String API = "/api/";
static final String LOGS = "/logs/";
- static final String TEXT_CT = "text/plain";
+ public static final String TEXT_CT = "text/plain";
static final String INGRESS = "/ingress/";
static final String EGRESS = "/egress/";
static final String NETWORK = "/network/";
static final String END_TIME = "end_time";
static final String REASON_SQL = "reasonSQL";
-
/**
* A boolean to trigger one time "provisioning changed" event on startup.
*/
private InetAddress loopback;
//DMAAP-597 (Tech Dept) REST request source IP auth relaxation to accommodate OOM kubernetes deploy
- private static String isAddressAuthEnabled = (new DB()).getProperties()
- .getProperty("org.onap.dmaap.datarouter.provserver.isaddressauthenabled", "false");
+ private static String isAddressAuthEnabled = ProvRunner.getProvProperties()
+ .getProperty("org.onap.dmaap.datarouter.provserver.isaddressauthenabled", "false");
- static String isCadiEnabled = (new DB()).getProperties()
- .getProperty("org.onap.dmaap.datarouter.provserver.cadi.enabled", "false");
+ static String isCadiEnabled = ProvRunner.getProvProperties()
+ .getProperty("org.onap.dmaap.datarouter.provserver.cadi.enabled", "false");
/**
* Initialize data common to all the provisioning server servlets.
*/
protected BaseServlet() {
+ setUpFields();
+ if (authz == null) {
+ authz = new ProvAuthorizer(this);
+ }
+ String name = this.getClass().getName();
+ intlogger.info("PROV0002 Servlet " + name + " started.");
+ }
+
+ private static void setUpFields() {
if (eventlogger == null) {
eventlogger = EELFManager.getInstance().getLogger("EventLog");
}
if (intlogger == null) {
intlogger = EELFManager.getInstance().getLogger("InternalLog");
}
- if (authz == null) {
- authz = new ProvAuthorizer(this);
- }
if (startmsgFlag) {
startmsgFlag = false;
provisioningParametersChanged();
if (synctask == null) {
synctask = SynchronizerTask.getSynchronizer();
}
- String name = this.getClass().getName();
- intlogger.info("PROV0002 Servlet " + name + " started.");
}
@Override
}
private static void processPassword(String maskKey, boolean action, JSONArray endpointIds, int index,
- String password) {
+ String password) {
try {
if (action) {
endpointIds.getJSONObject(index).put(maskKey, PasswordProcessor.encrypt(password));
* Something has changed in the provisioning data. Start the timers that will cause the pre-packaged JSON string to
* be regenerated, and cause nodes and the other provisioning server to be notified.
*/
- static void provisioningDataChanged() {
+ public static void provisioningDataChanged() {
long now = System.currentTimeMillis();
Poker pkr = Poker.getPoker();
pkr.setTimers(now + (pokeTimer1 * 1000L), now + (pokeTimer2 * 1000L));
/**
* Something in the parameters has changed, reload all parameters from the DB.
*/
- static void provisioningParametersChanged() {
+ public static void provisioningParametersChanged() {
Map<String, String> map = Parameters.getParameters();
requireSecure = getBoolean(map, Parameters.PROV_REQUIRE_SECURE);
requireCert = getBoolean(map, Parameters.PROV_REQUIRE_CERT);
return provName;
}
- static String getActiveProvName() {
+ public static String getActiveProvName() {
return activeProvName;
}
*/
protected boolean doInsert(Insertable bean) {
boolean rv;
- DB db = new DB();
- Connection conn = null;
- try {
- conn = db.getConnection();
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
rv = bean.doInsert(conn);
} catch (SQLException e) {
rv = false;
intlogger.warn("PROV0005 doInsert: " + e.getMessage(), e);
- } finally {
- if (conn != null) {
- db.release(conn);
- }
}
return rv;
}
*/
protected boolean doUpdate(Updateable bean) {
boolean rv;
- DB db = new DB();
- Connection conn = null;
- try {
- conn = db.getConnection();
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
rv = bean.doUpdate(conn);
} catch (SQLException e) {
rv = false;
intlogger.warn("PROV0006 doUpdate: " + e.getMessage(), e);
- } finally {
- if (conn != null) {
- db.release(conn);
- }
}
return rv;
}
*/
protected boolean doDelete(Deleteable bean) {
boolean rv;
- DB db = new DB();
- Connection conn = null;
- try {
- conn = db.getConnection();
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
rv = bean.doDelete(conn);
} catch (SQLException e) {
rv = false;
intlogger.warn("PROV0007 doDelete: " + e.getMessage(), e);
- } finally {
- if (conn != null) {
- db.release(conn);
- }
}
return rv;
}
*/
String getFeedPermission(String aafInstance, String userAction) {
try {
- Properties props = (new DB()).getProperties();
+ Properties props = ProvRunner.getProvProperties();
String type = props.getProperty(AAF_CADI_FEED_TYPE, AAF_CADI_FEED);
String action;
switch (userAction) {
*/
String getSubscriberPermission(String aafInstance, String userAction) {
try {
- Properties props = (new DB()).getProperties();
+ Properties props = ProvRunner.getProvProperties();
String type = props.getProperty(AAF_CADI_SUB_TYPE, AAF_CADI_SUB);
String action;
switch (userAction) {
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
+import org.onap.dmaap.datarouter.provisioning.utils.Poker;
+import org.onap.dmaap.datarouter.provisioning.utils.SynchronizerTask;
import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord;
import org.onap.dmaap.datarouter.provisioning.beans.LogRecord;
import org.onap.dmaap.datarouter.provisioning.beans.Parameters;
import org.onap.dmaap.datarouter.provisioning.eelf.EelfMsgs;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
import org.onap.dmaap.datarouter.provisioning.utils.LogfileLoader;
import org.onap.dmaap.datarouter.provisioning.utils.RLEBitSet;
* <td class="colFirst">/internal/route/*</td>
* <td class="colOne">*</td>
* <td class="colLast">URLs under this path are handled via the
- * {@link org.onap.dmaap.datarouter.provisioning.RouteServlet}</td>
+ * {@link RouteServlet}</td>
* </tr>
* </table>
* </div>
eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID,
req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");
String path = req.getPathInfo();
- Properties props = (new DB()).getProperties();
+ Properties props = ProvRunner.getProvProperties();
if ("/halt".equals(path) && !req.isSecure()) {
// request to halt the server - can ONLY come from localhost
String remote = req.getRemoteAddr();
if (remote.equals(props.getProperty("org.onap.dmaap.datarouter.provserver.localhost"))) {
intlogger.info("PROV0009 Request to HALT received.");
resp.setStatus(HttpServletResponse.SC_OK);
- Main.shutdown();
+ ProvRunner.shutdown();
} else {
intlogger.info("PROV0010 Disallowed request to HALT received from " + remote);
resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
String logdir = props.getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir");
String logfile = path.substring(6);
if (logdir != null && logfile != null && logfile.indexOf('/') < 0) {
- File log = new File(logdir + "/" + logfile);
+ File log = new File(logdir + File.separator + logfile);
if (log.exists() && log.isFile()) {
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType(TEXT_CT);
return;
}
String spooldir =
- (new DB()).getProperties().getProperty("org.onap.dmaap.datarouter.provserver.spooldir");
+ ProvRunner.getProvProperties().getProperty("org.onap.dmaap.datarouter.provserver.spooldir");
String spoolname = String.format("%d-%d-", System.currentTimeMillis(), Thread.currentThread().getId());
synchronized (lock) {
// perhaps unnecessary, but it helps make the name unique
} catch (Exception e) {
intlogger.error("PROV0137 InternalServlet.doPost: " + e.getMessage(), e);
}
- if (((avail * 100) / total) < 5) {
+ if (total != 0 && ((avail * 100) / total) < 5) {
elr.setResult(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
eventlogger.error(elr.toString());
private JSONArray generateLogfileList() {
JSONArray ja = new JSONArray();
- Properties prop = (new DB()).getProperties();
+ Properties prop = ProvRunner.getProvProperties();
String str = prop.getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir");
if (str != null) {
String[] dirs = str.split(",");
import com.att.eelf.configuration.EELFManager;\r
import java.io.IOException;\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.text.ParseException;\r
import java.text.SimpleDateFormat;\r
import java.util.Date;\r
import javax.servlet.ServletOutputStream;\r
import javax.servlet.http.HttpServletRequest;\r
import javax.servlet.http.HttpServletResponse;\r
-\r
import org.onap.dmaap.datarouter.provisioning.beans.DeliveryRecord;\r
import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord;\r
import org.onap.dmaap.datarouter.provisioning.beans.ExpiryRecord;\r
import org.onap.dmaap.datarouter.provisioning.beans.PublishRecord;\r
import org.onap.dmaap.datarouter.provisioning.beans.Subscription;\r
import org.onap.dmaap.datarouter.provisioning.eelf.EelfMsgs;\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
import org.onap.dmaap.datarouter.provisioning.utils.LOGJSONObject;\r
-\r
-\r
-\r
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
\r
\r
/**\r
\r
private final boolean isfeedlog;\r
\r
- public abstract class RowHandler {\r
+ public abstract static class RowHandler {\r
private final ServletOutputStream out;\r
private final String[] fields;\r
private boolean firstrow;\r
* @param fieldparam String field\r
* @param bool boolean\r
*/\r
- public RowHandler(ServletOutputStream out, String fieldparam, boolean bool) {\r
+ RowHandler(ServletOutputStream out, String fieldparam, boolean bool) {\r
this.out = out;\r
this.firstrow = bool;\r
this.fields = (fieldparam != null) ? fieldparam.split(":") : null;\r
* Handling row from DB.\r
* @param rs DB Resultset\r
*/\r
- public void handleRow(ResultSet rs) {\r
+ void handleRow(ResultSet rs) {\r
try {\r
LOGJSONable js = buildJSONable(rs);\r
LOGJSONObject jo = js.asJSONObject();\r
public abstract LOGJSONable buildJSONable(ResultSet rs) throws SQLException;\r
}\r
\r
- public class PublishRecordRowHandler extends RowHandler {\r
- public PublishRecordRowHandler(ServletOutputStream out, String fields, boolean bool) {\r
+ public static class PublishRecordRowHandler extends RowHandler {\r
+ PublishRecordRowHandler(ServletOutputStream out, String fields, boolean bool) {\r
super(out, fields, bool);\r
}\r
\r
}\r
}\r
\r
- public class DeliveryRecordRowHandler extends RowHandler {\r
- public DeliveryRecordRowHandler(ServletOutputStream out, String fields, boolean bool) {\r
+ public static class DeliveryRecordRowHandler extends RowHandler {\r
+ DeliveryRecordRowHandler(ServletOutputStream out, String fields, boolean bool) {\r
super(out, fields, bool);\r
}\r
\r
}\r
}\r
\r
- public class ExpiryRecordRowHandler extends RowHandler {\r
- public ExpiryRecordRowHandler(ServletOutputStream out, String fields, boolean bool) {\r
+ public static class ExpiryRecordRowHandler extends RowHandler {\r
+ ExpiryRecordRowHandler(ServletOutputStream out, String fields, boolean bool) {\r
super(out, fields, bool);\r
}\r
\r
\r
/**\r
* This class must be created from either a {@link FeedLogServlet} or a {@link SubLogServlet}.\r
- * @param isFeedLog boolean to handle those places where a feedlog request is different from\r
- * a sublog request\r
+ * @param isFeedLog boolean to handle those places where a feedlog request is different from a sublog request\r
*/\r
- protected LogServlet(boolean isFeedLog) {\r
+ LogServlet(boolean isFeedLog) {\r
this.isfeedlog = isFeedLog;\r
}\r
\r
eelfLogger.info(EelfMsgs.ENTRY);\r
try {\r
eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID,\r
- req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");\r
+ req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");\r
String message = "DELETE not allowed for the logURL.";\r
EventLogRecord elr = new EventLogRecord(req);\r
elr.setMessage(message);\r
eelfLogger.info(EelfMsgs.ENTRY);\r
try {\r
eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID,\r
- req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");\r
+ req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");\r
int id = getIdFromPath(req);\r
if (id < 0) {\r
sendResponseError(resp, HttpServletResponse.SC_BAD_REQUEST,\r
- "Missing or bad feed/subscription number.", eventlogger);\r
+ "Missing or bad feed/subscription number.", eventlogger);\r
return;\r
}\r
Map<String, String> map = buildMapFromRequest(req);\r
if (map.get("err") != null) {\r
sendResponseError(resp, HttpServletResponse.SC_BAD_REQUEST,\r
- "Invalid arguments: " + map.get("err"), eventlogger);\r
+ "Invalid arguments: " + map.get("err"), eventlogger);\r
return;\r
}\r
// check Accept: header??\r
-\r
resp.setStatus(HttpServletResponse.SC_OK);\r
resp.setContentType(LOGLIST_CONTENT_TYPE);\r
-\r
try (ServletOutputStream out = resp.getOutputStream()) {\r
final String fields = req.getParameter("fields");\r
-\r
out.print("[");\r
if (isfeedlog) {\r
// Handle /feedlog/feedid request\r
boolean firstrow = true;\r
-\r
// 1. Collect publish records for this feed\r
RowHandler rh = new PublishRecordRowHandler(out, fields, firstrow);\r
getPublishRecordsForFeed(id, rh, map);\r
firstrow = rh.firstrow;\r
-\r
// 2. Collect delivery records for subscriptions to this feed\r
rh = new DeliveryRecordRowHandler(out, fields, firstrow);\r
getDeliveryRecordsForFeed(id, rh, map);\r
firstrow = rh.firstrow;\r
-\r
// 3. Collect expiry records for subscriptions to this feed\r
rh = new ExpiryRecordRowHandler(out, fields, firstrow);\r
getExpiryRecordsForFeed(id, rh, map);\r
// 1. Collect publish records for the feed this subscription feeds\r
RowHandler rh = new PublishRecordRowHandler(out, fields, true);\r
getPublishRecordsForFeed(sub.getFeedid(), rh, map);\r
-\r
// 2. Collect delivery records for this subscription\r
rh = new DeliveryRecordRowHandler(out, fields, rh.firstrow);\r
getDeliveryRecordsForSubscription(id, rh, map);\r
-\r
// 3. Collect expiry records for this subscription\r
rh = new ExpiryRecordRowHandler(out, fields, rh.firstrow);\r
getExpiryRecordsForSubscription(id, rh, map);\r
eelfLogger.info(EelfMsgs.ENTRY);\r
try {\r
eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID,\r
- req.getHeader(BEHALF_HEADER),getIdFromPath(req) + "");\r
+ req.getHeader(BEHALF_HEADER),getIdFromPath(req) + "");\r
String message = "PUT not allowed for the logURL.";\r
EventLogRecord elr = new EventLogRecord(req);\r
elr.setMessage(message);\r
str = req.getParameter("expiryReason");\r
if (str != null) {\r
map.put("type", "exp");\r
- if ("notRetryable".equals(str)) {\r
- map.put(REASON_SQL, " AND REASON = 'notRetryable'");\r
- } else if ("retriesExhausted".equals(str)) {\r
- map.put(REASON_SQL, " AND REASON = 'retriesExhausted'");\r
- } else if ("diskFull".equals(str)) {\r
- map.put(REASON_SQL, " AND REASON = 'diskFull'");\r
- } else if ("other".equals(str)) {\r
- map.put(REASON_SQL, " AND REASON = 'other'");\r
- } else {\r
- map.put("err", "bad expiryReason");\r
- return map;\r
+ switch (str) {\r
+ case "notRetryable":\r
+ map.put(REASON_SQL, " AND REASON = 'notRetryable'");\r
+ break;\r
+ case "retriesExhausted":\r
+ map.put(REASON_SQL, " AND REASON = 'retriesExhausted'");\r
+ break;\r
+ case "diskFull":\r
+ map.put(REASON_SQL, " AND REASON = 'diskFull'");\r
+ break;\r
+ case "other":\r
+ map.put(REASON_SQL, " AND REASON = 'other'");\r
+ break;\r
+ default:\r
+ map.put("err", "bad expiryReason");\r
+ return map;\r
}\r
}\r
\r
private void getRecordsForSQL(String sql, RowHandler rh) {\r
intlogger.debug(sql);\r
long start = System.currentTimeMillis();\r
- DB db = new DB();\r
- Connection conn = null;\r
- try {\r
- conn = db.getConnection();\r
- try (Statement stmt = conn.createStatement()) {\r
- try (ResultSet rs = stmt.executeQuery(sql)) {\r
- while (rs.next()) {\r
- rh.handleRow(rs);\r
- }\r
- }\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(sql);\r
+ ResultSet rs = ps.executeQuery()) {\r
+ while (rs.next()) {\r
+ rh.handleRow(rs);\r
}\r
} catch (SQLException sqlException) {\r
intlogger.info("Failed to get Records. Exception = " + sqlException.getMessage(),sqlException);\r
- } finally {\r
- if (conn != null) {\r
- db.release(conn);\r
- }\r
}\r
intlogger.debug("Time: " + (System.currentTimeMillis() - start) + " ms");\r
}\r
package org.onap.dmaap.datarouter.provisioning;
import static java.lang.System.exit;
+import static java.lang.System.getProperty;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import java.io.File;
+import java.io.FileInputStream;
import java.io.IOException;
import java.security.Security;
import java.util.EnumSet;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.onap.dmaap.datarouter.provisioning.utils.AafPropsUtils;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
import org.onap.dmaap.datarouter.provisioning.utils.DRProvCadiFilter;
import org.onap.dmaap.datarouter.provisioning.utils.LogfileLoader;
+import org.onap.dmaap.datarouter.provisioning.utils.Poker;
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;
import org.onap.dmaap.datarouter.provisioning.utils.PurgeLogDirTask;
+import org.onap.dmaap.datarouter.provisioning.utils.SynchronizerTask;
import org.onap.dmaap.datarouter.provisioning.utils.ThrottleFilter;
/**
* @author Robert Eby
* @version $Id: Main.java,v 1.12 2014/03/12 19:45:41 eby Exp $
*/
-public class Main {
+public class ProvRunner {
public static final EELFLogger intlogger = EELFManager.getInstance()
.getLogger("org.onap.dmaap.datarouter.provisioning.internal");
* The one and only {@link Server} instance in this JVM.
*/
private static Server server;
- static AafPropsUtils aafPropsUtils;
+ private static AafPropsUtils aafPropsUtils;
+ private static Properties provProperties;
/**
* Starts the Data Router Provisioning server.
* @throws Exception if Jetty has a problem starting
*/
public static void main(String[] args) throws Exception {
- Security.setProperty("networkaddress.cache.ttl", "4");
+
+ intlogger.info("PROV0000 **** Data Router Provisioning Server starting....");
+
// Check DB is accessible and contains the expected tables
- if (!checkDatabase()) {
+ if (!ProvDbUtils.getInstance().initProvDB()) {
intlogger.error("Data Router Provisioning database init failure. Exiting.");
exit(1);
}
- intlogger.info("PROV0000 **** Data Router Provisioning Server starting....");
+ int httpPort = Integer.parseInt(
+ getProvProperties().getProperty("org.onap.dmaap.datarouter.provserver.http.port", "8080"));
+ final int httpsPort = Integer.parseInt(
+ getProvProperties().getProperty("org.onap.dmaap.datarouter.provserver.https.port", "8443"));
Security.setProperty("networkaddress.cache.ttl", "4");
- Properties provProperties = (new DB()).getProperties();
- int httpPort = Integer.parseInt(provProperties
- .getProperty("org.onap.dmaap.datarouter.provserver.http.port", "8080"));
- final int httpsPort = Integer.parseInt(provProperties
- .getProperty("org.onap.dmaap.datarouter.provserver.https.port", "8443"));
-
// Server's thread pool
QueuedThreadPool queuedThreadPool = new QueuedThreadPool();
queuedThreadPool.setMinThreads(10);
// Request log configuration
NCSARequestLog ncsaRequestLog = new NCSARequestLog();
- ncsaRequestLog.setFilename(provProperties
+ ncsaRequestLog.setFilename(getProvProperties()
.getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir")
+ "/request.log.yyyy_mm_dd");
ncsaRequestLog.setFilenameDateFormat("yyyyMMdd");
httpConfiguration.setSendDateHeader(false);
try {
- AafPropsUtils.init(new File(provProperties.getProperty(
+ AafPropsUtils.init(new File(getProvProperties().getProperty(
"org.onap.dmaap.datarouter.provserver.aafprops.path",
"/opt/app/osaaf/local/org.onap.dmaap-dr.props")));
} catch (IOException e) {
// SSL Context
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStoreType(AafPropsUtils.KEYSTORE_TYPE_PROPERTY);
- sslContextFactory.setKeyStorePath(aafPropsUtils.getKeystorePathProperty());
- sslContextFactory.setKeyStorePassword(aafPropsUtils.getKeystorePassProperty());
- sslContextFactory.setKeyManagerPassword(aafPropsUtils.getKeystorePassProperty());
+ sslContextFactory.setKeyStorePath(getAafPropsUtils().getKeystorePathProperty());
+ sslContextFactory.setKeyStorePassword(getAafPropsUtils().getKeystorePassProperty());
+ sslContextFactory.setKeyManagerPassword(getAafPropsUtils().getKeystorePassProperty());
- String truststorePathProperty = aafPropsUtils.getTruststorePathProperty();
+ String truststorePathProperty = getAafPropsUtils().getTruststorePathProperty();
if (truststorePathProperty != null && truststorePathProperty.length() > 0) {
intlogger.info("@@ TS -> " + truststorePathProperty);
sslContextFactory.setTrustStoreType(AafPropsUtils.TRUESTSTORE_TYPE_PROPERTY);
sslContextFactory.setTrustStorePath(truststorePathProperty);
- sslContextFactory.setTrustStorePassword(aafPropsUtils.getTruststorePassProperty());
+ sslContextFactory.setTrustStorePassword(getAafPropsUtils().getTruststorePassProperty());
} else {
sslContextFactory.setTrustStorePath(AafPropsUtils.DEFAULT_TRUSTSTORE);
sslContextFactory.setTrustStorePassword("changeit");
"SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"
);
sslContextFactory.addExcludeProtocols("SSLv3");
- sslContextFactory.setIncludeProtocols(provProperties.getProperty(
+ sslContextFactory.setIncludeProtocols(getProvProperties().getProperty(
"org.onap.dmaap.datarouter.provserver.https.include.protocols",
"TLSv1.1|TLSv1.2").trim().split("\\|"));
"/publish/*", EnumSet.of(DispatcherType.REQUEST));
//CADI Filter activation check
- if (Boolean.parseBoolean(provProperties.getProperty(
+ if (Boolean.parseBoolean(getProvProperties().getProperty(
"org.onap.dmaap.datarouter.provserver.cadi.enabled", "false"))) {
- servletContextHandler.addFilter(new FilterHolder(new DRProvCadiFilter(true, aafPropsUtils.getPropAccess())),
+ servletContextHandler.addFilter(new FilterHolder(new DRProvCadiFilter(true, getAafPropsUtils().getPropAccess())),
"/*", EnumSet.of(DispatcherType.REQUEST));
intlogger.info("PROV0001 AAF CADI Auth enabled for ");
}
intlogger.info("PROV0001 **** AT&T Data Router Provisioning Server halted.");
}
- private static boolean checkDatabase() {
- DB db = new DB();
- return db.runRetroFits();
- }
-
/**
* Stop the Jetty server.
*/
- static void shutdown() {
+ public static void shutdown() {
new Thread(() -> {
try {
server.stop();
}
});
}
+
+ public static Properties getProvProperties() {
+ if (provProperties == null) {
+ try {
+ provProperties = new Properties();
+ provProperties.load(new FileInputStream(getProperty(
+ "org.onap.dmaap.datarouter.provserver.properties",
+ "/opt/app/datartr/etc/provserver.properties")));
+ } catch (IOException e) {
+ intlogger.error("Failed to load PROV properties: " + e.getMessage(), e);
+ exit(1);
+ }
+ }
+ return provProperties;
+ }
+
+ public static AafPropsUtils getAafPropsUtils() {
+ return aafPropsUtils;
+ }
}
import java.security.KeyStoreException;
import java.util.Collections;
import java.util.List;
-import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.onap.dmaap.datarouter.provisioning.utils.AafPropsUtils;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
+import org.onap.dmaap.datarouter.provisioning.utils.SynchronizerTask;
import org.onap.dmaap.datarouter.provisioning.utils.URLUtilities;
/**
try {
// Set up keystore
String type = AafPropsUtils.KEYSTORE_TYPE_PROPERTY;
- String store = Main.aafPropsUtils.getKeystorePathProperty();
- String pass = Main.aafPropsUtils.getKeystorePassProperty();
+ String store = ProvRunner.getAafPropsUtils().getKeystorePathProperty();
+ String pass = ProvRunner.getAafPropsUtils().getKeystorePassProperty();
KeyStore keyStore = readStore(store, pass, type);
// Set up truststore
- store = Main.aafPropsUtils.getTruststorePathProperty();
- pass = Main.aafPropsUtils.getTruststorePassProperty();
+ store = ProvRunner.getAafPropsUtils().getTruststorePathProperty();
+ pass = ProvRunner.getAafPropsUtils().getTruststorePassProperty();
if (store == null || store.length() == 0) {
store = AafPropsUtils.DEFAULT_TRUSTSTORE;
pass = "changeit";
// We are connecting with the node name, but the certificate will have the CNAME
// So we need to accept a non-matching certificate name
SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore,
- Main.aafPropsUtils.getKeystorePassProperty(), trustStore);
+ ProvRunner.getAafPropsUtils().getKeystorePassProperty(), trustStore);
socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
sch = new Scheme("https", 443, socketFactory);
inited = true;
import org.json.JSONException;\r
import org.json.JSONObject;\r
import org.json.JSONTokener;\r
+import org.onap.dmaap.datarouter.provisioning.utils.Poker;\r
import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord;\r
import org.onap.dmaap.datarouter.provisioning.beans.IngressRoute;\r
import org.onap.dmaap.datarouter.provisioning.eelf.EelfMsgs;\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
\r
/**\r
* This servlet handles redirects for the <publishURL> on the provisioning server, which is generated by the\r
} else {\r
// Generate new URL\r
String nextnode = getRedirectNode(feedid, req);\r
- nextnode = nextnode + ":" + DB.getHttpsPort();\r
+ nextnode = nextnode + ":" + ProvRunner.getProvProperties().getProperty(\r
+ "org.onap.dmaap.datarouter.provserver.https.port", "8443");\r
String newurl = "https://" + nextnode + "/publish" + req.getPathInfo();\r
String qs = req.getQueryString();\r
if (qs != null) {\r
import javax.servlet.http.HttpServletResponse;\r
import org.json.JSONException;\r
import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord;\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
import org.onap.dmaap.datarouter.provisioning.utils.LOGJSONObject;\r
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
\r
\r
/**\r
private static final String SQL_TYPE_PUB = ") and c.FEEDID=e.FEEDID AND c.TYPE='PUB') AS FILES_PUBLISHED,";\r
private static final String SQL_SELECT_SUM = "(SELECT SUM(content_length) FROM LOG_RECORDS AS c WHERE c.FEEDID in(";\r
private static final String SQL_PUBLISH_LENGTH = ") and c.FEEDID=e.FEEDID AND c.TYPE='PUB') AS PUBLISH_LENGTH, COUNT(e.EVENT_TIME) as FILES_DELIVERED,";\r
- private static final String SQL_SUBSCRIBER_URL = " sum(m.content_length) as DELIVERED_LENGTH,SUBSTRING_INDEX(e.REQURI,'/',+3) as SUBSCRIBER_URL,";\r
+ private static final String SQL_SUBSCRIBER_URL = " sum(m.content_length) as DELIVERED_LENGTH, SUBSTRING_INDEX(e.REQURI,'/',+3) as SUBSCRIBER_URL,";\r
private static final String SQL_SUB_ID = " e.DELIVERY_SUBID as SUBID, ";\r
private static final String SQL_DELIVERY_TIME = " e.EVENT_TIME AS PUBLISH_TIME, m.EVENT_TIME AS DELIVERY_TIME, ";\r
private static final String SQL_AVERAGE_DELAY = " AVG(e.EVENT_TIME - m.EVENT_TIME)/1000 as AverageDelay FROM LOG_RECORDS";\r
Map<String, String> map = buildMapFromRequest(req);\r
if (map.get("err") != null) {\r
sendResponseError(resp, HttpServletResponse.SC_BAD_REQUEST,\r
- "Invalid arguments: " + map.get("err"), eventlogger);\r
+ "Invalid arguments: " + map.get("err"), eventlogger);\r
return;\r
}\r
// check Accept: header??\r
try {\r
groupid1 = this.getFeedIdsByGroupId(Integer.parseInt(req.getParameter(GROUPID)));\r
map.put(FEEDIDS, groupid1.toString());\r
- } catch (NumberFormatException | SQLException e) {\r
+ } catch (NumberFormatException e) {\r
eventlogger.error("PROV0172 StatisticsServlet.doGet: " + e.getMessage(), e);\r
}\r
}\r
groupid1.append(",");\r
groupid1.append(req.getParameter(FEEDID).replace("|", ","));\r
map.put(FEEDIDS, groupid1.toString());\r
- } catch (NumberFormatException | SQLException e) {\r
+ } catch (NumberFormatException e) {\r
eventlogger.error("PROV0173 StatisticsServlet.doGet: " + e.getMessage(), e);\r
}\r
}\r
* @throws IOException input/output exception\r
* @throws SQLException SQL exception\r
*/\r
- public void rsToCSV(ResultSet rs, ServletOutputStream out) throws IOException, SQLException {\r
+ private void rsToCSV(ResultSet rs, ServletOutputStream out) throws IOException, SQLException {\r
String header = "FEEDNAME,FEEDID,FILES_PUBLISHED,PUBLISH_LENGTH, FILES_DELIVERED, "\r
+ "DELIVERED_LENGTH, SUBSCRIBER_URL, SUBID, PUBLISH_TIME,DELIVERY_TIME, AverageDelay\n";\r
out.write(header.getBytes());\r
/**\r
* getFeedIdsByGroupId - Getting FEEDID's by GROUP ID.\r
*\r
- * @throws SQLException Query SQLException.\r
+ * @param groupIds Integer ref of Group\r
*/\r
- private StringBuilder getFeedIdsByGroupId(int groupIds) throws SQLException {\r
- DB db = null;\r
- Connection conn = null;\r
- ResultSet resultSet = null;\r
- String sqlGoupid = null;\r
+ private StringBuilder getFeedIdsByGroupId(int groupIds) {\r
StringBuilder feedIds = new StringBuilder();\r
- try {\r
- db = new DB();\r
- conn = db.getConnection();\r
- sqlGoupid = " SELECT FEEDID from FEEDS WHERE GROUPID = ?";\r
- try (PreparedStatement prepareStatement = conn.prepareStatement(sqlGoupid)) {\r
- prepareStatement.setInt(1, groupIds);\r
- resultSet = prepareStatement.executeQuery();\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement prepareStatement = conn.prepareStatement(\r
+ " SELECT FEEDID from FEEDS WHERE GROUPID = ?")) {\r
+ prepareStatement.setInt(1, groupIds);\r
+ try (ResultSet resultSet = prepareStatement.executeQuery()) {\r
while (resultSet.next()) {\r
feedIds.append(resultSet.getInt(FEEDID));\r
feedIds.append(",");\r
}\r
- feedIds.deleteCharAt(feedIds.length() - 1);\r
- eventlogger.info("PROV0177 StatisticsServlet.getFeedIdsByGroupId: feedIds = " + feedIds.toString());\r
}\r
+ feedIds.deleteCharAt(feedIds.length() - 1);\r
+ eventlogger.info("PROV0177 StatisticsServlet.getFeedIdsByGroupId: feedIds = " + feedIds.toString());\r
} catch (SQLException e) {\r
eventlogger.error("PROV0175 StatisticsServlet.getFeedIdsByGroupId: " + e.getMessage(), e);\r
- } finally {\r
- try {\r
- if (resultSet != null) {\r
- resultSet.close();\r
- }\r
- if (conn != null) {\r
- db.release(conn);\r
- }\r
- } catch (Exception e) {\r
- eventlogger.error("PROV0176 StatisticsServlet.getFeedIdsByGroupId: " + e.getMessage(), e);\r
- }\r
}\r
return feedIds;\r
}\r
if (endTime == null && startTime == null) {\r
\r
sql = SQL_SELECT_NAME + feedids + SQL_FEED_ID + SQL_SELECT_COUNT + feedids + SQL_TYPE_PUB\r
- + SQL_SELECT_SUM\r
- + feedids + SQL_PUBLISH_LENGTH\r
+ + SQL_SELECT_SUM\r
+ + feedids + SQL_PUBLISH_LENGTH\r
+ SQL_SUBSCRIBER_URL + SQL_SUB_ID + SQL_DELIVERY_TIME + SQL_AVERAGE_DELAY + SQL_JOIN_RECORDS\r
- + feedids + ") " + subid\r
- + SQL_STATUS_204 + SQL_GROUP_SUB_ID;\r
+ + feedids + ") " + subid\r
+ + SQL_STATUS_204 + SQL_GROUP_SUB_ID;\r
\r
return sql;\r
} else if (startTime != null && endTime == null) {\r
long compareTime = currentTimeInMilli - inputTimeInMilli;\r
\r
sql = SQL_SELECT_NAME + feedids + SQL_FEED_ID + SQL_SELECT_COUNT + feedids + SQL_TYPE_PUB\r
- + SQL_SELECT_SUM\r
- + feedids + SQL_PUBLISH_LENGTH\r
+ + SQL_SELECT_SUM\r
+ + feedids + SQL_PUBLISH_LENGTH\r
+ SQL_SUBSCRIBER_URL + SQL_SUB_ID + SQL_DELIVERY_TIME + SQL_AVERAGE_DELAY + SQL_JOIN_RECORDS\r
- + feedids + ") " + subid\r
+ + feedids + ") " + subid\r
+ SQL_STATUS_204 + " and e.event_time>=" + compareTime + SQL_GROUP_SUB_ID;\r
return sql;\r
\r
long endInMillis = endDate.getTime();\r
\r
sql = SQL_SELECT_NAME + feedids + SQL_FEED_ID + SQL_SELECT_COUNT + feedids + SQL_TYPE_PUB\r
- + SQL_SELECT_SUM\r
- + feedids + SQL_PUBLISH_LENGTH + SQL_SUBSCRIBER_URL\r
- + SQL_SUB_ID + SQL_DELIVERY_TIME + SQL_AVERAGE_DELAY + SQL_JOIN_RECORDS + feedids + ")" + subid + SQL_STATUS_204\r
- +" and e.event_time between " + startInMillis + " and " + endInMillis + SQL_GROUP_SUB_ID;\r
+ + SQL_SELECT_SUM\r
+ + feedids + SQL_PUBLISH_LENGTH + SQL_SUBSCRIBER_URL\r
+ + SQL_SUB_ID + SQL_DELIVERY_TIME + SQL_AVERAGE_DELAY + SQL_JOIN_RECORDS + feedids + ")" + subid + SQL_STATUS_204\r
+ +" and e.event_time between " + startInMillis + " and " + endInMillis + SQL_GROUP_SUB_ID;\r
\r
return sql;\r
}\r
}\r
\r
private void getRecordsForSQL(Map<String, String> map, String outputType, ServletOutputStream out,\r
- HttpServletResponse resp) {\r
+ HttpServletResponse resp) {\r
try {\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
- try (Connection conn = db.getConnection()) {\r
- try (ResultSet rs = conn.prepareStatement(filterQuery).executeQuery()) {\r
- if ("csv".equals(outputType)) {\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
- rsToCSV(rs, out);\r
- } else {\r
- eventlogger.info("Generating JSON for Statistics resultset");\r
- this.rsToJson(rs, out);\r
- }\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(filterQuery);\r
+ ResultSet rs = ps.executeQuery()) {\r
+ if ("csv".equals(outputType)) {\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
+ rsToCSV(rs, out);\r
+ } else {\r
+ eventlogger.info("Generating JSON for Statistics resultset");\r
+ this.rsToJson(rs, out);\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
eventlogger.error("SQLException:" + e);\r
}\r
import org.json.JSONException;\r
import org.json.JSONObject;\r
import org.onap.dmaap.datarouter.authz.AuthorizationResponse;\r
+import org.onap.dmaap.datarouter.provisioning.utils.SynchronizerTask;\r
import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord;\r
import org.onap.dmaap.datarouter.provisioning.beans.Subscription;\r
import org.onap.dmaap.datarouter.provisioning.eelf.EelfMsgs;\r
* @param conn the JDBC Connection to use\r
* @return true if the DELETE succeeded, false otherwise\r
*/\r
- public boolean doDelete(Connection conn);\r
+ boolean doDelete(Connection conn);\r
}\r
import java.util.SortedSet;\r
import java.util.TreeSet;\r
import org.json.JSONObject;\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
\r
/**\r
* The representation of one route in the Egress Route Table.\r
*/\r
public static SortedSet<EgressRoute> getAllEgressRoutes() {\r
SortedSet<EgressRoute> set = new TreeSet<>();\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(sql)) {\r
- addEgressRouteToSet(set, rs);\r
- }\r
- } finally {\r
- db.release(conn);\r
- }\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ Statement stmt = conn.createStatement();\r
+ ResultSet rs = stmt.executeQuery("select SUBID, NODEID from EGRESS_ROUTES")) {\r
+ addEgressRouteToSet(set, rs);\r
} catch (SQLException e) {\r
intlogger.error("PROV0008 EgressRoute.getAllEgressRoutes: " + e.getMessage(), e);\r
}\r
*/\r
public static EgressRoute getEgressRoute(int sub) {\r
EgressRoute er = null;\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
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement("select NODEID from EGRESS_ROUTES where SUBID = ?")) {\r
ps.setInt(1, sub);\r
- try (ResultSet rs = ps.executeQuery()) {\r
- if (rs.next()) {\r
- int node = rs.getInt("NODEID");\r
- er = new EgressRoute(sub, node);\r
- }\r
- } finally {\r
- db.release(conn);\r
+ ResultSet rs = ps.executeQuery();\r
+ if (rs.next()) {\r
+ int node = rs.getInt("NODEID");\r
+ er = new EgressRoute(sub, node);\r
}\r
} catch (SQLException e) {\r
intlogger.error("PROV0009 EgressRoute.getEgressRoute: " + e.getMessage(), e);\r
@Override\r
public boolean doDelete(Connection conn) {\r
boolean rv = true;\r
- String sql = "delete from EGRESS_ROUTES where SUBID = ?";\r
- try (PreparedStatement ps = conn.prepareStatement(sql)) {\r
+ try (PreparedStatement ps = conn.prepareStatement("delete from EGRESS_ROUTES where SUBID = ?")) {\r
ps.setInt(1, subid);\r
ps.execute();\r
} catch (SQLException e) {\r
@Override\r
public boolean doInsert(Connection conn) {\r
boolean rv = false;\r
- String sql = "insert into EGRESS_ROUTES (SUBID, NODEID) values (?, ?)";\r
- try (PreparedStatement ps = conn.prepareStatement(sql)) {\r
- // Create the NETWORK_ROUTES row\r
+ try (PreparedStatement ps = conn.prepareStatement("insert into EGRESS_ROUTES (SUBID, NODEID) values (?, ?)")) {\r
ps.setInt(1, this.subid);\r
ps.setInt(2, this.nodeid);\r
ps.execute();\r
@Override\r
public boolean doUpdate(Connection conn) {\r
boolean rv = true;\r
- String sql = "update EGRESS_ROUTES set NODEID = ? where SUBID = ?";\r
- try (PreparedStatement ps = conn.prepareStatement(sql)) {\r
+ try (PreparedStatement ps = conn.prepareStatement("update EGRESS_ROUTES set NODEID = ? where SUBID = ?")) {\r
ps.setInt(1, nodeid);\r
ps.setInt(2, subid);\r
ps.executeUpdate();\r
import org.json.JSONArray;\r
import org.json.JSONException;\r
import org.json.JSONObject;\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
import org.onap.dmaap.datarouter.provisioning.utils.JSONUtilities;\r
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
import org.onap.dmaap.datarouter.provisioning.utils.URLUtilities;\r
\r
\r
\r
private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");\r
private static int nextFeedID = getMaxFeedID() + 1;\r
- private static final String SQLEXCEPTION = "SQLException: ";\r
private static final String FEED_ID_SQL = "FEEDID";\r
private static final String FEED_ID = "feedid";\r
private static final String DEL = "deleted";\r
* @return true if it is valid\r
*/\r
@SuppressWarnings("resource")\r
- public static boolean isFeedValid(int id) {\r
+ static boolean isFeedValid(int id) {\r
int count = 0;\r
- try {\r
- DB db = new DB();\r
- Connection conn = db.getConnection();\r
- try (PreparedStatement stmt = conn.prepareStatement("select COUNT(*) from FEEDS where FEEDID = ?")) {\r
- stmt.setInt(1, id);\r
- try (ResultSet rs = stmt.executeQuery()) {\r
- if (rs.next()) {\r
- count = rs.getInt(1);\r
- }\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(\r
+ "select COUNT(*) from FEEDS where FEEDID = ?")) {\r
+ ps.setInt(1, id);\r
+ try (ResultSet rs = ps.executeQuery()) {\r
+ if (rs.next()) {\r
+ count = rs.getInt(1);\r
}\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.warn("PROV0024 Feed.isFeedValid: " + e.getMessage(), e);\r
}\r
*/\r
public static int countActiveFeeds() {\r
int count = 0;\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource") Connection conn = db.getConnection();\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
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(\r
+ "select count(*) from FEEDS where DELETED = 0")) {\r
+ try (ResultSet rs = ps.executeQuery()) {\r
+ if (rs.next()) {\r
+ count = rs.getInt(1);\r
}\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.warn("PROV0025 Feed.countActiveFeeds: " + e.getMessage(), e);\r
}\r
*/\r
public static int getMaxFeedID() {\r
int max = 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("select MAX(feedid) from FEEDS")) {\r
- if (rs.next()) {\r
- max = rs.getInt(1);\r
- }\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(\r
+ "select MAX(feedid) from FEEDS")) {\r
+ try (ResultSet rs = ps.executeQuery()) {\r
+ if (rs.next()) {\r
+ max = rs.getInt(1);\r
}\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.warn("PROV0026 Feed.getMaxFeedID: " + e.getMessage(), e);\r
}\r
*/\r
public static Collection<Feed> getAllFeeds() {\r
Map<Integer, Feed> map = new HashMap<>();\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("select * from FEEDS")) {\r
- while (rs.next()) {\r
- Feed feed = new Feed(rs);\r
- map.put(feed.getFeedid(), feed);\r
- }\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {\r
+ try (PreparedStatement ps = conn.prepareStatement("select * from FEEDS");\r
+ ResultSet rs = ps.executeQuery()) {\r
+ while (rs.next()) {\r
+ Feed feed = new Feed(rs);\r
+ map.put(feed.getFeedid(), feed);\r
}\r
-\r
- String sql = "select * from FEED_ENDPOINT_IDS";\r
- try (ResultSet rs = stmt.executeQuery(sql)) {\r
- while (rs.next()) {\r
- int id = rs.getInt(FEED_ID_SQL);\r
- Feed feed = map.get(id);\r
- if (feed != null) {\r
- FeedEndpointID epi = new FeedEndpointID(rs);\r
- Collection<FeedEndpointID> ecoll = feed.getAuthorization().getEndpointIDS();\r
- ecoll.add(epi);\r
- }\r
+ }\r
+ try (PreparedStatement ps = conn.prepareStatement("select * from FEED_ENDPOINT_IDS");\r
+ ResultSet rs = ps.executeQuery()) {\r
+ while (rs.next()) {\r
+ int id = rs.getInt(FEED_ID_SQL);\r
+ Feed feed = map.get(id);\r
+ if (feed != null) {\r
+ FeedEndpointID epi = new FeedEndpointID(rs);\r
+ Collection<FeedEndpointID> ecoll = feed.getAuthorization().getEndpointIDS();\r
+ ecoll.add(epi);\r
}\r
}\r
-\r
- sql = "select * from FEED_ENDPOINT_ADDRS";\r
- try (ResultSet rs = stmt.executeQuery(sql)) {\r
- while (rs.next()) {\r
- int id = rs.getInt(FEED_ID_SQL);\r
- Feed feed = map.get(id);\r
- if (feed != null) {\r
- Collection<String> acoll = feed.getAuthorization().getEndpointAddrs();\r
- acoll.add(rs.getString("ADDR"));\r
- }\r
+ }\r
+ try (PreparedStatement ps = conn.prepareStatement("select * from FEED_ENDPOINT_ADDRS");\r
+ ResultSet rs = ps.executeQuery()) {\r
+ while (rs.next()) {\r
+ int id = rs.getInt(FEED_ID_SQL);\r
+ Feed feed = map.get(id);\r
+ if (feed != null) {\r
+ Collection<String> acoll = feed.getAuthorization().getEndpointAddrs();\r
+ acoll.add(rs.getString("ADDR"));\r
}\r
}\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.warn("PROV0027 Feed.getAllFeeds: " + e.getMessage(), e);\r
}\r
sql += " and PUBLISHER = ?";\r
} else if (name.equals("subs")) {\r
sql = "select distinct FEEDS.SELF_LINK from FEEDS, SUBSCRIPTIONS "\r
- + "where DELETED = 0 "\r
- + "and FEEDS.FEEDID = SUBSCRIPTIONS.FEEDID "\r
- + "and SUBSCRIPTIONS.SUBSCRIBER = ?";\r
+ + "where DELETED = 0 "\r
+ + "and FEEDS.FEEDID = SUBSCRIPTIONS.FEEDID "\r
+ + "and SUBSCRIPTIONS.SUBSCRIBER = ?";\r
}\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- try (PreparedStatement ps = conn.prepareStatement(sql)) {\r
- if (sql.indexOf('?') >= 0) {\r
- ps.setString(1, val);\r
- }\r
- try (ResultSet rs = ps.executeQuery()) {\r
- while (rs.next()) {\r
- String str = rs.getString(1);\r
- list.add(str.trim());\r
- }\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(sql)) {\r
+ if (sql.indexOf('?') >= 0) {\r
+ ps.setString(1, val);\r
+ }\r
+ try (ResultSet rs = ps.executeQuery()) {\r
+ while (rs.next()) {\r
+ String str = rs.getString(1);\r
+ list.add(str.trim());\r
}\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.warn("PROV0028 Feed.getFilteredFeedUrlList: " + e.getMessage(), e);\r
}\r
@SuppressWarnings("resource")\r
private static Feed getFeedBySQL(String sql) {\r
Feed feed = null;\r
- try {\r
- DB db = new DB();\r
- Connection conn = db.getConnection();\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {\r
try (Statement stmt = conn.createStatement()) {\r
try (ResultSet rs = stmt.executeQuery(sql)) {\r
if (rs.next()) {\r
}\r
}\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.warn("PROV0029 Feed.getFeedBySQL: " + e.getMessage(), e);\r
}\r
\r
/**\r
* Set feedid with FeedLinks.\r
- * @param feedid Feedid to set to\r
+ * @param feedid Feedid to set to\r
*/\r
public void setFeedid(int feedid) {\r
this.feedid = feedid;\r
return aafInstance;\r
}\r
\r
- public void setAafInstance(String aafInstance) {\r
- this.aafInstance = aafInstance;\r
- }\r
-\r
//new getter setters for groups- Rally:US708115 - 1610\r
public int getGroupid() {\r
return groupid;\r
}\r
\r
// New field is added - Groups feature Rally:US708102 - 1610\r
- public String getBusinessDescription() {\r
+ String getBusinessDescription() {\r
return businessDescription;\r
}\r
\r
- public void setBusinessDescription(String businessDescription) {\r
+ void setBusinessDescription(String businessDescription) {\r
this.businessDescription = businessDescription;\r
}\r
\r
return links;\r
}\r
\r
- public void setLinks(FeedLinks links) {\r
+ void setLinks(FeedLinks links) {\r
this.links = links;\r
}\r
\r
this.deleted = deleted;\r
}\r
\r
- public boolean isSuspended() {\r
+ boolean isSuspended() {\r
return suspended;\r
}\r
\r
- public void setSuspended(boolean suspended) {\r
+ void setSuspended(boolean suspended) {\r
this.suspended = suspended;\r
}\r
\r
@Override\r
public boolean doDelete(Connection conn) {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
- String sql = "delete from FEEDS where FEEDID = ?";\r
- ps = conn.prepareStatement(sql);\r
+ try (PreparedStatement ps = conn.prepareStatement("delete from FEEDS where FEEDID = ?")) {\r
ps.setInt(1, feedid);\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
if (feedid > nextFeedID) {\r
nextFeedID = feedid + 1;\r
}\r
-\r
// Create FEED_ENDPOINT_IDS rows\r
FeedAuthorization auth = getAuthorization();\r
- String sql = "insert into FEED_ENDPOINT_IDS values (?, ?, ?)";\r
- try (PreparedStatement ps2 = conn.prepareStatement(sql)) {\r
+ try (PreparedStatement ps = conn.prepareStatement("insert into FEED_ENDPOINT_IDS values (?, ?, ?)")) {\r
for (FeedEndpointID fid : auth.getEndpointIDS()) {\r
- ps2.setInt(1, feedid);\r
- ps2.setString(2, fid.getId());\r
- ps2.setString(3, fid.getPassword());\r
- ps2.executeUpdate();\r
+ ps.setInt(1, feedid);\r
+ ps.setString(2, fid.getId());\r
+ ps.setString(3, fid.getPassword());\r
+ ps.executeUpdate();\r
}\r
}\r
-\r
// Create FEED_ENDPOINT_ADDRS rows\r
- sql = "insert into FEED_ENDPOINT_ADDRS values (?, ?)";\r
- try (PreparedStatement ps2 = conn.prepareStatement(sql)) {\r
+ try (PreparedStatement ps = conn.prepareStatement("insert into FEED_ENDPOINT_ADDRS values (?, ?)")) {\r
for (String t : auth.getEndpointAddrs()) {\r
- ps2.setInt(1, feedid);\r
- ps2.setString(2, t);\r
- ps2.executeUpdate();\r
+ ps.setInt(1, feedid);\r
+ ps.setString(2, t);\r
+ ps.executeUpdate();\r
}\r
}\r
-\r
// Finally, create the FEEDS row\r
- sql = "insert into FEEDS (FEEDID, NAME, VERSION, DESCRIPTION, AUTH_CLASS, PUBLISHER, SELF_LINK, "\r
- + "PUBLISH_LINK, SUBSCRIBE_LINK, LOG_LINK, DELETED, SUSPENDED,"\r
- + "BUSINESS_DESCRIPTION, GROUPID, AAF_INSTANCE) "\r
- + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";\r
- try (PreparedStatement ps2 = conn.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, getBusinessDescription());\r
- ps2.setInt(14, groupid);\r
- ps2.setString(15, getAafInstance());\r
- ps2.executeUpdate();\r
+ try (PreparedStatement ps = conn.prepareStatement(\r
+ "insert into FEEDS (FEEDID, NAME, VERSION, DESCRIPTION, AUTH_CLASS, PUBLISHER, SELF_LINK, "\r
+ + "PUBLISH_LINK, SUBSCRIBE_LINK, LOG_LINK, DELETED, SUSPENDED,"\r
+ + "BUSINESS_DESCRIPTION, GROUPID, AAF_INSTANCE) "\r
+ + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {\r
+ ps.setInt(1, feedid);\r
+ ps.setString(2, getName());\r
+ ps.setString(3, getVersion());\r
+ ps.setString(4, getDescription());\r
+ ps.setString(5, getAuthorization().getClassification());\r
+ ps.setString(6, getPublisher());\r
+ ps.setString(7, getLinks().getSelf());\r
+ ps.setString(8, getLinks().getPublish());\r
+ ps.setString(9, getLinks().getSubscribe());\r
+ ps.setString(10, getLinks().getLog());\r
+ ps.setBoolean(11, isDeleted());\r
+ ps.setBoolean(12, isSuspended());\r
+ ps.setString(13, getBusinessDescription());\r
+ ps.setInt(14, groupid);\r
+ ps.setString(15, getAafInstance());\r
+ ps.executeUpdate();\r
}\r
} catch (SQLException e) {\r
rv = false;\r
@Override\r
public boolean doUpdate(Connection conn) {\r
boolean rv = true;\r
- Feed oldobj = getFeedById(feedid);\r
- PreparedStatement ps = null;\r
try {\r
+ Feed oldobj = getFeedById(feedid);\r
Set<FeedEndpointID> newset = getAuthorization().getEndpointIDS();\r
Set<FeedEndpointID> oldset = oldobj.getAuthorization().getEndpointIDS();\r
-\r
- // Insert new FEED_ENDPOINT_IDS rows\r
- String sql = "insert into FEED_ENDPOINT_IDS values (?, ?, ?)";\r
- ps = conn.prepareStatement(sql);\r
- for (FeedEndpointID fid : newset) {\r
- if (!oldset.contains(fid)) {\r
- ps.setInt(1, feedid);\r
- ps.setString(2, fid.getId());\r
- ps.setString(3, fid.getPassword());\r
- ps.executeUpdate();\r
+ try (PreparedStatement ps = conn.prepareStatement("insert into FEED_ENDPOINT_IDS values (?, ?, ?)")) {\r
+ // Insert new FEED_ENDPOINT_IDS rows\r
+ for (FeedEndpointID fid : newset) {\r
+ if (!oldset.contains(fid)) {\r
+ ps.setInt(1, feedid);\r
+ ps.setString(2, fid.getId());\r
+ ps.setString(3, fid.getPassword());\r
+ ps.executeUpdate();\r
+ }\r
}\r
}\r
- ps.close();\r
-\r
// Delete old FEED_ENDPOINT_IDS rows\r
- sql = "delete from FEED_ENDPOINT_IDS where FEEDID = ? AND USERID = ? AND PASSWORD = ?";\r
- ps = conn.prepareStatement(sql);\r
- for (FeedEndpointID fid : oldset) {\r
- if (!newset.contains(fid)) {\r
- ps.setInt(1, feedid);\r
- ps.setString(2, fid.getId());\r
- ps.setString(3, fid.getPassword());\r
- ps.executeUpdate();\r
+ try (PreparedStatement ps = conn.prepareStatement(\r
+ "delete from FEED_ENDPOINT_IDS where FEEDID = ? AND USERID = ? AND PASSWORD = ?")) {\r
+ for (FeedEndpointID fid : oldset) {\r
+ if (!newset.contains(fid)) {\r
+ ps.setInt(1, feedid);\r
+ ps.setString(2, fid.getId());\r
+ ps.setString(3, fid.getPassword());\r
+ ps.executeUpdate();\r
+ }\r
}\r
}\r
- ps.close();\r
-\r
- // Insert new FEED_ENDPOINT_ADDRS rows\r
Set<String> newset2 = getAuthorization().getEndpointAddrs();\r
Set<String> oldset2 = oldobj.getAuthorization().getEndpointAddrs();\r
- sql = "insert into FEED_ENDPOINT_ADDRS values (?, ?)";\r
- ps = conn.prepareStatement(sql);\r
- for (String t : newset2) {\r
- if (!oldset2.contains(t)) {\r
- ps.setInt(1, feedid);\r
- ps.setString(2, t);\r
- ps.executeUpdate();\r
+ // Insert new FEED_ENDPOINT_ADDRS rows\r
+ try (PreparedStatement ps = conn.prepareStatement("insert into FEED_ENDPOINT_ADDRS values (?, ?)")) {\r
+ for (String t : newset2) {\r
+ if (!oldset2.contains(t)) {\r
+ ps.setInt(1, feedid);\r
+ ps.setString(2, t);\r
+ ps.executeUpdate();\r
+ }\r
}\r
}\r
- ps.close();\r
-\r
// Delete old FEED_ENDPOINT_ADDRS rows\r
- sql = "delete from FEED_ENDPOINT_ADDRS where FEEDID = ? AND ADDR = ?";\r
- ps = conn.prepareStatement(sql);\r
- for (String t : oldset2) {\r
- if (!newset2.contains(t)) {\r
- ps.setInt(1, feedid);\r
- ps.setString(2, t);\r
- ps.executeUpdate();\r
+ try (PreparedStatement ps = conn.prepareStatement(\r
+ "delete from FEED_ENDPOINT_ADDRS where FEEDID = ? AND ADDR = ?")) {\r
+ for (String t : oldset2) {\r
+ if (!newset2.contains(t)) {\r
+ ps.setInt(1, feedid);\r
+ ps.setString(2, t);\r
+ ps.executeUpdate();\r
+ }\r
}\r
}\r
- ps.close();\r
-\r
- // Finally, update the FEEDS row\r
- sql = "update FEEDS set DESCRIPTION = ?, AUTH_CLASS = ?, DELETED = ?, SUSPENDED = ?, "\r
- + "BUSINESS_DESCRIPTION=?, GROUPID=? where FEEDID = ?";\r
- ps = conn.prepareStatement(sql);\r
- ps.setString(1, getDescription());\r
- ps.setString(2, getAuthorization().getClassification());\r
- ps.setInt(3, deleted ? 1 : 0);\r
- ps.setInt(4, suspended ? 1 : 0);\r
- ps.setString(5, getBusinessDescription());\r
- ps.setInt(6, groupid);\r
- ps.setInt(7, feedid);\r
- ps.executeUpdate();\r
- ps.close();\r
+ try (PreparedStatement ps = conn.prepareStatement(\r
+ "update FEEDS set DESCRIPTION = ?, AUTH_CLASS = ?, DELETED = ?, SUSPENDED = ?, "\r
+ + "BUSINESS_DESCRIPTION=?, GROUPID=? where FEEDID = ?")) {\r
+ // Finally, update the FEEDS row\r
+ ps.setString(1, getDescription());\r
+ ps.setString(2, getAuthorization().getClassification());\r
+ ps.setInt(3, deleted ? 1 : 0);\r
+ ps.setInt(4, suspended ? 1 : 0);\r
+ ps.setString(5, getBusinessDescription());\r
+ ps.setInt(6, groupid);\r
+ ps.setInt(7, feedid);\r
+ ps.executeUpdate();\r
+ }\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
public boolean changeOwnerShip() {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
-\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- String sql = "update FEEDS set PUBLISHER = ? where FEEDID = ?";\r
- ps = conn.prepareStatement(sql);\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(\r
+ "update FEEDS set PUBLISHER = ? where FEEDID = ?")) {\r
ps.setString(1, this.publisher);\r
ps.setInt(2, feedid);\r
ps.execute();\r
- ps.close();\r
} catch (SQLException e) {\r
rv = false;\r
intlogger.warn("PROV0008 changeOwnerShip: " + 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
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.List;\r
import java.util.Objects;\r
import org.json.JSONObject;\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
\r
/**\r
* The representation of a Subscription. Subscriptions can be retrieved from the DB, or stored/updated in the DB.\r
private static final String GROUP_ID_CONST = "groupid";\r
private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");\r
private static int nextGroupid = getMaxGroupID() + 1;\r
- private static final String SQLEXCEPTION = "SQLException: ";\r
\r
private int groupid;\r
private String authid;\r
} catch (InvalidObjectException e) {\r
throw e;\r
} catch (Exception e) {\r
- intlogger.warn("Invalid JSON: " + e.getMessage(), e);\r
+ intlogger.error("Invalid JSON: " + e.getMessage(), e);\r
throw new InvalidObjectException("Invalid JSON: " + e.getMessage());\r
}\r
}\r
*/\r
public static Group getGroupMatching(Group gup) {\r
String sql = String.format(\r
- "select * from GROUPS where NAME='%s'",\r
- gup.getName()\r
+ "select * from GROUPS where NAME='%s'",\r
+ gup.getName()\r
);\r
List<Group> list = getGroupsForSQL(sql);\r
return !list.isEmpty() ? list.get(0) : null;\r
*/\r
public static Group getGroupMatching(Group gup, int groupid) {\r
String sql = String.format(\r
- "select * from GROUPS where NAME = '%s' and GROUPID != %d ", gup.getName(), gup.getGroupid());\r
+ "select * from GROUPS where NAME = '%s' and GROUPID != %d ", gup.getName(), groupid);\r
List<Group> list = getGroupsForSQL(sql);\r
return !list.isEmpty() ? list.get(0) : null;\r
}\r
\r
private static List<Group> getGroupsForSQL(String sql) {\r
List<Group> list = new ArrayList<>();\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
- Group group = new Group(rs);\r
- list.add(group);\r
- }\r
- }\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(sql);\r
+ ResultSet rs = ps.executeQuery()) {\r
+ while (rs.next()) {\r
+ Group group = new Group(rs);\r
+ list.add(group);\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.error("PROV0009 getGroupsForSQL: " + e.getMessage(), e);\r
}\r
\r
private static int getMaxGroupID() {\r
int max = 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("select MAX(groupid) from GROUPS")) {\r
- if (rs.next()) {\r
- max = rs.getInt(1);\r
- }\r
- }\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement("select MAX(groupid) from GROUPS");\r
+ ResultSet rs = ps.executeQuery()) {\r
+ if (rs.next()) {\r
+ max = rs.getInt(1);\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
- intlogger.info("PROV0001 getMaxSubID: " + e.getMessage(), e);\r
+ intlogger.error("PROV0001 getMaxSubID: " + e.getMessage(), e);\r
}\r
return max;\r
}\r
@Override\r
public boolean doInsert(Connection conn) {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
+ try (PreparedStatement ps = conn.prepareStatement(\r
+ "insert into GROUPS(GROUPID, AUTHID, NAME, DESCRIPTION, CLASSIFICATION, MEMBERS) "\r
+ + "values (?, ?, ?, ?, ?, ?)", new String[]{"GROUPID"})) {\r
if (groupid == -1) {\r
// No feed ID assigned yet, so assign the next available one\r
setGroupid(nextGroupid++);\r
}\r
- // In case we insert a gropup from synchronization\r
+ // In case we insert a group from synchronization\r
if (groupid > nextGroupid) {\r
nextGroupid = groupid + 1;\r
}\r
-\r
// Create the GROUPS row\r
- String sql = "insert into GROUPS (GROUPID, AUTHID, NAME, DESCRIPTION, CLASSIFICATION, MEMBERS) "\r
- + "values (?, ?, ?, ?, ?, ?)";\r
- ps = conn.prepareStatement(sql, new String[]{"GROUPID"});\r
ps.setInt(1, groupid);\r
ps.setString(2, authid);\r
ps.setString(3, name);\r
ps.setString(5, classification);\r
ps.setString(6, members);\r
ps.execute();\r
- ps.close();\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(), e);\r
- }\r
+ intlogger.error("PROV0005 doInsert: " + e.getMessage(), e);\r
}\r
return rv;\r
}\r
@Override\r
public boolean doUpdate(Connection conn) {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
- String sql = "update GROUPS set AUTHID = ?, NAME = ?, DESCRIPTION = ?, CLASSIFICATION = ? , MEMBERS = ? "\r
- + "where GROUPID = ?";\r
- ps = conn.prepareStatement(sql);\r
+ try (PreparedStatement ps = conn.prepareStatement(\r
+ "update GROUPS set AUTHID = ?, NAME = ?, DESCRIPTION = ?, CLASSIFICATION = ? , MEMBERS = ? where GROUPID = ?")) {\r
ps.setString(1, authid);\r
ps.setString(2, name);\r
ps.setString(3, description);\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
+ intlogger.error("PROV0006 doUpdate: " + e.getMessage(), e);\r
}\r
return rv;\r
}\r
@Override\r
public boolean doDelete(Connection conn) {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
- String sql = "delete from GROUPS where GROUPID = ?";\r
- ps = conn.prepareStatement(sql);\r
+ try (PreparedStatement ps = conn.prepareStatement("delete from GROUPS where GROUPID = ?")) {\r
ps.setInt(1, groupid);\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
+ intlogger.error("PROV0007 doDelete: " + e.getMessage(), e);\r
}\r
return rv;\r
}\r
if (groupid != os.groupid) {\r
return false;\r
}\r
- if (authid != os.authid) {\r
+ if (!authid.equals(os.authid)) {\r
return false;\r
}\r
if (!name.equals(os.name)) {\r
return false;\r
}\r
- if (description != os.description) {\r
+ if (!description.equals(os.description)) {\r
return false;\r
}\r
if (!classification.equals(os.classification)) {\r
return false;\r
}\r
- if (!members.equals(os.members)) {\r
- return false;\r
- }\r
-\r
- return true;\r
+ return members.equals(os.members);\r
}\r
\r
@Override\r
import java.sql.PreparedStatement;\r
import java.sql.ResultSet;\r
import java.sql.SQLException;\r
-import java.sql.Statement;\r
import java.util.Collection;\r
import java.util.Set;\r
import java.util.SortedSet;\r
import org.apache.commons.codec.binary.Base64;\r
import org.json.JSONArray;\r
import org.json.JSONObject;\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
\r
/**\r
* The representation of one route in the Ingress Route Table.\r
*/\r
public static Set<IngressRoute> getIngressRoutesForSeq(int seq) {\r
return getAllIngressRoutesForSQL(\r
- "select SEQUENCE, FEEDID, USERID, SUBNET, NODESET from INGRESS_ROUTES where SEQUENCE = " + seq);\r
+ "select SEQUENCE, FEEDID, USERID, SUBNET, NODESET from INGRESS_ROUTES where SEQUENCE = " + seq);\r
}\r
\r
private static SortedSet<IngressRoute> getAllIngressRoutesForSQL(String sql) {\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
- addIngressRouteToSet(set, rs);\r
- }\r
- }\r
- db.release(conn);\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(sql);\r
+ ResultSet rs = ps.executeQuery()) {\r
+ addIngressRouteToSet(set, rs);\r
} catch (SQLException e) {\r
intlogger.error("PROV0001 getAllIngressRoutesForSQL: " + e.getMessage(), e);\r
}\r
\r
private static int getMax(String sql) {\r
int rv = 0;\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
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(sql);\r
+ ResultSet rs = ps.executeQuery(sql)) {\r
+ if (rs.next()) {\r
+ rv = rs.getInt("MAX");\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.error("PROV0002 getMax: " + e.getMessage(), e);\r
}\r
*/\r
public static IngressRoute getIngressRoute(int feedid, String user, String subnet) {\r
IngressRoute ir = null;\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
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(\r
+ "select SEQUENCE, NODESET from INGRESS_ROUTES where FEEDID = ? AND USERID = ? and SUBNET = ?")) {\r
ps.setInt(1, feedid);\r
ps.setString(2, user);\r
ps.setString(3, subnet);\r
ir = new IngressRoute(seq, feedid, user, subnet, nodeset);\r
}\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.error("PROV0003 getIngressRoute: " + e.getMessage(), e);\r
}\r
* Compare IP addresses as byte arrays to a subnet specified as a CIDR. Taken from\r
* org.onap.dmaap.datarouter.node.SubnetMatcher and modified somewhat.\r
*/\r
- public class SubnetMatcher {\r
+ public static class SubnetMatcher {\r
\r
private byte[] sn;\r
private int len;\r
*\r
* @param subnet The CIDR to match\r
*/\r
- public SubnetMatcher(String subnet) {\r
+ SubnetMatcher(String subnet) {\r
int index = subnet.lastIndexOf('/');\r
if (index == -1) {\r
try {\r
\r
private Collection<String> readNodes() {\r
Collection<String> set = new TreeSet<>();\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
- addNodeToSet(set, ps);\r
- }\r
- db.release(conn);\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement("select NODEID from NODESETS where SETID = ?")) {\r
+ ps.setInt(1, nodelist);\r
+ addNodeToSet(set, ps);\r
} catch (SQLException e) {\r
intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
}\r
public boolean doDelete(Connection conn) {\r
boolean rv = true;\r
try (PreparedStatement ps = conn.prepareStatement(\r
- "delete from INGRESS_ROUTES where FEEDID = ? and USERID = ? and SUBNET = ?");\r
- PreparedStatement ps2 = conn.prepareStatement("delete from NODESETS where SETID = ?")) {\r
+ "delete from INGRESS_ROUTES where FEEDID = ? and USERID = ? and SUBNET = ?");\r
+ PreparedStatement ps2 = conn.prepareStatement("delete from NODESETS where SETID = ?")) {\r
// Delete the Ingress Route\r
ps.setInt(1, feedid);\r
ps.setString(2, userid);\r
ps2.execute();\r
} catch (SQLException e) {\r
rv = false;\r
- intlogger.warn("PROV0007 doDelete: " + e.getMessage(), e);\r
+ intlogger.error("PROV0007 doDelete: " + e.getMessage(), e);\r
}\r
return rv;\r
}\r
public boolean doInsert(Connection conn) {\r
boolean rv = false;\r
try (PreparedStatement ps = conn.prepareStatement("insert into NODESETS (SETID, NODEID) values (?,?)");\r
- PreparedStatement ps2 = conn.prepareStatement("insert into INGRESS_ROUTES (SEQUENCE, FEEDID, USERID,"\r
- + " SUBNET, NODESET) values (?, ?, ?, ?, ?)")) {\r
+ PreparedStatement ps2 = conn.prepareStatement("insert into INGRESS_ROUTES (SEQUENCE, FEEDID, USERID,"\r
+ + " SUBNET, NODESET) values (?, ?, ?, ?, ?)")) {\r
// Create the NODESETS rows & set nodelist\r
this.nodelist = getMaxNodeSetID() + 1;\r
for (String node : nodes) {\r
ps2.execute();\r
rv = true;\r
} catch (SQLException e) {\r
- intlogger.warn("PROV0005 doInsert: " + e.getMessage(), e);\r
+ intlogger.error("PROV0005 doInsert: " + e.getMessage(), e);\r
}\r
return rv;\r
}\r
@Override\r
public String getKey() {\r
return String\r
- .format("%d/%s/%s/%d", feedid, (userid == null) ? "" : userid, (subnet == null) ? "" : subnet, seq);\r
+ .format("%d/%s/%s/%d", feedid, (userid == null) ? "" : userid, (subnet == null) ? "" : subnet, seq);\r
}\r
\r
@Override\r
@Override\r
public String toString() {\r
return String.format("INGRESS: feed=%d, userid=%s, subnet=%s, seq=%d", feedid, (userid == null) ? "" : userid,\r
- (subnet == null) ? "" : subnet, seq);\r
+ (subnet == null) ? "" : subnet, seq);\r
}\r
}\r
import java.sql.Types;\r
import java.text.ParseException;\r
import java.util.Iterator;\r
-\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
import org.onap.dmaap.datarouter.provisioning.utils.RLEBitSet;\r
\r
\r
*/\r
public class LogRecord extends BaseLogRecord {\r
\r
- /**\r
- * Print all log records whose RECORD_IDs are in the bit set provided.\r
- *\r
- * @param os the {@link OutputStream} to print the records on\r
- * @param bs the {@link RLEBitSet} listing the record IDs to print\r
- * @throws IOException in case of I/O error\r
- */\r
private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");\r
private final String type;\r
private final String feedFileID;\r
* @param rs ResultSet from SQL statement\r
* @throws SQLException in case of SQL error\r
*/\r
- public LogRecord(ResultSet rs) throws SQLException {\r
+ private LogRecord(ResultSet rs) throws SQLException {\r
super(rs);\r
this.type = rs.getString("TYPE");\r
this.feedFileID = rs.getString("FEED_FILEID");\r
}\r
\r
/**\r
- * Get Log Records.\r
- * @param os outputstream\r
- * @param bs RLEBitSet object\r
+ * Print all log records whose RECORD_IDs are in the bit set provided.\r
+ *\r
+ * @param os the {@link OutputStream} to print the records on\r
+ * @param bs the {@link RLEBitSet} listing the record IDs to print\r
* @throws IOException in case of I/O error\r
*/\r
public static void printLogRecords(OutputStream os, RLEBitSet bs) throws IOException {\r
- final String sql = "select * from LOG_RECORDS where RECORD_ID >= ? AND RECORD_ID <= ?";\r
- DB db = new DB();\r
- try (Connection conn = db.getConnection()) {\r
- Iterator<Long[]> iter = bs.getRangeIterator();\r
- try (PreparedStatement ps = conn.prepareStatement(sql)) {\r
- while (iter.hasNext()) {\r
- Long[] nxt = iter.next();\r
- ps.setLong(1, nxt[0]);\r
- ps.setLong(2, nxt[1]);\r
- try (ResultSet rs = ps.executeQuery()) {\r
- while (rs.next()) {\r
- LogRecord lr = new LogRecord(rs);\r
- os.write(lr.toString().getBytes());\r
- }\r
- ps.clearParameters();\r
+ Iterator<Long[]> iter = bs.getRangeIterator();\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(\r
+ "select * from LOG_RECORDS where RECORD_ID >= ? AND RECORD_ID <= ?")) {\r
+ while (iter.hasNext()) {\r
+ Long[] nxt = iter.next();\r
+ ps.setLong(1, nxt[0]);\r
+ ps.setLong(2, nxt[1]);\r
+ try (ResultSet rs = ps.executeQuery()) {\r
+ while (rs.next()) {\r
+ LogRecord lr = new LogRecord(rs);\r
+ os.write(lr.toString().getBytes());\r
}\r
+ ps.clearParameters();\r
}\r
}\r
} catch (SQLException e) {\r
@Override\r
public String toString() {\r
return\r
- sdf.format(getEventTime()) + "|"\r
- + "LOG|"\r
- + getPublishId() + "|"\r
- + getFeedid() + "|"\r
- + getRequestUri() + "|"\r
- + getMethod() + "|"\r
- + getContentType() + "|"\r
- + getContentLength() + "|"\r
- + type + "|"\r
- + feedFileID + "|"\r
- + remoteAddr + "|"\r
- + user + "|"\r
- + status + "|"\r
- + subID + "|"\r
- + fileID + "|"\r
- + result + "|"\r
- + attempts + "|"\r
- + reason + "|"\r
- + recordId + "|"\r
- + clength2\r
- + "\n";\r
+ sdf.format(getEventTime()) + "|"\r
+ + "LOG|"\r
+ + getPublishId() + "|"\r
+ + getFeedid() + "|"\r
+ + getRequestUri() + "|"\r
+ + getMethod() + "|"\r
+ + getContentType() + "|"\r
+ + getContentLength() + "|"\r
+ + type + "|"\r
+ + feedFileID + "|"\r
+ + remoteAddr + "|"\r
+ + user + "|"\r
+ + status + "|"\r
+ + subID + "|"\r
+ + fileID + "|"\r
+ + result + "|"\r
+ + attempts + "|"\r
+ + reason + "|"\r
+ + recordId + "|"\r
+ + clength2\r
+ + "\n";\r
}\r
\r
@Override\r
import java.sql.PreparedStatement;\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
import org.json.JSONObject;\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
\r
/**\r
* The representation of one route in the Network Route Table.\r
*/\r
public static SortedSet<NetworkRoute> getAllNetworkRoutes() {\r
SortedSet<NetworkRoute> 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("select FROMNODE, TONODE, VIANODE from NETWORK_ROUTES")) {\r
- addNetworkRouteToSet(set, rs);\r
- }\r
- } finally {\r
- db.release(conn);\r
- }\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement("select FROMNODE, TONODE, VIANODE from NETWORK_ROUTES");\r
+ ResultSet rs = ps.executeQuery()) {\r
+ addNetworkRouteToSet(set, rs);\r
} catch (SQLException e) {\r
intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
}\r
return tonode;\r
}\r
\r
- public int getVianode() {\r
+ int getVianode() {\r
return vianode;\r
}\r
\r
@Override\r
public boolean doDelete(Connection conn) {\r
boolean rv = true;\r
- String sql = "delete from NETWORK_ROUTES where FROMNODE = ? AND TONODE = ?";\r
- try (PreparedStatement ps = conn.prepareStatement(sql)) {\r
+ try (PreparedStatement ps = conn.prepareStatement(\r
+ "delete from NETWORK_ROUTES where FROMNODE = ? AND TONODE = ?")) {\r
ps.setInt(1, fromnode);\r
ps.setInt(2, tonode);\r
ps.execute();\r
@Override\r
public boolean doInsert(Connection conn) {\r
boolean rv = false;\r
- String sql = "insert into NETWORK_ROUTES (FROMNODE, TONODE, VIANODE) values (?, ?, ?)";\r
if (this.vianode >= 0) {\r
- try (PreparedStatement ps = conn.prepareStatement(sql)) {\r
+ try (PreparedStatement ps = conn.prepareStatement(\r
+ "insert into NETWORK_ROUTES (FROMNODE, TONODE, VIANODE) values (?, ?, ?)")) {\r
// Create the NETWORK_ROUTES row\r
ps.setInt(1, this.fromnode);\r
ps.setInt(2, this.tonode);\r
@Override\r
public boolean doUpdate(Connection conn) {\r
boolean rv = true;\r
- String sql = "update NETWORK_ROUTES set VIANODE = ? where FROMNODE = ? and TONODE = ?";\r
- try (PreparedStatement ps = conn.prepareStatement(sql)) {\r
+ try (PreparedStatement ps = conn.prepareStatement(\r
+ "update NETWORK_ROUTES set VIANODE = ? where FROMNODE = ? and TONODE = ?")) {\r
ps.setInt(1, vianode);\r
ps.setInt(2, fromnode);\r
ps.setInt(3, tonode);\r
* * org.onap.dmaap\r
* * ===========================================================================\r
* * Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
- * * ===========================================================================\r
+ * * ===========================================================================\r
* * Licensed under the Apache License, Version 2.0 (the "License");\r
* * you may not use this file except in compliance with the License.\r
* * You may obtain a copy of the License at\r
import java.util.Map;\r
import java.util.Set;\r
import java.util.TreeSet;\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
\r
/**\r
* This class is used to aid in the mapping of node names from/to node IDs.\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 Map<String, Integer> nodesMap;\r
private static EELFLogger intLogger = EELFManager.getInstance().getLogger("InternalLog");\r
\r
NodeClass() {\r
// init on first use\r
- if (map == null) {\r
+ if (nodesMap == null) {\r
reload();\r
}\r
}\r
* @param nodes a pipe separated list of the current nodes\r
*/\r
public static void setNodes(String[] nodes) {\r
- if (map == null) {\r
+ if (nodesMap == null) {\r
reload();\r
}\r
int nextid = 0;\r
- for (Integer n : map.values()) {\r
+ for (Integer n : nodesMap.values()) {\r
if (n >= nextid) {\r
nextid = n + 1;\r
}\r
\r
for (String node : nodes) {\r
node = normalizeNodename(node);\r
- if (!map.containsKey(node)) {\r
+ if (!nodesMap.containsKey(node)) {\r
intLogger.info("..adding " + node + " to NODES with index " + nextid);\r
- map.put(node, nextid);\r
+ nodesMap.put(node, nextid);\r
insertNodesToTable(nextid, node);\r
nextid++;\r
}\r
}\r
\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
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(\r
+ "insert into NODES (NODEID, NAME, ACTIVE) values (?, ?, 1)")) {\r
+ ps.setInt(1, nextid);\r
+ ps.setString(2, node);\r
+ ps.execute();\r
} catch (SQLException e) {\r
intLogger.error(PROV_0005_DO_INSERT + e.getMessage(), e);\r
}\r
}\r
\r
private static void reload() {\r
- Map<String, Integer> hmap = 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
- hmap.put(name, id);\r
- }\r
- } finally {\r
- db.release(conn);\r
+ Map<String, Integer> tmpNodesMap = new HashMap<>();\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement("select NODEID, NAME from NODES");\r
+ ResultSet rs = ps.executeQuery()) {\r
+ while (rs.next()) {\r
+ int id = rs.getInt("NODEID");\r
+ String name = rs.getString("NAME");\r
+ tmpNodesMap.put(name, id);\r
}\r
} catch (SQLException e) {\r
intLogger.error(PROV_0005_DO_INSERT + e.getMessage(),e);\r
}\r
- map = hmap;\r
+ nodesMap = tmpNodesMap;\r
}\r
\r
static Integer lookupNodeName(final String name) {\r
- Integer nodeName = map.get(name);\r
+ Integer nodeName = nodesMap.get(name);\r
if (nodeName == 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<>();\r
- final Set<String> keyset = map.keySet();\r
+ final Set<String> keyset = nodesMap.keySet();\r
for (String s : patt.toLowerCase().split(",")) {\r
if (s.endsWith("*")) {\r
addNodeToCollection(coll, keyset, s);\r
}\r
\r
String lookupNodeID(int node) {\r
- for (Map.Entry<String, Integer> entry : map.entrySet()) {\r
+ for (Map.Entry<String, Integer> entry : nodesMap.entrySet()) {\r
if (entry.getValue() == node) {\r
return entry.getKey();\r
}\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.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
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
\r
/**\r
* Methods to provide access to Provisioning parameters in the DB. This class also provides constants of the standard\r
public static final String PROV_AUTH_SUBJECTS = "PROV_AUTH_SUBJECTS";\r
public static final String PROV_NAME = "PROV_NAME";\r
public static final String PROV_ACTIVE_NAME = "PROV_ACTIVE_NAME";\r
- public static final String PROV_DOMAIN = "PROV_DOMAIN";\r
+ static final String PROV_DOMAIN = "PROV_DOMAIN";\r
public static final String PROV_MAXFEED_COUNT = "PROV_MAXFEED_COUNT";\r
public static final String PROV_MAXSUB_COUNT = "PROV_MAXSUB_COUNT";\r
public static final String PROV_POKETIMER1 = "PROV_POKETIMER1";\r
*/\r
public static Collection<Parameters> getParameterCollection() {\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 param = new Parameters(rs);\r
- coll.add(param);\r
- }\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement("select * from PARAMETERS")) {\r
+ ResultSet rs = ps.executeQuery();\r
+ while (rs.next()) {\r
+ Parameters param = new Parameters(rs);\r
+ coll.add(param);\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
}\r
*/\r
public static Parameters getParameter(String key) {\r
Parameters val = null;\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
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement stmt = conn.prepareStatement(\r
+ "select KEYNAME, VALUE from PARAMETERS where KEYNAME = ?")) {\r
stmt.setString(1, key);\r
- try (ResultSet rs = stmt.executeQuery()) {\r
- if (rs.next()) {\r
- val = new Parameters(rs);\r
- }\r
+ ResultSet rs = stmt.executeQuery();\r
+ if (rs.next()) {\r
+ val = new Parameters(rs);\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
}\r
@Override\r
public boolean doInsert(Connection conn) {\r
boolean rv = true;\r
- String sql = "insert into PARAMETERS values (?, ?)";\r
- try (PreparedStatement ps = conn.prepareStatement(sql)) {\r
+ try (PreparedStatement ps = conn.prepareStatement("insert into PARAMETERS values (?, ?)")) {\r
ps.setString(1, getKeyname());\r
ps.setString(2, getValue());\r
ps.execute();\r
@Override\r
public boolean doUpdate(Connection conn) {\r
boolean rv = true;\r
- String sql = "update PARAMETERS set VALUE = ? where KEYNAME = ?";\r
- try (PreparedStatement ps = conn.prepareStatement(sql)) {\r
+ try (PreparedStatement ps = conn.prepareStatement("update PARAMETERS set VALUE = ? where KEYNAME = ?")) {\r
ps.setString(1, getValue());\r
ps.setString(2, getKeyname());\r
ps.executeUpdate();\r
@Override\r
public boolean doDelete(Connection conn) {\r
boolean rv = true;\r
- String sql = "delete from PARAMETERS where KEYNAME = ?";\r
- try (PreparedStatement ps = conn.prepareStatement(sql)) {\r
+ try (PreparedStatement ps = conn.prepareStatement("delete from PARAMETERS where KEYNAME = ?")) {\r
ps.setString(1, getKeyname());\r
ps.execute();\r
} catch (SQLException e) {\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.List;\r
import java.util.Properties;\r
import org.json.JSONObject;\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
+import org.onap.dmaap.datarouter.provisioning.ProvRunner;\r
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
import org.onap.dmaap.datarouter.provisioning.utils.URLUtilities;\r
\r
\r
this.followRedirect = rs.getBoolean("FOLLOW_REDIRECTS");\r
this.subscriber = rs.getString("SUBSCRIBER");\r
this.links = new SubLinks(rs.getString("SELF_LINK"), URLUtilities.generateFeedURL(feedid),\r
- rs.getString("LOG_LINK"));\r
+ rs.getString("LOG_LINK"));\r
this.suspended = rs.getBoolean("SUSPENDED");\r
this.lastMod = rs.getDate("LAST_MOD");\r
this.createdDate = rs.getDate("CREATED_DATE");\r
final boolean use100 = jdeli.getBoolean("use100");\r
\r
//Data Router Subscriber HTTPS Relaxation feature USERSTORYID:US674047.\r
- Properties prop = (new DB()).getProperties();\r
+ Properties prop = ProvRunner.getProvProperties();\r
if (!url.startsWith("https://") && isHttpsRelaxationFalseAndHasSyncKey(jo, prop)) {\r
throw new InvalidObjectException("delivery URL is not HTTPS");\r
}\r
public static Subscription getSubscriptionMatching(Subscription sub) {\r
SubDelivery deli = sub.getDelivery();\r
String sql = String.format(\r
- "select * from SUBSCRIPTIONS where FEEDID = %d and DELIVERY_URL = \"%s\" and DELIVERY_USER = \"%s\" "\r
- + "and DELIVERY_PASSWORD = \"%s\" and DELIVERY_USE100 = %d and METADATA_ONLY = %d "\r
- + "and FOLLOW_REDIRECTS = %d",\r
- sub.getFeedid(),\r
- deli.getUrl(),\r
- deli.getUser(),\r
- deli.getPassword(),\r
- deli.isUse100() ? 1 : 0,\r
- sub.isMetadataOnly() ? 1 : 0,\r
- sub.isFollowRedirect() ? 1 : 0\r
+ "select * from SUBSCRIPTIONS where FEEDID = %d and DELIVERY_URL = \"%s\" and DELIVERY_USER = \"%s\" "\r
+ + "and DELIVERY_PASSWORD = \"%s\" and DELIVERY_USE100 = %d and METADATA_ONLY = %d "\r
+ + "and FOLLOW_REDIRECTS = %d",\r
+ sub.getFeedid(),\r
+ deli.getUrl(),\r
+ deli.getUser(),\r
+ deli.getPassword(),\r
+ deli.isUse100() ? 1 : 0,\r
+ sub.isMetadataOnly() ? 1 : 0,\r
+ sub.isFollowRedirect() ? 1 : 0\r
);\r
List<Subscription> list = getSubscriptionsForSQL(sql);\r
return !list.isEmpty() ? list.get(0) : null;\r
*/\r
private static List<Subscription> getSubscriptionsForSQL(String sql) {\r
List<Subscription> list = new ArrayList<>();\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
- Subscription sub = new Subscription(rs);\r
- list.add(sub);\r
- }\r
- }\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(sql);\r
+ ResultSet rs = ps.executeQuery()) {\r
+ while (rs.next()) {\r
+ Subscription sub = new Subscription(rs);\r
+ list.add(sub);\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.error("PROV0001 getSubscriptionsForSQL: " + e.toString(), e);\r
}\r
*/\r
public static int getMaxSubID() {\r
int max = 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("select MAX(subid) from SUBSCRIPTIONS")) {\r
- if (rs.next()) {\r
- max = rs.getInt(1);\r
- }\r
- }\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement("select MAX(subid) from SUBSCRIPTIONS");\r
+ ResultSet rs = ps.executeQuery()) {\r
+ if (rs.next()) {\r
+ max = rs.getInt(1);\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.info("getMaxSubID: " + e.getMessage(), e);\r
}\r
*/\r
public static Collection<String> getSubscriptionUrlList(int feedid) {\r
List<String> list = new ArrayList<>();\r
- String sql = "select SUBID from SUBSCRIPTIONS where FEEDID = ?";\r
-\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- try (PreparedStatement stmt = conn.prepareStatement(sql)) {\r
- stmt.setString(1, String.valueOf(feedid));\r
- try (ResultSet rs = stmt.executeQuery()) {\r
- while (rs.next()) {\r
- int subid = rs.getInt(SUBID_COL);\r
- list.add(URLUtilities.generateSubscriptionURL(subid));\r
- }\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement stmt = conn.prepareStatement("select SUBID from SUBSCRIPTIONS where FEEDID = ?")) {\r
+ stmt.setString(1, String.valueOf(feedid));\r
+ try (ResultSet rs = stmt.executeQuery()) {\r
+ while (rs.next()) {\r
+ int subid = rs.getInt(SUBID_COL);\r
+ list.add(URLUtilities.generateSubscriptionURL(subid));\r
}\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.error(SQLEXCEPTION + e.getMessage(), e);\r
}\r
*/\r
public static int countActiveSubscriptions() {\r
int count = 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("select count(*) from SUBSCRIPTIONS")) {\r
- if (rs.next()) {\r
- count = rs.getInt(1);\r
- }\r
- }\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement("select count(*) from SUBSCRIPTIONS");\r
+ ResultSet rs = ps.executeQuery()) {\r
+ if (rs.next()) {\r
+ count = rs.getInt(1);\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
intlogger.warn("PROV0008 countActiveSubscriptions: " + e.getMessage(), e);\r
}\r
\r
private boolean isHttpsRelaxationFalseAndHasSyncKey(JSONObject jo, Properties prop) {\r
return prop.get("org.onap.dmaap.datarouter.provserver.https.relaxation").toString().equals("false") && !jo\r
- .has("sync");\r
+ .has("sync");\r
}\r
\r
public int getSubid() {\r
\r
// Create the SUBSCRIPTIONS row\r
String sql = "insert into SUBSCRIPTIONS (SUBID, FEEDID, DELIVERY_URL, DELIVERY_USER, DELIVERY_PASSWORD, "\r
- + "DELIVERY_USE100, METADATA_ONLY, SUBSCRIBER, SUSPENDED, GROUPID, "\r
- + "PRIVILEGED_SUBSCRIBER, FOLLOW_REDIRECTS, DECOMPRESS, AAF_INSTANCE) "\r
- + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";\r
+ + "DELIVERY_USE100, METADATA_ONLY, SUBSCRIBER, SUSPENDED, GROUPID, "\r
+ + "PRIVILEGED_SUBSCRIBER, FOLLOW_REDIRECTS, DECOMPRESS, AAF_INSTANCE) "\r
+ + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";\r
ps = conn.prepareStatement(sql, new String[]{SUBID_COL});\r
ps.setInt(1, subid);\r
ps.setInt(2, feedid);\r
@Override\r
public boolean doUpdate(Connection conn) {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
- String sql = "update SUBSCRIPTIONS set DELIVERY_URL = ?, DELIVERY_USER = ?, DELIVERY_PASSWORD = ?, "\r
- + "DELIVERY_USE100 = ?, METADATA_ONLY = ?, " + "SUSPENDED = ?, GROUPID = ?, "\r
- + "PRIVILEGED_SUBSCRIBER = ?, "\r
- + "FOLLOW_REDIRECTS = ?, DECOMPRESS = ? where SUBID = ?";\r
- ps = conn.prepareStatement(sql);\r
+ try (PreparedStatement ps = conn.prepareStatement(\r
+ "update SUBSCRIPTIONS set DELIVERY_URL = ?, DELIVERY_USER = ?, DELIVERY_PASSWORD = ?, "\r
+ + "DELIVERY_USE100 = ?, METADATA_ONLY = ?, SUSPENDED = ?, GROUPID = ?, PRIVILEGED_SUBSCRIBER = ?, "\r
+ + "FOLLOW_REDIRECTS = ?, DECOMPRESS = ? where SUBID = ?")) {\r
ps.setString(1, delivery.getUrl());\r
ps.setString(2, delivery.getUser());\r
ps.setString(3, delivery.getPassword());\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
public boolean changeOwnerShip() {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
-\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- String sql = "update SUBSCRIPTIONS set SUBSCRIBER = ? where SUBID = ?";\r
- ps = conn.prepareStatement(sql);\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(\r
+ "update SUBSCRIPTIONS set SUBSCRIBER = ? where SUBID = ?")) {\r
ps.setString(1, this.subscriber);\r
ps.setInt(2, subid);\r
ps.execute();\r
- ps.close();\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 conn) {\r
boolean rv = true;\r
- PreparedStatement ps = null;\r
- try {\r
- String sql = "delete from SUBSCRIPTIONS where SUBID = ?";\r
- ps = conn.prepareStatement(sql);\r
+ try (PreparedStatement ps = conn.prepareStatement("delete from SUBSCRIPTIONS where SUBID = ?")) {\r
ps.setInt(1, subid);\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
+++ /dev/null
-/*******************************************************************************\r
- * ============LICENSE_START==================================================\r
- * * org.onap.dmaap\r
- * * ===========================================================================\r
- * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
- * * ===========================================================================\r
- * * Licensed under the Apache License, Version 2.0 (the "License");\r
- * * you may not use this file except in compliance with the License.\r
- * * You may obtain a copy of the License at\r
- * *\r
- * * http://www.apache.org/licenses/LICENSE-2.0\r
- * *\r
- * * Unless required by applicable law or agreed to in writing, software\r
- * * distributed under the License is distributed on an "AS IS" BASIS,\r
- * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * * See the License for the specific language governing permissions and\r
- * * limitations under the License.\r
- * * ============LICENSE_END====================================================\r
- * *\r
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
- * *\r
- ******************************************************************************/\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.io.IOException;\r
-import java.io.LineNumberReader;\r
-import java.sql.Connection;\r
-import java.sql.DatabaseMetaData;\r
-import java.sql.DriverManager;\r
-import java.sql.ResultSet;\r
-import java.sql.SQLException;\r
-import java.sql.Statement;\r
-import java.util.HashSet;\r
-import java.util.LinkedList;\r
-import java.util.NoSuchElementException;\r
-import java.util.Properties;\r
-import java.util.Queue;\r
-import java.util.Set;\r
-\r
-/**\r
- * Load the DB JDBC driver, and manage a simple pool of connections to the DB.\r
- *\r
- * @author Robert Eby\r
- * @version $Id$\r
- */\r
-public class DB {\r
-\r
- private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");\r
-\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 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
- * for the server, and attempt to load the JDBC driver for the database. If a fatal error occurs (e.g. either the\r
- * properties file or the DB driver is missing), the JVM will exit.\r
- */\r
- public DB() {\r
- if (props == null) {\r
- props = new Properties();\r
- try {\r
- props.load(new FileInputStream(getProperty(\r
- "org.onap.dmaap.datarouter.provserver.properties",\r
- "/opt/app/datartr/etc/provserver.properties")));\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
- String dbDriver = (String) props.get("org.onap.dmaap.datarouter.db.driver");\r
- Class.forName(dbDriver);\r
- } catch (IOException e) {\r
- intlogger.error("PROV9003 Opening properties: " + e.getMessage(), e);\r
- exit(1);\r
- } catch (ClassNotFoundException e) {\r
- intlogger.error("PROV9004 cannot find the DB driver: " + e);\r
- exit(1);\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * Get the provisioning server properties (loaded from provserver.properties).\r
- *\r
- * @return the Properties object\r
- */\r
- public Properties getProperties() {\r
- return props;\r
- }\r
-\r
- /**\r
- * Get a JDBC connection to the DB from the pool. Creates a new one if none are available.\r
- *\r
- * @return the Connection\r
- */\r
- public Connection getConnection() throws SQLException {\r
- Connection connection = null;\r
- while (connection == null) {\r
- synchronized (queue) {\r
- try {\r
- connection = queue.remove();\r
- } catch (NoSuchElementException ignore) {\r
- int num = 0;\r
- do {\r
- // Try up to 3 times to get a connection\r
- try {\r
- connection = DriverManager.getConnection(dbUrl, dbLogin, dbPassword);\r
- } catch (SQLException sqlEx) {\r
- if (++num >= 3) {\r
- throw sqlEx;\r
- }\r
- }\r
- }\r
- while (connection == null);\r
- }\r
- }\r
- if (connection != null && !connection.isValid(1)) {\r
- connection.close();\r
- connection = null;\r
- }\r
- }\r
- return connection;\r
- }\r
-\r
- /**\r
- * Returns a JDBC connection to the pool.\r
- *\r
- * @param connection the Connection to return\r
- */\r
- public void release(Connection connection) {\r
- if (connection != null) {\r
- synchronized (queue) {\r
- if (!queue.contains(connection)) {\r
- queue.add(connection);\r
- }\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * Run all necessary retrofits required to bring the database up to the level required for this version of the\r
- * provisioning server. This should be run before the server itself is started.\r
- *\r
- * @return true if all retrofits worked, false otherwise\r
- */\r
- public boolean runRetroFits() {\r
- return retroFit1();\r
- }\r
-\r
-\r
- public static String getHttpsPort() {\r
- return httpsPort;\r
- }\r
-\r
- public static String getHttpPort() {\r
- return httpPort;\r
- }\r
-\r
- /**\r
- * Retrofit 1 - Make sure the expected tables are in DB and are initialized. Uses sql_init_01.sql to setup the DB.\r
- *\r
- * @return true if the retrofit worked, false otherwise\r
- */\r
- private boolean retroFit1() {\r
- final String[] expectedTables = {\r
- "FEEDS", "FEED_ENDPOINT_ADDRS", "FEED_ENDPOINT_IDS", "PARAMETERS",\r
- "SUBSCRIPTIONS", "LOG_RECORDS", "INGRESS_ROUTES", "EGRESS_ROUTES",\r
- "NETWORK_ROUTES", "NODESETS", "NODES", "GROUPS"\r
- };\r
- Connection connection = null;\r
- try {\r
- connection = getConnection();\r
- Set<String> actualTables = getTableSet(connection);\r
- boolean initialize = false;\r
- for (String tableName : expectedTables) {\r
- initialize |= !actualTables.contains(tableName);\r
- }\r
- if (initialize) {\r
- intlogger.info("PROV9001: First time startup; The database is being initialized.");\r
- runInitScript(connection, 1);\r
- }\r
- } catch (SQLException e) {\r
- intlogger.error("PROV9000: The database credentials are not working: " + e.getMessage(), e);\r
- return false;\r
- } finally {\r
- if (connection != null) {\r
- release(connection);\r
- }\r
- }\r
- return true;\r
- }\r
-\r
- /**\r
- * Get a set of all table names in the DB.\r
- *\r
- * @param connection a DB connection\r
- * @return the set of table names\r
- */\r
- private Set<String> getTableSet(Connection connection) {\r
- Set<String> tables = new HashSet<>();\r
- try {\r
- DatabaseMetaData md = connection.getMetaData();\r
- ResultSet rs = md.getTables(null, null, "%", null);\r
- if (rs != null) {\r
- while (rs.next()) {\r
- tables.add(rs.getString("TABLE_NAME").toUpperCase());\r
- }\r
- rs.close();\r
- }\r
- } catch (SQLException e) {\r
- intlogger.error("PROV9010: Failed to get TABLE data from DB: " + e.getMessage(), e);\r
- }\r
- return tables;\r
- }\r
-\r
- /**\r
- * Initialize the tables by running the initialization scripts located in the directory specified by the property\r
- * <i>org.onap.dmaap.datarouter.provserver.dbscripts</i>. Scripts have names of the form\r
- * sql_init_NN.sql\r
- *\r
- * @param connection a DB connection\r
- * @param scriptId the number of the sql_init_NN.sql script to run\r
- */\r
- private void runInitScript(Connection connection, int scriptId) {\r
- String scriptDir = (String) props.get("org.onap.dmaap.datarouter.provserver.dbscripts");\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
- executeDdlStatement(statement, strBuilder, line);\r
- }\r
- }\r
- strBuilder.setLength(0);\r
- } catch (Exception e) {\r
- intlogger.error("PROV9002 Error when initializing table: " + e.getMessage(), e);\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 org.json.JSONArray;\r
import org.json.JSONObject;\r
import org.json.JSONTokener;\r
+import org.onap.dmaap.datarouter.provisioning.ProvRunner;\r
\r
/**\r
* This class provides a Command Line Interface for the routing tables in the DR Release 2.0 DB.\r
this.server = server;\r
this.httpclient = new DefaultHttpClient();\r
\r
- Properties provProperties = (new DB()).getProperties();\r
+ Properties provProperties = ProvRunner.getProvProperties();\r
try {\r
AafPropsUtils.init(new File(provProperties.getProperty(\r
"org.onap.dmaap.datarouter.provserver.aafprops.path",\r
import java.util.TreeSet;
import java.util.zip.GZIPInputStream;
import org.onap.dmaap.datarouter.provisioning.BaseServlet;
+import org.onap.dmaap.datarouter.provisioning.ProvRunner;
import org.onap.dmaap.datarouter.provisioning.beans.DeliveryExtraRecord;
import org.onap.dmaap.datarouter.provisioning.beans.DeliveryRecord;
import org.onap.dmaap.datarouter.provisioning.beans.ExpiryRecord;
*/
private static LogfileLoader logfileLoader;
- /**
- * The PreparedStatement which is loaded by a <i>Loadable</i>.
- */
- private static final String INSERT_SQL = "insert into LOG_RECORDS "
- + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
/**
* Each server can assign this many IDs.
*/
private static final long SET_SIZE = (1L << 56);
private final EELFLogger logger;
- private final DB db;
private final String spooldir;
private final long setStart;
private final long setEnd;
private LogfileLoader() {
this.logger = EELFManager.getInstance().getLogger("InternalLog");
- this.db = new DB();
- this.spooldir = db.getProperties().getProperty("org.onap.dmaap.datarouter.provserver.spooldir");
+ this.spooldir = ProvRunner.getProvProperties().getProperty("org.onap.dmaap.datarouter.provserver.spooldir");
this.setStart = getIdRange();
this.setEnd = setStart + SET_SIZE - 1;
this.seqSet = new RLEBitSet();
cutoff *= 86400000L;
logger.debug(" Pruning records older than=" + (cutoff / 86400000L) + " (" + new Date(cutoff) + ")");
- Connection conn = null;
- try {
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
// Limit to a million at a time to avoid typing up the DB for too long.
- conn = db.getConnection();
try (PreparedStatement ps = conn.prepareStatement(
- "DELETE from LOG_RECORDS where EVENT_TIME < ? limit 1000000")) {
+ "DELETE from LOG_RECORDS where EVENT_TIME < ? limit 1000000")) {
ps.setLong(1, cutoff);
while (count > 0) {
if (!ps.execute()) {
}
} catch (SQLException e) {
logger.error("LogfileLoader.pruneRecords: " + e.getMessage(), e);
- } finally {
- db.release(conn);
}
}
return did1;
private long countRecords() {
long count = 0;
- 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);
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();
+ PreparedStatement ps = conn.prepareStatement("SELECT COUNT(*) as COUNT from LOG_RECORDS");
+ ResultSet rs = ps.executeQuery()) {
+ if (rs.next()) {
+ count = rs.getLong("COUNT");
}
} catch (SQLException e) {
logger.error("LogfileLoader.countRecords: " + e.getMessage(), e);
private Map<Long, Long> getHistogram() {
Map<Long, Long> map = new HashMap<>();
- try (Connection conn = db.getConnection();
- Statement stmt = conn.createStatement()) {
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();
+ PreparedStatement ps = conn.prepareStatement(
+ "SELECT FLOOR(EVENT_TIME/86400000) AS DAY, COUNT(*) AS COUNT FROM LOG_RECORDS GROUP BY DAY");
+ ResultSet rs = ps.executeQuery()) {
logger.debug(" LOG_RECORD table histogram...");
- 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);
+ while (rs.next()) {
+ long day = rs.getLong("DAY");
+ long cnt = rs.getLong("COUNT");
+ map.put(day, cnt);
+ logger.debug(" " + day + " " + cnt);
}
} catch (SQLException e) {
logger.error("LogfileLoader.getHistogram: " + e.getMessage(), e);
}
private void initializeNextid() {
- Connection conn = null;
- try {
- conn = db.getConnection();
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
RLEBitSet nbs = new RLEBitSet();
try (Statement stmt = conn.createStatement()) {
// Build a bitset of all records in the LOG_RECORDS table
logger.debug(String.format("LogfileLoader.initializeNextid, next ID is %d (%x)", nextId, nextId));
} catch (SQLException e) {
logger.error("LogfileLoader.initializeNextid: " + e.getMessage(), e);
- } finally {
- db.release(conn);
}
}
int[] process(File file) {
int ok = 0;
int total = 0;
- try {
- Connection conn = db.getConnection();
- PreparedStatement ps = conn.prepareStatement(INSERT_SQL);
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();
+ PreparedStatement ps = conn.prepareStatement(
+ "insert into LOG_RECORDS values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
Reader reader = file.getPath().endsWith(".gz")
? new InputStreamReader(new GZIPInputStream(new FileInputStream(file)))
: new FileReader(file);
total++;
}
}
- ps.close();
- db.release(conn);
} catch (SQLException | IOException e) {
logger.warn("PROV8007 Exception reading " + file + ": " + e);
}
ExpiryRecord expiryRecord = new ExpiryRecord(pp);
if ("other".equals(expiryRecord.getReason())) {
logger.info("Invalid reason '" + pp[9] + "' changed to 'other' for record: "
- + expiryRecord.getPublishId());
+ + expiryRecord.getPublishId());
}
return new Loadable[]{expiryRecord};
}
import javax.crypto.SecretKeyFactory;\r
import javax.crypto.spec.PBEKeySpec;\r
import javax.crypto.spec.PBEParameterSpec;\r
+import org.onap.dmaap.datarouter.provisioning.ProvRunner;\r
\r
/**\r
* The Processing of a Password. Password can be encrypted and decrypted.\r
\r
private static final String SECRET_KEY_FACTORY_TYPE = "PBEWithMD5AndDES";\r
private static final String PASSWORD_ENCRYPTION_STRING =\r
- (new DB()).getProperties().getProperty("org.onap.dmaap.datarouter.provserver.passwordencryption");\r
+ ProvRunner.getProvProperties().getProperty("org.onap.dmaap.datarouter.provserver.passwordencryption");\r
private static final char[] PASSWORD = PASSWORD_ENCRYPTION_STRING.toCharArray();\r
private static final byte[] SALT = {(byte) 0xde, (byte) 0x33, (byte) 0x10,\r
(byte) 0x12, (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,};\r
* *\r
******************************************************************************/\r
\r
-package org.onap.dmaap.datarouter.provisioning;\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 org.json.JSONObject;\r
import org.json.JSONTokener;\r
\r
+import org.onap.dmaap.datarouter.provisioning.ProvRunner;\r
import org.onap.dmaap.datarouter.provisioning.beans.EgressRoute;\r
import org.onap.dmaap.datarouter.provisioning.beans.Feed;\r
import org.onap.dmaap.datarouter.provisioning.beans.Group;\r
import org.onap.dmaap.datarouter.provisioning.beans.NetworkRoute;\r
import org.onap.dmaap.datarouter.provisioning.beans.Parameters;\r
import org.onap.dmaap.datarouter.provisioning.beans.Subscription;\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
+import org.onap.dmaap.datarouter.provisioning.BaseServlet;\r
\r
/**\r
* This class handles the two timers (described in R1 Design Notes), and takes care of issuing the GET to each node of\r
\r
private void pokeNode(final String nodename) {\r
logger.debug("PROV0012 Poking node " + nodename + " ...");\r
- String nodeUrl = String.format(POKE_URL_TEMPLATE, nodename + ":" + DB.getHttpPort());\r
+ String nodeUrl = String.format(POKE_URL_TEMPLATE, nodename + ":" + ProvRunner.getProvProperties().get(\r
+ "org.onap.dmaap.datarouter.provserver.http.port"), "8080");\r
Runnable runn = () -> {\r
try {\r
URL url = new URL(nodeUrl);\r
--- /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 static java.lang.System.exit;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import java.io.File;
+import java.io.FileReader;
+import java.io.LineNumberReader;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+import javax.sql.DataSource;
+import org.apache.commons.dbcp2.BasicDataSource;
+import org.onap.dmaap.datarouter.provisioning.ProvRunner;
+
+public class ProvDbUtils {
+
+ private static EELFLogger intLogger = EELFManager.getInstance().getLogger("InternalLog");
+ private static DataSource dataSource;
+ private static ProvDbUtils provDbUtils;
+
+ private ProvDbUtils() {
+ }
+
+ public static ProvDbUtils getInstance() {
+ if (provDbUtils == null) {
+ try {
+ provDbUtils = new ProvDbUtils();
+ dataSource = setupDataSource(ProvRunner.getProvProperties());
+ } catch (ClassNotFoundException e) {
+ intLogger.error("PROV9010: Failed to load DB Driver Class: " + e.getMessage(), e);
+ exit(1);
+ }
+ }
+ return provDbUtils;
+ }
+
+ private static DataSource setupDataSource(Properties props) throws ClassNotFoundException {
+ intLogger.info("PROV9009: Setting up DB dataSource");
+ Class.forName((String) props.get("org.onap.dmaap.datarouter.db.driver"));
+ BasicDataSource dataSource = new BasicDataSource();
+ dataSource.setUrl((String) props.get("org.onap.dmaap.datarouter.db.url"));
+ dataSource.setUsername((String) props.get("org.onap.dmaap.datarouter.db.login"));
+ dataSource.setPassword((String) props.get("org.onap.dmaap.datarouter.db.password"));
+ dataSource.setMinIdle(5);
+ dataSource.setMaxIdle(15);
+ dataSource.setMaxOpenPreparedStatements(100);
+ return dataSource;
+ }
+
+ public Connection getConnection() throws SQLException {
+ return dataSource.getConnection();
+ }
+
+ public boolean initProvDB() {
+ final String[] expectedTables = {
+ "FEEDS", "FEED_ENDPOINT_ADDRS", "FEED_ENDPOINT_IDS", "PARAMETERS",
+ "SUBSCRIPTIONS", "LOG_RECORDS", "INGRESS_ROUTES", "EGRESS_ROUTES",
+ "NETWORK_ROUTES", "NODESETS", "NODES", "GROUPS"
+ };
+ try (Connection connection = getConnection()) {
+ Set<String> actualTables = getTableSet(connection);
+ boolean initialize = false;
+ for (String tableName : expectedTables) {
+ initialize |= !actualTables.contains(tableName);
+ }
+ if (initialize) {
+ intLogger.info("PROV9001: First time startup; The database is being initialized.");
+ runInitScript(connection, 1);
+ }
+ } catch (SQLException e) {
+ intLogger.error("PROV9000: The database credentials are not working: " + e.getMessage(), e);
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Get a set of all table names in the DB.
+ *
+ * @param connection a DB connection
+ * @return the set of table names
+ */
+ private Set<String> getTableSet(Connection connection) {
+ Set<String> tables = new HashSet<>();
+ try {
+ DatabaseMetaData md = connection.getMetaData();
+ ResultSet rs = md.getTables(null, null, "%", null);
+ if (rs != null) {
+ while (rs.next()) {
+ tables.add(rs.getString("TABLE_NAME").toUpperCase());
+ }
+ rs.close();
+ }
+ } catch (SQLException e) {
+ intLogger.error("PROV9010: Failed to get TABLE data from DB: " + e.getMessage(), e);
+ }
+ return tables;
+ }
+
+ /**
+ * Initialize the tables by running the initialization scripts located in the directory specified by the property
+ * <i>org.onap.dmaap.datarouter.provserver.dbscripts</i>. Scripts have names of the form
+ * sql_init_NN.sql
+ *
+ * @param connection a DB connection
+ * @param scriptId the number of the sql_init_NN.sql script to run
+ */
+ private void runInitScript(Connection connection, int scriptId) {
+ String scriptDir = ProvRunner.getProvProperties().getProperty("org.onap.dmaap.datarouter.provserver.dbscripts");
+ String scriptFile = String.format("%s/sql_init_%02d.sql", scriptDir, scriptId);
+ if (!(new File(scriptFile)).exists()) {
+ intLogger.error("PROV9005 Failed to load sql script from : " + scriptFile);
+ exit(1);
+ }
+ try (LineNumberReader lineReader = new LineNumberReader(new FileReader(scriptFile));
+ Statement statement = connection.createStatement()) {
+ StringBuilder strBuilder = new StringBuilder();
+ String line;
+ while ((line = lineReader.readLine()) != null) {
+ if (!line.startsWith("--")) {
+ line = line.trim();
+ strBuilder.append(line);
+ executeDdlStatement(statement, strBuilder, line);
+ }
+ }
+ strBuilder.setLength(0);
+ } catch (Exception e) {
+ intLogger.error("PROV9002 Error when initializing table: " + e.getMessage(), e);
+ exit(1);
+ }
+ }
+
+
+ private void executeDdlStatement(Statement statement, StringBuilder strBuilder, String line) throws SQLException {
+ if (line.endsWith(";")) {
+ String sql = strBuilder.toString();
+ strBuilder.setLength(0);
+ statement.execute(sql);
+ }
+ }
+}
\ No newline at end of file
import java.util.Objects;\r
import java.util.Properties;\r
import java.util.TimerTask;\r
+import org.onap.dmaap.datarouter.provisioning.ProvRunner;\r
\r
/**\r
* This class provides a {@link TimerTask} that purges old logfiles (older than the number of days specified by the\r
* PurgeLogDirTask constructor.\r
*/\r
public PurgeLogDirTask() {\r
- Properties prop = (new DB()).getProperties();\r
+ Properties prop = ProvRunner.getProvProperties();\r
logdir = prop.getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir");\r
String str = prop.getProperty("org.onap.dmaap.datarouter.provserver.logretention", "30");\r
this.utilsLogger = EELFManager.getInstance().getLogger("UtilsLog");\r
******************************************************************************/
-package org.onap.dmaap.datarouter.provisioning;
+package org.onap.dmaap.datarouter.provisioning.utils;
import static org.onap.dmaap.datarouter.provisioning.BaseServlet.TEXT_CT;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
-
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
-import java.util.Properties;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeSet;
-
import javax.servlet.http.HttpServletResponse;
-
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
+import org.onap.dmaap.datarouter.provisioning.BaseServlet;
+import org.onap.dmaap.datarouter.provisioning.ProvRunner;
import org.onap.dmaap.datarouter.provisioning.beans.EgressRoute;
import org.onap.dmaap.datarouter.provisioning.beans.Feed;
import org.onap.dmaap.datarouter.provisioning.beans.Group;
import org.onap.dmaap.datarouter.provisioning.beans.Parameters;
import org.onap.dmaap.datarouter.provisioning.beans.Subscription;
import org.onap.dmaap.datarouter.provisioning.beans.Syncable;
-import org.onap.dmaap.datarouter.provisioning.utils.AafPropsUtils;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
-import org.onap.dmaap.datarouter.provisioning.utils.LogfileLoader;
-import org.onap.dmaap.datarouter.provisioning.utils.RLEBitSet;
-import org.onap.dmaap.datarouter.provisioning.utils.URLUtilities;
/**
* This class handles synchronization between provisioning servers (PODs). It has three primary functions:
private SynchronizerTask() {
logger = EELFManager.getInstance().getLogger("InternalLog");
rolex = new Timer();
- spooldir = (new DB()).getProperties().getProperty("org.onap.dmaap.datarouter.provserver.spooldir");
+ spooldir = ProvRunner.getProvProperties().getProperty("org.onap.dmaap.datarouter.provserver.spooldir");
podState = UNKNOWN_POD;
doFetch = true; // start off with a fetch
nextsynctime = 0;
try {
// Set up keystore
String type = AafPropsUtils.KEYSTORE_TYPE_PROPERTY;
- String store = Main.aafPropsUtils.getKeystorePathProperty();
- String pass = Main.aafPropsUtils.getKeystorePassProperty();
+ String store = ProvRunner.getAafPropsUtils().getKeystorePathProperty();
+ String pass = ProvRunner.getAafPropsUtils().getKeystorePassProperty();
KeyStore keyStore = KeyStore.getInstance(type);
try (FileInputStream instream = new FileInputStream(new File(store))) {
keyStore.load(instream, pass.toCharArray());
}
// Set up truststore
- store = Main.aafPropsUtils.getTruststorePathProperty();
- pass = Main.aafPropsUtils.getTruststorePassProperty();
+ store = ProvRunner.getAafPropsUtils().getTruststorePathProperty();
+ pass = ProvRunner.getAafPropsUtils().getTruststorePassProperty();
KeyStore trustStore = null;
if (store != null && store.length() > 0) {
trustStore = KeyStore.getInstance(AafPropsUtils.TRUESTSTORE_TYPE_PROPERTY);
// We are connecting with the node name, but the certificate will have the CNAME
// So we need to accept a non-matching certificate name
- String keystorepass = Main.aafPropsUtils.getKeystorePassProperty();
+ String keystorepass = ProvRunner.getAafPropsUtils().getKeystorePassProperty();
try (AbstractHttpClient hc = new DefaultHttpClient()) {
SSLSocketFactory socketFactory =
(trustStore == null)
hc.getConnectionManager().getSchemeRegistry().register(sch);
httpclient = hc;
}
- setSynchTimer(new DB().getProperties().getProperty(
+ setSynchTimer(ProvRunner.getProvProperties().getProperty(
"org.onap.dmaap.datarouter.provserver.sync_interval", "5000"));
} catch (Exception e) {
logger.warn("PROV5005: Problem starting the synchronizer: " + e);
* This method is used to signal that another POD (the active POD) has sent us a /fetchProv request, and that we
* should re-synchronize with the master.
*/
- void doFetch() {
+ public void doFetch() {
doFetch = true;
}
*
* @return the current podState
*/
- int lookupState() {
+ public int lookupState() {
int newPodState = UNKNOWN_POD;
try {
InetAddress myaddr = InetAddress.getLocalHost();
Map<String, Syncable> oldmap = getMap(oldc);
Set<String> union = new TreeSet<>(newmap.keySet());
union.addAll(oldmap.keySet());
- DB db = new DB();
- @SuppressWarnings("resource")
- Connection conn = db.getConnection();
for (String n : union) {
Syncable newobj = newmap.get(n);
Syncable oldobj = oldmap.get(n);
if (oldobj == null) {
- changes = insertRecord(conn, newobj);
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
+ changes = insertRecord(conn, newobj);
+ }
} else if (newobj == null) {
- changes = deleteRecord(conn, oldobj);
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
+ changes = deleteRecord(conn, oldobj);
+ }
} else if (!newobj.equals(oldobj)) {
- changes = updateRecord(conn, newobj, oldobj);
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
+ changes = updateRecord(conn, newobj, oldobj);
+ }
}
}
- db.release(conn);
} catch (SQLException e) {
logger.warn("PROV5009: problem during sync, exception: " + e);
}
*
* @return the bitset
*/
- RLEBitSet readRemoteLoglist() {
+ public RLEBitSet readRemoteLoglist() {
RLEBitSet bs = new RLEBitSet();
String url = URLUtilities.generatePeerLogsURL();
*
* @param bs the bitset (an RELBitSet) of log records to fetch
*/
- void replicateDataRouterLogs(RLEBitSet bs) {
+ public void replicateDataRouterLogs(RLEBitSet bs) {
String url = URLUtilities.generatePeerLogsURL();
HttpPost post = new HttpPost(url);
try {
import java.util.List;\r
import java.util.Map;\r
import java.util.TreeSet;\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
\r
/**\r
* Generate a daily per feed latency report. The report is a .csv file containing the following columns:\r
*/\r
public class DailyLatencyReport extends ReportBase {\r
\r
- private static final String SELECT_SQL =\r
- "select EVENT_TIME, TYPE, PUBLISH_ID, FEED_FILEID, FEEDID, CONTENT_LENGTH from LOG_RECORDS" +\r
- " where EVENT_TIME >= ? and EVENT_TIME <= ?";\r
-\r
private class Job {\r
private long pubtime = 0;\r
private long clen = 0;\r
Map<String, Counters> map = new HashMap<>();\r
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");\r
long start = System.currentTimeMillis();\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- try (PreparedStatement ps = conn.prepareStatement(SELECT_SQL)) {\r
- ps.setLong(1, from);\r
- ps.setLong(2, to);\r
- try (ResultSet rs = ps.executeQuery()) {\r
- while (rs.next()) {\r
- String id = rs.getString("PUBLISH_ID");\r
- int feed = rs.getInt("FEEDID");\r
- long etime = rs.getLong("EVENT_TIME");\r
- String type = rs.getString("TYPE");\r
- String fid = rs.getString("FEED_FILEID");\r
- long clen = rs.getLong("CONTENT_LENGTH");\r
- String date = sdf.format(new Date(getPstart(id)));\r
- String key = date + "," + feed;\r
- Counters c = map.get(key);\r
- if (c == null) {\r
- c = new Counters(date, feed);\r
- map.put(key, c);\r
- }\r
- c.addEvent(etime, type, id, fid, clen);\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(\r
+ "select EVENT_TIME, TYPE, PUBLISH_ID, FEED_FILEID, FEEDID, "\r
+ + "CONTENT_LENGTH from LOG_RECORDS where EVENT_TIME >= ? and EVENT_TIME <= ?")) {\r
+ ps.setLong(1, from);\r
+ ps.setLong(2, to);\r
+ try (ResultSet rs = ps.executeQuery()) {\r
+ while (rs.next()) {\r
+ String id = rs.getString("PUBLISH_ID");\r
+ int feed = rs.getInt("FEEDID");\r
+ long etime = rs.getLong("EVENT_TIME");\r
+ String type = rs.getString("TYPE");\r
+ String fid = rs.getString("FEED_FILEID");\r
+ long clen = rs.getLong("CONTENT_LENGTH");\r
+ String date = sdf.format(new Date(getPstart(id)));\r
+ String key = date + "," + feed;\r
+ Counters c = map.get(key);\r
+ if (c == null) {\r
+ c = new Counters(date, feed);\r
+ map.put(key, c);\r
}\r
+ c.addEvent(etime, type, id, fid, clen);\r
}\r
-\r
- db.release(conn);\r
}\r
} catch (SQLException e) {\r
logger.error("SQLException: " + e.getMessage());\r
import java.util.Calendar;\r
import java.util.Date;\r
import java.util.GregorianCalendar;\r
-\r
import org.json.JSONException;\r
import org.json.JSONObject;\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
\r
/**\r
* Generate a feeds report. The report is a .CSV file.\r
* @version $Id: FeedReport.java,v 1.2 2013/11/06 16:23:55 eby Exp $\r
*/\r
public class FeedReport extends ReportBase {\r
- private static final String SELECT_SQL =\r
- // Note to use the time in the publish_id, use date(from_unixtime(substring(publish_id, 1, 10)))\r
- // To just use month, substring(from_unixtime(event_time div 1000), 1, 7)\r
- "select date(from_unixtime(event_time div 1000)) as date, type, feedid, delivery_subid, count(*) as count" +\r
- " from LOG_RECORDS" +\r
- " where type = 'pub' or type = 'del'" +\r
- " group by date, type, feedid, delivery_subid";\r
- private static final String SELECT_SQL_OLD =\r
- "select PUBLISH_ID, TYPE, FEEDID, DELIVERY_SUBID from LOG_RECORDS where EVENT_TIME >= ? and EVENT_TIME <= ?";\r
\r
@Override\r
public void run() {\r
JSONObject jo = new JSONObject();\r
long start = System.currentTimeMillis();\r
StringBuilder sb = new StringBuilder();\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- try( PreparedStatement ps = conn.prepareStatement(SELECT_SQL)) {\r
- try (ResultSet rs = ps.executeQuery()) {\r
- while (rs.next()) {\r
- String date = rs.getString("date");\r
- String type = rs.getString("type");\r
- int feedid = rs.getInt("feedid");\r
- int subid = type.equals("del") ? rs.getInt("delivery_subid") : 0;\r
- int count = rs.getInt("count");\r
- sb.append(date + "," + type + "," + feedid + "," + subid + "," + count + "\n");\r
- }\r
- }\r
- }\r
- db.release(conn);\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(\r
+ // Note to use the time in the publish_id, use date(from_unixtime(substring(publish_id, 1, 10)))\r
+ // To just use month, substring(from_unixtime(event_time div 1000), 1, 7)\r
+ "select date(from_unixtime(event_time div 1000)) as date, type, feedid, delivery_subid, count(*) "\r
+ + "as count from LOG_RECORDS where type = 'pub' or type = 'del' group by date, type, feedid, delivery_subid")) {\r
+ try (ResultSet rs = ps.executeQuery()) {\r
+ while (rs.next()) {\r
+ String date = rs.getString("date");\r
+ String type = rs.getString("type");\r
+ int feedid = rs.getInt("feedid");\r
+ int subid = type.equals("del") ? rs.getInt("delivery_subid") : 0;\r
+ int count = rs.getInt("count");\r
+ sb.append(date + "," + type + "," + feedid + "," + subid + "," + count + "\n");\r
+ }\r
+ }\r
} catch (SQLException e) {\r
logger.error(e.toString());\r
}\r
JSONObject jo = new JSONObject();\r
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");\r
long start = System.currentTimeMillis();\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- try(PreparedStatement ps = conn.prepareStatement(SELECT_SQL_OLD)) {\r
- ps.setLong(1, from);\r
- ps.setLong(2, to);\r
- ps.setFetchSize(100000);\r
- try(ResultSet rs = ps.executeQuery()) {\r
- while (rs.next()) {\r
- String id = rs.getString("PUBLISH_ID");\r
- String date = sdf.format(new Date(getPstart(id)));\r
- JSONObject datemap = jo.optJSONObject(date);\r
- if (datemap == null) {\r
- datemap = new JSONObject();\r
- jo.put(date, datemap);\r
- }\r
- int feed = rs.getInt("FEEDID");\r
- JSONObject feedmap = datemap.optJSONObject("" + feed);\r
- if (feedmap == null) {\r
- feedmap = new JSONObject();\r
- feedmap.put("pubcount", 0);\r
- datemap.put("" + feed, feedmap);\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(\r
+ "select PUBLISH_ID, TYPE, FEEDID, DELIVERY_SUBID from LOG_RECORDS "\r
+ + "where EVENT_TIME >= ? and EVENT_TIME <= ?")) {\r
+ ps.setLong(1, from);\r
+ ps.setLong(2, to);\r
+ ps.setFetchSize(100000);\r
+ try(ResultSet rs = ps.executeQuery()) {\r
+ while (rs.next()) {\r
+ String id = rs.getString("PUBLISH_ID");\r
+ String date = sdf.format(new Date(getPstart(id)));\r
+ JSONObject datemap = jo.optJSONObject(date);\r
+ if (datemap == null) {\r
+ datemap = new JSONObject();\r
+ jo.put(date, datemap);\r
+ }\r
+ int feed = rs.getInt("FEEDID");\r
+ JSONObject feedmap = datemap.optJSONObject("" + feed);\r
+ if (feedmap == null) {\r
+ feedmap = new JSONObject();\r
+ feedmap.put("pubcount", 0);\r
+ datemap.put("" + feed, feedmap);\r
+ }\r
+ String type = rs.getString("TYPE");\r
+ if (type.equals("pub")) {\r
+ try {\r
+ int n = feedmap.getInt("pubcount");\r
+ feedmap.put("pubcount", n + 1);\r
+ } catch (JSONException e) {\r
+ feedmap.put("pubcount", 1);\r
+ logger.error(e.toString());\r
}\r
- String type = rs.getString("TYPE");\r
- if (type.equals("pub")) {\r
- try {\r
- int n = feedmap.getInt("pubcount");\r
- feedmap.put("pubcount", n + 1);\r
- } catch (JSONException e) {\r
- feedmap.put("pubcount", 1);\r
- logger.error(e.toString());\r
- }\r
- } else if (type.equals("del")) {\r
- String subid = "" + rs.getInt("DELIVERY_SUBID");\r
- try {\r
- int n = feedmap.getInt(subid);\r
- feedmap.put(subid, n + 1);\r
- } catch (JSONException e) {\r
- feedmap.put(subid, 1);\r
- logger.error(e.toString());\r
- }\r
+ } else if (type.equals("del")) {\r
+ String subid = "" + rs.getInt("DELIVERY_SUBID");\r
+ try {\r
+ int n = feedmap.getInt(subid);\r
+ feedmap.put(subid, n + 1);\r
+ } catch (JSONException e) {\r
+ feedmap.put(subid, 1);\r
+ logger.error(e.toString());\r
}\r
}\r
}\r
}\r
- db.release(conn);\r
} catch (SQLException e) {\r
logger.error(e.toString());\r
}\r
String[] feeds = JSONObject.getNames(j2);\r
Arrays.sort(feeds);\r
s.append("<tr><td rowspan=\"" + rc1 + "\">")\r
- .append(date)\r
- .append("</td>");\r
+ .append(date)\r
+ .append("</td>");\r
s.append("<td rowspan=\"" + rc1 + "\">")\r
- .append(feeds.length)\r
- .append("</td>");\r
+ .append(feeds.length)\r
+ .append("</td>");\r
String px1 = "";\r
for (String feed : feeds) {\r
JSONObject j3 = j2.getJSONObject(feed);\r
String[] subs = JSONObject.getNames(j3);\r
Arrays.sort(subs);\r
s.append(px1)\r
- .append("<td rowspan=\"" + rc2 + "\">")\r
- .append(feed)\r
- .append("</td>");\r
+ .append("<td rowspan=\"" + rc2 + "\">")\r
+ .append(feed)\r
+ .append("</td>");\r
s.append("<td rowspan=\"" + rc2 + "\">")\r
- .append(pubcount)\r
- .append("</td>");\r
+ .append(pubcount)\r
+ .append("</td>");\r
s.append("<td rowspan=\"" + rc2 + "\">")\r
- .append(subcnt)\r
- .append("</td>");\r
+ .append(subcnt)\r
+ .append("</td>");\r
String px2 = "";\r
for (String sub : subs) {\r
if (!sub.equals("pubcount")) {\r
import java.sql.SQLException;\r
import java.util.ArrayList;\r
import java.util.List;\r
-\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
\r
/**\r
* Generate a per-file latency report. It reports on the details related to one file published\r
* @version $Id: LatencyReport.java,v 1.1 2013/10/28 18:06:53 eby Exp $\r
*/\r
public class LatencyReport extends ReportBase {\r
- private static final String SELECT_SQL =\r
- "select EVENT_TIME, TYPE, PUBLISH_ID, FEED_FILEID, FEEDID, CONTENT_LENGTH from LOG_RECORDS" +\r
- " where EVENT_TIME >= ? and EVENT_TIME <= ? order by PUBLISH_ID, EVENT_TIME";\r
\r
private class Event {\r
public final String type;\r
feedid = fid;\r
clen = c;\r
fileid = s;\r
- events = new ArrayList<Event>();\r
+ events = new ArrayList<>();\r
}\r
\r
private long pubtime;\r
@Override\r
public void run() {\r
long start = System.currentTimeMillis();\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
- try(PreparedStatement ps = conn.prepareStatement(SELECT_SQL)){\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
+ PreparedStatement ps = conn.prepareStatement(\r
+ "select EVENT_TIME, TYPE, PUBLISH_ID, FEED_FILEID, FEEDID, CONTENT_LENGTH from LOG_RECORDS where "\r
+ + "EVENT_TIME >= ? and EVENT_TIME <= ? order by PUBLISH_ID, EVENT_TIME")) {\r
ps.setLong(1, from);\r
ps.setLong(2, to);\r
try(ResultSet rs = ps.executeQuery()) {\r
- try(PrintWriter os = new PrintWriter(outfile)) {\r
+ try (PrintWriter os = new PrintWriter(outfile)) {\r
os.println("recordid,feedid,uri,size,min,max,avg,fanout");\r
Counters c = null;\r
while (rs.next()) {\r
c.addEvent(type, etime);\r
}\r
}\r
- db.release(conn);\r
- }\r
}\r
} catch (FileNotFoundException e) {\r
System.err.println("File cannot be written: " + outfile);\r
import java.util.HashMap;\r
import java.util.Map;\r
import java.util.TreeSet;\r
-\r
-import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
\r
/**\r
* Generate a subscribers report. The report is a .CSV file. It contains information per-day and per-subscriber,\r
*/\r
public class SubscriberReport extends ReportBase {\r
private static final String SELECT_SQL =\r
- "select date(from_unixtime(EVENT_TIME div 1000)) as DATE, DELIVERY_SUBID, RESULT, COUNT(RESULT) as COUNT" +\r
- " from LOG_RECORDS" +\r
- " where TYPE = 'del' and EVENT_TIME >= ? and EVENT_TIME <= ?" +\r
- " group by DATE, DELIVERY_SUBID, RESULT";\r
+ "select date(from_unixtime(EVENT_TIME div 1000)) as DATE, DELIVERY_SUBID, RESULT, COUNT(RESULT) as COUNT" +\r
+ " from LOG_RECORDS" +\r
+ " where TYPE = 'del' and EVENT_TIME >= ? and EVENT_TIME <= ?" +\r
+ " group by DATE, DELIVERY_SUBID, RESULT";\r
private static final String SELECT_SQL2 =\r
- "select date(from_unixtime(EVENT_TIME div 1000)) as DATE, DELIVERY_SUBID, COUNT(CONTENT_LENGTH_2) as COUNT" +\r
- " from LOG_RECORDS" +\r
- " where TYPE = 'dlx' and CONTENT_LENGTH_2 = -1 and EVENT_TIME >= ? and EVENT_TIME <= ?" +\r
- " group by DATE, DELIVERY_SUBID";\r
+ "select date(from_unixtime(EVENT_TIME div 1000)) as DATE, DELIVERY_SUBID, COUNT(CONTENT_LENGTH_2) as COUNT" +\r
+ " from LOG_RECORDS" +\r
+ " where TYPE = 'dlx' and CONTENT_LENGTH_2 = -1 and EVENT_TIME >= ? and EVENT_TIME <= ?" +\r
+ " group by DATE, DELIVERY_SUBID";\r
\r
private class Counters {\r
private String date;\r
@Override\r
public String toString() {\r
return date + "," + sub + "," +\r
- c100 + "," + c200 + "," + c300 + "," + c400 + "," + c500 + "," +\r
- cm1 + "," + cdlx;\r
+ c100 + "," + c200 + "," + c300 + "," + c400 + "," + c500 + "," +\r
+ cm1 + "," + cdlx;\r
}\r
}\r
\r
@Override\r
public void run() {\r
- Map<String, Counters> map = new HashMap<String, Counters>();\r
+ Map<String, Counters> map = new HashMap<>();\r
long start = System.currentTimeMillis();\r
\r
- try {\r
- DB db = new DB();\r
- @SuppressWarnings("resource")\r
- Connection conn = db.getConnection();\r
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {\r
try(PreparedStatement ps = conn.prepareStatement(SELECT_SQL)) {\r
ps.setLong(1, from);\r
ps.setLong(2, to);\r
}\r
}\r
\r
- try( PreparedStatement ps2 = conn.prepareStatement(SELECT_SQL2)) {\r
- ps2.setLong(1, from);\r
- ps2.setLong(2, to);\r
- try(ResultSet rs2 = ps2.executeQuery()) {\r
- while (rs2.next()) {\r
- String date = rs2.getString("DATE");\r
- int sub = rs2.getInt("DELIVERY_SUBID");\r
- int count = rs2.getInt("COUNT");\r
- String key = date + "," + sub;\r
- Counters c = map.get(key);\r
- if (c == null) {\r
- c = new Counters(date, sub);\r
- map.put(key, c);\r
- }\r
- c.addDlxCount(count);\r
- }\r
- }\r
- }\r
-\r
- db.release(conn);\r
+ try( PreparedStatement ps2 = conn.prepareStatement(SELECT_SQL2)) {\r
+ ps2.setLong(1, from);\r
+ ps2.setLong(2, to);\r
+ try (ResultSet rs2 = ps2.executeQuery()) {\r
+ while (rs2.next()) {\r
+ String date = rs2.getString("DATE");\r
+ int sub = rs2.getInt("DELIVERY_SUBID");\r
+ int count = rs2.getInt("COUNT");\r
+ String key = date + "," + sub;\r
+ Counters c = map.get(key);\r
+ if (c == null) {\r
+ c = new Counters(date, sub);\r
+ map.put(key, c);\r
+ }\r
+ c.addDlxCount(count);\r
+ }\r
+ }\r
+ }\r
} catch (SQLException e) {\r
logger.error("SQLException: " + e.getMessage());\r
}\r
logger.debug("Query time: " + (System.currentTimeMillis() - start) + " ms");\r
- try (PrintWriter os = new PrintWriter(outfile)){\r
+ try (PrintWriter os = new PrintWriter(outfile)) {\r
os.println("date,subid,count100,count200,count300,count400,count500,countminus1,countdlx");\r
- for (String key : new TreeSet<String>(map.keySet())) {\r
+ for (String key : new TreeSet<>(map.keySet())) {\r
Counters c = map.get(key);\r
os.println(c.toString());\r
}\r
package org.onap.dmaap.datarouter.reports;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;
/**
* Generate a traffic volume report. The report is a .csv file containing the following columns:
* @version $Id: VolumeReport.java,v 1.3 2014/02/28 15:11:13 eby Exp $
*/
public class VolumeReport extends ReportBase {
- private static final String SELECT_SQL = "select EVENT_TIME, TYPE, FEEDID, CONTENT_LENGTH, RESULT" +
- " from LOG_RECORDS where EVENT_TIME >= ? and EVENT_TIME <= ? LIMIT ?, ?";
- private EELFLogger loggerVolumeReport= EELFManager.getInstance().getLogger("ReportLog");;
+ private EELFLogger loggerVolumeReport= EELFManager.getInstance().getLogger("ReportLog");
private class Counters {
int filespublished, filesdelivered, filesexpired;
long bytespublished, bytesdelivered, bytesexpired;
@Override
public String toString() {
return String.format("%d,%d,%d,%d,%d,%d",
- filespublished, bytespublished, filesdelivered,
- bytesdelivered, filesexpired, bytesexpired);
+ filespublished, bytespublished, filesdelivered,
+ bytesdelivered, filesexpired, bytesexpired);
}
}
@Override
public void run() {
- Map<String, Counters> map = new HashMap<String, Counters>();
+ Map<String, Counters> map = new HashMap<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
long start = System.currentTimeMillis();
- try {
- DB db = new DB();
- @SuppressWarnings("resource")
- Connection conn = db.getConnection();
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
// We need to run this SELECT in stages, because otherwise we run out of memory!
final long stepsize = 6000000L;
- boolean go_again = true;
- for (long i = 0; go_again; i += stepsize) {
- try (PreparedStatement ps = conn.prepareStatement(SELECT_SQL)) {
+ boolean goAgain = true;
+ for (long i = 0; goAgain; i += stepsize) {
+ try (PreparedStatement ps = conn.prepareStatement(
+ "select EVENT_TIME, TYPE, FEEDID, CONTENT_LENGTH, RESULT from LOG_RECORDS "
+ + "where EVENT_TIME >= ? and EVENT_TIME <= ? LIMIT ?, ?")) {
ps.setLong(1, from);
ps.setLong(2, to);
ps.setLong(3, i);
ps.setLong(4, stepsize);
- try(ResultSet rs = ps.executeQuery()) {
- go_again = false;
+ try (ResultSet rs = ps.executeQuery()) {
+ goAgain = false;
while (rs.next()) {
- go_again = true;
+ goAgain = true;
long etime = rs.getLong("EVENT_TIME");
String type = rs.getString("TYPE");
int feed = rs.getInt("FEEDID");
}
}
}
- }
- catch (SQLException sqlException)
- {
- loggerVolumeReport.error("SqlException",sqlException);
+ } catch (SQLException sqlException) {
+ loggerVolumeReport.error("SqlException", sqlException);
}
}
-
- db.release(conn);
} catch (SQLException e) {
loggerVolumeReport.error("SQLException: " + e.getMessage());
}
for FILE in `find $LIB -name *.jar`; do
CLASSPATH=$CLASSPATH:$FILE
done
-java -classpath $CLASSPATH org.onap.dmaap.datarouter.provisioning.Main
+java -classpath $CLASSPATH org.onap.dmaap.datarouter.provisioning.ProvRunner
runner_file="$LIB/datarouter-prov-jar-with-dependencies.jar"
echo "Starting using" $runner_file
exit 0
fi
echo '0 1 * * * /opt/app/datartr/bin/runreports' | crontab
- nohup java $JAVA_OPTS org.onap.dmaap.datarouter.provisioning.Main </dev/null &
+ nohup java $JAVA_OPTS org.onap.dmaap.datarouter.provisioning.ProvRunner </dev/null &
sleep 5
PIDS=`pids`
if [ "$PIDS" = "" ]
import org.mockito.Mock;
import org.mockito.Mockito;
import org.onap.dmaap.datarouter.authz.AuthorizationResponse;
-import org.onap.dmaap.datarouter.authz.impl.ProvAuthorizer;
import org.onap.dmaap.datarouter.provisioning.StatisticsServlet;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
private static EntityManagerFactory emf;
private static EntityManager em;
- private DB db;
@BeforeClass
public static void init() {
@Before
public void setUp() throws Exception {
- db = new DB();
provAuthorizer = new ProvAuthorizer(statisticsServlet);
}
import java.security.NoSuchAlgorithmException;
import javax.crypto.SecretKeyFactory;
import org.apache.commons.lang3.reflect.FieldUtils;
-import org.jetbrains.annotations.NotNull;
-import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Before;
******************************************************************************/
package org.onap.dmaap.datarouter.provisioning;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.mockito.Mockito.argThat;
+import static org.mockito.Mockito.contains;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER;
+
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
+import java.util.HashSet;
+import java.util.Set;
+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.apache.commons.lang3.reflect.FieldUtils;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.onap.dmaap.datarouter.authz.AuthorizationResponse;
import org.onap.dmaap.datarouter.authz.Authorizer;
import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
+import org.onap.dmaap.datarouter.provisioning.utils.Poker;
import org.powermock.modules.junit4.PowerMockRunner;
-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 java.util.HashSet;
-import java.util.Set;
-
-import static org.hamcrest.Matchers.notNullValue;
-import static org.mockito.Mockito.*;
-import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER;
-
@RunWith(PowerMockRunner.class)
public class DRFeedsServletTest extends DrServletTestBase {
private static DRFeedsServlet drfeedsServlet;
private static EntityManagerFactory emf;
private static EntityManager em;
- private DB db;
@Mock
private HttpServletRequest request;
public void setUp() throws Exception {
listAppender = setTestLogger(DRFeedsServlet.class);
drfeedsServlet = new DRFeedsServlet();
- db = new DB();
setAuthoriserToReturnRequestIsAuthorized();
setPokerToNotCreateTimersWhenDeleteFeedIsCalled();
setupValidAuthorisedRequest();
when(request.getHeader(DRFeedsServlet.EXCLUDE_AAF_HEADER)).thenReturn("true");
JSONObject JSObject = buildRequestJsonObject();
DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "not_stub_name");
jo.put("version", "1.0");
when(request.getHeader(DRFeedsServlet.EXCLUDE_AAF_HEADER)).thenReturn("true");
JSONObject JSObject = buildRequestJsonObject();
DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "not_stub_name");
jo.put("version", "1.0");
FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isCadiEnabled", "true", true);
JSONObject JSObject = buildRequestJsonObject();
DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "not_stub_name");
jo.put("version", "1.0");
FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isCadiEnabled", "true", true);
JSONObject JSObject = buildRequestJsonObject();
DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "not_stub_name");
jo.put("version", "1.0");
JSONObject JSObject = buildRequestJsonObject();
when(request.isUserInRole("org.onap.dmaap-dr.feed|*|create")).thenReturn(true);
DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "not_stub_name");
jo.put("version", "1.0");
throws Exception {
FieldUtils.writeDeclaredStaticField(BaseServlet.class, "maxFeeds", 0, true);
DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
return new JSONObject();
}
};
public void Given_Request_Is_HTTP_POST_And_Feed_Is_Not_Valid_Object_Bad_Request_Response_Is_Generated()
throws Exception {
DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
return new JSONObject();
}
};
when(request.isUserInRole("org.onap.dmaap-dr.feed|*|create")).thenReturn(true);
JSONObject JSObject = buildRequestJsonObject();
DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "AafFeed");
jo.put("version", "v0.1");
JSONObject JSObject = buildRequestJsonObject();
when(request.getHeader(DRFeedsServlet.EXCLUDE_AAF_HEADER)).thenReturn("true");
DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "2.0");
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
+import java.lang.reflect.Field;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.junit.After;
import org.junit.Before;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
+import org.onap.dmaap.datarouter.provisioning.utils.SynchronizerTask;
import org.slf4j.LoggerFactory;
import java.util.Properties;
props.setProperty("org.onap.dmaap.datarouter.provserver.spooldir", "unit-test-logs/spool");
props.setProperty("org.onap.dmaap.datarouter.provserver.https.relaxation", "false");
props.setProperty("org.onap.dmaap.datarouter.provserver.passwordencryption", "PasswordEncryptionKey#@$%^&1234#");
- FieldUtils.writeDeclaredStaticField(DB.class, "props", props, true);
+ FieldUtils.writeDeclaredStaticField(ProvRunner.class, "provProperties", props, true);
FieldUtils.writeDeclaredStaticField(BaseServlet.class, "startmsgFlag", false, true);
SynchronizerTask synchronizerTask = mock(SynchronizerTask.class);
when(synchronizerTask.getPodState()).thenReturn(SynchronizerTask.UNKNOWN_POD);
******************************************************************************/
package org.onap.dmaap.datarouter.provisioning;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.mockito.Mockito.argThat;
+import static org.mockito.Mockito.contains;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER;
+
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.HashSet;
+import java.util.Set;
+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.jetbrains.annotations.NotNull;
import org.json.JSONArray;
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.onap.dmaap.datarouter.provisioning.utils.DB;
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;
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;
-
-import static org.hamcrest.Matchers.notNullValue;
-import static org.mockito.Mockito.*;
-import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER;
-
@RunWith(PowerMockRunner.class)
public class FeedServletTest extends DrServletTestBase {
private static EntityManagerFactory emf;
private static EntityManager em;
- private DB db;
private ListAppender<ILoggingEvent> listAppender;
public void setUp() throws Exception {
listAppender = setTestLogger(FeedServlet.class);
feedServlet = new FeedServlet();
- db = new DB();
setAuthoriserToReturnRequestIsAuthorized();
setUpValidAuthorisedRequest();
setUpValidSecurityOnHttpRequest();
when(request.getInputStream()).thenReturn(inStream);
when(request.getPathInfo()).thenReturn("/2");
FeedServlet feedServlet = new FeedServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
return null;
}
};
public void Given_Request_Is_HTTP_PUT_And_Request_Contains_Invalid_JSON_Then_Bad_Request_Response_Is_Generated() throws Exception {
when(request.getPathInfo()).thenReturn("/2");
FeedServlet feedServlet = new FeedServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
return new JSONObject();
}
};
when(request.getPathInfo()).thenReturn("/2");
JSONObject JSObject = buildRequestJsonObject();
FeedServlet feedServlet = new FeedServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "1.0");
when(request.getPathInfo()).thenReturn("/2");
JSONObject JSObject = buildRequestJsonObject();
FeedServlet feedServlet = new FeedServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "not_stub_name");
jo.put("version", "1.0");
when(request.getPathInfo()).thenReturn("/2");
JSONObject JSObject = buildRequestJsonObject();
FeedServlet feedServlet = new FeedServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "AafFeed");
jo.put("version", "v0.2");
when(request.getPathInfo()).thenReturn("/2");
JSONObject JSObject = buildRequestJsonObject();
FeedServlet feedServlet = new FeedServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "AafFeed");
jo.put("version", "v0.1");
when(request.getPathInfo()).thenReturn("/2");
JSONObject JSObject = buildRequestJsonObject();
FeedServlet feedServlet = new FeedServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "AafFeed");
jo.put("version", "v0.1");
when(request.isUserInRole("org.onap.dmaap-dr.feed|*|edit")).thenReturn(true);
JSONObject JSObject = buildRequestJsonObject();
FeedServlet feedServlet = new FeedServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "AafFeed");
jo.put("version", "v0.1");
when(request.getPathInfo()).thenReturn("/2");
JSONObject JSObject = buildRequestJsonObject();
FeedServlet feedServlet = new FeedServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "AafFeed");
jo.put("version", "v0.1");
when(request.getPathInfo()).thenReturn("/2");
JSONObject JSObject = buildRequestJsonObject();
FeedServlet feedServlet = new FeedServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "AafFeed");
jo.put("version", "v0.1");
feed.setFeedid(1);
feed.setGroupid(1);
feed.setDeleted(false);
- feed.doUpdate(db.getConnection());
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
+ feed.doUpdate(conn);
+ }
}
}
\ No newline at end of file
import org.onap.dmaap.datarouter.authz.Authorizer;
import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
import org.onap.dmaap.datarouter.provisioning.beans.Updateable;
+import org.onap.dmaap.datarouter.provisioning.utils.Poker;
import org.powermock.modules.junit4.PowerMockRunner;
import javax.persistence.EntityManager;
private GroupServlet overideGetJSONFromInputToReturnAnInvalidGroup(Boolean invalidName) {
GroupServlet groupServlet = new GroupServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject invalidGroup = new JSONObject();
String invalidEntry = "groupNameThatIsTooLongTooBeValidgroupNameThatIsTooLongTooBeValid";
invalidEntry = invalidEntry + invalidEntry + invalidEntry + invalidEntry + invalidEntry;
private GroupServlet overideGetJSONFromInputToReturnAValidGroupWithFail() {
GroupServlet groupServlet = new GroupServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject validGroup = new JSONObject();
validGroup.put("name", "groupName");
validGroup.put("groupid", 2);
private GroupServlet overideGetJSONFromInputToReturnGroupInDb() {
GroupServlet groupServlet = new GroupServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject validGroup = new JSONObject();
validGroup.put("name", "Group1");
validGroup.put("groupid", 2);
private GroupServlet overideGetJSONFromInputToReturnNewGroupToInsert() {
GroupServlet groupServlet = new GroupServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject validGroup = new JSONObject();
validGroup.put("name", "Group2");
validGroup.put("groupid", 2);
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.onap.dmaap.datarouter.provisioning.utils.Poker;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
private HttpServletResponse response;
@Mock
- private ServletOutputStream s;
+ private ServletOutputStream servletOutputStream;
- ListAppender<ILoggingEvent> listAppender;
+ private ListAppender<ILoggingEvent> listAppender;
@BeforeClass
public static void init() {
}
@Test
- public void Given_Request_Is_HTTP_GET_And_Is_FeedLog_A_STATUS_OK_Response_Is_Generated()
- throws Exception {
+ public void Given_Request_Is_HTTP_GET_And_Is_FeedLog_A_STATUS_OK_Response_Is_Generated() {
logServlet.doGet(request, response);
verify(response).setStatus(eq(HttpServletResponse.SC_OK));
verifyEnteringExitCalled(listAppender);
}
@Test
- public void Given_Request_Is_GetPublishRecordsForFeed_And_Type_Is_Publish_A_STATUS_OK_Response_Is_Generated()
- throws Exception {
+ public void Given_Request_Is_GetPublishRecordsForFeed_And_Type_Is_Publish_A_STATUS_OK_Response_Is_Generated() {
when(request.getParameter("type")).thenReturn("pub");
when(request.getParameter("expiryReason")).thenReturn(null);
logServlet.doGet(request, response);
when(request.getParameter("filename")).thenReturn("file123");
logServlet.doGet(request, response);
verify(response).setStatus(eq(HttpServletResponse.SC_OK));
- verify(s, times(1)).print("[");
- verify(s, times(1)).print(matches("\n\\{\"statusCode\":204,\"publishId\":\"ID\",\"requestURI\":\"URL/file123\",\"sourceIP\":\"172.0.0.8\",\"method\":\"PUT\",\"contentType\":\"application/vnd.dmaap-dr.log-list; version=1.0\",\"endpointId\":\"user\",\"type\":\"pub\",\"date\":\"2050-05-14T1[6-7]:46:04.422Z\",\"contentLength\":100,\"fileName\":\"file123\"}"));
- verify(s, times(1)).print("[");
+ verify(servletOutputStream, times(1)).print("[");
+ verify(servletOutputStream, times(1)).print(matches("\n\\{\"statusCode\":204,\"publishId\":\"ID\",\"requestURI\":\"URL/file123\",\"sourceIP\":\"172.0.0.8\",\"method\":\"PUT\",\"contentType\":\"application/vnd.dmaap-dr.log-list; version=1.0\",\"endpointId\":\"user\",\"type\":\"pub\",\"date\":\"2050-05-14T1[6-7]:46:04.422Z\",\"contentLength\":100,\"fileName\":\"file123\"}"));
+ verify(servletOutputStream, times(1)).print("[");
}
@Test
when(request.getParameter("filename")).thenReturn("file456");
logServlet.doGet(request, response);
verify(response).setStatus(eq(HttpServletResponse.SC_OK));
- verify(s, times(1)).print("[");
- verify(s, times(0)).print(matches("\n\\{\"statusCode\":204,\"publishId\":\"ID\",\"requestURI\":\"URL/file123\",\"sourceIP\":\"172.0.0.8\",\"method\":\"PUT\",\"contentType\":\"application/vnd.dmaap-dr.log-list; version=1.0\",\"endpointId\":\"user\",\"type\":\"pub\",\"date\":\"2050-05-14T1[6-7]:46:04.422Z\",\"contentLength\":100,\"fileName\":\"file123\"}"));
- verify(s, times(1)).print("[");
+ verify(servletOutputStream, times(1)).print("[");
+ verify(servletOutputStream, times(0)).print(matches("\n\\{\"statusCode\":204,\"publishId\":\"ID\",\"requestURI\":\"URL/file123\",\"sourceIP\":\"172.0.0.8\",\"method\":\"PUT\",\"contentType\":\"application/vnd.dmaap-dr.log-list; version=1.0\",\"endpointId\":\"user\",\"type\":\"pub\",\"date\":\"2050-05-14T1[6-7]:46:04.422Z\",\"contentLength\":100,\"fileName\":\"file123\"}"));
+ verify(servletOutputStream, times(1)).print("[");
}
@Test
when(request.getParameter("expiryReason")).thenReturn("other");
when(request.getParameter("start")).thenReturn("2536159564422");
when(request.getParameter("end")).thenReturn("2536159564422");
- s = mock(ServletOutputStream.class);
- when(response.getOutputStream()).thenReturn(s);
+ servletOutputStream = mock(ServletOutputStream.class);
+ when(response.getOutputStream()).thenReturn(servletOutputStream);
}
}
\ No newline at end of file
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
+import org.onap.dmaap.datarouter.provisioning.utils.SynchronizerTask;
import org.onap.dmaap.datarouter.provisioning.utils.URLUtilities;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.junit.*;
import org.junit.runner.RunWith;
import org.mockito.Mock;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
private static EntityManagerFactory emf;
private static EntityManager em;
- private DB db;
- ListAppender<ILoggingEvent> listAppender;
+ private ListAppender<ILoggingEvent> listAppender;
@BeforeClass
public static void init() {
public void setUp() throws Exception {
listAppender = setTestLogger(PublishServlet.class);
publishServlet = new PublishServlet();
- db = new DB();
+ ProvDbUtils.getInstance().initProvDB();
}
@Test
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.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)
public class StatisticsServletTest {
@Mock
private HttpServletResponse response;
- private DB db;
-
private static EntityManagerFactory emf;
private static EntityManager em;
@Before
public void setUp() throws Exception {
statisticsServlet = new StatisticsServlet();
- db = new DB();
buildRequestParameters();
}
import org.onap.dmaap.datarouter.authz.AuthorizationResponse;
import org.onap.dmaap.datarouter.authz.Authorizer;
import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
+import org.onap.dmaap.datarouter.provisioning.utils.Poker;
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;
import org.powermock.modules.junit4.PowerMockRunner;
private static SubscribeServlet subscribeServlet;
private static EntityManagerFactory emf;
private static EntityManager em;
- private DB db;
@Mock
private HttpServletRequest request;
@Before
public void setUp() throws Exception {
- db = new DB();
+ ProvDbUtils.getInstance().initProvDB();
listAppender = setTestLogger(SubscribeServlet.class);
subscribeServlet = new SubscribeServlet();
setAuthoriserToReturnRequestIsAuthorized();
when(request.getPathInfo()).thenReturn("/1");
JSONObject JSObject = buildRequestJsonObject();
SubscribeServlet subscribeServlet = new SubscribeServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "2.0");
when(request.getPathInfo()).thenReturn("/1");
JSONObject JSObject = buildRequestJsonObject();
SubscribeServlet subscribeServlet = new SubscribeServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "2.0");
when(request.getPathInfo()).thenReturn("/2");
JSONObject JSObject = buildRequestJsonObject();
SubscribeServlet subscribeServlet = new SubscribeServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "2.0");
when(request.getPathInfo()).thenReturn("/2");
JSONObject JSObject = buildRequestJsonObject();
SubscribeServlet subscribeServlet = new SubscribeServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "2.0");
when(request.isUserInRole("org.onap.dmaap-dr.feed|*|approveSub")).thenReturn(true);
JSONObject JSObject = buildRequestJsonObject();
SubscribeServlet subscribeServlet = new SubscribeServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "2.0");
FieldUtils.writeDeclaredStaticField(BaseServlet.class, "maxSubs", 0, true);
when(request.getPathInfo()).thenReturn("/1");
SubscribeServlet subscribeServlet = new SubscribeServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
return new JSONObject();
}
};
when(request.getPathInfo()).thenReturn("/2");
JSONObject JSObject = buildRequestJsonObject();
SubscribeServlet subscribeServlet = new SubscribeServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "2.0");
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
+import java.sql.Connection;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import org.onap.dmaap.datarouter.provisioning.beans.SubDelivery;
import org.onap.dmaap.datarouter.provisioning.beans.Subscription;
import org.onap.dmaap.datarouter.provisioning.beans.Updateable;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
import org.onap.dmaap.datarouter.provisioning.utils.PasswordProcessor;
+import org.onap.dmaap.datarouter.provisioning.utils.Poker;
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
private static EntityManagerFactory emf;
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";
public void setUp() throws Exception {
listAppender = setTestLogger(SubscriptionServlet.class);
subscriptionServlet = new SubscriptionServlet();
- db = new DB();
setAuthoriserToReturnRequestIsAuthorized();
setPokerToNotCreateTimersWhenDeleteSubscriptionIsCalled();
setupValidAuthorisedRequest();
when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
JSONObject JSObject = buildRequestJsonObject();
SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "2.0");
when(request.getPathInfo()).thenReturn("/3");
JSONObject JSObject = buildRequestJsonObject();
SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "2.0");
PowerMockito.mockStatic(PasswordProcessor.class);
JSONObject JSObject = buildRequestJsonObject();
SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "2.0");
public void Given_Request_Is_HTTP_PUT_And_Subscription_Object_Is_Invalid_Bad_Request_Response_Is_Generated() throws Exception {
when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
return jo;
}
when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
JSONObject JSObject = buildRequestJsonObject();
SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "2.0");
when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
JSONObject JSObject = buildRequestJsonObject();
SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "2.0");
PowerMockito.mockStatic(PasswordProcessor.class);
JSONObject JSObject = buildRequestJsonObject();
SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "2.0");
when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription-control; version=1.0");
JSONObject JSObject = buildRequestJsonObject();
SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "2.0");
when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription-control; version=1.0");
JSONObject JSObject = buildRequestJsonObject();
SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
- protected JSONObject getJSONfromInput(HttpServletRequest req) {
+ public JSONObject getJSONfromInput(HttpServletRequest req) {
JSONObject jo = new JSONObject();
jo.put("name", "stub_name");
jo.put("version", "2.0");
subscription.setPrivilegedSubscriber(false);
subscription.setDecompress(false);
subscription.changeOwnerShip();
- subscription.doUpdate(db.getConnection());
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
+ subscription.doUpdate(conn);
+ }
}
private void resetAafSubscriptionInDB() throws SQLException {
subscription.setAafInstance("https://aaf-onap-test.osaaf.org:8095");
subscription.setDecompress(false);
subscription.setPrivilegedSubscriber(false);
- subscription.doUpdate(db.getConnection());
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
+ subscription.doUpdate(conn);
+ }
}
private void addNewSubscriptionInDB() throws SQLException {
subscription.setMetadataOnly(false);
subscription.setSuspended(false);
subscription.setDecompress(false);
- subscription.doInsert(db.getConnection());
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
+ subscription.doInsert(conn);
+ }
}
}
\ No newline at end of file
import org.mockito.Mock;
import org.mockito.Mockito;
import org.onap.dmaap.datarouter.provisioning.utils.RLEBitSet;
+import org.onap.dmaap.datarouter.provisioning.utils.SynchronizerTask;
import org.onap.dmaap.datarouter.provisioning.utils.URLUtilities;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
package org.onap.dmaap.datarouter.provisioning.beans;
+import java.sql.Connection;
import java.sql.SQLException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
private static EntityManagerFactory emf;
private static EntityManager em;
- private DB db;
@BeforeClass
public static void init() {
}
@Before
public void setUp() throws Exception {
- db = new DB();
egressRoute = new EgressRoute(2, 1);
}
public void Verify_EgressRoute_Is_Removed_Successfully() throws SQLException {
Assert.assertEquals(1, EgressRoute.getAllEgressRoutes().size());
EgressRoute egressRoute = new EgressRoute(1, 1);
- egressRoute.doDelete(db.getConnection());
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
+ egressRoute.doDelete(conn);
+ }
Assert.assertEquals(0, EgressRoute.getAllEgressRoutes().size());
}
@Test
- public void Verify_EgressRoute_Is_Updated_Successfully() throws SQLException {
+ public void Verify_EgressRoute_Is_Updated_Successfully() {
EgressRoute egressRoute = new EgressRoute(1, 1);
EgressRoute egressRoute1 = new EgressRoute(1, 1);
Assert.assertEquals(egressRoute.hashCode(), egressRoute1.hashCode());
******************************************************************************/
package org.onap.dmaap.datarouter.provisioning.beans;
-import org.json.JSONObject;
-import org.junit.*;
-import org.junit.runner.RunWith;
-import org.mockito.Mockito;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
-import org.powermock.modules.junit4.PowerMockRunner;
+import static org.mockito.Matchers.anyString;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.Persistence;
-import java.io.InvalidObjectException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-
-import static org.mockito.Matchers.anyString;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import org.json.JSONObject;
+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.mockito.Mockito;
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;
+import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
public class FeedTest {
private static EntityManagerFactory emf;
private static EntityManager em;
private Feed feed;
- private DB db;
+ private ProvDbUtils provDbUtils;
@BeforeClass
public static void init() {
@Before
public void setUp() throws Exception {
- db = new DB();
+ provDbUtils = ProvDbUtils.getInstance();
feed = new Feed("Feed1","v0.1", "First Feed for testing", "First Feed for testing");
feed.setFeedid(1);
feed.setGroupid(1);
@Test
public void Given_getFilteredFeedUrlList_With_Name_Then_Method_Returns_Self_Links() {
- List<String> list= feed.getFilteredFeedUrlList("name","Feed1");
+ List<String> list= Feed.getFilteredFeedUrlList("name","Feed1");
Assert.assertEquals("self_link",list.get(0));
}
@Test
public void Given_getFilteredFeedUrlList_With_Publ_Then_Method_Returns_Self_Links() {
- List<String> list= feed.getFilteredFeedUrlList("publ","pub");
+ List<String> list= Feed.getFilteredFeedUrlList("publ","pub");
Assert.assertEquals("self_link",list.get(0));
}
@Test
public void Given_getFilteredFeedUrlList_With_Subs_Then_Method_Returns_Self_Links() {
- List<String> list= feed.getFilteredFeedUrlList("subs","sub123");
+ List<String> list= Feed.getFilteredFeedUrlList("subs","sub123");
Assert.assertEquals("self_link",list.get(0));
}
@Test
- public void Given_doDelete_Succeeds_Then_doInsert_To_Put_Feed_Back_And_Bool_Is_True() throws SQLException, InvalidObjectException {
- Boolean bool = feed.doDelete(db.getConnection());
+ public void Given_doDelete_Succeeds_Then_doInsert_To_Put_Feed_Back_And_Bool_Is_True() throws SQLException {
+ Boolean bool = feed.doDelete(provDbUtils.getConnection());
Assert.assertEquals(true, bool);
JSONObject jo = new JSONObject();
jo.put("self","self_link");
jo.put("subscribe","subscribe_link");
jo.put("log","log_link");
feed.setLinks(new FeedLinks(jo));
- bool = feed.doInsert(db.getConnection());
+ bool = feed.doInsert(provDbUtils.getConnection());
Assert.assertEquals(true, bool);
}
@Test
public void Given_doInsert_Throws_SQLException_Then_Returns_False() throws SQLException {
- Connection connection = db.getConnection();
+ Connection connection = provDbUtils.getConnection();
FeedAuthorization fa = new FeedAuthorization();
Set setA = new HashSet();
setA.add(new FeedEndpointID("1", "Name"));
@Test
public void Given_IsFeedValid_Called_And_Feed_Exists_Returns_True(){
- Assert.assertEquals(feed.isFeedValid(1), true);
+ Assert.assertTrue(Feed.isFeedValid(1));
}
private Connection CreateSpyForDbConnection() throws SQLException {
- Connection conn = db.getConnection();
+ Connection conn = provDbUtils.getConnection();
return Mockito.spy(conn);
}
}
\ No newline at end of file
******************************************************************************/
package org.onap.dmaap.datarouter.provisioning.beans;
-import org.junit.*;
-import org.junit.runner.RunWith;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
-import org.powermock.modules.junit4.PowerMockRunner;
-
+import java.sql.Connection;
+import java.util.Collection;
+import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
+import org.junit.After;
+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.ProvDbUtils;
+import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
public class GroupTest {
private static EntityManagerFactory emf;
private static EntityManager em;
private Group group;
- private DB db;
+ private ProvDbUtils provDbUtils = ProvDbUtils.getInstance();
@BeforeClass
public static void init() {
@Before
public void setUp() throws Exception {
- db = new DB();
- group = new Group("GroupTest", "", "");
- group.doInsert(db.getConnection());
+ group = new Group("GroupTest", "This group has a description", "");
+ try (Connection conn = provDbUtils.getConnection()) {
+ group.doInsert(conn);
+ }
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ try (Connection conn = provDbUtils.getConnection()) {
+ group.doDelete(conn);
+ }
}
@Test
public void Given_Group_Inserted_With_Same_Name_GetGroupMatching_With_Id_Returns_Correct_Group()
throws Exception {
Group sameGroupName = new Group("GroupTest", "This group has a description", "");
- sameGroupName.doInsert(db.getConnection());
+ sameGroupName.doInsert(provDbUtils.getConnection());
Assert.assertEquals(
"This group has a description", Group.getGroupMatching(group, 2).getDescription());
- sameGroupName.doDelete(db.getConnection());
- }
-
- @Test
- public void Given_Group_Inserted_GetGroupById_Returns_Correct_Group() {
- Assert.assertEquals(group, Group.getGroupById(group.getGroupid()));
+ sameGroupName.doDelete(provDbUtils.getConnection());
}
@Test
public void Given_Group_AuthId_Updated_GetGroupByAuthId_Returns_Correct_Group() throws Exception {
group.setAuthid("Basic TmFtZTp6Z04wMFkyS3gybFppbXltNy94ZDhuMkdEYjA9");
- group.doUpdate(db.getConnection());
+ group.doUpdate(provDbUtils.getConnection());
Assert.assertEquals(group, Group.getGroupByAuthId("Basic TmFtZTp6Z04wMFkyS3gybFppbXltNy94ZDhuMkdEYjA9"));
}
- @After
- public void tearDown() throws Exception {
- group.doDelete(db.getConnection());
+ @Test
+ public void Given_Group_Inserted_GetGroupById_Returns_Correct_Group() {
+ Assert.assertEquals(group, Group.getGroupById(group.getGroupid()));
}
}
Feed feed = mock(Feed.class);
PowerMockito.when(Feed.getFeedById(1)).thenReturn(feed);
Map<String, Integer> map = new HashMap<>();
- FieldUtils.writeDeclaredStaticField(NodeClass.class, "map", map, true);
+ FieldUtils.writeDeclaredStaticField(NodeClass.class, "nodesMap", map, true);
}
@Test
package org.onap.dmaap.datarouter.provisioning.beans;
-import org.junit.*;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
-import org.onap.dmaap.datarouter.provisioning.utils.RLEBitSet;
-
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.Persistence;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
+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.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;
+import org.onap.dmaap.datarouter.provisioning.utils.RLEBitSet;
public class LogRecordTest {
- private LogRecord logRecord;
private static EntityManagerFactory emf;
private static EntityManager em;
- private DB db;
- private static final String INSERT_SQL = "insert into LOG_RECORDS values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
- private PreparedStatement ps;
@BeforeClass
public static void init() {
@Before
public void setUp() throws ParseException, SQLException {
- db = new DB();
- Connection conn = db.getConnection();
- ps = conn.prepareStatement(INSERT_SQL);
+
}
@Test
private void setArgsLoadAndAssertEquals(String type, String s) throws ParseException, SQLException {
String[] args = {"2018-08-29-10-10-10-543.", "LOG", "ID", "1", "URL/file123", "PUT", "application/vnd.dmaap-.log-list; version=1.0", "100", type, "1", "172.0.0.8", "user", "204", "1", "1", "204", "0", "other", "1", "100", "file123"};
- logRecord = new LogRecord(args);
- logRecord.load(ps);
- String compare_string = ps.toString().substring(ps.toString().indexOf("{1:"), ps.toString().indexOf("2:")) + ps.toString().substring(ps.toString().indexOf("3:"));
- Assert.assertEquals(compare_string, s);
+ LogRecord logRecord = new LogRecord(args);
+ try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
+ PreparedStatement ps = conn.prepareStatement(
+ "insert into LOG_RECORDS values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
+ logRecord.load(ps);
+ String compare_string = ps.toString().substring(ps.toString().indexOf("{1:"), ps.toString().indexOf("2:")) + ps
+ .toString().substring(ps.toString().indexOf("3:"));
+ Assert.assertEquals(compare_string, s);
+ }
}
}
package org.onap.dmaap.datarouter.provisioning.beans;
+import java.sql.Connection;
import java.sql.SQLException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.onap.dmaap.datarouter.provisioning.utils.DB;
+import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
public class NetworkRouteTest {
- private NetworkRoute networkRoute;
+ private NetworkRoute networkRoute = new NetworkRoute("node01.","node03.","node02.");
+ private ProvDbUtils provDbUtils = ProvDbUtils.getInstance();
+
private static EntityManagerFactory emf;
private static EntityManager em;
- private DB db;
@BeforeClass
public static void init() {
}
@Before
public void setUp() throws Exception {
- db = new DB();
- networkRoute = new NetworkRoute("node01.","node03.","node02.");
+ try (Connection conn = provDbUtils.getConnection()) {
+ networkRoute.doInsert(conn);
+ }
}
@Test
public void Verify_NetworkRoute_Is_Removed_Successfully() throws SQLException {
+ Assert.assertEquals(2, NetworkRoute.getAllNetworkRoutes().size());
+ networkRoute.doDelete(provDbUtils.getConnection());
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));
+ networkRoute.doUpdate(provDbUtils.getConnection());
for (NetworkRoute net :
NetworkRoute.getAllNetworkRoutes()) {
Assert.assertEquals(5, net.getVianode());
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)
private static EntityManagerFactory emf;
private static EntityManager em;
- private DB db;
@BeforeClass
public static void init() {
}
@Before
public void setUp() throws Exception {
- db = new DB();
subscription = new Subscription();
}
private static EntityManagerFactory emf;
private static EntityManager em;
- private DB db = new DB();
-
@BeforeClass
public static void init() {
emf = Persistence.createEntityManagerFactory("db-unit-tests");
@Test
public void Verify_DB_Is_Initialised_Successfully() {
- Assert.assertTrue(db.runRetroFits());
+ Assert.assertTrue(ProvDbUtils.getInstance().initProvDB());
}
}
<maven.build.timestamp.format>yyyyMMdd'T'HHmmss'Z'</maven.build.timestamp.format>
<!--dependency version across all modules-->
- <jetty.version>9.4.14.v20181114</jetty.version>
+ <jetty.version>9.4.20.v20190813</jetty.version>
<javax.mail-api.version>1.5.5</javax.mail-api.version>
<javax.servlet-api.version>4.0.1</javax.servlet-api.version>
<qos.logback.version>1.2.3</qos.logback.version>