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