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.util.SystemProperties;
66 import org.springframework.http.HttpHeaders;
67 import org.springframework.http.MediaType;
69 import com.fasterxml.jackson.core.JsonProcessingException;
70 import com.fasterxml.jackson.databind.ObjectMapper;
72 public class EcompPortalUtils {
74 private static 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^\\.^%^(^)^=^:^-])";
85 public static final String EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS_EXCLUDE_HYPHEN = "([^A-Z^a-z^0-9^\\.^%^(^)^=^:])";
87 public static final String slash = "/";
90 * @param orgUserId User ID to validate
91 * @return true if orgUserId is not empty and contains only alphanumeric, false
94 public static boolean legitimateUserId(String orgUserId) {
95 return orgUserId.matches("^[a-zA-Z0-9/_/-/@]+$");
99 * Splits the string into a list of tokens using the specified regular
102 * @param source String to split
103 * @param regex tokens
104 * @return List of tokens split from the source
106 public static List<String> parsingByRegularExpression(String source, String regex) {
107 List<String> tokens = new ArrayList<String>();
108 if (source != null && source.length() > 0) {
109 String[] parsed = source.split(regex);
110 for (String token : parsed) {
111 if (token.length() > 0) {
120 * Builds a JSON object with error code and message information.
122 * @param errorCode error code
123 * @param errorMessage message
124 * @return JSON object as a String
126 public static String jsonErrorMessageResponse(int errorCode, String errorMessage) {
127 return "{\"error\":{\"code\":" + errorCode + "," + "\"message\":\"" + errorMessage + "\"}}";
131 * Builds a JSON object with the specified message
133 * @param message Message to embed
134 * @return JSON object as a String
136 public static String jsonMessageResponse(String message) {
137 return String.format("{\"message\":\"%s\"}", message);
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.
144 * @param logger Logger for the class where the object was built; the logger
145 * carries the class name.
146 * @param source First portion of the log message
147 * @param msg Second portion of the log message
148 * @param obj Object to serialize as JSON
150 public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) {
152 String objectAsJson = new ObjectMapper().writeValueAsString(obj);
153 logger.debug(EELFLoggerDelegate.debugLogger,
154 String.format("source= [%s]; %s [%s];", source, msg, objectAsJson));
155 } catch (JsonProcessingException e) {
156 logger.warn(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed to serialize", e);
157 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
158 } catch (Exception e) {
159 logger.error(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed", e);
160 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
165 * Serializes the specified object as JSON and writes the result to the debug
166 * log. If serialization fails, logs a message to the error logger.
168 * @param source First portion of the log message
169 * @param msg Second portion of the log message
170 * @param obj Object to serialize as JSON
172 public static void logAndSerializeObject(String source, String msg, Object obj) {
173 logAndSerializeObject(logger, source, msg, obj);
176 public static void rollbackTransaction(Transaction transaction, String errorMessage) {
177 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
179 if (transaction != null) {
180 transaction.rollback();
182 } catch (Exception e) {
183 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
184 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing a rollback transaction",
189 public static void closeLocalSession(Session localSession, String errorMessage) {
190 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
192 if (localSession != null) {
193 localSession.close();
195 } catch (Exception e) {
196 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
197 logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception", e);
202 * Set response status to Unauthorized if user == null and to Forbidden in all
203 * (!) other cases. Logging is not performed if invocator == null
205 * @param user User object
206 * @param response HttpServletResponse
207 * @param invocator may be null
209 public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) {
211 String loginUrl = SystemProperties.getProperty(EPCommonSystemProperties.LOGIN_URL_NO_RET_VAL);
212 response.setHeader(GLOBAL_LOGIN_URL, loginUrl);
213 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
214 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_UNAUTHORIZED));
216 response.setStatus(HttpServletResponse.SC_FORBIDDEN);
217 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN));
219 if (invocator != null) {
220 logger.warn(EELFLoggerDelegate.errorLogger,
221 invocator + ", permissions problem, response status = " + response.getStatus());
225 public static int getExternalAppResponseCode() {
226 String responseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
227 int responseCodeInt = 0;
229 if (responseCode != null && responseCode != "") {
230 responseCodeInt = Integer.valueOf(responseCode);
232 } catch (Exception e) {
233 logger.error(EELFLoggerDelegate.errorLogger, "getExternalAppResponseCode failed", e);
235 return responseCodeInt;
238 // This method might be just for testing purposes.
239 public static void setExternalAppResponseCode(int responseCode) {
242 * String code = String.valueOf(responseCode);
243 * MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code );
244 * code=StringUtils.EMPTY;
246 String code = Integer.toString(responseCode);
247 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, code);
248 char[] chars = code.toCharArray();
249 Arrays.fill(chars, ' ');
250 } catch (Exception e) {
251 logger.error(EELFLoggerDelegate.errorLogger, "setExternalAppResponseCode failed", e);
255 public static String getHTTPStatusString(int httpStatusCode) {
256 String httpStatusString = "unknown_error";
258 httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
259 if (httpStatusString != null) {
260 httpStatusString = httpStatusString.toLowerCase();
262 } catch (Exception e) {
263 logger.error(EELFLoggerDelegate.errorLogger, "getHTTPStatusString failed", e);
265 return httpStatusString;
268 public static String getFEErrorString(Boolean internal, int responseCode) {
269 // Return a String like the following:
270 // "Internal Onap Error: 500 internal_server_error" or
271 // "External App Error: 404 not_found"
272 // TODO: create our own Ecomp error codes, starting with 1000 and up.
273 String internalExternalString = internal ? "Ecomp Error: " : "App Error: ";
274 String httpStatusString = "unknown_error";
276 if (responseCode < 1000) {
277 httpStatusString = getHTTPStatusString(responseCode);
279 } catch (Exception e) {
280 logger.error(EELFLoggerDelegate.errorLogger, "getFEErrorString failed", e);
282 String responseString = internalExternalString + responseCode + " " + httpStatusString;
283 return responseString;
286 public static boolean isProductionBuild() {
287 boolean productionBuild = true;
288 String epVersion = EcompVersion.buildNumber;
289 if (epVersion != null) {
290 int buildNum = epVersion.lastIndexOf('.');
292 int buildNumber = Integer.parseInt(epVersion.substring(buildNum + 1));
293 if (buildNumber < 3000) // Production versions are 3000+, (ie
296 productionBuild = false;
300 return productionBuild;
303 public static String getMyIpAdddress() {
307 ip = InetAddress.getLocalHost();
308 localIp = ip.getHostAddress();
309 } catch (UnknownHostException e) {
311 logger.error(EELFLoggerDelegate.errorLogger, "getMyIpAdddress failed ", e);
316 public static String getMyHostName() {
320 ip = InetAddress.getLocalHost();
321 hostName = ip.getHostName();
322 } catch (UnknownHostException e) {
323 hostName = "unknown";
324 logger.error(EELFLoggerDelegate.errorLogger, "getMyHostName failed", e);
330 * Returns a default property if the expected one is not available
332 * @param property Key
333 * @param defaultValue default Value
334 * @return Default value if property is not defined or yields the empty string;
335 * else the property value.
337 public static String getPropertyOrDefault(String property, String defaultValue) {
338 if (!SystemProperties.containsProperty(property))
340 String value = SystemProperties.getProperty(property);
341 if (value == null || "".equals(value))
347 * Calculates the time duration of a function call for logging purpose. It
348 * stores the result by using "MDC.put(SystemProperties.MDC_TIMER,
349 * timeDifference);" It is important to call
350 * "MDC.remove(SystemProperties.MDC_TIMER);" after this method call to clean up
353 * @param beginDateTime the given begin time for the call
354 * @param endDateTime the given end time for the call
357 public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) {
358 if (beginDateTime != null && endDateTime != null) {
360 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
362 Date beginDate = ecompLogDateFormat.parse(beginDateTime);
363 Date endDate = ecompLogDateFormat.parse(endDateTime);
364 String timeDifference = String.format("%d", endDate.getTime() - beginDate.getTime());
365 MDC.put(SystemProperties.MDC_TIMER, timeDifference);
366 } catch (Exception e) {
367 logger.error(EELFLoggerDelegate.errorLogger, "calculateDateTimeDifferenceForLog failed", e);
373 * Answers the protocol to use.
375 * @return Protocol name from property file; defaults to https.
377 public static String widgetMsProtocol() {
378 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_PROTOCOL, "https");
382 * Answers the protocol to use.
384 * @return Protocol name from property file; defaults to https.
386 public static String widgetMLProtocol() {
387 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_ML_PROTOCOL, "https");
391 * Answers the host to use.
393 * @return Host name from property file; defaults to localhost.
395 public static String localOrDockerHost() {
396 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_HOSTNAME, "localhost");
400 * Answers the host to use.
402 * @return Host name from property file; defaults to localhost.
404 public static String mlLocalOrDockerHost() {
405 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_ML_HOSTNAME, "localhost");
409 * It returns headers where username and password of external central auth is
412 * @return header which contains external central auth username and password
414 * @throws Exception if unable to decrypt the password
416 public static HttpHeaders base64encodeKeyForAAFBasicAuth() throws Exception {
417 String userName = "";
418 String decryptedPass = "";
419 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME)
420 && EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD)) {
421 decryptedPass = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD);
422 userName = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
424 String decPass = decrypted(decryptedPass);
425 String usernamePass = userName + ":" + decPass;
426 String encToBase64 = String.valueOf((DatatypeConverter.printBase64Binary(usernamePass.getBytes())));
427 HttpHeaders headers = new HttpHeaders();
428 headers.add("Authorization", "Basic " + encToBase64);
429 headers.setContentType(MediaType.APPLICATION_JSON);
433 private static String decrypted(String encrypted) throws Exception {
435 if (encrypted != null && encrypted.length() > 0) {
437 result = CipherUtil.decryptPKC(encrypted,
438 SystemProperties.getProperty(SystemProperties.Decryption_Key));
439 } catch (Exception e) {
440 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
447 public static String truncateString(String originString, int size) {
448 if (originString.length() >= size) {
449 StringBuilder stringBuilder = new StringBuilder();
450 stringBuilder.append(originString);
451 stringBuilder.setLength(size);
452 stringBuilder.append("...");
453 return stringBuilder.toString();
460 * If function code value has any pipes it does pipe filter and returns value.
462 * @param functionCode
463 * @return function instance without pipe
465 public static String getFunctionCode(String functionCode) {
466 String finalFunctionCodeVal = "";
467 if (functionCode.contains(FUNCTION_PIPE)) {
468 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
470 finalFunctionCodeVal = functionCode.substring(functionCode.indexOf(FUNCTION_PIPE) + 1,
471 functionCode.lastIndexOf(FUNCTION_PIPE));
473 finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
475 finalFunctionCodeVal = functionCode;
477 return finalFunctionCodeVal;
482 * If function code value has any pipes it does pipe filter and returns value.
484 * @param functionCode
485 * @return function Type without pipe
487 public static String getFunctionType(String functionCode) {
488 String finalFunctionCodeVal = "";
489 if (functionCode.contains(FUNCTION_PIPE)) {
490 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
492 String[] getTypeValue = functionCode.split("\\" + FUNCTION_PIPE);
493 finalFunctionCodeVal = getTypeValue[0];
496 finalFunctionCodeVal = functionCode;
498 return finalFunctionCodeVal;
503 * If function code value has any pipes it does pipe filter and returns value.
505 * @param functionCode
506 * @return function Action without pipe
508 public static String getFunctionAction(String functionCode) {
509 String finalFunctionCodeVal = "";
510 if (functionCode.contains(FUNCTION_PIPE)) {
511 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
513 finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
515 finalFunctionCodeVal = functionCode;
517 return finalFunctionCodeVal;
522 * It check whether the external auth namespace is matching with current
523 * namespace exists in local DB
526 * @param appNamespaceVal
527 * @return true or false
529 public static boolean checkNameSpaceMatching(String permTypeVal, String appNamespaceVal) {
530 String[] typeNamespace = permTypeVal.split("\\.");
531 String[] appNamespace = appNamespaceVal.split("\\.");
532 boolean isNamespaceMatching = true;
533 if (appNamespace.length <= typeNamespace.length) {
534 for (int k = 0; k < appNamespace.length; k++) {
535 if (!appNamespace[k].equals(typeNamespace[k]))
536 isNamespaceMatching = false;
539 isNamespaceMatching = false;
541 return isNamespaceMatching;
544 public static boolean checkIfRemoteCentralAccessAllowed() {
545 boolean result = false;
546 String rmtCentralAccess = SystemProperties
547 .getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS);
548 if (rmtCentralAccess == null) {
549 logger.error(EELFLoggerDelegate.errorLogger,
550 "Please check in system.properties whether the property exists or not!");
552 } else if (new Boolean(rmtCentralAccess)) {
553 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}", rmtCentralAccess);
561 * It validates whether given string is JSON or not
563 * @param jsonInString
564 * @return true or false
566 public static boolean isJSONValid(String jsonInString) {
568 final ObjectMapper mapper = new ObjectMapper();
569 mapper.readTree(jsonInString);
571 } catch (IOException e) {
572 logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e);
579 * It retrieves account information from input String
582 * @return Array of Account information
585 public static String[] getUserNamePassword(String authValue) {
586 String base64Credentials = authValue.substring("Basic".length()).trim();
587 String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
588 final String[] values = credentials.split(":", 2);
593 * It encodes the function code based on Hex encoding
598 public static String encodeFunctionCode(String funCode) {
599 String encodedString = funCode;
600 Pattern encodePattern = Pattern.compile(EcompPortalUtils.slash);
601 return encodedString = encodePattern.matcher(encodedString)
602 .replaceAll("%" + Hex.encodeHexString(encodePattern.toString().getBytes()))
603 .replaceAll("\\*", "%" + Hex.encodeHexString("*".getBytes()));
606 public static boolean checkFunctionCodeHasEncodePattern(String code) {
607 return code.contains(EcompPortalUtils.slash);