diff options
author | egernug <gerard.nugent@est.tech> | 2019-08-13 08:05:54 +0000 |
---|---|---|
committer | egernug <gerard.nugent@est.tech> | 2019-08-13 08:05:54 +0000 |
commit | 381d4ebc5e83d5fd5b62fff7e5a6fa6d582149d9 (patch) | |
tree | a638df50708e3507e21b2a351e5331259701c570 /datarouter-prov/src/main/java | |
parent | 632e4aaf606ca99ddc5a5cba11deb5e2ee2a90c5 (diff) |
Checkstyle fixes for prov eelf and utils
Change-Id: I54978d8ab828513d280c456149075773442d277a
Issue-ID: DMAAP-1250
Signed-off-by: egernug <gerard.nugent@est.tech>
Diffstat (limited to 'datarouter-prov/src/main/java')
15 files changed, 507 insertions, 398 deletions
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/eelf/DebugTraceFilter.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/eelf/DebugTraceFilter.java index 6bc555e8..f768273e 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/eelf/DebugTraceFilter.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/eelf/DebugTraceFilter.java @@ -17,6 +17,7 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ + package org.onap.dmaap.datarouter.provisioning.eelf; import ch.qos.logback.classic.Level; @@ -27,7 +28,8 @@ import ch.qos.logback.core.spi.FilterReply; public class DebugTraceFilter extends Filter<ILoggingEvent> { @Override public FilterReply decide(ILoggingEvent event) { - if (event.getLoggerName().contains("InternalLog") && (event.getLevel() == Level.DEBUG || event.getLevel() == Level.TRACE) ) { + if (event.getLoggerName().contains("InternalLog") && (event.getLevel() == Level.DEBUG + || event.getLevel() == Level.TRACE) ) { return FilterReply.ACCEPT; } else { return FilterReply.DENY; diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/eelf/EelfMsgs.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/eelf/EelfMsgs.java index b1d856c5..595ce4fe 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/eelf/EelfMsgs.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/eelf/EelfMsgs.java @@ -20,6 +20,7 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
* *
******************************************************************************/
+
package org.onap.dmaap.datarouter.provisioning.eelf;
import com.att.eelf.i18n.EELFResolvableErrorEnum;
@@ -27,19 +28,20 @@ import com.att.eelf.i18n.EELFResourceManager; public enum EelfMsgs implements EELFResolvableErrorEnum {
+
/**
- * Application message prints user (accepts one argument)
+ * Application message prints user (accepts one argument).
*/
MESSAGE_WITH_BEHALF,
/**
- * Application message prints user and FeedID (accepts two arguments)
+ * Application message prints user and FeedID (accepts two arguments).
*/
MESSAGE_WITH_BEHALF_AND_FEEDID,
/**
- * Application message prints user and SUBID (accepts two arguments)
+ * Application message prints user and SUBID (accepts two arguments).
*/
MESSAGE_WITH_BEHALF_AND_SUBID,
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/eelf/JettyFilter.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/eelf/JettyFilter.java index eb8ffe6c..3874f33f 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/eelf/JettyFilter.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/eelf/JettyFilter.java @@ -20,6 +20,7 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
* *
******************************************************************************/
+
package org.onap.dmaap.datarouter.provisioning.eelf;
import ch.qos.logback.classic.spi.ILoggingEvent;
@@ -27,6 +28,7 @@ import ch.qos.logback.core.filter.Filter; import ch.qos.logback.core.spi.FilterReply;
public class JettyFilter extends Filter<ILoggingEvent> {
+
@Override
public FilterReply decide(ILoggingEvent event) {
if (event.getLoggerName().contains("org.eclipse.jetty")) {
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DB.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DB.java index 55b2c038..340b4213 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DB.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DB.java @@ -21,7 +21,6 @@ * *
******************************************************************************/
-
package org.onap.dmaap.datarouter.provisioning.utils;
import static java.lang.System.exit;
@@ -78,12 +77,12 @@ public class DB { props.load(new FileInputStream(getProperty(
"org.onap.dmaap.datarouter.provserver.properties",
"/opt/app/datartr/etc/provserver.properties")));
- String dbDriver = (String) props.get("org.onap.dmaap.datarouter.db.driver");
dbUrl = (String) props.get("org.onap.dmaap.datarouter.db.url");
dbLogin = (String) props.get("org.onap.dmaap.datarouter.db.login");
dbPassword = (String) props.get("org.onap.dmaap.datarouter.db.password");
httpsPort = (String) props.get("org.onap.dmaap.datarouter.provserver.https.port");
httpPort = (String) props.get("org.onap.dmaap.datarouter.provserver.http.port");
+ String dbDriver = (String) props.get("org.onap.dmaap.datarouter.db.driver");
Class.forName(dbDriver);
} catch (IOException e) {
intlogger.error("PROV9003 Opening properties: " + e.getMessage(), e);
@@ -117,17 +116,18 @@ public class DB { connection = queue.remove();
} catch (NoSuchElementException nseEx) {
intlogger.error("PROV9006 No connection on queue: " + nseEx.getMessage(), nseEx);
- int n = 0;
+ int num = 0;
do {
// Try up to 3 times to get a connection
try {
connection = DriverManager.getConnection(dbUrl, dbLogin, dbPassword);
} catch (SQLException sqlEx) {
- if (++n >= 3) {
+ if (++num >= 3) {
throw sqlEx;
}
}
- } while (connection == null);
+ }
+ while (connection == null);
}
}
if (connection != null && !connection.isValid(1)) {
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRProvCadiFilter.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRProvCadiFilter.java index d5521ba8..8301bf9b 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRProvCadiFilter.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRProvCadiFilter.java @@ -18,25 +18,25 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ + package org.onap.dmaap.datarouter.provisioning.utils; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import org.onap.aaf.cadi.PropAccess; -import org.onap.aaf.cadi.filter.CadiFilter; -import org.onap.dmaap.datarouter.provisioning.BaseServlet; -import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord; -import org.onap.dmaap.datarouter.provisioning.beans.Feed; -import org.onap.dmaap.datarouter.provisioning.beans.Subscription; - +import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.filter.CadiFilter; +import org.onap.dmaap.datarouter.provisioning.BaseServlet; +import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord; +import org.onap.dmaap.datarouter.provisioning.beans.Feed; +import org.onap.dmaap.datarouter.provisioning.beans.Subscription; public class DRProvCadiFilter extends CadiFilter { protected static EELFLogger eventlogger = EELFManager.getInstance().getLogger("EventLog"); @@ -48,25 +48,28 @@ public class DRProvCadiFilter extends CadiFilter { } @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; EventLogRecord elr = new EventLogRecord(httpRequest); - String excludeAAF = httpRequest.getHeader(BaseServlet.EXCLUDE_AAF_HEADER);//send this param value as true, if want to add legacy feed/subscriber in AAF env + String excludeAAF = httpRequest.getHeader(BaseServlet.EXCLUDE_AAF_HEADER); + //send this param value as true, if want to add legacy feed/subscriber in AAF env String pathUrl = httpRequest.getServletPath(); - if (!(pathUrl.contains("internal") || - pathUrl.contains("sublog") || - pathUrl.contains("feedlog") || - pathUrl.contains("statistics") || - pathUrl.contains("publish") || - pathUrl.contains("group"))) { + if (!(pathUrl.contains("internal") + || pathUrl.contains("sublog") + || pathUrl.contains("feedlog") + || pathUrl.contains("statistics") + || pathUrl.contains("publish") + || pathUrl.contains("group"))) { String method = httpRequest.getMethod().toUpperCase(); - if (!(method.equals("POST"))) { // if request method is PUT method (publish or Feed update) Needs to check for DELETE + if (!(method.equals("POST"))) { + // if request method is PUT method (publish or Feed update) Needs to check for DELETE if (method.equals("PUT") || method.equals("DELETE")) { - if ((pathUrl.contains("subs"))) {//edit subscriber + if ((pathUrl.contains("subs"))) { //edit subscriber int subId = BaseServlet.getIdFromPath(httpRequest); if (subId <= 0) { String message = String.format("Invalid request URI - %s", httpRequest.getPathInfo()); @@ -76,21 +79,23 @@ public class DRProvCadiFilter extends CadiFilter { httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND, message); return; } - if (isAAFSubscriber(subId)) {//edit AAF Subscriber - String message = String.format("DRProvCadiFilter - Edit AAF Subscriber : %d : AAF Instance - %s", subId, aafInstance); + if (isAAFSubscriber(subId)) { //edit AAF Subscriber + String message = String.format("DRProvCadiFilter - " + + "Edit AAF Subscriber : %d : AAF Instance - %s", subId, aafInstance); elr.setMessage(message); eventlogger.info(elr.toString()); - //request.setAttribute("aafInstance", aafInstance);// no need to set it in request since it is taken care in respective servlets + //request.setAttribute("aafInstance", aafInstance);// + // no need to set it in request since it is taken care in respective servlets super.doFilter(request, response, chain); - } else {//Edit or publish legacy Subscriber + } else { //Edit or publish legacy Subscriber String message = "DRProvCadiFilter - Edit/Publish Legacy Subscriber :" + subId; elr.setMessage(message); eventlogger.info(elr.toString()); chain.doFilter(request, response); } - } else {//edit or publish Feed + } else { //edit or publish Feed int feedId = BaseServlet.getIdFromPath(httpRequest); if (feedId <= 0) { String message = "Invalid request URI - " + httpRequest.getPathInfo(); @@ -101,28 +106,30 @@ public class DRProvCadiFilter extends CadiFilter { return; } - if (isAAFFeed(feedId)) {//edit AAF Feed - String message = "DRProvCadiFilter - Edit AAF Feed:" + feedId + ":" + "AAF Instance -" + aafInstance; + if (isAAFFeed(feedId)) { //edit AAF Feed + String message = "DRProvCadiFilter - Edit AAF Feed:" + + feedId + ":" + "AAF Instance -" + aafInstance; elr.setMessage(message); eventlogger.info(elr.toString()); super.doFilter(request, response, chain); - } else {//Edit or publish legacy Feed + } else { //Edit or publish legacy Feed String message = "DRProvCadiFilter - Edit/Publish Legacy Feed:" + feedId; elr.setMessage(message); eventlogger.info(elr.toString()); chain.doFilter(request, response); } } - } else {// in all other cases defaults to legacy behavior - String message = "DRProvCadiFilter - Default Legacy Feed/Subscriber URI -:" + httpRequest.getPathInfo(); + } else { // in all other cases defaults to legacy behavior + String message = "DRProvCadiFilter - Default Legacy Feed/Subscriber URI -:" + + httpRequest.getPathInfo(); elr.setMessage(message); eventlogger.info(elr.toString()); chain.doFilter(request, response); } } else { //check to add legacy/AAF subscriber - if ((pathUrl.contains("subscribe"))) {//add subscriber + if ((pathUrl.contains("subscribe"))) { //add subscriber int feedId = BaseServlet.getIdFromPath(httpRequest); if (feedId <= 0) { String message = "Invalid request URI - " + httpRequest.getPathInfo(); @@ -132,47 +139,52 @@ public class DRProvCadiFilter extends CadiFilter { httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND, message); return; } - if (isAAFFeed(feedId)) {//check if AAF Feed or legacy to add new subscriber + if (isAAFFeed(feedId)) { //check if AAF Feed or legacy to add new subscriber if (excludeAAF == null) { - String message = "DRProvCadiFilter -Invalid request Header Parmeter " + BaseServlet.EXCLUDE_AAF_HEADER + " = " + httpRequest.getHeader(BaseServlet.EXCLUDE_AAF_HEADER); + String message = "DRProvCadiFilter -Invalid request Header Parmeter " + + BaseServlet.EXCLUDE_AAF_HEADER + + " = " + httpRequest.getHeader(BaseServlet.EXCLUDE_AAF_HEADER); elr.setMessage(message); elr.setResult(HttpServletResponse.SC_BAD_REQUEST); eventlogger.error(elr.toString()); httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, message); return; } - if (excludeAAF.equalsIgnoreCase("true")) {//Check to add legacy subscriber to AAF Feed + if (excludeAAF.equalsIgnoreCase("true")) { //Check to add legacy subscriber to AAF Feed String message = "DRProvCadiFilter - add legacy subscriber to AAF Feed, FeedID:" + feedId; elr.setMessage(message); eventlogger.info(elr.toString()); chain.doFilter(request, response); } else { - String message = "DRProvCadiFilter - Add AAF subscriber to AAF Feed, FeedID:" + feedId + ":" + "AAF Instance -" + aafInstance; + String message = "DRProvCadiFilter - Add AAF subscriber to AAF Feed, FeedID:" + + feedId + ":" + "AAF Instance -" + aafInstance; elr.setMessage(message); eventlogger.info(elr.toString()); super.doFilter(request, response, chain); } - } else {//Add legacy susbcriber to legacy Feed + } else { //Add legacy susbcriber to legacy Feed String message = "DRProvCadiFilter - add legacy subscriber to legacy Feed:" + feedId; elr.setMessage(message); eventlogger.info(elr.toString()); chain.doFilter(request, response); } - } else {//add AAF feed + } else { //add AAF feed if (excludeAAF == null) { - String message = "DRProvCadiFilter -Invalid request Header Parmeter " + BaseServlet.EXCLUDE_AAF_HEADER + " = " + httpRequest.getHeader(BaseServlet.EXCLUDE_AAF_HEADER); + String message = "DRProvCadiFilter -Invalid request Header Parmeter " + + BaseServlet.EXCLUDE_AAF_HEADER + + " = " + httpRequest.getHeader(BaseServlet.EXCLUDE_AAF_HEADER); elr.setMessage(message); elr.setResult(HttpServletResponse.SC_BAD_REQUEST); eventlogger.error(elr.toString()); httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, message); return; } - if (excludeAAF.equalsIgnoreCase("true")) {//add legacy feed + if (excludeAAF.equalsIgnoreCase("true")) { //add legacy feed String message = "DRProvCadiFilter - Create new legacy Feed : EXCLUDE_AAF = " + excludeAAF; elr.setMessage(message); eventlogger.info(elr.toString()); chain.doFilter(request, response); - } else {//add AAF Feed + } else { //add AAF Feed String message = "DRProvCadiFilter - Create new AAF Feed : EXCLUDE_AAF = " + excludeAAF; elr.setMessage(message); eventlogger.info(elr.toString()); @@ -197,7 +209,8 @@ public class DRProvCadiFilter extends CadiFilter { try { Feed feed = Feed.getFeedById(feedId); if (feed != null) { - if (!((feed.getAafInstance().equalsIgnoreCase("legacy")) || feed.getAafInstance() == null || feed.getAafInstance().equals(""))) { //also apply null check and empty check too + if (!((feed.getAafInstance().equalsIgnoreCase("legacy")) || feed.getAafInstance() == null + || feed.getAafInstance().equals(""))) { //also apply null check and empty check too aafInstance = feed.getAafInstance(); String message = "DRProvCadiFilter.isAAFFeed: aafInstance-:" + aafInstance + "; feedId:- " + feedId; intlogger.debug(message); @@ -228,9 +241,12 @@ public class DRProvCadiFilter extends CadiFilter { try { Subscription subscriber = Subscription.getSubscriptionById(subId); if (subscriber != null) { - if (!((subscriber.getAafInstance().equalsIgnoreCase("legacy")) || subscriber.getAafInstance() == null || subscriber.getAafInstance().equals(""))) { //also apply null check and empty check too + if (!((subscriber.getAafInstance().equalsIgnoreCase("legacy")) + || subscriber.getAafInstance() == null + || subscriber.getAafInstance().equals(""))) { //also apply null check and empty check too aafInstance = subscriber.getAafInstance(); - String message = "DRProvCadiFilter.isAAFSubscriber: aafInstance-:" + aafInstance + "; subId:- " + subId; + String message = "DRProvCadiFilter.isAAFSubscriber: aafInstance-:" + aafInstance + "; subId:- " + + subId; intlogger.debug(message); return true; } else { diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java index a593c8a7..867d1163 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java @@ -21,7 +21,6 @@ * *
******************************************************************************/
-
package org.onap.dmaap.datarouter.provisioning.utils;
import com.att.eelf.configuration.EELFLogger;
@@ -77,10 +76,11 @@ public class DRRouteCLI { String server = System.getenv(ENV_VAR);
if (args.length >= 2 && args[0].equals("-s")) {
server = args[1];
- String[] t = new String[args.length - 2];
- if (t.length > 0)
- System.arraycopy(args, 2, t, 0, t.length);
- args = t;
+ String[] str = new String[args.length - 2];
+ if (str.length > 0) {
+ System.arraycopy(args, 2, str, 0, str.length);
+ }
+ args = str;
}
if (server == null || server.equals("")) {
System.err.println("dr-route: you need to specify a server, either via $PROVSRVR or the '-s' option.");
@@ -88,8 +88,8 @@ public class DRRouteCLI { }
DRRouteCLI cli = new DRRouteCLI(server);
if (args.length > 0) {
- boolean b = cli.runCommand(args);
- System.exit(b ? 0 : 1);
+ boolean bool = cli.runCommand(args);
+ System.exit(bool ? 0 : 1);
} else {
cli.interactive();
System.exit(0);
@@ -109,29 +109,30 @@ public class DRRouteCLI { * Create a DRRouteCLI object connecting to the specified server.
*
* @param server the server to send command to
- * @throws Exception
+ * @throws Exception generic exception
*/
public DRRouteCLI(String server) throws Exception {
this.server = server;
this.width = 120;
this.httpclient = new DefaultHttpClient();
- Properties p = (new DB()).getProperties();
- String truststore_file = p.getProperty("org.onap.dmaap.datarouter.provserver.truststore.path");
- String truststore_pw = p.getProperty("org.onap.dmaap.datarouter.provserver.truststore.password");
+ Properties prop = (new DB()).getProperties();
+ String truststoreFile = prop.getProperty("org.onap.dmaap.datarouter.provserver.truststore.path");
+ String truststorePw = prop.getProperty("org.onap.dmaap.datarouter.provserver.truststore.password");
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
- if (truststore_file == null || truststore_file.equals("")) {
+ if (truststoreFile == null || truststoreFile.equals("")) {
String jhome = System.getenv("JAVA_HOME");
- if (jhome == null || jhome.equals(""))
+ if (jhome == null || jhome.equals("")) {
jhome = "/opt/java/jdk/jdk180";
- truststore_file = jhome + DEFAULT_TRUSTSTORE_PATH;
+ }
+ truststoreFile = jhome + DEFAULT_TRUSTSTORE_PATH;
}
- File f = new File(truststore_file);
- if (f.exists()) {
- FileInputStream instream = new FileInputStream(f);
+ File file = new File(truststoreFile);
+ if (file.exists()) {
+ FileInputStream instream = new FileInputStream(file);
try {
- trustStore.load(instream, truststore_pw.toCharArray());
+ trustStore.load(instream, truststorePw.toCharArray());
} catch (Exception x) {
intlogger.error("Problem reading truststore: " + x.getMessage(), x);
throw x;
@@ -154,16 +155,20 @@ public class DRRouteCLI { while (true) {
System.out.print(PROMPT);
String line = in.readLine();
- if (line == null)
+ if (line == null) {
return;
+ }
line = line.trim();
- if (line.equalsIgnoreCase("exit")) // "exit" may only be used in interactive mode
+ if (line.equalsIgnoreCase("exit")) { // "exit" may only be used in interactive mode
return;
- if (line.equalsIgnoreCase("quit")) // "quit" may only be used in interactive mode
+ }
+ if (line.equalsIgnoreCase("quit")) { // "quit" may only be used in interactive mode
return;
+ }
String[] args = line.split("[ \t]+");
- if (args.length > 0)
+ if (args.length > 0) {
runCommand(args);
+ }
}
}
@@ -242,8 +247,9 @@ public class DRRouteCLI { private boolean addIngress(String[] args) {
String url = String.format("https://%s/internal/route/ingress/?feed=%s&user=%s&subnet=%s&nodepatt=%s", server, args[2], args[3], args[4], args[5]);
- if (args.length > 6)
+ if (args.length > 6) {
url += "&seq=" + args[6];
+ }
return doPost(url);
}
@@ -285,31 +291,40 @@ public class DRRouteCLI { if (tbl.startsWith("al") || tbl.startsWith("in")) {
// Display the IRT
JSONArray irt = jo.optJSONArray("ingress");
- int cw1 = 6, cw2 = 6, cw3 = 6, cw4 = 6; // determine column widths for first 4 cols
+ int cw1 = 6;
+ int cw2 = 6;
+ int cw3 = 6;
+ int cw4 = 6; // determine column widths for first 4 cols
for (int i = 0; irt != null && i < irt.length(); i++) {
- JSONObject e = irt.getJSONObject(i);
- cw1 = Math.max(cw1, ("" + e.getInt("seq")).length());
- cw2 = Math.max(cw2, ("" + e.getInt("feedid")).length());
- String t = e.optString("user");
- cw3 = Math.max(cw3, (t == null) ? 1 : t.length());
- t = e.optString("subnet");
- cw4 = Math.max(cw4, (t == null) ? 1 : t.length());
+ JSONObject jsonObject = irt.getJSONObject(i);
+ cw1 = Math.max(cw1, ("" + jsonObject.getInt("seq")).length());
+ cw2 = Math.max(cw2, ("" + jsonObject.getInt("feedid")).length());
+ String str = jsonObject.optString("user");
+ cw3 = Math.max(cw3, (str == null) ? 1 : str.length());
+ str = jsonObject.optString("subnet");
+ cw4 = Math.max(cw4, (str == null) ? 1 : str.length());
}
int nblank = cw1 + cw2 + cw3 + cw4 + 8;
sb.append("Ingress Routing Table\n");
- sb.append(String.format("%s %s %s %s Nodes\n", ext("Seq", cw1), ext("FeedID", cw2), ext("User", cw3), ext("Subnet", cw4)));
+ sb.append(String.format("%s %s %s %s Nodes\n", ext("Seq", cw1),
+ ext("FeedID", cw2), ext("User", cw3), ext("Subnet", cw4)));
for (int i = 0; irt != null && i < irt.length(); i++) {
- JSONObject e = irt.getJSONObject(i);
- String seq = "" + e.getInt("seq");
- String feedid = "" + e.getInt("feedid");
- String user = e.optString("user");
- String subnet = e.optString("subnet");
- if (user.equals("")) user = "-";
- if (subnet.equals("")) subnet = "-";
- JSONArray nodes = e.getJSONArray("node");
+ JSONObject jsonObject = irt.getJSONObject(i);
+ String seq = "" + jsonObject.getInt("seq");
+ String feedid = "" + jsonObject.getInt("feedid");
+ String user = jsonObject.optString("user");
+ String subnet = jsonObject.optString("subnet");
+ if (user.equals("")) {
+ user = "-";
+ }
+ if (subnet.equals("")) {
+ subnet = "-";
+ }
+ JSONArray nodes = jsonObject.getJSONArray("node");
int sol = sb.length();
- sb.append(String.format("%s %s %s %s ", ext(seq, cw1), ext(feedid, cw2), ext(user, cw3), ext(subnet, cw4)));
+ sb.append(String.format("%s %s %s %s ", ext(seq, cw1),
+ ext(feedid, cw2), ext(user, cw3), ext(subnet, cw4)));
for (int j = 0; j < nodes.length(); j++) {
String nd = nodes.getString(j);
int cursor = sb.length() - sol;
@@ -330,20 +345,22 @@ public class DRRouteCLI { // Display the ERT
JSONObject ert = jo.optJSONObject("egress");
String[] subs = (ert == null) ? new String[0] : JSONObject.getNames(ert);
- if (subs == null)
+ if (subs == null) {
subs = new String[0];
+ }
Arrays.sort(subs);
int cw1 = 5;
for (int i = 0; i < subs.length; i++) {
cw1 = Math.max(cw1, subs[i].length());
}
- if (sb.length() > 0)
+ if (sb.length() > 0) {
sb.append("\n");
+ }
sb.append("Egress Routing Table\n");
sb.append(String.format("%s Node\n", ext("SubID", cw1)));
for (int i = 0; i < subs.length; i++) {
- if(ert!=null&&ert.length()!=0) {
+ if (ert != null && ert.length() != 0 ) {
String node = ert.getString(subs[i]);
sb.append(String.format("%s %s\n", ext(subs[i], cw1), node));
}
@@ -353,24 +370,26 @@ public class DRRouteCLI { if (tbl.startsWith("al") || tbl.startsWith("ne")) {
// Display the NRT
JSONArray nrt = jo.optJSONArray("routing");
- int cw1 = 4, cw2 = 4;
+ int cw1 = 4;
+ int cw2 = 4;
for (int i = 0; nrt != null && i < nrt.length(); i++) {
- JSONObject e = nrt.getJSONObject(i);
- String from = e.getString("from");
- String to = e.getString("to");
+ JSONObject jsonObject = nrt.getJSONObject(i);
+ String from = jsonObject.getString("from");
+ String to = jsonObject.getString("to");
cw1 = Math.max(cw1, from.length());
cw2 = Math.max(cw2, to.length());
}
- if (sb.length() > 0)
+ if (sb.length() > 0) {
sb.append("\n");
+ }
sb.append("Network Routing Table\n");
sb.append(String.format("%s %s Via\n", ext("From", cw1), ext("To", cw2)));
for (int i = 0; nrt != null && i < nrt.length(); i++) {
- JSONObject e = nrt.getJSONObject(i);
- String from = e.getString("from");
- String to = e.getString("to");
- String via = e.getString("via");
+ JSONObject jsonObject = nrt.getJSONObject(i);
+ String from = jsonObject.getString("from");
+ String to = jsonObject.getString("to");
+ String via = jsonObject.getString("via");
sb.append(String.format("%s %s %s\n", ext(from, cw1), ext(to, cw2), via));
}
}
@@ -378,12 +397,14 @@ public class DRRouteCLI { return true;
}
- private String ext(String s, int n) {
- if (s == null)
- s = "-";
- while (s.length() < n)
- s += " ";
- return s;
+ private String ext(String str, int num) {
+ if (str == null) {
+ str = "-";
+ }
+ while (str.length() < num) {
+ str += " ";
+ }
+ return str;
}
private boolean doDelete(String url) {
@@ -454,18 +475,20 @@ public class DRRouteCLI { // Look for and print only the part of the output between <pre>...</pre>
InputStream is = entity.getContent();
StringBuilder sb = new StringBuilder();
- byte[] b = new byte[512];
- int n = 0;
- while ((n = is.read(b)) > 0) {
- sb.append(new String(b, 0, n));
+ byte[] bite = new byte[512];
+ int num = 0;
+ while ((num = is.read(bite)) > 0) {
+ sb.append(new String(bite, 0, num));
}
is.close();
int ix = sb.indexOf("<pre>");
- if (ix > 0)
+ if (ix > 0) {
sb.delete(0, ix + 5);
+ }
ix = sb.indexOf("</pre>");
- if (ix > 0)
+ if (ix > 0) {
sb.delete(ix, sb.length());
+ }
System.err.println(sb.toString());
}
}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/HttpServletUtils.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/HttpServletUtils.java index f59dc919..ebd09127 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/HttpServletUtils.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/HttpServletUtils.java @@ -33,7 +33,15 @@ public class HttpServletUtils { } - public static void sendResponseError(HttpServletResponse response, int errorCode, String message, EELFLogger intlogger) { + /** + * Send response error. + * @param response HttpServletResponse + * @param errorCode errorcode int + * @param message String message + * @param intlogger Logger + */ + public static void sendResponseError(HttpServletResponse response, + int errorCode, String message, EELFLogger intlogger) { try { response.sendError(errorCode, message); } catch (IOException ioe) { diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/JSONUtilities.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/JSONUtilities.java index 9abd5a83..f773599d 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/JSONUtilities.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/JSONUtilities.java @@ -21,7 +21,6 @@ * *
******************************************************************************/
-
package org.onap.dmaap.datarouter.provisioning.utils;
import com.att.eelf.configuration.EELFLogger;
@@ -43,24 +42,27 @@ public class JSONUtilities { private JSONUtilities(){
}
+
/**
* Does the String <i>v</i> represent a valid Internet address (with or without a
* mask length appended).
*
- * @param v the string to check
+ * @param str the string to check
* @return true if valid, false otherwise
*/
- public static boolean validIPAddrOrSubnet(String v) {
- String[] pp = {v, ""};
- if (v.indexOf('/') > 0)
- pp = v.split("/");
+ public static boolean validIPAddrOrSubnet(String str) {
+ String[] pp = {str, ""};
+ if (str.indexOf('/') > 0) {
+ pp = str.split("/");
+ }
try {
InetAddress addr = InetAddress.getByName(pp[0]);
if (pp[1].length() > 0) {
// check subnet mask
int mask = Integer.parseInt(pp[1]);
- if (mask > (addr.getAddress().length * 8))
+ if (mask > (addr.getAddress().length * 8)) {
return false;
+ }
}
return true;
} catch (UnknownHostException e) {
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LOGJSONObject.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LOGJSONObject.java index bc1f4493..0f955234 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LOGJSONObject.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LOGJSONObject.java @@ -57,22 +57,22 @@ import org.json.JSONTokener; * returns a value if one can be found, and throws an exception if one cannot be * found. An <code>opt</code> method returns a default value instead of throwing * an exception, and so is useful for obtaining optional values. - * <p> - * The generic <code>get()</code> and <code>opt()</code> methods return an + * + * <p>The generic <code>get()</code> and <code>opt()</code> methods return an * object, which you can cast or query for type. There are also typed * <code>get</code> and <code>opt</code> methods that do type checking and type * coercion for you. The opt methods differ from the get methods in that they do * not throw. Instead, they return a specified value, such as null. - * <p> - * The <code>put</code> methods add or replace values in an object. For example, + * + * <p>The <code>put</code> methods add or replace values in an object. For example, * * <pre> * myString = new JSONObject().put("JSON", "Hello, World!").toString(); * </pre> - * <p> - * produces the string <code>{"JSON": "Hello, World"}</code>. - * <p> - * The texts produced by the <code>toString</code> methods strictly conform to + * + * <p>* produces the string <code>{"JSON": "Hello, World"}</code>. + * + * <p>The texts produced by the <code>toString</code> methods strictly conform to * the JSON syntax rules. The constructors are more forgiving in the texts they * will accept: * <ul> @@ -95,6 +95,7 @@ import org.json.JSONTokener; * @author JSON.org * @version 2012-12-01 */ + public class LOGJSONObject { /** @@ -146,8 +147,8 @@ public class LOGJSONObject { * Returns a hash code value for the object. This method is * supported for the benefit of hash tables such as those provided by * {@link HashMap}. - * <p> - * The general contract of {@code hashCode} is: + * + * <p>* The general contract of {@code hashCode} is: * <ul> * <li>Whenever it is invoked on the same object more than once during * an execution of a Java application, the {@code hashCode} method @@ -165,8 +166,8 @@ public class LOGJSONObject { * programmer should be aware that producing distinct integer results * for unequal objects may improve the performance of hash tables. * </ul> - * <p> - * As much as is reasonably practical, the hashCode method defined by + * + * <p>* As much as is reasonably practical, the hashCode method defined by * class {@code Object} does return distinct integers for distinct * objects. (This is typically implemented by converting the internal * address of the object into an integer, but this implementation @@ -234,56 +235,56 @@ public class LOGJSONObject { /** * Construct a JSONObject from a JSONTokener. * - * @param x A JSONTokener object containing the source string. + * @param tokener A JSONTokener object containing the source string. * @throws JSONException If there is a syntax error in the source string * or a duplicated key. */ - public LOGJSONObject(JSONTokener x) { + public LOGJSONObject(JSONTokener tokener) { this(); - char c; + char chr; String key; - if (x.nextClean() != '{') { - throw x.syntaxError("A JSONObject text must begin with '{'"); + if (tokener.nextClean() != '{') { + throw tokener.syntaxError("A JSONObject text must begin with '{'"); } for (; ; ) { - c = x.nextClean(); - switch (c) { + chr = tokener.nextClean(); + switch (chr) { case 0: - throw x.syntaxError("A JSONObject text must end with '}'"); + throw tokener.syntaxError("A JSONObject text must end with '}'"); case '}': return; default: - x.back(); - key = x.nextValue().toString(); + tokener.back(); + key = tokener.nextValue().toString(); } -// The key is followed by ':'. We will also tolerate '=' or '=>'. + // The key is followed by ':'. We will also tolerate '=' or '=>'. - c = x.nextClean(); - if (c == '=') { - if (x.next() != '>') { - x.back(); + chr = tokener.nextClean(); + if (chr == '=') { + if (tokener.next() != '>') { + tokener.back(); } - } else if (c != ':') { - throw x.syntaxError("Expected a ':' after a key"); + } else if (chr != ':') { + throw tokener.syntaxError("Expected a ':' after a key"); } - this.putOnce(key, x.nextValue()); + this.putOnce(key, tokener.nextValue()); -// Pairs are separated by ','. We will also tolerate ';'. + // Pairs are separated by ','. We will also tolerate ';'. - switch (x.nextClean()) { + switch (tokener.nextClean()) { case ';': case ',': - if (x.nextClean() == '}') { + if (tokener.nextClean() == '}') { return; } - x.back(); + tokener.back(); break; case '}': return; default: - throw x.syntaxError("Expected a ',' or '}'"); + throw tokener.syntaxError("Expected a ',' or '}'"); } } } @@ -293,17 +294,17 @@ public class LOGJSONObject { * * @param map A map object that can be used to initialize the contents of * the JSONObject. - * @throws JSONException + * @throws JSONException json exception */ public LOGJSONObject(Map<String, Object> map) { this.map = new LinkedHashMap<>(); if (map != null) { - Iterator<Map.Entry<String, Object>> i = map.entrySet().iterator(); - while (i.hasNext()) { - Map.Entry<String, Object> e = i.next(); - Object value = e.getValue(); + Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry<String, Object> entry = iterator.next(); + Object value = entry.getValue(); if (value != null) { - this.map.put(e.getKey(), wrap(value)); + this.map.put(entry.getKey(), wrap(value)); } } } @@ -316,12 +317,12 @@ public class LOGJSONObject { * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter, * the method is invoked, and a key and the value returned from the getter method * are put into the new JSONObject. - * <p> - * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. + * + * <p>* The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. * If the second remaining character is not upper case, then the first * character is converted to lower case. - * <p> - * For example, if an object has a method named <code>"getName"</code>, and + * + * <p>* For example, if an object has a method named <code>"getName"</code>, and * if the result of calling <code>object.getName()</code> is <code>"Larry Fine"</code>, * then the JSONObject will contain <code>"name": "Larry Fine"</code>. * @@ -339,8 +340,8 @@ public class LOGJSONObject { * JSONArray is stored under the key to hold all of the accumulated values. * If there is already a JSONArray, then the new value is appended to it. * In contrast, the put method replaces the previous value. - * <p> - * If only one value is accumulated that is not a JSONArray, then the + * + * <p>* If only one value is accumulated that is not a JSONArray, then the * result will be the same as using put. But if multiple values are * accumulated, then the result will be like append. * @@ -388,8 +389,8 @@ public class LOGJSONObject { } else if (object instanceof JSONArray) { this.put(key, ((JSONArray) object).put(value)); } else { - throw new JSONException(JSON_OBJECT_CONST + key + - "] is not a JSONArray."); + throw new JSONException(JSON_OBJECT_CONST + key + + "] is not a JSONArray."); } return this; } @@ -398,17 +399,17 @@ public class LOGJSONObject { * Produce a string from a double. The string "null" will be returned if * the number is not finite. * - * @param d A double. + * @param dub A double. * @return A String. */ - public static String doubleToString(double d) { - if (Double.isInfinite(d) || Double.isNaN(d)) { + public static String doubleToString(double dub) { + if (Double.isInfinite(dub) || Double.isNaN(dub)) { return "null"; } -// Shave off trailing zeros and decimal point, if possible. + // Shave off trailing zeros and decimal point, if possible. - String string = Double.toString(d); + String string = Double.toString(dub); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { @@ -434,8 +435,8 @@ public class LOGJSONObject { } Object object = this.opt(key); if (object == null) { - throw new JSONException(JSON_OBJECT_CONST + quote(key) + - "] not found."); + throw new JSONException(JSON_OBJECT_CONST + quote(key) + + "] not found."); } return object; } @@ -449,17 +450,17 @@ public class LOGJSONObject { */ public boolean getBoolean(String key) { Object object = this.get(key); - if (object.equals(Boolean.FALSE) || - (object instanceof String && - "false".equalsIgnoreCase((String) object))) { + if (object.equals(Boolean.FALSE) + || (object instanceof String + && "false".equalsIgnoreCase((String) object))) { return false; - } else if (object.equals(Boolean.TRUE) || - (object instanceof String && - "true".equalsIgnoreCase((String) object))) { + } else if (object.equals(Boolean.TRUE) + || (object instanceof String + && "true".equalsIgnoreCase((String) object))) { return true; } - throw new JSONException(JSON_OBJECT_CONST + quote(key) + - "] is not a Boolean."); + throw new JSONException(JSON_OBJECT_CONST + quote(key) + + "] is not a Boolean."); } /** @@ -515,8 +516,8 @@ public class LOGJSONObject { if (object instanceof JSONArray) { return (JSONArray) object; } - throw new JSONException(JSON_OBJECT_CONST + quote(key) + - "] is not a JSONArray."); + throw new JSONException(JSON_OBJECT_CONST + quote(key) + + "] is not a JSONArray."); } /** @@ -532,8 +533,8 @@ public class LOGJSONObject { if (object instanceof LOGJSONObject) { return (LOGJSONObject) object; } - throw new JSONException(JSON_OBJECT_CONST + quote(key) + - "] is not a JSONObject."); + throw new JSONException(JSON_OBJECT_CONST + quote(key) + + "] is not a JSONObject."); } /** @@ -568,10 +569,10 @@ public class LOGJSONObject { } Iterator<String> iterator = jo.keys(); String[] names = new String[length]; - int i = 0; + int iter = 0; while (iterator.hasNext()) { - names[i] = iterator.next(); - i += 1; + names[iter] = iterator.next(); + iter += 1; } return names; } @@ -588,8 +589,8 @@ public class LOGJSONObject { if (object instanceof String) { return (String) object; } - throw new JSONException(JSON_OBJECT_CONST + quote(key) + - "] not a string."); + throw new JSONException(JSON_OBJECT_CONST + quote(key) + + "] not a string."); } /** @@ -680,18 +681,17 @@ public class LOGJSONObject { * @return A String. * @throws JSONException If n is a non-finite number. */ - public static String numberToString(Number number) - { + public static String numberToString(Number number) { if (number == null) { throw new JSONException("Null pointer"); } testValidity(number); -// Shave off trailing zeros and decimal point, if possible. + // Shave off trailing zeros and decimal point, if possible. String string = number.toString(); - if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && - string.indexOf('E') < 0) { + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 + && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } @@ -803,7 +803,7 @@ public class LOGJSONObject { private void populateMap(Object bean) { Class<?> klass = bean.getClass(); -// If klass is a System class then set includeSuperClass to false. + // If klass is a System class then set includeSuperClass to false. boolean includeSuperClass = klass.getClassLoader() != null; @@ -817,8 +817,8 @@ public class LOGJSONObject { String name = method.getName(); String key = ""; if (name.startsWith("get")) { - if ("getClass".equals(name) || - "getDeclaringClass".equals(name)) { + if ("getClass".equals(name) + || "getDeclaringClass".equals(name)) { key = ""; } else { key = name.substring(3); @@ -826,14 +826,14 @@ public class LOGJSONObject { } else if (name.startsWith("is")) { key = name.substring(2); } - if (key.length() > 0 && - Character.isUpperCase(key.charAt(0)) && - method.getParameterTypes().length == 0) { + if (key.length() > 0 + && Character.isUpperCase(key.charAt(0)) + && method.getParameterTypes().length == 0) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { - key = key.substring(0, 1).toLowerCase() + - key.substring(1); + key = key.substring(0, 1).toLowerCase() + + key.substring(1); } Object result = method.invoke(bean, (Object[]) null); @@ -927,9 +927,9 @@ public class LOGJSONObject { * value are both non-null, and only if there is not already a member * with that name. * - * @param key - * @param value - * @return his. + * @param key string key + * @param value obj value + * @return this LOGJSONObject * @throws JSONException if the key is a duplicate */ public LOGJSONObject putOnce(String key, Object value) { @@ -944,8 +944,7 @@ public class LOGJSONObject { /** * Produce a string in double quotes with backslash sequences in all the - * right places. A backslash will be inserted within </, producing <\/, - * allowing JSON text to be delivered in HTML. In JSON text, a string + * right places. In JSON text, a string * cannot contain a control character or an unescaped quote or backslash. * * @param string A String @@ -963,63 +962,69 @@ public class LOGJSONObject { } } - public static Writer quote(String string, Writer w) throws IOException { + /** + * Writer method. + * @param string string + * @param writer writer + * @return A writer + * @throws IOException input/output exception + */ + public static Writer quote(String string, Writer writer) throws IOException { if (string == null || string.length() == 0) { - w.write("\"\""); - return w; + writer.write("\"\""); + return writer; } - char b; - char c = 0; + char char1; + char char2 = 0; String hhhh; - int i; int len = string.length(); - w.write('"'); - for (i = 0; i < len; i += 1) { - b = c; - c = string.charAt(i); - switch (c) { + writer.write('"'); + for (int i = 0; i < len; i += 1) { + char1 = char2; + char2 = string.charAt(i); + switch (char2) { case '\\': case '"': - w.write('\\'); - w.write(c); + writer.write('\\'); + writer.write(char2); break; case '/': - if (b == '<') { - w.write('\\'); + if (char1 == '<') { + writer.write('\\'); } - w.write(c); + writer.write(char2); break; case '\b': - w.write("\\b"); + writer.write("\\b"); break; case '\t': - w.write("\\t"); + writer.write("\\t"); break; case '\n': - w.write("\\n"); + writer.write("\\n"); break; case '\f': - w.write("\\f"); + writer.write("\\f"); break; case '\r': - w.write("\\r"); + writer.write("\\r"); break; default: - if (c < ' ' || (c >= '\u0080' && c < '\u00a0') - || (c >= '\u2000' && c < '\u2100')) { - w.write("\\u"); - hhhh = Integer.toHexString(c); - w.write("0000", 0, 4 - hhhh.length()); - w.write(hhhh); + if (char2 < ' ' || (char2 >= '\u0080' && char2 < '\u00a0') + || (char2 >= '\u2000' && char2 < '\u2100')) { + writer.write("\\u"); + hhhh = Integer.toHexString(char2); + writer.write("0000", 0, 4 - hhhh.length()); + writer.write(hhhh); } else { - w.write(c); + writer.write(char2); } } } - w.write('"'); - return w; + writer.write('"'); + return writer; } /** @@ -1041,7 +1046,7 @@ public class LOGJSONObject { * @return A simple JSON value. */ public static Object stringToValue(String string) { - Double d; + Double dub; if ("".equals(string)) { return string; } @@ -1063,14 +1068,14 @@ public class LOGJSONObject { * non-JSON forms as long as it accepts all correct JSON forms. */ - char b = string.charAt(0); - if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { + char chr = string.charAt(0); + if ((chr >= '0' && chr <= '9') || chr == '.' || chr == '-' || chr == '+') { try { if (string.indexOf('.') > -1 || string.indexOf('e') > -1 || string.indexOf('E') > -1) { - d = Double.valueOf(string); - if (!d.isInfinite() && !d.isNaN()) { - return d; + dub = Double.valueOf(string); + if (!dub.isInfinite() && !dub.isNaN()) { + return dub; } } else { Long myLong = new Long(string); @@ -1090,17 +1095,17 @@ public class LOGJSONObject { /** * Throw an exception if the object is a NaN or infinite number. * - * @param o The object to test. + * @param obj The object to test. * @throws JSONException If o is a non-finite number. */ - public static void testValidity(Object o) { - if (o != null) { - if (o instanceof Double) { - if (((Double) o).isInfinite() || ((Double) o).isNaN()) { + public static void testValidity(Object obj) { + if (obj != null) { + if (obj instanceof Double) { + if (((Double) obj).isInfinite() || ((Double) obj).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } - } else if (o instanceof Float && (((Float) o).isInfinite() || ((Float) o).isNaN())) { + } else if (obj instanceof Float && (((Float) obj).isInfinite() || ((Float) obj).isNaN())) { throw new JSONException( "JSON does not allow non-finite numbers."); } @@ -1131,8 +1136,8 @@ public class LOGJSONObject { * Make a JSON text of this JSONObject. For compactness, no whitespace * is added. If this would not result in a syntactically correct JSON text, * then null will be returned instead. - * <p> - * Warning: This method assumes that the data structure is acyclical. + * + * <p>* Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, portable, transmittable * representation of the object, beginning @@ -1150,8 +1155,8 @@ public class LOGJSONObject { /** * Make a prettyprinted JSON text of this JSONObject. - * <p> - * Warning: This method assumes that the data structure is acyclical. + * + * <p>* Warning: This method assumes that the data structure is acyclical. * * @param indentFactor The number of spaces to add to each level of * indentation. @@ -1162,9 +1167,9 @@ public class LOGJSONObject { * @throws JSONException If the object contains an invalid number. */ public String toString(int indentFactor) { - StringWriter w = new StringWriter(); - synchronized (w.getBuffer()) { - return this.write(w, indentFactor, 0).toString(); + StringWriter writer = new StringWriter(); + synchronized (writer.getBuffer()) { + return this.write(writer, indentFactor, 0).toString(); } } @@ -1180,8 +1185,7 @@ public class LOGJSONObject { * from it and its toJSONString method will be called. Otherwise, the * value's toString method will be called, and the result will be quoted. * - * <p> - * Warning: This method assumes that the data structure is acyclical. + * <p>* Warning: This method assumes that the data structure is acyclical. * * @param value The value to be serialized. * @return a printable, displayable, transmittable @@ -1244,13 +1248,13 @@ public class LOGJSONObject { if (object == null) { return NULL; } - if (object instanceof LOGJSONObject || object instanceof JSONArray || - NULL.equals(object) || object instanceof JSONString || - object instanceof Byte || object instanceof Character || - object instanceof Short || object instanceof Integer || - object instanceof Long || object instanceof Boolean || - object instanceof Float || object instanceof Double || - object instanceof String) { + if (object instanceof LOGJSONObject || object instanceof JSONArray + || NULL.equals(object) || object instanceof JSONString + || object instanceof Byte || object instanceof Character + || object instanceof Short || object instanceof Integer + || object instanceof Long || object instanceof Boolean + || object instanceof Float || object instanceof Double + || object instanceof String) { return object; } @@ -1268,9 +1272,9 @@ public class LOGJSONObject { ? objectPackage.getName() : ""; if ( - objectPackageName.startsWith("java.") || - objectPackageName.startsWith("javax.") || - object.getClass().getClassLoader() == null + objectPackageName.startsWith("java.") + || objectPackageName.startsWith("javax.") + || object.getClass().getClassLoader() == null ) { return object.toString(); } @@ -1300,13 +1304,13 @@ public class LOGJSONObject { } else if (value instanceof Boolean) { writer.write(value.toString()); } else if (value instanceof JSONString) { - Object o; + Object obj; try { - o = ((JSONString) value).toJSONString(); + obj = ((JSONString) value).toJSONString(); } catch (Exception e) { throw new JSONException(e); } - writer.write(o != null ? o.toString() : quote(value.toString())); + writer.write(obj != null ? obj.toString() : quote(value.toString())); } else { quote(value.toString(), writer); } @@ -1322,14 +1326,13 @@ public class LOGJSONObject { /** * Write the contents of the JSONObject as JSON text to a writer. For * compactness, no whitespace is added. - * <p> - * Warning: This method assumes that the data structure is acyclical. + * + * <p>* Warning: This method assumes that the data structure is acyclical. * * @return The writer. - * @throws JSONException + * @throws JSONException JSON exception */ - Writer write(Writer writer, int indentFactor, int indent) - { + Writer write(Writer writer, int indentFactor, int indent) { try { boolean commanate = false; final int length = this.length(); @@ -1347,7 +1350,6 @@ public class LOGJSONObject { } else if (length != 0) { final int newindent = indent + indentFactor; while (keys.hasNext()) { - Object key = keys.next(); if (commanate) { writer.write(','); } @@ -1355,6 +1357,7 @@ public class LOGJSONObject { writer.write('\n'); } indent(writer, newindent); + Object key = keys.next(); writer.write(quote(key.toString())); writer.write(':'); if (indentFactor > 0) { diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LogfileLoader.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LogfileLoader.java index b48907fc..afbadcd2 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LogfileLoader.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/LogfileLoader.java @@ -82,7 +82,8 @@ public class LogfileLoader extends Thread { /** * The PreparedStatement which is loaded by a <i>Loadable</i>. */ - private static final String INSERT_SQL = "insert into LOG_RECORDS values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + private static final String INSERT_SQL = "insert into LOG_RECORDS " + + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; /** * Each server can assign this many IDs. */ @@ -126,17 +127,17 @@ public class LogfileLoader extends Thread { } private long getIdRange() { - long n; + long size; if (BaseServlet.isInitialActivePOD()) { - n = 0; + size = 0; } else if (BaseServlet.isInitialStandbyPOD()) { - n = SET_SIZE; + size = SET_SIZE; } else { - n = SET_SIZE * 2; + size = SET_SIZE * 2; } - String r = String.format("[%X .. %X]", n, n + SET_SIZE - 1); - logger.debug("This server shall assign RECORD_IDs in the range " + r); - return n; + String range = String.format("[%X .. %X]", size, size + SET_SIZE - 1); + logger.debug("This server shall assign RECORD_IDs in the range " + range); + return size; } /** @@ -207,10 +208,10 @@ public class LogfileLoader extends Thread { logger.debug("PROV8001 Starting " + infile + " ..."); } long time = System.currentTimeMillis(); - int[] n = process(infile); + int[] array = process(infile); time = System.currentTimeMillis() - time; logger.info(String.format("PROV8000 Processed %s in %d ms; %d of %d records.", - infile.toString(), time, n[0], n[1])); + infile.toString(), time, array[0], array[1])); try { Files.delete(infile.toPath()); } catch (IOException e) { @@ -226,10 +227,10 @@ public class LogfileLoader extends Thread { Parameters provLogRetention = Parameters.getParameter(Parameters.PROV_LOG_RETENTION); if (provLogRetention != null) { try { - long n = Long.parseLong(provLogRetention.getValue()); + long retention = Long.parseLong(provLogRetention.getValue()); // This check is to prevent inadvertent errors from wiping the table out - if (n > 1000000L) { - threshold = n; + if (retention > 1000000L) { + threshold = retention; } } catch (NumberFormatException e) { // ignore @@ -260,7 +261,8 @@ public class LogfileLoader extends Thread { try { // 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")) { + try (PreparedStatement ps = conn.prepareStatement( + "DELETE from LOG_RECORDS where EVENT_TIME < ? limit 1000000")) { ps.setLong(1, cutoff); while (count > 0) { if (!ps.execute()) { @@ -310,7 +312,8 @@ public class LogfileLoader extends Thread { try (Connection conn = db.getConnection(); Statement stmt = conn.createStatement()) { 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")) { + 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"); @@ -341,8 +344,8 @@ public class LogfileLoader extends Thread { try (ResultSet rs = stmt.executeQuery(sql)) { goAgain = false; while (rs.next()) { - long n = rs.getLong("RECORD_ID"); - nbs.set(n); + long recordId = rs.getLong("RECORD_ID"); + nbs.set(recordId); goAgain = true; } } @@ -355,8 +358,8 @@ public class LogfileLoader extends Thread { RLEBitSet idset = new RLEBitSet(); idset.set(setStart, setStart + SET_SIZE); tbs.and(idset); - long t = tbs.length(); - nextId = (t == 0) ? setStart : (t - 1); + long bitLength = tbs.length(); + nextId = (bitLength == 0) ? setStart : (bitLength - 1); if (nextId >= setStart + SET_SIZE) { // Handle wraparound, when the IDs reach the end of our "range" Long[] last = null; @@ -366,8 +369,8 @@ public class LogfileLoader extends Thread { } if (last != null) { tbs.clear(last[0], last[1] + 1); - t = tbs.length(); - nextId = (t == 0) ? setStart : (t - 1); + bitLength = tbs.length(); + nextId = (bitLength == 0) ? setStart : (bitLength - 1); } } logger.debug(String.format("LogfileLoader.initializeNextid, next ID is %d (%x)", nextId, nextId)); @@ -379,16 +382,16 @@ public class LogfileLoader extends Thread { } @SuppressWarnings("resource") - int[] process(File f) { + int[] process(File file) { int ok = 0; int total = 0; try { Connection conn = db.getConnection(); PreparedStatement ps = conn.prepareStatement(INSERT_SQL); - Reader r = f.getPath().endsWith(".gz") - ? new InputStreamReader(new GZIPInputStream(new FileInputStream(f))) - : new FileReader(f); - try (LineNumberReader in = new LineNumberReader(r)) { + Reader reader = file.getPath().endsWith(".gz") + ? new InputStreamReader(new GZIPInputStream(new FileInputStream(file))) + : new FileReader(file); + try (LineNumberReader in = new LineNumberReader(reader)) { String line; while ((line = in.readLine()) != null) { try { @@ -428,7 +431,7 @@ public class LogfileLoader extends Thread { ps.close(); db.release(conn); } catch (SQLException | IOException e) { - logger.warn("PROV8007 Exception reading " + f + ": " + e); + logger.warn("PROV8007 Exception reading " + file + ": " + e); } return new int[]{ok, total}; } @@ -456,11 +459,12 @@ public class LogfileLoader extends Thread { } if ("EXP".equals(rtype) && pp.length == 11) { // Fields are: date|EXP|pubid|feedid|subid|requrl|method|ctype|clen|reason|attempts - ExpiryRecord e = new ExpiryRecord(pp); - if ("other".equals(e.getReason())) { - logger.info("Invalid reason '" + pp[9] + "' changed to 'other' for record: " + e.getPublishId()); + ExpiryRecord expiryRecord = new ExpiryRecord(pp); + if ("other".equals(expiryRecord.getReason())) { + logger.info("Invalid reason '" + pp[9] + "' changed to 'other' for record: " + + expiryRecord.getPublishId()); } - return new Loadable[]{e}; + return new Loadable[]{expiryRecord}; } if ("PBF".equals(rtype) && pp.length == 12) { // Fields are: date|PBF|pubid|feedid|requrl|method|ctype|clen-expected|clen-received|srcip|user|error @@ -471,7 +475,8 @@ public class LogfileLoader extends Thread { return new Loadable[]{new DeliveryExtraRecord(pp)}; } if ("LOG".equals(rtype) && (pp.length == 19 || pp.length == 20)) { - // Fields are: date|LOG|pubid|feedid|requrl|method|ctype|clen|type|feedFileid|remoteAddr|user|status|subid|fileid|result|attempts|reason|record_id + // Fields are: date|LOG|pubid|feedid|requrl|method|ctype|clen|type| + // feedFileid|remoteAddr|user|status|subid|fileid|result|attempts|reason|record_id return new Loadable[]{new LogRecord(pp)}; } } @@ -482,9 +487,9 @@ public class LogfileLoader extends Thread { /** * The LogfileLoader can be run stand-alone by invoking the main() method of this class. * - * @param a ignored + * @param str ignored */ - public static void main(String[] a) throws InterruptedException { + public static void main(String[] str) throws InterruptedException { LogfileLoader.getLoader(); Thread.sleep(200000L); } diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/PasswordProcessor.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/PasswordProcessor.java index cb6881fb..f87a9b9c 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/PasswordProcessor.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/PasswordProcessor.java @@ -39,9 +39,11 @@ import javax.crypto.spec.PBEParameterSpec; public class PasswordProcessor {
private static final String SECRET_KEY_FACTORY_TYPE = "PBEWithMD5AndDES";
- private static final String PASSWORD_ENCRYPTION_STRING = (new DB()).getProperties().getProperty("org.onap.dmaap.datarouter.provserver.passwordencryption");
+ private static final String PASSWORD_ENCRYPTION_STRING =
+ (new DB()).getProperties().getProperty("org.onap.dmaap.datarouter.provserver.passwordencryption");
private static final char[] PASSWORD = PASSWORD_ENCRYPTION_STRING.toCharArray();
- private static final byte[] SALT = {(byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12, (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,};
+ private static final byte[] SALT = {(byte) 0xde, (byte) 0x33, (byte) 0x10,
+ (byte) 0x12, (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,};
private PasswordProcessor(){
}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/PurgeLogDirTask.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/PurgeLogDirTask.java index 7cb1c02a..92ab86da 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/PurgeLogDirTask.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/PurgeLogDirTask.java @@ -48,18 +48,21 @@ public class PurgeLogDirTask extends TimerTask { private final long interval;
private EELFLogger utilsLogger;
+ /**
+ * PurgeLogDirTask constructor.
+ */
public PurgeLogDirTask() {
- Properties p = (new DB()).getProperties();
- logdir = p.getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir");
- String s = p.getProperty("org.onap.dmaap.datarouter.provserver.logretention", "30");
+ Properties prop = (new DB()).getProperties();
+ logdir = prop.getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir");
+ String str = prop.getProperty("org.onap.dmaap.datarouter.provserver.logretention", "30");
this.utilsLogger = EELFManager.getInstance().getLogger("UtilsLog");
- long n = 30;
+ long retention = 30;
try {
- n = Long.parseLong(s);
+ retention = Long.parseLong(str);
} catch (NumberFormatException e) {
// ignore
}
- interval = n * ONEDAY;
+ interval = retention * ONEDAY;
}
@Override
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/RLEBitSet.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/RLEBitSet.java index b57ceb12..457479be 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/RLEBitSet.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/RLEBitSet.java @@ -70,23 +70,30 @@ public class RLEBitSet { return start + nbits - 1;
}
+
public boolean intersects(RLE b2) {
- if (b2.lastBit() < this.firstBit())
+ if (b2.lastBit() < this.firstBit()) {
return false;
- if (b2.firstBit() > this.lastBit())
+ }
+ if (b2.firstBit() > this.lastBit()) {
return false;
+ }
return true;
}
public boolean isSubset(RLE b2) {
- if (firstBit() < b2.firstBit())
+ if (firstBit() < b2.firstBit()) {
return false;
- if (firstBit() > b2.lastBit())
+ }
+ if (firstBit() > b2.lastBit()) {
return false;
- if (lastBit() < b2.firstBit())
+ }
+ if (lastBit() < b2.firstBit()) {
return false;
- if (lastBit() > b2.lastBit())
+ }
+ if (lastBit() > b2.lastBit()) {
return false;
+ }
return true;
}
@@ -97,8 +104,9 @@ public class RLEBitSet { b2 = this;
}
long end = b1.lastBit();
- if (b2.lastBit() > b1.lastBit())
+ if (b2.lastBit() > b1.lastBit()) {
end = b2.lastBit();
+ }
return new RLE(b1.firstBit(), end - b1.firstBit() + 1);
}
@@ -112,17 +120,18 @@ public class RLEBitSet { }
@Override
- public int compareTo(RLE o) {
- if (this.equals(o))
+ public int compareTo(RLE rle) {
+ if (this.equals(rle)) {
return 0;
- return (start < o.start) ? -1 : 1;
+ }
+ return (start < rle.start) ? -1 : 1;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof RLE) {
- RLE b = (RLE) obj;
- return (start == b.start) && (nbits == b.nbits);
+ RLE rle = (RLE) obj;
+ return (start == rle.start) && (nbits == rle.nbits);
}
return false;
}
@@ -150,11 +159,11 @@ public class RLEBitSet { /**
* Creates a new bit set, with bits set according to the value of <code>s</code>.
*
- * @param s the initialization String
+ * @param str the initialization String
*/
- public RLEBitSet(String s) {
+ public RLEBitSet(String str) {
bitsets = new TreeSet<>();
- set(s);
+ set(str);
}
/**
@@ -164,8 +173,9 @@ public class RLEBitSet { * @return the logical size of this {@code RLEBitSet}
*/
public long length() {
- if (isEmpty())
+ if (isEmpty()) {
return 0;
+ }
return bitsets.last().lastBit() + 1;
}
@@ -179,8 +189,9 @@ public class RLEBitSet { public boolean get(long bit) {
synchronized (bitsets) {
for (RLE bs : bitsets) {
- if (bit >= bs.firstBit() && bit <= bs.lastBit())
+ if (bit >= bs.firstBit() && bit <= bs.lastBit()) {
return true;
+ }
}
}
return false;
@@ -189,24 +200,25 @@ public class RLEBitSet { /**
* Set one or more bits to true, based on the value of <code>s</code>.
*
- * @param s the initialization String, which consists of a comma or space separated list of
+ * @param str the initialization String, which consists of a comma or space separated list of
* non-negative numbers and ranges. An individual number represents the bit index to set.
* A range (two numbers separated by a dash) causes all bit indexes between the two numbers
* (inclusive) to be set.
* @throws NumberFormatException - if a number is incorrectly formatted
* @throws IndexOutOfBoundsException - if an index is negative
*/
- public void set(String s) {
- s = s.trim();
- if (!s.isEmpty()) {
- for (String s2 : s.split("[, \n]+")) {
+ public void set(String str) {
+ str = str.trim();
+ if (!str.isEmpty()) {
+ for (String s2 : str.split("[, \n]+")) {
if (s2.indexOf('-') >= 0) {
String[] pp = s2.split("-");
- long f = Long.parseLong(pp[0]);
- long t = Long.parseLong(pp[1]);
- set(f, t + 1);
- } else
+ long l1 = Long.parseLong(pp[0]);
+ long l2 = Long.parseLong(pp[1]);
+ set(l1, l2 + 1);
+ } else {
set(Long.parseLong(s2));
+ }
}
}
}
@@ -286,11 +298,13 @@ public class RLEBitSet { if (bs.intersects(newbits)) {
// preserve the bits that are not being cleared
long len = newbits.firstBit() - bs.firstBit();
- if (len > 0)
+ if (len > 0) {
newranges.add(new RLE(bs.firstBit(), len));
+ }
len = bs.lastBit() - newbits.lastBit();
- if (len > 0)
+ if (len > 0) {
newranges.add(new RLE(newbits.lastBit() + 1, len));
+ }
bs.nbits = 0;
}
}
@@ -328,12 +342,15 @@ public class RLEBitSet { * Checks that fromIndex ... toIndex is a valid range of bit indices.
*/
private static void checkRange(long from, long to) {
- if (from < 0)
+ if (from < 0) {
throw new IndexOutOfBoundsException("fromIndex < 0: " + from);
- if (to < 0)
+ }
+ if (to < 0) {
throw new IndexOutOfBoundsException("toIndex < 0: " + to);
- if (from > to)
+ }
+ if (from > to) {
throw new IndexOutOfBoundsException("fromIndex: " + from + " > toIndex: " + to);
+ }
}
/**
@@ -385,13 +402,13 @@ public class RLEBitSet { * @return the number of bits set to {@code true} in this {@code RLEBitSet}.
*/
public int cardinality() {
- int n = 0;
+ int trueCount = 0;
synchronized (bitsets) {
for (RLE bs : bitsets) {
- n += bs.cardinality();
+ trueCount += bs.cardinality();
}
}
- return n;
+ return trueCount;
}
/**
@@ -427,11 +444,12 @@ public class RLEBitSet { for (RLE bs : bitsets) {
sb.append(prefix);
prefix = ",";
- long s = bs.firstBit();
- long e = bs.lastBit();
- sb.append(s);
- if (s != e)
- sb.append('-').append(e);
+ long bit1 = bs.firstBit();
+ long bit2 = bs.lastBit();
+ sb.append(bit1);
+ if (bit1 != bit2) {
+ sb.append('-').append(bit2);
+ }
}
}
return sb.toString();
@@ -445,16 +463,16 @@ public class RLEBitSet { */
public Iterator<Long[]> getRangeIterator() {
return new Iterator<Long[]>() {
- private Iterator<RLE> i = bitsets.iterator();
+ private Iterator<RLE> iterator = bitsets.iterator();
@Override
public boolean hasNext() {
- return i.hasNext();
+ return iterator.hasNext();
}
@Override
public Long[] next() {
- RLE bs = i.next();
+ RLE bs = iterator.next();
return new Long[]{bs.firstBit(), bs.lastBit()};
}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/ThrottleFilter.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/ThrottleFilter.java index da06f6bb..659dbacd 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/ThrottleFilter.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/ThrottleFilter.java @@ -61,8 +61,8 @@ import org.onap.dmaap.datarouter.provisioning.beans.Parameters; * If the action is missing, it defaults to <i>drop</i>.
* </td></tr>
* </table>
- * <p>
- * The <i>action</i> is triggered iff:
+ *
+ * <p>* The <i>action</i> is triggered iff:
* <ol>
* <li>the filter is enabled, and</li>
* <li>N /publish requests come to the provisioning server in M minutes
@@ -76,7 +76,8 @@ import org.onap.dmaap.datarouter.provisioning.beans.Parameters; * The action that can be performed (if triggered) are:
* <ol>
* <li><i>drop</i> - the connection is dropped immediately.</li>
- * <li><i>throttle</i> - [not supported] the connection is put into a low priority queue with all other throttled connections.
+ * <li><i>throttle</i> - [not supported] the connection is put into a low priority queue
+ * with all other throttled connections.
* These are then processed at a slower rate. Note: this option does not work correctly, and is disabled.
* The only action that is supported is <i>drop</i>.
* </li>
@@ -85,6 +86,7 @@ import org.onap.dmaap.datarouter.provisioning.beans.Parameters; * @author Robert Eby
* @version $Id: ThrottleFilter.java,v 1.2 2014/03/12 19:45:41 eby Exp $
*/
+
public class ThrottleFilter extends TimerTask implements Filter {
private static final int DEFAULT_N = 10;
private static final int DEFAULT_M = 5;
@@ -111,27 +113,30 @@ public class ThrottleFilter extends TimerTask implements Filter { }
/**
- * Configure the throttle. This should be called from BaseServlet.provisioningParametersChanged(), to make sure it stays up to date.
+ * Configure the throttle. This should be called from BaseServlet.provisioningParametersChanged(),
+ * to make sure it stays up to date.
*/
public static void configure() {
- Parameters p = Parameters.getParameter(Parameters.THROTTLE_FILTER);
- if (p != null) {
+ Parameters param = Parameters.getParameter(Parameters.THROTTLE_FILTER);
+ if (param != null) {
try {
Class.forName(JETTY_REQUEST);
- String v = p.getValue();
- if (v != null && !"off".equals(v)) {
- String[] pp = v.split(",");
+ String val = param.getValue();
+ if (val != null && !"off".equals(val)) {
+ String[] pp = val.split(",");
if (pp != null) {
numRequests = (pp.length > 0) ? getInt(pp[0], DEFAULT_N) : DEFAULT_N;
samplingPeriod = (pp.length > 1) ? getInt(pp[1], DEFAULT_M) : DEFAULT_M;
- action = (pp.length > 2 && pp[2] != null && "throttle".equalsIgnoreCase(pp[2])) ? ACTION_THROTTLE : ACTION_DROP;
+ action = (pp.length > 2 && pp[2] != null
+ && "throttle".equalsIgnoreCase(pp[2])) ? ACTION_THROTTLE : ACTION_DROP;
enabled = true;
// ACTION_THROTTLE is not currently working, so is not supported
if (action == ACTION_THROTTLE) {
action = ACTION_DROP;
logger.info("Throttling is not currently supported; action changed to DROP");
}
- logger.info("ThrottleFilter is ENABLED for /publish requests; N=" + numRequests + ", M=" + samplingPeriod
+ logger.info("ThrottleFilter is ENABLED for /publish requests; N="
+ + numRequests + ", M=" + samplingPeriod
+ ", Action=" + action);
return;
}
@@ -145,9 +150,9 @@ public class ThrottleFilter extends TimerTask implements Filter { map.clear();
}
- private static int getInt(String s, int deflt) {
+ private static int getInt(String str, int deflt) {
try {
- return Integer.parseInt(s);
+ return Integer.parseInt(str);
} catch (NumberFormatException x) {
return deflt;
}
@@ -171,14 +176,23 @@ public class ThrottleFilter extends TimerTask implements Filter { }
}
+ /**
+ * Method to drop filter chain.
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @param chain FilterChain
+ * @throws IOException input/output exception
+ * @throws ServletException servle exception
+ */
public void dropFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
int rate = getRequestRate(request);
if (rate >= numRequests) {
// drop request - only works under Jetty
- String m = String.format("Dropping connection: %s %d bad connections in %d minutes", getConnectionId(request), rate,
+ String str = String.format("Dropping connection: %s %d bad connections in %d minutes",
+ getConnectionId(request), rate,
samplingPeriod);
- logger.info(m);
+ logger.info(str);
Request baseRequest = (request instanceof Request)
? (Request) request
: HttpConnection.getCurrentConnection().getHttpChannel().getRequest();
@@ -195,9 +209,9 @@ public class ThrottleFilter extends TimerTask implements Filter { int rate = getRequestRate(request);
Object results = request.getAttribute(THROTTLE_MARKER);
if (rate >= numRequests && results == null) {
- String m = String.format("Throttling connection: %s %d bad connections in %d minutes",
+ String str = String.format("Throttling connection: %s %d bad connections in %d minutes",
getConnectionId(request), rate, samplingPeriod);
- logger.info(m);
+ logger.info(str);
Continuation continuation = ContinuationSupport.getContinuation(request);
continuation.suspend();
register(id, continuation);
@@ -206,10 +220,10 @@ public class ThrottleFilter extends TimerTask implements Filter { chain.doFilter(request, response);
@SuppressWarnings("resource")
InputStream is = request.getInputStream();
- byte[] b = new byte[4096];
- int n = is.read(b);
- while (n > 0) {
- n = is.read(b);
+ byte[] bite = new byte[4096];
+ int num = is.read(bite);
+ while (num > 0) {
+ num = is.read(bite);
}
resume(id);
}
@@ -249,8 +263,9 @@ public class ThrottleFilter extends TimerTask implements Filter { */
private int getRequestRate(HttpServletRequest request) {
String expecthdr = request.getHeader("Expect");
- if (expecthdr != null && "100-continue".equalsIgnoreCase(expecthdr))
+ if (expecthdr != null && "100-continue".equalsIgnoreCase(expecthdr)) {
return 0;
+ }
String key = getConnectionId(request);
synchronized (map) {
@@ -266,13 +281,17 @@ public class ThrottleFilter extends TimerTask implements Filter { public class Counter {
private List<Long> times = new ArrayList<>(); // a record of request times
+ /**
+ * Method to prune request rate.
+ * @return times
+ */
public int prune() {
try {
- long n = System.currentTimeMillis() - (samplingPeriod * ONE_MINUTE);
- long t = times.get(0);
- while (t < n) {
+ long num = System.currentTimeMillis() - (samplingPeriod * ONE_MINUTE);
+ long time = times.get(0);
+ while (time < num) {
times.remove(0);
- t = times.get(0);
+ time = times.get(0);
}
} catch (IndexOutOfBoundsException e) {
logger.trace("Exception: " + e.getMessage(), e);
@@ -295,12 +314,14 @@ public class ThrottleFilter extends TimerTask implements Filter { private int getFeedId(HttpServletRequest req) {
String path = req.getPathInfo();
- if (path == null || path.length() < 2)
+ if (path == null || path.length() < 2) {
return -1;
+ }
path = path.substring(1);
int ix = path.indexOf('/');
- if (ix < 0 || ix == path.length() - 1)
+ if (ix < 0 || ix == path.length() - 1) {
return -2;
+ }
try {
return Integer.parseInt(path.substring(0, ix));
} catch (NumberFormatException e) {
@@ -313,9 +334,10 @@ public class ThrottleFilter extends TimerTask implements Filter { // Once every 5 minutes, go through the map, and remove empty entrys
for (Object s : map.keySet().toArray()) {
synchronized (map) {
- Counter c = map.get(s);
- if (c.prune() <= 0)
+ Counter counter = map.get(s);
+ if (counter.prune() <= 0) {
map.remove(s);
+ }
}
}
}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/URLUtilities.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/URLUtilities.java index 5813024c..2e000027 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/URLUtilities.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/URLUtilities.java @@ -39,6 +39,7 @@ import org.onap.dmaap.datarouter.provisioning.BaseServlet; */
public class URLUtilities {
+
private static final EELFLogger utilsLogger = EELFManager.getInstance().getLogger("UtilsLog");
private static final String HTTPS = "https://";
private static String otherPod;
|