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_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 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;
43 import java.util.List;
44 import java.util.ArrayList;
46 import javax.servlet.ServletConfig;
47 import javax.servlet.ServletException;
48 import javax.servlet.http.HttpServlet;
49 import javax.servlet.http.HttpServletRequest;
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;
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;
84 * This is the base class for all Servlets in the provisioning code. It provides standard constants and some common
88 * @version $Id: BaseServlet.java,v 1.16 2014/03/12 19:45:40 eby Exp $
90 @SuppressWarnings("serial")
91 public class BaseServlet extends HttpServlet implements ProvDataProvider {
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";
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";
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";
116 static final String DB_PROBLEM_MSG = "There has been a problem with the DB. It is suggested you try the operation again.";
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
127 * A boolean to trigger one time "provisioning changed" event on startup
129 private static boolean startmsgFlag = true;
131 * This POD should require SSL connections from clients; pulled from the DB (PROV_REQUIRE_SECURE)
133 private static boolean requireSecure = true;
135 * This POD should require signed, recognized certificates from clients; pulled from the DB (PROV_REQUIRE_CERT)
137 private static boolean requireCert = true;
139 * The set of authorized addresses and networks; pulled from the DB (PROV_AUTH_ADDRESSES)
141 private static Set<String> authorizedAddressesAndNetworks = new HashSet<>();
143 * The set of authorized names; pulled from the DB (PROV_AUTH_SUBJECTS)
145 private static Set<String> authorizedNames = new HashSet<>();
147 * The FQDN of the initially "active" provisioning server in this Data Router ecosystem
149 private static String initialActivePod;
151 * The FQDN of the initially "standby" provisioning server in this Data Router ecosystem
153 private static String initialStandbyPod;
155 * The FQDN of this provisioning server in this Data Router ecosystem
157 private static String thisPod;
159 * "Timer 1" - used to determine when to notify nodes of provisioning changes
161 private static long pokeTimer1;
163 * "Timer 2" - used to determine when to notify nodes of provisioning changes
165 private static long pokeTimer2;
167 * Array of nodes names and/or FQDNs
169 private static String[] nodes = new String[0];
171 * Array of node IP addresses
173 private static InetAddress[] nodeAddresses = new InetAddress[0];
175 * Array of POD IP addresses
177 private static InetAddress[] podAddresses = new InetAddress[0];
179 * The maximum number of feeds allowed; pulled from the DB (PROV_MAXFEED_COUNT)
181 static int maxFeeds = 0;
183 * The maximum number of subscriptions allowed; pulled from the DB (PROV_MAXSUB_COUNT)
185 static int maxSubs = 0;
187 * The current number of feeds in the system
189 static int activeFeeds = 0;
191 * The current number of subscriptions in the system
193 static int activeSubs = 0;
195 * The domain used to generate a FQDN from the "bare" node names
197 private static String provDomain = "web.att.com";
199 * The standard FQDN of the provisioning server in this Data Router ecosystem
201 private static String provName = "feeds-drtr.web.att.com";
204 * The standard FQDN of the ACTIVE provisioning server in this Data Router ecosystem
206 private static String activeProvName = "feeds-drtr.web.att.com";
208 private static String staticRoutingNodes = STATIC_ROUTING_NODES; //Adding new param for static Routing - Rally:US664862-1610
211 * This logger is used to log provisioning events
213 protected static Logger eventlogger;
215 * This logger is used to log internal events (errors, etc.)
217 protected static Logger intlogger;
219 * Authorizer - interface to the Policy Engine
221 protected static Authorizer authz;
223 * The Synchronizer used to sync active DB to standby one
225 private static SynchronizerTask synctask = null;
227 //Data Router Subscriber HTTPS Relaxation feature USERSTORYID:US674047.
228 private InetAddress thishost;
229 private InetAddress loopback;
230 private static Boolean mailSendFlag = false;
232 private static final String MAILCONFIG_FILE = "mail.properties";
233 private static Properties mailprops;
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");
240 * Initialize data common to all the provisioning server servlets.
242 protected BaseServlet() {
243 if (eventlogger == null) {
244 eventlogger = Logger.getLogger("org.onap.dmaap.datarouter.provisioning.events");
246 if (intlogger == null) {
247 intlogger = Logger.getLogger("org.onap.dmaap.datarouter.provisioning.internal");
250 authz = new ProvAuthorizer(this);
253 startmsgFlag = false;
254 provisioningParametersChanged();
256 if (synctask == null) {
257 synctask = SynchronizerTask.getSynchronizer();
259 String name = this.getClass().getName();
260 intlogger.info("PROV0002 Servlet " + name + " started.");
264 public void init(ServletConfig config) throws ServletException {
267 thishost = InetAddress.getLocalHost();
268 loopback = InetAddress.getLoopbackAddress();
269 //checkHttpsRelaxation(); //Data Router Subscriber HTTPS Relaxation feature USERSTORYID:US674047.
270 } catch (UnknownHostException e) {
275 int getIdFromPath(HttpServletRequest req) {
276 String path = req.getPathInfo();
277 if (path == null || path.length() < 2) {
281 return Integer.parseInt(path.substring(1));
282 } catch (NumberFormatException e) {
288 * Read the request's input stream and return a JSONObject from it
290 * @param req the HTTP request
291 * @return the JSONObject, or null if the stream cannot be parsed
293 JSONObject getJSONfromInput(HttpServletRequest req) {
294 JSONObject jo = null;
296 jo = new JSONObject(new JSONTokener(req.getInputStream()));
297 if (intlogger.isDebugEnabled()) {
298 intlogger.debug("JSON: " + jo.toString());
300 } catch (Exception e) {
301 intlogger.info("Error reading JSON: " + e);
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)?
311 * @param request the request
312 * @return an error string, or null if all is OK
314 String isAuthorizedForProvisioning(HttpServletRequest request) {
315 if (!Boolean.parseBoolean(isAddressAuthEnabled)) {
318 // Is the request https?
319 if (requireSecure && !request.isSecure()) {
320 return "Request must be made over an HTTPS connection.";
323 // Is remote IP authorized?
324 String remote = request.getRemoteAddr();
326 boolean found = false;
327 InetAddress ip = InetAddress.getByName(remote);
328 for (String addrnet : authorizedAddressesAndNetworks) {
329 found |= addressMatchesNetwork(ip, addrnet);
332 return "Unauthorized address: " + remote;
334 } catch (UnknownHostException e) {
335 return "Unauthorized address: " + remote;
338 // Does remote have a valid certificate?
340 X509Certificate certs[] = (X509Certificate[]) request.getAttribute(CERT_ATTRIBUTE);
341 if (certs == null || certs.length == 0) {
342 return "Client certificate is missing.";
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.";
357 * Check if the remote IP address is authorized to see the /internal URL tree.
359 * @param request the HTTP request
360 * @return true iff authorized
362 boolean isAuthorizedForInternal(HttpServletRequest request) {
365 if (!Boolean.parseBoolean(isAddressAuthEnabled)) {
368 InetAddress ip = InetAddress.getByName(request.getRemoteAddr());
369 for (InetAddress node : getNodeAddresses()) {
370 if (node != null && ip.equals(node)) {
374 for (InetAddress pod : getPodAddresses()) {
375 if (pod != null && ip.equals(pod)) {
379 if (thishost != null && ip.equals(thishost)) {
382 if (loopback != null && ip.equals(loopback)) {
385 } catch (UnknownHostException e) {
392 * Check if an IP address matches a network address.
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
398 private static boolean addressMatchesNetwork(InetAddress ip, String s) {
400 int n = s.indexOf("/");
402 mlen = Integer.parseInt(s.substring(n + 1));
403 s = s.substring(0, n);
406 InetAddress i2 = InetAddress.getByName(s);
407 byte[] b1 = ip.getAddress();
408 byte[] b2 = i2.getAddress();
409 if (b1.length != b2.length) {
414 (byte) 0x00, (byte) 0x80, (byte) 0xC0, (byte) 0xE0,
415 (byte) 0xF0, (byte) 0xF8, (byte) 0xFC, (byte) 0xFE
417 byte mask = masks[mlen % 8];
418 for (n = mlen / 8; n < b1.length; n++) {
424 for (n = 0; n < b1.length; n++) {
425 if (b1[n] != b2[n]) {
429 } catch (UnknownHostException e) {
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.
439 public static void provisioningDataChanged() {
440 long now = System.currentTimeMillis();
441 Poker p = Poker.getPoker();
442 p.setTimers(now + (pokeTimer1 * 1000L), now + (pokeTimer2 * 1000L));
446 * Something in the parameters has changed, reload all parameters from the DB.
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();
471 thisPod = InetAddress.getLocalHost().getHostName();
472 } catch (UnknownHostException e) {
474 intlogger.warn("PROV0014 Cannot determine the name of this provisioning server.");
477 // Normalize the nodes, and fill in nodeAddresses
478 InetAddress[] na = new InetAddress[nodes.length];
479 for (int i = 0; i < nodes.length; i++) {
481 na[i] = InetAddress.getByName(nodes[i]);
482 intlogger.debug("PROV0003 DNS lookup: " + nodes[i] + " => " + na[i].toString());
483 } catch (UnknownHostException e) {
485 intlogger.warn("PROV0004 Cannot lookup " + nodes[i] + ": " + e);
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);
496 nodes = filterNodes.toArray(new String[filterNodes.size()]);
499 NodeClass.setNodes(nodes); // update NODES table
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++) {
506 na[i] = InetAddress.getByName(pods[i]);
507 intlogger.debug("PROV0003 DNS lookup: " + pods[i] + " => " + na[i].toString());
508 } catch (UnknownHostException e) {
510 intlogger.warn("PROV0004 Cannot lookup " + pods[i] + ": " + e);
515 // Update ThrottleFilter
516 ThrottleFilter.configure();
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.");
526 * Data Router Subscriber HTTPS Relaxation feature USERSTORYID:US674047. Load mail properties.
530 private void loadMailProperties() {
531 if (mailprops == null) {
532 mailprops = new Properties();
533 InputStream inStream = getClass().getClassLoader().getResourceAsStream(MAILCONFIG_FILE);
535 mailprops.load(inStream);
536 } catch (IOException e) {
537 intlogger.fatal("PROV9003 Opening properties: " + e.getMessage());
542 } catch (IOException e) {
549 * Data Router Subscriber HTTPS Relaxation feature USERSTORYID:US674047. Check if HTTPS Relexaction is enabled
553 private void checkHttpsRelaxation() {
555 Properties p = (new DB()).getProperties();
556 intlogger.info("HTTPS relaxation: " + p.get("org.onap.dmaap.datarouter.provserver.https.relaxation"));
558 if (p.get("org.onap.dmaap.datarouter.provserver.https.relaxation").equals("true")) {
560 notifyPSTeam(p.get("org.onap.dmaap.datarouter.provserver.https.relax.notify").toString());
561 } catch (Exception e) {
562 intlogger.warn("Exception: " + e.getMessage());
570 * Data Router Subscriber HTTPS Relaxation feature USERSTORYID:US674047.
572 * @param email - list of email ids to notify if HTTP relexcation is enabled.
575 private void notifyPSTeam(String email) throws Exception {
576 loadMailProperties(); //Load HTTPS Relex mail properties.
577 String[] emails = email.split(Pattern.quote("|"));
579 Properties mailproperties = new Properties();
580 mailproperties.put("mail.smtp.host", mailprops.get("com.att.dmaap.datarouter.mail.server"));
581 mailproperties.put("mail.transport.protocol", mailprops.get("com.att.dmaap.datarouter.mail.protocol"));
583 Session session = Session.getDefaultInstance(mailproperties, null);
584 Multipart mp = new MimeMultipart();
585 MimeBodyPart htmlPart = new MimeBodyPart();
589 Message msg = new MimeMessage(session);
590 msg.setFrom(new InternetAddress(mailprops.get("com.att.dmaap.datarouter.mail.from").toString()));
592 InternetAddress[] addressTo = new InternetAddress[emails.length];
593 for (int x = 0; x < emails.length; x++) {
594 addressTo[x] = new InternetAddress(emails[x]);
597 msg.addRecipients(Message.RecipientType.TO, addressTo);
598 msg.setSubject(mailprops.get("com.att.dmaap.datarouter.mail.subject").toString());
599 htmlPart.setContent(mailprops.get("com.att.dmaap.datarouter.mail.body").toString()
600 .replace("[SERVER]", InetAddress.getLocalHost().getHostName()), "text/html");
601 mp.addBodyPart(htmlPart);
604 System.out.println(mailprops.get("com.att.dmaap.datarouter.mail.body").toString()
605 .replace("[SERVER]", InetAddress.getLocalHost().getHostName()));
608 intlogger.info("HTTPS relaxation mail is sent to - : " + email);
610 } catch (AddressException e) {
611 intlogger.error("Invalid email address, unable to send https relaxation mail to - : " + email);
612 } catch (MessagingException e) {
613 intlogger.error("Invalid email address, unable to send https relaxation mail to - : " + email);
617 public static String getProvName() {
621 public static String getActiveProvName() {
622 return activeProvName;
626 * Get an array of all node names in the DR network.
628 * @return an array of Strings
630 public static String[] getNodes() {
635 * Get an array of all node InetAddresses in the DR network.
637 * @return an array of InetAddresses
639 public static InetAddress[] getNodeAddresses() {
640 return nodeAddresses;
644 * Get an array of all POD names in the DR network.
646 * @return an array of Strings
648 public static String[] getPods() {
649 return new String[]{initialActivePod, initialStandbyPod};
653 * Get an array of all POD InetAddresses in the DR network.
655 * @return an array of InetAddresses
657 private static InetAddress[] getPodAddresses() {
662 * Gets the FQDN of the initially ACTIVE provisioning server (POD). Note: this used to be called isActivePOD(),
663 * however, that is a misnomer, as the active status could shift to the standby POD without these parameters
664 * changing. Hence, the function names have been changed to more accurately reflect their purpose.
668 public static boolean isInitialActivePOD() {
669 return thisPod.equals(initialActivePod);
673 * Gets the FQDN of the initially STANDBY provisioning server (POD). Note: this used to be called isStandbyPOD(),
674 * however, that is a misnomer, as the standby status could shift to the active POD without these parameters
675 * changing. Hence, the function names have been changed to more accurately reflect their purpose.
679 public static boolean isInitialStandbyPOD() {
680 return thisPod.equals(initialStandbyPod);
684 * INSERT an {@link Insertable} bean into the database.
686 * @param bean the bean representing a row to insert
687 * @return true if the INSERT was successful
689 protected boolean doInsert(Insertable bean) {
692 Connection conn = null;
694 conn = db.getConnection();
695 rv = bean.doInsert(conn);
696 } catch (SQLException e) {
698 intlogger.warn("PROV0005 doInsert: " + e.getMessage());
708 * UPDATE an {@link Updateable} bean in the database.
710 * @param bean the bean representing a row to update
711 * @return true if the UPDATE was successful
713 protected boolean doUpdate(Updateable bean) {
716 Connection conn = null;
718 conn = db.getConnection();
719 rv = bean.doUpdate(conn);
720 } catch (SQLException e) {
722 intlogger.warn("PROV0006 doUpdate: " + e.getMessage());
732 * DELETE an {@link Deleteable} bean from the database.
734 * @param bean the bean representing a row to delete
735 * @return true if the DELETE was successful
737 protected boolean doDelete(Deleteable bean) {
740 Connection conn = null;
742 conn = db.getConnection();
743 rv = bean.doDelete(conn);
744 } catch (SQLException e) {
746 intlogger.warn("PROV0007 doDelete: " + e.getMessage());
755 private static boolean getBoolean(Map<String, String> map, String name) {
756 String s = map.get(name);
757 return (s != null) && s.equalsIgnoreCase("true");
760 private static String getString(Map<String, String> map, String name, String dflt) {
761 String s = map.get(name);
762 return (s != null) ? s : dflt;
765 private static int getInt(Map<String, String> map, String name, int dflt) {
767 String s = map.get(name);
768 return Integer.parseInt(s);
769 } catch (NumberFormatException e) {
774 private static Set<String> getSet(Map<String, String> map, String name) {
775 Set<String> set = new HashSet<>();
776 String s = map.get(name);
778 String[] pp = s.split("\\|");
780 for (String t : pp) {
781 String t2 = t.trim();
782 if (t2.length() > 0) {
792 * A class used to encapsulate a Content-type header, separating out the "version" attribute (which defaults to
795 public class ContentHeader {
797 private String type = "";
798 private Map<String, String> map = new HashMap<>();
804 ContentHeader(String t, String v) {
806 map.put("version", v);
809 public String getType() {
813 public String getAttribute(String key) {
814 String s = map.get(key);
823 * Get the ContentHeader from an HTTP request.
825 * @param req the request
826 * @return the header, encapsulated in a ContentHeader object
828 ContentHeader getContentHeader(HttpServletRequest req) {
829 ContentHeader ch = new ContentHeader();
830 String s = req.getHeader("Content-Type");
832 String[] pp = s.split(";");
833 ch.type = pp[0].trim();
834 for (int i = 1; i < pp.length; i++) {
835 int ix = pp[i].indexOf('=');
837 String k = pp[i].substring(0, ix).trim();
838 String v = pp[i].substring(ix + 1).trim();
841 ch.map.put(pp[i].trim(), "");
848 // Methods for the Policy Engine classes - ProvDataProvider interface
850 public String getFeedOwner(String feedId) {
852 int n = Integer.parseInt(feedId);
853 Feed f = Feed.getFeedById(n);
855 return f.getPublisher();
857 } catch (NumberFormatException e) {
864 public String getFeedClassification(String feedId) {
866 int n = Integer.parseInt(feedId);
867 Feed f = Feed.getFeedById(n);
869 return f.getAuthorization().getClassification();
871 } catch (NumberFormatException e) {
878 public String getSubscriptionOwner(String subId) {
880 int n = Integer.parseInt(subId);
881 Subscription s = Subscription.getSubscriptionById(n);
883 return s.getSubscriber();
885 } catch (NumberFormatException e) {
892 * @Method - isUserMemberOfGroup - Rally:US708115
893 * @Params - group object and user to check if exists in given group
894 * @return - boolean value /true/false
896 private boolean isUserMemberOfGroup(Group group, String user) {
898 String groupDetails = group.getMembers().replace("]", "").replace("[", "");
899 String[] s = groupDetails.split("},");
901 for (String value : s) {
904 jsonObj = new JSONObject(value + "}");
905 if (jsonObj.get("id").equals(user)) {
908 } catch (JSONException e) {
909 intlogger.error("JSONException: " + e.getMessage());
917 * @Method - getGroupByFeedGroupId- Rally:US708115
918 * @Params - User to check in group and feedid which is assigned the group.
919 * @return - string value grupid/null
922 public String getGroupByFeedGroupId(String owner, String feedId) {
924 int n = Integer.parseInt(feedId);
925 Feed f = Feed.getFeedById(n);
927 int groupid = f.getGroupid();
929 Group group = Group.getGroupById(groupid);
930 assert group != null;
931 if (isUserMemberOfGroup(group, owner)) {
932 return group.getAuthid();
936 } catch (NumberFormatException e) {
943 * @Method - getGroupBySubGroupId - Rally:US708115
944 * @Params - User to check in group and subid which is assigned the group.
945 * @return - string value grupid/null
948 public String getGroupBySubGroupId(String owner, String subId) {
950 int n = Integer.parseInt(subId);
951 Subscription s = Subscription.getSubscriptionById(n);
953 int groupid = s.getGroupid();
955 Group group = Group.getGroupById(groupid);
956 assert group != null;
957 if (isUserMemberOfGroup(group, owner)) {
958 return group.getAuthid();
962 } catch (NumberFormatException e) {
969 * @Method - setIpAndFqdnForEelf - Rally:US664892
970 * @Params - method, prints method name in EELF log.
972 void setIpAndFqdnForEelf(String method) {
974 MDC.put(MDC_SERVICE_NAME, method);
976 MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
977 MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
978 } catch (Exception e) {
979 intlogger.error("Exception: " + e.getMessage());