Ecomp DTO up
[portal.git] / portal-BE / src / main / java / org / onap / portal / utils / EcompPortalUtils.java
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ===================================================================
9  *
10  * Unless otherwise specified, all software contained herein is licensed
11  * under the Apache License, Version 2.0 (the "License");
12  * you may not use this software except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * Unless otherwise specified, all documentation contained herein is licensed
24  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25  * you may not use this documentation except in compliance with the License.
26  * You may obtain a copy of the License at
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
30  * Unless required by applicable law or agreed to in writing, documentation
31  * distributed under the License is distributed on an "AS IS" BASIS,
32  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33  * See the License for the specific language governing permissions and
34  * limitations under the License.
35  *
36  * ============LICENSE_END============================================
37  *
38  *
39  */
40
41 package org.onap.portal.utils;
42
43 import com.fasterxml.jackson.core.JsonProcessingException;
44 import com.fasterxml.jackson.databind.ObjectMapper;
45 import java.io.IOException;
46 import java.net.InetAddress;
47 import java.net.UnknownHostException;
48 import java.nio.charset.Charset;
49 import java.text.SimpleDateFormat;
50 import java.util.ArrayList;
51 import java.util.Arrays;
52 import java.util.Base64;
53 import java.util.Date;
54 import java.util.List;
55 import java.util.regex.Pattern;
56 import javax.servlet.http.HttpServletResponse;
57 import javax.xml.bind.DatatypeConverter;
58 import org.apache.commons.codec.binary.Hex;
59 import org.apache.commons.lang.StringUtils;
60 import org.hibernate.Session;
61 import org.hibernate.Transaction;
62 import org.onap.portal.domain.db.fn.FnUser;
63 import org.onap.portal.logging.format.EPAppMessagesEnum;
64 import org.onap.portal.logging.logic.EPLogUtil;
65 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
66 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
67 import org.onap.portalsdk.core.util.SystemProperties;
68 import org.slf4j.MDC;
69 import org.springframework.http.HttpHeaders;
70 import org.springframework.http.MediaType;
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(FnUser 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 host to use.
382          * 
383          * @return Host name from property file; defaults to localhost.
384          */
385         public static String localOrDockerHost() {
386                 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_HOSTNAME, "localhost");
387         }
388
389         /**
390          * It returns headers where username and password of external central auth is
391          * encoded to base64
392          * 
393          * @return header which contains external central auth username and password
394          *         base64 encoded
395          * @throws Exception if unable to decrypt the password
396          */
397         public static HttpHeaders base64encodeKeyForAAFBasicAuth() throws Exception {
398                 String userName = "";
399                 String decryptedPass = "";
400                 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME)
401                                 && EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD)) {
402                         decryptedPass = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD);
403                         userName = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
404                 }
405                 String decPass = decrypted(decryptedPass);
406                 String usernamePass = userName + ":" + decPass;
407                 String encToBase64 = String.valueOf((DatatypeConverter.printBase64Binary(usernamePass.getBytes())));
408                 HttpHeaders headers = new HttpHeaders();
409                 headers.add("Authorization", "Basic " + encToBase64);
410                 headers.setContentType(MediaType.APPLICATION_JSON);
411                 return headers;
412         }
413
414         private static String decrypted(String encrypted) throws Exception {
415                 String result = "";
416                 if (encrypted != null && encrypted.length() > 0) {
417                         try {
418                                 result = CipherUtil.decryptPKC(encrypted,
419                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
420                         } catch (Exception e) {
421                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
422                                 throw e;
423                         }
424                 }
425                 return result;
426         }
427
428         public static String truncateString(String originString, int size) {
429                 if (originString.length() >= size) {
430                         StringBuilder stringBuilder = new StringBuilder();
431                         stringBuilder.append(originString);
432                         stringBuilder.setLength(size);
433                         stringBuilder.append("...");
434                         return stringBuilder.toString();
435                 }
436                 return originString;
437         }
438
439         /**
440          * 
441          * If function code value has any pipes it does pipe filter and returns value.
442          * 
443          * @param functionCode
444          * @return function instance without pipe
445          */
446         public static String getFunctionCode(String functionCode) {
447                 String finalFunctionCodeVal = "";
448                 if (functionCode.contains(FUNCTION_PIPE)) {
449                         int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
450                         if (count == 2)
451                                 finalFunctionCodeVal = functionCode.substring(functionCode.indexOf(FUNCTION_PIPE) + 1,
452                                                 functionCode.lastIndexOf(FUNCTION_PIPE));
453                         else
454                                 finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
455                 } else {
456                         finalFunctionCodeVal = functionCode;
457                 }
458                 return finalFunctionCodeVal;
459         }
460
461         /**
462          * 
463          * If function code value has any pipes it does pipe filter and returns value.
464          * 
465          * @param functionCode
466          * @return function Type without pipe
467          */
468         public static String getFunctionType(String functionCode) {
469                 String finalFunctionCodeVal = "";
470                 if (functionCode.contains(FUNCTION_PIPE)) {
471                         int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
472                         if (count == 2) {
473                                 String[] getTypeValue = functionCode.split("\\" + FUNCTION_PIPE);
474                                 finalFunctionCodeVal = getTypeValue[0];
475                         }
476                 } else {
477                         finalFunctionCodeVal = functionCode;
478                 }
479                 return finalFunctionCodeVal;
480         }
481
482         /**
483          * 
484          * If function code value has any pipes it does pipe filter and returns value.
485          * 
486          * @param functionCode
487          * @return function Action without pipe
488          */
489         public static String getFunctionAction(String functionCode) {
490                 String finalFunctionCodeVal = "";
491                 if (functionCode.contains(FUNCTION_PIPE)) {
492                         int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
493                         if (count == 2)
494                                 finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
495                 } else {
496                         finalFunctionCodeVal = functionCode;
497                 }
498                 return finalFunctionCodeVal;
499         }
500
501         /**
502          * 
503          * It check whether the external auth namespace is matching with current
504          * namespace exists in local DB
505          * 
506          * @param permTypeVal
507          * @param appNamespaceVal
508          * @return true or false
509          */
510         public static boolean checkNameSpaceMatching(String permTypeVal, String appNamespaceVal) {
511                 String[] typeNamespace = permTypeVal.split("\\.");
512                 String[] appNamespace = appNamespaceVal.split("\\.");
513                 boolean isNamespaceMatching = true;
514                 if (appNamespace.length <= typeNamespace.length) {
515                         for (int k = 0; k < appNamespace.length; k++) {
516                                 if (!appNamespace[k].equals(typeNamespace[k]))
517                                         isNamespaceMatching = false;
518                         }
519                 } else {
520                         isNamespaceMatching = false;
521                 }
522                 return isNamespaceMatching;
523         }
524
525         public static boolean checkIfRemoteCentralAccessAllowed() {
526                 boolean result = false;
527                 String rmtCentralAccess = SystemProperties
528                                 .getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS);
529                 if (rmtCentralAccess == null) {
530                         logger.error(EELFLoggerDelegate.errorLogger,
531                                         "Please check in system.properties whether the property exists or not!");
532                         return false;
533                 } else if (new Boolean(rmtCentralAccess)) {
534                         logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}", rmtCentralAccess);
535                         result = true;
536                 }
537                 return result;
538         }
539
540         /**
541          * 
542          * It validates whether given string is JSON or not
543          * 
544          * @param jsonInString
545          * @return true or false
546          */
547         public static boolean isJSONValid(String jsonInString) {
548                 try {
549                         final ObjectMapper mapper = new ObjectMapper();
550                         mapper.readTree(jsonInString);
551                         return true;
552                 } catch (IOException e) {
553                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e);
554                         return false;
555                 }
556         }
557
558         /**
559          * 
560          * It retrieves account information from input String
561          * 
562          * @param authValue
563          * @return Array of Account information
564          * 
565          */
566         public static String[] getUserNamePassword(String authValue) {
567                 String base64Credentials = authValue.substring("Basic".length()).trim();
568                 String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
569                 final String[] values = credentials.split(":", 2);
570                 return values;
571         }
572
573         /**
574          * It encodes the function code based on Hex encoding
575          * 
576          * @param funCode
577          * 
578          */
579         public static String encodeFunctionCode(String funCode) {
580                 String encodedString = funCode;
581                 Pattern encodePattern = Pattern.compile(EcompPortalUtils.slash);
582                 return encodedString = encodePattern.matcher(encodedString)
583                                 .replaceAll("%" + Hex.encodeHexString(encodePattern.toString().getBytes()))
584                                 .replaceAll("\\*", "%" + Hex.encodeHexString("*".getBytes()));
585         }
586
587         public static boolean checkFunctionCodeHasEncodePattern(String code) {
588                 return code.contains(EcompPortalUtils.slash);
589         }
590
591 }