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