X-Git-Url: https://gerrit.onap.org/r/gitweb?a=blobdiff_plain;f=ecomp-portal-BE-common%2Fsrc%2Fmain%2Fjava%2Forg%2Fonap%2Fportalapp%2Fportal%2Futils%2FEcompPortalUtils.java;h=913f8b5fc6d72a106b5d564643a724307b6a1237;hb=0d2d51e2fbcb7b90b62be1ffa0c462a78b1fc166;hp=809e42f97f88b6c50e925ad0a1e2770f92cab204;hpb=a59bc3e85eaf33c0a38063e5c30fe890588a0eb1;p=portal.git diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java index 809e42f9..913f8b5f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java @@ -43,13 +43,16 @@ import java.net.UnknownHostException; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Arrays; import java.util.Base64; import java.util.Date; import java.util.List; +import java.util.regex.Pattern; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.DatatypeConverter; +import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang.StringUtils; import org.hibernate.Session; import org.hibernate.Transaction; @@ -58,6 +61,8 @@ import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum; import org.onap.portalapp.portal.logging.logic.EPLogUtil; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.onboarding.util.CipherUtil; +import org.onap.portalsdk.core.onboarding.util.KeyConstants; +import org.onap.portalsdk.core.onboarding.util.KeyProperties; import org.onap.portalsdk.core.util.SystemProperties; import org.slf4j.MDC; import org.springframework.http.HttpHeaders; @@ -69,34 +74,35 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class EcompPortalUtils { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class); - + private static final String FUNCTION_PIPE = "|"; - + // TODO: GLOBAL_LOGIN_URL is the same as in SessionTimeoutInterceptor. // It should be defined in SystemProperties. private static final String GLOBAL_LOGIN_URL = "global-login-url"; - - // It is a regular expression used for while creating a External Central Auth Role - public static final String EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS = "([^A-Z^a-z^0-9^\\.^%^(^)^=^:])"; - + + // It is a regular expression used for while creating a External Central Auth + // Role + public static final String EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS = "([^A-Z^a-z^0-9^\\.^%^(^)^=^:^-])"; + public static final String EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS_EXCLUDE_HYPHEN = "([^A-Z^a-z^0-9^\\.^%^(^)^=^:])"; + + public static final String slash = "/"; + /** - * @param orgUserId - * User ID to validate + * @param orgUserId User ID to validate * @return true if orgUserId is not empty and contains only alphanumeric, false * otherwise */ public static boolean legitimateUserId(String orgUserId) { - return orgUserId.matches("^[a-zA-Z0-9]+$"); + return orgUserId.matches("^[a-zA-Z0-9/_/-/@]+$"); } /** * Splits the string into a list of tokens using the specified regular * expression * - * @param source - * String to split - * @param regex - * tokens + * @param source String to split + * @param regex tokens * @return List of tokens split from the source */ public static List parsingByRegularExpression(String source, String regex) { @@ -115,10 +121,8 @@ public class EcompPortalUtils { /** * Builds a JSON object with error code and message information. * - * @param errorCode - * error code - * @param errorMessage - * message + * @param errorCode error code + * @param errorMessage message * @return JSON object as a String */ public static String jsonErrorMessageResponse(int errorCode, String errorMessage) { @@ -128,8 +132,7 @@ public class EcompPortalUtils { /** * Builds a JSON object with the specified message * - * @param message - * Message to embed + * @param message Message to embed * @return JSON object as a String */ public static String jsonMessageResponse(String message) { @@ -140,15 +143,11 @@ public class EcompPortalUtils { * Serializes the specified object as JSON and writes the result to the debug * log. If serialization fails, logs a message to the error logger. * - * @param logger - * Logger for the class where the object was built; the logger - * carries the class name. - * @param source - * First portion of the log message - * @param msg - * Second portion of the log message - * @param obj - * Object to serialize as JSON + * @param logger Logger for the class where the object was built; the logger + * carries the class name. + * @param source First portion of the log message + * @param msg Second portion of the log message + * @param obj Object to serialize as JSON */ public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) { try { @@ -168,12 +167,9 @@ public class EcompPortalUtils { * Serializes the specified object as JSON and writes the result to the debug * log. If serialization fails, logs a message to the error logger. * - * @param source - * First portion of the log message - * @param msg - * Second portion of the log message - * @param obj - * Object to serialize as JSON + * @param source First portion of the log message + * @param msg Second portion of the log message + * @param obj Object to serialize as JSON */ public static void logAndSerializeObject(String source, String msg, Object obj) { logAndSerializeObject(logger, source, msg, obj); @@ -208,12 +204,9 @@ public class EcompPortalUtils { * Set response status to Unauthorized if user == null and to Forbidden in all * (!) other cases. Logging is not performed if invocator == null * - * @param user - * User object - * @param response - * HttpServletResponse - * @param invocator - * may be null + * @param user User object + * @param response HttpServletResponse + * @param invocator may be null */ public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) { if (user == null) { @@ -247,9 +240,15 @@ public class EcompPortalUtils { // This method might be just for testing purposes. public static void setExternalAppResponseCode(int responseCode) { try { - String code = String.valueOf(responseCode); - MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code ); - code=StringUtils.EMPTY; + /* + * String code = String.valueOf(responseCode); + * MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code ); + * code=StringUtils.EMPTY; + */ + String code = Integer.toString(responseCode); + MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, code); + char[] chars = code.toCharArray(); + Arrays.fill(chars, ' '); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "setExternalAppResponseCode failed", e); } @@ -332,10 +331,8 @@ public class EcompPortalUtils { /** * Returns a default property if the expected one is not available * - * @param property - * Key - * @param defaultValue - * default Value + * @param property Key + * @param defaultValue default Value * @return Default value if property is not defined or yields the empty string; * else the property value. */ @@ -355,10 +352,8 @@ public class EcompPortalUtils { * "MDC.remove(SystemProperties.MDC_TIMER);" after this method call to clean up * the record in MDC * - * @param beginDateTime - * the given begin time for the call - * @param endDateTime - * the given end time for the call + * @param beginDateTime the given begin time for the call + * @param endDateTime the given end time for the call * */ public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) { @@ -384,6 +379,15 @@ public class EcompPortalUtils { public static String widgetMsProtocol() { return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_PROTOCOL, "https"); } + + /** + * Answers the protocol to use. + * + * @return Protocol name from property file; defaults to https. + */ + public static String widgetMLProtocol() { + return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_ML_PROTOCOL, "https"); + } /** * Answers the host to use. @@ -393,6 +397,15 @@ public class EcompPortalUtils { public static String localOrDockerHost() { return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_HOSTNAME, "localhost"); } + + /** + * Answers the host to use. + * + * @return Host name from property file; defaults to localhost. + */ + public static String mlLocalOrDockerHost() { + return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_ML_HOSTNAME, "localhost"); + } /** * It returns headers where username and password of external central auth is @@ -400,8 +413,7 @@ public class EcompPortalUtils { * * @return header which contains external central auth username and password * base64 encoded - * @throws Exception - * if unable to decrypt the password + * @throws Exception if unable to decrypt the password */ public static HttpHeaders base64encodeKeyForAAFBasicAuth() throws Exception { String userName = ""; @@ -411,7 +423,13 @@ public class EcompPortalUtils { decryptedPass = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD); userName = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME); } - String decPass = decrypted(decryptedPass); + String decPass; + try { + decPass = decrypted(decryptedPass); + } catch (Exception e) { + logger.warn(EELFLoggerDelegate.errorLogger, "decryptedPassword failed using non decrypted pwd from the Properties file", e); + decPass = decryptedPass; + } String usernamePass = userName + ":" + decPass; String encToBase64 = String.valueOf((DatatypeConverter.printBase64Binary(usernamePass.getBytes()))); HttpHeaders headers = new HttpHeaders(); @@ -424,7 +442,8 @@ public class EcompPortalUtils { String result = ""; if (encrypted != null && encrypted.length() > 0) { try { - result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key)); + result = CipherUtil.decryptPKC(encrypted, + KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY)); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e); throw e; @@ -433,8 +452,8 @@ public class EcompPortalUtils { return result; } - public static String truncateString(String originString, int size){ - if(originString.length()>=size){ + public static String truncateString(String originString, int size) { + if (originString.length() >= size) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(originString); stringBuilder.setLength(size); @@ -443,11 +462,10 @@ public class EcompPortalUtils { } return originString; } - + /** * - * If function code value has any pipes it does pipe filter and - * returns value. + * If function code value has any pipes it does pipe filter and returns value. * * @param functionCode * @return function instance without pipe @@ -457,22 +475,19 @@ public class EcompPortalUtils { if (functionCode.contains(FUNCTION_PIPE)) { int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE); if (count == 2) - finalFunctionCodeVal = functionCode.substring( - functionCode.indexOf(FUNCTION_PIPE) + 1, + finalFunctionCodeVal = functionCode.substring(functionCode.indexOf(FUNCTION_PIPE) + 1, functionCode.lastIndexOf(FUNCTION_PIPE)); else - finalFunctionCodeVal = functionCode - .substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1); - } else{ + finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1); + } else { finalFunctionCodeVal = functionCode; } return finalFunctionCodeVal; } - + /** * - * If function code value has any pipes it does pipe filter and - * returns value. + * If function code value has any pipes it does pipe filter and returns value. * * @param functionCode * @return function Type without pipe @@ -481,20 +496,19 @@ public class EcompPortalUtils { String finalFunctionCodeVal = ""; if (functionCode.contains(FUNCTION_PIPE)) { int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE); - if (count == 2){ - String[] getTypeValue = functionCode.split("\\"+FUNCTION_PIPE); + if (count == 2) { + String[] getTypeValue = functionCode.split("\\" + FUNCTION_PIPE); finalFunctionCodeVal = getTypeValue[0]; } - } else{ + } else { finalFunctionCodeVal = functionCode; } return finalFunctionCodeVal; } - + /** * - * If function code value has any pipes it does pipe filter and - * returns value. + * If function code value has any pipes it does pipe filter and returns value. * * @param functionCode * @return function Action without pipe @@ -504,17 +518,17 @@ public class EcompPortalUtils { if (functionCode.contains(FUNCTION_PIPE)) { int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE); if (count == 2) - finalFunctionCodeVal = functionCode.substring( - functionCode.lastIndexOf(FUNCTION_PIPE)+1); - } else{ + finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1); + } else { finalFunctionCodeVal = functionCode; } return finalFunctionCodeVal; } - + /** * - * It check whether the external auth namespace is matching with current namespace exists in local DB + * It check whether the external auth namespace is matching with current + * namespace exists in local DB * * @param permTypeVal * @param appNamespaceVal @@ -534,20 +548,22 @@ public class EcompPortalUtils { } return isNamespaceMatching; } - + public static boolean checkIfRemoteCentralAccessAllowed() { boolean result = false; - String rmtCentralAccess = SystemProperties.getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS); - if(rmtCentralAccess == null) { - logger.error(EELFLoggerDelegate.errorLogger, "Please check in system.properties whether the property exists or not!"); + String rmtCentralAccess = SystemProperties + .getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS); + if (rmtCentralAccess == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "Please check in system.properties whether the property exists or not!"); return false; - }else if(new Boolean(rmtCentralAccess)){ - logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}",rmtCentralAccess); + } else if (new Boolean(rmtCentralAccess)) { + logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}", rmtCentralAccess); result = true; } return result; } - + /** * * It validates whether given string is JSON or not @@ -555,28 +571,48 @@ public class EcompPortalUtils { * @param jsonInString * @return true or false */ - public static boolean isJSONValid(String jsonInString ) { - try { - final ObjectMapper mapper = new ObjectMapper(); - mapper.readTree(jsonInString); - return true; - } catch (IOException e) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e); - return false; - } - } - /** - * - * It retrieves account information from input String - * - * @param authValue - * @return Array of Account information - * - */ - public static String[] getUserNamePassword(String authValue) { - String base64Credentials = authValue.substring("Basic".length()).trim(); - String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8")); - final String[] values = credentials.split(":", 2); - return values; + public static boolean isJSONValid(String jsonInString) { + try { + final ObjectMapper mapper = new ObjectMapper(); + mapper.readTree(jsonInString); + return true; + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e); + return false; } + } + + /** + * + * It retrieves account information from input String + * + * @param authValue + * @return Array of Account information + * + */ + public static String[] getUserNamePassword(String authValue) { + String base64Credentials = authValue.substring("Basic".length()).trim(); + String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8")); + final String[] values = credentials.split(":", 2); + return values; + } + + /** + * It encodes the function code based on Hex encoding + * + * @param funCode + * + */ + public static String encodeFunctionCode(String funCode) { + String encodedString = funCode; + Pattern encodePattern = Pattern.compile(EcompPortalUtils.slash); + return encodedString = encodePattern.matcher(encodedString) + .replaceAll("%" + Hex.encodeHexString(encodePattern.toString().getBytes())) + .replaceAll("\\*", "%" + Hex.encodeHexString("*".getBytes())); + } + + public static boolean checkFunctionCodeHasEncodePattern(String code) { + return code.contains(EcompPortalUtils.slash); + } + }