[MR] Add support for configuring jaas.sasl.config at runtime
[dmaap/messagerouter/messageservice.git] / src / main / java / org / onap / dmaap / dmf / mr / utils / Utils.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  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *  ============LICENSE_END=========================================================
18  *
19  *  ECOMP is a trademark and service mark of AT&T Intellectual Property.
20  *
21  *******************************************************************************/
22 package org.onap.dmaap.dmf.mr.utils;
23
24 import com.att.eelf.configuration.EELFLogger;
25 import com.att.eelf.configuration.EELFManager;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.security.Principal;
29 import java.text.DecimalFormat;
30 import java.text.SimpleDateFormat;
31 import java.util.*;
32 import javax.servlet.http.HttpServletRequest;
33 import org.apache.kafka.clients.admin.AdminClientConfig;
34 import org.onap.dmaap.dmf.mr.beans.DMaaPContext;
35
36 /**
37  * This is an utility class for various operations for formatting
38  * @author nilanjana.maity
39  *
40  */
41 public class Utils {
42
43         private static final String DATE_FORMAT = "dd-MM-yyyy::hh:mm:ss:SSS";
44         public static final String CAMBRIA_AUTH_HEADER = "X-CambriaAuth";
45         private static final String AUTH_HEADER = "Authorization";
46         private static final String BATCH_ID_FORMAT = "000000";
47         private static final String X509_ATTR = "javax.servlet.request.X509Certificate";
48         private static final EELFLogger log = EELFManager.getInstance().getLogger(Utils.class);
49         public static final String SASL_MECH = "sasl.mechanism";
50
51         private Utils() {
52                 super();
53         }
54
55         /**
56          * Formatting the date
57          * @param date
58          * @return date or null
59          */
60         public static String getFormattedDate(Date date) {
61                 SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
62                 if (null != date){
63                         return sdf.format(date);
64                 }
65                 return null;
66         }
67         /**
68          * to get the details of User Api Key
69          * @param request
70          * @return authkey or null
71          */
72         public static String getUserApiKey(HttpServletRequest request) {
73                 final String auth = request.getHeader(CAMBRIA_AUTH_HEADER);
74                 if (null != auth) {
75                         final String[] splittedAuthKey = auth.split(":");
76                         return splittedAuthKey[0];
77                 }else if (null != request.getHeader(AUTH_HEADER) || null != request.getAttribute(X509_ATTR)){
78                         /**
79                          * AAF implementation enhancement
80                          */
81                         Principal principal = request.getUserPrincipal();
82                         if(principal != null){
83                                 String name = principal.getName();
84                                 return name.substring(0, name.lastIndexOf('@'));
85                         }
86                         log.warn("No principal has been provided on HTTP request");
87                 }
88                 return null;
89         }
90
91
92         /**
93          * to format the batch sequence id
94          * @param batchId
95          * @return batchId
96          */
97         public static String getFromattedBatchSequenceId(Long batchId) {
98                 DecimalFormat format = new DecimalFormat(BATCH_ID_FORMAT);
99                 return format.format(batchId);
100         }
101
102         /**
103          * to get the message length in bytes
104          * @param message
105          * @return bytes or 0
106          */
107         public static long messageLengthInBytes(String message) {
108                 if (null != message) {
109                         return message.getBytes().length;
110                 }
111                 return 0;
112         }
113         /**
114          * To get transaction id details
115          * @param transactionId
116          * @return transactionId or null
117          */
118         public static String getResponseTransactionId(String transactionId) {
119                 if (null != transactionId && !transactionId.isEmpty()) {
120                         return transactionId.substring(0, transactionId.lastIndexOf("::"));
121                 }
122                 return null;
123         }
124
125         /**
126          * get the thread sleep time
127          * @param ratePerMinute
128          * @return ratePerMinute or 0
129          */
130         public static long getSleepMsForRate ( double ratePerMinute )
131         {
132                 if ( ratePerMinute <= 0.0 )
133                 {
134                         return 0;
135                 }
136                 return Math.max ( 1000, Math.round ( 60 * 1000 / ratePerMinute ) );
137         }
138
139         public static String getRemoteAddress(DMaaPContext ctx)
140         {
141                 String reqAddr = ctx.getRequest().getRemoteAddr();
142                 String fwdHeader = getFirstHeader("X-Forwarded-For",ctx);
143                 return ((fwdHeader != null) ? fwdHeader : reqAddr);
144         }
145         public static String getFirstHeader(String h,DMaaPContext ctx)
146         {
147                 List l = getHeader(h,ctx);
148                 return ((l.size() > 0) ? (String)l.iterator().next() : null);
149         }
150         public static List<String> getHeader(String h,DMaaPContext ctx)
151         {
152                 LinkedList list = new LinkedList();
153                 Enumeration e = ctx.getRequest().getHeaders(h);
154                 while (e.hasMoreElements())
155                 {
156                         list.add(e.nextElement().toString());
157                 }
158                 return list;
159         }
160
161         public static String getKafkaproperty(){
162                 InputStream input = new Utils().getClass().getResourceAsStream("/kafka.properties");
163                 Properties props = new Properties();
164                 try {
165                         props.load(input);
166                 } catch (IOException e) {
167                         log.error("failed to read kafka.properties");
168                 }
169                 return props.getProperty("key");
170
171
172         }
173
174         public static boolean isCadiEnabled(){
175                 boolean enableCadi=false;
176                 if(System.getenv("enableCadi")!=null&&System.getenv("enableCadi").equals("true")){
177                         enableCadi=true;
178                 }
179
180                 return enableCadi;
181         }
182
183         public static Properties addSaslProps(){
184                 Properties props = new Properties();
185                 String saslMech = System.getenv("SASLMECH");
186                 if (saslMech != null && saslMech.equals("scram-sha-512")) {
187                         props.put("sasl.jaas.config", System.getenv("JAASLOGIN"));
188                         props.put(SASL_MECH, saslMech.toUpperCase());
189                 }
190                 else {
191                         props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username='admin' password='" + getKafkaproperty() + "';");
192                         props.put(SASL_MECH, "PLAIN");
193                 }
194                 props.put(AdminClientConfig.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
195                 log.info("KafkaAdmin sasl.mechanism set to " + props.getProperty(SASL_MECH));
196                 return props;
197
198         }
199 }