* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
+
package org.onap.dmaap.datarouter.provisioning.eelf;
import ch.qos.logback.classic.Level;
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;
* * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
* *\r
******************************************************************************/\r
+\r
package org.onap.dmaap.datarouter.provisioning.eelf;\r
\r
import com.att.eelf.i18n.EELFResolvableErrorEnum;\r
\r
public enum EelfMsgs implements EELFResolvableErrorEnum {\r
\r
+\r
/**\r
- * Application message prints user (accepts one argument)\r
+ * Application message prints user (accepts one argument).\r
*/\r
MESSAGE_WITH_BEHALF,\r
\r
/**\r
- * Application message prints user and FeedID (accepts two arguments)\r
+ * Application message prints user and FeedID (accepts two arguments).\r
*/\r
\r
MESSAGE_WITH_BEHALF_AND_FEEDID,\r
\r
/**\r
- * Application message prints user and SUBID (accepts two arguments)\r
+ * Application message prints user and SUBID (accepts two arguments).\r
*/\r
\r
MESSAGE_WITH_BEHALF_AND_SUBID,\r
* * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
* *\r
******************************************************************************/\r
+\r
package org.onap.dmaap.datarouter.provisioning.eelf;\r
\r
import ch.qos.logback.classic.spi.ILoggingEvent;\r
import ch.qos.logback.core.spi.FilterReply;\r
\r
public class JettyFilter extends Filter<ILoggingEvent> {\r
+\r
@Override\r
public FilterReply decide(ILoggingEvent event) {\r
if (event.getLoggerName().contains("org.eclipse.jetty")) {\r
* *\r
******************************************************************************/\r
\r
-\r
package org.onap.dmaap.datarouter.provisioning.utils;\r
\r
import static java.lang.System.exit;\r
props.load(new FileInputStream(getProperty(\r
"org.onap.dmaap.datarouter.provserver.properties",\r
"/opt/app/datartr/etc/provserver.properties")));\r
- String dbDriver = (String) props.get("org.onap.dmaap.datarouter.db.driver");\r
dbUrl = (String) props.get("org.onap.dmaap.datarouter.db.url");\r
dbLogin = (String) props.get("org.onap.dmaap.datarouter.db.login");\r
dbPassword = (String) props.get("org.onap.dmaap.datarouter.db.password");\r
httpsPort = (String) props.get("org.onap.dmaap.datarouter.provserver.https.port");\r
httpPort = (String) props.get("org.onap.dmaap.datarouter.provserver.http.port");\r
+ 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
connection = queue.remove();\r
} catch (NoSuchElementException nseEx) {\r
intlogger.error("PROV9006 No connection on queue: " + nseEx.getMessage(), nseEx);\r
- int n = 0;\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 (++n >= 3) {\r
+ if (++num >= 3) {\r
throw sqlEx;\r
}\r
}\r
- } while (connection == null);\r
+ }\r
+ while (connection == null);\r
}\r
}\r
if (connection != null && !connection.isValid(1)) {\r
* 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");
}
@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());
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();
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();
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());
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);
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 {
* *\r
******************************************************************************/\r
\r
-\r
package org.onap.dmaap.datarouter.provisioning.utils;\r
\r
import com.att.eelf.configuration.EELFLogger;\r
String server = System.getenv(ENV_VAR);\r
if (args.length >= 2 && args[0].equals("-s")) {\r
server = args[1];\r
- String[] t = new String[args.length - 2];\r
- if (t.length > 0)\r
- System.arraycopy(args, 2, t, 0, t.length);\r
- args = t;\r
+ String[] str = new String[args.length - 2];\r
+ if (str.length > 0) {\r
+ System.arraycopy(args, 2, str, 0, str.length);\r
+ }\r
+ args = str;\r
}\r
if (server == null || server.equals("")) {\r
System.err.println("dr-route: you need to specify a server, either via $PROVSRVR or the '-s' option.");\r
}\r
DRRouteCLI cli = new DRRouteCLI(server);\r
if (args.length > 0) {\r
- boolean b = cli.runCommand(args);\r
- System.exit(b ? 0 : 1);\r
+ boolean bool = cli.runCommand(args);\r
+ System.exit(bool ? 0 : 1);\r
} else {\r
cli.interactive();\r
System.exit(0);\r
* Create a DRRouteCLI object connecting to the specified server.\r
*\r
* @param server the server to send command to\r
- * @throws Exception\r
+ * @throws Exception generic exception\r
*/\r
public DRRouteCLI(String server) throws Exception {\r
this.server = server;\r
this.width = 120;\r
this.httpclient = new DefaultHttpClient();\r
\r
- Properties p = (new DB()).getProperties();\r
- String truststore_file = p.getProperty("org.onap.dmaap.datarouter.provserver.truststore.path");\r
- String truststore_pw = p.getProperty("org.onap.dmaap.datarouter.provserver.truststore.password");\r
+ Properties prop = (new DB()).getProperties();\r
+ String truststoreFile = prop.getProperty("org.onap.dmaap.datarouter.provserver.truststore.path");\r
+ String truststorePw = prop.getProperty("org.onap.dmaap.datarouter.provserver.truststore.password");\r
\r
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());\r
- if (truststore_file == null || truststore_file.equals("")) {\r
+ if (truststoreFile == null || truststoreFile.equals("")) {\r
String jhome = System.getenv("JAVA_HOME");\r
- if (jhome == null || jhome.equals(""))\r
+ if (jhome == null || jhome.equals("")) {\r
jhome = "/opt/java/jdk/jdk180";\r
- truststore_file = jhome + DEFAULT_TRUSTSTORE_PATH;\r
+ }\r
+ truststoreFile = jhome + DEFAULT_TRUSTSTORE_PATH;\r
}\r
- File f = new File(truststore_file);\r
- if (f.exists()) {\r
- FileInputStream instream = new FileInputStream(f);\r
+ File file = new File(truststoreFile);\r
+ if (file.exists()) {\r
+ FileInputStream instream = new FileInputStream(file);\r
try {\r
- trustStore.load(instream, truststore_pw.toCharArray());\r
+ trustStore.load(instream, truststorePw.toCharArray());\r
} catch (Exception x) {\r
intlogger.error("Problem reading truststore: " + x.getMessage(), x);\r
throw x;\r
while (true) {\r
System.out.print(PROMPT);\r
String line = in.readLine();\r
- if (line == null)\r
+ if (line == null) {\r
return;\r
+ }\r
line = line.trim();\r
- if (line.equalsIgnoreCase("exit")) // "exit" may only be used in interactive mode\r
+ if (line.equalsIgnoreCase("exit")) { // "exit" may only be used in interactive mode\r
return;\r
- if (line.equalsIgnoreCase("quit")) // "quit" may only be used in interactive mode\r
+ }\r
+ if (line.equalsIgnoreCase("quit")) { // "quit" may only be used in interactive mode\r
return;\r
+ }\r
String[] args = line.split("[ \t]+");\r
- if (args.length > 0)\r
+ if (args.length > 0) {\r
runCommand(args);\r
+ }\r
}\r
}\r
\r
\r
private boolean addIngress(String[] args) {\r
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]);\r
- if (args.length > 6)\r
+ if (args.length > 6) {\r
url += "&seq=" + args[6];\r
+ }\r
return doPost(url);\r
}\r
\r
if (tbl.startsWith("al") || tbl.startsWith("in")) {\r
// Display the IRT\r
JSONArray irt = jo.optJSONArray("ingress");\r
- int cw1 = 6, cw2 = 6, cw3 = 6, cw4 = 6; // determine column widths for first 4 cols\r
+ int cw1 = 6;\r
+ int cw2 = 6;\r
+ int cw3 = 6;\r
+ int cw4 = 6; // determine column widths for first 4 cols\r
for (int i = 0; irt != null && i < irt.length(); i++) {\r
- JSONObject e = irt.getJSONObject(i);\r
- cw1 = Math.max(cw1, ("" + e.getInt("seq")).length());\r
- cw2 = Math.max(cw2, ("" + e.getInt("feedid")).length());\r
- String t = e.optString("user");\r
- cw3 = Math.max(cw3, (t == null) ? 1 : t.length());\r
- t = e.optString("subnet");\r
- cw4 = Math.max(cw4, (t == null) ? 1 : t.length());\r
+ JSONObject jsonObject = irt.getJSONObject(i);\r
+ cw1 = Math.max(cw1, ("" + jsonObject.getInt("seq")).length());\r
+ cw2 = Math.max(cw2, ("" + jsonObject.getInt("feedid")).length());\r
+ String str = jsonObject.optString("user");\r
+ cw3 = Math.max(cw3, (str == null) ? 1 : str.length());\r
+ str = jsonObject.optString("subnet");\r
+ cw4 = Math.max(cw4, (str == null) ? 1 : str.length());\r
}\r
\r
int nblank = cw1 + cw2 + cw3 + cw4 + 8;\r
sb.append("Ingress Routing Table\n");\r
- sb.append(String.format("%s %s %s %s Nodes\n", ext("Seq", cw1), ext("FeedID", cw2), ext("User", cw3), ext("Subnet", cw4)));\r
+ sb.append(String.format("%s %s %s %s Nodes\n", ext("Seq", cw1),\r
+ ext("FeedID", cw2), ext("User", cw3), ext("Subnet", cw4)));\r
for (int i = 0; irt != null && i < irt.length(); i++) {\r
- JSONObject e = irt.getJSONObject(i);\r
- String seq = "" + e.getInt("seq");\r
- String feedid = "" + e.getInt("feedid");\r
- String user = e.optString("user");\r
- String subnet = e.optString("subnet");\r
- if (user.equals("")) user = "-";\r
- if (subnet.equals("")) subnet = "-";\r
- JSONArray nodes = e.getJSONArray("node");\r
+ JSONObject jsonObject = irt.getJSONObject(i);\r
+ String seq = "" + jsonObject.getInt("seq");\r
+ String feedid = "" + jsonObject.getInt("feedid");\r
+ String user = jsonObject.optString("user");\r
+ String subnet = jsonObject.optString("subnet");\r
+ if (user.equals("")) {\r
+ user = "-";\r
+ }\r
+ if (subnet.equals("")) {\r
+ subnet = "-";\r
+ }\r
+ JSONArray nodes = jsonObject.getJSONArray("node");\r
int sol = sb.length();\r
- sb.append(String.format("%s %s %s %s ", ext(seq, cw1), ext(feedid, cw2), ext(user, cw3), ext(subnet, cw4)));\r
+ sb.append(String.format("%s %s %s %s ", ext(seq, cw1),\r
+ ext(feedid, cw2), ext(user, cw3), ext(subnet, cw4)));\r
for (int j = 0; j < nodes.length(); j++) {\r
String nd = nodes.getString(j);\r
int cursor = sb.length() - sol;\r
// Display the ERT\r
JSONObject ert = jo.optJSONObject("egress");\r
String[] subs = (ert == null) ? new String[0] : JSONObject.getNames(ert);\r
- if (subs == null)\r
+ if (subs == null) {\r
subs = new String[0];\r
+ }\r
Arrays.sort(subs);\r
int cw1 = 5;\r
for (int i = 0; i < subs.length; i++) {\r
cw1 = Math.max(cw1, subs[i].length());\r
}\r
\r
- if (sb.length() > 0)\r
+ if (sb.length() > 0) {\r
sb.append("\n");\r
+ }\r
sb.append("Egress Routing Table\n");\r
sb.append(String.format("%s Node\n", ext("SubID", cw1)));\r
for (int i = 0; i < subs.length; i++) {\r
- if(ert!=null&&ert.length()!=0) {\r
+ if (ert != null && ert.length() != 0 ) {\r
String node = ert.getString(subs[i]);\r
sb.append(String.format("%s %s\n", ext(subs[i], cw1), node));\r
}\r
if (tbl.startsWith("al") || tbl.startsWith("ne")) {\r
// Display the NRT\r
JSONArray nrt = jo.optJSONArray("routing");\r
- int cw1 = 4, cw2 = 4;\r
+ int cw1 = 4;\r
+ int cw2 = 4;\r
for (int i = 0; nrt != null && i < nrt.length(); i++) {\r
- JSONObject e = nrt.getJSONObject(i);\r
- String from = e.getString("from");\r
- String to = e.getString("to");\r
+ JSONObject jsonObject = nrt.getJSONObject(i);\r
+ String from = jsonObject.getString("from");\r
+ String to = jsonObject.getString("to");\r
cw1 = Math.max(cw1, from.length());\r
cw2 = Math.max(cw2, to.length());\r
}\r
\r
- if (sb.length() > 0)\r
+ if (sb.length() > 0) {\r
sb.append("\n");\r
+ }\r
sb.append("Network Routing Table\n");\r
sb.append(String.format("%s %s Via\n", ext("From", cw1), ext("To", cw2)));\r
for (int i = 0; nrt != null && i < nrt.length(); i++) {\r
- JSONObject e = nrt.getJSONObject(i);\r
- String from = e.getString("from");\r
- String to = e.getString("to");\r
- String via = e.getString("via");\r
+ JSONObject jsonObject = nrt.getJSONObject(i);\r
+ String from = jsonObject.getString("from");\r
+ String to = jsonObject.getString("to");\r
+ String via = jsonObject.getString("via");\r
sb.append(String.format("%s %s %s\n", ext(from, cw1), ext(to, cw2), via));\r
}\r
}\r
return true;\r
}\r
\r
- private String ext(String s, int n) {\r
- if (s == null)\r
- s = "-";\r
- while (s.length() < n)\r
- s += " ";\r
- return s;\r
+ private String ext(String str, int num) {\r
+ if (str == null) {\r
+ str = "-";\r
+ }\r
+ while (str.length() < num) {\r
+ str += " ";\r
+ }\r
+ return str;\r
}\r
\r
private boolean doDelete(String url) {\r
// Look for and print only the part of the output between <pre>...</pre>\r
InputStream is = entity.getContent();\r
StringBuilder sb = new StringBuilder();\r
- byte[] b = new byte[512];\r
- int n = 0;\r
- while ((n = is.read(b)) > 0) {\r
- sb.append(new String(b, 0, n));\r
+ byte[] bite = new byte[512];\r
+ int num = 0;\r
+ while ((num = is.read(bite)) > 0) {\r
+ sb.append(new String(bite, 0, num));\r
}\r
is.close();\r
int ix = sb.indexOf("<pre>");\r
- if (ix > 0)\r
+ if (ix > 0) {\r
sb.delete(0, ix + 5);\r
+ }\r
ix = sb.indexOf("</pre>");\r
- if (ix > 0)\r
+ if (ix > 0) {\r
sb.delete(ix, sb.length());\r
+ }\r
System.err.println(sb.toString());\r
}\r
}\r
}
- 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) {
* *\r
******************************************************************************/\r
\r
-\r
package org.onap.dmaap.datarouter.provisioning.utils;\r
\r
import com.att.eelf.configuration.EELFLogger;\r
private JSONUtilities(){\r
\r
}\r
+\r
/**\r
* Does the String <i>v</i> represent a valid Internet address (with or without a\r
* mask length appended).\r
*\r
- * @param v the string to check\r
+ * @param str the string to check\r
* @return true if valid, false otherwise\r
*/\r
- public static boolean validIPAddrOrSubnet(String v) {\r
- String[] pp = {v, ""};\r
- if (v.indexOf('/') > 0)\r
- pp = v.split("/");\r
+ public static boolean validIPAddrOrSubnet(String str) {\r
+ String[] pp = {str, ""};\r
+ if (str.indexOf('/') > 0) {\r
+ pp = str.split("/");\r
+ }\r
try {\r
InetAddress addr = InetAddress.getByName(pp[0]);\r
if (pp[1].length() > 0) {\r
// check subnet mask\r
int mask = Integer.parseInt(pp[1]);\r
- if (mask > (addr.getAddress().length * 8))\r
+ if (mask > (addr.getAddress().length * 8)) {\r
return false;\r
+ }\r
}\r
return true;\r
} catch (UnknownHostException e) {\r
* 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>
* @author JSON.org
* @version 2012-12-01
*/
+
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
* 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
/**
* 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 '}'");
}
}
}
*
* @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));
}
}
}
* 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>.
*
* 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.
*
} 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;
}
* 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")) {
}
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;
}
*/
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.");
}
/**
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.");
}
/**
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.");
}
/**
}
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;
}
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.");
}
/**
* @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);
}
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;
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);
} 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);
* 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) {
/**
* 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
}
}
- 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;
}
/**
* @return A simple JSON value.
*/
public static Object stringToValue(String string) {
- Double d;
+ Double dub;
if ("".equals(string)) {
return string;
}
* 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);
/**
* 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.");
}
* 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
/**
* 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.
* @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();
}
}
* 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
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;
}
? 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();
}
} 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);
}
/**
* 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();
} else if (length != 0) {
final int newindent = indent + indentFactor;
while (keys.hasNext()) {
- Object key = keys.next();
if (commanate) {
writer.write(',');
}
writer.write('\n');
}
indent(writer, newindent);
+ Object key = keys.next();
writer.write(quote(key.toString()));
writer.write(':');
if (indentFactor > 0) {
/**
* 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.
*/
}
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;
}
/**
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) {
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
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()) {
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");
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;
}
}
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;
}
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));
}
@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 {
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};
}
}
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
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)};
}
}
/**
* 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);
}
public class PasswordProcessor {\r
\r
private static final String SECRET_KEY_FACTORY_TYPE = "PBEWithMD5AndDES";\r
- private static final String PASSWORD_ENCRYPTION_STRING = (new DB()).getProperties().getProperty("org.onap.dmaap.datarouter.provserver.passwordencryption");\r
+ private static final String PASSWORD_ENCRYPTION_STRING =\r
+ (new DB()).getProperties().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, (byte) 0x12, (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,};\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
private PasswordProcessor(){\r
}\r
private final long interval;\r
private EELFLogger utilsLogger;\r
\r
+ /**\r
+ * PurgeLogDirTask constructor.\r
+ */\r
public PurgeLogDirTask() {\r
- Properties p = (new DB()).getProperties();\r
- logdir = p.getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir");\r
- String s = p.getProperty("org.onap.dmaap.datarouter.provserver.logretention", "30");\r
+ Properties prop = (new DB()).getProperties();\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
- long n = 30;\r
+ long retention = 30;\r
try {\r
- n = Long.parseLong(s);\r
+ retention = Long.parseLong(str);\r
} catch (NumberFormatException e) {\r
// ignore\r
}\r
- interval = n * ONEDAY;\r
+ interval = retention * ONEDAY;\r
}\r
\r
@Override\r
return start + nbits - 1;\r
}\r
\r
+\r
public boolean intersects(RLE b2) {\r
- if (b2.lastBit() < this.firstBit())\r
+ if (b2.lastBit() < this.firstBit()) {\r
return false;\r
- if (b2.firstBit() > this.lastBit())\r
+ }\r
+ if (b2.firstBit() > this.lastBit()) {\r
return false;\r
+ }\r
return true;\r
}\r
\r
public boolean isSubset(RLE b2) {\r
- if (firstBit() < b2.firstBit())\r
+ if (firstBit() < b2.firstBit()) {\r
return false;\r
- if (firstBit() > b2.lastBit())\r
+ }\r
+ if (firstBit() > b2.lastBit()) {\r
return false;\r
- if (lastBit() < b2.firstBit())\r
+ }\r
+ if (lastBit() < b2.firstBit()) {\r
return false;\r
- if (lastBit() > b2.lastBit())\r
+ }\r
+ if (lastBit() > b2.lastBit()) {\r
return false;\r
+ }\r
return true;\r
}\r
\r
b2 = this;\r
}\r
long end = b1.lastBit();\r
- if (b2.lastBit() > b1.lastBit())\r
+ if (b2.lastBit() > b1.lastBit()) {\r
end = b2.lastBit();\r
+ }\r
return new RLE(b1.firstBit(), end - b1.firstBit() + 1);\r
}\r
\r
}\r
\r
@Override\r
- public int compareTo(RLE o) {\r
- if (this.equals(o))\r
+ public int compareTo(RLE rle) {\r
+ if (this.equals(rle)) {\r
return 0;\r
- return (start < o.start) ? -1 : 1;\r
+ }\r
+ return (start < rle.start) ? -1 : 1;\r
}\r
\r
@Override\r
public boolean equals(Object obj) {\r
if (obj instanceof RLE) {\r
- RLE b = (RLE) obj;\r
- return (start == b.start) && (nbits == b.nbits);\r
+ RLE rle = (RLE) obj;\r
+ return (start == rle.start) && (nbits == rle.nbits);\r
}\r
return false;\r
}\r
/**\r
* Creates a new bit set, with bits set according to the value of <code>s</code>.\r
*\r
- * @param s the initialization String\r
+ * @param str the initialization String\r
*/\r
- public RLEBitSet(String s) {\r
+ public RLEBitSet(String str) {\r
bitsets = new TreeSet<>();\r
- set(s);\r
+ set(str);\r
}\r
\r
/**\r
* @return the logical size of this {@code RLEBitSet}\r
*/\r
public long length() {\r
- if (isEmpty())\r
+ if (isEmpty()) {\r
return 0;\r
+ }\r
return bitsets.last().lastBit() + 1;\r
}\r
\r
public boolean get(long bit) {\r
synchronized (bitsets) {\r
for (RLE bs : bitsets) {\r
- if (bit >= bs.firstBit() && bit <= bs.lastBit())\r
+ if (bit >= bs.firstBit() && bit <= bs.lastBit()) {\r
return true;\r
+ }\r
}\r
}\r
return false;\r
/**\r
* Set one or more bits to true, based on the value of <code>s</code>.\r
*\r
- * @param s the initialization String, which consists of a comma or space separated list of\r
+ * @param str the initialization String, which consists of a comma or space separated list of\r
* non-negative numbers and ranges. An individual number represents the bit index to set.\r
* A range (two numbers separated by a dash) causes all bit indexes between the two numbers\r
* (inclusive) to be set.\r
* @throws NumberFormatException - if a number is incorrectly formatted\r
* @throws IndexOutOfBoundsException - if an index is negative\r
*/\r
- public void set(String s) {\r
- s = s.trim();\r
- if (!s.isEmpty()) {\r
- for (String s2 : s.split("[, \n]+")) {\r
+ public void set(String str) {\r
+ str = str.trim();\r
+ if (!str.isEmpty()) {\r
+ for (String s2 : str.split("[, \n]+")) {\r
if (s2.indexOf('-') >= 0) {\r
String[] pp = s2.split("-");\r
- long f = Long.parseLong(pp[0]);\r
- long t = Long.parseLong(pp[1]);\r
- set(f, t + 1);\r
- } else\r
+ long l1 = Long.parseLong(pp[0]);\r
+ long l2 = Long.parseLong(pp[1]);\r
+ set(l1, l2 + 1);\r
+ } else {\r
set(Long.parseLong(s2));\r
+ }\r
}\r
}\r
}\r
if (bs.intersects(newbits)) {\r
// preserve the bits that are not being cleared\r
long len = newbits.firstBit() - bs.firstBit();\r
- if (len > 0)\r
+ if (len > 0) {\r
newranges.add(new RLE(bs.firstBit(), len));\r
+ }\r
len = bs.lastBit() - newbits.lastBit();\r
- if (len > 0)\r
+ if (len > 0) {\r
newranges.add(new RLE(newbits.lastBit() + 1, len));\r
+ }\r
bs.nbits = 0;\r
}\r
}\r
* Checks that fromIndex ... toIndex is a valid range of bit indices.\r
*/\r
private static void checkRange(long from, long to) {\r
- if (from < 0)\r
+ if (from < 0) {\r
throw new IndexOutOfBoundsException("fromIndex < 0: " + from);\r
- if (to < 0)\r
+ }\r
+ if (to < 0) {\r
throw new IndexOutOfBoundsException("toIndex < 0: " + to);\r
- if (from > to)\r
+ }\r
+ if (from > to) {\r
throw new IndexOutOfBoundsException("fromIndex: " + from + " > toIndex: " + to);\r
+ }\r
}\r
\r
/**\r
* @return the number of bits set to {@code true} in this {@code RLEBitSet}.\r
*/\r
public int cardinality() {\r
- int n = 0;\r
+ int trueCount = 0;\r
synchronized (bitsets) {\r
for (RLE bs : bitsets) {\r
- n += bs.cardinality();\r
+ trueCount += bs.cardinality();\r
}\r
}\r
- return n;\r
+ return trueCount;\r
}\r
\r
/**\r
for (RLE bs : bitsets) {\r
sb.append(prefix);\r
prefix = ",";\r
- long s = bs.firstBit();\r
- long e = bs.lastBit();\r
- sb.append(s);\r
- if (s != e)\r
- sb.append('-').append(e);\r
+ long bit1 = bs.firstBit();\r
+ long bit2 = bs.lastBit();\r
+ sb.append(bit1);\r
+ if (bit1 != bit2) {\r
+ sb.append('-').append(bit2);\r
+ }\r
}\r
}\r
return sb.toString();\r
*/\r
public Iterator<Long[]> getRangeIterator() {\r
return new Iterator<Long[]>() {\r
- private Iterator<RLE> i = bitsets.iterator();\r
+ private Iterator<RLE> iterator = bitsets.iterator();\r
\r
@Override\r
public boolean hasNext() {\r
- return i.hasNext();\r
+ return iterator.hasNext();\r
}\r
\r
@Override\r
public Long[] next() {\r
- RLE bs = i.next();\r
+ RLE bs = iterator.next();\r
return new Long[]{bs.firstBit(), bs.lastBit()};\r
}\r
\r
* If the action is missing, it defaults to <i>drop</i>.\r
* </td></tr>\r
* </table>\r
- * <p>\r
- * The <i>action</i> is triggered iff:\r
+ *\r
+ * <p>* The <i>action</i> is triggered iff:\r
* <ol>\r
* <li>the filter is enabled, and</li>\r
* <li>N /publish requests come to the provisioning server in M minutes\r
* The action that can be performed (if triggered) are:\r
* <ol>\r
* <li><i>drop</i> - the connection is dropped immediately.</li>\r
- * <li><i>throttle</i> - [not supported] the connection is put into a low priority queue with all other throttled connections.\r
+ * <li><i>throttle</i> - [not supported] the connection is put into a low priority queue\r
+ * with all other throttled connections.\r
* These are then processed at a slower rate. Note: this option does not work correctly, and is disabled.\r
* The only action that is supported is <i>drop</i>.\r
* </li>\r
* @author Robert Eby\r
* @version $Id: ThrottleFilter.java,v 1.2 2014/03/12 19:45:41 eby Exp $\r
*/\r
+\r
public class ThrottleFilter extends TimerTask implements Filter {\r
private static final int DEFAULT_N = 10;\r
private static final int DEFAULT_M = 5;\r
}\r
\r
/**\r
- * Configure the throttle. This should be called from BaseServlet.provisioningParametersChanged(), to make sure it stays up to date.\r
+ * Configure the throttle. This should be called from BaseServlet.provisioningParametersChanged(),\r
+ * to make sure it stays up to date.\r
*/\r
public static void configure() {\r
- Parameters p = Parameters.getParameter(Parameters.THROTTLE_FILTER);\r
- if (p != null) {\r
+ Parameters param = Parameters.getParameter(Parameters.THROTTLE_FILTER);\r
+ if (param != null) {\r
try {\r
Class.forName(JETTY_REQUEST);\r
- String v = p.getValue();\r
- if (v != null && !"off".equals(v)) {\r
- String[] pp = v.split(",");\r
+ String val = param.getValue();\r
+ if (val != null && !"off".equals(val)) {\r
+ String[] pp = val.split(",");\r
if (pp != null) {\r
numRequests = (pp.length > 0) ? getInt(pp[0], DEFAULT_N) : DEFAULT_N;\r
samplingPeriod = (pp.length > 1) ? getInt(pp[1], DEFAULT_M) : DEFAULT_M;\r
- action = (pp.length > 2 && pp[2] != null && "throttle".equalsIgnoreCase(pp[2])) ? ACTION_THROTTLE : ACTION_DROP;\r
+ action = (pp.length > 2 && pp[2] != null\r
+ && "throttle".equalsIgnoreCase(pp[2])) ? ACTION_THROTTLE : ACTION_DROP;\r
enabled = true;\r
// ACTION_THROTTLE is not currently working, so is not supported\r
if (action == ACTION_THROTTLE) {\r
action = ACTION_DROP;\r
logger.info("Throttling is not currently supported; action changed to DROP");\r
}\r
- logger.info("ThrottleFilter is ENABLED for /publish requests; N=" + numRequests + ", M=" + samplingPeriod\r
+ logger.info("ThrottleFilter is ENABLED for /publish requests; N="\r
+ + numRequests + ", M=" + samplingPeriod\r
+ ", Action=" + action);\r
return;\r
}\r
map.clear();\r
}\r
\r
- private static int getInt(String s, int deflt) {\r
+ private static int getInt(String str, int deflt) {\r
try {\r
- return Integer.parseInt(s);\r
+ return Integer.parseInt(str);\r
} catch (NumberFormatException x) {\r
return deflt;\r
}\r
}\r
}\r
\r
+ /**\r
+ * Method to drop filter chain.\r
+ * @param request HttpServletRequest\r
+ * @param response HttpServletResponse\r
+ * @param chain FilterChain\r
+ * @throws IOException input/output exception\r
+ * @throws ServletException servle exception\r
+ */\r
public void dropFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)\r
throws IOException, ServletException {\r
int rate = getRequestRate(request);\r
if (rate >= numRequests) {\r
// drop request - only works under Jetty\r
- String m = String.format("Dropping connection: %s %d bad connections in %d minutes", getConnectionId(request), rate,\r
+ String str = String.format("Dropping connection: %s %d bad connections in %d minutes",\r
+ getConnectionId(request), rate,\r
samplingPeriod);\r
- logger.info(m);\r
+ logger.info(str);\r
Request baseRequest = (request instanceof Request)\r
? (Request) request\r
: HttpConnection.getCurrentConnection().getHttpChannel().getRequest();\r
int rate = getRequestRate(request);\r
Object results = request.getAttribute(THROTTLE_MARKER);\r
if (rate >= numRequests && results == null) {\r
- String m = String.format("Throttling connection: %s %d bad connections in %d minutes",\r
+ String str = String.format("Throttling connection: %s %d bad connections in %d minutes",\r
getConnectionId(request), rate, samplingPeriod);\r
- logger.info(m);\r
+ logger.info(str);\r
Continuation continuation = ContinuationSupport.getContinuation(request);\r
continuation.suspend();\r
register(id, continuation);\r
chain.doFilter(request, response);\r
@SuppressWarnings("resource")\r
InputStream is = request.getInputStream();\r
- byte[] b = new byte[4096];\r
- int n = is.read(b);\r
- while (n > 0) {\r
- n = is.read(b);\r
+ byte[] bite = new byte[4096];\r
+ int num = is.read(bite);\r
+ while (num > 0) {\r
+ num = is.read(bite);\r
}\r
resume(id);\r
}\r
*/\r
private int getRequestRate(HttpServletRequest request) {\r
String expecthdr = request.getHeader("Expect");\r
- if (expecthdr != null && "100-continue".equalsIgnoreCase(expecthdr))\r
+ if (expecthdr != null && "100-continue".equalsIgnoreCase(expecthdr)) {\r
return 0;\r
+ }\r
\r
String key = getConnectionId(request);\r
synchronized (map) {\r
public class Counter {\r
private List<Long> times = new ArrayList<>(); // a record of request times\r
\r
+ /**\r
+ * Method to prune request rate.\r
+ * @return times\r
+ */\r
public int prune() {\r
try {\r
- long n = System.currentTimeMillis() - (samplingPeriod * ONE_MINUTE);\r
- long t = times.get(0);\r
- while (t < n) {\r
+ long num = System.currentTimeMillis() - (samplingPeriod * ONE_MINUTE);\r
+ long time = times.get(0);\r
+ while (time < num) {\r
times.remove(0);\r
- t = times.get(0);\r
+ time = times.get(0);\r
}\r
} catch (IndexOutOfBoundsException e) {\r
logger.trace("Exception: " + e.getMessage(), e);\r
\r
private int getFeedId(HttpServletRequest req) {\r
String path = req.getPathInfo();\r
- if (path == null || path.length() < 2)\r
+ if (path == null || path.length() < 2) {\r
return -1;\r
+ }\r
path = path.substring(1);\r
int ix = path.indexOf('/');\r
- if (ix < 0 || ix == path.length() - 1)\r
+ if (ix < 0 || ix == path.length() - 1) {\r
return -2;\r
+ }\r
try {\r
return Integer.parseInt(path.substring(0, ix));\r
} catch (NumberFormatException e) {\r
// Once every 5 minutes, go through the map, and remove empty entrys\r
for (Object s : map.keySet().toArray()) {\r
synchronized (map) {\r
- Counter c = map.get(s);\r
- if (c.prune() <= 0)\r
+ Counter counter = map.get(s);\r
+ if (counter.prune() <= 0) {\r
map.remove(s);\r
+ }\r
}\r
}\r
}\r
*/\r
public class URLUtilities {\r
\r
+\r
private static final EELFLogger utilsLogger = EELFManager.getInstance().getLogger("UtilsLog");\r
private static final String HTTPS = "https://";\r
private static String otherPod;\r