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;
51 import javax.servlet.http.HttpServletResponse;
52 import javax.xml.bind.DatatypeConverter;
54 import org.apache.commons.lang.StringUtils;
55 import org.hibernate.Session;
56 import org.hibernate.Transaction;
57 import org.onap.portalapp.portal.domain.EPUser;
58 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
59 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
60 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
61 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
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 String code = Integer.toString(responseCode);
255 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code );
256 char[] chars=code.toCharArray();
257 Arrays.fill(chars, ' ');
258 } catch (Exception e) {
259 logger.error(EELFLoggerDelegate.errorLogger, "setExternalAppResponseCode failed", e);
263 public static String getHTTPStatusString(int httpStatusCode) {
264 String httpStatusString = "unknown_error";
266 httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
267 if (httpStatusString != null) {
268 httpStatusString = httpStatusString.toLowerCase();
270 } catch (Exception e) {
271 logger.error(EELFLoggerDelegate.errorLogger, "getHTTPStatusString failed", e);
273 return httpStatusString;
276 public static String getFEErrorString(Boolean internal, int responseCode) {
277 // Return a String like the following:
278 // "Internal Onap Error: 500 internal_server_error" or
279 // "External App Error: 404 not_found"
280 // TODO: create our own Ecomp error codes, starting with 1000 and up.
281 String internalExternalString = internal ? "Ecomp Error: " : "App Error: ";
282 String httpStatusString = "unknown_error";
284 if (responseCode < 1000) {
285 httpStatusString = getHTTPStatusString(responseCode);
287 } catch (Exception e) {
288 logger.error(EELFLoggerDelegate.errorLogger, "getFEErrorString failed", e);
290 String responseString = internalExternalString + responseCode + " " + httpStatusString;
291 return responseString;
294 public static boolean isProductionBuild() {
295 boolean productionBuild = true;
296 String epVersion = EcompVersion.buildNumber;
297 if (epVersion != null) {
298 int buildNum = epVersion.lastIndexOf('.');
300 int buildNumber = Integer.parseInt(epVersion.substring(buildNum + 1));
301 if (buildNumber < 3000) // Production versions are 3000+, (ie
304 productionBuild = false;
308 return productionBuild;
311 public static String getMyIpAdddress() {
315 ip = InetAddress.getLocalHost();
316 localIp = ip.getHostAddress();
317 } catch (UnknownHostException e) {
319 logger.error(EELFLoggerDelegate.errorLogger, "getMyIpAdddress failed ", e);
324 public static String getMyHostName() {
328 ip = InetAddress.getLocalHost();
329 hostName = ip.getHostName();
330 } catch (UnknownHostException e) {
331 hostName = "unknown";
332 logger.error(EELFLoggerDelegate.errorLogger, "getMyHostName failed", e);
338 * Returns a default property if the expected one is not available
342 * @param defaultValue
344 * @return Default value if property is not defined or yields the empty string;
345 * else the property value.
347 public static String getPropertyOrDefault(String property, String defaultValue) {
348 if (!SystemProperties.containsProperty(property))
350 String value = SystemProperties.getProperty(property);
351 if (value == null || "".equals(value))
357 * Calculates the time duration of a function call for logging purpose. It
358 * stores the result by using "MDC.put(SystemProperties.MDC_TIMER,
359 * timeDifference);" It is important to call
360 * "MDC.remove(SystemProperties.MDC_TIMER);" after this method call to clean up
363 * @param beginDateTime
364 * the given begin time for the call
366 * the given end time for the call
369 public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) {
370 if (beginDateTime != null && endDateTime != null) {
372 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
374 Date beginDate = ecompLogDateFormat.parse(beginDateTime);
375 Date endDate = ecompLogDateFormat.parse(endDateTime);
376 String timeDifference = String.format("%d", endDate.getTime() - beginDate.getTime());
377 MDC.put(SystemProperties.MDC_TIMER, timeDifference);
378 } catch (Exception e) {
379 logger.error(EELFLoggerDelegate.errorLogger, "calculateDateTimeDifferenceForLog failed", e);
385 * Answers the protocol to use.
387 * @return Protocol name from property file; defaults to https.
389 public static String widgetMsProtocol() {
390 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_PROTOCOL, "https");
394 * Answers the host to use.
396 * @return Host name from property file; defaults to localhost.
398 public static String localOrDockerHost() {
399 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_HOSTNAME, "localhost");
403 * It returns headers where username and password of external central auth is
406 * @return header which contains external central auth username and password
409 * if unable to decrypt the password
411 public static HttpHeaders base64encodeKeyForAAFBasicAuth() throws Exception {
412 String userName = "";
413 String decryptedPass = "";
414 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME)
415 && EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD)) {
416 decryptedPass = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD);
417 userName = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
419 String decPass = decrypted(decryptedPass);
420 String usernamePass = userName + ":" + decPass;
421 String encToBase64 = String.valueOf((DatatypeConverter.printBase64Binary(usernamePass.getBytes())));
422 HttpHeaders headers = new HttpHeaders();
423 headers.add("Authorization", "Basic " + encToBase64);
424 headers.setContentType(MediaType.APPLICATION_JSON);
428 private static String decrypted(String encrypted) throws Exception {
430 if (encrypted != null && encrypted.length() > 0) {
432 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
433 } catch (Exception e) {
434 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
441 public static String truncateString(String originString, int size){
442 if(originString.length()>=size){
443 StringBuilder stringBuilder = new StringBuilder();
444 stringBuilder.append(originString);
445 stringBuilder.setLength(size);
446 stringBuilder.append("...");
447 return stringBuilder.toString();
454 * If function code value has any pipes it does pipe filter and
457 * @param functionCode
458 * @return function instance without pipe
460 public static String getFunctionCode(String functionCode) {
461 String finalFunctionCodeVal = "";
462 if (functionCode.contains(FUNCTION_PIPE)) {
463 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
465 finalFunctionCodeVal = functionCode.substring(
466 functionCode.indexOf(FUNCTION_PIPE) + 1,
467 functionCode.lastIndexOf(FUNCTION_PIPE));
469 finalFunctionCodeVal = functionCode
470 .substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
472 finalFunctionCodeVal = functionCode;
474 return finalFunctionCodeVal;
479 * If function code value has any pipes it does pipe filter and
482 * @param functionCode
483 * @return function Type without pipe
485 public static String getFunctionType(String functionCode) {
486 String finalFunctionCodeVal = "";
487 if (functionCode.contains(FUNCTION_PIPE)) {
488 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
490 String[] getTypeValue = functionCode.split("\\"+FUNCTION_PIPE);
491 finalFunctionCodeVal = getTypeValue[0];
494 finalFunctionCodeVal = functionCode;
496 return finalFunctionCodeVal;
501 * If function code value has any pipes it does pipe filter and
504 * @param functionCode
505 * @return function Action without pipe
507 public static String getFunctionAction(String functionCode) {
508 String finalFunctionCodeVal = "";
509 if (functionCode.contains(FUNCTION_PIPE)) {
510 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
512 finalFunctionCodeVal = functionCode.substring(
513 functionCode.lastIndexOf(FUNCTION_PIPE)+1);
515 finalFunctionCodeVal = functionCode;
517 return finalFunctionCodeVal;
522 * It check whether the external auth namespace is matching with current namespace exists in local DB
525 * @param appNamespaceVal
526 * @return true or false
528 public static boolean checkNameSpaceMatching(String permTypeVal, String appNamespaceVal) {
529 String[] typeNamespace = permTypeVal.split("\\.");
530 String[] appNamespace = appNamespaceVal.split("\\.");
531 boolean isNamespaceMatching = true;
532 if (appNamespace.length <= typeNamespace.length) {
533 for (int k = 0; k < appNamespace.length; k++) {
534 if (!appNamespace[k].equals(typeNamespace[k]))
535 isNamespaceMatching = false;
538 isNamespaceMatching = false;
540 return isNamespaceMatching;
543 public static boolean checkIfRemoteCentralAccessAllowed() {
544 boolean result = false;
545 String rmtCentralAccess = SystemProperties.getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS);
546 if(rmtCentralAccess == null) {
547 logger.error(EELFLoggerDelegate.errorLogger, "Please check in system.properties whether the property exists or not!");
549 }else if(new Boolean(rmtCentralAccess)){
550 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}",rmtCentralAccess);
558 * It validates whether given string is JSON or not
560 * @param jsonInString
561 * @return true or false
563 public static boolean isJSONValid(String jsonInString ) {
565 final ObjectMapper mapper = new ObjectMapper();
566 mapper.readTree(jsonInString);
568 } catch (IOException e) {
569 logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e);
575 * It retrieves account information from input String
578 * @return Array of Account information
581 public static String[] getUserNamePassword(String authValue) {
582 String base64Credentials = authValue.substring("Basic".length()).trim();
583 String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
584 final String[] values = credentials.split(":", 2);