aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/Poker.java647
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/PublishServlet.java406
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/LogRecord.java43
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Subscription.java187
-rw-r--r--datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DB.java50
5 files changed, 694 insertions, 639 deletions
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/Poker.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/Poker.java
index 563e6f7f..193485e6 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/Poker.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/Poker.java
@@ -1,323 +1,324 @@
-/*******************************************************************************
- * ============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();
- }
-}
+/*******************************************************************************
+ * ============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.DB;
+
+/**
+ * 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;
+ 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
+ logger.info("UnknownHostException: Setting thisPod to \"*UNKNOWN*\"");
+ }
+ provString = buildProvisioningString();
+
+ rolex.scheduleAtFixedRate(this, 0L, 1000L); // Run once a second to check the timers
+ }
+
+ /**
+ * Get the singleton Poker object.
+ *
+ * @return the Poker
+ */
+ public static synchronized Poker getPoker() {
+ if (poker == null) {
+ poker = new Poker();
+ }
+ return poker;
+ }
+
+ /**
+ * 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);
+ }
+ }
+
+ 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.getHttpPort());
+ 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();
+ }
+}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/PublishServlet.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/PublishServlet.java
index 4cefdf1e..07285950 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/PublishServlet.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/PublishServlet.java
@@ -1,197 +1,209 @@
-/*******************************************************************************
- * ============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 &lt;publishURL&gt; 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;
- }
- }
-}
+/*******************************************************************************
+ * ============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 com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+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.DB;
+
+/**
+ * This servlet handles redirects for the &lt;publishURL&gt; 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.getHttpsPort();
+ 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;
+ }
+ }
+}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/LogRecord.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/LogRecord.java
index 70b8e6a0..1791bdc8 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/LogRecord.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/LogRecord.java
@@ -30,22 +30,22 @@ import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
-import java.sql.Statement;
import java.sql.Types;
import java.text.ParseException;
import java.util.Iterator;
-
+import org.apache.log4j.Logger;
import org.onap.dmaap.datarouter.provisioning.utils.DB;
import org.onap.dmaap.datarouter.provisioning.utils.RLEBitSet;
/**
- * The representation of a Log Record, as retrieved from the DB. Since this record format is only used
- * to replicate between provisioning servers, it is very bare-bones; e.g. there are no field setters and only 1 getter.
+ * The representation of a Log Record, as retrieved from the DB. Since this record format is only used to replicate
+ * between provisioning servers, it is very bare-bones; e.g. there are no field setters and only 1 getter.
*
* @author Robert Eby
* @version $Id: LogRecord.java,v 1.7 2014/03/12 19:45:41 eby Exp $
*/
public class LogRecord extends BaseLogRecord {
+
/**
* Print all log records whose RECORD_IDs are in the bit set provided.
*
@@ -53,34 +53,29 @@ public class LogRecord extends BaseLogRecord {
* @param bs the {@link RLEBitSet} listing the record IDs to print
* @throws IOException
*/
+ private static Logger intlogger = Logger.getLogger("org.onap.dmaap.datarouter.provisioning.beans");
+
public static void printLogRecords(OutputStream os, RLEBitSet bs) throws IOException {
final String sql = "select * from LOG_RECORDS where RECORD_ID >= ? AND RECORD_ID <= ?";
DB db = new DB();
- Connection conn = null;
- try {
- conn = db.getConnection();
- try(Statement stmt = conn.createStatement()) {
- Iterator<Long[]> iter = bs.getRangeIterator();
- try(PreparedStatement ps = conn.prepareStatement(sql)) {
- while (iter.hasNext()) {
- Long[] n = iter.next();
- ps.setLong(1, n[0]);
- ps.setLong(2, n[1]);
- try(ResultSet rs = ps.executeQuery()) {
- while (rs.next()) {
- LogRecord lr = new LogRecord(rs);
- os.write(lr.toString().getBytes());
- }
- ps.clearParameters();
+ try (Connection conn = db.getConnection()) {
+ Iterator<Long[]> iter = bs.getRangeIterator();
+ try (PreparedStatement ps = conn.prepareStatement(sql)) {
+ while (iter.hasNext()) {
+ Long[] n = iter.next();
+ ps.setLong(1, n[0]);
+ ps.setLong(2, n[1]);
+ try (ResultSet rs = ps.executeQuery()) {
+ while (rs.next()) {
+ LogRecord lr = new LogRecord(rs);
+ os.write(lr.toString().getBytes());
}
+ ps.clearParameters();
}
}
}
} catch (SQLException e) {
- e.printStackTrace();
- } finally {
- if (conn != null)
- db.release(conn);
+ intlogger.error("SQLException: " + e.getMessage());
}
}
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Subscription.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Subscription.java
index 1333b55e..f4275255 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Subscription.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Subscription.java
@@ -29,8 +29,12 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
-import java.util.*;
-
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.Objects;
+import java.util.Properties;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.onap.dmaap.datarouter.provisioning.utils.DB;
@@ -43,8 +47,16 @@ import org.onap.dmaap.datarouter.provisioning.utils.URLUtilities;
* @version $Id: Subscription.java,v 1.9 2013/10/28 18:06:53 eby Exp $
*/
public class Subscription extends Syncable {
+
+ private static final String SQLEXCEPTION = "SQLException: ";
+ private static final String SUBID_KEY = "subid";
+ private static final String SUBID_COL = "SUBID";
+ private static final String FEEDID_KEY = "feedid";
+ private static final String GROUPID_KEY = "groupid";
+ private static final String LAST_MOD_KEY = "last_mod";
+ private static final String CREATED_DATE = "created_date";
private static Logger intlogger = Logger.getLogger("org.onap.dmaap.datarouter.provisioning.internal");
- private static int next_subid = getMaxSubID() + 1;
+ private static int nextSubid = getMaxSubID() + 1;
private int subid;
private int feedid;
@@ -54,8 +66,8 @@ public class Subscription extends Syncable {
private String subscriber;
private SubLinks links;
private boolean suspended;
- private Date last_mod;
- private Date created_date;
+ private Date lastMod;
+ private Date createdDate;
public static Subscription getSubscriptionMatching(Subscription sub) {
SubDelivery deli = sub.getDelivery();
@@ -69,13 +81,13 @@ public class Subscription extends Syncable {
sub.isMetadataOnly() ? 1 : 0
);
List<Subscription> list = getSubscriptionsForSQL(sql);
- return list.size() > 0 ? list.get(0) : null;
+ return !list.isEmpty() ? list.get(0) : null;
}
public static Subscription getSubscriptionById(int id) {
String sql = "select * from SUBSCRIPTIONS where SUBID = " + id;
List<Subscription> list = getSubscriptionsForSQL(sql);
- return list.size() > 0 ? list.get(0) : null;
+ return !list.isEmpty() ? list.get(0) : null;
}
public static Collection<Subscription> getAllSubscriptions() {
@@ -83,13 +95,13 @@ public class Subscription extends Syncable {
}
private static List<Subscription> getSubscriptionsForSQL(String sql) {
- List<Subscription> list = new ArrayList<Subscription>();
+ List<Subscription> list = new ArrayList<>();
try {
DB db = new DB();
@SuppressWarnings("resource")
Connection conn = db.getConnection();
- try(Statement stmt = conn.createStatement()) {
- try(ResultSet rs = stmt.executeQuery(sql)) {
+ try (Statement stmt = conn.createStatement()) {
+ try (ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
Subscription sub = new Subscription(rs);
list.add(sub);
@@ -98,7 +110,7 @@ public class Subscription extends Syncable {
}
db.release(conn);
} catch (SQLException e) {
- e.printStackTrace();
+ intlogger.error(e);
}
return list;
}
@@ -109,8 +121,8 @@ public class Subscription extends Syncable {
DB db = new DB();
@SuppressWarnings("resource")
Connection conn = db.getConnection();
- try(Statement stmt = conn.createStatement()) {
- try(ResultSet rs = stmt.executeQuery("select MAX(subid) from SUBSCRIPTIONS")) {
+ try (Statement stmt = conn.createStatement()) {
+ try (ResultSet rs = stmt.executeQuery("select MAX(subid) from SUBSCRIPTIONS")) {
if (rs.next()) {
max = rs.getInt(1);
}
@@ -119,29 +131,31 @@ public class Subscription extends Syncable {
db.release(conn);
} catch (SQLException e) {
intlogger.info("getMaxSubID: " + e.getMessage());
- e.printStackTrace();
}
return max;
}
public static Collection<String> getSubscriptionUrlList(int feedid) {
- List<String> list = new ArrayList<String>();
- String sql = "select SUBID from SUBSCRIPTIONS where FEEDID = " + feedid;
+ List<String> list = new ArrayList<>();
+ String sql = "select SUBID from SUBSCRIPTIONS where FEEDID = ?";
+
try {
DB db = new DB();
@SuppressWarnings("resource")
Connection conn = db.getConnection();
- try(Statement stmt = conn.createStatement()) {
- try(ResultSet rs = stmt.executeQuery(sql)) {
+
+ try (PreparedStatement stmt = conn.prepareStatement(sql)) {
+ stmt.setString(1, String.valueOf(feedid));
+ try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
- int subid = rs.getInt("SUBID");
+ int subid = rs.getInt(SUBID_COL);
list.add(URLUtilities.generateSubscriptionURL(subid));
}
}
}
db.release(conn);
} catch (SQLException e) {
- e.printStackTrace();
+ intlogger.error(SQLEXCEPTION + e.getMessage());
}
return list;
}
@@ -157,8 +171,8 @@ public class Subscription extends Syncable {
DB db = new DB();
@SuppressWarnings("resource")
Connection conn = db.getConnection();
- try(Statement stmt = conn.createStatement()) {
- try(ResultSet rs = stmt.executeQuery("select count(*) from SUBSCRIPTIONS")) {
+ try (Statement stmt = conn.createStatement()) {
+ try (ResultSet rs = stmt.executeQuery("select count(*) from SUBSCRIPTIONS")) {
if (rs.next()) {
count = rs.getInt(1);
}
@@ -167,7 +181,6 @@ public class Subscription extends Syncable {
db.release(conn);
} catch (SQLException e) {
intlogger.warn("PROV0008 countActiveSubscriptions: " + e.getMessage());
- e.printStackTrace();
}
return count;
}
@@ -185,30 +198,31 @@ public class Subscription extends Syncable {
this.subscriber = "";
this.links = new SubLinks();
this.suspended = false;
- this.last_mod = new Date();
- this.created_date = new Date();
+ this.lastMod = new Date();
+ this.createdDate = new Date();
}
public Subscription(ResultSet rs) throws SQLException {
- this.subid = rs.getInt("SUBID");
+ this.subid = rs.getInt(SUBID_COL);
this.feedid = rs.getInt("FEEDID");
this.groupid = rs.getInt("GROUPID"); //New field is added - Groups feature Rally:US708115 - 1610
this.delivery = new SubDelivery(rs);
this.metadataOnly = rs.getBoolean("METADATA_ONLY");
this.subscriber = rs.getString("SUBSCRIBER");
- this.links = new SubLinks(rs.getString("SELF_LINK"), URLUtilities.generateFeedURL(feedid), rs.getString("LOG_LINK"));
+ this.links = new SubLinks(rs.getString("SELF_LINK"), URLUtilities.generateFeedURL(feedid),
+ rs.getString("LOG_LINK"));
this.suspended = rs.getBoolean("SUSPENDED");
- this.last_mod = rs.getDate("LAST_MOD");
- this.created_date = rs.getDate("CREATED_DATE");
+ this.lastMod = rs.getDate("LAST_MOD");
+ this.createdDate = rs.getDate("CREATED_DATE");
}
public Subscription(JSONObject jo) throws InvalidObjectException {
this("", "", "");
try {
// The JSONObject is assumed to contain a vnd.att-dr.subscription representation
- this.subid = jo.optInt("subid", -1);
- this.feedid = jo.optInt("feedid", -1);
- this.groupid = jo.optInt("groupid", -1); //New field is added - Groups feature Rally:US708115 - 1610
+ this.subid = jo.optInt(SUBID_KEY, -1);
+ this.feedid = jo.optInt(FEEDID_KEY, -1);
+ this.groupid = jo.optInt(GROUPID_KEY, -1); //New field is added - Groups feature Rally:US708115 - 1610
JSONObject jdeli = jo.getJSONObject("delivery");
String url = jdeli.getString("url");
@@ -216,20 +230,21 @@ public class Subscription extends Syncable {
String password = jdeli.getString("password");
boolean use100 = jdeli.getBoolean("use100");
-
//Data Router Subscriber HTTPS Relaxation feature USERSTORYID:US674047.
Properties p = (new DB()).getProperties();
- if (p.get("org.onap.dmaap.datarouter.provserver.https.relaxation").toString().equals("false") && !jo.has("sync")) {
- if (!url.startsWith("https://"))
- throw new InvalidObjectException("delivery URL is not HTTPS");
+ if (!url.startsWith("https://") && isHttpsRelaxationFalseAndHasSyncKey(jo, p)) {
+ throw new InvalidObjectException("delivery URL is not HTTPS");
}
- if (url.length() > 256)
+ if (url.length() > 256) {
throw new InvalidObjectException("delivery url field is too long");
- if (user.length() > 20)
+ }
+ if (user.length() > 20) {
throw new InvalidObjectException("delivery user field is too long");
- if (password.length() > 32)
+ }
+ if (password.length() > 32) {
throw new InvalidObjectException("delivery password field is too long");
+ }
this.delivery = new SubDelivery(url, user, password, use100);
this.metadataOnly = jo.getBoolean("metadataOnly");
@@ -245,6 +260,11 @@ public class Subscription extends Syncable {
}
}
+ private boolean isHttpsRelaxationFalseAndHasSyncKey(JSONObject jo, Properties p) {
+ return p.get("org.onap.dmaap.datarouter.provserver.https.relaxation").toString().equals("false") && !jo
+ .has("sync");
+ }
+
public int getSubid() {
return subid;
}
@@ -309,8 +329,9 @@ public class Subscription extends Syncable {
public void setSubscriber(String subscriber) {
if (subscriber != null) {
- if (subscriber.length() > 8)
+ if (subscriber.length() > 8) {
subscriber = subscriber.substring(0, 8);
+ }
this.subscriber = subscriber;
}
}
@@ -326,34 +347,34 @@ public class Subscription extends Syncable {
@Override
public JSONObject asJSONObject() {
JSONObject jo = new JSONObject();
- jo.put("subid", subid);
- jo.put("feedid", feedid);
- jo.put("groupid", groupid); //New field is added - Groups feature Rally:US708115 - 1610
+ jo.put(SUBID_KEY, subid);
+ jo.put(FEEDID_KEY, feedid);
+ jo.put(GROUPID_KEY, groupid); //New field is added - Groups feature Rally:US708115 - 1610
jo.put("delivery", delivery.asJSONObject());
jo.put("metadataOnly", metadataOnly);
jo.put("subscriber", subscriber);
jo.put("links", links.asJSONObject());
jo.put("suspend", suspended);
- jo.put("last_mod", last_mod.getTime());
- jo.put("created_date", created_date.getTime());
+ jo.put(LAST_MOD_KEY, lastMod.getTime());
+ jo.put(CREATED_DATE, createdDate.getTime());
return jo;
}
public JSONObject asLimitedJSONObject() {
JSONObject jo = asJSONObject();
- jo.remove("subid");
- jo.remove("feedid");
- jo.remove("last_mod");
+ jo.remove(SUBID_KEY);
+ jo.remove(FEEDID_KEY);
+ jo.remove(LAST_MOD_KEY);
return jo;
}
public JSONObject asJSONObject(boolean hidepasswords) {
JSONObject jo = asJSONObject();
if (hidepasswords) {
- jo.remove("subid"); // we no longer hide passwords, however we do hide these
- jo.remove("feedid");
- jo.remove("last_mod");
- jo.remove("created_date");
+ jo.remove(SUBID_KEY); // we no longer hide passwords, however we do hide these
+ jo.remove(FEEDID_KEY);
+ jo.remove(LAST_MOD_KEY);
+ jo.remove(CREATED_DATE);
}
return jo;
}
@@ -365,15 +386,16 @@ public class Subscription extends Syncable {
try {
if (subid == -1) {
// No feed ID assigned yet, so assign the next available one
- setSubid(next_subid++);
+ setSubid(nextSubid++);
}
// In case we insert a feed from synchronization
- if (subid > next_subid)
- next_subid = subid + 1;
+ if (subid > nextSubid) {
+ nextSubid = subid + 1;
+ }
// Create the SUBSCRIPTIONS row
String sql = "insert into SUBSCRIPTIONS (SUBID, FEEDID, DELIVERY_URL, DELIVERY_USER, DELIVERY_PASSWORD, DELIVERY_USE100, METADATA_ONLY, SUBSCRIBER, SUSPENDED, GROUPID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
- ps = c.prepareStatement(sql, new String[]{"SUBID"});
+ ps = c.prepareStatement(sql, new String[]{SUBID_COL});
ps.setInt(1, subid);
ps.setInt(2, feedid);
ps.setString(3, getDelivery().getUrl());
@@ -397,14 +419,13 @@ public class Subscription extends Syncable {
} catch (SQLException e) {
rv = false;
intlogger.warn("PROV0005 doInsert: " + e.getMessage());
- e.printStackTrace();
} finally {
try {
- if(ps!=null) {
+ if (ps != null) {
ps.close();
}
} catch (SQLException e) {
- e.printStackTrace();
+ intlogger.error(SQLEXCEPTION + e.getMessage());
}
}
return rv;
@@ -429,14 +450,13 @@ public class Subscription extends Syncable {
} catch (SQLException e) {
rv = false;
intlogger.warn("PROV0006 doUpdate: " + e.getMessage());
- e.printStackTrace();
} finally {
try {
- if(ps!=null) {
+ if (ps != null) {
ps.close();
}
} catch (SQLException e) {
- e.printStackTrace();
+ intlogger.error(SQLEXCEPTION + e.getMessage());
}
}
return rv;
@@ -444,8 +464,7 @@ public class Subscription extends Syncable {
/**
- * Rally US708115
- * Change Ownership of Subscription - 1610
+ * Rally US708115 Change Ownership of Subscription - 1610
*/
public boolean changeOwnerShip() {
boolean rv = true;
@@ -464,14 +483,13 @@ public class Subscription extends Syncable {
} catch (SQLException e) {
rv = false;
intlogger.warn("PROV0006 doUpdate: " + e.getMessage());
- e.printStackTrace();
} finally {
try {
- if(ps!=null) {
+ if (ps != null) {
ps.close();
}
} catch (SQLException e) {
- e.printStackTrace();
+ intlogger.error(SQLEXCEPTION + e.getMessage());
}
}
return rv;
@@ -490,14 +508,13 @@ public class Subscription extends Syncable {
} catch (SQLException e) {
rv = false;
intlogger.warn("PROV0007 doDelete: " + e.getMessage());
- e.printStackTrace();
} finally {
try {
- if(ps!=null) {
+ if (ps != null) {
ps.close();
}
} catch (SQLException e) {
- e.printStackTrace();
+ intlogger.error(SQLEXCEPTION + e.getMessage());
}
}
return rv;
@@ -510,31 +527,39 @@ public class Subscription extends Syncable {
@Override
public boolean equals(Object obj) {
- if (!(obj instanceof Subscription))
+ if (!(obj instanceof Subscription)) {
return false;
+ }
Subscription os = (Subscription) obj;
- if (subid != os.subid)
+ if (subid != os.subid) {
return false;
- if (feedid != os.feedid)
+ }
+ if (feedid != os.feedid) {
return false;
+ }
if (groupid != os.groupid) //New field is added - Groups feature Rally:US708115 - 1610
+ {
return false;
- if (!delivery.equals(os.delivery))
- return false;
- if (metadataOnly != os.metadataOnly)
+ }
+ if (!delivery.equals(os.delivery)) {
return false;
- if (!subscriber.equals(os.subscriber))
+ }
+ if (metadataOnly != os.metadataOnly) {
return false;
- if (!links.equals(os.links))
+ }
+ if (!subscriber.equals(os.subscriber)) {
return false;
- if (suspended != os.suspended)
+ }
+ if (!links.equals(os.links)) {
return false;
- return true;
+ }
+ return suspended == os.suspended;
}
@Override
public int hashCode() {
- return Objects.hash(subid, feedid, groupid, delivery, metadataOnly, subscriber, links, suspended, last_mod, created_date);
+ return Objects.hash(subid, feedid, groupid, delivery, metadataOnly, subscriber, links, suspended, lastMod,
+ createdDate);
}
@Override
diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DB.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DB.java
index 7f0d56b7..1952f946 100644
--- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DB.java
+++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DB.java
@@ -24,12 +24,25 @@
package org.onap.dmaap.datarouter.provisioning.utils;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.LineNumberReader;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.NoSuchElementException;
+import java.util.Properties;
+import java.util.Queue;
+import java.util.Set;
import org.apache.log4j.Logger;
-import java.io.*;
-import java.sql.*;
-import java.util.*;
-
/**
* Load the DB JDBC driver, and manage a simple pool of connections to the DB.
*
@@ -38,7 +51,8 @@ import java.util.*;
*/
public class DB {
- private static Logger intlogger = Logger.getLogger("org.onap.dmaap.datarouter.provisioning.internal");
+ private static Logger intlogger = Logger
+ .getLogger("org.onap.dmaap.datarouter.provisioning.internal");
private static String DB_URL;
private static String DB_LOGIN;
@@ -46,12 +60,12 @@ public class DB {
private static Properties props;
private static final Queue<Connection> queue = new LinkedList<>();
- public static String HTTPS_PORT;
- public static String HTTP_PORT;
+ private static String HTTPS_PORT;
+ private static String HTTP_PORT;
/**
* Construct a DB object. If this is the very first creation of this object, it will load a copy of the properties
- * for the server, and attempt to load the JDBC driver for the database. If a fatal error occurs (e.g. either the
+ * for the server, and attempt to load the JDBC driver for the database. If a fatal error occurs (e.g. either the
* properties file or the DB driver is missing), the JVM will exit.
*/
public DB() {
@@ -70,11 +84,9 @@ public class DB {
Class.forName(DB_DRIVER);
} catch (IOException e) {
intlogger.fatal("PROV9003 Opening properties: " + e.getMessage());
- e.printStackTrace();
System.exit(1);
} catch (ClassNotFoundException e) {
intlogger.fatal("PROV9004 cannot find the DB driver: " + e);
- e.printStackTrace();
System.exit(1);
}
}
@@ -111,8 +123,7 @@ public class DB {
if (++n >= 3) {
throw sqlEx;
}
- }
- finally {
+ } finally {
if (connection != null && !connection.isValid(1)) {
connection.close();
connection = null;
@@ -151,6 +162,15 @@ public class DB {
return retroFit1();
}
+
+ public static String getHttpsPort() {
+ return HTTPS_PORT;
+ }
+
+ public static String getHttpPort() {
+ return HTTP_PORT;
+ }
+
/**
* Retrofit 1 - Make sure the expected tables are in DB and are initialized. Uses sql_init_01.sql to setup the DB.
*
@@ -175,7 +195,8 @@ public class DB {
runInitScript(connection, 1);
}
} catch (SQLException e) {
- intlogger.fatal("PROV9000: The database credentials are not working: " + e.getMessage());
+ intlogger
+ .fatal("PROV9000: The database credentials are not working: " + e.getMessage());
return false;
} finally {
if (connection != null) {
@@ -210,7 +231,8 @@ public class DB {
/**
* Initialize the tables by running the initialization scripts located in the directory specified by the property
- * <i>org.onap.dmaap.datarouter.provserver.dbscripts</i>. Scripts have names of the form sql_init_NN.sql
+ * <i>org.onap.dmaap.datarouter.provserver.dbscripts</i>. Scripts have names of the form
+ * sql_init_NN.sql
*
* @param connection a DB connection
* @param scriptId the number of the sql_init_NN.sql script to run