2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 * https://creativecommons.org/licenses/by/4.0/
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.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.portal.utils;
40 import java.io.IOException;
41 import java.net.InetAddress;
42 import java.net.UnknownHostException;
43 import java.nio.charset.Charset;
44 import java.text.SimpleDateFormat;
45 import java.util.ArrayList;
46 import java.util.Arrays;
47 import java.util.Base64;
48 import java.util.Date;
49 import java.util.List;
50 import java.util.regex.Pattern;
52 import javax.servlet.http.HttpServletResponse;
53 import javax.xml.bind.DatatypeConverter;
55 import org.apache.commons.codec.binary.Hex;
56 import org.apache.commons.lang.StringUtils;
57 import org.hibernate.Session;
58 import org.hibernate.Transaction;
59 import org.onap.portalapp.portal.domain.EPUser;
60 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
61 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
62 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
63 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
64 import org.onap.portalsdk.core.onboarding.util.KeyConstants;
65 import org.onap.portalsdk.core.onboarding.util.KeyProperties;
66 import org.onap.portalsdk.core.util.SystemProperties;
68 import org.springframework.http.HttpHeaders;
69 import org.springframework.http.MediaType;
71 import com.fasterxml.jackson.core.JsonProcessingException;
72 import com.fasterxml.jackson.databind.ObjectMapper;
74 public class EcompPortalUtils {
76 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class);
78 private static final String FUNCTION_PIPE = "|";
80 // TODO: GLOBAL_LOGIN_URL is the same as in SessionTimeoutInterceptor.
81 // It should be defined in SystemProperties.
82 private static final String GLOBAL_LOGIN_URL = "global-login-url";
84 // It is a regular expression used for while creating a External Central Auth
86 public static final String EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS = "([^A-Z^a-z^0-9^\\.^%^(^)^=^:^-])";
87 public static final String EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS_EXCLUDE_HYPHEN = "([^A-Z^a-z^0-9^\\.^%^(^)^=^:])";
89 public static final String slash = "/";
92 * @param orgUserId User ID to validate
93 * @return true if orgUserId is not empty and contains only alphanumeric, false
96 public static boolean legitimateUserId(String orgUserId) {
97 return orgUserId.matches("^[a-zA-Z0-9/_/-/@]+$");
101 * Splits the string into a list of tokens using the specified regular
104 * @param source String to split
105 * @param regex tokens
106 * @return List of tokens split from the source
108 public static List<String> parsingByRegularExpression(String source, String regex) {
109 List<String> tokens = new ArrayList<String>();
110 if (source != null && source.length() > 0) {
111 String[] parsed = source.split(regex);
112 for (String token : parsed) {
113 if (token.length() > 0) {
122 * Builds a JSON object with error code and message information.
124 * @param errorCode error code
125 * @param errorMessage message
126 * @return JSON object as a String
128 public static String jsonErrorMessageResponse(int errorCode, String errorMessage) {
129 return "{\"error\":{\"code\":" + errorCode + "," + "\"message\":\"" + errorMessage + "\"}}";
133 * Builds a JSON object with the specified message
135 * @param message Message to embed
136 * @return JSON object as a String
138 public static String jsonMessageResponse(String message) {
139 return String.format("{\"message\":\"%s\"}", message);
143 * Serializes the specified object as JSON and writes the result to the debug
144 * log. If serialization fails, logs a message to the error logger.
146 * @param logger Logger for the class where the object was built; the logger
147 * carries the class name.
148 * @param source First portion of the log message
149 * @param msg Second portion of the log message
150 * @param obj Object to serialize as JSON
152 public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) {
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);
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.
170 * @param source First portion of the log message
171 * @param msg Second portion of the log message
172 * @param obj Object to serialize as JSON
174 public static void logAndSerializeObject(String source, String msg, Object obj) {
175 logAndSerializeObject(logger, source, msg, obj);
178 public static void rollbackTransaction(Transaction transaction, String errorMessage) {
179 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
181 if (transaction != null) {
182 transaction.rollback();
184 } catch (Exception e) {
185 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
186 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing a rollback transaction",
191 public static void closeLocalSession(Session localSession, String errorMessage) {
192 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
194 if (localSession != null) {
195 localSession.close();
197 } catch (Exception e) {
198 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
199 logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception", e);
204 * Set response status to Unauthorized if user == null and to Forbidden in all
205 * (!) other cases. Logging is not performed if invocator == null
207 * @param user User object
208 * @param response HttpServletResponse
209 * @param invocator may be null
211 public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) {
213 String loginUrl = SystemProperties.getProperty(EPCommonSystemProperties.LOGIN_URL_NO_RET_VAL);
214 response.setHeader(GLOBAL_LOGIN_URL, loginUrl);
215 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
216 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_UNAUTHORIZED));
218 response.setStatus(HttpServletResponse.SC_FORBIDDEN);
219 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN));
221 if (invocator != null) {
222 logger.warn(EELFLoggerDelegate.errorLogger,
223 invocator + ", permissions problem, response status = " + response.getStatus());
227 public static int getExternalAppResponseCode() {
228 String responseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
229 int responseCodeInt = 0;
231 if (responseCode != null && responseCode != "") {
232 responseCodeInt = Integer.valueOf(responseCode);
234 } catch (Exception e) {
235 logger.error(EELFLoggerDelegate.errorLogger, "getExternalAppResponseCode failed", e);
237 return responseCodeInt;
240 // This method might be just for testing purposes.
241 public static void setExternalAppResponseCode(int responseCode) {
244 * String code = String.valueOf(responseCode);
245 * MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code );
246 * code=StringUtils.EMPTY;
248 String code = Integer.toString(responseCode);
249 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, code);
250 char[] chars = code.toCharArray();
251 Arrays.fill(chars, ' ');
252 } catch (Exception e) {
253 logger.error(EELFLoggerDelegate.errorLogger, "setExternalAppResponseCode failed", e);
257 public static String getHTTPStatusString(int httpStatusCode) {
258 String httpStatusString = "unknown_error";
260 httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
261 if (httpStatusString != null) {
262 httpStatusString = httpStatusString.toLowerCase();
264 } catch (Exception e) {
265 logger.error(EELFLoggerDelegate.errorLogger, "getHTTPStatusString failed", e);
267 return httpStatusString;
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";
278 if (responseCode < 1000) {
279 httpStatusString = getHTTPStatusString(responseCode);
281 } catch (Exception e) {
282 logger.error(EELFLoggerDelegate.errorLogger, "getFEErrorString failed", e);
284 String responseString = internalExternalString + responseCode + " " + httpStatusString;
285 return responseString;
288 public static boolean isProductionBuild() {
289 boolean productionBuild = true;
290 String epVersion = EcompVersion.buildNumber;
291 if (epVersion != null) {
292 int buildNum = epVersion.lastIndexOf('.');
294 int buildNumber = Integer.parseInt(epVersion.substring(buildNum + 1));
295 if (buildNumber < 3000) // Production versions are 3000+, (ie
298 productionBuild = false;
302 return productionBuild;
305 public static String getMyIpAdddress() {
309 ip = InetAddress.getLocalHost();
310 localIp = ip.getHostAddress();
311 } catch (UnknownHostException e) {
313 logger.error(EELFLoggerDelegate.errorLogger, "getMyIpAdddress failed ", e);
318 public static String getMyHostName() {
322 ip = InetAddress.getLocalHost();
323 hostName = ip.getHostName();
324 } catch (UnknownHostException e) {
325 hostName = "unknown";
326 logger.error(EELFLoggerDelegate.errorLogger, "getMyHostName failed", e);
332 * Returns a default property if the expected one is not available
334 * @param property Key
335 * @param defaultValue default Value
336 * @return Default value if property is not defined or yields the empty string;
337 * else the property value.
339 public static String getPropertyOrDefault(String property, String defaultValue) {
340 if (!SystemProperties.containsProperty(property))
342 String value = SystemProperties.getProperty(property);
343 if (value == null || "".equals(value))
349 * Calculates the time duration of a function call for logging purpose. It
350 * stores the result by using "MDC.put(SystemProperties.MDC_TIMER,
351 * timeDifference);" It is important to call
352 * "MDC.remove(SystemProperties.MDC_TIMER);" after this method call to clean up
355 * @param beginDateTime the given begin time for the call
356 * @param endDateTime the given end time for the call
359 public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) {
360 if (beginDateTime != null && endDateTime != null) {
362 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
364 Date beginDate = ecompLogDateFormat.parse(beginDateTime);
365 Date endDate = ecompLogDateFormat.parse(endDateTime);
366 String timeDifference = String.format("%d", endDate.getTime() - beginDate.getTime());
367 MDC.put(SystemProperties.MDC_TIMER, timeDifference);
368 } catch (Exception e) {
369 logger.error(EELFLoggerDelegate.errorLogger, "calculateDateTimeDifferenceForLog failed", e);
375 * Answers the protocol to use.
377 * @return Protocol name from property file; defaults to https.
379 public static String widgetMsProtocol() {
380 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_PROTOCOL, "https");
384 * Answers the protocol to use.
386 * @return Protocol name from property file; defaults to https.
388 public static String widgetMLProtocol() {
389 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_ML_PROTOCOL, "https");
393 * Answers the host to use.
395 * @return Host name from property file; defaults to localhost.
397 public static String localOrDockerHost() {
398 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_HOSTNAME, "localhost");
402 * Answers the host to use.
404 * @return Host name from property file; defaults to localhost.
406 public static String mlLocalOrDockerHost() {
407 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_ML_HOSTNAME, "localhost");
411 * It returns headers where username and password of external central auth is
414 * @return header which contains external central auth username and password
416 * @throws Exception if unable to decrypt the password
418 public static HttpHeaders base64encodeKeyForAAFBasicAuth() throws Exception {
419 String userName = "";
420 String decryptedPass = "";
421 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME)
422 && EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD)) {
423 decryptedPass = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD);
424 userName = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
428 decPass = decrypted(decryptedPass);
429 } catch (Exception e) {
430 logger.warn(EELFLoggerDelegate.errorLogger, "decryptedPassword failed using non decrypted pwd from the Properties file", e);
431 decPass = decryptedPass;
433 String usernamePass = userName + ":" + decPass;
434 String encToBase64 = String.valueOf((DatatypeConverter.printBase64Binary(usernamePass.getBytes())));
435 HttpHeaders headers = new HttpHeaders();
436 headers.add("Authorization", "Basic " + encToBase64);
437 headers.setContentType(MediaType.APPLICATION_JSON);
441 private static String decrypted(String encrypted) throws Exception {
443 if (encrypted != null && encrypted.length() > 0) {
445 result = CipherUtil.decryptPKC(encrypted,
446 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
447 } catch (Exception e) {
448 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
455 public static String truncateString(String originString, int size) {
456 if (originString.length() >= size) {
457 StringBuilder stringBuilder = new StringBuilder();
458 stringBuilder.append(originString);
459 stringBuilder.setLength(size);
460 stringBuilder.append("...");
461 return stringBuilder.toString();
468 * If function code value has any pipes it does pipe filter and returns value.
470 * @param functionCode
471 * @return function instance without pipe
473 public static String getFunctionCode(String functionCode) {
474 String finalFunctionCodeVal = "";
475 if (functionCode.contains(FUNCTION_PIPE)) {
476 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
478 finalFunctionCodeVal = functionCode.substring(functionCode.indexOf(FUNCTION_PIPE) + 1,
479 functionCode.lastIndexOf(FUNCTION_PIPE));
481 finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
483 finalFunctionCodeVal = functionCode;
485 return finalFunctionCodeVal;
490 * If function code value has any pipes it does pipe filter and returns value.
492 * @param functionCode
493 * @return function Type without pipe
495 public static String getFunctionType(String functionCode) {
496 String finalFunctionCodeVal = "";
497 if (functionCode.contains(FUNCTION_PIPE)) {
498 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
500 String[] getTypeValue = functionCode.split("\\" + FUNCTION_PIPE);
501 finalFunctionCodeVal = getTypeValue[0];
504 finalFunctionCodeVal = functionCode;
506 return finalFunctionCodeVal;
511 * If function code value has any pipes it does pipe filter and returns value.
513 * @param functionCode
514 * @return function Action without pipe
516 public static String getFunctionAction(String functionCode) {
517 String finalFunctionCodeVal = "";
518 if (functionCode.contains(FUNCTION_PIPE)) {
519 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
521 finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
523 finalFunctionCodeVal = functionCode;
525 return finalFunctionCodeVal;
530 * It check whether the external auth namespace is matching with current
531 * namespace exists in local DB
534 * @param appNamespaceVal
535 * @return true or false
537 public static boolean checkNameSpaceMatching(String permTypeVal, String appNamespaceVal) {
538 String[] typeNamespace = permTypeVal.split("\\.");
539 String[] appNamespace = appNamespaceVal.split("\\.");
540 boolean isNamespaceMatching = true;
541 if (appNamespace.length <= typeNamespace.length) {
542 for (int k = 0; k < appNamespace.length; k++) {
543 if (!appNamespace[k].equals(typeNamespace[k]))
544 isNamespaceMatching = false;
547 isNamespaceMatching = false;
549 return isNamespaceMatching;
552 public static boolean checkIfRemoteCentralAccessAllowed() {
553 boolean result = false;
554 String rmtCentralAccess = SystemProperties
555 .getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS);
556 if (rmtCentralAccess == null) {
557 logger.error(EELFLoggerDelegate.errorLogger,
558 "Please check in system.properties whether the property exists or not!");
560 } else if (new Boolean(rmtCentralAccess)) {
561 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}", rmtCentralAccess);
569 * It validates whether given string is JSON or not
571 * @param jsonInString
572 * @return true or false
574 public static boolean isJSONValid(String jsonInString) {
576 final ObjectMapper mapper = new ObjectMapper();
577 mapper.readTree(jsonInString);
579 } catch (IOException e) {
580 logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e);
587 * It retrieves account information from input String
590 * @return Array of Account information
593 public static String[] getUserNamePassword(String authValue) {
594 String base64Credentials = authValue.substring("Basic".length()).trim();
595 String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
596 final String[] values = credentials.split(":", 2);
601 * It encodes the function code based on Hex encoding
606 public static String encodeFunctionCode(String funCode) {
607 String encodedString = funCode;
608 Pattern encodePattern = Pattern.compile(EcompPortalUtils.slash);
609 return encodedString = encodePattern.matcher(encodedString)
610 .replaceAll("%" + Hex.encodeHexString(encodePattern.toString().getBytes()))
611 .replaceAll("\\*", "%" + Hex.encodeHexString("*".getBytes()));
614 public static boolean checkFunctionCodeHasEncodePattern(String code) {
615 return code.contains(EcompPortalUtils.slash);