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