-/*******************************************************************************
- * ============LICENSE_START==================================================
- * * org.onap.dmaap
- * * ===========================================================================
- * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
- * * ===========================================================================
- * * 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.
- * * ============LICENSE_END====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-
-package org.onap.dmaap.datarouter.provisioning;
-
-import java.io.IOException;
-import java.net.HttpURLConnection;
-import java.net.InetAddress;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.UnknownHostException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.TreeSet;
-
-import org.apache.log4j.Logger;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.json.JSONTokener;
-import org.onap.dmaap.datarouter.provisioning.beans.EgressRoute;
-import org.onap.dmaap.datarouter.provisioning.beans.Feed;
-import org.onap.dmaap.datarouter.provisioning.beans.Group;
-import org.onap.dmaap.datarouter.provisioning.beans.IngressRoute;
-import org.onap.dmaap.datarouter.provisioning.beans.NetworkRoute;
-import org.onap.dmaap.datarouter.provisioning.beans.Parameters;
-import org.onap.dmaap.datarouter.provisioning.beans.Subscription;
-import org.onap.dmaap.datarouter.provisioning.utils.*;
-
-/**
- * This class handles the two timers (described in R1 Design Notes), and takes care of issuing the GET to each node of
- * the URL to "poke".
- *
- * @author Robert Eby
- * @version $Id: Poker.java,v 1.11 2014/01/08 16:13:47 eby Exp $
- */
-public class Poker extends TimerTask {
-
- /**
- * Template used to generate the URL to issue the GET against
- */
- private static final String POKE_URL_TEMPLATE = "http://%s/internal/fetchProv";
-
- private static final Object lock = new Object();
-
- /**
- * This is a singleton -- there is only one Poker object in the server
- */
- private static Poker poker;
-
- /**
- * Get the singleton Poker object.
- *
- * @return the Poker
- */
- public static synchronized Poker getPoker() {
- if (poker == null) {
- poker = new Poker();
- }
- return poker;
- }
-
- private long timer1;
- private long timer2;
- private String thisPod; // DNS name of this machine
- private Logger logger;
- private String provString;
-
- private Poker() {
- timer1 = timer2 = 0;
- Timer rolex = new Timer();
- logger = Logger.getLogger("org.onap.dmaap.datarouter.provisioning.internal");
- try {
- thisPod = InetAddress.getLocalHost().getHostName();
- } catch (UnknownHostException e) {
- thisPod = "*UNKNOWN*"; // not a major problem
- }
- provString = buildProvisioningString();
-
- rolex.scheduleAtFixedRate(this, 0L, 1000L); // Run once a second to check the timers
- }
-
- /**
- * This method sets the two timers described in the design notes.
- *
- * @param t1 the first timer controls how long to wait after a provisioning request before poking each node This
- * timer can be reset if it has not "gone off".
- * @param t2 the second timer set the outer bound on how long to wait. It cannot be reset.
- */
- public void setTimers(long t1, long t2) {
- synchronized (lock) {
- if (timer1 == 0 || t1 > timer1) {
- timer1 = t1;
- }
- if (timer2 == 0) {
- timer2 = t2;
- }
- }
- if (logger.isDebugEnabled()) {
- logger.debug("Poker timers set to " + timer1 + " and " + timer2);
- }
-
-
- }
-
- /**
- * Return the last provisioning string built.
- *
- * @return the last provisioning string built.
- */
- public String getProvisioningString() {
- return provString;
- }
-
- /**
- * The method to run at the predefined interval (once per second). This method checks to see if either of the two
- * timers has expired, and if so, will rebuild the provisioning string, and poke all the nodes and other PODs. The
- * timers are then reset to 0.
- */
- @Override
- public void run() {
- try {
- if (timer1 > 0) {
- long now = System.currentTimeMillis();
- boolean fire = false;
- synchronized (lock) {
- if (now > timer1 || now > timer2) {
- timer1 = timer2 = 0;
- fire = true;
- }
- }
- if (fire) {
- pokeNodes();
- }
- }
- } catch (Exception e) {
- logger.warn("PROV0020: Caught exception in Poker: " + e);
- e.printStackTrace();
- }
- }
-
- private void pokeNodes() {
- // Rebuild the prov string
- provString = buildProvisioningString();
- // Only the active POD should poke nodes, etc.
- boolean active = SynchronizerTask.getSynchronizer().isActive();
- if (active) {
- // Poke all the DR nodes
- for (String n : BaseServlet.getNodes()) {
- pokeNode(n);
- }
- // Poke the pod that is not us
- for (String n : BaseServlet.getPods()) {
- if (n.length() > 0 && !n.equals(thisPod)) {
- pokeNode(n);
- }
- }
- }
- }
-
- private void pokeNode(final String nodename) {
- logger.debug("PROV0012 Poking node " + nodename + " ...");
- String nodeUrl = String.format(POKE_URL_TEMPLATE, nodename + ":" + DB.HTTP_PORT);
- Runnable r = () -> {
- try {
- URL url = new URL(nodeUrl);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setConnectTimeout(60000); //Fixes for Itrack DATARTR-3, poke timeout
- conn.connect();
- conn.getContentLength(); // Force the GET through
- conn.disconnect();
- } catch (MalformedURLException e) {
- logger.warn("PROV0013 MalformedURLException Error poking node at " + nodeUrl + " : " + e.getMessage());
- } catch (IOException e) {
- logger.warn("PROV0013 IOException Error poking node at " + nodeUrl + " : " + e.getMessage());
- }
- };
- r.run();
- }
-
- private String buildProvisioningString() {
- StringBuilder sb = new StringBuilder("{\n");
-
- // Append Feeds to the string
- String pfx = "\n";
- sb.append("\"feeds\": [");
- for (Feed f : Feed.getAllFeeds()) {
- sb.append(pfx);
- sb.append(f.asJSONObject().toString());
- pfx = ",\n";
- }
- sb.append("\n],\n");
-
- //Append groups to the string - Rally:US708115 - 1610
- pfx = "\n";
- sb.append("\"groups\": [");
- for (Group s : Group.getAllgroups()) {
- sb.append(pfx);
- sb.append(s.asJSONObject().toString());
- pfx = ",\n";
- }
- sb.append("\n],\n");
-
- // Append Subscriptions to the string
- pfx = "\n";
- sb.append("\"subscriptions\": [");
- for (Subscription s : Subscription.getAllSubscriptions()) {
- sb.append(pfx);
- if (s != null) {
- sb.append(s.asJSONObject().toString());
- }
- pfx = ",\n";
- }
- sb.append("\n],\n");
-
- // Append Parameters to the string
- pfx = "\n";
- sb.append("\"parameters\": {");
- Map<String, String> props = Parameters.getParameters();
- Set<String> ivals = new HashSet<String>();
- String intv = props.get("_INT_VALUES");
- if (intv != null) {
- ivals.addAll(Arrays.asList(intv.split("\\|")));
- }
- for (String key : new TreeSet<String>(props.keySet())) {
- String v = props.get(key);
- sb.append(pfx);
- sb.append(" \"").append(key).append("\": ");
- if (ivals.contains(key)) {
- // integer value
- sb.append(v);
- } else if (key.endsWith("S")) {
- // Split and append array of strings
- String[] pp = v.split("\\|");
- String p2 = "";
- sb.append("[");
- for (String t : pp) {
- sb.append(p2).append("\"").append(quote(t)).append("\"");
- p2 = ",";
- }
- sb.append("]");
- } else {
- sb.append("\"").append(quote(v)).append("\"");
- }
- pfx = ",\n";
- }
- sb.append("\n},\n");
-
- // Append Routes to the string
- pfx = "\n";
- sb.append("\"ingress\": [");
- for (IngressRoute in : IngressRoute.getAllIngressRoutes()) {
- sb.append(pfx);
- sb.append(in.asJSONObject().toString());
- pfx = ",\n";
- }
- sb.append("\n],\n");
-
- pfx = "\n";
- sb.append("\"egress\": {");
- for (EgressRoute eg : EgressRoute.getAllEgressRoutes()) {
- sb.append(pfx);
- String t = eg.asJSONObject().toString();
- t = t.substring(1, t.length() - 1);
- sb.append(t);
- pfx = ",\n";
- }
- sb.append("\n},\n");
-
- pfx = "\n";
- sb.append("\"routing\": [");
- for (NetworkRoute ne : NetworkRoute.getAllNetworkRoutes()) {
- sb.append(pfx);
- sb.append(ne.asJSONObject().toString());
- pfx = ",\n";
- }
- sb.append("\n]");
- sb.append("\n}");
-
- // Convert to string and verify it is valid JSON
- String tempProvString = sb.toString();
- try {
- new JSONObject(new JSONTokener(tempProvString));
- } catch (JSONException e) {
- logger.warn("PROV0016: Possible invalid prov string: " + e);
- }
- return tempProvString;
- }
-
- private String quote(String s) {
- StringBuilder sb = new StringBuilder();
- for (char ch : s.toCharArray()) {
- if (ch == '\\' || ch == '"') {
- sb.append('\\');
- }
- sb.append(ch);
- }
- return sb.toString();
- }
-}
+/*******************************************************************************\r
+ * ============LICENSE_START==================================================\r
+ * * org.onap.dmaap\r
+ * * ===========================================================================\r
+ * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
+ * * ===========================================================================\r
+ * * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * * you may not use this file except in compliance with the License.\r
+ * * You may obtain a copy of the License at\r
+ * *\r
+ * * http://www.apache.org/licenses/LICENSE-2.0\r
+ * *\r
+ * * Unless required by applicable law or agreed to in writing, software\r
+ * * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * * See the License for the specific language governing permissions and\r
+ * * limitations under the License.\r
+ * * ============LICENSE_END====================================================\r
+ * *\r
+ * * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
+ * *\r
+ ******************************************************************************/\r
+\r
+package org.onap.dmaap.datarouter.provisioning;\r
+\r
+import java.io.IOException;\r
+import java.net.HttpURLConnection;\r
+import java.net.InetAddress;\r
+import java.net.MalformedURLException;\r
+import java.net.URL;\r
+import java.net.UnknownHostException;\r
+import java.util.Arrays;\r
+import java.util.HashSet;\r
+import java.util.Map;\r
+import java.util.Set;\r
+import java.util.Timer;\r
+import java.util.TimerTask;\r
+import java.util.TreeSet;\r
+import org.apache.log4j.Logger;\r
+import org.json.JSONException;\r
+import org.json.JSONObject;\r
+import org.json.JSONTokener;\r
+import org.onap.dmaap.datarouter.provisioning.beans.EgressRoute;\r
+import org.onap.dmaap.datarouter.provisioning.beans.Feed;\r
+import org.onap.dmaap.datarouter.provisioning.beans.Group;\r
+import org.onap.dmaap.datarouter.provisioning.beans.IngressRoute;\r
+import org.onap.dmaap.datarouter.provisioning.beans.NetworkRoute;\r
+import org.onap.dmaap.datarouter.provisioning.beans.Parameters;\r
+import org.onap.dmaap.datarouter.provisioning.beans.Subscription;\r
+import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
+\r
+/**\r
+ * This class handles the two timers (described in R1 Design Notes), and takes care of issuing the GET to each node of\r
+ * the URL to "poke".\r
+ *\r
+ * @author Robert Eby\r
+ * @version $Id: Poker.java,v 1.11 2014/01/08 16:13:47 eby Exp $\r
+ */\r
+public class Poker extends TimerTask {\r
+\r
+ /**\r
+ * Template used to generate the URL to issue the GET against\r
+ */\r
+ private static final String POKE_URL_TEMPLATE = "http://%s/internal/fetchProv";\r
+\r
+ private static final Object lock = new Object();\r
+\r
+ /**\r
+ * This is a singleton -- there is only one Poker object in the server\r
+ */\r
+ private static Poker poker;\r
+ private long timer1;\r
+ private long timer2;\r
+ private String thisPod; // DNS name of this machine\r
+ private Logger logger;\r
+ private String provString;\r
+\r
+ private Poker() {\r
+ timer1 = timer2 = 0;\r
+ Timer rolex = new Timer();\r
+ logger = Logger.getLogger("org.onap.dmaap.datarouter.provisioning.internal");\r
+ try {\r
+ thisPod = InetAddress.getLocalHost().getHostName();\r
+ } catch (UnknownHostException e) {\r
+ thisPod = "*UNKNOWN*"; // not a major problem\r
+ logger.info("UnknownHostException: Setting thisPod to \"*UNKNOWN*\"");\r
+ }\r
+ provString = buildProvisioningString();\r
+\r
+ rolex.scheduleAtFixedRate(this, 0L, 1000L); // Run once a second to check the timers\r
+ }\r
+\r
+ /**\r
+ * Get the singleton Poker object.\r
+ *\r
+ * @return the Poker\r
+ */\r
+ public static synchronized Poker getPoker() {\r
+ if (poker == null) {\r
+ poker = new Poker();\r
+ }\r
+ return poker;\r
+ }\r
+\r
+ /**\r
+ * This method sets the two timers described in the design notes.\r
+ *\r
+ * @param t1 the first timer controls how long to wait after a provisioning request before poking each node This\r
+ * timer can be reset if it has not "gone off".\r
+ * @param t2 the second timer set the outer bound on how long to wait. It cannot be reset.\r
+ */\r
+ public void setTimers(long t1, long t2) {\r
+ synchronized (lock) {\r
+ if (timer1 == 0 || t1 > timer1) {\r
+ timer1 = t1;\r
+ }\r
+ if (timer2 == 0) {\r
+ timer2 = t2;\r
+ }\r
+ }\r
+ if (logger.isDebugEnabled()) {\r
+ logger.debug("Poker timers set to " + timer1 + " and " + timer2);\r
+ }\r
+\r
+\r
+ }\r
+\r
+ /**\r
+ * Return the last provisioning string built.\r
+ *\r
+ * @return the last provisioning string built.\r
+ */\r
+ public String getProvisioningString() {\r
+ return provString;\r
+ }\r
+\r
+ /**\r
+ * The method to run at the predefined interval (once per second). This method checks to see if either of the two\r
+ * timers has expired, and if so, will rebuild the provisioning string, and poke all the nodes and other PODs. The\r
+ * timers are then reset to 0.\r
+ */\r
+ @Override\r
+ public void run() {\r
+ try {\r
+ if (timer1 > 0) {\r
+ long now = System.currentTimeMillis();\r
+ boolean fire = false;\r
+ synchronized (lock) {\r
+ if (now > timer1 || now > timer2) {\r
+ timer1 = timer2 = 0;\r
+ fire = true;\r
+ }\r
+ }\r
+ if (fire) {\r
+ pokeNodes();\r
+ }\r
+ }\r
+ } catch (Exception e) {\r
+ logger.warn("PROV0020: Caught exception in Poker: " + e);\r
+ }\r
+ }\r
+\r
+ private void pokeNodes() {\r
+ // Rebuild the prov string\r
+ provString = buildProvisioningString();\r
+ // Only the active POD should poke nodes, etc.\r
+ boolean active = SynchronizerTask.getSynchronizer().isActive();\r
+ if (active) {\r
+ // Poke all the DR nodes\r
+ for (String n : BaseServlet.getNodes()) {\r
+ pokeNode(n);\r
+ }\r
+ // Poke the pod that is not us\r
+ for (String n : BaseServlet.getPods()) {\r
+ if (n.length() > 0 && !n.equals(thisPod)) {\r
+ pokeNode(n);\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ private void pokeNode(final String nodename) {\r
+ logger.debug("PROV0012 Poking node " + nodename + " ...");\r
+ String nodeUrl = String.format(POKE_URL_TEMPLATE, nodename + ":" + DB.getHttpPort());\r
+ Runnable r = () -> {\r
+ try {\r
+ URL url = new URL(nodeUrl);\r
+ HttpURLConnection conn = (HttpURLConnection) url.openConnection();\r
+ conn.setConnectTimeout(60000); //Fixes for Itrack DATARTR-3, poke timeout\r
+ conn.connect();\r
+ conn.getContentLength(); // Force the GET through\r
+ conn.disconnect();\r
+ } catch (MalformedURLException e) {\r
+ logger.warn(\r
+ "PROV0013 MalformedURLException Error poking node at " + nodeUrl + " : " + e\r
+ .getMessage());\r
+ } catch (IOException e) {\r
+ logger.warn("PROV0013 IOException Error poking node at " + nodeUrl + " : " + e\r
+ .getMessage());\r
+ }\r
+ };\r
+ r.run();\r
+ }\r
+\r
+ private String buildProvisioningString() {\r
+ StringBuilder sb = new StringBuilder("{\n");\r
+\r
+ // Append Feeds to the string\r
+ String pfx = "\n";\r
+ sb.append("\"feeds\": [");\r
+ for (Feed f : Feed.getAllFeeds()) {\r
+ sb.append(pfx);\r
+ sb.append(f.asJSONObject().toString());\r
+ pfx = ",\n";\r
+ }\r
+ sb.append("\n],\n");\r
+\r
+ //Append groups to the string - Rally:US708115 - 1610\r
+ pfx = "\n";\r
+ sb.append("\"groups\": [");\r
+ for (Group s : Group.getAllgroups()) {\r
+ sb.append(pfx);\r
+ sb.append(s.asJSONObject().toString());\r
+ pfx = ",\n";\r
+ }\r
+ sb.append("\n],\n");\r
+\r
+ // Append Subscriptions to the string\r
+ pfx = "\n";\r
+ sb.append("\"subscriptions\": [");\r
+ for (Subscription s : Subscription.getAllSubscriptions()) {\r
+ sb.append(pfx);\r
+ if (s != null) {\r
+ sb.append(s.asJSONObject().toString());\r
+ }\r
+ pfx = ",\n";\r
+ }\r
+ sb.append("\n],\n");\r
+\r
+ // Append Parameters to the string\r
+ pfx = "\n";\r
+ sb.append("\"parameters\": {");\r
+ Map<String, String> props = Parameters.getParameters();\r
+ Set<String> ivals = new HashSet<String>();\r
+ String intv = props.get("_INT_VALUES");\r
+ if (intv != null) {\r
+ ivals.addAll(Arrays.asList(intv.split("\\|")));\r
+ }\r
+ for (String key : new TreeSet<String>(props.keySet())) {\r
+ String v = props.get(key);\r
+ sb.append(pfx);\r
+ sb.append(" \"").append(key).append("\": ");\r
+ if (ivals.contains(key)) {\r
+ // integer value\r
+ sb.append(v);\r
+ } else if (key.endsWith("S")) {\r
+ // Split and append array of strings\r
+ String[] pp = v.split("\\|");\r
+ String p2 = "";\r
+ sb.append("[");\r
+ for (String t : pp) {\r
+ sb.append(p2).append("\"").append(quote(t)).append("\"");\r
+ p2 = ",";\r
+ }\r
+ sb.append("]");\r
+ } else {\r
+ sb.append("\"").append(quote(v)).append("\"");\r
+ }\r
+ pfx = ",\n";\r
+ }\r
+ sb.append("\n},\n");\r
+\r
+ // Append Routes to the string\r
+ pfx = "\n";\r
+ sb.append("\"ingress\": [");\r
+ for (IngressRoute in : IngressRoute.getAllIngressRoutes()) {\r
+ sb.append(pfx);\r
+ sb.append(in.asJSONObject().toString());\r
+ pfx = ",\n";\r
+ }\r
+ sb.append("\n],\n");\r
+\r
+ pfx = "\n";\r
+ sb.append("\"egress\": {");\r
+ for (EgressRoute eg : EgressRoute.getAllEgressRoutes()) {\r
+ sb.append(pfx);\r
+ String t = eg.asJSONObject().toString();\r
+ t = t.substring(1, t.length() - 1);\r
+ sb.append(t);\r
+ pfx = ",\n";\r
+ }\r
+ sb.append("\n},\n");\r
+\r
+ pfx = "\n";\r
+ sb.append("\"routing\": [");\r
+ for (NetworkRoute ne : NetworkRoute.getAllNetworkRoutes()) {\r
+ sb.append(pfx);\r
+ sb.append(ne.asJSONObject().toString());\r
+ pfx = ",\n";\r
+ }\r
+ sb.append("\n]");\r
+ sb.append("\n}");\r
+\r
+ // Convert to string and verify it is valid JSON\r
+ String tempProvString = sb.toString();\r
+ try {\r
+ new JSONObject(new JSONTokener(tempProvString));\r
+ } catch (JSONException e) {\r
+ logger.warn("PROV0016: Possible invalid prov string: " + e);\r
+ }\r
+ return tempProvString;\r
+ }\r
+\r
+ private String quote(String s) {\r
+ StringBuilder sb = new StringBuilder();\r
+ for (char ch : s.toCharArray()) {\r
+ if (ch == '\\' || ch == '"') {\r
+ sb.append('\\');\r
+ }\r
+ sb.append(ch);\r
+ }\r
+ return sb.toString();\r
+ }\r
+}\r
-/*******************************************************************************
- * ============LICENSE_START==================================================
- * * org.onap.dmaap
- * * ===========================================================================
- * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
- * * ===========================================================================
- * * 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.
- * * ============LICENSE_END====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-
-
-package org.onap.dmaap.datarouter.provisioning;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.json.JSONArray;
-import org.json.JSONObject;
-import org.json.JSONTokener;
-import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord;
-import org.onap.dmaap.datarouter.provisioning.beans.Feed;
-import org.onap.dmaap.datarouter.provisioning.beans.IngressRoute;
-import org.onap.dmaap.datarouter.provisioning.eelf.EelfMsgs;
-import org.onap.dmaap.datarouter.provisioning.utils.*;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-
-/**
- * This servlet handles redirects for the <publishURL> on the provisioning server,
- * which is generated by the provisioning server to handle a particular subscriptions to a feed.
- * See the <b>File Publishing and Delivery API</b> document for details on how these methods
- * should be invoked.
- *
- * @author Robert Eby
- * @version $Id: PublishServlet.java,v 1.8 2014/03/12 19:45:41 eby Exp $
- */
-@SuppressWarnings("serial")
-public class PublishServlet extends BaseServlet {
- private int next_node;
- private String provstring;
- private List<IngressRoute> irt;
- //Adding EELF Logger Rally:US664892
- private static EELFLogger eelflogger = EELFManager.getInstance().getLogger("org.onap.dmaap.datarouter.provisioning.PublishServlet");
- private static final Object lock = new Object();
-
-
- @Override
- public void init(ServletConfig config) throws ServletException {
- super.init(config);
- next_node = 0;
- provstring = "";
- irt = new ArrayList<IngressRoute>();
-
- }
- @Override
- public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
- setIpAndFqdnForEelf("doDelete");
- eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");
- redirect(req, resp);
- }
- @Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
- setIpAndFqdnForEelf("doGet");
- eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");
- redirect(req, resp);
- }
- @Override
- public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
- setIpAndFqdnForEelf("doPut");
- eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");
- redirect(req, resp);
- }
- @Override
- public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
- setIpAndFqdnForEelf("doPost");
- eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF, req.getHeader(BEHALF_HEADER));
- redirect(req, resp);
-
- }
- private void redirect(HttpServletRequest req, HttpServletResponse resp) {
- try {
- String[] nodes = getNodes();
- if (nodes == null || nodes.length == 0) {
- resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "There are no nodes defined in the DR network.");
- } else {
- EventLogRecord elr = new EventLogRecord(req);
- int feedid = checkPath(req);
- if (feedid < 0) {
- String message = (feedid == -1)
- ? "Invalid request - Missing or bad feed number."
- : "Invalid request - Missing file ID.";
- elr.setMessage(message);
- elr.setResult(HttpServletResponse.SC_NOT_FOUND);
- eventlogger.info(elr);
-
- resp.sendError(HttpServletResponse.SC_NOT_FOUND, message);
- } else {
- // Generate new URL
- String nextnode = getRedirectNode(feedid, req);
- nextnode = nextnode + ":" + DB.HTTPS_PORT;
- String newurl = "https://" + nextnode + "/publish" + req.getPathInfo();
- String qs = req.getQueryString();
- if (qs != null)
- newurl += "?" + qs;
-
- // Log redirect in event log
- String message = "Redirected to: " + newurl;
- elr.setMessage(message);
- elr.setResult(HttpServletResponse.SC_MOVED_PERMANENTLY);
- eventlogger.info(elr);
-
- resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
- resp.setHeader("Location", newurl);
- }
- }
- } catch (IOException ioe) {
- intlogger.error("IOException" + ioe.getMessage());
-
- }
- }
- private String getRedirectNode(int feedid, HttpServletRequest req) {
- // Check to see if the IRT needs to be updated
- Poker p = Poker.getPoker();
- String s = p.getProvisioningString();
- synchronized (lock) {
- if (irt == null || (s.length() != provstring.length()) || !s.equals(provstring)) {
- // Provisioning string has changed -- update the IRT
- provstring = s;
- JSONObject jo = new JSONObject(new JSONTokener(provstring));
- JSONArray ja = jo.getJSONArray("ingress");
- List<IngressRoute> newlist = new ArrayList<IngressRoute>();
- for (int i = 0; i < ja.length(); i++) {
- IngressRoute iroute = new IngressRoute(ja.getJSONObject(i));
- newlist.add(iroute);
- }
- irt = newlist;
- }
- }
-
- // Look in IRT for next node
- for (IngressRoute route : irt) {
- if (route.matches(feedid, req)) {
- // pick a node at random from the list
- Collection<String> nodes = route.getNodes();
- String[] arr = nodes.toArray(new String[0]);
- long id = System.currentTimeMillis() % arr.length;
- String node = arr[(int) id];
- intlogger.info("Redirecting to "+node+" because of route "+route);
- return node;
- }
- }
-
- // No IRT rule matches, do round robin of all active nodes
- String[] nodes = getNodes();
- if (next_node >= nodes.length) // The list of nodes may have grown/shrunk
- next_node = 0;
- return nodes[next_node++];
- }
- private int checkPath(HttpServletRequest req) {
- String path = req.getPathInfo();
- if (path == null || path.length() < 2)
- return -1;
- path = path.substring(1);
- int ix = path.indexOf('/');
- if (ix < 0 || ix == path.length()-1)
- return -2;
- try {
- int feedid = Integer.parseInt(path.substring(0, ix));
- if (!Feed.isFeedValid(feedid))
- return -1;
- return feedid;
- } catch (NumberFormatException e) {
- return -1;
- }
- }
-}
+/*******************************************************************************\r
+ * ============LICENSE_START==================================================\r
+ * * org.onap.dmaap\r
+ * * ===========================================================================\r
+ * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
+ * * ===========================================================================\r
+ * * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * * you may not use this file except in compliance with the License.\r
+ * * You may obtain a copy of the License at\r
+ * *\r
+ * * http://www.apache.org/licenses/LICENSE-2.0\r
+ * *\r
+ * * Unless required by applicable law or agreed to in writing, software\r
+ * * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * * See the License for the specific language governing permissions and\r
+ * * limitations under the License.\r
+ * * ============LICENSE_END====================================================\r
+ * *\r
+ * * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
+ * *\r
+ ******************************************************************************/\r
+\r
+\r
+package org.onap.dmaap.datarouter.provisioning;\r
+\r
+import com.att.eelf.configuration.EELFLogger;\r
+import com.att.eelf.configuration.EELFManager;\r
+import java.io.IOException;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.List;\r
+import javax.servlet.ServletConfig;\r
+import javax.servlet.ServletException;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+import org.json.JSONArray;\r
+import org.json.JSONObject;\r
+import org.json.JSONTokener;\r
+import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord;\r
+import org.onap.dmaap.datarouter.provisioning.beans.Feed;\r
+import org.onap.dmaap.datarouter.provisioning.beans.IngressRoute;\r
+import org.onap.dmaap.datarouter.provisioning.eelf.EelfMsgs;\r
+import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
+\r
+/**\r
+ * This servlet handles redirects for the <publishURL> on the provisioning server, which is generated by the\r
+ * provisioning server to handle a particular subscriptions to a feed. See the <b>File Publishing and Delivery API</b>\r
+ * document for details on how these methods should be invoked.\r
+ *\r
+ * @author Robert Eby\r
+ * @version $Id: PublishServlet.java,v 1.8 2014/03/12 19:45:41 eby Exp $\r
+ */\r
+@SuppressWarnings("serial")\r
+public class PublishServlet extends BaseServlet {\r
+\r
+ private int next_node;\r
+ private String provstring;\r
+ private List<IngressRoute> irt;\r
+ //Adding EELF Logger Rally:US664892\r
+ private static EELFLogger eelflogger = EELFManager.getInstance()\r
+ .getLogger("org.onap.dmaap.datarouter.provisioning.PublishServlet");\r
+ private static final Object lock = new Object();\r
+\r
+\r
+ @Override\r
+ public void init(ServletConfig config) throws ServletException {\r
+ super.init(config);\r
+ next_node = 0;\r
+ provstring = "";\r
+ irt = new ArrayList<IngressRoute>();\r
+\r
+ }\r
+\r
+ @Override\r
+ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {\r
+ setIpAndFqdnForEelf("doDelete");\r
+ eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");\r
+ redirect(req, resp);\r
+ }\r
+\r
+ @Override\r
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {\r
+ setIpAndFqdnForEelf("doGet");\r
+ eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");\r
+ redirect(req, resp);\r
+ }\r
+\r
+ @Override\r
+ public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {\r
+ setIpAndFqdnForEelf("doPut");\r
+ eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");\r
+ redirect(req, resp);\r
+ }\r
+\r
+ @Override\r
+ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {\r
+ setIpAndFqdnForEelf("doPost");\r
+ eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF, req.getHeader(BEHALF_HEADER));\r
+ redirect(req, resp);\r
+\r
+ }\r
+\r
+ private void redirect(HttpServletRequest req, HttpServletResponse resp) {\r
+ try {\r
+ String[] nodes = getNodes();\r
+ if (nodes == null || nodes.length == 0) {\r
+ resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,\r
+ "There are no nodes defined in the DR network.");\r
+ } else {\r
+ EventLogRecord elr = new EventLogRecord(req);\r
+ int feedid = checkPath(req);\r
+ if (feedid < 0) {\r
+ String message = (feedid == -1)\r
+ ? "Invalid request - Missing or bad feed number."\r
+ : "Invalid request - Missing file ID.";\r
+ elr.setMessage(message);\r
+ elr.setResult(HttpServletResponse.SC_NOT_FOUND);\r
+ eventlogger.info(elr);\r
+\r
+ resp.sendError(HttpServletResponse.SC_NOT_FOUND, message);\r
+ } else {\r
+ // Generate new URL\r
+ String nextnode = getRedirectNode(feedid, req);\r
+ nextnode = nextnode + ":" + DB.getHttpsPort();\r
+ String newurl = "https://" + nextnode + "/publish" + req.getPathInfo();\r
+ String qs = req.getQueryString();\r
+ if (qs != null) {\r
+ newurl += "?" + qs;\r
+ }\r
+\r
+ // Log redirect in event log\r
+ String message = "Redirected to: " + newurl;\r
+ elr.setMessage(message);\r
+ elr.setResult(HttpServletResponse.SC_MOVED_PERMANENTLY);\r
+ eventlogger.info(elr);\r
+\r
+ resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);\r
+ resp.setHeader("Location", newurl);\r
+ }\r
+ }\r
+ } catch (IOException ioe) {\r
+ intlogger.error("IOException" + ioe.getMessage());\r
+\r
+ }\r
+ }\r
+\r
+ private String getRedirectNode(int feedid, HttpServletRequest req) {\r
+ // Check to see if the IRT needs to be updated\r
+ Poker p = Poker.getPoker();\r
+ String s = p.getProvisioningString();\r
+ synchronized (lock) {\r
+ if (irt == null || (s.length() != provstring.length()) || !s.equals(provstring)) {\r
+ // Provisioning string has changed -- update the IRT\r
+ provstring = s;\r
+ JSONObject jo = new JSONObject(new JSONTokener(provstring));\r
+ JSONArray ja = jo.getJSONArray("ingress");\r
+ List<IngressRoute> newlist = new ArrayList<IngressRoute>();\r
+ for (int i = 0; i < ja.length(); i++) {\r
+ IngressRoute iroute = new IngressRoute(ja.getJSONObject(i));\r
+ newlist.add(iroute);\r
+ }\r
+ irt = newlist;\r
+ }\r
+ }\r
+\r
+ // Look in IRT for next node\r
+ for (IngressRoute route : irt) {\r
+ if (route.matches(feedid, req)) {\r
+ // pick a node at random from the list\r
+ Collection<String> nodes = route.getNodes();\r
+ String[] arr = nodes.toArray(new String[0]);\r
+ long id = System.currentTimeMillis() % arr.length;\r
+ String node = arr[(int) id];\r
+ intlogger.info("Redirecting to " + node + " because of route " + route);\r
+ return node;\r
+ }\r
+ }\r
+\r
+ // No IRT rule matches, do round robin of all active nodes\r
+ String[] nodes = getNodes();\r
+ if (next_node >= nodes.length) // The list of nodes may have grown/shrunk\r
+ {\r
+ next_node = 0;\r
+ }\r
+ return nodes[next_node++];\r
+ }\r
+\r
+ private int checkPath(HttpServletRequest req) {\r
+ String path = req.getPathInfo();\r
+ if (path == null || path.length() < 2) {\r
+ return -1;\r
+ }\r
+ path = path.substring(1);\r
+ int ix = path.indexOf('/');\r
+ if (ix < 0 || ix == path.length() - 1) {\r
+ return -2;\r
+ }\r
+ try {\r
+ int feedid = Integer.parseInt(path.substring(0, ix));\r
+ if (!Feed.isFeedValid(feedid)) {\r
+ return -1;\r
+ }\r
+ return feedid;\r
+ } catch (NumberFormatException e) {\r
+ return -1;\r
+ }\r
+ }\r
+}\r
import java.sql.ResultSet;\r
import java.sql.SQLException;\r
import java.sql.Statement;\r
-import java.util.*;\r
-\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Date;\r
+import java.util.List;\r
+import java.util.Objects;\r
+import java.util.Properties;\r
import org.apache.log4j.Logger;\r
import org.json.JSONObject;\r
import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
* @version $Id: Subscription.java,v 1.9 2013/10/28 18:06:53 eby Exp $\r
*/\r
public class Subscription extends Syncable {\r
+\r
+ private static final String SQLEXCEPTION = "SQLException: ";\r
+ private static final String SUBID_KEY = "subid";\r
+ private static final String SUBID_COL = "SUBID";\r
+ private static final String FEEDID_KEY = "feedid";\r
+ private static final String GROUPID_KEY = "groupid";\r
+ private static final String LAST_MOD_KEY = "last_mod";\r
+ private static final String CREATED_DATE = "created_date";\r
private static Logger intlogger = Logger.getLogger("org.onap.dmaap.datarouter.provisioning.internal");\r
- private static int next_subid = getMaxSubID() + 1;\r
+ private static int nextSubid = getMaxSubID() + 1;\r
\r
private int subid;\r
private int feedid;\r
private String subscriber;\r
private SubLinks links;\r
private boolean suspended;\r
- private Date last_mod;\r
- private Date created_date;\r
+ private Date lastMod;\r
+ private Date createdDate;\r
\r
public static Subscription getSubscriptionMatching(Subscription sub) {\r
SubDelivery deli = sub.getDelivery();\r
sub.isMetadataOnly() ? 1 : 0\r
);\r
List<Subscription> list = getSubscriptionsForSQL(sql);\r
- return list.size() > 0 ? list.get(0) : null;\r
+ return !list.isEmpty() ? list.get(0) : null;\r
}\r
\r
public static Subscription getSubscriptionById(int id) {\r
String sql = "select * from SUBSCRIPTIONS where SUBID = " + id;\r
List<Subscription> list = getSubscriptionsForSQL(sql);\r
- return list.size() > 0 ? list.get(0) : null;\r
+ return !list.isEmpty() ? list.get(0) : null;\r
}\r
\r
public static Collection<Subscription> getAllSubscriptions() {\r
}\r
\r
private static List<Subscription> getSubscriptionsForSQL(String sql) {\r
- List<Subscription> list = new ArrayList<Subscription>();\r
+ List<Subscription> list = new ArrayList<>();\r
try {\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- try(Statement stmt = conn.createStatement()) {\r
- try(ResultSet rs = stmt.executeQuery(sql)) {\r
+ try (Statement stmt = conn.createStatement()) {\r
+ try (ResultSet rs = stmt.executeQuery(sql)) {\r
while (rs.next()) {\r
Subscription sub = new Subscription(rs);\r
list.add(sub);\r
}\r
db.release(conn);\r
} catch (SQLException e) {\r
- e.printStackTrace();\r
+ intlogger.error(e);\r
}\r
return list;\r
}\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- try(Statement stmt = conn.createStatement()) {\r
- try(ResultSet rs = stmt.executeQuery("select MAX(subid) from SUBSCRIPTIONS")) {\r
+ try (Statement stmt = conn.createStatement()) {\r
+ try (ResultSet rs = stmt.executeQuery("select MAX(subid) from SUBSCRIPTIONS")) {\r
if (rs.next()) {\r
max = rs.getInt(1);\r
}\r
db.release(conn);\r
} catch (SQLException e) {\r
intlogger.info("getMaxSubID: " + e.getMessage());\r
- e.printStackTrace();\r
}\r
return max;\r
}\r
\r
public static Collection<String> getSubscriptionUrlList(int feedid) {\r
- List<String> list = new ArrayList<String>();\r
- String sql = "select SUBID from SUBSCRIPTIONS where FEEDID = " + feedid;\r
+ List<String> list = new ArrayList<>();\r
+ String sql = "select SUBID from SUBSCRIPTIONS where FEEDID = ?";\r
+\r
try {\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- try(Statement stmt = conn.createStatement()) {\r
- try(ResultSet rs = stmt.executeQuery(sql)) {\r
+\r
+ try (PreparedStatement stmt = conn.prepareStatement(sql)) {\r
+ stmt.setString(1, String.valueOf(feedid));\r
+ try (ResultSet rs = stmt.executeQuery()) {\r
while (rs.next()) {\r
- int subid = rs.getInt("SUBID");\r
+ int subid = rs.getInt(SUBID_COL);\r
list.add(URLUtilities.generateSubscriptionURL(subid));\r
}\r
}\r
}\r
db.release(conn);\r
} catch (SQLException e) {\r
- e.printStackTrace();\r
+ intlogger.error(SQLEXCEPTION + e.getMessage());\r
}\r
return list;\r
}\r
DB db = new DB();\r
@SuppressWarnings("resource")\r
Connection conn = db.getConnection();\r
- try(Statement stmt = conn.createStatement()) {\r
- try(ResultSet rs = stmt.executeQuery("select count(*) from SUBSCRIPTIONS")) {\r
+ try (Statement stmt = conn.createStatement()) {\r
+ try (ResultSet rs = stmt.executeQuery("select count(*) from SUBSCRIPTIONS")) {\r
if (rs.next()) {\r
count = rs.getInt(1);\r
}\r
db.release(conn);\r
} catch (SQLException e) {\r
intlogger.warn("PROV0008 countActiveSubscriptions: " + e.getMessage());\r
- e.printStackTrace();\r
}\r
return count;\r
}\r
this.subscriber = "";\r
this.links = new SubLinks();\r
this.suspended = false;\r
- this.last_mod = new Date();\r
- this.created_date = new Date();\r
+ this.lastMod = new Date();\r
+ this.createdDate = new Date();\r
}\r
\r
public Subscription(ResultSet rs) throws SQLException {\r
- this.subid = rs.getInt("SUBID");\r
+ this.subid = rs.getInt(SUBID_COL);\r
this.feedid = rs.getInt("FEEDID");\r
this.groupid = rs.getInt("GROUPID"); //New field is added - Groups feature Rally:US708115 - 1610\r
this.delivery = new SubDelivery(rs);\r
this.metadataOnly = rs.getBoolean("METADATA_ONLY");\r
this.subscriber = rs.getString("SUBSCRIBER");\r
- this.links = new SubLinks(rs.getString("SELF_LINK"), URLUtilities.generateFeedURL(feedid), rs.getString("LOG_LINK"));\r
+ this.links = new SubLinks(rs.getString("SELF_LINK"), URLUtilities.generateFeedURL(feedid),\r
+ rs.getString("LOG_LINK"));\r
this.suspended = rs.getBoolean("SUSPENDED");\r
- this.last_mod = rs.getDate("LAST_MOD");\r
- this.created_date = rs.getDate("CREATED_DATE");\r
+ this.lastMod = rs.getDate("LAST_MOD");\r
+ this.createdDate = rs.getDate("CREATED_DATE");\r
}\r
\r
public Subscription(JSONObject jo) throws InvalidObjectException {\r
this("", "", "");\r
try {\r
// The JSONObject is assumed to contain a vnd.att-dr.subscription representation\r
- this.subid = jo.optInt("subid", -1);\r
- this.feedid = jo.optInt("feedid", -1);\r
- this.groupid = jo.optInt("groupid", -1); //New field is added - Groups feature Rally:US708115 - 1610\r
+ this.subid = jo.optInt(SUBID_KEY, -1);\r
+ this.feedid = jo.optInt(FEEDID_KEY, -1);\r
+ this.groupid = jo.optInt(GROUPID_KEY, -1); //New field is added - Groups feature Rally:US708115 - 1610\r
\r
JSONObject jdeli = jo.getJSONObject("delivery");\r
String url = jdeli.getString("url");\r
String password = jdeli.getString("password");\r
boolean use100 = jdeli.getBoolean("use100");\r
\r
-\r
//Data Router Subscriber HTTPS Relaxation feature USERSTORYID:US674047.\r
Properties p = (new DB()).getProperties();\r
- if (p.get("org.onap.dmaap.datarouter.provserver.https.relaxation").toString().equals("false") && !jo.has("sync")) {\r
- if (!url.startsWith("https://"))\r
- throw new InvalidObjectException("delivery URL is not HTTPS");\r
+ if (!url.startsWith("https://") && isHttpsRelaxationFalseAndHasSyncKey(jo, p)) {\r
+ throw new InvalidObjectException("delivery URL is not HTTPS");\r
}\r
\r
- if (url.length() > 256)\r
+ if (url.length() > 256) {\r
throw new InvalidObjectException("delivery url field is too long");\r
- if (user.length() > 20)\r
+ }\r
+ if (user.length() > 20) {\r
throw new InvalidObjectException("delivery user field is too long");\r
- if (password.length() > 32)\r
+ }\r
+ if (password.length() > 32) {\r
throw new InvalidObjectException("delivery password field is too long");\r
+ }\r
this.delivery = new SubDelivery(url, user, password, use100);\r
\r
this.metadataOnly = jo.getBoolean("metadataOnly");\r
}\r
}\r
\r
+ private boolean isHttpsRelaxationFalseAndHasSyncKey(JSONObject jo, Properties p) {\r
+ return p.get("org.onap.dmaap.datarouter.provserver.https.relaxation").toString().equals("false") && !jo\r
+ .has("sync");\r
+ }\r
+\r
public int getSubid() {\r
return subid;\r
}\r
\r
public void setSubscriber(String subscriber) {\r
if (subscriber != null) {\r
- if (subscriber.length() > 8)\r
+ if (subscriber.length() > 8) {\r
subscriber = subscriber.substring(0, 8);\r
+ }\r
this.subscriber = subscriber;\r
}\r
}\r
@Override\r
public JSONObject asJSONObject() {\r
JSONObject jo = new JSONObject();\r
- jo.put("subid", subid);\r
- jo.put("feedid", feedid);\r
- jo.put("groupid", groupid); //New field is added - Groups feature Rally:US708115 - 1610\r
+ jo.put(SUBID_KEY, subid);\r
+ jo.put(FEEDID_KEY, feedid);\r
+ jo.put(GROUPID_KEY, groupid); //New field is added - Groups feature Rally:US708115 - 1610\r
jo.put("delivery", delivery.asJSONObject());\r
jo.put("metadataOnly", metadataOnly);\r
jo.put("subscriber", subscriber);\r
jo.put("links", links.asJSONObject());\r
jo.put("suspend", suspended);\r
- jo.put("last_mod", last_mod.getTime());\r
- jo.put("created_date", created_date.getTime());\r
+ jo.put(LAST_MOD_KEY, lastMod.getTime());\r
+ jo.put(CREATED_DATE, createdDate.getTime());\r
return jo;\r
}\r
\r
public JSONObject asLimitedJSONObject() {\r
JSONObject jo = asJSONObject();\r
- jo.remove("subid");\r
- jo.remove("feedid");\r
- jo.remove("last_mod");\r
+ jo.remove(SUBID_KEY);\r
+ jo.remove(FEEDID_KEY);\r
+ jo.remove(LAST_MOD_KEY);\r
return jo;\r
}\r
\r
public JSONObject asJSONObject(boolean hidepasswords) {\r
JSONObject jo = asJSONObject();\r
if (hidepasswords) {\r
- jo.remove("subid"); // we no longer hide passwords, however we do hide these\r
- jo.remove("feedid");\r
- jo.remove("last_mod");\r
- jo.remove("created_date");\r
+ jo.remove(SUBID_KEY); // we no longer hide passwords, however we do hide these\r
+ jo.remove(FEEDID_KEY);\r
+ jo.remove(LAST_MOD_KEY);\r
+ jo.remove(CREATED_DATE);\r
}\r
return jo;\r
}\r
try {\r
if (subid == -1) {\r
// No feed ID assigned yet, so assign the next available one\r
- setSubid(next_subid++);\r
+ setSubid(nextSubid++);\r
}\r
// In case we insert a feed from synchronization\r
- if (subid > next_subid)\r
- next_subid = subid + 1;\r
+ if (subid > nextSubid) {\r
+ nextSubid = subid + 1;\r
+ }\r
\r
// Create the SUBSCRIPTIONS row\r
String sql = "insert into SUBSCRIPTIONS (SUBID, FEEDID, DELIVERY_URL, DELIVERY_USER, DELIVERY_PASSWORD, DELIVERY_USE100, METADATA_ONLY, SUBSCRIBER, SUSPENDED, GROUPID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";\r
- ps = c.prepareStatement(sql, new String[]{"SUBID"});\r
+ ps = c.prepareStatement(sql, new String[]{SUBID_COL});\r
ps.setInt(1, subid);\r
ps.setInt(2, feedid);\r
ps.setString(3, getDelivery().getUrl());\r
} catch (SQLException e) {\r
rv = false;\r
intlogger.warn("PROV0005 doInsert: " + e.getMessage());\r
- e.printStackTrace();\r
} finally {\r
try {\r
- if(ps!=null) {\r
+ if (ps != null) {\r
ps.close();\r
}\r
} catch (SQLException e) {\r
- e.printStackTrace();\r
+ intlogger.error(SQLEXCEPTION + e.getMessage());\r
}\r
}\r
return rv;\r
} catch (SQLException e) {\r
rv = false;\r
intlogger.warn("PROV0006 doUpdate: " + e.getMessage());\r
- e.printStackTrace();\r
} finally {\r
try {\r
- if(ps!=null) {\r
+ if (ps != null) {\r
ps.close();\r
}\r
} catch (SQLException e) {\r
- e.printStackTrace();\r
+ intlogger.error(SQLEXCEPTION + e.getMessage());\r
}\r
}\r
return rv;\r
\r
\r
/**\r
- * Rally US708115\r
- * Change Ownership of Subscription - 1610\r
+ * Rally US708115 Change Ownership of Subscription - 1610\r
*/\r
public boolean changeOwnerShip() {\r
boolean rv = true;\r
} catch (SQLException e) {\r
rv = false;\r
intlogger.warn("PROV0006 doUpdate: " + e.getMessage());\r
- e.printStackTrace();\r
} finally {\r
try {\r
- if(ps!=null) {\r
+ if (ps != null) {\r
ps.close();\r
}\r
} catch (SQLException e) {\r
- e.printStackTrace();\r
+ intlogger.error(SQLEXCEPTION + e.getMessage());\r
}\r
}\r
return rv;\r
} catch (SQLException e) {\r
rv = false;\r
intlogger.warn("PROV0007 doDelete: " + e.getMessage());\r
- e.printStackTrace();\r
} finally {\r
try {\r
- if(ps!=null) {\r
+ if (ps != null) {\r
ps.close();\r
}\r
} catch (SQLException e) {\r
- e.printStackTrace();\r
+ intlogger.error(SQLEXCEPTION + e.getMessage());\r
}\r
}\r
return rv;\r
\r
@Override\r
public boolean equals(Object obj) {\r
- if (!(obj instanceof Subscription))\r
+ if (!(obj instanceof Subscription)) {\r
return false;\r
+ }\r
Subscription os = (Subscription) obj;\r
- if (subid != os.subid)\r
+ if (subid != os.subid) {\r
return false;\r
- if (feedid != os.feedid)\r
+ }\r
+ if (feedid != os.feedid) {\r
return false;\r
+ }\r
if (groupid != os.groupid) //New field is added - Groups feature Rally:US708115 - 1610\r
+ {\r
return false;\r
- if (!delivery.equals(os.delivery))\r
- return false;\r
- if (metadataOnly != os.metadataOnly)\r
+ }\r
+ if (!delivery.equals(os.delivery)) {\r
return false;\r
- if (!subscriber.equals(os.subscriber))\r
+ }\r
+ if (metadataOnly != os.metadataOnly) {\r
return false;\r
- if (!links.equals(os.links))\r
+ }\r
+ if (!subscriber.equals(os.subscriber)) {\r
return false;\r
- if (suspended != os.suspended)\r
+ }\r
+ if (!links.equals(os.links)) {\r
return false;\r
- return true;\r
+ }\r
+ return suspended == os.suspended;\r
}\r
\r
@Override\r
public int hashCode() {\r
- return Objects.hash(subid, feedid, groupid, delivery, metadataOnly, subscriber, links, suspended, last_mod, created_date);\r
+ return Objects.hash(subid, feedid, groupid, delivery, metadataOnly, subscriber, links, suspended, lastMod,\r
+ createdDate);\r
}\r
\r
@Override\r
\r
package org.onap.dmaap.datarouter.provisioning.utils;\r
\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.FileReader;\r
+import java.io.IOException;\r
+import java.io.LineNumberReader;\r
+import java.sql.Connection;\r
+import java.sql.DatabaseMetaData;\r
+import java.sql.DriverManager;\r
+import java.sql.ResultSet;\r
+import java.sql.SQLException;\r
+import java.sql.Statement;\r
+import java.util.HashSet;\r
+import java.util.LinkedList;\r
+import java.util.NoSuchElementException;\r
+import java.util.Properties;\r
+import java.util.Queue;\r
+import java.util.Set;\r
import org.apache.log4j.Logger;\r
\r
-import java.io.*;\r
-import java.sql.*;\r
-import java.util.*;\r
-\r
/**\r
* Load the DB JDBC driver, and manage a simple pool of connections to the DB.\r
*\r
*/\r
public class DB {\r
\r
- private static Logger intlogger = Logger.getLogger("org.onap.dmaap.datarouter.provisioning.internal");\r
+ private static Logger intlogger = Logger\r
+ .getLogger("org.onap.dmaap.datarouter.provisioning.internal");\r
\r
private static String DB_URL;\r
private static String DB_LOGIN;\r
private static Properties props;\r
private static final Queue<Connection> queue = new LinkedList<>();\r
\r
- public static String HTTPS_PORT;\r
- public static String HTTP_PORT;\r
+ private static String HTTPS_PORT;\r
+ private static String HTTP_PORT;\r
\r
/**\r
* Construct a DB object. If this is the very first creation of this object, it will load a copy of the properties\r
- * for the server, and attempt to load the JDBC driver for the database. If a fatal error occurs (e.g. either the\r
+ * for the server, and attempt to load the JDBC driver for the database. If a fatal error occurs (e.g. either the\r
* properties file or the DB driver is missing), the JVM will exit.\r
*/\r
public DB() {\r
Class.forName(DB_DRIVER);\r
} catch (IOException e) {\r
intlogger.fatal("PROV9003 Opening properties: " + e.getMessage());\r
- e.printStackTrace();\r
System.exit(1);\r
} catch (ClassNotFoundException e) {\r
intlogger.fatal("PROV9004 cannot find the DB driver: " + e);\r
- e.printStackTrace();\r
System.exit(1);\r
}\r
}\r
if (++n >= 3) {\r
throw sqlEx;\r
}\r
- }\r
- finally {\r
+ } finally {\r
if (connection != null && !connection.isValid(1)) {\r
connection.close();\r
connection = null;\r
return retroFit1();\r
}\r
\r
+\r
+ public static String getHttpsPort() {\r
+ return HTTPS_PORT;\r
+ }\r
+\r
+ public static String getHttpPort() {\r
+ return HTTP_PORT;\r
+ }\r
+\r
/**\r
* Retrofit 1 - Make sure the expected tables are in DB and are initialized. Uses sql_init_01.sql to setup the DB.\r
*\r
runInitScript(connection, 1);\r
}\r
} catch (SQLException e) {\r
- intlogger.fatal("PROV9000: The database credentials are not working: " + e.getMessage());\r
+ intlogger\r
+ .fatal("PROV9000: The database credentials are not working: " + e.getMessage());\r
return false;\r
} finally {\r
if (connection != null) {\r
\r
/**\r
* Initialize the tables by running the initialization scripts located in the directory specified by the property\r
- * <i>org.onap.dmaap.datarouter.provserver.dbscripts</i>. Scripts have names of the form sql_init_NN.sql\r
+ * <i>org.onap.dmaap.datarouter.provserver.dbscripts</i>. Scripts have names of the form\r
+ * sql_init_NN.sql\r
*\r
* @param connection a DB connection\r
* @param scriptId the number of the sql_init_NN.sql script to run\r