diff options
30 files changed, 1321 insertions, 812 deletions
diff --git a/ci_scripts/onap-style-java.xml b/ci_scripts/onap-style-java.xml index 89b25682..502ea7ac 100644 --- a/ci_scripts/onap-style-java.xml +++ b/ci_scripts/onap-style-java.xml @@ -169,7 +169,7 @@ </module> <module name="AbbreviationAsWordInName"> <property name="ignoreFinal" value="false"/> - <property name="allowedAbbreviationLength" value="3"/> + <property name="allowedAbbreviationLength" value="20"/> </module> <module name="OverloadMethodsDeclarationOrder"/> <module name="VariableDeclarationUsageDistance"/> diff --git a/datarouter-node/pom.xml b/datarouter-node/pom.xml index 06aa3fcf..a4de6f76 100755 --- a/datarouter-node/pom.xml +++ b/datarouter-node/pom.xml @@ -128,6 +128,11 @@ <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> + <dependency> + <groupId>org.awaitility</groupId> + <artifactId>awaitility</artifactId> + <version>3.1.6</version> + </dependency> </dependencies> <profiles> <profile> diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/Delivery.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/Delivery.java index 9af8ed77..150d2aa2 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/Delivery.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/Delivery.java @@ -28,7 +28,7 @@ import com.att.eelf.configuration.EELFManager; import java.io.File; import java.util.ArrayList; import java.util.Arrays; -import java.util.Hashtable; +import java.util.HashMap; import java.util.Objects; /** @@ -50,7 +50,7 @@ public class Delivery { private int threads; private int curthreads; private NodeConfigManager config; - private Hashtable<String, DeliveryQueue> dqs = new Hashtable<>(); + private HashMap<String, DeliveryQueue> dqs = new HashMap<>(); private DeliveryQueue[] queues = new DeliveryQueue[0]; private int qpos = 0; private long nextcheck; @@ -178,7 +178,7 @@ public class Delivery { DestInfo[] alldis = config.getAllDests(); DeliveryQueue[] nqs = new DeliveryQueue[alldis.length]; qpos = 0; - Hashtable<String, DeliveryQueue> ndqs = new Hashtable<>(); + HashMap<String, DeliveryQueue> ndqs = new HashMap<>(); for (DestInfo di : alldis) { String spl = di.getSpool(); DeliveryQueue dq = dqs.get(spl); @@ -266,7 +266,7 @@ public class Delivery { return false; } - private static class DelItem implements Comparable<DelItem> { + static class DelItem implements Comparable<DelItem> { private String pubid; private String spool; 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 2093d6d4..bbd13912 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,11 +79,11 @@ public class DeliveryTask implements Runnable, Comparable<DeliveryTask> { /** - * Create a delivery task for a given delivery queue and pub ID + * Create a delivery task for a given delivery queue and pub ID. * * @param deliveryTaskHelper The delivery task helper for the queue this task is in. * @param pubid The publish ID for this file. This is used as the base for the file name in the spool directory and - * is of the form <milliseconds since 1970>.<fqdn of initial data router node> + * is of the form (milliseconds since 1970).(fqdn of initial data router node) */ DeliveryTask(DeliveryTaskHelper deliveryTaskHelper, String pubid) { this.deliveryTaskHelper = deliveryTaskHelper; 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 3277408c..cf3b29a5 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 @@ -48,6 +48,7 @@ import org.jetbrains.annotations.NotNull; public class LogManager extends TimerTask { + private static final String EXCEPTION = "Exception"; private EELFLogger logger = EELFManager.getInstance().getLogger(LogManager.class); private NodeConfigManager config; private Matcher isnodelog; @@ -68,7 +69,7 @@ public class LogManager extends TimerTask { isnodelog = Pattern.compile("node\\.log\\.\\d{8}").matcher(""); iseventlog = Pattern.compile("events-\\d{12}\\.log").matcher(""); } catch (Exception e) { - logger.error("Exception", e); + logger.error(EXCEPTION, e); } logdir = config.getLogDir(); uploaddir = logdir + "/.spool"; @@ -87,9 +88,12 @@ public class LogManager extends TimerTask { worker.poke(); } - private class Uploader extends Thread implements DeliveryQueueHelper { + public Uploader getWorker() { + return worker; + } + + class Uploader extends Thread implements DeliveryQueueHelper { - private static final String EXCEPTION = "Exception"; private static final String META = "/.meta"; private EELFLogger logger = EELFManager.getInstance().getLogger(Uploader.class); private DeliveryQueue dq; @@ -166,6 +170,7 @@ public class LogManager extends TimerTask { notify(); } + @Override public void run() { while (true) { scan(); diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeConfig.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeConfig.java index 7f018210..127668ff 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeConfig.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeConfig.java @@ -31,6 +31,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import org.jetbrains.annotations.NotNull; /** * Processed configuration for this node. @@ -68,6 +69,21 @@ public class NodeConfig { for (ProvParam p : pd.getParams()) { params.put(p.getName(), p.getValue()); } + ArrayList<DestInfo> destInfos = addDestInfoToNodeConfig(pd, myname, spooldir, port, nodeauthkey); + PathFinder pf = new PathFinder(myname, nodeinfo.keySet().toArray(new String[0]), pd.getHops()); + HashMap<String, ArrayList<Redirection>> rdtab = addSubRedirInfoToNodeConfig(pd); + HashMap<String, HashMap<String, String>> pfutab = addFeedUsersToNodeConfig(pd); + HashMap<String, String> egrtab = addEgressRoutesToNodeConfig(pd, myname); + HashMap<String, ArrayList<SubnetMatcher>> pfstab = addFeedSubnetToNodeConfig(pd); + HashSet<String> allfeeds = addFeedsToNodeConfig(pd); + HashMap<String, StringBuilder> feedTargets = addSubsToNodeConfig(pd, spooldir, destInfos, pf, egrtab, allfeeds); + alldests = destInfos.toArray(new DestInfo[0]); + addFeedTargetsToNodeConfig(pd, rdtab, pfutab, pfstab, feedTargets); + } + + @NotNull + private ArrayList<DestInfo> addDestInfoToNodeConfig(ProvData pd, String myname, String spooldir, int port, + String nodeauthkey) { ArrayList<DestInfo> destInfos = new ArrayList<>(); myauth = NodeUtils.getNodeAuthHdr(myname, nodeauthkey); for (ProvNode pn : pd.getNodes()) { @@ -86,31 +102,45 @@ public class NodeConfig { nodeinfo.put(commonName, di); nodes.put(auth, new IsFrom(commonName)); } - PathFinder pf = new PathFinder(myname, nodeinfo.keySet().toArray(new String[0]), pd.getHops()); + return destInfos; + } + + @NotNull + private HashMap<String, ArrayList<Redirection>> addSubRedirInfoToNodeConfig(ProvData pd) { HashMap<String, ArrayList<Redirection>> rdtab = new HashMap<>(); for (ProvForceIngress pfi : pd.getForceIngress()) { - ArrayList<Redirection> v = rdtab.get(pfi.getFeedId()); - if (v == null) { - v = new ArrayList<>(); - rdtab.put(pfi.getFeedId(), v); + ArrayList<Redirection> redirections = rdtab.get(pfi.getFeedId()); + if (redirections == null) { + redirections = new ArrayList<>(); + rdtab.put(pfi.getFeedId(), redirections); } - Redirection r = new Redirection(); + Redirection redirection = new Redirection(); if (pfi.getSubnet() != null) { - r.snm = new SubnetMatcher(pfi.getSubnet()); + redirection.snm = new SubnetMatcher(pfi.getSubnet()); } - r.user = pfi.getUser(); - r.nodes = pfi.getNodes(); - v.add(r); + redirection.user = pfi.getUser(); + redirection.nodes = pfi.getNodes(); + redirections.add(redirection); } + return rdtab; + } + + @NotNull + private HashMap<String, HashMap<String, String>> addFeedUsersToNodeConfig(ProvData pd) { HashMap<String, HashMap<String, String>> pfutab = new HashMap<>(); for (ProvFeedUser pfu : pd.getFeedUsers()) { - HashMap<String, String> t = pfutab.get(pfu.getFeedId()); - if (t == null) { - t = new HashMap<>(); - pfutab.put(pfu.getFeedId(), t); + HashMap<String, String> userInfo = pfutab.get(pfu.getFeedId()); + if (userInfo == null) { + userInfo = new HashMap<>(); + pfutab.put(pfu.getFeedId(), userInfo); } - t.put(pfu.getCredentials(), pfu.getUser()); + userInfo.put(pfu.getCredentials(), pfu.getUser()); } + return pfutab; + } + + @NotNull + private HashMap<String, String> addEgressRoutesToNodeConfig(ProvData pd, String myname) { HashMap<String, String> egrtab = new HashMap<>(); for (ProvForceEgress pfe : pd.getForceEgress()) { if (pfe.getNode().equals(myname) || nodeinfo.get(pfe.getNode()) == null) { @@ -118,22 +148,38 @@ public class NodeConfig { } egrtab.put(pfe.getSubId(), pfe.getNode()); } + return egrtab; + } + + @NotNull + private HashMap<String, ArrayList<SubnetMatcher>> addFeedSubnetToNodeConfig(ProvData pd) { HashMap<String, ArrayList<SubnetMatcher>> pfstab = new HashMap<>(); for (ProvFeedSubnet pfs : pd.getFeedSubnets()) { - ArrayList<SubnetMatcher> v = pfstab.get(pfs.getFeedId()); - if (v == null) { - v = new ArrayList<>(); - pfstab.put(pfs.getFeedId(), v); + ArrayList<SubnetMatcher> subnetMatchers = pfstab.get(pfs.getFeedId()); + if (subnetMatchers == null) { + subnetMatchers = new ArrayList<>(); + pfstab.put(pfs.getFeedId(), subnetMatchers); } - v.add(new SubnetMatcher(pfs.getCidr())); + subnetMatchers.add(new SubnetMatcher(pfs.getCidr())); } - HashMap<String, StringBuilder> feedTargets = new HashMap<>(); + return pfstab; + } + + @NotNull + private HashSet<String> addFeedsToNodeConfig(ProvData pd) { HashSet<String> allfeeds = new HashSet<>(); for (ProvFeed pfx : pd.getFeeds()) { if (pfx.getStatus() == null) { allfeeds.add(pfx.getId()); } } + return allfeeds; + } + + @NotNull + private HashMap<String, StringBuilder> addSubsToNodeConfig(ProvData pd, String spooldir, + ArrayList<DestInfo> destInfos, PathFinder pf, HashMap<String, String> egrtab, HashSet<String> allfeeds) { + HashMap<String, StringBuilder> feedTargets = new HashMap<>(); for (ProvSubscription provSubscription : pd.getSubscriptions()) { String subId = provSubscription.getSubId(); String feedId = provSubscription.getFeedId(); @@ -165,51 +211,56 @@ public class NodeConfig { } sb.append(' ').append(subId); } - alldests = destInfos.toArray(new DestInfo[0]); + return feedTargets; + } + + private void addFeedTargetsToNodeConfig(ProvData pd, HashMap<String, ArrayList<Redirection>> rdtab, + HashMap<String, HashMap<String, String>> pfutab, HashMap<String, ArrayList<SubnetMatcher>> pfstab, + HashMap<String, StringBuilder> feedTargets) { for (ProvFeed pfx : pd.getFeeds()) { String fid = pfx.getId(); - Feed f = feeds.get(fid); - if (f != null) { + Feed feed = feeds.get(fid); + if (feed != null) { continue; } - f = new Feed(); - feeds.put(fid, f); - f.createdDate = pfx.getCreatedDate(); - f.loginfo = pfx.getLogData(); - f.status = pfx.getStatus(); + feed = new Feed(); + feeds.put(fid, feed); + feed.createdDate = pfx.getCreatedDate(); + feed.loginfo = pfx.getLogData(); + feed.status = pfx.getStatus(); /* * AAF changes: TDP EPIC US# 307413 * Passing aafInstance from ProvFeed to identify legacy/AAF feeds */ - f.aafInstance = pfx.getAafInstance(); + feed.aafInstance = pfx.getAafInstance(); ArrayList<SubnetMatcher> v1 = pfstab.get(fid); if (v1 == null) { - f.subnets = new SubnetMatcher[0]; + feed.subnets = new SubnetMatcher[0]; } else { - f.subnets = v1.toArray(new SubnetMatcher[0]); + feed.subnets = v1.toArray(new SubnetMatcher[0]); } HashMap<String, String> h1 = pfutab.get(fid); if (h1 == null) { h1 = new HashMap(); } - f.authusers = h1; + feed.authusers = h1; ArrayList<Redirection> v2 = rdtab.get(fid); if (v2 == null) { - f.redirections = new Redirection[0]; + feed.redirections = new Redirection[0]; } else { - f.redirections = v2.toArray(new Redirection[0]); + feed.redirections = v2.toArray(new Redirection[0]); } StringBuilder sb = feedTargets.get(fid); if (sb == null) { - f.targets = new Target[0]; + feed.targets = new Target[0]; } else { - f.targets = parseRouting(sb.toString()); + feed.targets = parseRouting(sb.toString()); } } } /** - * Parse a target string into an array of targets + * Parse a target string into an array of targets. * * @param routing Target string * @return Array of targets. @@ -219,31 +270,31 @@ public class NodeConfig { if ("".equals(routing)) { return (new Target[0]); } - String[] xx = routing.split("\\s+"); + String[] routingTable = routing.split("\\s+"); HashMap<String, Target> tmap = new HashMap<>(); HashSet<String> subset = new HashSet<>(); - ArrayList<Target> tv = new ArrayList<>(); - for (int i = 0; i < xx.length; i++) { - String t = xx[i]; - int j = t.indexOf('/'); - if (j == -1) { - addTarget(subset, tv, t); + ArrayList<Target> targets = new ArrayList<>(); + for (int i = 0; i < routingTable.length; i++) { + String target = routingTable[i]; + int index = target.indexOf('/'); + if (index == -1) { + addTarget(subset, targets, target); } else { - addTargetWithRouting(tmap, tv, t, j); + addTargetWithRouting(tmap, targets, target, index); } } - return (tv.toArray(new Target[0])); + return (targets.toArray(new Target[0])); } /** - * Check whether this is a valid node-to-node transfer + * Check whether this is a valid node-to-node transfer. * * @param credentials Credentials offered by the supposed node * @param ip IP address the request came from */ public boolean isAnotherNode(String credentials, String ip) { - IsFrom n = nodes.get(credentials); - return (n != null && n.isFrom(ip)); + IsFrom node = nodes.get(credentials); + return (node != null && node.isFrom(ip)); } /** @@ -254,23 +305,23 @@ public class NodeConfig { * @param ip The requesting IP address */ public String isPublishPermitted(String feedid, String credentials, String ip) { - Feed f = feeds.get(feedid); + Feed feed = feeds.get(feedid); String nf = "Feed does not exist"; - if (f != null) { - nf = f.status; + if (feed != null) { + nf = feed.status; } if (nf != null) { return (nf); } - String user = f.authusers.get(credentials); + String user = feed.authusers.get(credentials); if (user == null) { return (PUBLISHER_NOT_PERMITTED); } - if (f.subnets.length == 0) { + if (feed.subnets.length == 0) { return (null); } byte[] addr = NodeUtils.getInetAddress(ip); - for (SubnetMatcher snm : f.subnets) { + for (SubnetMatcher snm : feed.subnets) { if (snm.matches(addr)) { return (null); } @@ -279,35 +330,25 @@ public class NodeConfig { } /** - * Check whether delete file is allowed. - * - * @param subId The ID of the subscription being requested. - */ - public boolean isDeletePermitted(String subId) { - ProvSubscription provSubscription = provSubscriptions.get(subId); - return provSubscription.isPrivilegedSubscriber(); - } - - /** * Check whether publication is allowed for AAF Feed. * * @param feedid The ID of the feed being requested. * @param ip The requesting IP address */ public String isPublishPermitted(String feedid, String ip) { - Feed f = feeds.get(feedid); + Feed feed = feeds.get(feedid); String nf = "Feed does not exist"; - if (f != null) { - nf = f.status; + if (feed != null) { + nf = feed.status; } if (nf != null) { return nf; } - if (f.subnets.length == 0) { + if (feed.subnets.length == 0) { return null; } byte[] addr = NodeUtils.getInetAddress(ip); - for (SubnetMatcher snm : f.subnets) { + for (SubnetMatcher snm : feed.subnets) { if (snm.matches(addr)) { return null; } @@ -316,32 +357,42 @@ public class NodeConfig { } /** - * Get authenticated user + * Check whether delete file is allowed. + * + * @param subId The ID of the subscription being requested. + */ + public boolean isDeletePermitted(String subId) { + ProvSubscription provSubscription = provSubscriptions.get(subId); + return provSubscription.isPrivilegedSubscriber(); + } + + /** + * Get authenticated user. */ public String getAuthUser(String feedid, String credentials) { return (feeds.get(feedid).authusers.get(credentials)); } /** - * AAF changes: TDP EPIC US# 307413 Check AAF_instance for feed ID + * AAF changes: TDP EPIC US# 307413 Check AAF_instance for feed ID. * * @param feedid The ID of the feed specified */ public String getAafInstance(String feedid) { - Feed f = feeds.get(feedid); - return f.aafInstance; + Feed feed = feeds.get(feedid); + return feed.aafInstance; } /** - * Check if the request should be redirected to a different ingress node + * Check if the request should be redirected to a different ingress node. */ public String getIngressNode(String feedid, String user, String ip) { - Feed f = feeds.get(feedid); - if (f.redirections.length == 0) { + Feed feed = feeds.get(feedid); + if (feed.redirections.length == 0) { return (null); } byte[] addr = NodeUtils.getInetAddress(ip); - for (Redirection r : f.redirections) { + for (Redirection r : feed.redirections) { if ((r.user != null && !user.equals(r.user)) || (r.snm != null && !r.snm.matches(addr))) { continue; } @@ -359,21 +410,21 @@ public class NodeConfig { } /** - * Get a provisioned configuration parameter + * Get a provisioned configuration parameter. */ public String getProvParam(String name) { return (params.get(name)); } /** - * Get all the DestInfos + * Get all the DestInfos. */ public DestInfo[] getAllDests() { return (alldests); } /** - * Get the targets for a feed + * Get the targets for a feed. * * @param feedid The feed ID * @return The targets this feed should be delivered to @@ -382,26 +433,26 @@ public class NodeConfig { if (feedid == null) { return (new Target[0]); } - Feed f = feeds.get(feedid); - if (f == null) { + Feed feed = feeds.get(feedid); + if (feed == null) { return (new Target[0]); } - return (f.targets); + return (feed.targets); } /** - * Get the creation date for a feed + * Get the creation date for a feed. * * @param feedid The feed ID * @return the timestamp of creation date of feed id passed */ public String getCreatedDate(String feedid) { - Feed f = feeds.get(feedid); - return (f.createdDate); + Feed feed = feeds.get(feedid); + return (feed.createdDate); } /** - * Get the feed ID for a subscription + * Get the feed ID for a subscription. * * @param subid The subscription ID * @return The feed ID @@ -415,7 +466,7 @@ public class NodeConfig { } /** - * Get the spool directory for a subscription + * Get the spool directory for a subscription. * * @param subid The subscription ID * @return The spool directory @@ -429,7 +480,7 @@ public class NodeConfig { } /** - * Get the Authorization value this node uses + * Get the Authorization value this node uses. * * @return The Authorization header value for this node */ @@ -441,38 +492,39 @@ public class NodeConfig { return !allfeeds.contains(feedId) || subinfo.get(subId) != null; } - private void addTargetWithRouting(HashMap<String, Target> tmap, ArrayList<Target> tv, String t, int j) { - String node = t.substring(0, j); - String rtg = t.substring(j + 1); + private void addTargetWithRouting(HashMap<String, Target> tmap, ArrayList<Target> targets, String target, + int index) { + String node = target.substring(0, index); + String rtg = target.substring(index + 1); DestInfo di = nodeinfo.get(node); if (di == null) { - tv.add(new Target(null, t)); + targets.add(new Target(null, target)); } else { Target tt = tmap.get(node); if (tt == null) { tt = new Target(di, rtg); tmap.put(node, tt); - tv.add(tt); + targets.add(tt); } else { tt.addRouting(rtg); } } } - private void addTarget(HashSet<String> subset, ArrayList<Target> tv, String t) { - DestInfo di = subinfo.get(t); - if (di == null) { - tv.add(new Target(null, t)); + private void addTarget(HashSet<String> subset, ArrayList<Target> targets, String target) { + DestInfo destInfo = subinfo.get(target); + if (destInfo == null) { + targets.add(new Target(null, target)); } else { - if (!subset.contains(t)) { - subset.add(t); - tv.add(new Target(di, null)); + if (!subset.contains(target)) { + subset.add(target); + targets.add(new Target(destInfo, null)); } } } /** - * Raw configuration entry for a data router node + * Raw configuration entry for a data router node. */ public static class ProvNode { @@ -488,7 +540,7 @@ public class NodeConfig { } /** - * Get the cname of the node + * Get the cname of the node. */ public String getCName() { return (cname); @@ -496,7 +548,7 @@ public class NodeConfig { } /** - * Raw configuration entry for a provisioning parameter + * Raw configuration entry for a provisioning parameter. */ public static class ProvParam { @@ -550,7 +602,7 @@ public class NodeConfig { * @param id The feed ID of the entry. * @param logdata String for log entries about the entry. * @param status The reason why this feed cannot be used (Feed has been deleted, Feed has been suspended) or - * null if it is valid. + * null if it is valid. */ public ProvFeed(String id, String logdata, String status, String createdDate, String aafInstance) { this.id = id; @@ -606,7 +658,7 @@ public class NodeConfig { private String credentials; /** - * Construct a feed user configuration entry + * Construct a feed user configuration entry. * * @param feedid The feed id. * @param user The user that will publish to the feed. @@ -641,7 +693,7 @@ public class NodeConfig { } /** - * Raw configuration entry for a feed subnet + * Raw configuration entry for a feed subnet. */ public static class ProvFeedSubnet { @@ -649,7 +701,7 @@ public class NodeConfig { private String cidr; /** - * Construct a feed subnet configuration entry + * Construct a feed subnet configuration entry. * * @param feedid The feed ID * @param cidr The CIDR allowed to publish to the feed. @@ -675,7 +727,7 @@ public class NodeConfig { } /** - * Raw configuration entry for a subscription + * Raw configuration entry for a subscription. */ public static class ProvSubscription { @@ -691,14 +743,14 @@ public class NodeConfig { private boolean decompress; /** - * Construct a subscription configuration entry + * Construct a subscription configuration entry. * * @param subid The subscription ID * @param feedid The feed ID * @param url The base delivery URL (not including the fileid) * @param authuser The user in the credentials used to deliver * @param credentials The credentials used to authenticate to the delivery URL exactly as they go in the - * Authorization header. + * Authorization header. * @param metaonly Is this a meta data only subscription? * @param use100 Should we send Expect: 100-continue? * @param privilegedSubscriber Can we wait to receive a delete file call before deleting file @@ -721,63 +773,63 @@ public class NodeConfig { } /** - * Get the subscription ID + * Get the subscription ID. */ public String getSubId() { return (subid); } /** - * Get the feed ID + * Get the feed ID. */ public String getFeedId() { return (feedid); } /** - * Get the delivery URL + * Get the delivery URL. */ public String getURL() { return (url); } /** - * Get the user + * Get the user. */ public String getAuthUser() { return (authuser); } /** - * Get the delivery credentials + * Get the delivery credentials. */ public String getCredentials() { return (credentials); } /** - * Is this a meta data only subscription? + * Is this a meta data only subscription. */ public boolean isMetaDataOnly() { return (metaonly); } /** - * Should we send Expect: 100-continue? + * Should we send Expect: 100-continue. */ public boolean isUsing100() { return (use100); } /** - * Can we wait to receive a delete file call before deleting file + * Can we wait to receive a delete file call before deleting file. */ public boolean isPrivilegedSubscriber() { return (privilegedSubscriber); } /** - * Should i decompress the file before sending it on + * Should I decompress the file before sending it on. */ public boolean isDecompress() { return (decompress); @@ -785,7 +837,7 @@ public class NodeConfig { /** * New field is added - FOLLOW_REDIRECTS feature iTrack:DATARTR-17 - 1706 Get the followRedirect of this - * destination + * destination. */ boolean getFollowRedirect() { return (followRedirect); @@ -793,7 +845,7 @@ public class NodeConfig { } /** - * Raw configuration entry for controlled ingress to the data router node + * Raw configuration entry for controlled ingress to the data router node. */ public static class ProvForceIngress { @@ -803,11 +855,11 @@ public class NodeConfig { private String[] nodes; /** - * Construct a forced ingress configuration entry + * Construct a forced ingress configuration entry. * * @param feedid The feed ID that this entry applies to * @param subnet The CIDR for which publisher IP addresses this entry applies to or "" if it applies to all - * publisher IP addresses + * publisher IP addresses * @param user The publishing user this entry applies to or "" if it applies to all publishing users. * @param nodes The array of FQDNs of the data router nodes to redirect publication attempts to. */ @@ -824,28 +876,28 @@ public class NodeConfig { } /** - * Get the feed ID + * Get the feed ID. */ public String getFeedId() { return (feedid); } /** - * Get the subnet + * Get the subnet. */ public String getSubnet() { return (subnet); } /** - * Get the user + * Get the user. */ public String getUser() { return (user); } /** - * Get the node + * Get the node. */ public String[] getNodes() { return (nodes); @@ -853,7 +905,7 @@ public class NodeConfig { } /** - * Raw configuration entry for controlled egress from the data router + * Raw configuration entry for controlled egress from the data router. */ public static class ProvForceEgress { @@ -861,7 +913,7 @@ public class NodeConfig { private String node; /** - * Construct a forced egress configuration entry + * Construct a forced egress configuration entry. * * @param subid The subscription ID the subscription with forced egress * @param node The node handling deliveries for this subscription @@ -872,14 +924,14 @@ public class NodeConfig { } /** - * Get the subscription ID + * Get the subscription ID. */ public String getSubId() { return (subid); } /** - * Get the node + * Get the node. */ public String getNode() { return (node); @@ -887,7 +939,7 @@ public class NodeConfig { } /** - * Raw configuration entry for routing within the data router network + * Raw configuration entry for routing within the data router network. */ public static class ProvHop { @@ -896,7 +948,7 @@ public class NodeConfig { private String via; /** - * Construct a hop entry + * Construct a hop entry. * * @param from The FQDN of the node with the data to be delivered * @param to The FQDN of the node that will deliver to the subscriber @@ -909,28 +961,28 @@ public class NodeConfig { } /** - * A human readable description of this entry + * A human readable description of this entry. */ public String toString() { return ("Hop " + from + "->" + to + " via " + via); } /** - * Get the from node + * Get the from node. */ public String getFrom() { return (from); } /** - * Get the to node + * Get the to node. */ public String getTo() { return (to); } /** - * Get the next intermediate node + * Get the next intermediate node. */ public String getVia() { return (via); diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeConfigManager.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeConfigManager.java index 8a0b0b86..9ffc8ae8 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeConfigManager.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeConfigManager.java @@ -38,13 +38,13 @@ import org.onap.dmaap.datarouter.node.eelf.EelfMsgs; /** * Maintain the configuration of a Data Router node - * <p> - * The NodeConfigManager is the single point of contact for servlet, delivery, event logging, and log retention + * + * <p>The NodeConfigManager is the single point of contact for servlet, delivery, event logging, and log retention * subsystems to access configuration information. - * <p> - * There are two basic sets of configuration data. The static local configuration data, stored in a local configuration - * file (created as part of installation by SWM), and the dynamic global configuration data fetched from the data router - * provisioning server. + * + * <p>There are two basic sets of configuration data. The static local configuration data, stored in a local + * configuration file (created as part of installation by SWM), and the dynamic global configuration data fetched from + * the data router provisioning server. */ public class NodeConfigManager implements DeliveryQueueHelper { @@ -103,7 +103,7 @@ public class NodeConfigManager implements DeliveryQueueHelper { /** - * Initialize the configuration of a Data Router node + * Initialize the configuration of a Data Router node. */ private NodeConfigManager() { @@ -148,8 +148,6 @@ public class NodeConfigManager implements DeliveryQueueHelper { gfport = Integer.parseInt(drNodeProperties.getProperty("IntHttpPort", "8080")); svcport = Integer.parseInt(drNodeProperties.getProperty("IntHttpsPort", "8443")); port = Integer.parseInt(drNodeProperties.getProperty("ExtHttpsPort", "443")); - long minpfinterval = Long.parseLong(drNodeProperties.getProperty("MinProvFetchInterval", "10000")); - long minrsinterval = Long.parseLong(drNodeProperties.getProperty("MinRedirSaveInterval", "10000")); spooldir = drNodeProperties.getProperty("SpoolDir", "spool"); File fdir = new File(spooldir + "/f"); fdir.mkdirs(); @@ -187,6 +185,8 @@ public class NodeConfigManager implements DeliveryQueueHelper { } eelfLogger.info("NODE0304 My certificate says my name is " + myname); pid = new PublishId(myname); + long minrsinterval = Long.parseLong(drNodeProperties.getProperty("MinRedirSaveInterval", "10000")); + long minpfinterval = Long.parseLong(drNodeProperties.getProperty("MinProvFetchInterval", "10000")); rdmgr = new RedirManager(redirfile, minrsinterval, timer); pfetcher = new RateLimitedOperation(minpfinterval, timer) { public void run() { @@ -198,7 +198,7 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Get the default node configuration manager + * Get the default node configuration manager. */ public static NodeConfigManager getInstance() { return base; @@ -285,8 +285,8 @@ public class NodeConfigManager implements DeliveryQueueHelper { private void fetchconfig() { try { eelfLogger.info("NodeConfigMan.fetchConfig: provurl:: " + provurl); - Reader r = new InputStreamReader((new URL(provurl)).openStream()); - config = new NodeConfig(new ProvData(r), myname, spooldir, port, nak); + Reader reader = new InputStreamReader((new URL(provurl)).openStream()); + config = new NodeConfig(new ProvData(reader), myname, spooldir, port, nak); localconfig(); configtasks.startRun(); runTasks(); @@ -324,14 +324,14 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Am I configured? + * Am I configured. */ public boolean isConfigured() { return (config != null); } /** - * Am I shut down? + * Am I shut down. */ public boolean isShutdown() { return (quiesce.exists()); @@ -348,7 +348,7 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Given a set of credentials and an IP address, is this request from another node? + * Given a set of credentials and an IP address, is this request from another node. * * @param credentials Credentials offered by the supposed node * @param ip IP address the request came from @@ -371,16 +371,6 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Check whether delete file is allowed. - * - * @param subId The ID of the subscription being requested - * @return True if the delete file is permitted for the subscriber. - */ - public boolean isDeletePermitted(String subId) { - return (config.isDeletePermitted(subId)); - } - - /** * Check whether publication is allowed for AAF Feed. * * @param feedid The ID of the feed being requested @@ -392,6 +382,16 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** + * Check whether delete file is allowed. + * + * @param subId The ID of the subscription being requested + * @return True if the delete file is permitted for the subscriber. + */ + public boolean isDeletePermitted(String subId) { + return (config.isDeletePermitted(subId)); + } + + /** * Check who the user is given the feed ID and the offered credentials. * * @param feedid The ID of the feed specified @@ -403,7 +403,7 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * AAF changes: TDP EPIC US# 307413 Check AAF_instance for feed ID in NodeConfig + * AAF changes: TDP EPIC US# 307413 Check AAF_instance for feed ID in NodeConfig. * * @param feedid The ID of the feed specified */ @@ -411,6 +411,10 @@ public class NodeConfigManager implements DeliveryQueueHelper { return (config.getAafInstance(feedid)); } + public String getAafInstance() { + return aafInstance; + } + /** * Check if the publish request should be sent to another node based on the feedid, user, and source IP address. * @@ -424,7 +428,7 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Get a provisioned configuration parameter (from the provisioning server configuration) + * Get a provisioned configuration parameter (from the provisioning server configuration). * * @param name The name of the parameter * @return The value of the parameter or null if it is not defined. @@ -434,7 +438,7 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Get a provisioned configuration parameter (from the provisioning server configuration) + * Get a provisioned configuration parameter (from the provisioning server configuration). * * @param name The name of the parameter * @param defaultValue The value to use if the parameter is not defined @@ -449,7 +453,7 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Generate a publish ID + * Generate a publish ID. */ public String getPublishId() { return (pid.next()); @@ -463,14 +467,14 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Register a task to run whenever the configuration changes + * Register a task to run whenever the configuration changes. */ public void registerConfigTask(Runnable task) { configtasks.addTask(task); } /** - * Deregister a task to run whenever the configuration changes + * Deregister a task to run whenever the configuration changes. */ public void deregisterConfigTask(Runnable task) { configtasks.removeTask(task); @@ -493,14 +497,14 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Is a destination redirected? + * Is a destination redirected. */ public boolean isDestRedirected(DestInfo destinfo) { return (followredirects && rdmgr.isRedirected(destinfo.getSubId())); } /** - * Set up redirection on receipt of a 3XX from a target URL + * Set up redirection on receipt of a 3XX from a target URL. */ public boolean handleRedirection(DestInfo destinationInfo, String redirto, String fileid) { fileid = "/" + fileid; @@ -517,7 +521,7 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Set up redirection on receipt of a 3XX from a target URL + * Set up redirection on receipt of a 3XX from a target URL. */ public boolean handleRedirectionSubLevel(DeliveryTask task, DestInfo destinfo, String redirto, String fileid) { fileid = "/" + fileid; @@ -534,7 +538,7 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Handle unreachable target URL + * Handle unreachable target URL. */ public void handleUnreachable(DestInfo destinationInfo) { String subid = destinationInfo.getSubId(); @@ -544,35 +548,35 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Get the timeout before retrying after an initial delivery failure + * Get the timeout before retrying after an initial delivery failure. */ public long getInitFailureTimer() { return (initfailuretimer); } /** - * Get the timeout before retrying after delivery and wait for file processing + * Get the timeout before retrying after delivery and wait for file processing. */ public long getWaitForFileProcessFailureTimer() { return (waitForFileProcessFailureTimer); } /** - * Get the maximum timeout between delivery attempts + * Get the maximum timeout between delivery attempts. */ public long getMaxFailureTimer() { return (maxfailuretimer); } /** - * Get the ratio between consecutive delivery attempts + * Get the ratio between consecutive delivery attempts. */ public double getFailureBackoff() { return (failurebackoff); } /** - * Get the expiration timer for deliveries + * Get the expiration timer for deliveries. */ public long getExpirationTimer() { return (expirationtimer); @@ -593,7 +597,7 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Get the targets for a feed + * Get the targets for a feed. * * @param feedid The feed ID * @return The targets this feed should be delivered to @@ -603,7 +607,7 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Get the creation date for a feed + * Get the creation date for a feed. * * @param feedid The feed ID * @return the timestamp of creation date of feed id passed @@ -613,140 +617,160 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Get the spool directory for temporary files + * Get the spool directory for temporary files. */ public String getSpoolDir() { return (spooldir + "/f"); } /** - * Get the base directory for spool directories + * Get the spool directory for a subscription. + */ + public String getSpoolDir(String subid, String remoteaddr) { + if (provcheck.isFrom(remoteaddr)) { + String sdir = config.getSpoolDir(subid); + if (sdir != null) { + eelfLogger.info("NODE0310 Received subscription reset request for subscription " + subid + + " from provisioning server " + remoteaddr); + } else { + eelfLogger.info("NODE0311 Received subscription reset request for unknown subscription " + subid + + " from provisioning server " + remoteaddr); + } + return (sdir); + } else { + eelfLogger.info("NODE0312 Received subscription reset request from unexpected server " + remoteaddr); + return (null); + } + } + + /** + * Get the base directory for spool directories. */ public String getSpoolBase() { return (spooldir); } /** - * Get the key store type + * Get the key store type. */ public String getKSType() { return (kstype); } /** - * Get the key store file + * Get the key store file. */ public String getKSFile() { return (ksfile); } /** - * Get the key store password + * Get the key store password. */ public String getKSPass() { return (kspass); } /** - * Get the key password + * Get the key password. */ public String getKPass() { return (kpass); } /** - * Get the http port + * Get the http port. */ public int getHttpPort() { return (gfport); } /** - * Get the https port + * Get the https port. */ public int getHttpsPort() { return (svcport); } /** - * Get the externally visible https port + * Get the externally visible https port. */ public int getExtHttpsPort() { return (port); } /** - * Get the external name of this machine + * Get the external name of this machine. */ public String getMyName() { return (myname); } /** - * Get the number of threads to use for delivery + * Get the number of threads to use for delivery. */ public int getDeliveryThreads() { return (deliverythreads); } /** - * Get the URL for uploading the event log data + * Get the URL for uploading the event log data. */ public String getEventLogUrl() { return (eventlogurl); } /** - * Get the prefix for the names of event log files + * Get the prefix for the names of event log files. */ public String getEventLogPrefix() { return (eventlogprefix); } /** - * Get the suffix for the names of the event log files + * Get the suffix for the names of the event log files. */ public String getEventLogSuffix() { return (eventlogsuffix); } /** - * Get the interval between event log file rollovers + * Get the interval between event log file rollovers. */ public String getEventLogInterval() { return (eventloginterval); } /** - * Should I follow redirects from subscribers? + * Should I follow redirects from subscribers. */ public boolean isFollowRedirects() { return (followredirects); } /** - * Get the directory where the event and node log files live + * Get the directory where the event and node log files live. */ public String getLogDir() { return (logdir); } /** - * How long do I keep log files (in milliseconds) + * How long do I keep log files (in milliseconds). */ public long getLogRetention() { return (logretention); } /** - * Get the timer + * Get the timer. */ public Timer getTimer() { return (timer); } /** - * Get the feed ID for a subscription + * Get the feed ID for a subscription. * * @param subid The subscription ID * @return The feed ID @@ -756,7 +780,7 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Get the authorization string this node uses + * Get the authorization string this node uses. * * @return The Authorization string for this node */ @@ -781,7 +805,7 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Disable and enable protocols + * Disable and enable protocols. */ public String[] getEnabledprotocols() { return enabledprotocols; @@ -791,26 +815,6 @@ public class NodeConfigManager implements DeliveryQueueHelper { this.enabledprotocols = enabledprotocols.clone(); } - /** - * Get the spool directory for a subscription - */ - public String getSpoolDir(String subid, String remoteaddr) { - if (provcheck.isFrom(remoteaddr)) { - String sdir = config.getSpoolDir(subid); - if (sdir != null) { - eelfLogger.info("NODE0310 Received subscription reset request for subscription " + subid - + " from provisioning server " + remoteaddr); - } else { - eelfLogger.info("NODE0311 Received subscription reset request for unknown subscription " + subid - + " from provisioning server " + remoteaddr); - } - return (sdir); - } else { - eelfLogger.info("NODE0312 Received subscription reset request from unexpected server " + remoteaddr); - return (null); - } - } - public String getAafType() { return aafType; } @@ -819,10 +823,6 @@ public class NodeConfigManager implements DeliveryQueueHelper { this.aafType = aafType; } - public String getAafInstance() { - return aafInstance; - } - public void setAafInstance(String aafInstance) { this.aafInstance = aafInstance; } @@ -855,7 +855,7 @@ public class NodeConfigManager implements DeliveryQueueHelper { } /** - * Builds the permissions string to be verified + * Builds the permissions string to be verified. * * @param aafInstance The aaf instance * @return The permissions 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 9eaea283..abec7393 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,7 +23,6 @@ package org.onap.dmaap.datarouter.node; - import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; import java.io.IOException; @@ -47,7 +46,7 @@ import org.eclipse.jetty.util.ssl.SslContextFactory; import org.onap.aaf.cadi.PropAccess; /** - * The main starting point for the Data Router node + * The main starting point for the Data Router node. */ public class NodeMain { @@ -59,7 +58,7 @@ public class NodeMain { } /** - * Reset the retry timer for a subscription + * Reset the retry timer for a subscription. */ static void resetQueue(String subid, String ip) { delivery.resetQueue(nodeConfigManager.getSpoolDir(subid, ip)); @@ -67,9 +66,9 @@ public class NodeMain { /** * Start the data router. - * <p> - * The location of the node configuration file can be set using the org.onap.dmaap.datarouter.node.properties system - * property. By default, it is "/opt/app/datartr/etc/node.properties". + * + * <p>The location of the node configuration file can be set using the org.onap.dmaap.datarouter.node.properties + * system property. By default, it is "/opt/app/datartr/etc/node.properties". */ public static void main(String[] args) throws Exception { nodeMainLogger.info("NODE0001 Data Router Node Starting"); @@ -99,7 +98,8 @@ public class NodeMain { sslContextFactory.setKeyStorePassword(nodeConfigManager.getKSPass()); sslContextFactory.setKeyManagerPassword(nodeConfigManager.getKPass()); - //SP-6 : Fixes for SDV scan to exclude/remove DES/3DES ciphers are taken care by upgrading jdk in descriptor.xml + //SP-6: Fixes for SDV scan to exclude/remove DES/3DES + // ciphers are taken care by upgrading jdk in descriptor.xml sslContextFactory.setExcludeCipherSuites( "SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA", @@ -112,12 +112,12 @@ public class NodeMain { sslContextFactory.addExcludeProtocols("SSLv3"); sslContextFactory.setIncludeProtocols(nodeConfigManager.getEnabledprotocols()); - nodeMainLogger.info("NODE00004 Unsupported protocols node server:-" + - String.join(",", sslContextFactory.getExcludeProtocols())); - nodeMainLogger.info("NODE00004 Supported protocols node server:-" + - String.join(",", sslContextFactory.getIncludeProtocols())); - nodeMainLogger.info("NODE00004 Unsupported ciphers node server:-" + - String.join(",", sslContextFactory.getExcludeCipherSuites())); + nodeMainLogger.info("NODE00004 Unsupported protocols node server:-" + + String.join(",", sslContextFactory.getExcludeProtocols())); + nodeMainLogger.info("NODE00004 Supported protocols node server:-" + + String.join(",", sslContextFactory.getIncludeProtocols())); + nodeMainLogger.info("NODE00004 Unsupported ciphers node server:-" + + String.join(",", sslContextFactory.getExcludeCipherSuites())); HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration); httpsConfiguration.setRequestHeaderSize(8192); @@ -155,7 +155,7 @@ public class NodeMain { server.start(); nodeMainLogger.info("NODE00006 Node Server started-" + server.getState()); } catch (Exception e) { - nodeMainLogger.info("NODE00006 Jetty failed to start. Reporting will we unavailable", e.getMessage()); + nodeMainLogger.info("NODE00006 Jetty failed to start. Reporting will we unavailable: " + e.getMessage(), e); } server.join(); nodeMainLogger.info("NODE00007 Node Server joined - " + server.getState()); @@ -168,7 +168,8 @@ public class NodeMain { InputStream in = obj.getCadiProps(); cadiProperties.load(in); } catch (IOException e1) { - nodeMainLogger.error("NODE00005 Exception in NodeMain.Main() loading CADI properties " + e1.getMessage()); + nodeMainLogger + .error("NODE00005 Exception in NodeMain.Main() loading CADI properties " + e1.getMessage(), e1); } cadiProperties.setProperty("aaf_locate_url", nodeConfigManager.getAafURL()); nodeMainLogger.info("NODE00005 aaf_url set to - " + cadiProperties.getProperty("aaf_url")); 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 3f2fc09f..3b82484a 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 @@ -48,9 +48,9 @@ import org.onap.dmaap.datarouter.node.eelf.EelfMsgs; import org.slf4j.MDC; /** - * Servlet for handling all http and https requests to the data router node - * <p> - * Handled requests are: + * Servlet for handling all http and https requests to the data router node. + * + * <p>Handled requests are: * <br> * GET http://<i>node</i>/internal/fetchProv - fetch the provisioning data * <br> @@ -86,7 +86,7 @@ public class NodeServlet extends HttpServlet { } /** - * Get the NodeConfigurationManager + * Get the NodeConfigurationManager. */ @Override public void init() { @@ -104,7 +104,7 @@ public class NodeServlet extends HttpServlet { } /** - * Handle a GET for /internal/fetchProv + * Handle a GET for /internal/fetchProv. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) { @@ -144,7 +144,7 @@ public class NodeServlet extends HttpServlet { } /** - * Handle all PUT requests + * Handle all PUT requests. */ @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) { @@ -162,7 +162,7 @@ public class NodeServlet extends HttpServlet { } /** - * Handle all DELETE requests + * Handle all DELETE requests. */ @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) { @@ -210,8 +210,8 @@ public class NodeServlet extends HttpServlet { } if (fileid.startsWith(PUBLISH)) { fileid = fileid.substring(9); - int i = fileid.indexOf('/'); - if (i == -1 || i == fileid.length() - 1) { + int index = fileid.indexOf('/'); + if (index == -1 || index == fileid.length() - 1) { eelfLogger.error("NODE0205 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + FROM + req .getRemoteAddr()); resp.sendError(HttpServletResponse.SC_NOT_FOUND, @@ -219,7 +219,7 @@ public class NodeServlet extends HttpServlet { eelfLogger.info(EelfMsgs.EXIT); return; } - feedid = fileid.substring(0, i); + feedid = fileid.substring(0, index); if (config.getCadiEnabled()) { String path = req.getPathInfo(); @@ -242,7 +242,7 @@ public class NodeServlet extends HttpServlet { } } - fileid = fileid.substring(i + 1); + fileid = fileid.substring(index + 1); pubid = config.getPublishId(); targets = config.getTargets(feedid); } else if (fileid.startsWith(INTERNAL_PUBLISH)) { @@ -352,13 +352,13 @@ public class NodeServlet extends HttpServlet { while (hnames.hasMoreElements()) { 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-dmaap-dr-meta".equals(hnlc) || - (feedid == null && "x-dmaap-dr-received".equals(hnlc)) || - (hnlc.startsWith("x-") && !hnlc.startsWith("x-dmaap-dr-"))) { + if ((isput && ("content-type".equals(hnlc) + || "content-language".equals(hnlc) + || "content-md5".equals(hnlc) + || "content-range".equals(hnlc))) + || "x-dmaap-dr-meta".equals(hnlc) + || (feedid == null && "x-dmaap-dr-received".equals(hnlc)) + || (hnlc.startsWith("x-") && !hnlc.startsWith("x-dmaap-dr-"))) { Enumeration hvals = req.getHeaders(hn); while (hvals.hasMoreElements()) { String hv = (String) hvals.nextElement(); @@ -469,11 +469,11 @@ public class NodeServlet extends HttpServlet { private String writeInputStreamToFile(HttpServletRequest req, File data) { byte[] buf = new byte[1024 * 1024]; - int i; + int bytesRead; try (OutputStream dos = new FileOutputStream(data); InputStream is = req.getInputStream()) { - while ((i = is.read(buf)) > 0) { - dos.write(buf, 0, i); + while ((bytesRead = is.read(buf)) > 0) { + dos.write(buf, 0, bytesRead); } } catch (IOException ioe) { eelfLogger.error("NODE0530 Exception common: " + ioe, ioe); @@ -497,8 +497,8 @@ public class NodeServlet extends HttpServlet { final String FROM_DR_MESSAGE = ".M) from DR Node: "; try { fileid = fileid.substring(8); - int i = fileid.indexOf('/'); - if (i == -1 || i == fileid.length() - 1) { + int index = fileid.indexOf('/'); + if (index == -1 || index == fileid.length() - 1) { eelfLogger.error("NODE0112 Rejecting bad URI for DELETE of " + req.getPathInfo() + FROM + req .getRemoteAddr()); resp.sendError(HttpServletResponse.SC_NOT_FOUND, @@ -506,9 +506,9 @@ public class NodeServlet extends HttpServlet { eelfLogger.info(EelfMsgs.EXIT); return; } - String subscriptionId = fileid.substring(0, i); + String subscriptionId = fileid.substring(0, index); int subId = Integer.parseInt(subscriptionId); - pubid = fileid.substring(i + 1); + pubid = fileid.substring(index + 1); String errorMessage = "Unable to delete files (" + pubid + ", " + pubid + FROM_DR_MESSAGE + config.getMyName() + "."; int subIdDir = subId - (subId % 100); @@ -571,8 +571,8 @@ public class NodeServlet extends HttpServlet { return false; } } catch (NullPointerException npe) { - eelfLogger.error("NODE0114 " + errorMessage + " Error: Subscription " + subscriptionId + - " does not exist", npe); + eelfLogger.error("NODE0114 " + errorMessage + " Error: Subscription " + subscriptionId + + " does not exist", npe); resp.sendError(HttpServletResponse.SC_NOT_FOUND); eelfLogger.info(EelfMsgs.EXIT); return false; diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeUtils.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeUtils.java index e79e2ee3..d4fc7dbe 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeUtils.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/NodeUtils.java @@ -55,7 +55,7 @@ import org.onap.dmaap.datarouter.node.eelf.EelfMsgs; import org.slf4j.MDC; /** - * Utility functions for the data router node + * Utility functions for the data router node. */ public class NodeUtils { @@ -66,7 +66,7 @@ public class NodeUtils { } /** - * Base64 encode a byte array + * Base64 encode a byte array. * * @param raw The bytes to be encoded * @return The encoded string @@ -76,7 +76,7 @@ public class NodeUtils { } /** - * Given a user and password, generate the credentials + * Given a user and password, generate the credentials. * * @param user User name * @param password User password @@ -90,7 +90,7 @@ public class NodeUtils { } /** - * Given a node name, generate the credentials + * Given a node name, generate the credentials. * * @param node Node name */ @@ -155,7 +155,7 @@ public class NodeUtils { } /** - * Given a string representation of an IP address, get the corresponding byte array + * Given a string representation of an IP address, get the corresponding byte array. * * @param ip The IP address as a string * @return The IP address as a byte array or null if the address is invalid @@ -172,48 +172,48 @@ public class NodeUtils { } /** - * Given a uri with parameters, split out the feed ID and file ID + * Given a uri with parameters, split out the feed ID and file ID. */ public static String[] getFeedAndFileID(String uriandparams) { int end = uriandparams.length(); - int i = uriandparams.indexOf('#'); - if (i != -1 && i < end) { - end = i; + int index = uriandparams.indexOf('#'); + if (index != -1 && index < end) { + end = index; } - i = uriandparams.indexOf('?'); - if (i != -1 && i < end) { - end = i; + index = uriandparams.indexOf('?'); + if (index != -1 && index < end) { + end = index; } end = uriandparams.lastIndexOf('/', end); if (end < 2) { return (null); } - i = uriandparams.lastIndexOf('/', end - 1); - if (i == -1) { + index = uriandparams.lastIndexOf('/', end - 1); + if (index == -1) { return (null); } - return (new String[]{uriandparams.substring(i + 1, end), uriandparams.substring(end + 1)}); + return (new String[]{uriandparams.substring(index + 1, end), uriandparams.substring(end + 1)}); } /** * Escape fields that might contain vertical bar, backslash, or newline by replacing them with backslash p, * backslash e and backslash n. */ - public static String loge(String s) { - if (s == null) { - return (s); + public static String loge(String string) { + if (string == null) { + return (string); } - return (s.replaceAll("\\\\", "\\\\e").replaceAll("\\|", "\\\\p").replaceAll("\n", "\\\\n")); + return (string.replaceAll("\\\\", "\\\\e").replaceAll("\\|", "\\\\p").replaceAll("\n", "\\\\n")); } /** * Undo what loge does. */ - public static String unloge(String s) { - if (s == null) { - return (s); + public static String unloge(String string) { + if (string == null) { + return (string); } - return (s.replaceAll("\\\\p", "\\|").replaceAll("\\\\n", "\n").replaceAll("\\\\e", "\\\\")); + return (string.replaceAll("\\\\p", "\\|").replaceAll("\\\\n", "\n").replaceAll("\\\\e", "\\\\")); } /** @@ -232,9 +232,9 @@ public class NodeUtils { return (logDate.format(when)); } - /* Method prints method name, server FQDN and IP Address of the machine in EELF logs - * @Method - setIpAndFqdnForEelf - Rally:US664892 - * @Params - method, prints method name in EELF log. + /** Method prints method name, server FQDN and IP Address of the machine in EELF logs. + * + * @param method Prints method name in EELF log. */ public static void setIpAndFqdnForEelf(String method) { MDC.clear(); @@ -250,9 +250,9 @@ public class NodeUtils { } - /* Method sets RequestIs and InvocationId for se in EELF logs - * @Method - setIpAndFqdnForEelf - * @Params - Req, Request used to get RequestId and InvocationId + /** Method sets RequestIs and InvocationId for se in EELF logs. + * + * @param req Request used to get RequestId and InvocationId. */ public static void setRequestIdAndInvocationId(HttpServletRequest req) { String reqId = req.getHeader("X-ONAP-RequestID"); @@ -267,6 +267,9 @@ public class NodeUtils { MDC.put("InvocationId", invId); } + /** + * Sends error as response with error code input. + */ public static void sendResponseError(HttpServletResponse response, int errorCode, EELFLogger intlogger) { try { response.sendError(errorCode); @@ -276,7 +279,7 @@ public class NodeUtils { } /** - * Method to check to see if file is of type gzip + * Method to check to see if file is of type gzip. * * @param file The name of the file to be checked * @return True if the file is of type gzip @@ -307,11 +310,11 @@ public class NodeUtils { private static String getNameFromSubject(KeyStore ks, Enumeration<String> aliases) throws KeyStoreException { - String s = aliases.nextElement(); - if (ks.entryInstanceOf(s, KeyStore.PrivateKeyEntry.class)) { - X509Certificate c = (X509Certificate) ks.getCertificate(s); - if (c != null) { - String subject = c.getSubjectX500Principal().getName(); + String alias = aliases.nextElement(); + if (ks.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) { + X509Certificate cert = (X509Certificate) ks.getCertificate(alias); + if (cert != null) { + String subject = cert.getSubjectX500Principal().getName(); String[] parts = subject.split(","); if (parts.length < 1) { return null; diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/PathFinder.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/PathFinder.java index d8beab5a..d86b1e4d 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/PathFinder.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/PathFinder.java @@ -32,7 +32,7 @@ import org.onap.dmaap.datarouter.node.NodeConfig.ProvHop; /** * Given a set of node names and next hops, identify and ignore any cycles and figure out the sequence of next hops to - * get from this node to any other node + * get from this node to any other node. */ public class PathFinder { @@ -55,13 +55,13 @@ public class PathFinder { ht.put(n, new HashMap<>()); } for (NodeConfig.ProvHop ph : hops) { - Hop h = getHop(known, ht, ph); - if (h == null) { + Hop hop = getHop(known, ht, ph); + if (hop == null) { continue; } if (ph.getVia().equals(ph.getTo())) { errors.add(ph + " gives destination as via"); - h.bad = true; + hop.bad = true; } } for (String n : known) { @@ -73,7 +73,7 @@ public class PathFinder { } /** - * Get list of errors encountered while finding paths + * Get list of errors encountered while finding paths. * * @return array of error descriptions */ @@ -82,7 +82,7 @@ public class PathFinder { } /** - * Get the route from this node to the specified node + * Get the route from this node to the specified node. * * @param destination node * @return list of node names separated by and ending with "/" @@ -109,12 +109,12 @@ public class PathFinder { return (to); } nh.mark = true; - String x = plot(nh.basis.getVia(), to, info); + String route = plot(nh.basis.getVia(), to, info); nh.mark = false; if (nh.bad) { return (to); } - return (nh.basis.getVia() + "/" + x); + return (nh.basis.getVia() + "/" + route); } @Nullable @@ -128,21 +128,21 @@ public class PathFinder { return null; } HashMap<String, Hop> ht2 = ht.get(ph.getTo()); - Hop h = ht2.get(ph.getFrom()); - if (h != null) { - h.bad = true; - errors.add(ph + " gives duplicate next hop - previous via was " + h.basis.getVia()); + Hop hop = ht2.get(ph.getFrom()); + if (hop != null) { + hop.bad = true; + errors.add(ph + " gives duplicate next hop - previous via was " + hop.basis.getVia()); return null; } - h = new Hop(); - h.basis = ph; - ht2.put(ph.getFrom(), h); + hop = new Hop(); + hop.basis = ph; + ht2.put(ph.getFrom(), hop); if (!known.contains(ph.getVia())) { errors.add(ph + " references unknown via node"); - h.bad = true; + hop.bad = true; return null; } - return h; + return hop; } private static class Hop { diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/PathUtil.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/PathUtil.java index 16f8033b..d67c9094 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/PathUtil.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/PathUtil.java @@ -21,7 +21,7 @@ package org.onap.dmaap.datarouter.node;
/**
- * FORTIFY SCAN FIXES
+ * FORTIFY SCAN FIXES.
* <p>This Utility is used for Fortify fixes. It Validates the path url formed from
* the string passed in the request parameters.</p>
*/
@@ -34,16 +34,16 @@ class PathUtil { /**
* This method takes String as the parameter and return the filtered path string.
*
- * @param aString String to clean
+ * @param string String to clean
* @return A cleaned String
*/
- static String cleanString(String aString) {
- if (aString == null) {
+ static String cleanString(String string) {
+ if (string == null) {
return null;
}
StringBuilder cleanString = new StringBuilder();
- for (int i = 0; i < aString.length(); ++i) {
- cleanString.append(cleanChar(aString.charAt(i)));
+ for (int i = 0; i < string.length(); ++i) {
+ cleanString.append(cleanChar(string.charAt(i)));
}
return cleanString.toString();
}
@@ -51,34 +51,34 @@ class PathUtil { /**
* This method filters the valid special characters in path string.
*
- * @param aChar The char to be cleaned
+ * @param character The char to be cleaned
* @return The cleaned char
*/
- private static char cleanChar(char aChar) {
+ private static char cleanChar(char character) {
// 0 - 9
for (int i = 48; i < 58; ++i) {
- if (aChar == i) {
+ if (character == i) {
return (char) i;
}
}
// 'A' - 'Z'
for (int i = 65; i < 91; ++i) {
- if (aChar == i) {
+ if (character == i) {
return (char) i;
}
}
// 'a' - 'z'
for (int i = 97; i < 123; ++i) {
- if (aChar == i) {
+ if (character == i) {
return (char) i;
}
}
- return getValidCharacter(aChar);
+ return getValidCharacter(character);
}
- private static char getValidCharacter(char aChar) {
+ private static char getValidCharacter(char character) {
// other valid characters
- switch (aChar) {
+ switch (character) {
case '/':
return '/';
case '.':
diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/ProvData.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/ProvData.java index bb9ddc3b..c436076f 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/ProvData.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/ProvData.java @@ -47,52 +47,52 @@ import org.onap.dmaap.datarouter.node.eelf.EelfMsgs; /** * Parser for provisioning data from the provisioning server. - * <p> - * The ProvData class uses a Reader for the text configuration from the provisioning server to construct arrays of raw - * configuration entries. + * + * <p>The ProvData class uses a Reader for the text configuration from the provisioning server to construct arrays of + * raw configuration entries. */ public class ProvData { private static final String FEED_ID = "feedid"; private static EELFLogger eelfLogger = EELFManager.getInstance().getLogger(ProvData.class); - private NodeConfig.ProvNode[] provNodes; - private NodeConfig.ProvParam[] provParams; - private NodeConfig.ProvFeed[] provFeeds; - private NodeConfig.ProvFeedUser[] provFeedUsers; - private NodeConfig.ProvFeedSubnet[] provFeedSubnets; - private NodeConfig.ProvSubscription[] provSubscriptions; - private NodeConfig.ProvForceIngress[] provForceIngresses; - private NodeConfig.ProvForceEgress[] provForceEgresses; - private NodeConfig.ProvHop[] provHops; + private NodeConfig.ProvNode[] pn; + private NodeConfig.ProvParam[] pp; + private NodeConfig.ProvFeed[] pf; + private NodeConfig.ProvFeedUser[] pfu; + private NodeConfig.ProvFeedSubnet[] pfsn; + private NodeConfig.ProvSubscription[] ps; + private NodeConfig.ProvForceIngress[] pfi; + private NodeConfig.ProvForceEgress[] pfe; + private NodeConfig.ProvHop[] ph; /** * Construct raw provisioing data entries from the text (JSON) provisioning document received from the provisioning - * server + * server. * - * @param r The reader for the JSON text. + * @param reader The reader for the JSON text. */ - public ProvData(Reader r) throws IOException { - ArrayList<ProvNode> provNodes1 = new ArrayList<>(); - ArrayList<NodeConfig.ProvParam> provParams1 = new ArrayList<>(); - ArrayList<NodeConfig.ProvFeed> provFeeds1 = new ArrayList<>(); - ArrayList<NodeConfig.ProvFeedUser> provFeedUsers1 = new ArrayList<>(); - ArrayList<NodeConfig.ProvFeedSubnet> provFeedSubnets1 = new ArrayList<>(); - ArrayList<NodeConfig.ProvSubscription> provSubscriptions1 = new ArrayList<>(); - ArrayList<NodeConfig.ProvForceIngress> provForceIngresses1 = new ArrayList<>(); - ArrayList<NodeConfig.ProvForceEgress> provForceEgresses1 = new ArrayList<>(); - ArrayList<NodeConfig.ProvHop> provHops1 = new ArrayList<>(); + public ProvData(Reader reader) throws IOException { + ArrayList<ProvNode> pnv = new ArrayList<>(); + ArrayList<NodeConfig.ProvParam> ppv = new ArrayList<>(); + ArrayList<NodeConfig.ProvFeed> pfv = new ArrayList<>(); + ArrayList<NodeConfig.ProvFeedUser> pfuv = new ArrayList<>(); + ArrayList<NodeConfig.ProvFeedSubnet> pfsnv = new ArrayList<>(); + ArrayList<NodeConfig.ProvSubscription> psv = new ArrayList<>(); + ArrayList<NodeConfig.ProvForceIngress> pfiv = new ArrayList<>(); + ArrayList<NodeConfig.ProvForceEgress> pfev = new ArrayList<>(); + ArrayList<NodeConfig.ProvHop> phv = new ArrayList<>(); try { - JSONTokener jtx = new JSONTokener(r); + JSONTokener jtx = new JSONTokener(reader); JSONObject jcfg = new JSONObject(jtx); char c = jtx.nextClean(); if (c != '\0') { throw new JSONException("Spurious characters following configuration"); } - r.close(); - addJSONFeeds(provFeeds1, provFeedUsers1, provFeedSubnets1, jcfg); - addJSONSubs(provSubscriptions1, jcfg); - addJSONParams(provNodes1, provParams1, jcfg); - addJSONRoutingInformation(provForceIngresses1, provForceEgresses1, provHops1, jcfg); + reader.close(); + addJSONFeeds(pfv, pfuv, pfsnv, jcfg); + addJSONSubs(psv, jcfg); + addJSONParams(pnv, ppv, jcfg); + addJSONRoutingInformation(pfiv, pfev, phv, jcfg); } catch (JSONException jse) { NodeUtils.setIpAndFqdnForEelf("ProvData"); eelfLogger.error(EelfMsgs.MESSAGE_PARSING_ERROR, jse.toString()); @@ -100,53 +100,53 @@ public class ProvData { .error("NODE0201 Error parsing configuration data from provisioning server " + jse.toString(), jse); throw new IOException(jse.toString(), jse); } - provNodes = provNodes1.toArray(new NodeConfig.ProvNode[provNodes1.size()]); - provParams = provParams1.toArray(new NodeConfig.ProvParam[provParams1.size()]); - provFeeds = provFeeds1.toArray(new NodeConfig.ProvFeed[provFeeds1.size()]); - provFeedUsers = provFeedUsers1.toArray(new NodeConfig.ProvFeedUser[provFeedUsers1.size()]); - provFeedSubnets = provFeedSubnets1.toArray(new NodeConfig.ProvFeedSubnet[provFeedSubnets1.size()]); - provSubscriptions = provSubscriptions1.toArray(new NodeConfig.ProvSubscription[provSubscriptions1.size()]); - provForceIngresses = provForceIngresses1.toArray(new NodeConfig.ProvForceIngress[provForceIngresses1.size()]); - provForceEgresses = provForceEgresses1.toArray(new NodeConfig.ProvForceEgress[provForceEgresses1.size()]); - provHops = provHops1.toArray(new NodeConfig.ProvHop[provHops1.size()]); + pn = pnv.toArray(new NodeConfig.ProvNode[pnv.size()]); + pp = ppv.toArray(new NodeConfig.ProvParam[ppv.size()]); + pf = pfv.toArray(new NodeConfig.ProvFeed[pfv.size()]); + pfu = pfuv.toArray(new NodeConfig.ProvFeedUser[pfuv.size()]); + pfsn = pfsnv.toArray(new NodeConfig.ProvFeedSubnet[pfsnv.size()]); + ps = psv.toArray(new NodeConfig.ProvSubscription[psv.size()]); + pfi = pfiv.toArray(new NodeConfig.ProvForceIngress[pfiv.size()]); + pfe = pfev.toArray(new NodeConfig.ProvForceEgress[pfev.size()]); + ph = phv.toArray(new NodeConfig.ProvHop[phv.size()]); } - private static String[] gvasa(JSONObject o, String key) { - return (gvasa(o.opt(key))); + private static String[] gvasa(JSONObject object, String key) { + return (gvasa(object.opt(key))); } - private static String[] gvasa(Object o) { - if (o instanceof JSONArray) { - JSONArray a = (JSONArray) o; - ArrayList<String> v = new ArrayList<>(); - for (int i = 0; i < a.length(); i++) { - String s = gvas(a, i); - if (s != null) { - v.add(s); + private static String[] gvasa(Object object) { + if (object instanceof JSONArray) { + JSONArray jsonArray = (JSONArray) object; + ArrayList<String> array = new ArrayList<>(); + for (int i = 0; i < jsonArray.length(); i++) { + String string = gvas(jsonArray, i); + if (string != null) { + array.add(string); } } - return (v.toArray(new String[v.size()])); + return (array.toArray(new String[array.size()])); } else { - String s = gvas(o); - if (s == null) { + String string = gvas(object); + if (string == null) { return (new String[0]); } else { - return (new String[]{s}); + return (new String[]{string}); } } } - private static String gvas(JSONArray a, int index) { - return (gvas(a.get(index))); + private static String gvas(JSONArray array, int index) { + return (gvas(array.get(index))); } - private static String gvas(JSONObject o, String key) { - return (gvas(o.opt(key))); + private static String gvas(JSONObject object, String key) { + return (gvas(object.opt(key))); } - private static String gvas(Object o) { - if (o instanceof Boolean || o instanceof Number || o instanceof String) { - return (o.toString()); + private static String gvas(Object object) { + if (object instanceof Boolean || object instanceof Number || object instanceof String) { + return (object.toString()); } return (null); } @@ -155,63 +155,63 @@ public class ProvData { * Get the raw node configuration entries */ public NodeConfig.ProvNode[] getNodes() { - return (provNodes); + return (pn); } /** - * Get the raw parameter configuration entries + * Get the raw parameter configuration entries. */ public NodeConfig.ProvParam[] getParams() { - return (provParams); + return (pp); } /** - * Ge the raw feed configuration entries + * Ge the raw feed configuration entries. */ public NodeConfig.ProvFeed[] getFeeds() { - return (provFeeds); + return (pf); } /** - * Get the raw feed user configuration entries + * Get the raw feed user configuration entries. */ public NodeConfig.ProvFeedUser[] getFeedUsers() { - return (provFeedUsers); + return (pfu); } /** - * Get the raw feed subnet configuration entries + * Get the raw feed subnet configuration entries. */ public NodeConfig.ProvFeedSubnet[] getFeedSubnets() { - return (provFeedSubnets); + return (pfsn); } /** - * Get the raw subscription entries + * Get the raw subscription entries. */ public NodeConfig.ProvSubscription[] getSubscriptions() { - return (provSubscriptions); + return (ps); } /** - * Get the raw forced ingress entries + * Get the raw forced ingress entries. */ public NodeConfig.ProvForceIngress[] getForceIngress() { - return (provForceIngresses); + return (pfi); } /** - * Get the raw forced egress entries + * Get the raw forced egress entries. */ public NodeConfig.ProvForceEgress[] getForceEgress() { - return (provForceEgresses); + return (pfe); } /** - * Get the raw next hop entries + * Get the raw next hop entries. */ public NodeConfig.ProvHop[] getHops() { - return (provHops); + return (ph); } @Nullable @@ -226,20 +226,19 @@ public class ProvData { return stat; } - private void addJSONFeeds(ArrayList<ProvFeed> provFeeds1, ArrayList<ProvFeedUser> provFeedUsers1, - ArrayList<ProvFeedSubnet> provFeedSubnets1, - JSONObject jsonConfig) { - JSONArray jfeeds = jsonConfig.optJSONArray("feeds"); + private void addJSONFeeds(ArrayList<ProvFeed> pfv, ArrayList<ProvFeedUser> pfuv, ArrayList<ProvFeedSubnet> pfsnv, + JSONObject jcfg) { + JSONArray jfeeds = jcfg.optJSONArray("feeds"); if (jfeeds != null) { for (int fx = 0; fx < jfeeds.length(); fx++) { - addJSONFeed(provFeeds1, provFeedUsers1, provFeedSubnets1, jfeeds, fx); + addJSONFeed(pfv, pfuv, pfsnv, jfeeds, fx); } } } - private void addJSONFeed(ArrayList<ProvFeed> provFeeds1, ArrayList<ProvFeedUser> provFeedUsers1, - ArrayList<ProvFeedSubnet> provFeedSubnets1, JSONArray jfeeds, int feedIndex) { - JSONObject jfeed = jfeeds.getJSONObject(feedIndex); + private void addJSONFeed(ArrayList<ProvFeed> pfv, ArrayList<ProvFeedUser> pfuv, ArrayList<ProvFeedSubnet> pfsnv, + JSONArray jfeeds, int fx) { + JSONObject jfeed = jfeeds.getJSONObject(fx); String stat = getFeedStatus(jfeed); String fid = gvas(jfeed, FEED_ID); String fname = gvas(jfeed, "name"); @@ -251,15 +250,15 @@ public class ProvData { * Passing aafInstance to ProvFeed from feeds json passed by prov to identify legacy/AAF feeds */ String aafInstance = gvas(jfeed, "aaf_instance"); - provFeeds1.add(new ProvFeed(fid, fname + "//" + fver, stat, createdDate, aafInstance)); + pfv.add(new ProvFeed(fid, fname + "//" + fver, stat, createdDate, aafInstance)); /* * END - AAF changes */ - addJSONFeedAuthArrays(provFeedUsers1, provFeedSubnets1, jfeed, fid); + addJSONFeedAuthArrays(pfuv, pfsnv, jfeed, fid); } - private void addJSONFeedAuthArrays(ArrayList<ProvFeedUser> provFeedUsers1, - ArrayList<ProvFeedSubnet> provFeedSubnets1, JSONObject jfeed, String fid) { + private void addJSONFeedAuthArrays(ArrayList<ProvFeedUser> pfuv, ArrayList<ProvFeedSubnet> pfsnv, JSONObject jfeed, + String fid) { JSONObject jauth = jfeed.optJSONObject("authorization"); if (jauth == null) { return; @@ -270,28 +269,28 @@ public class ProvData { JSONObject ju = jeids.getJSONObject(ux); String login = gvas(ju, "id"); String password = gvas(ju, "password"); - provFeedUsers1.add(new ProvFeedUser(fid, login, NodeUtils.getAuthHdr(login, password))); + pfuv.add(new ProvFeedUser(fid, login, NodeUtils.getAuthHdr(login, password))); } } JSONArray jeips = jauth.optJSONArray("endpoint_addrs"); if (jeips != null) { for (int ix = 0; ix < jeips.length(); ix++) { String sn = gvas(jeips, ix); - provFeedSubnets1.add(new ProvFeedSubnet(fid, sn)); + pfsnv.add(new ProvFeedSubnet(fid, sn)); } } } - private void addJSONSubs(ArrayList<ProvSubscription> provSubscriptions1, JSONObject jsonConfig) { - JSONArray jsubs = jsonConfig.optJSONArray("subscriptions"); + private void addJSONSubs(ArrayList<ProvSubscription> psv, JSONObject jcfg) { + JSONArray jsubs = jcfg.optJSONArray("subscriptions"); if (jsubs != null) { for (int sx = 0; sx < jsubs.length(); sx++) { - addJSONSub(provSubscriptions1, jsubs, sx); + addJSONSub(psv, jsubs, sx); } } } - private void addJSONSub(ArrayList<ProvSubscription> provSubscriptions1, JSONArray jsubs, int sx) { + private void addJSONSub(ArrayList<ProvSubscription> psv, JSONArray jsubs, int sx) { JSONObject jsub = jsubs.getJSONObject(sx); if (jsub.optBoolean("suspend", false)) { return; @@ -307,74 +306,68 @@ public class ProvData { boolean privilegedSubscriber = jsub.getBoolean("privilegedSubscriber"); boolean decompress = jsub.getBoolean("decompress"); boolean followRedirect = jsub.getBoolean("follow_redirect"); - provSubscriptions1 - .add(new ProvSubscription(sid, fid, delurl, id, NodeUtils.getAuthHdr(id, password), monly, use100, - privilegedSubscriber, followRedirect, decompress)); + psv.add(new ProvSubscription(sid, fid, delurl, id, NodeUtils.getAuthHdr(id, password), monly, use100, + privilegedSubscriber, followRedirect, decompress)); } - private void addJSONParams(ArrayList<ProvNode> provNodes1, ArrayList<ProvParam> provParams1, - JSONObject jsonconfig) { - JSONObject jparams = jsonconfig.optJSONObject("parameters"); + private void addJSONParams(ArrayList<ProvNode> pnv, ArrayList<ProvParam> ppv, JSONObject jcfg) { + JSONObject jparams = jcfg.optJSONObject("parameters"); if (jparams != null) { for (String pname : JSONObject.getNames(jparams)) { - addJSONParam(provParams1, jparams, pname); + addJSONParam(ppv, jparams, pname); } - addJSONNodesToParams(provNodes1, jparams); + addJSONNodesToParams(pnv, jparams); } } - private void addJSONParam(ArrayList<ProvParam> provParams1, JSONObject jparams, String pname) { + private void addJSONParam(ArrayList<ProvParam> ppv, JSONObject jparams, String pname) { String pvalue = gvas(jparams, pname); if (pvalue != null) { - provParams1.add(new ProvParam(pname, pvalue)); + ppv.add(new ProvParam(pname, pvalue)); } } - private void addJSONNodesToParams(ArrayList<ProvNode> provNodes1, JSONObject jparams) { + private void addJSONNodesToParams(ArrayList<ProvNode> pnv, JSONObject jparams) { String sfx = gvas(jparams, "PROV_DOMAIN"); JSONArray jnodes = jparams.optJSONArray("NODES"); if (jnodes != null) { for (int nx = 0; nx < jnodes.length(); nx++) { String nn = gvas(jnodes, nx); - if (nn == null) { - continue; - } if (nn.indexOf('.') == -1) { nn = nn + "." + sfx; } - provNodes1.add(new ProvNode(nn)); + pnv.add(new ProvNode(nn)); } } } - private void addJSONRoutingInformation(ArrayList<ProvForceIngress> provForceIngresses1, - ArrayList<ProvForceEgress> provForceEgresses1, ArrayList<ProvHop> provHops1, JSONObject jsonConfig) { - JSONArray jingresses = jsonConfig.optJSONArray("ingress"); + private void addJSONRoutingInformation(ArrayList<ProvForceIngress> pfiv, ArrayList<ProvForceEgress> pfev, + ArrayList<ProvHop> phv, JSONObject jcfg) { + JSONArray jingresses = jcfg.optJSONArray("ingress"); if (jingresses != null) { for (int fx = 0; fx < jingresses.length(); fx++) { - addJSONIngressRoute(provForceIngresses1, jingresses, fx); + addJSONIngressRoute(pfiv, jingresses, fx); } } - JSONObject jegresses = jsonConfig.optJSONObject("egress"); + JSONObject jegresses = jcfg.optJSONObject("egress"); if (jegresses != null && JSONObject.getNames(jegresses) != null) { for (String esid : JSONObject.getNames(jegresses)) { - addJSONEgressRoute(provForceEgresses1, jegresses, esid); + addJSONEgressRoute(pfev, jegresses, esid); } } - JSONArray jhops = jsonConfig.optJSONArray("routing"); + JSONArray jhops = jcfg.optJSONArray("routing"); if (jhops != null) { for (int fx = 0; fx < jhops.length(); fx++) { - addJSONRoutes(provHops1, jhops, fx); + addJSONRoutes(phv, jhops, fx); } } } - private void addJSONIngressRoute(ArrayList<ProvForceIngress> provForceIngresses1, JSONArray jingresses, int fx) { + private void addJSONIngressRoute(ArrayList<ProvForceIngress> pfiv, JSONArray jingresses, int fx) { JSONObject jingress = jingresses.getJSONObject(fx); String fid = gvas(jingress, FEED_ID); String subnet = gvas(jingress, "subnet"); String user = gvas(jingress, "user"); - String[] nodes = gvasa(jingress, "node"); if (fid == null || "".equals(fid)) { return; } @@ -384,17 +377,18 @@ public class ProvData { if ("".equals(user)) { user = null; } - provForceIngresses1.add(new ProvForceIngress(fid, subnet, user, nodes)); + String[] nodes = gvasa(jingress, "node"); + pfiv.add(new ProvForceIngress(fid, subnet, user, nodes)); } - private void addJSONEgressRoute(ArrayList<ProvForceEgress> provForceEgresses1, JSONObject jegresses, String esid) { + private void addJSONEgressRoute(ArrayList<ProvForceEgress> pfev, JSONObject jegresses, String esid) { String enode = gvas(jegresses, esid); if (esid != null && enode != null && !"".equals(esid) && !"".equals(enode)) { - provForceEgresses1.add(new ProvForceEgress(esid, enode)); + pfev.add(new ProvForceEgress(esid, enode)); } } - private void addJSONRoutes(ArrayList<ProvHop> provHops1, JSONArray jhops, int fx) { + private void addJSONRoutes(ArrayList<ProvHop> phv, JSONArray jhops, int fx) { JSONObject jhop = jhops.getJSONObject(fx); String from = gvas(jhop, "from"); String to = gvas(jhop, "to"); @@ -402,6 +396,6 @@ public class ProvData { if (from == null || to == null || via == null || "".equals(from) || "".equals(to) || "".equals(via)) { return; } - provHops1.add(new ProvHop(from, to, via)); + phv.add(new ProvHop(from, to, via)); } } diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/PublishId.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/PublishId.java index 5b7248af..d1d2abb3 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/PublishId.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/PublishId.java @@ -25,7 +25,7 @@ package org.onap.dmaap.datarouter.node; /** - * Generate publish IDs + * Generate publish IDs. */ public class PublishId { @@ -33,7 +33,7 @@ public class PublishId { private String myname; /** - * Generate publish IDs for the specified name + * Generate publish IDs for the specified name. * * @param myname Unique identifier for this publish ID generator (usually fqdn of server) */ diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/RateLimitedOperation.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/RateLimitedOperation.java index 94b694d4..02704553 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/RateLimitedOperation.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/RateLimitedOperation.java @@ -28,7 +28,7 @@ import java.util.Timer; import java.util.TimerTask; /** - * Execute an operation no more frequently than a specified interval + * Execute an operation no more frequently than a specified interval. */ public abstract class RateLimitedOperation implements Runnable { @@ -41,10 +41,10 @@ public abstract class RateLimitedOperation implements Runnable { private long mininterval; /** - * Create a rate limited operation + * Create a rate limited operation. * * @param mininterval The minimum number of milliseconds after the last execution starts before a new execution can - * begin + * begin * @param timer The timer used to perform deferred executions */ public RateLimitedOperation(long mininterval, Timer timer) { @@ -53,7 +53,7 @@ public abstract class RateLimitedOperation implements Runnable { } /** - * Request that the operation be performed by this thread or at a later time by the timer + * Request that the operation be performed by this thread or at a later time by the timer. */ public void request() { if (premark()) { @@ -61,7 +61,8 @@ public abstract class RateLimitedOperation implements Runnable { } do { run(); - } while (demark()); + } + while (demark()); } private synchronized boolean premark() { 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 83e3c30d..f501583a 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 @@ -35,7 +35,7 @@ import java.util.Map; import java.util.Timer; /** - * Track redirections of subscriptions + * Track redirections of subscriptions. */ public class RedirManager { @@ -59,10 +59,10 @@ public class RedirManager { try { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : sid2primary.entrySet()) { - String s = entry.getKey(); + String key = entry.getKey(); String value = entry.getValue(); - sb.append(s).append(' ').append(value).append(' ') - .append(sid2secondary.get(s)).append('\n'); + sb.append(key).append(' ').append(value).append(' ') + .append(sid2secondary.get(key)).append('\n'); } try (OutputStream os = new FileOutputStream(RedirManager.this.redirfile)) { os.write(sb.toString().getBytes()); @@ -73,10 +73,10 @@ public class RedirManager { } }; try { - String s; + String line; try (BufferedReader br = new BufferedReader(new FileReader(redirfile))) { - while ((s = br.readLine()) != null) { - addSubRedirInfo(s); + while ((line = br.readLine()) != null) { + addSubRedirInfo(line); } } } catch (Exception e) { @@ -128,16 +128,16 @@ public class RedirManager { } /** - * Is a subscription redirected? + * Is a subscription redirected. */ public synchronized boolean isRedirected(String sid) { return (sid != null && sid2secondary.get(sid) != null); } - private void addSubRedirInfo(String s) { - s = s.trim(); - String[] sx = s.split(" "); - if (s.startsWith("#") || sx.length != 3) { + private void addSubRedirInfo(String subRedirInfo) { + subRedirInfo = subRedirInfo.trim(); + String[] sx = subRedirInfo.split(" "); + if (subRedirInfo.startsWith("#") || sx.length != 3) { return; } sid2primary.put(sx[0], sx[1]); diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/StatusLog.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/StatusLog.java index e6165588..53e53145 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/StatusLog.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/StatusLog.java @@ -37,7 +37,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; /** - * Logging for data router delivery events (PUB/DEL/EXP) + * Logging for data router delivery events (PUB/DEL/EXP). */ public class StatusLog { @@ -53,7 +53,7 @@ public class StatusLog { private long nexttime; private OutputStream os; private long intvl; - private NodeConfigManager config = NodeConfigManager.getInstance(); + private static NodeConfigManager config = NodeConfigManager.getInstance(); private StatusLog() { } @@ -64,9 +64,9 @@ public class StatusLog { */ public static long parseInterval(String interval, int def) { try { - Matcher m = Pattern.compile("(?:(\\d+)[Hh])?(?:(\\d+)[Mm])?(?:(\\d+)[Ss]?)?").matcher(interval); - if (m.matches()) { - int dur = getDur(m); + Matcher matcher = Pattern.compile("(?:(\\d+)[Hh])?(?:(\\d+)[Mm])?(?:(\\d+)[Ss]?)?").matcher(interval); + if (matcher.matches()) { + int dur = getDur(matcher); int best = 86400; int dist = best - dur; if (dur > best) { @@ -106,19 +106,19 @@ public class StatusLog { return best; } - private static int getDur(Matcher m) { + private static int getDur(Matcher matcher) { int dur = 0; - String x = m.group(1); - if (x != null) { - dur += 3600 * Integer.parseInt(x); + String match = matcher.group(1); + if (match != null) { + dur += 3600 * Integer.parseInt(match); } - x = m.group(2); - if (x != null) { - dur += 60 * Integer.parseInt(x); + match = matcher.group(2); + if (match != null) { + dur += 60 * Integer.parseInt(match); } - x = m.group(3); - if (x != null) { - dur += Integer.parseInt(x); + match = matcher.group(3); + if (match != null) { + dur += Integer.parseInt(match); } if (dur < 60) { dur = 60; @@ -127,7 +127,7 @@ public class StatusLog { } /** - * Get the name of the current log file + * Get the name of the current log file. * * @return The full path name of the current event log file */ @@ -161,7 +161,7 @@ public class StatusLog { } /** - * Log a data transfer error receiving a publication attempt + * Log a data transfer error receiving a publication attempt. * * @param pubid The publish ID assigned by the node * @param feedid The feed id given by the publisher @@ -205,7 +205,7 @@ public class StatusLog { } /** - * Log delivery attempts expired + * Log delivery attempts expired. * * @param pubid The publish ID assigned by the node * @param feedid The feed ID @@ -235,7 +235,7 @@ public class StatusLog { * @param subid The (space delimited list of) subscription ID * @param clen The content length * @param sent The # of bytes sent or -1 if subscriber returned an error instead of 100 Continue, otherwise, the - * number of bytes sent before an error occurred. + * number of bytes sent before an error occurred. */ public static void logDelExtra(String pubid, String feedid, String subid, long clen, long sent) { if (feedid == null) { @@ -260,7 +260,7 @@ public class StatusLog { } } - private synchronized void log(String s) { + private synchronized void log(String string) { try { long now = System.currentTimeMillis(); checkRoll(now); @@ -269,7 +269,7 @@ public class StatusLog { (new File(plainfile)).delete(); Files.createLink(Paths.get(plainfile), Paths.get(curfile)); } - os.write((NodeUtils.logts(new Date(now)) + '|' + s + '\n').getBytes()); + os.write((NodeUtils.logts(new Date(now)) + '|' + string + '\n').getBytes()); os.flush(); } catch (IOException ioe) { eelfLogger.error("IOException", ioe); diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/SubnetMatcher.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/SubnetMatcher.java index fd5a6bc6..2f510120 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/SubnetMatcher.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/SubnetMatcher.java @@ -25,7 +25,7 @@ package org.onap.dmaap.datarouter.node; /** - * Compare IP addresses as byte arrays to a subnet specified as a CIDR + * Compare IP addresses as byte arrays to a subnet specified as a CIDR. */ public class SubnetMatcher { @@ -34,25 +34,25 @@ public class SubnetMatcher { private int mask; /** - * Construct a subnet matcher given a CIDR + * Construct a subnet matcher given a CIDR. * * @param subnet The CIDR to match */ public SubnetMatcher(String subnet) { - int i = subnet.lastIndexOf('/'); - if (i == -1) { + int index = subnet.lastIndexOf('/'); + if (index == -1) { sn = NodeUtils.getInetAddress(subnet); len = sn.length; } else { - len = Integer.parseInt(subnet.substring(i + 1)); - sn = NodeUtils.getInetAddress(subnet.substring(0, i)); + len = Integer.parseInt(subnet.substring(index + 1)); + sn = NodeUtils.getInetAddress(subnet.substring(0, index)); mask = ((0xff00) >> (len % 8)) & 0xff; len /= 8; } } /** - * Is the IP address in the CIDR? + * Is the IP address in the CIDR. * * @param addr the IP address as bytes in network byte order * @return true if the IP address matches. diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/Target.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/Target.java index d86b2e92..475c876c 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/Target.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/Target.java @@ -25,7 +25,7 @@ package org.onap.dmaap.datarouter.node; /** - * A destination to deliver a message + * A destination to deliver a message. */ public class Target { @@ -33,7 +33,7 @@ public class Target { private String routing; /** - * A destination to deliver a message + * A destination to deliver a message. * * @param destinfo Either info for a subscription ID or info for a node-to-node transfer * @param routing For a node-to-node transfer, what to do when it gets there. @@ -44,21 +44,21 @@ public class Target { } /** - * Add additional routing + * Add additional routing. */ public void addRouting(String routing) { this.routing = this.routing + " " + routing; } /** - * Get the destination information for this target + * Get the destination information for this target. */ public DestInfo getDestInfo() { return (destinfo); } /** - * Get the next hop information for this target + * Get the next hop information for this target. */ public String getRouting() { return (routing); diff --git a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/TaskList.java b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/TaskList.java index 1eb73c69..7fa0dc4d 100644 --- a/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/TaskList.java +++ b/datarouter-node/src/main/java/org/onap/dmaap/datarouter/node/TaskList.java @@ -59,7 +59,7 @@ public class TaskList { } /** - * Get the next task to execute + * Get the next task to execute. */ public synchronized Runnable next() { while (runlist != null) { diff --git a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DRNodeCadiFilterTest.java b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DRNodeCadiFilterTest.java index f6737b1e..bb367186 100644 --- a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DRNodeCadiFilterTest.java +++ b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DRNodeCadiFilterTest.java @@ -1,4 +1,4 @@ -/**-
+/*
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
* ================================================================================
@@ -20,6 +20,17 @@ package org.onap.dmaap.datarouter.node;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -32,19 +43,10 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.powermock.modules.junit4.PowerMockRunner;
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-
-import static org.mockito.Mockito.*;
-
@SuppressStaticInitializationFor("org.onap.dmaap.datarouter.node.NodeConfigManager")
@PrepareForTest({CadiFilter.class})
@RunWith(PowerMockRunner.class)
-public class DRNodeCadiFilterTest
-{
+public class DRNodeCadiFilterTest {
@Mock
private PropAccess access;
@@ -67,7 +69,8 @@ public class DRNodeCadiFilterTest }
@Test
- public void Given_doFilter_Called_And_Method_Is_GET_And_AAF_DB_Instance_Is_NULL_Then_Chain_doFilter_Called() throws Exception {
+ public void Given_doFilter_Called_And_Method_Is_GET_And_AAF_DB_Instance_Is_NULL_Then_Chain_doFilter_Called()
+ throws Exception {
PowerMockito.mockStatic(NodeConfigManager.class);
NodeConfigManager config = mock(NodeConfigManager.class);
@@ -75,12 +78,13 @@ public class DRNodeCadiFilterTest PowerMockito.when(config.getAafInstance("/other/5")).thenReturn("legacy");
when(request.getPathInfo()).thenReturn("/publish/5");
when(request.getMethod()).thenReturn("GET");
- cadiFilter.doFilter(request,response,chain);
+ cadiFilter.doFilter(request, response, chain);
verify(chain, times(1)).doFilter(request, response);
}
@Test
- public void Given_doFilter_Called_And_Method_Is_GET_And_Path_Includes_Internal_Then_Chain_doFilter_Called() throws Exception {
+ public void Given_doFilter_Called_And_Method_Is_GET_And_Path_Includes_Internal_Then_Chain_doFilter_Called()
+ throws Exception {
PowerMockito.mockStatic(NodeConfigManager.class);
NodeConfigManager config = mock(NodeConfigManager.class);
@@ -88,12 +92,13 @@ public class DRNodeCadiFilterTest PowerMockito.when(config.getAafInstance("/other/5")).thenReturn("legacy");
when(request.getPathInfo()).thenReturn("/internal/5");
when(request.getMethod()).thenReturn("GET");
- cadiFilter.doFilter(request,response,chain);
+ cadiFilter.doFilter(request, response, chain);
verify(chain, times(1)).doFilter(request, response);
}
@Test
- public void Given_doFilter_Called_And_Method_Is_GET_And_AAF_DB_Is_Not_Null_Then_Super_doFilter_Called() throws Exception {
+ public void Given_doFilter_Called_And_Method_Is_GET_And_AAF_DB_Is_Not_Null_Then_Super_doFilter_Called()
+ throws Exception {
PowerMockito.mockStatic(NodeConfigManager.class);
NodeConfigManager config = mock(NodeConfigManager.class);
@@ -102,20 +107,22 @@ public class DRNodeCadiFilterTest when(request.getPathInfo()).thenReturn("/publish/5/fileId");
when(request.getMethod()).thenReturn("GET");
PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(CadiFilter.class));
- cadiFilter.doFilter(request,response,chain);
+ cadiFilter.doFilter(request, response, chain);
verify(chain, times(0)).doFilter(request, response);
}
@Test
- public void Given_getFileid_Called_And_SendError_Fails_Then_Throw_IOException_And_Call_chain_doFilter() throws Exception {
+ public void Given_getFileid_Called_And_SendError_Fails_Then_Throw_IOException_And_Call_chain_doFilter()
+ throws Exception {
PowerMockito.mockStatic(NodeConfigManager.class);
NodeConfigManager config = mock(NodeConfigManager.class);
PowerMockito.when(NodeConfigManager.getInstance()).thenReturn(config);
when(request.getPathInfo()).thenReturn("/publish/5");
when(request.getMethod()).thenReturn("DELETE");
- doThrow(new IOException()).when(response).sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid request URI. Expecting <feed-publishing-url>/<fileid>. Possible missing fileid.");
- cadiFilter.doFilter(request,response,chain);
+ doThrow(new IOException()).when(response).sendError(HttpServletResponse.SC_NOT_FOUND,
+ "Invalid request URI. Expecting <feed-publishing-url>/<fileid>. Possible missing fileid.");
+ cadiFilter.doFilter(request, response, chain);
verify(chain, times(1)).doFilter(request, response);
}
}
diff --git a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryQueueTest.java b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryQueueTest.java index fa868b26..6a5f219b 100644 --- a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryQueueTest.java +++ b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryQueueTest.java @@ -23,34 +23,48 @@ package org.onap.dmaap.datarouter.node; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.Hashtable; +import java.util.Vector; import org.apache.commons.lang3.reflect.FieldUtils; +import org.jetbrains.annotations.NotNull; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; -import java.io.File; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.when; - @RunWith(PowerMockRunner.class) +@SuppressStaticInitializationFor("org.onap.dmaap.datarouter.node.NodeConfigManager") public class DeliveryQueueTest { + @Mock + DeliveryQueueHelper deliveryQueueHelper; private DeliveryQueue deliveryQueue; @Mock private DestInfo destInfo; - @Mock - DeliveryQueueHelper deliveryQueueHelper; - private String dirPath = "/tmp/dir001/"; private String fileName = "10000000000004.fileName.M"; @Before - public void setUp() { + public void setUp() throws IllegalAccessException { when(destInfo.getSpool()).thenReturn(dirPath); + when(destInfo.isPrivilegedSubscriber()).thenReturn(true); deliveryQueue = new DeliveryQueue(deliveryQueueHelper, destInfo); + NodeConfigManager configManager = mockNodeConfigManager(); + FieldUtils.writeDeclaredStaticField(StatusLog.class, "config", configManager, true); } @Test @@ -61,8 +75,8 @@ public class DeliveryQueueTest { @Test public void Given_Delivery_Task_Failed_And_Resume_Time_Not_Reached_Return_Null() throws Exception { - FieldUtils.writeField(deliveryQueue,"failed",true,true); - FieldUtils.writeField(deliveryQueue,"resumetime",System.currentTimeMillis()*2,true); + FieldUtils.writeField(deliveryQueue, "failed", true, true); + FieldUtils.writeField(deliveryQueue, "resumetime", System.currentTimeMillis() * 2, true); assertNull(deliveryQueue.peekNext()); } @@ -78,11 +92,147 @@ public class DeliveryQueueTest { } @Test + public void Given_Task_In_Todo_Is_Already_Cleaned_GetNext_Returns_Null() throws Exception { + when(deliveryQueueHelper.getExpirationTimer()).thenReturn(10000L); + deliveryQueue = new DeliveryQueue(deliveryQueueHelper, destInfo); + Vector<DeliveryTask> tasks = new Vector<>(); + DeliveryTask task = new DeliveryTask(deliveryQueue, "123.node.datarouternew.com"); + task.clean(); + tasks.add(task); + FieldUtils.writeField(deliveryQueue, "todo", tasks, true); + DeliveryTask nt = deliveryQueue.getNext(); + assertNull(nt); + } + + @Test + public void Given_Task_In_Todo_Has_Resume_Time_In_Future_GetNext_Returns_Null() throws Exception { + when(destInfo.isPrivilegedSubscriber()).thenReturn(true); + when(deliveryQueueHelper.getExpirationTimer()).thenReturn(10000L); + deliveryQueue = new DeliveryQueue(deliveryQueueHelper, destInfo); + Vector<DeliveryTask> tasks = new Vector<>(); + DeliveryTask task = new DeliveryTask(deliveryQueue, "123.node.datarouternew.com"); + long timeInFuture = 2558366240223L; + task.setResumeTime(timeInFuture); + tasks.add(task); + FieldUtils.writeField(deliveryQueue, "todo", tasks, true); + DeliveryTask nt = deliveryQueue.getNext(); + assertNull(nt); + } + + @Test + public void Given_Task_In_Todo_Is_Expired_GetNext_Returns_Null() throws Exception { + when(destInfo.isPrivilegedSubscriber()).thenReturn(true); + when(deliveryQueueHelper.getExpirationTimer()).thenReturn(10000L); + deliveryQueue = new DeliveryQueue(deliveryQueueHelper, destInfo); + Vector<DeliveryTask> tasks = new Vector<>(); + DeliveryTask task = new DeliveryTask(deliveryQueue, "123.node.datarouternew.com"); + long timeInPast = 1058366240223L; + task.setResumeTime(timeInPast); + tasks.add(task); + FieldUtils.writeField(deliveryQueue, "todo", tasks, true); + DeliveryTask nt = deliveryQueue.getNext(); + assertNull(nt); + } + + @Test public void Given_Delivery_Task_Cancel_And_FileId_Is_Null_Return_Zero() { long rc = deliveryQueue.cancelTask("123.node.datarouternew.com"); assertEquals(0, rc); } + @Test + public void Given_Delivery_Task_Is_Working_Cancel_Task_Returns_Zero() throws IllegalAccessException { + Hashtable<String, DeliveryTask> tasks = new Hashtable<>(); + tasks.put("123.node.datarouternew.com", new DeliveryTask(deliveryQueue, "123.node.datarouternew.com")); + FieldUtils.writeField(deliveryQueue, "working", tasks, true); + long rc = deliveryQueue.cancelTask("123.node.datarouternew.com"); + assertEquals(0, rc); + } + + @Test + public void Given_Delivery_Task_In_Todo_Cancel_Task_Returns_Zero() throws IllegalAccessException { + Vector<DeliveryTask> tasks = new Vector<>(); + tasks.add(new DeliveryTask(deliveryQueue, "123.node.datarouternew.com")); + FieldUtils.writeField(deliveryQueue, "todo", tasks, true); + long rc = deliveryQueue.cancelTask("123.node.datarouternew.com"); + assertEquals(0, rc); + } + + @Test + public void Given_Ok_Status_And_Privileged_Subscriber_Then_Set_Resume_Time_Is_Called_On_DeliveryTask() { + DeliveryTask deliveryTask = mockDeliveryTask(); + deliveryQueue.reportStatus(deliveryTask, 200, "123456789.dmaap-dr-node", "delivery"); + verify(deliveryTask, times(1)).setResumeTime(anyLong()); + cleanUpLogging(); + } + + @Test + public void Given_Ok_Status_And_Not_Privileged_Subscriber_Then_Clean_Is_Called_On_DeliveryTask() { + DeliveryTask deliveryTask = mockDeliveryTask(); + when(destInfo.isPrivilegedSubscriber()).thenReturn(false); + deliveryQueue = new DeliveryQueue(deliveryQueueHelper, destInfo); + deliveryQueue.reportStatus(deliveryTask, 200, "123456789.dmaap-dr-node", "delivery"); + verify(deliveryTask, times(1)).clean(); + cleanUpLogging(); + } + + @Test + public void Given_Not_Ok_Status_Then_Clean_Is_Called_On_DeliveryTask() { + DeliveryTask deliveryTask = mockDeliveryTask(); + deliveryQueue.reportStatus(deliveryTask, 400, "123456789.dmaap-dr-node", "delivery"); + verify(deliveryTask, times(1)).clean(); + cleanUpLogging(); + } + + @Test + public void Given_Task_In_Working_MarkTaskSuccess_Returns_True() throws IllegalAccessException { + Hashtable<String, DeliveryTask> tasks = new Hashtable<>(); + tasks.put("123.node.datarouternew.com", new DeliveryTask(deliveryQueue, "123.node.datarouternew.com")); + FieldUtils.writeField(deliveryQueue, "working", tasks, true); + assertTrue(deliveryQueue.markTaskSuccess("123.node.datarouternew.com")); + } + + @Test + public void Given_Task_In_Retry_MarkTaskSuccess_Returns_True() throws IllegalAccessException { + Hashtable<String, DeliveryTask> tasks = new Hashtable<>(); + tasks.put("123.node.datarouternew.com", new DeliveryTask(deliveryQueue, "123.node.datarouternew.com")); + FieldUtils.writeField(deliveryQueue, "retry", tasks, true); + assertTrue(deliveryQueue.markTaskSuccess("123.node.datarouternew.com")); + } + + @Test + public void Given_Task_Does_Not_Exist_MarkTaskSuccess_Returns_False() { + assertFalse(deliveryQueue.markTaskSuccess("false.pubId.com")); + } + + private void cleanUpLogging() { + final File currentDir = new File(System.getProperty("user.dir")); + final File[] files = currentDir.listFiles((file, name) -> name.matches("null.*")); + if (files != null) { + for (final File file : files) { + file.delete(); + } + } + } + + @NotNull + private DeliveryTask mockDeliveryTask() { + DeliveryTask deliveryTask = mock(DeliveryTask.class); + when(deliveryTask.getPublishId()).thenReturn("123456789.dmaap-dr-node"); + when(deliveryTask.getFeedId()).thenReturn("1"); + when(deliveryTask.getSubId()).thenReturn("1"); + when(deliveryTask.getURL()).thenReturn("http://subcriber.com:7070/delivery"); + when(deliveryTask.getCType()).thenReturn("application/json"); + when(deliveryTask.getLength()).thenReturn(486L); + return deliveryTask; + } + + private NodeConfigManager mockNodeConfigManager() { + NodeConfigManager config = mock(NodeConfigManager.class); + PowerMockito.when(config.getEventLogInterval()).thenReturn("30000"); + return config; + } + private void prepareFiles() throws Exception { createFolder(dirPath); createFile(fileName, dirPath); diff --git a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryTaskTest.java b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryTaskTest.java new file mode 100644 index 00000000..3d17e3e3 --- /dev/null +++ b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryTaskTest.java @@ -0,0 +1,71 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.datarouter.node; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mock; + +public class DeliveryTaskTest { + + @Mock + private DeliveryQueue deliveryQueue; + + @Test + public void Validate_Delivery_Task_Equals() { + DestInfo destInfo = getDestInfo(); + deliveryQueue = mockDelvieryQueue(destInfo); + DeliveryTask task = new DeliveryTask(deliveryQueue, "123456789.test-dr-datafile"); + DeliveryTask task2 = new DeliveryTask(deliveryQueue, "123456789.test-dr-datafile"); + Assert.assertEquals(task, task2); + Assert.assertEquals(task.hashCode(), task2.hashCode()); + Assert.assertEquals(task.toString(), task2.toString()); + Assert.assertEquals(0, task.compareTo(task2)); + } + + @Test + public void Validate_Delivery_Tasks_Not_Equal() { + DestInfo destInfo = getDestInfo(); + deliveryQueue = mockDelvieryQueue(destInfo); + DeliveryTask task = new DeliveryTask(deliveryQueue, "123456789.test-dr-node"); + DeliveryTask task2 = new DeliveryTask(deliveryQueue, "123456789.test-dr-datafile"); + Assert.assertNotEquals(task, task2); + Assert.assertNotEquals(0, task.compareTo(task2)); + } + + private DestInfo getDestInfo() { + return new DestInfoBuilder().setName("n:" + "dmaap-dr-node") + .setSpool(System.getProperty("user.dir") + "/src/test/resources") + .setSubid("1").setLogdata("n2n-dmaap-dr-node").setUrl("https://dmaap-dr-node:8443/internal/publish") + .setAuthuser("dmaap-dr-node").setAuthentication("Auth").setMetaonly(false).setUse100(true) + .setPrivilegedSubscriber(false).setFollowRedirects(false).setDecompress(false).createDestInfo(); + } + + private DeliveryQueue mockDelvieryQueue(DestInfo destInfo) { + DeliveryQueue mockedDeliveryQueue = mock(DeliveryQueue.class); + when(mockedDeliveryQueue.getDestinationInfo()).thenReturn(destInfo); + return mockedDeliveryQueue; + } + +} diff --git a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryTest.java b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryTest.java index c21bdecc..18d9d56c 100644 --- a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryTest.java +++ b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DeliveryTest.java @@ -22,86 +22,124 @@ ******************************************************************************/ package org.onap.dmaap.datarouter.node; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Hashtable; import org.apache.commons.lang3.reflect.FieldUtils; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; +import org.onap.dmaap.datarouter.node.Delivery.DelItem; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; -import java.io.File; -import java.io.IOException; -import java.util.Hashtable; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - @RunWith(PowerMockRunner.class) @SuppressStaticInitializationFor("org.onap.dmaap.datarouter.node.NodeConfigManager") public class DeliveryTest { - @Mock - private DeliveryQueue deliveryQueue; + @Mock + private DeliveryQueue deliveryQueue; + @Mock + private NodeConfigManager config; + private File nDir = new File("tmp/n"); + private File newNDir = new File("tmp/n/0"); + private File newNFile = new File("tmp/n/0/testN.txt"); + private File sDir = new File("tmp/s"); + private File newSDir = new File("tmp/s/0/1"); + private File newSpoolFile = new File("tmp/s/0/1/123456789.dmaap-dr-node"); + private File spoolFileMeta = new File("tmp/s/0/1/123456789.dmaap-dr-node.M"); + + @Before + public void setUp() throws IOException { + nDir.mkdirs(); + sDir.mkdirs(); + newNDir.mkdirs(); + newNFile.createNewFile(); + newSDir.mkdirs(); + newSpoolFile.createNewFile(); + spoolFileMeta.createNewFile(); + config = mockNodeConfigManager(); + } + + @Test + public void Validate_Reset_Queue_Calls_Reset_Queue_On_Delivery_Queue_Object() throws IllegalAccessException { + Delivery delivery = new Delivery(config); + HashMap<String, DeliveryQueue> dqs = new HashMap<>(); + dqs.put("tmp/s/0/1", deliveryQueue); + FieldUtils.writeDeclaredField(delivery, "dqs", dqs, true); + delivery.resetQueue("tmp/s/0/1"); + verify(deliveryQueue, times(1)).resetQueue(); + } - private File nDir = new File("tmp/n"); - private File sDir = new File("tmp/s"); + @Test + public void Validate_Mark_Success_Calls_Mark_Success_On_Delivery_Queue_Object() throws IllegalAccessException { + Delivery delivery = new Delivery(config); + HashMap<String, DeliveryQueue> dqs = new HashMap<>(); + dqs.put("tmp/s/0/1", deliveryQueue); + FieldUtils.writeDeclaredField(delivery, "dqs", dqs, true); + delivery.markTaskSuccess("tmp/s/0/1", "123456789.dmaap-dr-node"); + verify(deliveryQueue, times(1)).markTaskSuccess("123456789.dmaap-dr-node"); + } - @Before - public void setUp() throws IOException { - nDir.mkdirs(); - sDir.mkdirs(); - File newNDir = new File("tmp/n/0"); - newNDir.mkdirs(); - File newNFile = new File("tmp/n/0/testN.txt"); - newNFile.createNewFile(); - File newSDir = new File("tmp/s/0/1"); - newSDir.mkdirs(); - File newSpoolFile = new File("tmp/s/0/1/testSpool.txt"); - newSpoolFile.createNewFile(); - } + @Test + public void Validate_DelItem_With_Equal_Spool_And_PubId_Are_Equal() { + DelItem delItem1 = new DelItem("123456789.dmaap-dr-node", "tmp/s/0/1"); + DelItem delItem2 = new DelItem("123456789.dmaap-dr-node", "tmp/s/0/1"); + Assert.assertEquals(delItem1, delItem2); + Assert.assertEquals(0, delItem1.compareTo(delItem2)); + } - @Test - public void Validate_Reset_Queue_Calls_Reset_Queue_On_Delivery_Queue_Object() throws IllegalAccessException { - NodeConfigManager config = mockNodeConfigManager(); - Delivery delivery = new Delivery(config); - Hashtable<String, DeliveryQueue> dqs = new Hashtable<>(); - dqs.put("spool/s/0/1", deliveryQueue); - FieldUtils.writeDeclaredField(delivery, "dqs", dqs, true); - delivery.resetQueue("spool/s/0/1"); - verify(deliveryQueue, times(1)).resetQueue(); - } + @Test + public void Validate_DelItem_With_Unequal_Spool_And_PubId_Are_Not_Equal() { + DelItem delItem1 = new DelItem("123456789.dmaap-dr-node", "tmp/s/0/1"); + DelItem delItem2 = new DelItem("000000000.dmaap-dr-node", "tmp/s/0/2"); + Assert.assertNotEquals(delItem1, delItem2); + Assert.assertNotEquals(0, delItem1.compareTo(delItem2)); + } - @After - public void tearDown() { - nDir.delete(); - sDir.delete(); - File tmpDir = new File("tmp"); - tmpDir.delete(); - } + @After + public void tearDown() { + newSpoolFile.delete(); + spoolFileMeta.delete(); + newNFile.delete(); + newNDir.delete(); + newSDir.delete(); + new File("tmp/s/0").delete(); + nDir.delete(); + sDir.delete(); + File tmpDir = new File("tmp"); + tmpDir.delete(); + } - private NodeConfigManager mockNodeConfigManager() { - PowerMockito.mockStatic(NodeConfigManager.class); - NodeConfigManager config = mock(NodeConfigManager.class); - PowerMockito.when(config.isConfigured()).thenReturn(true); - PowerMockito.when(config.getAllDests()).thenReturn(createDestInfoObjects()); - PowerMockito.when(config.getFreeDiskStart()).thenReturn(0.49); - PowerMockito.when(config.getFreeDiskStop()).thenReturn(0.5); - PowerMockito.when(config.getDeliveryThreads()).thenReturn(0); - PowerMockito.when(config.getSpoolBase()).thenReturn("tmp"); - return config; - } + private NodeConfigManager mockNodeConfigManager() { + NodeConfigManager config = mock(NodeConfigManager.class); + PowerMockito.when(config.isConfigured()).thenReturn(true); + PowerMockito.when(config.getAllDests()).thenReturn(createDestInfoObjects()); + PowerMockito.when(config.getFreeDiskStart()).thenReturn(0.9); + PowerMockito.when(config.getFreeDiskStop()).thenReturn(0.2); + PowerMockito.when(config.getDeliveryThreads()).thenReturn(0); + PowerMockito.when(config.getSpoolBase()).thenReturn("tmp"); + return config; + } - private DestInfo[] createDestInfoObjects() { - DestInfo[] destInfos = new DestInfo[1]; - DestInfo destInfo = new DestInfoBuilder().setName("node.datarouternew.com").setSpool("spool/s/0/1").setSubid("1") - .setLogdata("logs/").setUrl("/subs/1").setAuthuser("user1").setAuthentication("Basic dXNlcjE6cGFzc3dvcmQx") - .setMetaonly(false).setUse100(true).setPrivilegedSubscriber(false).setFollowRedirects(false) - .setDecompress(false).createDestInfo(); - destInfos[0] = destInfo; - return destInfos; - } + private DestInfo[] createDestInfoObjects() { + DestInfo[] destInfos = new DestInfo[1]; + DestInfo destInfo = new DestInfoBuilder().setName("node.datarouternew.com").setSpool("tmp/s/0/1") + .setSubid("1") + .setLogdata("logs/").setUrl("/subs/1").setAuthuser("user1") + .setAuthentication("Basic dXNlcjE6cGFzc3dvcmQx") + .setMetaonly(false).setUse100(true).setPrivilegedSubscriber(false).setFollowRedirects(false) + .setDecompress(false).createDestInfo(); + destInfos[0] = destInfo; + return destInfos; + } } diff --git a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DestInfoTest.java b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DestInfoTest.java new file mode 100644 index 00000000..ed629bf2 --- /dev/null +++ b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/DestInfoTest.java @@ -0,0 +1,77 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.datarouter.node; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + +public class DestInfoTest { + + private DestInfo destInfo; + + @Before + public void setUp() { + destInfo = getDestInfo("/src/test/resources"); + } + + @Test + public void Validate_Getters_And_Setters() { + assertEquals("n:dmaap-dr-node", destInfo.getName()); + assertEquals("/src/test/resources", destInfo.getSpool()); + assertEquals("1", destInfo.getSubId()); + assertEquals("n2n-dmaap-dr-node", destInfo.getLogData()); + assertEquals("https://dmaap-dr-node:8443/internal/publish", destInfo.getURL()); + assertEquals("dmaap-dr-node", destInfo.getAuthUser()); + assertEquals("Auth", destInfo.getAuth()); + assertFalse(destInfo.isMetaDataOnly()); + assertTrue(destInfo.isUsing100()); + assertFalse(destInfo.isPrivilegedSubscriber()); + assertFalse(destInfo.isFollowRedirects()); + assertFalse(destInfo.isDecompress()); + } + + @Test + public void Validate_DestInfo_Objects_Are_Equal() { + DestInfo destInfo2 = getDestInfo("/src/test/resources"); + assertEquals(destInfo, destInfo2); + assertEquals(destInfo.hashCode(), destInfo2.hashCode()); + } + + @Test + public void Validate_DestInfo_Objects_Are_Not_Equal() { + DestInfo destInfo2 = getDestInfo("notEqual"); + assertNotEquals(destInfo, destInfo2); + assertNotEquals(destInfo.hashCode(), destInfo2.hashCode()); + } + + private DestInfo getDestInfo(String spool) { + return new DestInfoBuilder().setName("n:" + "dmaap-dr-node").setSpool(spool) + .setSubid("1").setLogdata("n2n-dmaap-dr-node").setUrl("https://dmaap-dr-node:8443/internal/publish") + .setAuthuser("dmaap-dr-node").setAuthentication("Auth").setMetaonly(false).setUse100(true) + .setPrivilegedSubscriber(false).setFollowRedirects(false).setDecompress(false).createDestInfo(); + } + +} diff --git a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/LogManagerTest.java b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/LogManagerTest.java new file mode 100644 index 00000000..b95fb365 --- /dev/null +++ b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/LogManagerTest.java @@ -0,0 +1,109 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.datarouter.node; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.util.Timer; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.onap.dmaap.datarouter.node.LogManager.Uploader; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@SuppressStaticInitializationFor({"org.onap.dmaap.datarouter.node.NodeConfigManager"}) +public class LogManagerTest { + + @Mock + private NodeConfigManager config; + + private LogManager logManager; + + @Before + public void setUp() throws IllegalAccessException { + mockNodeConfigManager(); + FieldUtils.writeDeclaredStaticField(StatusLog.class, "config", config, true); + logManager = new LogManager(config); + } + + @After + public void tearDown() { + File spoolDir = new File(System.getProperty("user.dir") + "/src/test/resources/.spool"); + for (File file : spoolDir.listFiles()) { + if (file.exists()) { + file.delete(); + } + } + spoolDir.delete(); + } + + @Test + public void Verify_LogManager_Attempts_To_Deliver_Log_Files_To_Prov() { + logManager.run(); + try { + Thread.sleep(1000); + } catch (Exception e) { + System.out.println("Exception caught: " + e.getMessage()); + } + File file = new File(System.getProperty("user.dir") + "/src/test/resources/.spool/.lastqueued"); + assertTrue(file.isFile()); + } + + @Test + public void Validate_Uploader_Getters() { + Uploader worker = logManager.getWorker(); + assertEquals(10000L, worker.getInitFailureTimer()); + assertEquals(600000L, worker.getWaitForFileProcessFailureTimer()); + assertEquals(2.0, worker.getFailureBackoff(), 0.0); + assertEquals(150000L, worker.getMaxFailureTimer()); + assertEquals(604800000L, worker.getExpirationTimer()); + assertEquals(10000, worker.getFairFileLimit()); + assertEquals(86400000, worker.getFairTimeLimit()); + assertEquals("https://dmaap-dr-prov:8443/internal/logs", + worker.getDestURL(new DestInfoBuilder().createDestInfo(), "String")); + assertFalse(worker.handleRedirection(new DestInfoBuilder().createDestInfo(), "", "")); + assertFalse(worker.isFollowRedirects()); + assertNull(worker.getFeedId("")); + } + + private void mockNodeConfigManager() { + PowerMockito.when(config.getLogDir()).thenReturn(System.getProperty("user.dir") + "/src/test/resources"); + PowerMockito.when(config.getTimer()).thenReturn(new Timer("Node Configuration Timer", true)); + PowerMockito.when(config.getEventLogPrefix()) + .thenReturn(System.getProperty("user.dir") + "/src/test/resources/events"); + PowerMockito.when(config.getEventLogSuffix()).thenReturn(".log"); + PowerMockito.when(config.getLogRetention()).thenReturn(94608000000L); + PowerMockito.when(config.getEventLogInterval()).thenReturn("30s"); + PowerMockito.when(config.getPublishId()).thenReturn("123456789.dmaap-dr-node"); + PowerMockito.when(config.getEventLogUrl()).thenReturn("https://dmaap-dr-prov:8443/internal/logs"); + } + +} diff --git a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/NodeConfigTest.java b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/NodeConfigTest.java index 5e357373..79719243 100644 --- a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/NodeConfigTest.java +++ b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/NodeConfigTest.java @@ -22,6 +22,9 @@ ******************************************************************************/ package org.onap.dmaap.datarouter.node; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; import org.json.JSONArray; import org.json.JSONObject; import org.junit.Assert; @@ -31,10 +34,6 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; - @RunWith(PowerMockRunner.class) @SuppressStaticInitializationFor({"org.onap.dmaap.datarouter.node.ProvData", "org.onap.dmaap.datarouter.node.NodeUtils"}) @@ -43,11 +42,107 @@ public class NodeConfigTest { private static NodeConfig nodeConfig; @BeforeClass - public static void setUp() throws IOException{ + public static void setUp() throws IOException { ProvData provData = setUpProvData(); nodeConfig = new NodeConfig(provData, "Name", "spool/dir", 80, "Key"); } + private static ProvData setUpProvData() throws IOException { + JSONObject provData = new JSONObject(); + createValidFeed(provData); + createValidSubscription(provData); + createValidParameters(provData); + createValidIngressValues(provData); + createValidEgressValues(provData); + createValidRoutingValues(provData); + Reader reader = new StringReader(provData.toString()); + return new ProvData(reader); + } + + private static void createValidFeed(JSONObject provData) { + JSONArray feeds = new JSONArray(); + JSONObject feed = new JSONObject(); + JSONObject auth = new JSONObject(); + JSONArray endpointIds = new JSONArray(); + JSONArray endpointAddrs = new JSONArray(); + JSONObject endpointId = new JSONObject(); + feed.put("feedid", "1"); + feed.put("name", "Feed1"); + feed.put("version", "m1.0"); + feed.put("suspend", false); + feed.put("deleted", false); + endpointId.put("id", "user1"); + endpointId.put("password", "password1"); + endpointIds.put(endpointId); + auth.put("endpoint_ids", endpointIds); + endpointAddrs.put("172.0.0.1"); + auth.put("endpoint_addrs", endpointAddrs); + feed.put("authorization", auth); + feed.put("aaf_instance", "legacy"); + feeds.put(feed); + provData.put("feeds", feeds); + } + + private static void createValidSubscription(JSONObject provData) { + JSONArray subscriptions = new JSONArray(); + JSONObject subscription = new JSONObject(); + JSONObject delivery = new JSONObject(); + subscription.put("subid", "1"); + subscription.put("feedid", "1"); + subscription.put("suspend", false); + subscription.put("metadataOnly", false); + delivery.put("url", "https://172.0.0.2"); + delivery.put("user", "user1"); + delivery.put("password", "password1"); + delivery.put("use100", true); + subscription.put("delivery", delivery); + subscription.put("privilegedSubscriber", false); + subscription.put("follow_redirect", false); + subscription.put("decompress", false); + subscriptions.put(subscription); + provData.put("subscriptions", subscriptions); + } + + private static void createValidParameters(JSONObject provData) { + JSONObject parameters = new JSONObject(); + JSONArray nodes = new JSONArray(); + parameters.put("PROV_NAME", "prov.datarouternew.com"); + parameters.put("DELIVERY_INIT_RETRY_INTERVAL", "10"); + parameters.put("DELIVERY_MAX_AGE", "86400"); + parameters.put("PROV_DOMAIN", ""); + nodes.put("172.0.0.4"); + parameters.put("NODES", nodes); + provData.put("parameters", parameters); + } + + private static void createValidIngressValues(JSONObject provData) { + JSONArray ingresses = new JSONArray(); + JSONObject ingress = new JSONObject(); + ingress.put("feedid", "1"); + ingress.put("subnet", ""); + ingress.put("user", ""); + ingress.put("node", "172.0.0.4"); + ingresses.put(ingress); + provData.put("ingress", ingresses); + } + + private static void createValidEgressValues(JSONObject provData) { + JSONObject egress = new JSONObject(); + egress.put("subid", "1"); + egress.put("nodeid", "172.0.0.4"); + provData.put("egress", egress); + } + + private static void createValidRoutingValues(JSONObject provData) { + JSONArray routings = new JSONArray(); + JSONObject routing = new JSONObject(); + routing.put("from", "prov.datarouternew.com"); + routing.put("to", "172.0.0.4"); + routing.put("via", "172.100.0.1"); + routings.put(routing); + provData.put("routing", routings); + } + @Test public void Given_Feed_Does_Not_Exist_Then_Is_Publish_Permitted_Returns_Not_Null() { String permitted = nodeConfig.isPublishPermitted("2", "user", "0.0.0.0"); @@ -73,7 +168,7 @@ public class NodeConfigTest { } @Test - public void Given_SubId_Then_Get_Feed_Id_Returns_Correct_Id(){ + public void Given_SubId_Then_Get_Feed_Id_Returns_Correct_Id() { String feedId = nodeConfig.getFeedId("1"); Assert.assertEquals("1", feedId); } @@ -164,100 +259,4 @@ public class NodeConfigTest { String auth = nodeConfig.getMyAuth(); Assert.assertEquals("Basic TmFtZTp6Z04wMFkyS3gybFppbXltNy94ZDhuMkdEYjA9", auth); } - - private static ProvData setUpProvData() throws IOException { - JSONObject provData = new JSONObject(); - createValidFeed(provData); - createValidSubscription(provData); - createValidParameters(provData); - createValidIngressValues(provData); - createValidEgressValues(provData); - createValidRoutingValues(provData); - Reader reader = new StringReader(provData.toString()); - return new ProvData(reader); - } - - private static void createValidFeed(JSONObject provData) { - JSONArray feeds = new JSONArray(); - JSONObject feed = new JSONObject(); - JSONObject auth = new JSONObject(); - JSONArray endpointIds = new JSONArray(); - JSONArray endpointAddrs = new JSONArray(); - JSONObject endpointId = new JSONObject(); - feed.put("feedid", "1"); - feed.put("name", "Feed1"); - feed.put("version", "m1.0"); - feed.put("suspend", false); - feed.put("deleted", false); - endpointId.put("id", "user1"); - endpointId.put("password", "password1"); - endpointIds.put(endpointId); - auth.put("endpoint_ids", endpointIds); - endpointAddrs.put("172.0.0.1"); - auth.put("endpoint_addrs", endpointAddrs); - feed.put("authorization", auth); - feed.put("aaf_instance", "legacy"); - feeds.put(feed); - provData.put("feeds", feeds); - } - - private static void createValidSubscription(JSONObject provData) { - JSONArray subscriptions = new JSONArray(); - JSONObject subscription = new JSONObject(); - JSONObject delivery = new JSONObject(); - subscription.put("subid", "1"); - subscription.put("feedid", "1"); - subscription.put("suspend", false); - subscription.put("metadataOnly", false); - delivery.put("url", "https://172.0.0.2"); - delivery.put("user", "user1"); - delivery.put("password", "password1"); - delivery.put("use100", true); - subscription.put("delivery", delivery); - subscription.put("privilegedSubscriber", false); - subscription.put("follow_redirect", false); - subscription.put("decompress", false); - subscriptions.put(subscription); - provData.put("subscriptions", subscriptions); - } - - private static void createValidParameters(JSONObject provData) { - JSONObject parameters = new JSONObject(); - JSONArray nodes = new JSONArray(); - parameters.put("PROV_NAME", "prov.datarouternew.com"); - parameters.put("DELIVERY_INIT_RETRY_INTERVAL", "10"); - parameters.put("DELIVERY_MAX_AGE", "86400"); - parameters.put("PROV_DOMAIN", ""); - nodes.put("172.0.0.4"); - parameters.put("NODES", nodes); - provData.put("parameters", parameters); - } - - private static void createValidIngressValues(JSONObject provData) { - JSONArray ingresses = new JSONArray(); - JSONObject ingress = new JSONObject(); - ingress.put("feedid", "1"); - ingress.put("subnet", ""); - ingress.put("user", ""); - ingress.put("node", "172.0.0.4"); - ingresses.put(ingress); - provData.put("ingress", ingresses); - } - - private static void createValidEgressValues(JSONObject provData) { - JSONObject egress = new JSONObject(); - egress.put("subid", "1"); - egress.put("nodeid", "172.0.0.4"); - provData.put("egress", egress); - } - - private static void createValidRoutingValues(JSONObject provData) { - JSONArray routings = new JSONArray(); - JSONObject routing = new JSONObject(); - routing.put("from", "prov.datarouternew.com"); - routing.put("to", "172.0.0.4"); - routing.put("via", "172.100.0.1"); - routings.put(routing); - provData.put("routing", routings); - } } diff --git a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/NodeUtilsTest.java b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/NodeUtilsTest.java index 27fcd1c4..88e57432 100644 --- a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/NodeUtilsTest.java +++ b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/NodeUtilsTest.java @@ -22,6 +22,15 @@ ******************************************************************************/ package org.onap.dmaap.datarouter.node; +import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN; +import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS; +import static org.mockito.Mockito.when; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + +import java.io.IOException; +import java.net.InetAddress; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -31,20 +40,9 @@ import org.powermock.core.classloader.annotations.SuppressStaticInitializationFo import org.powermock.modules.junit4.PowerMockRunner; import org.slf4j.MDC; -import javax.servlet.http.HttpServletRequest; - -import java.io.IOException; -import java.net.InetAddress; -import java.util.UUID; - -import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN; -import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS; -import static org.mockito.Mockito.when; -import static org.powermock.api.mockito.PowerMockito.mockStatic; - @RunWith(PowerMockRunner.class) @SuppressStaticInitializationFor("org.onap.dmaap.datarouter.node.NodeUtils") -@PrepareForTest({ UUID.class, InetAddress.class }) +@PrepareForTest({UUID.class, InetAddress.class}) public class NodeUtilsTest { @Mock diff --git a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/ProvDataTest.java b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/ProvDataTest.java index 662f2cc0..1fd79d9a 100644 --- a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/ProvDataTest.java +++ b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/ProvDataTest.java @@ -20,17 +20,16 @@ package org.onap.dmaap.datarouter.node; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.modules.junit4.PowerMockRunner; +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertNull; import java.io.ByteArrayInputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; - -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertNull; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class ProvDataTest { @@ -40,77 +39,77 @@ public class ProvDataTest { public void Validate_Values_Are_Set_Correctly_Through_ProvData_Constuctor() throws Exception { String InternalProvData = "{" + - "\"ingress\":[{" + - "\"feedid\":1," + - "\"subnet\":\"\"," + - "\"user\":\"\"," + - "\"node\":\"node\"" + - "}]," + - "\"routing\":[{" + - "\"from\":\"172.10.10.10\"," + - "\"to\":\"172.10.10.12\"," + - "\"via\":\"172.10.10.11\"" + - "}]," + - "\"subscriptions\":[{" + - "\"subid\":1," + - "\"suspend\":false," + - "\"delivery\":{" + - "\"use100\":true," + - "\"password\":\"PASSWORD\"," + - "\"user\":\"LOGIN\"," + - "\"url\":\"http://172.18.0.2:7070\"" + - "}," + - "\"last_mod\":1553608460000," + - "\"subscriber\":\"PMMAPER\"," + - "\"feedid\":1," + - "\"decompress\":false," + - "\"groupid\":1," + - "\"metadataOnly\":false," + - "\"follow_redirect\":false," + - "\"links\":{" + - "\"feed\":\"https://dmaap-dr-prov/feed/1\"" + - ",\"log\":\"https://dmaap-dr-prov/sublog/1\"" + - ",\"self\":\"https://dmaap-dr-prov/subs/1\"" + - "}," + - "\"created_date\":1553608460000," + - "\"privilegedSubscriber\":false" + - "}]," + - "\"feeds\":[{" + - "\"suspend\":false," + - "\"groupid\":0," + - "\"description\":\"Default feed\"," + - "\"version\":\"m1.0\"," + - "\"authorization\":{" + - "\"endpoint_addrs\":[\"172.10.10.20\"]," + - "\"classification\":\"unclassified\"," + - "\"endpoint_ids\":[{" + - "\"password\":\"password\"," + - "\"id\":\"user\"" + - "}]" + - "}," + - "\"last_mod\":1553608454000," + - "\"deleted\":false," + - "\"feedid\":1," + - "\"name\":\"CSIT_Test2\"" + - ",\"business_description\":\"Default Feed\"" + - ",\"publisher\":\"dradmin\"" + - ",\"links\":{" + - "\"subscribe\":\"https://dmaap-dr-prov/subscribe/1\"," + - "\"log\":\"https://dmaap-dr-prov/feedlog/1\"," + - "\"publish\":\"https://dmaap-dr-prov/publish/1\"," + - "\"self\":\"https://dmaap-dr-prov/feed/1\"" + - "}," + - "\"created_date\":1553608454000" + - "}]," + - "\"groups\":[]," + - "\"parameters\":{" + - "\"NODES\":[\"dmaap-dr-node\"]," + - "\"PROV_DOMAIN\":\"\"" + - "}," + - "\"egress\":{" + - "\"1\":1" + - "}" + - "}" ; + "\"ingress\":[{" + + "\"feedid\":1," + + "\"subnet\":\"\"," + + "\"user\":\"\"," + + "\"node\":\"node\"" + + "}]," + + "\"routing\":[{" + + "\"from\":\"172.10.10.10\"," + + "\"to\":\"172.10.10.12\"," + + "\"via\":\"172.10.10.11\"" + + "}]," + + "\"subscriptions\":[{" + + "\"subid\":1," + + "\"suspend\":false," + + "\"delivery\":{" + + "\"use100\":true," + + "\"password\":\"PASSWORD\"," + + "\"user\":\"LOGIN\"," + + "\"url\":\"http://172.18.0.2:7070\"" + + "}," + + "\"last_mod\":1553608460000," + + "\"subscriber\":\"PMMAPER\"," + + "\"feedid\":1," + + "\"decompress\":false," + + "\"groupid\":1," + + "\"metadataOnly\":false," + + "\"follow_redirect\":false," + + "\"links\":{" + + "\"feed\":\"https://dmaap-dr-prov/feed/1\"" + + ",\"log\":\"https://dmaap-dr-prov/sublog/1\"" + + ",\"self\":\"https://dmaap-dr-prov/subs/1\"" + + "}," + + "\"created_date\":1553608460000," + + "\"privilegedSubscriber\":false" + + "}]," + + "\"feeds\":[{" + + "\"suspend\":false," + + "\"groupid\":0," + + "\"description\":\"Default feed\"," + + "\"version\":\"m1.0\"," + + "\"authorization\":{" + + "\"endpoint_addrs\":[\"172.10.10.20\"]," + + "\"classification\":\"unclassified\"," + + "\"endpoint_ids\":[{" + + "\"password\":\"password\"," + + "\"id\":\"user\"" + + "}]" + + "}," + + "\"last_mod\":1553608454000," + + "\"deleted\":false," + + "\"feedid\":1," + + "\"name\":\"CSIT_Test2\"" + + ",\"business_description\":\"Default Feed\"" + + ",\"publisher\":\"dradmin\"" + + ",\"links\":{" + + "\"subscribe\":\"https://dmaap-dr-prov/subscribe/1\"," + + "\"log\":\"https://dmaap-dr-prov/feedlog/1\"," + + "\"publish\":\"https://dmaap-dr-prov/publish/1\"," + + "\"self\":\"https://dmaap-dr-prov/feed/1\"" + + "}," + + "\"created_date\":1553608454000" + + "}]," + + "\"groups\":[]," + + "\"parameters\":{" + + "\"NODES\":[\"dmaap-dr-node\"]," + + "\"PROV_DOMAIN\":\"\"" + + "}," + + "\"egress\":{" + + "\"1\":1" + + "}" + + "}"; Reader r = new InputStreamReader(new ByteArrayInputStream(InternalProvData.getBytes(StandardCharsets.UTF_8))); ProvData pd = new ProvData(r); diff --git a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/StatusLogTest.java b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/StatusLogTest.java index e60f576c..d3793069 100644 --- a/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/StatusLogTest.java +++ b/datarouter-node/src/test/java/org/onap/dmaap/datarouter/node/StatusLogTest.java @@ -22,6 +22,9 @@ ******************************************************************************/ package org.onap.dmaap.datarouter.node; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -31,9 +34,6 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - @RunWith(PowerMockRunner.class) @SuppressStaticInitializationFor("org.onap.dmaap.datarouter.node.NodeConfigManager") @PrepareForTest(StatusLog.class) |