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