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.Base64;
47 import java.util.Date;
48 import java.util.List;
50 import javax.servlet.http.HttpServletResponse;
51 import javax.xml.bind.DatatypeConverter;
53 import org.apache.commons.lang.StringUtils;
54 import org.hibernate.Session;
55 import org.hibernate.Transaction;
56 import org.onap.portalapp.portal.domain.EPUser;
57 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
58 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
59 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
60 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
61 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
62 import org.onap.portalsdk.core.util.SystemProperties;
64 import org.springframework.http.HttpHeaders;
65 import org.springframework.http.MediaType;
67 import com.fasterxml.jackson.core.JsonProcessingException;
68 import com.fasterxml.jackson.databind.ObjectMapper;
70 public class EcompPortalUtils {
72 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class);
74 private static final String FUNCTION_PIPE = "|";
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";
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^\\.^%^(^)^=^:])";
83 // regex for alphanumeric , dashes and underscore
84 public static final String SEARCH_USERS_REGEX = "(^[a-zA-Z0-9_-]*$)";
89 * @return true if orgUserId is not empty and contains only alphanumeric, false
92 public static boolean legitimateUserId(String orgUserId) {
93 return orgUserId.matches("^[a-zA-Z0-9]+$");
97 * Splits the string into a list of tokens using the specified regular
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.
124 * @param errorMessage
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
137 * @return JSON object as a String
139 public static String jsonMessageResponse(String message) {
140 return String.format("{\"message\":\"%s\"}", message);
144 * Serializes the specified object as JSON and writes the result to the debug
145 * log. If serialization fails, logs a message to the error logger.
148 * Logger for the class where the object was built; the logger
149 * carries the class name.
151 * First portion of the log message
153 * Second portion of the log message
155 * Object to serialize as JSON
157 public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) {
159 String objectAsJson = new ObjectMapper().writeValueAsString(obj);
160 logger.debug(EELFLoggerDelegate.debugLogger,
161 String.format("source= [%s]; %s [%s];", source, msg, objectAsJson));
162 } catch (JsonProcessingException e) {
163 logger.warn(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed to serialize", e);
164 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
165 } catch (Exception e) {
166 logger.error(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed", e);
167 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
172 * Serializes the specified object as JSON and writes the result to the debug
173 * log. If serialization fails, logs a message to the error logger.
176 * First portion of the log message
178 * Second portion of the log message
180 * Object to serialize as JSON
182 public static void logAndSerializeObject(String source, String msg, Object obj) {
183 logAndSerializeObject(logger, source, msg, obj);
186 public static void rollbackTransaction(Transaction transaction, String errorMessage) {
187 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
189 if (transaction != null) {
190 transaction.rollback();
192 } catch (Exception e) {
193 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
194 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing a rollback transaction",
199 public static void closeLocalSession(Session localSession, String errorMessage) {
200 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
202 if (localSession != null) {
203 localSession.close();
205 } catch (Exception e) {
206 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
207 logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception", e);
212 * Set response status to Unauthorized if user == null and to Forbidden in all
213 * (!) other cases. Logging is not performed if invocator == null
218 * HttpServletResponse
222 public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) {
224 String loginUrl = SystemProperties.getProperty(EPCommonSystemProperties.LOGIN_URL_NO_RET_VAL);
225 response.setHeader(GLOBAL_LOGIN_URL, loginUrl);
226 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
227 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_UNAUTHORIZED));
229 response.setStatus(HttpServletResponse.SC_FORBIDDEN);
230 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN));
232 if (invocator != null) {
233 logger.warn(EELFLoggerDelegate.errorLogger,
234 invocator + ", permissions problem, response status = " + response.getStatus());
238 public static int getExternalAppResponseCode() {
239 String responseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
240 int responseCodeInt = 0;
242 if (responseCode != null && responseCode != "") {
243 responseCodeInt = Integer.valueOf(responseCode);
245 } catch (Exception e) {
246 logger.error(EELFLoggerDelegate.errorLogger, "getExternalAppResponseCode failed", e);
248 return responseCodeInt;
251 // This method might be just for testing purposes.
252 public static void setExternalAppResponseCode(int responseCode) {
254 String code = String.valueOf(responseCode);
255 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code );
256 code=StringUtils.EMPTY;
257 } catch (Exception e) {
258 logger.error(EELFLoggerDelegate.errorLogger, "setExternalAppResponseCode failed", e);
262 public static String getHTTPStatusString(int httpStatusCode) {
263 String httpStatusString = "unknown_error";
265 httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
266 if (httpStatusString != null) {
267 httpStatusString = httpStatusString.toLowerCase();
269 } catch (Exception e) {
270 logger.error(EELFLoggerDelegate.errorLogger, "getHTTPStatusString failed", e);
272 return httpStatusString;
275 public static String getFEErrorString(Boolean internal, int responseCode) {
276 // Return a String like the following:
277 // "Internal Onap Error: 500 internal_server_error" or
278 // "External App Error: 404 not_found"
279 // TODO: create our own Ecomp error codes, starting with 1000 and up.
280 String internalExternalString = internal ? "Ecomp Error: " : "App Error: ";
281 String httpStatusString = "unknown_error";
283 if (responseCode < 1000) {
284 httpStatusString = getHTTPStatusString(responseCode);
286 } catch (Exception e) {
287 logger.error(EELFLoggerDelegate.errorLogger, "getFEErrorString failed", e);
289 String responseString = internalExternalString + responseCode + " " + httpStatusString;
290 return responseString;
293 public static boolean isProductionBuild() {
294 boolean productionBuild = true;
295 String epVersion = EcompVersion.buildNumber;
296 if (epVersion != null) {
297 int buildNum = epVersion.lastIndexOf('.');
299 int buildNumber = Integer.parseInt(epVersion.substring(buildNum + 1));
300 if (buildNumber < 3000) // Production versions are 3000+, (ie
303 productionBuild = false;
307 return productionBuild;
310 public static String getMyIpAdddress() {
314 ip = InetAddress.getLocalHost();
315 localIp = ip.getHostAddress();
316 } catch (UnknownHostException e) {
318 logger.error(EELFLoggerDelegate.errorLogger, "getMyIpAdddress failed ", e);
323 public static String getMyHostName() {
327 ip = InetAddress.getLocalHost();
328 hostName = ip.getHostName();
329 } catch (UnknownHostException e) {
330 hostName = "unknown";
331 logger.error(EELFLoggerDelegate.errorLogger, "getMyHostName failed", e);
337 * Returns a default property if the expected one is not available
341 * @param defaultValue
343 * @return Default value if property is not defined or yields the empty string;
344 * else the property value.
346 public static String getPropertyOrDefault(String property, String defaultValue) {
347 if (!SystemProperties.containsProperty(property))
349 String value = SystemProperties.getProperty(property);
350 if (value == null || "".equals(value))
356 * Calculates the time duration of a function call for logging purpose. It
357 * stores the result by using "MDC.put(SystemProperties.MDC_TIMER,
358 * timeDifference);" It is important to call
359 * "MDC.remove(SystemProperties.MDC_TIMER);" after this method call to clean up
362 * @param beginDateTime
363 * the given begin time for the call
365 * the given end time for the call
368 public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) {
369 if (beginDateTime != null && endDateTime != null) {
371 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
373 Date beginDate = ecompLogDateFormat.parse(beginDateTime);
374 Date endDate = ecompLogDateFormat.parse(endDateTime);
375 String timeDifference = String.format("%d", endDate.getTime() - beginDate.getTime());
376 MDC.put(SystemProperties.MDC_TIMER, timeDifference);
377 } catch (Exception e) {
378 logger.error(EELFLoggerDelegate.errorLogger, "calculateDateTimeDifferenceForLog failed", e);
384 * Answers the protocol to use.
386 * @return Protocol name from property file; defaults to https.
388 public static String widgetMsProtocol() {
389 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_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 * It returns headers where username and password of external central auth is
405 * @return header which contains external central auth username and password
408 * if unable to decrypt the password
410 public static HttpHeaders base64encodeKeyForAAFBasicAuth() throws Exception {
411 String userName = "";
412 String decryptedPass = "";
413 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME)
414 && EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD)) {
415 decryptedPass = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD);
416 userName = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
418 String decPass = decrypted(decryptedPass);
419 String usernamePass = userName + ":" + decPass;
420 String encToBase64 = String.valueOf((DatatypeConverter.printBase64Binary(usernamePass.getBytes())));
421 HttpHeaders headers = new HttpHeaders();
422 headers.add("Authorization", "Basic " + encToBase64);
423 headers.setContentType(MediaType.APPLICATION_JSON);
427 private static String decrypted(String encrypted) throws Exception {
429 if (encrypted != null && encrypted.length() > 0) {
431 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
432 } catch (Exception e) {
433 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
440 public static String truncateString(String originString, int size){
441 if(originString.length()>=size){
442 StringBuilder stringBuilder = new StringBuilder();
443 stringBuilder.append(originString);
444 stringBuilder.setLength(size);
445 stringBuilder.append("...");
446 return stringBuilder.toString();
453 * If function code value has any pipes it does pipe filter and
456 * @param functionCode
457 * @return function instance without pipe
459 public static String getFunctionCode(String functionCode) {
460 String finalFunctionCodeVal = "";
461 if (functionCode.contains(FUNCTION_PIPE)) {
462 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
464 finalFunctionCodeVal = functionCode.substring(
465 functionCode.indexOf(FUNCTION_PIPE) + 1,
466 functionCode.lastIndexOf(FUNCTION_PIPE));
468 finalFunctionCodeVal = functionCode
469 .substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
471 finalFunctionCodeVal = functionCode;
473 return finalFunctionCodeVal;
478 * If function code value has any pipes it does pipe filter and
481 * @param functionCode
482 * @return function Type without pipe
484 public static String getFunctionType(String functionCode) {
485 String finalFunctionCodeVal = "";
486 if (functionCode.contains(FUNCTION_PIPE)) {
487 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
489 String[] getTypeValue = functionCode.split("\\"+FUNCTION_PIPE);
490 finalFunctionCodeVal = getTypeValue[0];
493 finalFunctionCodeVal = functionCode;
495 return finalFunctionCodeVal;
500 * If function code value has any pipes it does pipe filter and
503 * @param functionCode
504 * @return function Action without pipe
506 public static String getFunctionAction(String functionCode) {
507 String finalFunctionCodeVal = "";
508 if (functionCode.contains(FUNCTION_PIPE)) {
509 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
511 finalFunctionCodeVal = functionCode.substring(
512 functionCode.lastIndexOf(FUNCTION_PIPE)+1);
514 finalFunctionCodeVal = functionCode;
516 return finalFunctionCodeVal;
521 * It check whether the external auth namespace is matching with current namespace exists in local DB
524 * @param appNamespaceVal
525 * @return true or false
527 public static boolean checkNameSpaceMatching(String permTypeVal, String appNamespaceVal) {
528 String[] typeNamespace = permTypeVal.split("\\.");
529 String[] appNamespace = appNamespaceVal.split("\\.");
530 boolean isNamespaceMatching = true;
531 if (appNamespace.length <= typeNamespace.length) {
532 for (int k = 0; k < appNamespace.length; k++) {
533 if (!appNamespace[k].equals(typeNamespace[k]))
534 isNamespaceMatching = false;
537 isNamespaceMatching = false;
539 return isNamespaceMatching;
542 public static boolean checkIfRemoteCentralAccessAllowed() {
543 boolean result = false;
544 String rmtCentralAccess = SystemProperties.getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS);
545 if(rmtCentralAccess == null) {
546 logger.error(EELFLoggerDelegate.errorLogger, "Please check in system.properties whether the property exists or not!");
548 }else if(new Boolean(rmtCentralAccess)){
549 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}",rmtCentralAccess);
557 * It validates whether given string is JSON or not
559 * @param jsonInString
560 * @return true or false
562 public static boolean isJSONValid(String jsonInString ) {
564 final ObjectMapper mapper = new ObjectMapper();
565 mapper.readTree(jsonInString);
567 } catch (IOException e) {
568 logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e);
574 * It retrieves account information from input String
577 * @return Array of Account information
580 public static String[] getUserNamePassword(String authValue) {
581 String base64Credentials = authValue.substring("Basic".length()).trim();
582 String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
583 final String[] values = credentials.split(":", 2);