2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ===================================================================
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
15 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
28 * https://creativecommons.org/licenses/by/4.0/
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.
36 * ============LICENSE_END============================================
41 package org.onap.portal.utils;
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;
69 import org.springframework.http.HttpHeaders;
70 import org.springframework.http.MediaType;
72 public class EcompPortalUtils {
74 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class);
76 private static final String FUNCTION_PIPE = "|";
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";
82 // It is a regular expression used for while creating a External Central Auth
84 public static final String EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS = "([^A-Z^a-z^0-9^\\.^%^(^)^=^:])";
86 public static final String slash = "/";
89 * @param orgUserId User ID to validate
90 * @return true if orgUserId is not empty and contains only alphanumeric, false
93 public static boolean legitimateUserId(String orgUserId) {
94 return orgUserId.matches("^[a-zA-Z0-9/_/-/@]+$");
98 * Splits the string into a list of tokens using the specified regular
101 * @param source String to split
102 * @param regex tokens
103 * @return List of tokens split from the source
105 public static List<String> parsingByRegularExpression(String source, String regex) {
106 List<String> tokens = new ArrayList<>();
107 if (source != null && source.length() > 0) {
108 String[] parsed = source.split(regex);
109 for (String token : parsed) {
110 if (token.length() > 0) {
119 * Builds a JSON object with error code and message information.
121 * @param errorCode error code
122 * @param errorMessage message
123 * @return JSON object as a String
125 public static String jsonErrorMessageResponse(int errorCode, String errorMessage) {
126 return "{\"error\":{\"code\":" + errorCode + "," + "\"message\":\"" + errorMessage + "\"}}";
130 * Builds a JSON object with the specified message
132 * @param message Message to embed
133 * @return JSON object as a String
135 public static String jsonMessageResponse(String message) {
136 return String.format("{\"message\":\"%s\"}", message);
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.
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
149 public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) {
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);
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.
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
171 public static void logAndSerializeObject(String source, String msg, Object obj) {
172 logAndSerializeObject(logger, source, msg, obj);
175 public static void rollbackTransaction(Transaction transaction, String errorMessage) {
176 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
178 if (transaction != null) {
179 transaction.rollback();
181 } catch (Exception e) {
182 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
183 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing a rollback transaction",
188 public static void closeLocalSession(Session localSession, String errorMessage) {
189 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
191 if (localSession != null) {
192 localSession.close();
194 } catch (Exception e) {
195 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
196 logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception", e);
201 * Set response status to Unauthorized if user == null and to Forbidden in all
202 * (!) other cases. Logging is not performed if invocator == null
204 * @param user User object
205 * @param response HttpServletResponse
206 * @param invocator may be null
208 public static void setBadPermissions(FnUser user, HttpServletResponse response, String invocator) {
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));
215 response.setStatus(HttpServletResponse.SC_FORBIDDEN);
216 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN));
218 if (invocator != null) {
219 logger.warn(EELFLoggerDelegate.errorLogger,
220 invocator + ", permissions problem, response status = " + response.getStatus());
224 public static int getExternalAppResponseCode() {
225 String responseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
226 int responseCodeInt = 0;
228 if (responseCode != null && !responseCode.isEmpty()) {
229 responseCodeInt = Integer.valueOf(responseCode);
231 } catch (Exception e) {
232 logger.error(EELFLoggerDelegate.errorLogger, "getExternalAppResponseCode failed", e);
234 return responseCodeInt;
237 // This method might be just for testing purposes.
238 public static void setExternalAppResponseCode(int responseCode) {
241 * String code = String.valueOf(responseCode);
242 * MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code );
243 * code=StringUtils.EMPTY;
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);
254 public static String getHTTPStatusString(int httpStatusCode) {
255 String httpStatusString = "unknown_error";
257 httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
258 if (httpStatusString != null) {
259 httpStatusString = httpStatusString.toLowerCase();
261 } catch (Exception e) {
262 logger.error(EELFLoggerDelegate.errorLogger, "getHTTPStatusString failed", e);
264 return httpStatusString;
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";
275 if (responseCode < 1000) {
276 httpStatusString = getHTTPStatusString(responseCode);
278 } catch (Exception e) {
279 logger.error(EELFLoggerDelegate.errorLogger, "getFEErrorString failed", e);
281 String responseString = internalExternalString + responseCode + " " + httpStatusString;
282 return responseString;
285 public static boolean isProductionBuild() {
286 boolean productionBuild = true;
287 String epVersion = EcompVersion.buildNumber;
288 if (epVersion != null) {
289 int buildNum = epVersion.lastIndexOf('.');
291 int buildNumber = Integer.parseInt(epVersion.substring(buildNum + 1));
292 if (buildNumber < 3000) // Production versions are 3000+, (ie
295 productionBuild = false;
299 return productionBuild;
302 public static String getMyIpAdddress() {
306 ip = InetAddress.getLocalHost();
307 localIp = ip.getHostAddress();
308 } catch (UnknownHostException e) {
310 logger.error(EELFLoggerDelegate.errorLogger, "getMyIpAdddress failed ", e);
315 public static String getMyHostName() {
319 ip = InetAddress.getLocalHost();
320 hostName = ip.getHostName();
321 } catch (UnknownHostException e) {
322 hostName = "unknown";
323 logger.error(EELFLoggerDelegate.errorLogger, "getMyHostName failed", e);
329 * Returns a default property if the expected one is not available
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.
336 public static String getPropertyOrDefault(String property, String defaultValue) {
337 if (!SystemProperties.containsProperty(property))
339 String value = SystemProperties.getProperty(property);
340 if (value == null || "".equals(value))
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
352 * @param beginDateTime the given begin time for the call
353 * @param endDateTime the given end time for the call
356 public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) {
357 if (beginDateTime != null && endDateTime != null) {
359 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
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);
372 * Answers the protocol to use.
374 * @return Protocol name from property file; defaults to https.
376 public static String widgetMsProtocol() {
377 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_PROTOCOL, "https");
381 * Answers the host to use.
383 * @return Host name from property file; defaults to localhost.
385 public static String localOrDockerHost() {
386 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_HOSTNAME, "localhost");
390 * It returns headers where username and password of external central auth is
393 * @return header which contains external central auth username and password
395 * @throws Exception if unable to decrypt the password
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);
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);
414 private static String decrypted(String encrypted) throws Exception {
416 if (encrypted != null && encrypted.length() > 0) {
418 result = CipherUtil.decryptPKC(encrypted,
419 SystemProperties.getProperty(SystemProperties.Decryption_Key));
420 } catch (Exception e) {
421 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
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();
441 * If function code value has any pipes it does pipe filter and returns value.
443 * @param functionCode
444 * @return function instance without pipe
446 public static String getFunctionCode(String functionCode) {
447 String finalFunctionCodeVal = "";
448 if (functionCode.contains(FUNCTION_PIPE)) {
449 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
451 finalFunctionCodeVal = functionCode.substring(functionCode.indexOf(FUNCTION_PIPE) + 1,
452 functionCode.lastIndexOf(FUNCTION_PIPE));
454 finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
456 finalFunctionCodeVal = functionCode;
458 return finalFunctionCodeVal;
463 * If function code value has any pipes it does pipe filter and returns value.
465 * @param functionCode
466 * @return function Type without pipe
468 public static String getFunctionType(String functionCode) {
469 String finalFunctionCodeVal = "";
470 if (functionCode.contains(FUNCTION_PIPE)) {
471 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
473 String[] getTypeValue = functionCode.split("\\" + FUNCTION_PIPE);
474 finalFunctionCodeVal = getTypeValue[0];
477 finalFunctionCodeVal = functionCode;
479 return finalFunctionCodeVal;
484 * If function code value has any pipes it does pipe filter and returns value.
486 * @param functionCode
487 * @return function Action without pipe
489 public static String getFunctionAction(String functionCode) {
490 String finalFunctionCodeVal = "";
491 if (functionCode.contains(FUNCTION_PIPE)) {
492 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
494 finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
496 finalFunctionCodeVal = functionCode;
498 return finalFunctionCodeVal;
503 * It check whether the external auth namespace is matching with current
504 * namespace exists in local DB
507 * @param appNamespaceVal
508 * @return true or false
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;
520 isNamespaceMatching = false;
522 return isNamespaceMatching;
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!");
533 } else if (Boolean.valueOf(rmtCentralAccess)) {
534 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}", rmtCentralAccess);
542 * It validates whether given string is JSON or not
544 * @param jsonInString
545 * @return true or false
547 public static boolean isJSONValid(String jsonInString) {
549 final ObjectMapper mapper = new ObjectMapper();
550 mapper.readTree(jsonInString);
552 } catch (IOException e) {
553 logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e);
560 * It retrieves account information from input String
563 * @return Array of Account information
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);
574 * It encodes the function code based on Hex encoding
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()));
587 public static boolean checkFunctionCodeHasEncodePattern(String code) {
588 return code.contains(EcompPortalUtils.slash);