datarouter-prov code clean - remove tabs
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / onap / dmaap / datarouter / provisioning / Poker.java
index 1d9f714..4250624 100644 (file)
-/*******************************************************************************\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.FileInputStream;\r
-import java.io.IOException;\r
-import java.io.InputStream;\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.Properties;\r
-import java.util.Set;\r
-import java.util.Timer;\r
-import java.util.TimerTask;\r
-import java.util.TreeSet;\r
-\r
-import javax.servlet.ServletException;\r
-\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.*;\r
-\r
-/**\r
- * This class handles the two timers (described in R1 Design Notes), and takes care of issuing\r
- * the GET to each node of 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
-       /** Template used to generate the URL to issue the GET against */\r
-       public static final String POKE_URL_TEMPLATE = "http://%s/internal/fetchProv";\r
-       \r
-       \r
-       \r
-\r
-       /** This is a singleton -- there is only one Poker object in the server */\r
-       private static Poker p;\r
-\r
-       /**\r
-        * Get the singleton Poker object.\r
-        * @return the Poker\r
-        */\r
-       public static synchronized Poker getPoker() {\r
-               if (p == null)\r
-                       p = new Poker();\r
-               return p;\r
-       }\r
-\r
-       private long timer1;\r
-       private long timer2;\r
-       private Timer rolex;\r
-       private String this_pod;                // DNS name of this machine\r
-       private Logger logger;\r
-       private String provstring;\r
-\r
-       private Poker() {\r
-               timer1 = timer2 = 0;\r
-               rolex = new Timer();\r
-               logger = Logger.getLogger("org.onap.dmaap.datarouter.provisioning.internal");\r
-               try {\r
-                       this_pod = InetAddress.getLocalHost().getHostName();\r
-               } catch (UnknownHostException e) {\r
-                       this_pod = "*UNKNOWN*"; // not a major problem\r
-               }\r
-               provstring = buildProvisioningString();\r
-\r
-               rolex.scheduleAtFixedRate(this, 0L, 1000L);     // Run once a second to check the timers\r
-       }\r
-\r
-       /**\r
-        * This method sets the two timers described in the design notes.\r
-        * @param t1 the first timer controls how long to wait after a provisioning request before poking each node\r
-        *   This 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 (this_pod) {\r
-                       if (timer1 == 0 || t1 > timer1)\r
-                               timer1 = t1;\r
-                       if (timer2 == 0)\r
-                               timer2 = t2;\r
-               }\r
-               if (logger.isDebugEnabled())\r
-                       logger.debug("Poker timers set to " + timer1 + " and " + timer2);\r
-       \r
-               \r
-       }\r
-\r
-       /**\r
-        * Return the last provisioning string built.\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\r
-        * to see if either of the two timers has expired, and if so, will rebuild the provisioning\r
-        * string, and poke all the nodes and other PODs.  The 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 (this_pod) {\r
-                                       if (now > timer1 || now > timer2) {\r
-                                               timer1 = timer2 = 0;\r
-                                               fire = true;\r
-                                       }\r
-                               }\r
-                               if (fire) {\r
-                                       // Rebuild the prov string\r
-                                       provstring = buildProvisioningString();\r
-\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(this_pod))\r
-                                                               pokeNode(n);\r
-                                               }\r
-                                       }\r
-                               }\r
-                       }\r
-               } catch (Exception e) {\r
-                       logger.warn("PROV0020: Caught exception in Poker: "+e);\r
-                       e.printStackTrace();\r
-               }\r
-       }\r
-       private void pokeNode(final String nodename) {\r
-               logger.debug("PROV0012 Poking node " + nodename + " ...");\r
-               Runnable r = new Runnable() {\r
-                       @Override\r
-                       public void run() {\r
-                       \r
-                               try {\r
-                                       String u = String.format(POKE_URL_TEMPLATE, nodename+":"+DB.HTTP_PORT);\r
-                                       URL url = new URL(u);\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("PROV0013 MalformedURLException Error poking node "+nodename+": " + e.getMessage());\r
-                               } catch (IOException e) {\r
-                                       logger.warn("PROV0013 IOException Error poking node "+nodename+": " + e.getMessage());\r
-                               }\r
-                       }\r
-               };\r
-//             Thread t = new Thread(r);\r
-//             t.start();\r
-               r.run();\r
-       }\r
-       @SuppressWarnings("unused")\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
-\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
-                       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
-               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 provstring = sb.toString();\r
-               try {\r
-                       new JSONObject(new JSONTokener(provstring));\r
-               } catch (JSONException e) {\r
-                       logger.warn("PROV0016: Possible invalid prov string: "+e);\r
-               }\r
-               return provstring;\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.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+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.Properties;
+import java.util.Set;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.TreeSet;
+
+import javax.servlet.ServletException;
+
+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 */
+    public static final String POKE_URL_TEMPLATE = "http://%s/internal/fetchProv";
+
+
+
+
+    /** This is a singleton -- there is only one Poker object in the server */
+    private static Poker p;
+
+    /**
+     * Get the singleton Poker object.
+     * @return the Poker
+     */
+    public static synchronized Poker getPoker() {
+        if (p == null)
+            p = new Poker();
+        return p;
+    }
+
+    private long timer1;
+    private long timer2;
+    private Timer rolex;
+    private String this_pod;        // DNS name of this machine
+    private Logger logger;
+    private String provstring;
+
+    private Poker() {
+        timer1 = timer2 = 0;
+        rolex = new Timer();
+        logger = Logger.getLogger("org.onap.dmaap.datarouter.provisioning.internal");
+        try {
+            this_pod = InetAddress.getLocalHost().getHostName();
+        } catch (UnknownHostException e) {
+            this_pod = "*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 (this_pod) {
+            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 (this_pod) {
+                    if (now > timer1 || now > timer2) {
+                        timer1 = timer2 = 0;
+                        fire = true;
+                    }
+                }
+                if (fire) {
+                    // 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(this_pod))
+                                pokeNode(n);
+                        }
+                    }
+                }
+            }
+        } catch (Exception e) {
+            logger.warn("PROV0020: Caught exception in Poker: "+e);
+            e.printStackTrace();
+        }
+    }
+    private void pokeNode(final String nodename) {
+        logger.debug("PROV0012 Poking node " + nodename + " ...");
+        Runnable r = new Runnable() {
+            @Override
+            public void run() {
+
+                try {
+                    String u = String.format(POKE_URL_TEMPLATE, nodename+":"+DB.HTTP_PORT);
+                    URL url = new URL(u);
+                    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 "+nodename+": " + e.getMessage());
+                } catch (IOException e) {
+                    logger.warn("PROV0013 IOException Error poking node "+nodename+": " + e.getMessage());
+                }
+            }
+        };
+//        Thread t = new Thread(r);
+//        t.start();
+        r.run();
+    }
+    @SuppressWarnings("unused")
+    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 provstring = sb.toString();
+        try {
+            new JSONObject(new JSONTokener(provstring));
+        } catch (JSONException e) {
+            logger.warn("PROV0016: Possible invalid prov string: "+e);
+        }
+        return provstring;
+    }
+    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();
+    }
+}