From a9002c0a305c1af016272deb9fc2e2ffd1160d55 Mon Sep 17 00:00:00 2001 From: Ronan Keogh Date: Sat, 25 Aug 2018 21:27:49 +0100 Subject: [PATCH] datarouter node updates to address sonar issues Change-Id: I941b54a720f7a51236a024c857dd30f726dd482a Issue-ID: DMAAP-557 Signed-off-by: Ronan Keogh --- .../onap/dmaap/datarouter/node/DeliveryTask.java | 75 +++++------ .../org/onap/dmaap/datarouter/node/LogManager.java | 39 +++--- .../org/onap/dmaap/datarouter/node/NodeMain.java | 35 +++-- .../onap/dmaap/datarouter/node/NodeServlet.java | 144 +++++++++++++-------- .../onap/dmaap/datarouter/node/RedirManager.java | 62 +++++---- 5 files changed, 204 insertions(+), 151 deletions(-) diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/DeliveryTask.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/DeliveryTask.java index c28827a0..7e10d5a0 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/DeliveryTask.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/DeliveryTask.java @@ -79,33 +79,31 @@ public class DeliveryTask implements Runnable, Comparable { boolean monly = di.isMetaDataOnly(); date = Long.parseLong(pubid.substring(0, pubid.indexOf('.'))); Vector hdrv = new Vector(); - try { - try(BufferedReader br = new BufferedReader(new FileReader(metafile))){ - String s = br.readLine(); - int i = s.indexOf('\t'); - method = s.substring(0, i); - if (!"DELETE".equals(method) && !monly) { - length = datafile.length(); + + try (BufferedReader br = new BufferedReader(new FileReader(metafile))) { + String s = br.readLine(); + int i = s.indexOf('\t'); + method = s.substring(0, i); + if (!"DELETE".equals(method) && !monly) { + length = datafile.length(); + } + fileid = s.substring(i + 1); + while ((s = br.readLine()) != null) { + i = s.indexOf('\t'); + String h = s.substring(0, i); + String v = s.substring(i + 1); + if ("x-att-dr-routing".equalsIgnoreCase(h)) { + subid = v.replaceAll("[^ ]*/", ""); + feedid = dth.getFeedId(subid.replaceAll(" .*", "")); } - fileid = s.substring(i + 1); - while ((s = br.readLine()) != null) { - i = s.indexOf('\t'); - String h = s.substring(0, i); - String v = s.substring(i + 1); - if ("x-att-dr-routing".equalsIgnoreCase(h)) { - subid = v.replaceAll("[^ ]*/", ""); - feedid = dth.getFeedId(subid.replaceAll(" .*", "")); - } - if (length == 0 && h.toLowerCase().startsWith("content-")) { - continue; - } - if (h.equalsIgnoreCase("content-type")) { - ctype = v; - } - hdrv.add(new String[]{h, v}); + if (length == 0 && h.toLowerCase().startsWith("content-")) { + continue; + } + if (h.equalsIgnoreCase("content-type")) { + ctype = v; } + hdrv.add(new String[]{h, v}); } - } catch (Exception e) { loggerDeliveryTask.error("Exception "+e.getStackTrace(),e); } @@ -191,29 +189,24 @@ public class DeliveryTask implements Runnable, Comparable { } if (os != null) { long sofar = 0; - try { + try (InputStream is = new FileInputStream(datafile)) { byte[] buf = new byte[1024 * 1024]; - try(InputStream is = new FileInputStream(datafile)){ - while (sofar < length) { - int i = buf.length; - if (sofar + i > length) { - i = (int) (length - sofar); - } - i = is.read(buf, 0, i); - if (i <= 0) { - throw new IOException("Unexpected problem reading data file " + datafile); - } - sofar += i; - os.write(buf, 0, i); + while (sofar < length) { + int i = buf.length; + if (sofar + i > length) { + i = (int) (length - sofar); } - is.close(); - os.close(); + i = is.read(buf, 0, i); + if (i <= 0) { + throw new IOException("Unexpected problem reading data file " + datafile); + } + sofar += i; + os.write(buf, 0, i); } - + os.close(); } catch (IOException ioe) { dth.reportDeliveryExtra(this, sofar); throw ioe; - } } } diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/LogManager.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/LogManager.java index ade47730..ee81a321 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/LogManager.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/LogManager.java @@ -22,22 +22,28 @@ ******************************************************************************/ package org.onap.dmaap.datarouter.node; -import java.util.*; -import java.util.regex.*; -import java.io.*; -import java.nio.file.*; -import java.text.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.Writer; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.TimerTask; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Cleanup of old log files. *

- * Periodically scan the log directory for log files that are older than - * the log file retention interval, and delete them. In a future release, - * This class will also be responsible for uploading events logs to the - * log server to support the log query APIs. + * Periodically scan the log directory for log files that are older than the log file retention interval, and delete + * them. In a future release, This class will also be responsible for uploading events logs to the log server to + * support the log query APIs. */ public class LogManager extends TimerTask { + private NodeConfigManager config; private Matcher isnodelog; private Matcher iseventlog; @@ -46,6 +52,7 @@ public class LogManager extends TimerTask { private String logdir; private class Uploader extends Thread implements DeliveryQueueHelper { + public long getInitFailureTimer() { return (10000L); } @@ -92,7 +99,9 @@ public class LogManager extends TimerTask { private DeliveryQueue dq; public Uploader() { - dq = new DeliveryQueue(this, new DestInfo("LogUpload", uploaddir, null, null, null, config.getMyName(), config.getMyAuth(), false, false)); + dq = new DeliveryQueue(this, + new DestInfo("LogUpload", uploaddir, null, null, null, config.getMyName(), config.getMyAuth(), false, + false)); setDaemon(true); setName("Log Uploader"); start(); @@ -154,11 +163,9 @@ public class LogManager extends TimerTask { f.delete(); } } - try { + try (Writer w = new FileWriter(uploaddir + "/.lastqueued")) { (new File(uploaddir + "/.meta")).delete(); - Writer w = new FileWriter(uploaddir + "/.lastqueued"); w.write(lastqueued + "\n"); - w.close(); } catch (Exception e) { } } @@ -167,10 +174,8 @@ public class LogManager extends TimerTask { /** * Construct a log manager *

- * The log manager will check for expired log files every 5 minutes - * at 20 seconds after the 5 minute boundary. (Actually, the - * interval is the event log rollover interval, which - * defaults to 5 minutes). + * The log manager will check for expired log files every 5 minutes at 20 seconds after the 5 minute boundary. + * (Actually, the interval is the event log rollover interval, which defaults to 5 minutes). */ public LogManager(NodeConfigManager config) { this.config = config; diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeMain.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeMain.java index 006dc88c..e0f6b7f6 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeMain.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeMain.java @@ -23,13 +23,19 @@ package org.onap.dmaap.datarouter.node; -import org.eclipse.jetty.http.HttpVersion; -import org.eclipse.jetty.servlet.*; -import org.eclipse.jetty.util.ssl.*; -import org.eclipse.jetty.server.*; -import org.apache.log4j.Logger; - import java.util.Arrays; +import org.apache.log4j.Logger; +import org.eclipse.jetty.http.HttpVersion; +import org.eclipse.jetty.server.Connector; +import org.eclipse.jetty.server.HttpConfiguration; +import org.eclipse.jetty.server.HttpConnectionFactory; +import org.eclipse.jetty.server.SecureRequestCustomizer; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.server.SslConnectionFactory; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.util.ssl.SslContextFactory; /** * The main starting point for the Data Router node @@ -60,7 +66,9 @@ public class NodeMain { try { wait(); } catch (Exception exception) { - nodeMainLogger.debug("NodeMain: waitForConfig exception. Exception Message:- " + exception.toString(), exception); + nodeMainLogger + .debug("NodeMain: waitForConfig exception. Exception Message:- " + exception.toString(), + exception); } } localNodeConfigManager.deregisterConfigTask(this); @@ -123,14 +131,15 @@ public class NodeMain { httpsConfiguration.addCustomizer(secureRequestCustomizer); // HTTPS connector - ServerConnector httpsServerConnector = new ServerConnector(server, + try (ServerConnector httpsServerConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), - new HttpConnectionFactory(httpsConfiguration)); - httpsServerConnector.setPort(nodeConfigManager.getHttpsPort()); - httpsServerConnector.setIdleTimeout(500000); - httpsServerConnector.setAcceptQueueSize(2); + new HttpConnectionFactory(httpsConfiguration))) { + httpsServerConnector.setPort(nodeConfigManager.getHttpsPort()); + httpsServerConnector.setIdleTimeout(500000); + httpsServerConnector.setAcceptQueueSize(2); - server.setConnectors(new Connector[]{httpServerConnector, httpsServerConnector}); + server.setConnectors(new Connector[]{httpServerConnector, httpsServerConnector}); + } } ctxt = new ServletContextHandler(0); ctxt.setContextPath("/"); diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeServlet.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeServlet.java index 5d11206c..9ddbc25a 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeServlet.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeServlet.java @@ -24,20 +24,28 @@ package org.onap.dmaap.datarouter.node; -import javax.servlet.*; -import javax.servlet.http.*; -import java.util.*; -import java.util.regex.*; -import java.io.*; -import java.nio.file.*; - -import org.apache.log4j.Logger; -import org.onap.dmaap.datarouter.node.eelf.EelfMsgs; - import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; - -import java.net.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Writer; +import java.net.Socket; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Enumeration; +import java.util.regex.Pattern; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.apache.log4j.Logger; +import org.onap.dmaap.datarouter.node.eelf.EelfMsgs; /** * Servlet for handling all http and https requests to the data router node @@ -51,23 +59,25 @@ import java.net.*; * PUT/DELETE https://node/publish/feedid/fileid - publsh request */ public class NodeServlet extends HttpServlet { + private static Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.node.NodeServlet"); private static NodeConfigManager config; private static Pattern MetaDataPattern; private static SubnetMatcher internalsubnet = new SubnetMatcher("135.207.136.128/25"); //Adding EELF Logger Rally:US664892 - private static EELFLogger eelflogger = EELFManager.getInstance().getLogger("org.onap.dmaap.datarouter.node.NodeServlet"); + private static EELFLogger eelflogger = EELFManager.getInstance() + .getLogger("org.onap.dmaap.datarouter.node.NodeServlet"); static { try { - String ws = "\\s*"; + final String ws = "\\s*"; // assume that \\ and \" have been replaced by X - String string = "\"[^\"]*\""; + final String string = "\"[^\"]*\""; //String string = "\"(?:[^\"\\\\]|\\\\.)*\""; - String number = "[+-]?(?:\\.\\d+|(?:0|[1-9]\\d*)(?:\\.\\d*)?)(?:[eE][+-]?\\d+)?"; - String value = "(?:" + string + "|" + number + "|null|true|false)"; - String item = string + ws + ":" + ws + value + ws; - String object = ws + "\\{" + ws + "(?:" + item + "(?:" + "," + ws + item + ")*)?\\}" + ws; + final String number = "[+-]?(?:\\.\\d+|(?:0|[1-9]\\d*)(?:\\.\\d*)?)(?:[eE][+-]?\\d+)?"; + final String value = "(?:" + string + "|" + number + "|null|true|false)"; + final String item = string + ws + ":" + ws + value + ws; + final String object = ws + "\\{" + ws + "(?:" + item + "(?:" + "," + ws + item + ")*)?\\}" + ws; MetaDataPattern = Pattern.compile(object, Pattern.DOTALL); } catch (Exception e) { } @@ -95,7 +105,8 @@ public class NodeServlet extends HttpServlet { */ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { NodeUtils.setIpAndFqdnForEelf("doGet"); - eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"), getIdFromPath(req) + ""); + eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"), + getIdFromPath(req) + ""); if (down(resp)) { return; } @@ -130,13 +141,13 @@ public class NodeServlet extends HttpServlet { resp.setContentType("text/plain"); resp.setContentLength((int) fn.length()); resp.setStatus(200); - InputStream is = new FileInputStream(fn); - OutputStream os = resp.getOutputStream(); - int i; - while ((i = is.read(buf)) > 0) { - os.write(buf, 0, i); + try (InputStream is = new FileInputStream(fn)) { + OutputStream os = resp.getOutputStream(); + int i; + while ((i = is.read(buf)) > 0) { + os.write(buf, 0, i); + } } - is.close(); return; } if (path.startsWith("/internal/rtt/")) { @@ -161,7 +172,6 @@ public class NodeServlet extends HttpServlet { } logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip); resp.sendError(HttpServletResponse.SC_NOT_FOUND); - return; } /** @@ -169,7 +179,8 @@ public class NodeServlet extends HttpServlet { */ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { NodeUtils.setIpAndFqdnForEelf("doPut"); - eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"), getIdFromPath(req) + ""); + eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"), + getIdFromPath(req) + ""); common(req, resp, true); } @@ -178,30 +189,36 @@ public class NodeServlet extends HttpServlet { */ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { NodeUtils.setIpAndFqdnForEelf("doDelete"); - eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"), getIdFromPath(req) + ""); + eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"), + getIdFromPath(req) + ""); common(req, resp, false); } - private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput) throws ServletException, IOException { + private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput) + throws ServletException, IOException { if (down(resp)) { return; } if (!req.isSecure()) { - logger.info("NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr()); + logger.info( + "NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr()); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "https required on publish requests"); return; } String fileid = req.getPathInfo(); if (fileid == null) { - logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr()); - resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid request URI. Expecting /."); + logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req + .getRemoteAddr()); + resp.sendError(HttpServletResponse.SC_NOT_FOUND, + "Invalid request URI. Expecting /."); return; } String feedid = null; String user = null; String credentials = req.getHeader("Authorization"); if (credentials == null) { - logger.info("NODE0106 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr()); + logger.info("NODE0106 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + " from " + req + .getRemoteAddr()); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization header required"); return; } @@ -215,8 +232,10 @@ public class NodeServlet extends HttpServlet { fileid = fileid.substring(9); int i = fileid.indexOf('/'); if (i == -1 || i == fileid.length() - 1) { - logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr()); - resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid request URI. Expecting /. Possible missing fileid."); + logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req + .getRemoteAddr()); + resp.sendError(HttpServletResponse.SC_NOT_FOUND, + "Invalid request URI. Expecting /. Possible missing fileid."); return; } feedid = fileid.substring(0, i); @@ -234,13 +253,17 @@ public class NodeServlet extends HttpServlet { pubid = req.getHeader("X-ATT-DR-PUBLISH-ID"); targets = config.parseRouting(req.getHeader("X-ATT-DR-ROUTING")); } else { - logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr()); - resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid request URI. Expecting /."); + logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req + .getRemoteAddr()); + resp.sendError(HttpServletResponse.SC_NOT_FOUND, + "Invalid request URI. Expecting /."); return; } if (fileid.indexOf('/') != -1) { - logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr()); - resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid request URI. Expecting /."); + logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req + .getRemoteAddr()); + resp.sendError(HttpServletResponse.SC_NOT_FOUND, + "Invalid request URI. Expecting /."); return; } String qs = req.getQueryString(); @@ -257,7 +280,9 @@ public class NodeServlet extends HttpServlet { logurl = "https://" + hp + "/publish/" + feedid + "/" + fileid; String reason = config.isPublishPermitted(feedid, credentials, ip); if (reason != null) { - logger.info("NODE0111 Rejecting unauthorized publish attempt to feed " + feedid + " fileid " + fileid + " from " + ip + " reason " + reason); + logger.info( + "NODE0111 Rejecting unauthorized publish attempt to feed " + feedid + " fileid " + fileid + " from " + + ip + " reason " + reason); resp.sendError(HttpServletResponse.SC_FORBIDDEN, reason); return; } @@ -270,7 +295,9 @@ public class NodeServlet extends HttpServlet { port = ":" + iport; } String redirto = "https://" + newnode + port + "/publish/" + feedid + "/" + fileid; - logger.info("NODE0108 Redirecting publish attempt for feed " + feedid + " user " + user + " ip " + ip + " to " + redirto); + logger.info( + "NODE0108 Redirecting publish attempt for feed " + feedid + " user " + user + " ip " + ip + " to " + + redirto); resp.sendRedirect(redirto); return; } @@ -291,12 +318,12 @@ public class NodeServlet extends HttpServlet { String hn = (String) hnames.nextElement(); String hnlc = hn.toLowerCase(); if ((isput && ("content-type".equals(hnlc) || - "content-language".equals(hnlc) || - "content-md5".equals(hnlc) || - "content-range".equals(hnlc))) || - "x-att-dr-meta".equals(hnlc) || - (feedid == null && "x-att-dr-received".equals(hnlc)) || - (hnlc.startsWith("x-") && !hnlc.startsWith("x-att-dr-"))) { + "content-language".equals(hnlc) || + "content-md5".equals(hnlc) || + "content-range".equals(hnlc))) || + "x-att-dr-meta".equals(hnlc) || + (feedid == null && "x-att-dr-received".equals(hnlc)) || + (hnlc.startsWith("x-") && !hnlc.startsWith("x-att-dr-"))) { Enumeration hvals = req.getHeaders(hn); while (hvals.hasMoreElements()) { String hv = (String) hvals.nextElement(); @@ -305,12 +332,16 @@ public class NodeServlet extends HttpServlet { } if ("x-att-dr-meta".equals(hnlc)) { if (hv.length() > 4096) { - logger.info("NODE0109 Rejecting publish attempt with metadata too long for feed " + feedid + " user " + user + " ip " + ip); + logger.info( + "NODE0109 Rejecting publish attempt with metadata too long for feed " + feedid + + " user " + user + " ip " + ip); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Metadata too long"); return; } if (!MetaDataPattern.matcher(hv.replaceAll("\\\\.", "X")).matches()) { - logger.info("NODE0109 Rejecting publish attempt with malformed metadata for feed " + feedid + " user " + user + " ip " + ip); + logger.info( + "NODE0109 Rejecting publish attempt with malformed metadata for feed " + feedid + + " user " + user + " ip " + ip); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed metadata"); return; } @@ -339,7 +370,8 @@ public class NodeServlet extends HttpServlet { exlen = Long.parseLong(req.getHeader("Content-Length")); } catch (Exception e) { } - StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user, ioe.getMessage()); + StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user, + ioe.getMessage()); throw ioe; } Path dpath = Paths.get(fbase); @@ -361,9 +393,12 @@ public class NodeServlet extends HttpServlet { } resp.setStatus(HttpServletResponse.SC_NO_CONTENT); resp.getOutputStream().close(); - StatusLog.logPub(pubid, feedid, logurl, req.getMethod(), ctype, data.length(), ip, user, HttpServletResponse.SC_NO_CONTENT); + StatusLog.logPub(pubid, feedid, logurl, req.getMethod(), ctype, data.length(), ip, user, + HttpServletResponse.SC_NO_CONTENT); } catch (IOException ioe) { - logger.info("NODE0110 IO Exception receiving publish attempt for feed " + feedid + " user " + user + " ip " + ip + " " + ioe.toString(), ioe); + logger.info( + "NODE0110 IO Exception receiving publish attempt for feed " + feedid + " user " + user + " ip " + ip + + " " + ioe.toString(), ioe); throw ioe; } finally { if (is != null) { @@ -397,8 +432,9 @@ public class NodeServlet extends HttpServlet { private int getIdFromPath(HttpServletRequest req) { String path = req.getPathInfo(); - if (path == null || path.length() < 2) + if (path == null || path.length() < 2) { return -1; + } try { return Integer.parseInt(path.substring(1)); } catch (NumberFormatException e) { diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/RedirManager.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/RedirManager.java index a557e7ad..7e4078f8 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/RedirManager.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/RedirManager.java @@ -24,13 +24,18 @@ package org.onap.dmaap.datarouter.node; -import java.util.*; -import java.io.*; +import java.io.BufferedReader; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.OutputStream; +import java.util.Hashtable; +import java.util.Timer; /** * Track redirections of subscriptions */ public class RedirManager { + private Hashtable sid2primary = new Hashtable(); private Hashtable sid2secondary = new Hashtable(); private String redirfile; @@ -39,9 +44,10 @@ public class RedirManager { /** * Create a mechanism for maintaining subscription redirections. * - * @param redirfile The file to store the redirection information. - * @param mininterval The minimum number of milliseconds between writes to the redirection information file. - * @param timer The timer thread used to run delayed file writes. + * @param redirfile The file to store the redirection information. + * @param mininterval The minimum number of milliseconds between writes to the redirection + * information file. + * @param timer The timer thread used to run delayed file writes. */ public RedirManager(String redirfile, long mininterval, Timer timer) { this.redirfile = redirfile; @@ -50,38 +56,40 @@ public class RedirManager { try { StringBuffer sb = new StringBuffer(); for (String s : sid2primary.keySet()) { - sb.append(s).append(' ').append(sid2primary.get(s)).append(' ').append(sid2secondary.get(s)).append('\n'); + sb.append(s).append(' ').append(sid2primary.get(s)).append(' ') + .append(sid2secondary.get(s)).append('\n'); + } + try (OutputStream os = new FileOutputStream(RedirManager.this.redirfile)) { + os.write(sb.toString().getBytes()); } - OutputStream os = new FileOutputStream(RedirManager.this.redirfile); - os.write(sb.toString().getBytes()); - os.close(); } catch (Exception e) { } } }; try { String s; - BufferedReader br = new BufferedReader(new FileReader(redirfile)); - while ((s = br.readLine()) != null) { - s = s.trim(); - String[] sx = s.split(" "); - if (s.startsWith("#") || sx.length != 3) { - continue; + try (BufferedReader br = new BufferedReader(new FileReader(redirfile))) { + while ((s = br.readLine()) != null) { + s = s.trim(); + String[] sx = s.split(" "); + if (s.startsWith("#") || sx.length != 3) { + continue; + } + sid2primary.put(sx[0], sx[1]); + sid2secondary.put(sx[0], sx[2]); } - sid2primary.put(sx[0], sx[1]); - sid2secondary.put(sx[0], sx[2]); } - br.close(); } catch (Exception e) { // missing file is normal } } /** - * Set up redirection. If a request is to be sent to subscription ID sid, and that is configured to go to URL primary, instead, go to secondary. + * Set up redirection. If a request is to be sent to subscription ID sid, and that is + * configured to go to URL primary, instead, go to secondary. * - * @param sid The subscription ID to be redirected - * @param primary The URL associated with that subscription ID + * @param sid The subscription ID to be redirected + * @param primary The URL associated with that subscription ID * @param secondary The replacement URL to use instead */ public synchronized void redirect(String sid, String primary, String secondary) { @@ -91,9 +99,10 @@ public class RedirManager { } /** - * Cancel redirection. If a request is to be sent to subscription ID sid, send it to its primary URL. + * Cancel redirection. If a request is to be sent to subscription ID sid, send it to its + * primary URL. * - * @param sid The subscription ID to remove from the table. + * @param sid The subscription ID to remove from the table. */ public synchronized void forget(String sid) { sid2primary.remove(sid); @@ -102,10 +111,11 @@ public class RedirManager { } /** - * Look up where to send a subscription. If the primary has changed or there is no redirection, use the primary. Otherwise, redirect to the secondary URL. + * Look up where to send a subscription. If the primary has changed or there is no redirection, + * use the primary. Otherwise, redirect to the secondary URL. * - * @param sid The subscription ID to look up. - * @param primary The configured primary URL. + * @param sid The subscription ID to look up. + * @param primary The configured primary URL. * @return The destination URL to really use. */ public synchronized String lookup(String sid, String primary) { -- 2.16.6