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^\\.^%^(^)^=^:])";
86 * @return true if orgUserId is not empty and contains only alphanumeric, false
89 public static boolean legitimateUserId(String orgUserId) {
90 return orgUserId.matches("^[a-zA-Z0-9]+$");
94 * Splits the string into a list of tokens using the specified regular
101 * @return List of tokens split from the source
103 public static List<String> parsingByRegularExpression(String source, String regex) {
104 List<String> tokens = new ArrayList<String>();
105 if (source != null && source.length() > 0) {
106 String[] parsed = source.split(regex);
107 for (String token : parsed) {
108 if (token.length() > 0) {
117 * Builds a JSON object with error code and message information.
121 * @param errorMessage
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
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.
145 * Logger for the class where the object was built; the logger
146 * carries the class name.
148 * First portion of the log message
150 * Second portion of the log message
152 * Object to serialize as JSON
154 public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) {
156 String objectAsJson = new ObjectMapper().writeValueAsString(obj);
157 logger.debug(EELFLoggerDelegate.debugLogger,
158 String.format("source= [%s]; %s [%s];", source, msg, objectAsJson));
159 } catch (JsonProcessingException e) {
160 logger.warn(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed to serialize", e);
161 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
162 } catch (Exception e) {
163 logger.error(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed", e);
164 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
169 * Serializes the specified object as JSON and writes the result to the debug
170 * log. If serialization fails, logs a message to the error logger.
173 * First portion of the log message
175 * Second portion of the log message
177 * Object to serialize as JSON
179 public static void logAndSerializeObject(String source, String msg, Object obj) {
180 logAndSerializeObject(logger, source, msg, obj);
183 public static void rollbackTransaction(Transaction transaction, String errorMessage) {
184 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
186 if (transaction != null) {
187 transaction.rollback();
189 } catch (Exception e) {
190 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
191 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing a rollback transaction",
196 public static void closeLocalSession(Session localSession, String errorMessage) {
197 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
199 if (localSession != null) {
200 localSession.close();
202 } catch (Exception e) {
203 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
204 logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception", e);
209 * Set response status to Unauthorized if user == null and to Forbidden in all
210 * (!) other cases. Logging is not performed if invocator == null
215 * HttpServletResponse
219 public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) {
221 String loginUrl = SystemProperties.getProperty(EPCommonSystemProperties.LOGIN_URL_NO_RET_VAL);
222 response.setHeader(GLOBAL_LOGIN_URL, loginUrl);
223 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
224 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_UNAUTHORIZED));
226 response.setStatus(HttpServletResponse.SC_FORBIDDEN);
227 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN));
229 if (invocator != null) {
230 logger.warn(EELFLoggerDelegate.errorLogger,
231 invocator + ", permissions problem, response status = " + response.getStatus());
235 public static int getExternalAppResponseCode() {
236 String responseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
237 int responseCodeInt = 0;
239 if (responseCode != null && responseCode != "") {
240 responseCodeInt = Integer.valueOf(responseCode);
242 } catch (Exception e) {
243 logger.error(EELFLoggerDelegate.errorLogger, "getExternalAppResponseCode failed", e);
245 return responseCodeInt;
248 // This method might be just for testing purposes.
249 public static void setExternalAppResponseCode(int responseCode) {
251 String code = String.valueOf(responseCode);
252 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code );
253 code=StringUtils.EMPTY;
254 } catch (Exception e) {
255 logger.error(EELFLoggerDelegate.errorLogger, "setExternalAppResponseCode failed", e);
259 public static String getHTTPStatusString(int httpStatusCode) {
260 String httpStatusString = "unknown_error";
262 httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
263 if (httpStatusString != null) {
264 httpStatusString = httpStatusString.toLowerCase();
266 } catch (Exception e) {
267 logger.error(EELFLoggerDelegate.errorLogger, "getHTTPStatusString failed", e);
269 return httpStatusString;
272 public static String getFEErrorString(Boolean internal, int responseCode) {
273 // Return a String like the following:
274 // "Internal Onap Error: 500 internal_server_error" or
275 // "External App Error: 404 not_found"
276 // TODO: create our own Ecomp error codes, starting with 1000 and up.
277 String internalExternalString = internal ? "Ecomp Error: " : "App Error: ";
278 String httpStatusString = "unknown_error";
280 if (responseCode < 1000) {
281 httpStatusString = getHTTPStatusString(responseCode);
283 } catch (Exception e) {
284 logger.error(EELFLoggerDelegate.errorLogger, "getFEErrorString failed", e);
286 String responseString = internalExternalString + responseCode + " " + httpStatusString;
287 return responseString;
290 public static boolean isProductionBuild() {
291 boolean productionBuild = true;
292 String epVersion = EcompVersion.buildNumber;
293 if (epVersion != null) {
294 int buildNum = epVersion.lastIndexOf('.');
296 int buildNumber = Integer.parseInt(epVersion.substring(buildNum + 1));
297 if (buildNumber < 3000) // Production versions are 3000+, (ie
300 productionBuild = false;
304 return productionBuild;
307 public static String getMyIpAdddress() {
311 ip = InetAddress.getLocalHost();
312 localIp = ip.getHostAddress();
313 } catch (UnknownHostException e) {
315 logger.error(EELFLoggerDelegate.errorLogger, "getMyIpAdddress failed ", e);
320 public static String getMyHostName() {
324 ip = InetAddress.getLocalHost();
325 hostName = ip.getHostName();
326 } catch (UnknownHostException e) {
327 hostName = "unknown";
328 logger.error(EELFLoggerDelegate.errorLogger, "getMyHostName failed", e);
334 * Returns a default property if the expected one is not available
338 * @param defaultValue
340 * @return Default value if property is not defined or yields the empty string;
341 * else the property value.
343 public static String getPropertyOrDefault(String property, String defaultValue) {
344 if (!SystemProperties.containsProperty(property))
346 String value = SystemProperties.getProperty(property);
347 if (value == null || "".equals(value))
353 * Calculates the time duration of a function call for logging purpose. It
354 * stores the result by using "MDC.put(SystemProperties.MDC_TIMER,
355 * timeDifference);" It is important to call
356 * "MDC.remove(SystemProperties.MDC_TIMER);" after this method call to clean up
359 * @param beginDateTime
360 * the given begin time for the call
362 * the given end time for the call
365 public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) {
366 if (beginDateTime != null && endDateTime != null) {
368 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
370 Date beginDate = ecompLogDateFormat.parse(beginDateTime);
371 Date endDate = ecompLogDateFormat.parse(endDateTime);
372 String timeDifference = String.format("%d", endDate.getTime() - beginDate.getTime());
373 MDC.put(SystemProperties.MDC_TIMER, timeDifference);
374 } catch (Exception e) {
375 logger.error(EELFLoggerDelegate.errorLogger, "calculateDateTimeDifferenceForLog failed", e);
381 * Answers the protocol to use.
383 * @return Protocol name from property file; defaults to https.
385 public static String widgetMsProtocol() {
386 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_PROTOCOL, "https");
390 * Answers the host to use.
392 * @return Host name from property file; defaults to localhost.
394 public static String localOrDockerHost() {
395 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_HOSTNAME, "localhost");
399 * It returns headers where username and password of external central auth is
402 * @return header which contains external central auth username and password
405 * if unable to decrypt the password
407 public static HttpHeaders base64encodeKeyForAAFBasicAuth() throws Exception {
408 String userName = "";
409 String decryptedPass = "";
410 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME)
411 && EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD)) {
412 decryptedPass = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD);
413 userName = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
415 String decPass = decrypted(decryptedPass);
416 String usernamePass = userName + ":" + decPass;
417 String encToBase64 = String.valueOf((DatatypeConverter.printBase64Binary(usernamePass.getBytes())));
418 HttpHeaders headers = new HttpHeaders();
419 headers.add("Authorization", "Basic " + encToBase64);
420 headers.setContentType(MediaType.APPLICATION_JSON);
424 private static String decrypted(String encrypted) throws Exception {
426 if (encrypted != null && encrypted.length() > 0) {
428 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
429 } catch (Exception e) {
430 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
437 public static String truncateString(String originString, int size){
438 if(originString.length()>=size){
439 StringBuilder stringBuilder = new StringBuilder();
440 stringBuilder.append(originString);
441 stringBuilder.setLength(size);
442 stringBuilder.append("...");
443 return stringBuilder.toString();
450 * If function code value has any pipes it does pipe filter and
453 * @param functionCode
454 * @return function instance without pipe
456 public static String getFunctionCode(String functionCode) {
457 String finalFunctionCodeVal = "";
458 if (functionCode.contains(FUNCTION_PIPE)) {
459 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
461 finalFunctionCodeVal = functionCode.substring(
462 functionCode.indexOf(FUNCTION_PIPE) + 1,
463 functionCode.lastIndexOf(FUNCTION_PIPE));
465 finalFunctionCodeVal = functionCode
466 .substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
468 finalFunctionCodeVal = functionCode;
470 return finalFunctionCodeVal;
475 * If function code value has any pipes it does pipe filter and
478 * @param functionCode
479 * @return function Type without pipe
481 public static String getFunctionType(String functionCode) {
482 String finalFunctionCodeVal = "";
483 if (functionCode.contains(FUNCTION_PIPE)) {
484 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
486 String[] getTypeValue = functionCode.split("\\"+FUNCTION_PIPE);
487 finalFunctionCodeVal = getTypeValue[0];
490 finalFunctionCodeVal = functionCode;
492 return finalFunctionCodeVal;
497 * If function code value has any pipes it does pipe filter and
500 * @param functionCode
501 * @return function Action without pipe
503 public static String getFunctionAction(String functionCode) {
504 String finalFunctionCodeVal = "";
505 if (functionCode.contains(FUNCTION_PIPE)) {
506 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
508 finalFunctionCodeVal = functionCode.substring(
509 functionCode.lastIndexOf(FUNCTION_PIPE)+1);
511 finalFunctionCodeVal = functionCode;
513 return finalFunctionCodeVal;
518 * It check whether the external auth namespace is matching with current namespace exists in local DB
521 * @param appNamespaceVal
522 * @return true or false
524 public static boolean checkNameSpaceMatching(String permTypeVal, String appNamespaceVal) {
525 String[] typeNamespace = permTypeVal.split("\\.");
526 String[] appNamespace = appNamespaceVal.split("\\.");
527 boolean isNamespaceMatching = true;
528 if (appNamespace.length <= typeNamespace.length) {
529 for (int k = 0; k < appNamespace.length; k++) {
530 if (!appNamespace[k].equals(typeNamespace[k]))
531 isNamespaceMatching = false;
534 isNamespaceMatching = false;
536 return isNamespaceMatching;
539 public static boolean checkIfRemoteCentralAccessAllowed() {
540 boolean result = false;
541 String rmtCentralAccess = SystemProperties.getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS);
542 if(rmtCentralAccess == null) {
543 logger.error(EELFLoggerDelegate.errorLogger, "Please check in system.properties whether the property exists or not!");
545 }else if(new Boolean(rmtCentralAccess)){
546 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}",rmtCentralAccess);
554 * It validates whether given string is JSON or not
556 * @param jsonInString
557 * @return true or false
559 public static boolean isJSONValid(String jsonInString ) {
561 final ObjectMapper mapper = new ObjectMapper();
562 mapper.readTree(jsonInString);
564 } catch (IOException e) {
565 logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e);
571 * It retrieves account information from input String
574 * @return Array of Account information
577 public static String[] getUserNamePassword(String authValue) {
578 String base64Credentials = authValue.substring("Basic".length()).trim();
579 String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
580 final String[] values = credentials.split(":", 2);