Removing passwordencryption key
[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_KEY_REQUEST_ID;
28 import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
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 com.att.eelf.configuration.EELFLogger;
33 import com.att.eelf.configuration.EELFManager;
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.ArrayList;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Properties;
45 import java.util.Set;
46 import java.util.UUID;
47 import javax.servlet.ServletConfig;
48 import javax.servlet.ServletException;
49 import javax.servlet.http.HttpServlet;
50 import javax.servlet.http.HttpServletRequest;
51 import org.apache.commons.codec.digest.DigestUtils;
52 import org.apache.commons.lang3.StringUtils;
53 import org.jetbrains.annotations.Nullable;
54 import org.json.JSONArray;
55 import org.json.JSONException;
56 import org.json.JSONObject;
57 import org.json.JSONTokener;
58 import org.onap.dmaap.datarouter.authz.Authorizer;
59 import org.onap.dmaap.datarouter.authz.impl.ProvAuthorizer;
60 import org.onap.dmaap.datarouter.authz.impl.ProvDataProvider;
61 import org.onap.dmaap.datarouter.provisioning.beans.Deleteable;
62 import org.onap.dmaap.datarouter.provisioning.beans.Feed;
63 import org.onap.dmaap.datarouter.provisioning.beans.Group;
64 import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
65 import org.onap.dmaap.datarouter.provisioning.beans.NodeClass;
66 import org.onap.dmaap.datarouter.provisioning.beans.Parameters;
67 import org.onap.dmaap.datarouter.provisioning.beans.Subscription;
68 import org.onap.dmaap.datarouter.provisioning.beans.Updateable;
69 import org.onap.dmaap.datarouter.provisioning.utils.Poker;
70 import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;
71 import org.onap.dmaap.datarouter.provisioning.utils.SynchronizerTask;
72 import org.onap.dmaap.datarouter.provisioning.utils.ThrottleFilter;
73 import org.slf4j.MDC;
74
75
76 /**
77  * This is the base class for all Servlets in the provisioning code. It provides standard constants and some common
78  * methods.
79  *
80  * @author Robert Eby
81  * @version $Id: BaseServlet.java,v 1.16 2014/03/12 19:45:40 eby Exp $
82  */
83 @SuppressWarnings("serial")
84 public class BaseServlet extends HttpServlet implements ProvDataProvider {
85
86     public static final String BEHALF_HEADER = "X-DMAAP-DR-ON-BEHALF-OF";
87
88     public static final String EXCLUDE_AAF_HEADER = "X-EXCLUDE-AAF";
89
90     private static final String AAF_CADI_FEED_TYPE = "org.onap.dmaap.datarouter.provserver.aaf.feed.type";
91     private static final String AAF_CADI_SUB_TYPE = "org.onap.dmaap.datarouter.provserver.aaf.sub.type";
92     private static final String AAF_INSTANCE = "org.onap.dmaap.datarouter.provserver.aaf.instance";
93     private static final String AAF_CADI_FEED = "org.onap.dmaap-dr.feed";
94     private static final String AAF_CADI_SUB = "org.onap.dmaap-dr.sub";
95
96     static final String CREATE_PERMISSION = "create";
97     static final String EDIT_PERMISSION = "edit";
98     static final String DELETE_PERMISSION = "delete";
99     private static final String PUBLISH_PERMISSION = "publish";
100     private static final String SUSPEND_PERMISSION = "suspend";
101     private static final String RESTORE_PERMISSION = "restore";
102     private static final String SUBSCRIBE_PERMISSION = "subscribe";
103     static final String APPROVE_SUB_PERMISSION = "approveSub";
104
105     static final String FEED_BASECONTENT_TYPE = "application/vnd.dmaap-dr.feed";
106     public static final String FEED_CONTENT_TYPE = "application/vnd.dmaap-dr.feed; version=2.0";
107     public static final String FEEDFULL_CONTENT_TYPE = "application/vnd.dmaap-dr.feed-full; version=2.0";
108     public static final String FEEDLIST_CONTENT_TYPE = "application/vnd.dmaap-dr.feed-list; version=1.0";
109     static final String SUB_BASECONTENT_TYPE = "application/vnd.dmaap-dr.subscription";
110     public static final String SUB_CONTENT_TYPE = "application/vnd.dmaap-dr.subscription; version=2.0";
111     public static final String SUBFULL_CONTENT_TYPE = "application/vnd.dmaap-dr.subscription-full; version=2.0";
112     static final String SUBLIST_CONTENT_TYPE = "application/vnd.dmaap-dr.subscription-list; version=1.0";
113
114     //Adding groups functionality, ...1610
115     static final String GROUP_BASECONTENT_TYPE = "application/vnd.dmaap-dr.group";
116     static final String GROUP_CONTENT_TYPE = "application/vnd.dmaap-dr.group; version=2.0";
117     static final String GROUPFULL_CONTENT_TYPE = "application/vnd.dmaap-dr.group-full; version=2.0";
118     public static final String GROUPLIST_CONTENT_TYPE = "application/vnd.dmaap-dr.fegrouped-list; version=1.0";
119
120     public static final String LOGLIST_CONTENT_TYPE = "application/vnd.dmaap-dr.log-list; version=1.0";
121     public static final String PROVFULL_CONTENT_TYPE1 = "application/vnd.dmaap-dr.provfeed-full; version=1.0";
122     public static final String PROVFULL_CONTENT_TYPE2 = "application/vnd.dmaap-dr.provfeed-full; version=2.0";
123     public static final String CERT_ATTRIBUTE = "javax.servlet.request.X509Certificate";
124
125     static final String DB_PROBLEM_MSG = "There has been a problem with the DB.  It is suggested you "
126         + "try the operation again.";
127
128     private static final int DEFAULT_MAX_FEEDS = 10000;
129     private static final int DEFAULT_MAX_SUBS = 100000;
130     private static final int DEFAULT_POKETIMER1 = 5;
131     private static final int DEFAULT_POKETIMER2 = 30;
132     private static final String DEFAULT_PROVSRVR_NAME = "dmaap-dr-prov";
133
134     //Common Errors
135     static final String MISSING_ON_BEHALF = "Missing X-DMAAP-DR-ON-BEHALF-OF header.";
136     static final String MISSING_FEED = "Missing or bad feed number.";
137     static final String POLICY_ENGINE = "Policy Engine disallows access.";
138     static final String UNAUTHORIZED = "Unauthorized.";
139     static final String BAD_SUB = "Missing or bad subscription number.";
140     static final String BAD_JSON = "Badly formed JSON";
141     static final String BAD_URL = "Bad URL.";
142
143     public static final String API = "/api/";
144     static final String LOGS = "/logs/";
145     public static final String TEXT_CT = "text/plain";
146     static final String INGRESS = "/ingress/";
147     static final String EGRESS = "/egress/";
148     static final String NETWORK = "/network/";
149     static final String GROUPID = "groupid";
150     public static final String FEEDID = "feedid";
151     static final String FEEDIDS = "feedids";
152     static final String SUBID = "subid";
153     static final String EVENT_TYPE = "eventType";
154     static final String OUTPUT_TYPE = "output_type";
155     static final String START_TIME = "start_time";
156     static final String END_TIME = "end_time";
157     static final String REASON_SQL = "reasonSQL";
158     static final String JSON_HASH_STRING = "password";
159
160     /**
161      * A boolean to trigger one time "provisioning changed" event on startup.
162      */
163     private static boolean startmsgFlag = true;
164     /**
165      * This POD should require SSL connections from clients; pulled from the DB (PROV_REQUIRE_SECURE).
166      */
167     private static boolean requireSecure = true;
168     /**
169      * This POD should require signed, recognized certificates from clients; pulled from the DB (PROV_REQUIRE_CERT).
170      */
171     private static boolean requireCert = true;
172     /**
173      * The set of authorized addresses and networks; pulled from the DB (PROV_AUTH_ADDRESSES).
174      */
175     private static Set<String> authorizedAddressesAndNetworks = new HashSet<>();
176     /**
177      * The set of authorized names; pulled from the DB (PROV_AUTH_SUBJECTS).
178      */
179     private static Set<String> authorizedNames = new HashSet<>();
180     /**
181      * The FQDN of the initially "active" provisioning server in this Data Router ecosystem.
182      */
183     private static String initialActivePod;
184     /**
185      * The FQDN of the initially "standby" provisioning server in this Data Router ecosystem.
186      */
187     private static String initialStandbyPod;
188     /**
189      * The FQDN of this provisioning server in this Data Router ecosystem.
190      */
191     private static String thisPod;
192     /**
193      * "Timer 1" - used to determine when to notify nodes of provisioning changes.
194      */
195     private static long pokeTimer1;
196     /**
197      * "Timer 2" - used to determine when to notify nodes of provisioning changes.
198      */
199     private static long pokeTimer2;
200     /**
201      * Array of nodes names and/or FQDNs.
202      */
203     private static String[] nodes = new String[0];
204     /**
205      * Array of node IP addresses.
206      */
207     private static InetAddress[] nodeAddresses = new InetAddress[0];
208     /**
209      * Array of POD IP addresses.
210      */
211     private static InetAddress[] podAddresses = new InetAddress[0];
212     /**
213      * The maximum number of feeds allowed; pulled from the DB (PROV_MAXFEED_COUNT).
214      */
215     static int maxFeeds = 0;
216     /**
217      * The maximum number of subscriptions allowed; pulled from the DB (PROV_MAXSUB_COUNT).
218      */
219     static int maxSubs = 0;
220     /**
221      * The current number of feeds in the system.
222      */
223     static int activeFeeds = 0;
224     /**
225      * The current number of subscriptions in the system.
226      */
227     static int activeSubs = 0;
228
229     /**
230      * The standard FQDN of the provisioning server in this Data Router ecosystem.
231      */
232     private static String provName = "feeds-drtr.web.att.com";
233
234     /**
235      * The standard FQDN of the ACTIVE_POD provisioning server in this Data Router ecosystem.
236      */
237     private static String activeProvName = "feeds-drtr.web.att.com";
238
239     /**
240      * This logger is used to log provisioning events.
241      */
242     protected static EELFLogger eventlogger;
243     /**
244      * This logger is used to log internal events (errors, etc.)
245      */
246     protected static EELFLogger intlogger;
247     /**
248      * Authorizer - interface to the Policy Engine.
249      */
250     protected static Authorizer authz;
251     /**
252      * The Synchronizer used to sync active DB to standby one.
253      */
254     private static SynchronizerTask synctask = null;
255
256     //Data Router Subscriber HTTPS Relaxation feature USERSTORYID:US674047.
257     private InetAddress thishost;
258     private InetAddress loopback;
259
260     //DMAAP-597 (Tech Dept) REST request source IP auth relaxation to accommodate OOM kubernetes deploy
261     private static String isAddressAuthEnabled = ProvRunner.getProvProperties()
262         .getProperty("org.onap.dmaap.datarouter.provserver.isaddressauthenabled", "false");
263
264     static String isCadiEnabled = ProvRunner.getProvProperties()
265         .getProperty("org.onap.dmaap.datarouter.provserver.cadi.enabled", "false");
266
267     /**
268      * Initialize data common to all the provisioning server servlets.
269      */
270     protected BaseServlet() {
271         setUpFields();
272         if (authz == null) {
273             authz = new ProvAuthorizer(this);
274         }
275         String name = this.getClass().getName();
276         intlogger.info("PROV0002 Servlet " + name + " started.");
277     }
278
279     private static void setUpFields() {
280         if (eventlogger == null) {
281             eventlogger = EELFManager.getInstance().getLogger("EventLog");
282         }
283         if (intlogger == null) {
284             intlogger = EELFManager.getInstance().getLogger("InternalLog");
285         }
286         if (startmsgFlag) {
287             startmsgFlag = false;
288             provisioningParametersChanged();
289         }
290         if (synctask == null) {
291             synctask = SynchronizerTask.getSynchronizer();
292         }
293     }
294
295     @Override
296     public void init(ServletConfig config) throws ServletException {
297         super.init(config);
298         try {
299             thishost = InetAddress.getLocalHost();
300             loopback = InetAddress.getLoopbackAddress();
301         } catch (UnknownHostException e) {
302             intlogger.info("BaseServlet.init: " + e.getMessage(), e);
303         }
304     }
305
306     /**
307      * Get ID from Path.
308      * @param req HTTPServletRequest
309      * @return int ID
310      */
311     public static int getIdFromPath(HttpServletRequest req) {
312         String path = req.getPathInfo();
313         if (path == null || path.length() < 2) {
314             return -1;
315         }
316         try {
317             return Integer.parseInt(path.substring(1));
318         } catch (NumberFormatException e) {
319             return -1;
320         }
321     }
322
323     /**
324      * Read the request's input stream and return a JSONObject from it.
325      *
326      * @param req the HTTP request
327      * @return the JSONObject, or null if the stream cannot be parsed
328      */
329     JSONObject getJSONfromInput(HttpServletRequest req) {
330         JSONObject jo = null;
331         try {
332             jo = new JSONObject(new JSONTokener(req.getInputStream()));
333             if (intlogger.isDebugEnabled()) {
334                 intlogger.debug("JSON: " + hashPasswords(new JSONObject(jo.toString())).toString());
335             }
336         } catch (Exception e) {
337             intlogger.info("Error reading JSON: " + e);
338         }
339         return jo;
340     }
341
342     public static JSONObject hashPasswords(JSONObject jo) {
343         if (!jo.isNull("authorization")) {
344             JSONArray endpointIds = jo.getJSONObject("authorization").getJSONArray("endpoint_ids");
345             for (int index = 0; index < endpointIds.length(); index++) {
346                 if ((!endpointIds.getJSONObject(index).isNull(JSON_HASH_STRING))) {
347                     String password = endpointIds.getJSONObject(index).get(JSON_HASH_STRING).toString();
348                     processPassword(endpointIds, index, password);
349                 }
350             }
351         }
352         if (!jo.isNull("delivery")) {
353             JSONObject deliveryObj = jo.getJSONObject("delivery");
354             String password = deliveryObj.get(JSON_HASH_STRING).toString();
355             processPassword(deliveryObj, password);
356         }
357         return jo;
358     }
359
360     private static void processPassword(JSONArray endpointIds, int index, String password) {
361         try {
362             endpointIds.getJSONObject(index).put(JSON_HASH_STRING, DigestUtils.sha256Hex(password));
363         } catch (JSONException e) {
364             intlogger.info("Error reading JSON while hashing: " + e);
365         }
366     }
367
368     private static void processPassword(JSONObject deliveryObj, String password) {
369         try {
370             deliveryObj.put(JSON_HASH_STRING, DigestUtils.sha256Hex(password));
371         } catch (JSONException e) {
372             intlogger.info("Error reading JSON while hashing: " + e);
373         }
374     }
375
376     /**
377      * Check if the remote host is authorized to perform provisioning. Is the request secure? Is it coming from an
378      * authorized IP address or network (configured via PROV_AUTH_ADDRESSES)? Does it have a valid client certificate
379      * (configured via PROV_AUTH_SUBJECTS)?
380      *
381      * @param request the request
382      * @return an error string, or null if all is OK
383      */
384     String isAuthorizedForProvisioning(HttpServletRequest request) {
385         if (!Boolean.parseBoolean(isAddressAuthEnabled)) {
386             return null;
387         }
388         // Is the request https?
389         if (requireSecure && !request.isSecure()) {
390             return "Request must be made over an HTTPS connection.";
391         }
392         String remoteHostCheck = checkRemoteHostAuthorization(request);
393         if (remoteHostCheck != null) {
394             return remoteHostCheck;
395         }
396         // Does remote have a valid certificate?
397         if (requireCert) {
398             X509Certificate[] certs = (X509Certificate[]) request.getAttribute(CERT_ATTRIBUTE);
399             if (certs == null || certs.length == 0) {
400                 return "Client certificate is missing.";
401             }
402             // cert[0] is the client cert
403             // see http://www.proto.research.att.com/java/java7/api/javax/net/ssl/SSLSession.html#getPeerCertificates()
404             String name = certs[0].getSubjectX500Principal().getName();
405             if (!authorizedNames.contains(name)) {
406                 return "No authorized certificate found.";
407             }
408         }
409         // No problems!
410         return null;
411     }
412
413     @Nullable
414     private String checkRemoteHostAuthorization(HttpServletRequest request) {
415         // Is remote IP authorized?
416         String remote = request.getRemoteAddr();
417         try {
418             boolean found = false;
419             InetAddress ip = InetAddress.getByName(remote);
420             for (String addrnet : authorizedAddressesAndNetworks) {
421                 found |= addressMatchesNetwork(ip, addrnet);
422             }
423             if (!found) {
424                 return "Unauthorized address: " + remote;
425             }
426         } catch (UnknownHostException e) {
427             intlogger.error("PROV0051 BaseServlet.isAuthorizedForProvisioning: " + e.getMessage(), e);
428             return "Unauthorized address: " + remote;
429         }
430         return null;
431     }
432
433     /**
434      * Check if the remote IP address is authorized to see the /internal URL tree.
435      *
436      * @param request the HTTP request
437      * @return true iff authorized
438      */
439     boolean isAuthorizedForInternal(HttpServletRequest request) {
440         try {
441             if (!Boolean.parseBoolean(isAddressAuthEnabled)) {
442                 return true;
443             }
444             InetAddress ip = InetAddress.getByName(request.getRemoteAddr());
445             for (InetAddress node : getNodeAddresses()) {
446                 if (ip.equals(node)) {
447                     return true;
448                 }
449             }
450             for (InetAddress pod : getPodAddresses()) {
451                 if (ip.equals(pod)) {
452                     return true;
453                 }
454             }
455             if (ip.equals(thishost)) {
456                 return true;
457             }
458             if (ip.equals(loopback)) {
459                 return true;
460             }
461         } catch (UnknownHostException e) {
462             intlogger.error("PROV0052 BaseServlet.isAuthorizedForInternal: " + e.getMessage(), e);
463         }
464         return false;
465     }
466
467     /**
468      * Check if an IP address matches a network address.
469      *
470      * @param ip the IP address
471      * @param str  the network address; a bare IP address may be matched also
472      * @return true if they intersect
473      */
474     private static boolean addressMatchesNetwork(InetAddress ip, String str) {
475         int mlen = -1;
476         int substr = str.indexOf('/');
477         if (substr >= 0) {
478             mlen = Integer.parseInt(str.substring(substr + 1));
479             str = str.substring(0, substr);
480         }
481         try {
482             InetAddress i2 = InetAddress.getByName(str);
483             byte[] b1 = ip.getAddress();
484             byte[] b2 = i2.getAddress();
485             if (b1.length != b2.length) {
486                 return false;
487             }
488             if (mlen > 0) {
489                 byte[] masks = {
490                     (byte) 0x00, (byte) 0x80, (byte) 0xC0, (byte) 0xE0,
491                     (byte) 0xF0, (byte) 0xF8, (byte) 0xFC, (byte) 0xFE
492                 };
493                 byte mask = masks[mlen % 8];
494                 for (substr = mlen / 8; substr < b1.length; substr++) {
495                     b1[substr] &= mask;
496                     b2[substr] &= mask;
497                     mask = 0;
498                 }
499             }
500             for (substr = 0; substr < b1.length; substr++) {
501                 if (b1[substr] != b2[substr]) {
502                     return false;
503                 }
504             }
505         } catch (UnknownHostException e) {
506             intlogger.error("PROV0053 BaseServlet.addressMatchesNetwork: " + e.getMessage(), e);
507             return false;
508         }
509         return true;
510     }
511
512     /**
513      * Something has changed in the provisioning data. Start the timers that will cause the pre-packaged JSON string to
514      * be regenerated, and cause nodes and the other provisioning server to be notified.
515      */
516     public static void provisioningDataChanged() {
517         long now = System.currentTimeMillis();
518         Poker pkr = Poker.getPoker();
519         pkr.setTimers(now + (pokeTimer1 * 1000L), now + (pokeTimer2 * 1000L));
520     }
521
522     /**
523      * Something in the parameters has changed, reload all parameters from the DB.
524      */
525     public static void provisioningParametersChanged() {
526         Map<String, String> map = Parameters.getParameters();
527         requireSecure = getBoolean(map, Parameters.PROV_REQUIRE_SECURE);
528         requireCert = getBoolean(map, Parameters.PROV_REQUIRE_CERT);
529         authorizedAddressesAndNetworks = getSet(map, Parameters.PROV_AUTH_ADDRESSES);
530         authorizedNames = getSet(map, Parameters.PROV_AUTH_SUBJECTS);
531         nodes = getSet(map, Parameters.NODES).toArray(new String[0]);
532         maxFeeds = getInt(map, Parameters.PROV_MAXFEED_COUNT, DEFAULT_MAX_FEEDS);
533         maxSubs = getInt(map, Parameters.PROV_MAXSUB_COUNT, DEFAULT_MAX_SUBS);
534         pokeTimer1 = getInt(map, Parameters.PROV_POKETIMER1, DEFAULT_POKETIMER1);
535         pokeTimer2 = getInt(map, Parameters.PROV_POKETIMER2, DEFAULT_POKETIMER2);
536
537         // The domain used to generate a FQDN from the "bare" node names
538         provName = getString(map, Parameters.PROV_NAME, DEFAULT_PROVSRVR_NAME);
539         activeProvName = getString(map, Parameters.PROV_ACTIVE_NAME, provName);
540         initialActivePod = getString(map, Parameters.ACTIVE_POD, "");
541         initialStandbyPod = getString(map, Parameters.STANDBY_POD, "");
542
543         //Adding new param for static Routing - Rally:US664862-1610
544         String staticRoutingNodes = getString(map, Parameters.STATIC_ROUTING_NODES, "");
545         activeFeeds = Feed.countActiveFeeds();
546         activeSubs = Subscription.countActiveSubscriptions();
547         try {
548             thisPod = InetAddress.getLocalHost().getHostName();
549         } catch (UnknownHostException e) {
550             thisPod = "";
551             intlogger.warn("PROV0014 Cannot determine the name of this provisioning server.", e);
552         }
553
554         // Normalize the nodes, and fill in nodeAddresses
555         InetAddress[] na = new InetAddress[nodes.length];
556         for (int i = 0; i < nodes.length; i++) {
557             try {
558                 na[i] = InetAddress.getByName(nodes[i]);
559                 intlogger.debug("PROV0003 DNS lookup: " + nodes[i] + " => " + na[i].toString());
560             } catch (UnknownHostException e) {
561                 na[i] = null;
562                 intlogger.warn("PROV0004 Cannot lookup " + nodes[i] + ": " + e.getMessage(), e);
563             }
564         }
565
566         //Reset Nodes arr after - removing static routing Nodes, Rally Userstory - US664862 .
567         List<String> filterNodes = new ArrayList<>();
568         for (String node : nodes) {
569             if (!staticRoutingNodes.contains(node)) {
570                 filterNodes.add(node);
571             }
572         }
573         nodes = filterNodes.toArray(new String[0]);
574
575         nodeAddresses = na;
576         NodeClass.setNodes(nodes);        // update NODES table
577
578         // Normalize the PODs, and fill in podAddresses
579         String[] pods = getPods();
580         na = new InetAddress[pods.length];
581         for (int i = 0; i < pods.length; i++) {
582             try {
583                 na[i] = InetAddress.getByName(pods[i]);
584                 intlogger.debug("PROV0003 DNS lookup: " + pods[i] + " => " + na[i].toString());
585             } catch (UnknownHostException e) {
586                 na[i] = null;
587                 intlogger.warn("PROV0004 Cannot lookup " + pods[i] + ": " + e.getMessage(), e);
588             }
589         }
590         podAddresses = na;
591
592         // Update ThrottleFilter
593         ThrottleFilter.configure();
594
595         // Check if we are active or standby POD
596         if (!isInitialActivePOD() && !isInitialStandbyPOD()) {
597             intlogger.warn("PROV0015 This machine is neither the active nor the standby POD.");
598         }
599     }
600
601     public static String getProvName() {
602         return provName;
603     }
604
605     public static String getActiveProvName() {
606         return activeProvName;
607     }
608
609     /**
610      * Get an array of all node names in the DR network.
611      *
612      * @return an array of Strings
613      */
614     public static String[] getNodes() {
615         return nodes;
616     }
617
618     /**
619      * Get an array of all node InetAddresses in the DR network.
620      *
621      * @return an array of InetAddresses
622      */
623     private static InetAddress[] getNodeAddresses() {
624         return nodeAddresses;
625     }
626
627     /**
628      * Get an array of all POD names in the DR network.
629      *
630      * @return an array of Strings
631      */
632     public static String[] getPods() {
633         return new String[]{initialActivePod, initialStandbyPod};
634     }
635
636     /**
637      * Get an array of all POD InetAddresses in the DR network.
638      *
639      * @return an array of InetAddresses
640      */
641     private static InetAddress[] getPodAddresses() {
642         return podAddresses;
643     }
644
645     /**
646      * Gets the FQDN of the initially ACTIVE_POD provisioning server (POD). Note: this used to be called isActivePOD(),
647      * however, that is a misnomer, as the active status could shift to the standby POD without these parameters
648      * changing.  Hence, the function names have been changed to more accurately reflect their purpose.
649      *
650      * @return the FQDN
651      */
652     public static boolean isInitialActivePOD() {
653         return thisPod.equals(initialActivePod);
654     }
655
656     /**
657      * Gets the FQDN of the initially STANDBY_POD provisioning server (POD).Note: this used to be called isStandbyPOD(),
658      * however, that is a misnomer, as the standby status could shift to the active POD without these parameters
659      * changing.  Hence, the function names have been changed to more accurately reflect their purpose.
660      *
661      * @return the FQDN
662      */
663     public static boolean isInitialStandbyPOD() {
664         return thisPod.equals(initialStandbyPod);
665     }
666
667     /**
668      * INSERT an {@link Insertable} bean into the database.
669      *
670      * @param bean the bean representing a row to insert
671      * @return true if the INSERT was successful
672      */
673     protected boolean doInsert(Insertable bean) {
674         boolean rv;
675         try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
676             rv = bean.doInsert(conn);
677         } catch (SQLException e) {
678             rv = false;
679             intlogger.warn("PROV0005 doInsert: " + e.getMessage(), e);
680         }
681         return rv;
682     }
683
684     /**
685      * UPDATE an {@link Updateable} bean in the database.
686      *
687      * @param bean the bean representing a row to update
688      * @return true if the UPDATE was successful
689      */
690     protected boolean doUpdate(Updateable bean) {
691         boolean rv;
692         try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
693             rv = bean.doUpdate(conn);
694         } catch (SQLException e) {
695             rv = false;
696             intlogger.warn("PROV0006 doUpdate: " + e.getMessage(), e);
697         }
698         return rv;
699     }
700
701     /**
702      * DELETE an {@link Deleteable} bean from the database.
703      *
704      * @param bean the bean representing a row to delete
705      * @return true if the DELETE was successful
706      */
707     protected boolean doDelete(Deleteable bean) {
708         boolean rv;
709         try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
710             rv = bean.doDelete(conn);
711         } catch (SQLException e) {
712             rv = false;
713             intlogger.warn("PROV0007 doDelete: " + e.getMessage(), e);
714         }
715         return rv;
716     }
717
718     private static boolean getBoolean(Map<String, String> map, String name) {
719         String str = map.get(name);
720         return "true".equalsIgnoreCase(str);
721     }
722
723     private static String getString(Map<String, String> map, String name, String dflt) {
724         String str = map.get(name);
725         return (str != null) ? str : dflt;
726     }
727
728     private static int getInt(Map<String, String> map, String name, int dflt) {
729         try {
730             String str = map.get(name);
731             return Integer.parseInt(str);
732         } catch (NumberFormatException e) {
733             return dflt;
734         }
735     }
736
737     private static Set<String> getSet(Map<String, String> map, String name) {
738         Set<String> set = new HashSet<>();
739         String str = map.get(name);
740         if (str != null) {
741             String[] pp = str.split("\\|");
742             if (pp != null) {
743                 for (String t : pp) {
744                     String t2 = t.trim();
745                     if (t2.length() > 0) {
746                         set.add(t2);
747                     }
748                 }
749             }
750         }
751         return set;
752     }
753
754     /**
755      * A class used to encapsulate a Content-type header, separating out the "version" attribute (which defaults to
756      * "1.0" if missing).
757      */
758     public class ContentHeader {
759
760         private String type;
761         private Map<String, String> map = new HashMap<>();
762
763         ContentHeader() {
764             this("", "1.0");
765         }
766
767         ContentHeader(String headertype, String version) {
768             type = headertype.trim();
769             map.put("version", version);
770         }
771
772         public String getType() {
773             return type;
774         }
775
776         String getAttribute(String key) {
777             String str = map.get(key);
778             if (str == null) {
779                 str = "";
780             }
781             return str;
782         }
783     }
784
785     /**
786      * Get the ContentHeader from an HTTP request.
787      *
788      * @param req the request
789      * @return the header, encapsulated in a ContentHeader object
790      */
791     ContentHeader getContentHeader(HttpServletRequest req) {
792         ContentHeader ch = new ContentHeader();
793         String str = req.getHeader("Content-Type");
794         if (str != null) {
795             String[] pp = str.split(";");
796             ch.type = pp[0].trim();
797             for (int i = 1; i < pp.length; i++) {
798                 int ix = pp[i].indexOf('=');
799                 if (ix > 0) {
800                     String type = pp[i].substring(0, ix).trim();
801                     String version = pp[i].substring(ix + 1).trim();
802                     ch.map.put(type, version);
803                 } else {
804                     ch.map.put(pp[i].trim(), "");
805                 }
806             }
807         }
808         return ch;
809     }
810
811     // Methods for the Policy Engine classes - ProvDataProvider interface
812     @Override
813     public String getFeedOwner(String feedId) {
814         try {
815             int intID = Integer.parseInt(feedId);
816             Feed feed = Feed.getFeedById(intID);
817             if (feed != null) {
818                 return feed.getPublisher();
819             }
820         } catch (NumberFormatException e) {
821             // ignore
822         }
823         return null;
824     }
825
826     @Override
827     public String getFeedClassification(String feedId) {
828         try {
829             int intID = Integer.parseInt(feedId);
830             Feed feed = Feed.getFeedById(intID);
831             if (feed != null) {
832                 return feed.getAuthorization().getClassification();
833             }
834         } catch (NumberFormatException e) {
835             // ignore
836         }
837         return null;
838     }
839
840     @Override
841     public String getSubscriptionOwner(String subId) {
842         try {
843             int intID = Integer.parseInt(subId);
844             Subscription sub = Subscription.getSubscriptionById(intID);
845             if (sub != null) {
846                 return sub.getSubscriber();
847             }
848         } catch (NumberFormatException e) {
849             // ignore
850         }
851         return null;
852     }
853
854     /*
855      * @Method - isUserMemberOfGroup - Rally:US708115
856      * @Params - group object and user to check if exists in given group
857      * @return - boolean value /true/false
858      */
859     private boolean isUserMemberOfGroup(Group group, String user) {
860
861         String groupDetails = group.getMembers().replace("]", "").replace("[", "");
862         String[] str = groupDetails.split("},");
863
864         for (String value : str) {
865             JSONObject jsonObj;
866             try {
867                 jsonObj = new JSONObject(value + "}");
868                 if (jsonObj.get("id").equals(user)) {
869                     return true;
870                 }
871             } catch (JSONException e) {
872                 intlogger.error("JSONException: " + e.getMessage(), e);
873             }
874         }
875         return false;
876
877     }
878
879     /*
880      * @Method - getGroupByFeedGroupId- Rally:US708115
881      * @Params - User to check in group and feedid which is assigned the group.
882      * @return - string value groupid/null
883      */
884     @Override
885     public String getGroupByFeedGroupId(String owner, String feedId) {
886         try {
887             Feed feed = Feed.getFeedById(Integer.parseInt(feedId));
888             if (feed != null) {
889                 int groupid = feed.getGroupid();
890                 if (groupid > 0) {
891                     Group group = Group.getGroupById(groupid);
892                     if (group != null && isUserMemberOfGroup(group, owner)) {
893                         return group.getAuthid();
894                     }
895                 }
896             }
897         } catch (NumberFormatException e) {
898             // ignore
899         }
900         return null;
901     }
902
903     /*
904      * @Method - getGroupBySubGroupId - Rally:US708115
905      * @Params - User to check in group and subid which is assigned the group.
906      * @return - string value groupid/null
907      */
908     @Override
909     public String getGroupBySubGroupId(String owner, String subId) {
910         try {
911             int intID = Integer.parseInt(subId);
912             Subscription sub = Subscription.getSubscriptionById(intID);
913             if (sub != null) {
914                 int groupid = sub.getGroupid();
915                 if (groupid > 0) {
916                     Group group = Group.getGroupById(groupid);
917                     if (group != null && isUserMemberOfGroup(group, owner)) {
918                         return group.getAuthid();
919                     }
920                 }
921             }
922         } catch (NumberFormatException e) {
923             // ignore
924         }
925         return null;
926     }
927
928     /*
929      * @Method - setIpFqdnRequestIDandInvocationIDForEelf
930      * @Params - method, prints method name in EELF log.
931      * @Params- Req, Request used to get RequestId and InvocationId
932      */
933     void setIpFqdnRequestIDandInvocationIDForEelf(String method, HttpServletRequest req) {
934         setIpFqdnForEelf(method);
935         setMDC(req, "X-ONAP-RequestID", MDC_KEY_REQUEST_ID);
936         setMDC(req, "X-InvocationID", "InvocationId");
937     }
938
939     private void setMDC(HttpServletRequest req, String headerName, String keyName) {
940         String mdcId = req.getHeader(headerName);
941         if (StringUtils.isBlank(mdcId)) {
942             mdcId = UUID.randomUUID().toString();
943         }
944         MDC.put(keyName, mdcId);
945     }
946
947     /*
948      * @Method - setIpFqdnRequestIdForEelf - Rally:US664892
949      * @Params - method, prints method name in EELF log.
950      */
951     void setIpFqdnForEelf(String method) {
952         MDC.clear();
953         MDC.put(MDC_SERVICE_NAME, method);
954         try {
955             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
956             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
957         } catch (Exception e) {
958             intlogger.error("Exception: " + e.getMessage(), e);
959         }
960
961     }
962
963     /*
964      * AAF changes: TDP EPIC US# 307413
965      * @Method - getFeedPermission - Forming permission string for feed part to check AAF access in CADI Framework
966      * @Params - aafInstance Passing aafInstance as it's used in permission string
967      * @Params - userAction Passing CONST values to set different actions in permission string
968      */
969     String getFeedPermission(String aafInstance, String userAction) {
970         try {
971             Properties props = ProvRunner.getProvProperties();
972             String type = props.getProperty(AAF_CADI_FEED_TYPE, AAF_CADI_FEED);
973             String action;
974             switch (userAction) {
975                 case CREATE_PERMISSION:
976                     action = CREATE_PERMISSION;
977                     break;
978                 case EDIT_PERMISSION:
979                     action = EDIT_PERMISSION;
980                     break;
981                 case DELETE_PERMISSION:
982                     action = DELETE_PERMISSION;
983                     break;
984                 case PUBLISH_PERMISSION:
985                     action = PUBLISH_PERMISSION;
986                     break;
987                 case SUSPEND_PERMISSION:
988                     action = SUSPEND_PERMISSION;
989                     break;
990                 case RESTORE_PERMISSION:
991                     action = RESTORE_PERMISSION;
992                     break;
993                 default:
994                     action = "*";
995             }
996             if (aafInstance == null || "".equals(aafInstance)) {
997                 aafInstance = props.getProperty(AAF_INSTANCE, "org.onap.dmaap-dr.NoInstanceDefined");
998             }
999             return type + "|" + aafInstance + "|" + action;
1000         } catch (Exception e) {
1001             intlogger.error("PROV7005 BaseServlet.getFeedPermission: " + e.getMessage(), e);
1002         }
1003         return null;
1004     }
1005
1006     /*
1007      * AAF changes: TDP EPIC US# 307413
1008      * @Method - getSubscriberPermission - Forming permission string for subscription part to check
1009      * AAF access in CADI Framework
1010      * @Params - aafInstance Passing aafInstance as it's used in permission string
1011      * @Params - userAction Passing CONST values to set different actions in permission string
1012      */
1013     String getSubscriberPermission(String aafInstance, String userAction) {
1014         try {
1015             Properties props = ProvRunner.getProvProperties();
1016             String type = props.getProperty(AAF_CADI_SUB_TYPE, AAF_CADI_SUB);
1017             String action;
1018             switch (userAction) {
1019                 case SUBSCRIBE_PERMISSION:
1020                     action = SUBSCRIBE_PERMISSION;
1021                     type = props.getProperty(AAF_CADI_FEED_TYPE, AAF_CADI_FEED);
1022                     break;
1023                 case EDIT_PERMISSION:
1024                     action = EDIT_PERMISSION;
1025                     break;
1026                 case DELETE_PERMISSION:
1027                     action = DELETE_PERMISSION;
1028                     break;
1029                 case RESTORE_PERMISSION:
1030                     action = RESTORE_PERMISSION;
1031                     break;
1032                 case SUSPEND_PERMISSION:
1033                     action = SUSPEND_PERMISSION;
1034                     break;
1035                 case PUBLISH_PERMISSION:
1036                     action = PUBLISH_PERMISSION;
1037                     break;
1038                 case APPROVE_SUB_PERMISSION:
1039                     action = APPROVE_SUB_PERMISSION;
1040                     type = props.getProperty(AAF_CADI_FEED_TYPE, AAF_CADI_FEED);
1041                     break;
1042                 default:
1043                     action = "*";
1044             }
1045             if (aafInstance == null || "".equals(aafInstance)) {
1046                 aafInstance = props.getProperty(AAF_INSTANCE, "org.onap.dmaap-dr.NoInstanceDefined");
1047             }
1048             return type + "|" + aafInstance + "|" + action;
1049         } catch (Exception e) {
1050             intlogger.error("PROV7005 BaseServlet.getSubscriberPermission: " + e.getMessage(), e);
1051         }
1052         return null;
1053     }
1054 }