[DMAAP-48] Initial code import
[dmaap/datarouter.git] / datarouter-prov / src / main / java / com / att / research / datarouter / provisioning / BaseServlet.java
1 /*******************************************************************************\r
2  * ============LICENSE_START==================================================\r
3  * * org.onap.dmaap\r
4  * * ===========================================================================\r
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
6  * * ===========================================================================\r
7  * * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * * you may not use this file except in compliance with the License.\r
9  * * You may obtain a copy of the License at\r
10  * * \r
11  *  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * * \r
13  *  * Unless required by applicable law or agreed to in writing, software\r
14  * * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * * See the License for the specific language governing permissions and\r
17  * * limitations under the License.\r
18  * * ============LICENSE_END====================================================\r
19  * *\r
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
21  * *\r
22  ******************************************************************************/\r
23 \r
24 \r
25 package com.att.research.datarouter.provisioning;\r
26 \r
27 import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;\r
28 \r
29 import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;\r
30 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;\r
31 \r
32 import java.io.IOException;\r
33 import java.io.InputStream;\r
34 import java.net.InetAddress;\r
35 import java.net.UnknownHostException;\r
36 import java.security.cert.X509Certificate;\r
37 import java.sql.Connection;\r
38 import java.sql.SQLException;\r
39 import java.util.HashMap;\r
40 import java.util.HashSet;\r
41 import java.util.Map;\r
42 import java.util.Set;\r
43 import java.util.List;\r
44 import java.util.ArrayList;\r
45 \r
46 import javax.servlet.ServletConfig;\r
47 import javax.servlet.ServletException;\r
48 import javax.servlet.http.HttpServlet;\r
49 import javax.servlet.http.HttpServletRequest;\r
50 \r
51 import org.apache.log4j.Logger;\r
52 import org.json.JSONObject;\r
53 import org.json.JSONTokener;\r
54 import org.json.JSONException;  \r
55 import org.slf4j.MDC;\r
56 \r
57 import com.att.research.datarouter.authz.Authorizer;\r
58 import com.att.research.datarouter.authz.impl.ProvAuthorizer;\r
59 import com.att.research.datarouter.authz.impl.ProvDataProvider;\r
60 import com.att.research.datarouter.provisioning.beans.Deleteable;\r
61 import com.att.research.datarouter.provisioning.beans.Feed;\r
62 import com.att.research.datarouter.provisioning.beans.Insertable;\r
63 import com.att.research.datarouter.provisioning.beans.NodeClass;\r
64 import com.att.research.datarouter.provisioning.beans.Parameters;\r
65 import com.att.research.datarouter.provisioning.beans.Subscription;\r
66 import com.att.research.datarouter.provisioning.beans.Updateable;\r
67 import com.att.research.datarouter.provisioning.utils.DB;\r
68 import com.att.research.datarouter.provisioning.utils.ThrottleFilter;\r
69 import com.att.research.datarouter.provisioning.beans.Group; //Groups feature Rally:US708115 - 1610     \r
70 \r
71 import java.util.Properties;\r
72 import java.util.regex.Pattern;\r
73 import javax.mail.Message;\r
74 import javax.mail.MessagingException;\r
75 import javax.mail.Multipart;\r
76 import javax.mail.Session;\r
77 import javax.mail.Transport;\r
78 import javax.mail.internet.AddressException;\r
79 import javax.mail.internet.InternetAddress;\r
80 import javax.mail.internet.MimeBodyPart;\r
81 import javax.mail.internet.MimeMessage;\r
82 import javax.mail.internet.MimeMultipart;\r
83 /**\r
84  * This is the base class for all Servlets in the provisioning code.\r
85  * It provides standard constants and some common methods.\r
86  *\r
87  * @author Robert Eby\r
88  * @version $Id: BaseServlet.java,v 1.16 2014/03/12 19:45:40 eby Exp $\r
89  */\r
90 @SuppressWarnings("serial")\r
91 public class BaseServlet extends HttpServlet implements ProvDataProvider {\r
92         public static final String BEHALF_HEADER         = "X-ATT-DR-ON-BEHALF-OF";\r
93         public static final String FEED_BASECONTENT_TYPE = "application/vnd.att-dr.feed";\r
94         public static final String FEED_CONTENT_TYPE     = "application/vnd.att-dr.feed; version=2.0";\r
95         public static final String FEEDFULL_CONTENT_TYPE = "application/vnd.att-dr.feed-full; version=2.0";\r
96         public static final String FEEDLIST_CONTENT_TYPE = "application/vnd.att-dr.feed-list; version=1.0";\r
97         public static final String SUB_BASECONTENT_TYPE  = "application/vnd.att-dr.subscription";\r
98         public static final String SUB_CONTENT_TYPE      = "application/vnd.att-dr.subscription; version=2.0";\r
99         public static final String SUBFULL_CONTENT_TYPE  = "application/vnd.att-dr.subscription-full; version=2.0";\r
100         public static final String SUBLIST_CONTENT_TYPE  = "application/vnd.att-dr.subscription-list; version=1.0";\r
101 \r
102         \r
103         //Adding groups functionality, ...1610\r
104         public static final String GROUP_BASECONTENT_TYPE = "application/vnd.att-dr.group";\r
105         public static final String GROUP_CONTENT_TYPE     = "application/vnd.att-dr.group; version=2.0";\r
106         public static final String GROUPFULL_CONTENT_TYPE = "application/vnd.att-dr.group-full; version=2.0";\r
107         public static final String GROUPLIST_CONTENT_TYPE = "application/vnd.att-dr.fegrouped-list; version=1.0";\r
108 \r
109 \r
110         public static final String LOGLIST_CONTENT_TYPE  = "application/vnd.att-dr.log-list; version=1.0";\r
111         public static final String PROVFULL_CONTENT_TYPE1 = "application/vnd.att-dr.provfeed-full; version=1.0";\r
112         public static final String PROVFULL_CONTENT_TYPE2 = "application/vnd.att-dr.provfeed-full; version=2.0";\r
113         public static final String CERT_ATTRIBUTE        = "javax.servlet.request.X509Certificate";\r
114 \r
115         public static final String DB_PROBLEM_MSG = "There has been a problem with the DB.  It is suggested you try the operation again.";\r
116 \r
117         public static final int    DEFAULT_MAX_FEEDS     = 10000;\r
118         public static final int    DEFAULT_MAX_SUBS      = 100000;\r
119         public static final int    DEFAULT_POKETIMER1    = 5;\r
120         public static final int    DEFAULT_POKETIMER2    = 30;\r
121         public static final String DEFAULT_DOMAIN        = "web.att.com";\r
122         public static final String DEFAULT_PROVSRVR_NAME = "feeds-drtr.web.att.com";\r
123         public static final String RESEARCH_SUBNET       = "135.207.136.128/25";\r
124         public static final String STATIC_ROUTING_NODES       = ""; //Adding new param for static Routing - Rally:US664862-1610\r
125 \r
126         /** A boolean to trigger one time "provisioning changed" event on startup */\r
127         private static boolean startmsg_flag  = true;\r
128         /** This POD should require SSL connections from clients; pulled from the DB (PROV_REQUIRE_SECURE) */\r
129         private static boolean require_secure = true;\r
130         /** This POD should require signed, recognized certificates from clients; pulled from the DB (PROV_REQUIRE_CERT) */\r
131         private static boolean require_cert   = true;\r
132         /** The set of authorized addresses and networks; pulled from the DB (PROV_AUTH_ADDRESSES) */\r
133         private static Set<String> authorizedAddressesAndNetworks = new HashSet<String>();\r
134         /** The set of authorized names; pulled from the DB (PROV_AUTH_SUBJECTS) */\r
135         private static Set<String> authorizedNames = new HashSet<String>();\r
136         /** The FQDN of the initially "active" provisioning server in this Data Router ecosystem */\r
137         private static String initial_active_pod;\r
138         /** The FQDN of the initially "standby" provisioning server in this Data Router ecosystem */\r
139         private static String initial_standby_pod;\r
140         /** The FQDN of this provisioning server in this Data Router ecosystem */\r
141         private static String this_pod;\r
142         /** "Timer 1" - used to determine when to notify nodes of provisioning changes */\r
143         private static long poke_timer1;\r
144         /** "Timer 2" - used to determine when to notify nodes of provisioning changes */\r
145         private static long poke_timer2;\r
146         /** Array of nodes names and/or FQDNs */\r
147         private static String[] nodes = new String[0];\r
148         /** Array of node IP addresses */\r
149         private static InetAddress[] nodeAddresses = new InetAddress[0];\r
150         /** Array of POD IP addresses */\r
151         private static InetAddress[] podAddresses = new InetAddress[0];\r
152         /** The maximum number of feeds allowed; pulled from the DB (PROV_MAXFEED_COUNT) */\r
153         protected static int max_feeds    = 0;\r
154         /** The maximum number of subscriptions allowed; pulled from the DB (PROV_MAXSUB_COUNT) */\r
155         protected static int max_subs     = 0;\r
156         /** The current number of feeds in the system */\r
157         protected static int active_feeds = 0;\r
158         /** The current number of subscriptions in the system */\r
159         protected static int active_subs  = 0;\r
160         /** The domain used to generate a FQDN from the "bare" node names */\r
161         public static String prov_domain = "web.att.com";\r
162         /** The standard FQDN of the provisioning server in this Data Router ecosystem */\r
163         public static String prov_name   = "feeds-drtr.web.att.com";\r
164         /** The standard FQDN of the ACTIVE provisioning server in this Data Router ecosystem */\r
165         public static String active_prov_name   = "feeds-drtr.web.att.com";\r
166         /** Special subnet that is allowed access to /internal */\r
167         protected static String special_subnet = RESEARCH_SUBNET;\r
168 \r
169         /** Special subnet that is allowed access to /internal to Lab Machine */\r
170         protected static String special_subnet_secondary = RESEARCH_SUBNET;\r
171         protected static String static_routing_nodes = STATIC_ROUTING_NODES; //Adding new param for static Routing - Rally:US664862-1610\r
172 \r
173         /** This logger is used to log provisioning events */\r
174         protected static Logger eventlogger;\r
175         /** This logger is used to log internal events (errors, etc.) */\r
176         protected static Logger intlogger;\r
177         /** Authorizer - interface to the Policy Engine */\r
178         protected static Authorizer authz;\r
179         /** The Synchronizer used to sync active DB to standby one */\r
180         protected static SynchronizerTask synctask = null;\r
181     \r
182         //Data Router Subscriber HTTPS Relaxation feature USERSTORYID:US674047.\r
183         private InetAddress thishost;\r
184         private InetAddress loopback;\r
185     private static Boolean mailSendFlag = false;\r
186 \r
187         public static final String MAILCONFIG_FILE = "mail.properties";\r
188         private static Properties mailprops;\r
189         /**\r
190          * Initialize data common to all the provisioning server servlets.\r
191          */\r
192         protected BaseServlet() {\r
193                 if (eventlogger == null)\r
194                         eventlogger = Logger.getLogger("com.att.research.datarouter.provisioning.events");\r
195                 if (intlogger == null)\r
196                         intlogger   = Logger.getLogger("com.att.research.datarouter.provisioning.internal");\r
197                 if (authz == null)\r
198                         authz = new ProvAuthorizer(this);\r
199                 if (startmsg_flag) {\r
200                         startmsg_flag = false;\r
201                         provisioningParametersChanged();\r
202                 }\r
203                 if (synctask == null) {\r
204                         synctask = SynchronizerTask.getSynchronizer();\r
205                 }\r
206                 String name = this.getClass().getName();\r
207                 intlogger.info("PROV0002 Servlet "+name+" started.");\r
208         }\r
209         @Override\r
210         public void init(ServletConfig config) throws ServletException {\r
211                 super.init(config);\r
212                 try {\r
213                         thishost = InetAddress.getLocalHost();\r
214                         loopback = InetAddress.getLoopbackAddress();\r
215                         checkHttpsRelaxation(); //Data Router Subscriber HTTPS Relaxation feature USERSTORYID:US674047.\r
216                 } catch (UnknownHostException e) {\r
217                         // ignore\r
218                 }\r
219         }\r
220         protected int getIdFromPath(HttpServletRequest req) {\r
221                 String path = req.getPathInfo();\r
222                 if (path == null || path.length() < 2)\r
223                         return -1;\r
224                 try {\r
225                         return Integer.parseInt(path.substring(1));\r
226                 } catch (NumberFormatException e) {\r
227                         return -1;\r
228                 }\r
229         }\r
230         /**\r
231          * Read the request's input stream and return a JSONObject from it\r
232          * @param req the HTTP request\r
233          * @return the JSONObject, or null if the stream cannot be parsed\r
234          */\r
235         protected JSONObject getJSONfromInput(HttpServletRequest req) {\r
236                 JSONObject jo = null;\r
237                 try {\r
238                         jo = new JSONObject(new JSONTokener(req.getInputStream()));\r
239                         if (intlogger.isDebugEnabled())\r
240                                 intlogger.debug("JSON: "+jo.toString());\r
241                 } catch (Exception e) {\r
242                         intlogger.info("Error reading JSON: "+e);\r
243                 }\r
244                 return jo;\r
245         }\r
246         /**\r
247          * Check if the remote host is authorized to perform provisioning.\r
248          * Is the request secure?\r
249          * Is it coming from an authorized IP address or network (configured via PROV_AUTH_ADDRESSES)?\r
250          * Does it have a valid client certificate (configured via PROV_AUTH_SUBJECTS)?\r
251          * @param request the request\r
252          * @return an error string, or null if all is OK\r
253          */\r
254         protected String isAuthorizedForProvisioning(HttpServletRequest request) {\r
255                 // Is the request https?\r
256                 if (require_secure && !request.isSecure()) {\r
257                         return "Request must be made over an HTTPS connection.";\r
258                 }\r
259 \r
260                 // Is remote IP authorized?\r
261                 String remote = request.getRemoteAddr();\r
262                 try {\r
263                         boolean found = false;\r
264                         InetAddress ip = InetAddress.getByName(remote);\r
265                         for (String addrnet : authorizedAddressesAndNetworks) {\r
266                                 found |= addressMatchesNetwork(ip, addrnet);\r
267                         }\r
268                         if (!found) {\r
269                                 return "Unauthorized address: "+remote;\r
270                         }\r
271                 } catch (UnknownHostException e) {\r
272                         return "Unauthorized address: "+remote;\r
273                 }\r
274 \r
275                 // Does remote have a valid certificate?\r
276                 if (require_cert) {\r
277                         X509Certificate certs[] = (X509Certificate[]) request.getAttribute(CERT_ATTRIBUTE);\r
278                         if (certs == null || certs.length == 0) {\r
279                                 return "Client certificate is missing.";\r
280                         }\r
281                         // cert[0] is the client cert\r
282                         // see http://www.proto.research.att.com/java/java7/api/javax/net/ssl/SSLSession.html#getPeerCertificates()\r
283                         String name = certs[0].getSubjectX500Principal().getName();\r
284                         if (!authorizedNames.contains(name)) {\r
285                                 return "No authorized certificate found.";\r
286                         }\r
287                 }\r
288 \r
289                 // No problems!\r
290                 return null;\r
291         }\r
292         /**\r
293          * Check if the remote IP address is authorized to see the /internal URL tree.\r
294          * @param request the HTTP request\r
295          * @return true iff authorized\r
296          */\r
297         protected boolean isAuthorizedForInternal(HttpServletRequest request) {\r
298                 try {\r
299                         InetAddress ip = InetAddress.getByName(request.getRemoteAddr());\r
300                         for (InetAddress node : getNodeAddresses()) {\r
301                                 if (node != null && ip.equals(node))\r
302                                         return true;\r
303                         }\r
304                         for (InetAddress pod : getPodAddresses()) {\r
305                                 if (pod != null && ip.equals(pod))\r
306                                         return true;\r
307                         }\r
308                         if (thishost != null && ip.equals(thishost))\r
309                                 return true;\r
310                         if (loopback != null && ip.equals(loopback))\r
311                                 return true;\r
312                         // Also allow the "special subnet" access\r
313                         if (addressMatchesNetwork(ip, special_subnet_secondary))\r
314                                 return true;\r
315                         if (addressMatchesNetwork(ip, special_subnet))\r
316                                 return true;\r
317                 } catch (UnknownHostException e) {\r
318                         // ignore\r
319                 }\r
320                 return false;\r
321         }\r
322         /**\r
323          * Check if an IP address matches a network address.\r
324          * @param ip the IP address\r
325          * @param s the network address; a bare IP address may be matched also\r
326          * @return true if they intersect\r
327          */\r
328         protected static boolean addressMatchesNetwork(InetAddress ip, String s) {\r
329                 int mlen = -1;\r
330                 int n = s.indexOf("/");\r
331                 if (n >= 0) {\r
332                         mlen = Integer.parseInt(s.substring(n+1));\r
333                         s = s.substring(0, n);\r
334                 }\r
335                 try {\r
336                         InetAddress i2 = InetAddress.getByName(s);\r
337                         byte[] b1 = ip.getAddress();\r
338                         byte[] b2 = i2.getAddress();\r
339                         if (b1.length != b2.length)\r
340                                 return false;\r
341                         if (mlen > 0) {\r
342                                 byte[] masks = {\r
343                                         (byte)0x00, (byte)0x80, (byte)0xC0, (byte)0xE0,\r
344                                         (byte)0xF0, (byte)0xF8, (byte)0xFC, (byte)0xFE\r
345                                 };\r
346                                 byte mask = masks[mlen%8];\r
347                                 for (n = mlen/8; n < b1.length; n++) {\r
348                                         b1[n] &= mask;\r
349                                         b2[n] &= mask;\r
350                                         mask = 0;\r
351                                 }\r
352                         }\r
353                         for (n = 0; n < b1.length; n++)\r
354                                 if (b1[n] != b2[n])\r
355                                         return false;\r
356                 } catch (UnknownHostException e) {\r
357                         return false;\r
358                 }\r
359                 return true;\r
360         }\r
361         /**\r
362          * Something has changed in the provisioning data.\r
363          * Start the timers that will cause the pre-packaged JSON string to be regenerated,\r
364          * and cause nodes and the other provisioning server to be notified.\r
365          */\r
366         public static void provisioningDataChanged() {\r
367                 long now = System.currentTimeMillis();\r
368                 Poker p = Poker.getPoker();\r
369                 p.setTimers(now + (poke_timer1 * 1000L), now + (poke_timer2 * 1000L));\r
370         }\r
371         /**\r
372          * Something in the parameters has changed, reload all parameters from the DB.\r
373          */\r
374         public static void provisioningParametersChanged() {\r
375                 Map<String,String> map         = Parameters.getParameters();\r
376                 require_secure   = getBoolean(map, Parameters.PROV_REQUIRE_SECURE);\r
377                 require_cert     = getBoolean(map, Parameters.PROV_REQUIRE_CERT);\r
378                 authorizedAddressesAndNetworks = getSet(map, Parameters.PROV_AUTH_ADDRESSES);\r
379                 authorizedNames  = getSet    (map, Parameters.PROV_AUTH_SUBJECTS);\r
380                 nodes            = getSet    (map, Parameters.NODES).toArray(new String[0]);\r
381                 max_feeds        = getInt    (map, Parameters.PROV_MAXFEED_COUNT, DEFAULT_MAX_FEEDS);\r
382                 max_subs         = getInt    (map, Parameters.PROV_MAXSUB_COUNT, DEFAULT_MAX_SUBS);\r
383                 poke_timer1      = getInt    (map, Parameters.PROV_POKETIMER1, DEFAULT_POKETIMER1);\r
384                 poke_timer2      = getInt    (map, Parameters.PROV_POKETIMER2, DEFAULT_POKETIMER2);\r
385                 prov_domain      = getString (map, Parameters.PROV_DOMAIN, DEFAULT_DOMAIN);\r
386                 prov_name        = getString (map, Parameters.PROV_NAME, DEFAULT_PROVSRVR_NAME);\r
387                 active_prov_name = getString (map, Parameters.PROV_ACTIVE_NAME, prov_name);\r
388                 special_subnet   = getString (map, Parameters.PROV_SPECIAL_SUBNET, RESEARCH_SUBNET);\r
389                 static_routing_nodes = getString (map, Parameters.STATIC_ROUTING_NODES, ""); //Adding new param for static Routing - Rally:US664862-1610\r
390                 initial_active_pod  = getString (map, Parameters.ACTIVE_POD, "");\r
391                 initial_standby_pod = getString (map, Parameters.STANDBY_POD, "");\r
392                 static_routing_nodes = getString (map, Parameters.STATIC_ROUTING_NODES, ""); //Adding new param for static Routing - Rally:US664862-1610\r
393                 active_feeds     = Feed.countActiveFeeds();\r
394                 active_subs      = Subscription.countActiveSubscriptions();\r
395                 try {\r
396                         this_pod = InetAddress.getLocalHost().getHostName();\r
397                 } catch (UnknownHostException e) {\r
398                         this_pod = "";\r
399                         intlogger.warn("PROV0014 Cannot determine the name of this provisioning server.");\r
400                 }\r
401 \r
402                 // Normalize the nodes, and fill in nodeAddresses\r
403                 InetAddress[] na = new InetAddress[nodes.length];\r
404                 for (int i = 0; i < nodes.length; i++) {\r
405                         if (nodes[i].indexOf('.') < 0)\r
406                                 nodes[i] += "." + prov_domain;\r
407                         try {\r
408                                 na[i] = InetAddress.getByName(nodes[i]);\r
409                                 intlogger.debug("PROV0003 DNS lookup: "+nodes[i]+" => "+na[i].toString());\r
410                         } catch (UnknownHostException e) {\r
411                                 na[i] = null;\r
412                                 intlogger.warn("PROV0004 Cannot lookup "+nodes[i]+": "+e);\r
413                         }\r
414                 }\r
415 \r
416                 //Reset Nodes arr after - removing static routing Nodes, Rally Userstory - US664862 .   \r
417                 List<String> filterNodes = new ArrayList<>();           \r
418                 for (int i = 0; i < nodes.length; i++) {                \r
419                         if(!static_routing_nodes.contains(nodes[i])){           \r
420                                 filterNodes.add(nodes[i]);              \r
421                         }               \r
422                 }               \r
423                 String [] filteredNodes = filterNodes.toArray(new String[filterNodes.size()]);                          \r
424                 nodes = filteredNodes;\r
425 \r
426                 nodeAddresses = na;\r
427                 NodeClass.setNodes(nodes);              // update NODES table\r
428 \r
429                 // Normalize the PODs, and fill in podAddresses\r
430                 String[] pods = getPods();\r
431                 na = new InetAddress[pods.length];\r
432                 for (int i = 0; i < pods.length; i++) {\r
433                         if (pods[i].indexOf('.') < 0)\r
434                                 pods[i] += "." + prov_domain;\r
435                         try {\r
436                                 na[i] = InetAddress.getByName(pods[i]);\r
437                                 intlogger.debug("PROV0003 DNS lookup: "+pods[i]+" => "+na[i].toString());\r
438                         } catch (UnknownHostException e) {\r
439                                 na[i] = null;\r
440                                 intlogger.warn("PROV0004 Cannot lookup "+pods[i]+": "+e);\r
441                         }\r
442                 }\r
443                 podAddresses = na;\r
444 \r
445                 // Update ThrottleFilter\r
446                 ThrottleFilter.configure();\r
447 \r
448                 // Check if we are active or standby POD\r
449                 if (!isInitialActivePOD() && !isInitialStandbyPOD())\r
450                         intlogger.warn("PROV0015 This machine is neither the active nor the standby POD.");\r
451         }\r
452 \r
453 \r
454         /**Data Router Subscriber HTTPS Relaxation feature USERSTORYID:US674047.\r
455          * Load mail properties.\r
456          * @author vs215k\r
457          *  \r
458         **/\r
459         private void loadMailProperties() {\r
460                 if (mailprops == null) {\r
461                         mailprops = new Properties();\r
462                         InputStream inStream = getClass().getClassLoader().getResourceAsStream(MAILCONFIG_FILE);\r
463                         try {\r
464                                 mailprops.load(inStream);\r
465                         } catch (IOException e) {\r
466                                 intlogger.fatal("PROV9003 Opening properties: "+e.getMessage());\r
467                                 e.printStackTrace();\r
468                                 System.exit(1);\r
469                         }\r
470                         finally {\r
471                                 try {\r
472                                         inStream.close();\r
473                                 } \r
474                                 catch (IOException e) {\r
475                                 }\r
476                         }\r
477                 }\r
478         }\r
479         \r
480         /**Data Router Subscriber HTTPS Relaxation feature USERSTORYID:US674047.\r
481          * Check if HTTPS Relexaction is enabled \r
482          * @author vs215k\r
483          *  \r
484         **/\r
485         private void checkHttpsRelaxation() {\r
486                 if(mailSendFlag == false) {\r
487                         Properties p = (new DB()).getProperties();\r
488                         intlogger.info("HTTPS relaxatio: "+p.get("com.att.research.datarouter.provserver.https.relaxation"));\r
489                         \r
490                         if(p.get("com.att.research.datarouter.provserver.https.relaxation").equals("true")) {\r
491                             try {\r
492                                   notifyPSTeam(p.get("com.att.research.datarouter.provserver.https.relax.notify").toString());\r
493                             } \r
494                                 catch (Exception e) {\r
495                                     e.printStackTrace();\r
496                             }\r
497                          }\r
498                         mailSendFlag = true;\r
499                 }\r
500         }\r
501         \r
502         /**Data Router Subscriber HTTPS Relaxation feature USERSTORYID:US674047.\r
503          * @author vs215k\r
504          * @param email - list of email ids to notify if HTTP relexcation is enabled. \r
505         **/\r
506         private void notifyPSTeam(String email) throws Exception {\r
507                 loadMailProperties(); //Load HTTPS Relex mail properties.\r
508                 String[] emails = email.split(Pattern.quote("|"));\r
509         \r
510         Properties mailproperties = new Properties();\r
511                 mailproperties.put("mail.smtp.host", mailprops.get("com.att.dmaap.datarouter.mail.server"));\r
512                 mailproperties.put("mail.transport.protocol", mailprops.get("com.att.dmaap.datarouter.mail.protocol"));\r
513                 \r
514         Session session = Session.getDefaultInstance(mailproperties, null);\r
515         Multipart mp = new MimeMultipart();\r
516         MimeBodyPart htmlPart = new MimeBodyPart();\r
517         \r
518         try {\r
519                 \r
520           Message msg = new MimeMessage(session);\r
521           msg.setFrom(new InternetAddress(mailprops.get("com.att.dmaap.datarouter.mail.from").toString()));\r
522           \r
523           InternetAddress[] addressTo = new InternetAddress[emails.length];\r
524           for ( int x =0 ; x < emails.length; x++) {\r
525                addressTo[x] = new InternetAddress(emails[x]);\r
526           }\r
527           \r
528           msg.addRecipients(Message.RecipientType.TO, addressTo);\r
529           msg.setSubject(mailprops.get("com.att.dmaap.datarouter.mail.subject").toString());\r
530           htmlPart.setContent(mailprops.get("com.att.dmaap.datarouter.mail.body").toString().replace("[SERVER]", InetAddress.getLocalHost().getHostName()), "text/html");\r
531           mp.addBodyPart(htmlPart);\r
532           msg.setContent(mp);\r
533           \r
534           System.out.println(mailprops.get("com.att.dmaap.datarouter.mail.body").toString().replace("[SERVER]", InetAddress.getLocalHost().getHostName()));\r
535         \r
536           Transport.send(msg);\r
537           intlogger.info("HTTPS relaxation mail is sent to - : "+email);\r
538           \r
539         } catch (AddressException e) {\r
540                   intlogger.error("Invalid email address, unable to send https relaxation mail to - : "+email);\r
541         } catch (MessagingException e) {\r
542                 intlogger.error("Invalid email address, unable to send https relaxation mail to - : "+email);\r
543         } \r
544         }\r
545 \r
546 \r
547         /**\r
548          * Get an array of all node names in the DR network.\r
549          * @return an array of Strings\r
550          */\r
551         public static String[] getNodes() {\r
552                 return nodes;\r
553         }\r
554         /**\r
555          * Get an array of all node InetAddresses in the DR network.\r
556          * @return an array of InetAddresses\r
557          */\r
558         public static InetAddress[] getNodeAddresses() {\r
559                 return nodeAddresses;\r
560         }\r
561         /**\r
562          * Get an array of all POD names in the DR network.\r
563          * @return an array of Strings\r
564          */\r
565         public static String[] getPods() {\r
566                 return new String[] { initial_active_pod, initial_standby_pod };\r
567         }\r
568         /**\r
569          * Get an array of all POD InetAddresses in the DR network.\r
570          * @return an array of InetAddresses\r
571          */\r
572         public static InetAddress[] getPodAddresses() {\r
573                 return podAddresses;\r
574         }\r
575         /**\r
576          * Gets the FQDN of the initially ACTIVE provisioning server (POD).\r
577          * Note: this used to be called isActivePOD(), however, that is a misnomer, as the active status\r
578          * could shift to the standby POD without these parameters changing.  Hence, the function names\r
579          * have been changed to more accurately reflect their purpose.\r
580          * @return the FQDN\r
581          */\r
582         public static boolean isInitialActivePOD() {\r
583                 return this_pod.equals(initial_active_pod);\r
584         }\r
585         /**\r
586          * Gets the FQDN of the initially STANDBY provisioning server (POD).\r
587          * Note: this used to be called isStandbyPOD(), however, that is a misnomer, as the standby status\r
588          * could shift to the active POD without these parameters changing.  Hence, the function names\r
589          * have been changed to more accurately reflect their purpose.\r
590          * @return the FQDN\r
591          */\r
592         public static boolean isInitialStandbyPOD() {\r
593                 return this_pod.equals(initial_standby_pod);\r
594         }\r
595         /**\r
596          * INSERT an {@link Insertable} bean into the database.\r
597          * @param bean the bean representing a row to insert\r
598          * @return true if the INSERT was successful\r
599          */\r
600         protected boolean doInsert(Insertable bean) {\r
601                 boolean rv = false;\r
602                 DB db = new DB();\r
603                 Connection conn = null;\r
604                 try {\r
605                         conn = db.getConnection();\r
606                         rv = bean.doInsert(conn);\r
607                 } catch (SQLException e) {\r
608                         rv = false;\r
609                         intlogger.warn("PROV0005 doInsert: "+e.getMessage());\r
610                         e.printStackTrace();\r
611                 } finally {\r
612                         if (conn != null)\r
613                                 db.release(conn);\r
614                 }\r
615                 return rv;\r
616         }\r
617         /**\r
618          * UPDATE an {@link Updateable} bean in the database.\r
619          * @param bean the bean representing a row to update\r
620          * @return true if the UPDATE was successful\r
621          */\r
622         protected boolean doUpdate(Updateable bean) {\r
623                 boolean rv = false;\r
624                 DB db = new DB();\r
625                 Connection conn = null;\r
626                 try {\r
627                         conn = db.getConnection();\r
628                         rv = bean.doUpdate(conn);\r
629                 } catch (SQLException e) {\r
630                         rv = false;\r
631                         intlogger.warn("PROV0006 doUpdate: "+e.getMessage());\r
632                         e.printStackTrace();\r
633                 } finally {\r
634                         if (conn != null)\r
635                                 db.release(conn);\r
636                 }\r
637                 return rv;\r
638         }\r
639         /**\r
640          * DELETE an {@link Deleteable} bean from the database.\r
641          * @param bean the bean representing a row to delete\r
642          * @return true if the DELETE was successful\r
643          */\r
644         protected boolean doDelete(Deleteable bean) {\r
645                 boolean rv = false;\r
646                 DB db = new DB();\r
647                 Connection conn = null;\r
648                 try {\r
649                         conn = db.getConnection();\r
650                         rv = bean.doDelete(conn);\r
651                 } catch (SQLException e) {\r
652                         rv = false;\r
653                         intlogger.warn("PROV0007 doDelete: "+e.getMessage());\r
654                         e.printStackTrace();\r
655                 } finally {\r
656                         if (conn != null)\r
657                                 db.release(conn);\r
658                 }\r
659                 return rv;\r
660         }\r
661         private static boolean getBoolean(Map<String,String> map, String name) {\r
662                 String s = map.get(name);\r
663                 return (s != null) && s.equalsIgnoreCase("true");\r
664         }\r
665         private static String getString(Map<String,String> map, String name, String dflt) {\r
666                 String s = map.get(name);\r
667                 return (s != null) ? s : dflt;\r
668         }\r
669         private static int getInt(Map<String,String> map, String name, int dflt) {\r
670                 try {\r
671                         String s = map.get(name);\r
672                         return Integer.parseInt(s);\r
673                 } catch (NumberFormatException e) {\r
674                         return dflt;\r
675                 }\r
676         }\r
677         private static Set<String> getSet(Map<String,String> map, String name) {\r
678                 Set<String> set = new HashSet<String>();\r
679                 String s = map.get(name);\r
680                 if (s != null) {\r
681                         String[] pp = s.split("\\|");\r
682                         if (pp != null) {\r
683                                 for (String t : pp) {\r
684                                         String t2 = t.trim();\r
685                                         if (t2.length() > 0)\r
686                                                 set.add(t2);\r
687                                 }\r
688                         }\r
689                 }\r
690                 return set;\r
691         }\r
692 \r
693         /**\r
694          * A class used to encapsulate a Content-type header, separating out the "version" attribute\r
695          * (which defaults to "1.0" if missing).\r
696          */\r
697         public class ContentHeader {\r
698                 private String type = "";\r
699                 private Map<String, String> map = new HashMap<String, String>();\r
700                 public ContentHeader() {\r
701                         this("", "1.0");\r
702                 }\r
703                 public ContentHeader(String t, String v) {\r
704                         type = t.trim();\r
705                         map.put("version", v);\r
706                 }\r
707                 public String getType() {\r
708                         return type;\r
709                 }\r
710                 public String getAttribute(String key) {\r
711                         String s = map.get(key);\r
712                         if (s == null)\r
713                                 s = "";\r
714                         return s;\r
715                 }\r
716         }\r
717 \r
718         /**\r
719          * Get the ContentHeader from an HTTP request.\r
720          * @param req the request\r
721          * @return the header, encapsulated in a ContentHeader object\r
722          */\r
723         public ContentHeader getContentHeader(HttpServletRequest req) {\r
724                 ContentHeader ch = new ContentHeader();\r
725                 String s = req.getHeader("Content-Type");\r
726                 if (s != null) {\r
727                         String[] pp = s.split(";");\r
728                         ch.type = pp[0].trim();\r
729                         for (int i = 1; i < pp.length; i++) {\r
730                                 int ix = pp[i].indexOf('=');\r
731                                 if (ix > 0) {\r
732                                         String k = pp[i].substring(0, ix).trim();\r
733                                         String v = pp[i].substring(ix+1).trim();\r
734                                         ch.map.put(k,  v);\r
735                                 } else {\r
736                                         ch.map.put(pp[i].trim(), "");\r
737                                 }\r
738                         }\r
739                 }\r
740                 return ch;\r
741         }\r
742         // Methods for the Policy Engine classes - ProvDataProvider interface\r
743         @Override\r
744         public String getFeedOwner(String feedId) {\r
745                 try {\r
746                         int n = Integer.parseInt(feedId);\r
747                         Feed f = Feed.getFeedById(n);\r
748                         if (f != null)\r
749                                 return f.getPublisher();\r
750                 } catch (NumberFormatException e) {\r
751                         // ignore\r
752                 }\r
753                 return null;\r
754         }\r
755         @Override\r
756         public String getFeedClassification(String feedId) {\r
757                 try {\r
758                         int n = Integer.parseInt(feedId);\r
759                         Feed f = Feed.getFeedById(n);\r
760                         if (f != null)\r
761                                 return f.getAuthorization().getClassification();\r
762                 } catch (NumberFormatException e) {\r
763                         // ignore\r
764                 }\r
765                 return null;\r
766         }\r
767         @Override\r
768         public String getSubscriptionOwner(String subId) {\r
769                 try {\r
770                         int n = Integer.parseInt(subId);\r
771                         Subscription s = Subscription.getSubscriptionById(n);\r
772                         if (s != null)\r
773                                 return s.getSubscriber();\r
774                 } catch (NumberFormatException e) {\r
775                         // ignore\r
776                 }\r
777                 return null;\r
778         }\r
779 \r
780         /*\r
781          * @Method - isUserMemberOfGroup - Rally:US708115 \r
782          * @Params - group object and user to check if exists in given group\r
783          * @return - boolean value /true/false\r
784          */\r
785         private boolean isUserMemberOfGroup(Group group, String user) {\r
786                          \r
787                 String groupdetails = group.getMembers().replace("]", "").replace("[", "");\r
788             String s[] =        groupdetails.split("},");\r
789                 \r
790                 for(int i=0; i < s.length; i++) {\r
791                                 JSONObject jsonObj = null;\r
792                                 try {\r
793                             jsonObj = new JSONObject(s[i]+"}");\r
794                             if(jsonObj.get("id").equals(user))\r
795                                 return true;\r
796                         } catch (JSONException e) {\r
797                             e.printStackTrace();\r
798                         }\r
799                 }\r
800                 return false;\r
801                 \r
802         }\r
803         \r
804         /*\r
805          * @Method - getGroupByFeedGroupId- Rally:US708115 \r
806          * @Params - User to check in group and feedid which is assigned the group.\r
807          * @return - string value grupid/null\r
808          */\r
809         @Override\r
810         public String getGroupByFeedGroupId(String owner, String feedId) {\r
811                 try {\r
812                         int n = Integer.parseInt(feedId);\r
813                         Feed f = Feed.getFeedById(n);\r
814                         if (f != null) {\r
815                                 int groupid = f.getGroupid();\r
816                                 if(groupid > 0) {\r
817                                         Group group = Group.getGroupById(groupid);\r
818                                         if(isUserMemberOfGroup(group, owner)) {\r
819                                                 return group.getAuthid();\r
820                                         }\r
821                                 }\r
822                         }\r
823                 } catch (NumberFormatException e) {\r
824                         // ignore\r
825                 }\r
826                 return null;\r
827         }\r
828         \r
829         /*\r
830          * @Method - getGroupBySubGroupId - Rally:US708115  \r
831          * @Params - User to check in group and subid which is assigned the group.\r
832          * @return - string value grupid/null\r
833          */\r
834         @Override\r
835         public String getGroupBySubGroupId(String owner, String subId) {\r
836                 try {\r
837                         int n = Integer.parseInt(subId);\r
838                         Subscription s = Subscription.getSubscriptionById(n);\r
839                         if (s != null) {\r
840                                 int groupid = s.getGroupid();\r
841                                 if(groupid > 0) {\r
842                                         Group group = Group.getGroupById(groupid);\r
843                                         if(isUserMemberOfGroup(group, owner)) {\r
844                                                 return group.getAuthid();\r
845                                         }\r
846                                 }\r
847                         }\r
848                 } catch (NumberFormatException e) {\r
849                         // ignore\r
850                 }\r
851                 return null;\r
852         }\r
853         \r
854         /*\r
855          * @Method - setIpAndFqdnForEelf - Rally:US664892  \r
856          * @Params - method, prints method name in EELF log.\r
857          */     \r
858         protected void setIpAndFqdnForEelf(String method) {\r
859                 MDC.clear();\r
860         MDC.put(MDC_SERVICE_NAME, method);\r
861         try {\r
862             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());\r
863             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());\r
864         } catch (Exception e) {\r
865             e.printStackTrace();\r
866         }\r
867 \r
868         }\r
869 }\r