Changes made to upgrade pom version
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / utils / EcompPortalUtils.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalapp.portal.utils;
39
40 import java.io.IOException;
41 import java.net.InetAddress;
42 import java.net.UnknownHostException;
43 import java.nio.charset.Charset;
44 import java.text.SimpleDateFormat;
45 import java.util.ArrayList;
46 import java.util.Arrays;
47 import java.util.Base64;
48 import java.util.Date;
49 import java.util.List;
50 import java.util.regex.Pattern;
51
52 import javax.servlet.http.HttpServletResponse;
53 import javax.xml.bind.DatatypeConverter;
54
55 import org.apache.commons.codec.binary.Hex;
56 import org.apache.commons.lang.StringUtils;
57 import org.hibernate.Session;
58 import org.hibernate.Transaction;
59 import org.onap.portalapp.portal.domain.EPUser;
60 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
61 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
62 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
63 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
64 import org.onap.portalsdk.core.util.SystemProperties;
65 import org.slf4j.MDC;
66 import org.springframework.http.HttpHeaders;
67 import org.springframework.http.MediaType;
68
69 import com.fasterxml.jackson.core.JsonProcessingException;
70 import com.fasterxml.jackson.databind.ObjectMapper;
71
72 public class EcompPortalUtils {
73
74         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class);
75
76         private static final String FUNCTION_PIPE = "|";
77
78         // TODO: GLOBAL_LOGIN_URL is the same as in SessionTimeoutInterceptor.
79         // It should be defined in SystemProperties.
80         private static final String GLOBAL_LOGIN_URL = "global-login-url";
81
82         // It is a regular expression used for while creating a External Central Auth
83         // Role
84         public static final String EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS = "([^A-Z^a-z^0-9^\\.^%^(^)^=^:])";
85
86         public static final String slash = "/";
87
88         /**
89          * @param orgUserId User ID to validate
90          * @return true if orgUserId is not empty and contains only alphanumeric, false
91          *         otherwise
92          */
93         public static boolean legitimateUserId(String orgUserId) {
94                 return orgUserId.matches("^[a-zA-Z0-9/_/-/@]+$");
95         }
96
97         /**
98          * Splits the string into a list of tokens using the specified regular
99          * expression
100          * 
101          * @param source String to split
102          * @param regex  tokens
103          * @return List of tokens split from the source
104          */
105         public static List<String> parsingByRegularExpression(String source, String regex) {
106                 List<String> tokens = new ArrayList<String>();
107                 if (source != null && source.length() > 0) {
108                         String[] parsed = source.split(regex);
109                         for (String token : parsed) {
110                                 if (token.length() > 0) {
111                                         tokens.add(token);
112                                 }
113                         }
114                 }
115                 return tokens;
116         }
117
118         /**
119          * Builds a JSON object with error code and message information.
120          * 
121          * @param errorCode    error code
122          * @param errorMessage message
123          * @return JSON object as a String
124          */
125         public static String jsonErrorMessageResponse(int errorCode, String errorMessage) {
126                 return "{\"error\":{\"code\":" + errorCode + "," + "\"message\":\"" + errorMessage + "\"}}";
127         }
128
129         /**
130          * Builds a JSON object with the specified message
131          * 
132          * @param message Message to embed
133          * @return JSON object as a String
134          */
135         public static String jsonMessageResponse(String message) {
136                 return String.format("{\"message\":\"%s\"}", message);
137         }
138
139         /**
140          * Serializes the specified object as JSON and writes the result to the debug
141          * log. If serialization fails, logs a message to the error logger.
142          * 
143          * @param logger Logger for the class where the object was built; the logger
144          *               carries the class name.
145          * @param source First portion of the log message
146          * @param msg    Second portion of the log message
147          * @param obj    Object to serialize as JSON
148          */
149         public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) {
150                 try {
151                         String objectAsJson = new ObjectMapper().writeValueAsString(obj);
152                         logger.debug(EELFLoggerDelegate.debugLogger,
153                                         String.format("source= [%s]; %s [%s];", source, msg, objectAsJson));
154                 } catch (JsonProcessingException e) {
155                         logger.warn(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed to serialize", e);
156                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
157                 } catch (Exception e) {
158                         logger.error(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed", e);
159                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
160                 }
161         }
162
163         /**
164          * Serializes the specified object as JSON and writes the result to the debug
165          * log. If serialization fails, logs a message to the error logger.
166          * 
167          * @param source First portion of the log message
168          * @param msg    Second portion of the log message
169          * @param obj    Object to serialize as JSON
170          */
171         public static void logAndSerializeObject(String source, String msg, Object obj) {
172                 logAndSerializeObject(logger, source, msg, obj);
173         }
174
175         public static void rollbackTransaction(Transaction transaction, String errorMessage) {
176                 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
177                 try {
178                         if (transaction != null) {
179                                 transaction.rollback();
180                         }
181                 } catch (Exception e) {
182                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
183                         logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing a rollback transaction",
184                                         e);
185                 }
186         }
187
188         public static void closeLocalSession(Session localSession, String errorMessage) {
189                 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
190                 try {
191                         if (localSession != null) {
192                                 localSession.close();
193                         }
194                 } catch (Exception e) {
195                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
196                         logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception", e);
197                 }
198         }
199
200         /**
201          * Set response status to Unauthorized if user == null and to Forbidden in all
202          * (!) other cases. Logging is not performed if invocator == null
203          * 
204          * @param user      User object
205          * @param response  HttpServletResponse
206          * @param invocator may be null
207          */
208         public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) {
209                 if (user == null) {
210                         String loginUrl = SystemProperties.getProperty(EPCommonSystemProperties.LOGIN_URL_NO_RET_VAL);
211                         response.setHeader(GLOBAL_LOGIN_URL, loginUrl);
212                         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
213                         MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_UNAUTHORIZED));
214                 } else {
215                         response.setStatus(HttpServletResponse.SC_FORBIDDEN);
216                         MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN));
217                 }
218                 if (invocator != null) {
219                         logger.warn(EELFLoggerDelegate.errorLogger,
220                                         invocator + ", permissions problem, response status = " + response.getStatus());
221                 }
222         }
223
224         public static int getExternalAppResponseCode() {
225                 String responseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
226                 int responseCodeInt = 0;
227                 try {
228                         if (responseCode != null && responseCode != "") {
229                                 responseCodeInt = Integer.valueOf(responseCode);
230                         }
231                 } catch (Exception e) {
232                         logger.error(EELFLoggerDelegate.errorLogger, "getExternalAppResponseCode failed", e);
233                 }
234                 return responseCodeInt;
235         }
236
237         // This method might be just for testing purposes.
238         public static void setExternalAppResponseCode(int responseCode) {
239                 try {
240                         /*
241                          * String code = String.valueOf(responseCode);
242                          * MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code );
243                          * code=StringUtils.EMPTY;
244                          */
245                         String code = Integer.toString(responseCode);
246                         MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, code);
247                         char[] chars = code.toCharArray();
248                         Arrays.fill(chars, ' ');
249                 } catch (Exception e) {
250                         logger.error(EELFLoggerDelegate.errorLogger, "setExternalAppResponseCode failed", e);
251                 }
252         }
253
254         public static String getHTTPStatusString(int httpStatusCode) {
255                 String httpStatusString = "unknown_error";
256                 try {
257                         httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
258                         if (httpStatusString != null) {
259                                 httpStatusString = httpStatusString.toLowerCase();
260                         }
261                 } catch (Exception e) {
262                         logger.error(EELFLoggerDelegate.errorLogger, "getHTTPStatusString failed", e);
263                 }
264                 return httpStatusString;
265         }
266
267         public static String getFEErrorString(Boolean internal, int responseCode) {
268                 // Return a String like the following:
269                 // "Internal Onap Error: 500 internal_server_error" or
270                 // "External App Error: 404 not_found"
271                 // TODO: create our own Ecomp error codes, starting with 1000 and up.
272                 String internalExternalString = internal ? "Ecomp Error: " : "App Error: ";
273                 String httpStatusString = "unknown_error";
274                 try {
275                         if (responseCode < 1000) {
276                                 httpStatusString = getHTTPStatusString(responseCode);
277                         }
278                 } catch (Exception e) {
279                         logger.error(EELFLoggerDelegate.errorLogger, "getFEErrorString failed", e);
280                 }
281                 String responseString = internalExternalString + responseCode + " " + httpStatusString;
282                 return responseString;
283         }
284
285         public static boolean isProductionBuild() {
286                 boolean productionBuild = true;
287                 String epVersion = EcompVersion.buildNumber;
288                 if (epVersion != null) {
289                         int buildNum = epVersion.lastIndexOf('.');
290                         if (buildNum > 0) {
291                                 int buildNumber = Integer.parseInt(epVersion.substring(buildNum + 1));
292                                 if (buildNumber < 3000) // Production versions are 3000+, (ie
293                                                                                 // 1.0.3003)
294                                 {
295                                         productionBuild = false;
296                                 }
297                         }
298                 }
299                 return productionBuild;
300         }
301
302         public static String getMyIpAdddress() {
303                 InetAddress ip;
304                 String localIp;
305                 try {
306                         ip = InetAddress.getLocalHost();
307                         localIp = ip.getHostAddress();
308                 } catch (UnknownHostException e) {
309                         localIp = "unknown";
310                         logger.error(EELFLoggerDelegate.errorLogger, "getMyIpAdddress failed ", e);
311                 }
312                 return localIp;
313         }
314
315         public static String getMyHostName() {
316                 InetAddress ip;
317                 String hostName;
318                 try {
319                         ip = InetAddress.getLocalHost();
320                         hostName = ip.getHostName();
321                 } catch (UnknownHostException e) {
322                         hostName = "unknown";
323                         logger.error(EELFLoggerDelegate.errorLogger, "getMyHostName failed", e);
324                 }
325                 return hostName;
326         }
327
328         /**
329          * Returns a default property if the expected one is not available
330          * 
331          * @param property     Key
332          * @param defaultValue default Value
333          * @return Default value if property is not defined or yields the empty string;
334          *         else the property value.
335          */
336         public static String getPropertyOrDefault(String property, String defaultValue) {
337                 if (!SystemProperties.containsProperty(property))
338                         return defaultValue;
339                 String value = SystemProperties.getProperty(property);
340                 if (value == null || "".equals(value))
341                         return defaultValue;
342                 return value;
343         }
344
345         /**
346          * Calculates the time duration of a function call for logging purpose. It
347          * stores the result by using "MDC.put(SystemProperties.MDC_TIMER,
348          * timeDifference);" It is important to call
349          * "MDC.remove(SystemProperties.MDC_TIMER);" after this method call to clean up
350          * the record in MDC
351          *
352          * @param beginDateTime the given begin time for the call
353          * @param endDateTime   the given end time for the call
354          * 
355          */
356         public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) {
357                 if (beginDateTime != null && endDateTime != null) {
358                         try {
359                                 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
360
361                                 Date beginDate = ecompLogDateFormat.parse(beginDateTime);
362                                 Date endDate = ecompLogDateFormat.parse(endDateTime);
363                                 String timeDifference = String.format("%d", endDate.getTime() - beginDate.getTime());
364                                 MDC.put(SystemProperties.MDC_TIMER, timeDifference);
365                         } catch (Exception e) {
366                                 logger.error(EELFLoggerDelegate.errorLogger, "calculateDateTimeDifferenceForLog failed", e);
367                         }
368                 }
369         }
370
371         /**
372          * Answers the protocol to use.
373          * 
374          * @return Protocol name from property file; defaults to https.
375          */
376         public static String widgetMsProtocol() {
377                 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_PROTOCOL, "https");
378         }
379         
380         /**
381          * Answers the protocol to use.
382          * 
383          * @return Protocol name from property file; defaults to https.
384          */
385         public static String widgetMLProtocol() {
386                 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_ML_PROTOCOL, "https");
387         }
388
389         /**
390          * Answers the host to use.
391          * 
392          * @return Host name from property file; defaults to localhost.
393          */
394         public static String localOrDockerHost() {
395                 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_HOSTNAME, "localhost");
396         }
397         
398         /**
399          * Answers the host to use.
400          * 
401          * @return Host name from property file; defaults to localhost.
402          */
403         public static String mlLocalOrDockerHost() {
404                 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_ML_HOSTNAME, "localhost");
405         }
406
407         /**
408          * It returns headers where username and password of external central auth is
409          * encoded to base64
410          * 
411          * @return header which contains external central auth username and password
412          *         base64 encoded
413          * @throws Exception if unable to decrypt the password
414          */
415         public static HttpHeaders base64encodeKeyForAAFBasicAuth() throws Exception {
416                 String userName = "";
417                 String decryptedPass = "";
418                 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME)
419                                 && EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD)) {
420                         decryptedPass = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD);
421                         userName = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
422                 }
423                 String decPass = decrypted(decryptedPass);
424                 String usernamePass = userName + ":" + decPass;
425                 String encToBase64 = String.valueOf((DatatypeConverter.printBase64Binary(usernamePass.getBytes())));
426                 HttpHeaders headers = new HttpHeaders();
427                 headers.add("Authorization", "Basic " + encToBase64);
428                 headers.setContentType(MediaType.APPLICATION_JSON);
429                 return headers;
430         }
431
432         private static String decrypted(String encrypted) throws Exception {
433                 String result = "";
434                 if (encrypted != null && encrypted.length() > 0) {
435                         try {
436                                 result = CipherUtil.decryptPKC(encrypted,
437                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
438                         } catch (Exception e) {
439                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
440                                 throw e;
441                         }
442                 }
443                 return result;
444         }
445
446         public static String truncateString(String originString, int size) {
447                 if (originString.length() >= size) {
448                         StringBuilder stringBuilder = new StringBuilder();
449                         stringBuilder.append(originString);
450                         stringBuilder.setLength(size);
451                         stringBuilder.append("...");
452                         return stringBuilder.toString();
453                 }
454                 return originString;
455         }
456
457         /**
458          * 
459          * If function code value has any pipes it does pipe filter and returns value.
460          * 
461          * @param functionCode
462          * @return function instance without pipe
463          */
464         public static String getFunctionCode(String functionCode) {
465                 String finalFunctionCodeVal = "";
466                 if (functionCode.contains(FUNCTION_PIPE)) {
467                         int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
468                         if (count == 2)
469                                 finalFunctionCodeVal = functionCode.substring(functionCode.indexOf(FUNCTION_PIPE) + 1,
470                                                 functionCode.lastIndexOf(FUNCTION_PIPE));
471                         else
472                                 finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
473                 } else {
474                         finalFunctionCodeVal = functionCode;
475                 }
476                 return finalFunctionCodeVal;
477         }
478
479         /**
480          * 
481          * If function code value has any pipes it does pipe filter and returns value.
482          * 
483          * @param functionCode
484          * @return function Type without pipe
485          */
486         public static String getFunctionType(String functionCode) {
487                 String finalFunctionCodeVal = "";
488                 if (functionCode.contains(FUNCTION_PIPE)) {
489                         int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
490                         if (count == 2) {
491                                 String[] getTypeValue = functionCode.split("\\" + FUNCTION_PIPE);
492                                 finalFunctionCodeVal = getTypeValue[0];
493                         }
494                 } else {
495                         finalFunctionCodeVal = functionCode;
496                 }
497                 return finalFunctionCodeVal;
498         }
499
500         /**
501          * 
502          * If function code value has any pipes it does pipe filter and returns value.
503          * 
504          * @param functionCode
505          * @return function Action without pipe
506          */
507         public static String getFunctionAction(String functionCode) {
508                 String finalFunctionCodeVal = "";
509                 if (functionCode.contains(FUNCTION_PIPE)) {
510                         int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
511                         if (count == 2)
512                                 finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
513                 } else {
514                         finalFunctionCodeVal = functionCode;
515                 }
516                 return finalFunctionCodeVal;
517         }
518
519         /**
520          * 
521          * It check whether the external auth namespace is matching with current
522          * namespace exists in local DB
523          * 
524          * @param permTypeVal
525          * @param appNamespaceVal
526          * @return true or false
527          */
528         public static boolean checkNameSpaceMatching(String permTypeVal, String appNamespaceVal) {
529                 String[] typeNamespace = permTypeVal.split("\\.");
530                 String[] appNamespace = appNamespaceVal.split("\\.");
531                 boolean isNamespaceMatching = true;
532                 if (appNamespace.length <= typeNamespace.length) {
533                         for (int k = 0; k < appNamespace.length; k++) {
534                                 if (!appNamespace[k].equals(typeNamespace[k]))
535                                         isNamespaceMatching = false;
536                         }
537                 } else {
538                         isNamespaceMatching = false;
539                 }
540                 return isNamespaceMatching;
541         }
542
543         public static boolean checkIfRemoteCentralAccessAllowed() {
544                 boolean result = false;
545                 String rmtCentralAccess = SystemProperties
546                                 .getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS);
547                 if (rmtCentralAccess == null) {
548                         logger.error(EELFLoggerDelegate.errorLogger,
549                                         "Please check in system.properties whether the property exists or not!");
550                         return false;
551                 } else if (new Boolean(rmtCentralAccess)) {
552                         logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}", rmtCentralAccess);
553                         result = true;
554                 }
555                 return result;
556         }
557
558         /**
559          * 
560          * It validates whether given string is JSON or not
561          * 
562          * @param jsonInString
563          * @return true or false
564          */
565         public static boolean isJSONValid(String jsonInString) {
566                 try {
567                         final ObjectMapper mapper = new ObjectMapper();
568                         mapper.readTree(jsonInString);
569                         return true;
570                 } catch (IOException e) {
571                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e);
572                         return false;
573                 }
574         }
575
576         /**
577          * 
578          * It retrieves account information from input String
579          * 
580          * @param authValue
581          * @return Array of Account information
582          * 
583          */
584         public static String[] getUserNamePassword(String authValue) {
585                 String base64Credentials = authValue.substring("Basic".length()).trim();
586                 String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
587                 final String[] values = credentials.split(":", 2);
588                 return values;
589         }
590
591         /**
592          * It encodes the function code based on Hex encoding
593          * 
594          * @param funCode
595          * 
596          */
597         public static String encodeFunctionCode(String funCode) {
598                 String encodedString = funCode;
599                 Pattern encodePattern = Pattern.compile(EcompPortalUtils.slash);
600                 return encodedString = encodePattern.matcher(encodedString)
601                                 .replaceAll("%" + Hex.encodeHexString(encodePattern.toString().getBytes()))
602                                 .replaceAll("\\*", "%" + Hex.encodeHexString("*".getBytes()));
603         }
604
605         public static boolean checkFunctionCodeHasEncodePattern(String code) {
606                 return code.contains(EcompPortalUtils.slash);
607         }
608
609 }