1 /*******************************************************************************
2 * ============LICENSE_START==================================================
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
11 * * http://www.apache.org/licenses/LICENSE-2.0
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====================================================
20 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 ******************************************************************************/
25 package org.onap.dmaap.datarouter.provisioning;
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;
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;
44 import java.util.Properties;
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;
77 * This is the base class for all Servlets in the provisioning code. It provides standard constants and some common
81 * @version $Id: BaseServlet.java,v 1.16 2014/03/12 19:45:40 eby Exp $
83 @SuppressWarnings("serial")
84 public class BaseServlet extends HttpServlet implements ProvDataProvider {
86 public static final String BEHALF_HEADER = "X-DMAAP-DR-ON-BEHALF-OF";
88 public static final String EXCLUDE_AAF_HEADER = "X-EXCLUDE-AAF";
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";
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";
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";
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";
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";
125 static final String DB_PROBLEM_MSG = "There has been a problem with the DB. It is suggested you "
126 + "try the operation again.";
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";
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.";
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";
161 * A boolean to trigger one time "provisioning changed" event on startup.
163 private static boolean startmsgFlag = true;
165 * This POD should require SSL connections from clients; pulled from the DB (PROV_REQUIRE_SECURE).
167 private static boolean requireSecure = true;
169 * This POD should require signed, recognized certificates from clients; pulled from the DB (PROV_REQUIRE_CERT).
171 private static boolean requireCert = true;
173 * The set of authorized addresses and networks; pulled from the DB (PROV_AUTH_ADDRESSES).
175 private static Set<String> authorizedAddressesAndNetworks = new HashSet<>();
177 * The set of authorized names; pulled from the DB (PROV_AUTH_SUBJECTS).
179 private static Set<String> authorizedNames = new HashSet<>();
181 * The FQDN of the initially "active" provisioning server in this Data Router ecosystem.
183 private static String initialActivePod;
185 * The FQDN of the initially "standby" provisioning server in this Data Router ecosystem.
187 private static String initialStandbyPod;
189 * The FQDN of this provisioning server in this Data Router ecosystem.
191 private static String thisPod;
193 * "Timer 1" - used to determine when to notify nodes of provisioning changes.
195 private static long pokeTimer1;
197 * "Timer 2" - used to determine when to notify nodes of provisioning changes.
199 private static long pokeTimer2;
201 * Array of nodes names and/or FQDNs.
203 private static String[] nodes = new String[0];
205 * Array of node IP addresses.
207 private static InetAddress[] nodeAddresses = new InetAddress[0];
209 * Array of POD IP addresses.
211 private static InetAddress[] podAddresses = new InetAddress[0];
213 * The maximum number of feeds allowed; pulled from the DB (PROV_MAXFEED_COUNT).
215 static int maxFeeds = 0;
217 * The maximum number of subscriptions allowed; pulled from the DB (PROV_MAXSUB_COUNT).
219 static int maxSubs = 0;
221 * The current number of feeds in the system.
223 static int activeFeeds = 0;
225 * The current number of subscriptions in the system.
227 static int activeSubs = 0;
230 * The standard FQDN of the provisioning server in this Data Router ecosystem.
232 private static String provName = "feeds-drtr.web.att.com";
235 * The standard FQDN of the ACTIVE_POD provisioning server in this Data Router ecosystem.
237 private static String activeProvName = "feeds-drtr.web.att.com";
240 * This logger is used to log provisioning events.
242 protected static EELFLogger eventlogger;
244 * This logger is used to log internal events (errors, etc.)
246 protected static EELFLogger intlogger;
248 * Authorizer - interface to the Policy Engine.
250 protected static Authorizer authz;
252 * The Synchronizer used to sync active DB to standby one.
254 private static SynchronizerTask synctask = null;
256 //Data Router Subscriber HTTPS Relaxation feature USERSTORYID:US674047.
257 private InetAddress thishost;
258 private InetAddress loopback;
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");
264 static String isCadiEnabled = ProvRunner.getProvProperties()
265 .getProperty("org.onap.dmaap.datarouter.provserver.cadi.enabled", "false");
268 * Initialize data common to all the provisioning server servlets.
270 protected BaseServlet() {
273 authz = new ProvAuthorizer(this);
275 String name = this.getClass().getName();
276 intlogger.info("PROV0002 Servlet " + name + " started.");
279 private static void setUpFields() {
280 if (eventlogger == null) {
281 eventlogger = EELFManager.getInstance().getLogger("EventLog");
283 if (intlogger == null) {
284 intlogger = EELFManager.getInstance().getLogger("InternalLog");
287 startmsgFlag = false;
288 provisioningParametersChanged();
290 if (synctask == null) {
291 synctask = SynchronizerTask.getSynchronizer();
296 public void init(ServletConfig config) throws ServletException {
299 thishost = InetAddress.getLocalHost();
300 loopback = InetAddress.getLoopbackAddress();
301 } catch (UnknownHostException e) {
302 intlogger.info("BaseServlet.init: " + e.getMessage(), e);
308 * @param req HTTPServletRequest
311 public static int getIdFromPath(HttpServletRequest req) {
312 String path = req.getPathInfo();
313 if (path == null || path.length() < 2) {
317 return Integer.parseInt(path.substring(1));
318 } catch (NumberFormatException e) {
324 * Read the request's input stream and return a JSONObject from it.
326 * @param req the HTTP request
327 * @return the JSONObject, or null if the stream cannot be parsed
329 JSONObject getJSONfromInput(HttpServletRequest req) {
330 JSONObject jo = null;
332 jo = new JSONObject(new JSONTokener(req.getInputStream()));
333 if (intlogger.isDebugEnabled()) {
334 intlogger.debug("JSON: " + hashPasswords(new JSONObject(jo.toString())).toString());
336 } catch (Exception e) {
337 intlogger.info("Error reading JSON: " + e);
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);
352 if (!jo.isNull("delivery")) {
353 JSONObject deliveryObj = jo.getJSONObject("delivery");
354 String password = deliveryObj.get(JSON_HASH_STRING).toString();
355 processPassword(deliveryObj, password);
360 private static void processPassword(JSONArray endpointIds, int index, String password) {
362 endpointIds.getJSONObject(index).put(JSON_HASH_STRING, DigestUtils.sha256Hex(password));
363 } catch (JSONException e) {
364 intlogger.info("Error reading JSON while hashing: " + e);
368 private static void processPassword(JSONObject deliveryObj, String password) {
370 deliveryObj.put(JSON_HASH_STRING, DigestUtils.sha256Hex(password));
371 } catch (JSONException e) {
372 intlogger.info("Error reading JSON while hashing: " + e);
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)?
381 * @param request the request
382 * @return an error string, or null if all is OK
384 String isAuthorizedForProvisioning(HttpServletRequest request) {
385 if (!Boolean.parseBoolean(isAddressAuthEnabled)) {
388 // Is the request https?
389 if (requireSecure && !request.isSecure()) {
390 return "Request must be made over an HTTPS connection.";
392 String remoteHostCheck = checkRemoteHostAuthorization(request);
393 if (remoteHostCheck != null) {
394 return remoteHostCheck;
396 // Does remote have a valid certificate?
398 X509Certificate[] certs = (X509Certificate[]) request.getAttribute(CERT_ATTRIBUTE);
399 if (certs == null || certs.length == 0) {
400 return "Client certificate is missing.";
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.";
414 private String checkRemoteHostAuthorization(HttpServletRequest request) {
415 // Is remote IP authorized?
416 String remote = request.getRemoteAddr();
418 boolean found = false;
419 InetAddress ip = InetAddress.getByName(remote);
420 for (String addrnet : authorizedAddressesAndNetworks) {
421 found |= addressMatchesNetwork(ip, addrnet);
424 return "Unauthorized address: " + remote;
426 } catch (UnknownHostException e) {
427 intlogger.error("PROV0051 BaseServlet.isAuthorizedForProvisioning: " + e.getMessage(), e);
428 return "Unauthorized address: " + remote;
434 * Check if the remote IP address is authorized to see the /internal URL tree.
436 * @param request the HTTP request
437 * @return true iff authorized
439 boolean isAuthorizedForInternal(HttpServletRequest request) {
441 if (!Boolean.parseBoolean(isAddressAuthEnabled)) {
444 InetAddress ip = InetAddress.getByName(request.getRemoteAddr());
445 for (InetAddress node : getNodeAddresses()) {
446 if (ip.equals(node)) {
450 for (InetAddress pod : getPodAddresses()) {
451 if (ip.equals(pod)) {
455 if (ip.equals(thishost)) {
458 if (ip.equals(loopback)) {
461 } catch (UnknownHostException e) {
462 intlogger.error("PROV0052 BaseServlet.isAuthorizedForInternal: " + e.getMessage(), e);
468 * Check if an IP address matches a network address.
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
474 private static boolean addressMatchesNetwork(InetAddress ip, String str) {
476 int substr = str.indexOf('/');
478 mlen = Integer.parseInt(str.substring(substr + 1));
479 str = str.substring(0, substr);
482 InetAddress i2 = InetAddress.getByName(str);
483 byte[] b1 = ip.getAddress();
484 byte[] b2 = i2.getAddress();
485 if (b1.length != b2.length) {
490 (byte) 0x00, (byte) 0x80, (byte) 0xC0, (byte) 0xE0,
491 (byte) 0xF0, (byte) 0xF8, (byte) 0xFC, (byte) 0xFE
493 byte mask = masks[mlen % 8];
494 for (substr = mlen / 8; substr < b1.length; substr++) {
500 for (substr = 0; substr < b1.length; substr++) {
501 if (b1[substr] != b2[substr]) {
505 } catch (UnknownHostException e) {
506 intlogger.error("PROV0053 BaseServlet.addressMatchesNetwork: " + e.getMessage(), e);
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.
516 public static void provisioningDataChanged() {
517 long now = System.currentTimeMillis();
518 Poker pkr = Poker.getPoker();
519 pkr.setTimers(now + (pokeTimer1 * 1000L), now + (pokeTimer2 * 1000L));
523 * Something in the parameters has changed, reload all parameters from the DB.
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);
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, "");
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();
548 thisPod = InetAddress.getLocalHost().getHostName();
549 } catch (UnknownHostException e) {
551 intlogger.warn("PROV0014 Cannot determine the name of this provisioning server.", e);
554 // Normalize the nodes, and fill in nodeAddresses
555 InetAddress[] na = new InetAddress[nodes.length];
556 for (int i = 0; i < nodes.length; i++) {
558 na[i] = InetAddress.getByName(nodes[i]);
559 intlogger.debug("PROV0003 DNS lookup: " + nodes[i] + " => " + na[i].toString());
560 } catch (UnknownHostException e) {
562 intlogger.warn("PROV0004 Cannot lookup " + nodes[i] + ": " + e.getMessage(), e);
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);
573 nodes = filterNodes.toArray(new String[0]);
576 NodeClass.setNodes(nodes); // update NODES table
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++) {
583 na[i] = InetAddress.getByName(pods[i]);
584 intlogger.debug("PROV0003 DNS lookup: " + pods[i] + " => " + na[i].toString());
585 } catch (UnknownHostException e) {
587 intlogger.warn("PROV0004 Cannot lookup " + pods[i] + ": " + e.getMessage(), e);
592 // Update ThrottleFilter
593 ThrottleFilter.configure();
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.");
601 public static String getProvName() {
605 public static String getActiveProvName() {
606 return activeProvName;
610 * Get an array of all node names in the DR network.
612 * @return an array of Strings
614 public static String[] getNodes() {
619 * Get an array of all node InetAddresses in the DR network.
621 * @return an array of InetAddresses
623 private static InetAddress[] getNodeAddresses() {
624 return nodeAddresses;
628 * Get an array of all POD names in the DR network.
630 * @return an array of Strings
632 public static String[] getPods() {
633 return new String[]{initialActivePod, initialStandbyPod};
637 * Get an array of all POD InetAddresses in the DR network.
639 * @return an array of InetAddresses
641 private static InetAddress[] getPodAddresses() {
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.
652 public static boolean isInitialActivePOD() {
653 return thisPod.equals(initialActivePod);
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.
663 public static boolean isInitialStandbyPOD() {
664 return thisPod.equals(initialStandbyPod);
668 * INSERT an {@link Insertable} bean into the database.
670 * @param bean the bean representing a row to insert
671 * @return true if the INSERT was successful
673 protected boolean doInsert(Insertable bean) {
675 try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
676 rv = bean.doInsert(conn);
677 } catch (SQLException e) {
679 intlogger.warn("PROV0005 doInsert: " + e.getMessage(), e);
685 * UPDATE an {@link Updateable} bean in the database.
687 * @param bean the bean representing a row to update
688 * @return true if the UPDATE was successful
690 protected boolean doUpdate(Updateable bean) {
692 try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
693 rv = bean.doUpdate(conn);
694 } catch (SQLException e) {
696 intlogger.warn("PROV0006 doUpdate: " + e.getMessage(), e);
702 * DELETE an {@link Deleteable} bean from the database.
704 * @param bean the bean representing a row to delete
705 * @return true if the DELETE was successful
707 protected boolean doDelete(Deleteable bean) {
709 try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
710 rv = bean.doDelete(conn);
711 } catch (SQLException e) {
713 intlogger.warn("PROV0007 doDelete: " + e.getMessage(), e);
718 private static boolean getBoolean(Map<String, String> map, String name) {
719 String str = map.get(name);
720 return "true".equalsIgnoreCase(str);
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;
728 private static int getInt(Map<String, String> map, String name, int dflt) {
730 String str = map.get(name);
731 return Integer.parseInt(str);
732 } catch (NumberFormatException e) {
737 private static Set<String> getSet(Map<String, String> map, String name) {
738 Set<String> set = new HashSet<>();
739 String str = map.get(name);
741 String[] pp = str.split("\\|");
743 for (String t : pp) {
744 String t2 = t.trim();
745 if (t2.length() > 0) {
755 * A class used to encapsulate a Content-type header, separating out the "version" attribute (which defaults to
758 public class ContentHeader {
761 private Map<String, String> map = new HashMap<>();
767 ContentHeader(String headertype, String version) {
768 type = headertype.trim();
769 map.put("version", version);
772 public String getType() {
776 String getAttribute(String key) {
777 String str = map.get(key);
786 * Get the ContentHeader from an HTTP request.
788 * @param req the request
789 * @return the header, encapsulated in a ContentHeader object
791 ContentHeader getContentHeader(HttpServletRequest req) {
792 ContentHeader ch = new ContentHeader();
793 String str = req.getHeader("Content-Type");
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('=');
800 String type = pp[i].substring(0, ix).trim();
801 String version = pp[i].substring(ix + 1).trim();
802 ch.map.put(type, version);
804 ch.map.put(pp[i].trim(), "");
811 // Methods for the Policy Engine classes - ProvDataProvider interface
813 public String getFeedOwner(String feedId) {
815 int intID = Integer.parseInt(feedId);
816 Feed feed = Feed.getFeedById(intID);
818 return feed.getPublisher();
820 } catch (NumberFormatException e) {
827 public String getFeedClassification(String feedId) {
829 int intID = Integer.parseInt(feedId);
830 Feed feed = Feed.getFeedById(intID);
832 return feed.getAuthorization().getClassification();
834 } catch (NumberFormatException e) {
841 public String getSubscriptionOwner(String subId) {
843 int intID = Integer.parseInt(subId);
844 Subscription sub = Subscription.getSubscriptionById(intID);
846 return sub.getSubscriber();
848 } catch (NumberFormatException e) {
855 * @Method - isUserMemberOfGroup - Rally:US708115
856 * @Params - group object and user to check if exists in given group
857 * @return - boolean value /true/false
859 private boolean isUserMemberOfGroup(Group group, String user) {
861 String groupDetails = group.getMembers().replace("]", "").replace("[", "");
862 String[] str = groupDetails.split("},");
864 for (String value : str) {
867 jsonObj = new JSONObject(value + "}");
868 if (jsonObj.get("id").equals(user)) {
871 } catch (JSONException e) {
872 intlogger.error("JSONException: " + e.getMessage(), e);
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
885 public String getGroupByFeedGroupId(String owner, String feedId) {
887 Feed feed = Feed.getFeedById(Integer.parseInt(feedId));
889 int groupid = feed.getGroupid();
891 Group group = Group.getGroupById(groupid);
892 if (group != null && isUserMemberOfGroup(group, owner)) {
893 return group.getAuthid();
897 } catch (NumberFormatException e) {
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
909 public String getGroupBySubGroupId(String owner, String subId) {
911 int intID = Integer.parseInt(subId);
912 Subscription sub = Subscription.getSubscriptionById(intID);
914 int groupid = sub.getGroupid();
916 Group group = Group.getGroupById(groupid);
917 if (group != null && isUserMemberOfGroup(group, owner)) {
918 return group.getAuthid();
922 } catch (NumberFormatException e) {
929 * @Method - setIpFqdnRequestIDandInvocationIDForEelf
930 * @Params - method, prints method name in EELF log.
931 * @Params- Req, Request used to get RequestId and InvocationId
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");
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();
944 MDC.put(keyName, mdcId);
948 * @Method - setIpFqdnRequestIdForEelf - Rally:US664892
949 * @Params - method, prints method name in EELF log.
951 void setIpFqdnForEelf(String method) {
953 MDC.put(MDC_SERVICE_NAME, method);
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);
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
969 String getFeedPermission(String aafInstance, String userAction) {
971 Properties props = ProvRunner.getProvProperties();
972 String type = props.getProperty(AAF_CADI_FEED_TYPE, AAF_CADI_FEED);
974 switch (userAction) {
975 case CREATE_PERMISSION:
976 action = CREATE_PERMISSION;
978 case EDIT_PERMISSION:
979 action = EDIT_PERMISSION;
981 case DELETE_PERMISSION:
982 action = DELETE_PERMISSION;
984 case PUBLISH_PERMISSION:
985 action = PUBLISH_PERMISSION;
987 case SUSPEND_PERMISSION:
988 action = SUSPEND_PERMISSION;
990 case RESTORE_PERMISSION:
991 action = RESTORE_PERMISSION;
996 if (aafInstance == null || "".equals(aafInstance)) {
997 aafInstance = props.getProperty(AAF_INSTANCE, "org.onap.dmaap-dr.NoInstanceDefined");
999 return type + "|" + aafInstance + "|" + action;
1000 } catch (Exception e) {
1001 intlogger.error("PROV7005 BaseServlet.getFeedPermission: " + e.getMessage(), e);
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
1013 String getSubscriberPermission(String aafInstance, String userAction) {
1015 Properties props = ProvRunner.getProvProperties();
1016 String type = props.getProperty(AAF_CADI_SUB_TYPE, AAF_CADI_SUB);
1018 switch (userAction) {
1019 case SUBSCRIBE_PERMISSION:
1020 action = SUBSCRIBE_PERMISSION;
1021 type = props.getProperty(AAF_CADI_FEED_TYPE, AAF_CADI_FEED);
1023 case EDIT_PERMISSION:
1024 action = EDIT_PERMISSION;
1026 case DELETE_PERMISSION:
1027 action = DELETE_PERMISSION;
1029 case RESTORE_PERMISSION:
1030 action = RESTORE_PERMISSION;
1032 case SUSPEND_PERMISSION:
1033 action = SUSPEND_PERMISSION;
1035 case PUBLISH_PERMISSION:
1036 action = PUBLISH_PERMISSION;
1038 case APPROVE_SUB_PERMISSION:
1039 action = APPROVE_SUB_PERMISSION;
1040 type = props.getProperty(AAF_CADI_FEED_TYPE, AAF_CADI_FEED);
1045 if (aafInstance == null || "".equals(aafInstance)) {
1046 aafInstance = props.getProperty(AAF_INSTANCE, "org.onap.dmaap-dr.NoInstanceDefined");
1048 return type + "|" + aafInstance + "|" + action;
1049 } catch (Exception e) {
1050 intlogger.error("PROV7005 BaseServlet.getSubscriberPermission: " + e.getMessage(), e);