2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 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.text.SimpleDateFormat;
44 import java.util.ArrayList;
45 import java.util.Date;
46 import java.util.List;
48 import javax.servlet.http.HttpServletResponse;
49 import javax.xml.bind.DatatypeConverter;
51 import org.apache.commons.lang.StringUtils;
52 import org.hibernate.Session;
53 import org.hibernate.Transaction;
54 import org.onap.portalapp.portal.domain.EPUser;
55 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
56 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
57 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
58 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
59 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
60 import org.onap.portalsdk.core.util.SystemProperties;
62 import org.springframework.http.HttpHeaders;
63 import org.springframework.http.MediaType;
65 import com.fasterxml.jackson.core.JsonProcessingException;
66 import com.fasterxml.jackson.databind.ObjectMapper;
68 public class EcompPortalUtils {
70 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class);
72 private static final String FUNCTION_PIPE = "|";
74 // TODO: GLOBAL_LOGIN_URL is the same as in SessionTimeoutInterceptor.
75 // It should be defined in SystemProperties.
76 private static final String GLOBAL_LOGIN_URL = "global-login-url";
78 // It is a regular expression used for while creating a External Central Auth Role
79 public static final String EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS = "([^A-Z^a-z^0-9^\\.^%^(^)^=^:])";
84 * @return true if orgUserId is not empty and contains only alphanumeric, false
87 public static boolean legitimateUserId(String orgUserId) {
88 return orgUserId.matches("^[a-zA-Z0-9]+$");
92 * Splits the string into a list of tokens using the specified regular
99 * @return List of tokens split from the source
101 public static List<String> parsingByRegularExpression(String source, String regex) {
102 List<String> tokens = new ArrayList<String>();
103 if (source != null && source.length() > 0) {
104 String[] parsed = source.split(regex);
105 for (String token : parsed) {
106 if (token.length() > 0) {
115 * Builds a JSON object with error code and message information.
119 * @param errorMessage
121 * @return JSON object as a String
123 public static String jsonErrorMessageResponse(int errorCode, String errorMessage) {
124 return "{\"error\":{\"code\":" + errorCode + "," + "\"message\":\"" + errorMessage + "\"}}";
128 * Builds a JSON object with the specified message
132 * @return JSON object as a String
134 public static String jsonMessageResponse(String message) {
135 return String.format("{\"message\":\"%s\"}", message);
139 * Serializes the specified object as JSON and writes the result to the debug
140 * log. If serialization fails, logs a message to the error logger.
143 * Logger for the class where the object was built; the logger
144 * carries the class name.
146 * First portion of the log message
148 * Second portion of the log message
150 * Object to serialize as JSON
152 public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) {
154 String objectAsJson = new ObjectMapper().writeValueAsString(obj);
155 logger.debug(EELFLoggerDelegate.debugLogger,
156 String.format("source= [%s]; %s [%s];", source, msg, objectAsJson));
157 } catch (JsonProcessingException e) {
158 logger.warn(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed to serialize", e);
159 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
160 } catch (Exception e) {
161 logger.error(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed", e);
162 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
167 * Serializes the specified object as JSON and writes the result to the debug
168 * log. If serialization fails, logs a message to the error logger.
171 * First portion of the log message
173 * Second portion of the log message
175 * Object to serialize as JSON
177 public static void logAndSerializeObject(String source, String msg, Object obj) {
178 logAndSerializeObject(logger, source, msg, obj);
181 public static void rollbackTransaction(Transaction transaction, String errorMessage) {
182 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
184 if (transaction != null) {
185 transaction.rollback();
187 } catch (Exception e) {
188 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
189 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing a rollback transaction",
194 public static void closeLocalSession(Session localSession, String errorMessage) {
195 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
197 if (localSession != null) {
198 localSession.close();
200 } catch (Exception e) {
201 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
202 logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception", e);
207 * Set response status to Unauthorized if user == null and to Forbidden in all
208 * (!) other cases. Logging is not performed if invocator == null
213 * HttpServletResponse
217 public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) {
219 String loginUrl = SystemProperties.getProperty(EPCommonSystemProperties.LOGIN_URL_NO_RET_VAL);
220 response.setHeader(GLOBAL_LOGIN_URL, loginUrl);
221 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
222 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_UNAUTHORIZED));
224 response.setStatus(HttpServletResponse.SC_FORBIDDEN);
225 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN));
227 if (invocator != null) {
228 logger.warn(EELFLoggerDelegate.errorLogger,
229 invocator + ", permissions problem, response status = " + response.getStatus());
233 public static int getExternalAppResponseCode() {
234 String responseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
235 int responseCodeInt = 0;
237 if (responseCode != null && responseCode != "") {
238 responseCodeInt = Integer.valueOf(responseCode);
240 } catch (Exception e) {
241 logger.error(EELFLoggerDelegate.errorLogger, "getExternalAppResponseCode failed", e);
243 return responseCodeInt;
246 // This method might be just for testing purposes.
247 public static void setExternalAppResponseCode(int responseCode) {
249 String code = String.valueOf(responseCode);
250 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code );
251 code=StringUtils.EMPTY;
252 } catch (Exception e) {
253 logger.error(EELFLoggerDelegate.errorLogger, "setExternalAppResponseCode failed", e);
257 public static String getHTTPStatusString(int httpStatusCode) {
258 String httpStatusString = "unknown_error";
260 httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
261 if (httpStatusString != null) {
262 httpStatusString = httpStatusString.toLowerCase();
264 } catch (Exception e) {
265 logger.error(EELFLoggerDelegate.errorLogger, "getHTTPStatusString failed", e);
267 return httpStatusString;
270 public static String getFEErrorString(Boolean internal, int responseCode) {
271 // Return a String like the following:
272 // "Internal Onap Error: 500 internal_server_error" or
273 // "External App Error: 404 not_found"
274 // TODO: create our own Ecomp error codes, starting with 1000 and up.
275 String internalExternalString = internal ? "Ecomp Error: " : "App Error: ";
276 String httpStatusString = "unknown_error";
278 if (responseCode < 1000) {
279 httpStatusString = getHTTPStatusString(responseCode);
281 } catch (Exception e) {
282 logger.error(EELFLoggerDelegate.errorLogger, "getFEErrorString failed", e);
284 String responseString = internalExternalString + responseCode + " " + httpStatusString;
285 return responseString;
288 public static boolean isProductionBuild() {
289 boolean productionBuild = true;
290 String epVersion = EcompVersion.buildNumber;
291 if (epVersion != null) {
292 int buildNum = epVersion.lastIndexOf('.');
294 int buildNumber = Integer.parseInt(epVersion.substring(buildNum + 1));
295 if (buildNumber < 3000) // Production versions are 3000+, (ie
298 productionBuild = false;
302 return productionBuild;
305 public static String getMyIpAdddress() {
309 ip = InetAddress.getLocalHost();
310 localIp = ip.getHostAddress();
311 } catch (UnknownHostException e) {
313 logger.error(EELFLoggerDelegate.errorLogger, "getMyIpAdddress failed ", e);
318 public static String getMyHostName() {
322 ip = InetAddress.getLocalHost();
323 hostName = ip.getHostName();
324 } catch (UnknownHostException e) {
325 hostName = "unknown";
326 logger.error(EELFLoggerDelegate.errorLogger, "getMyHostName failed", e);
332 * Returns a default property if the expected one is not available
336 * @param defaultValue
338 * @return Default value if property is not defined or yields the empty string;
339 * else the property value.
341 public static String getPropertyOrDefault(String property, String defaultValue) {
342 if (!SystemProperties.containsProperty(property))
344 String value = SystemProperties.getProperty(property);
345 if (value == null || "".equals(value))
351 * Calculates the time duration of a function call for logging purpose. It
352 * stores the result by using "MDC.put(SystemProperties.MDC_TIMER,
353 * timeDifference);" It is important to call
354 * "MDC.remove(SystemProperties.MDC_TIMER);" after this method call to clean up
357 * @param beginDateTime
358 * the given begin time for the call
360 * the given end time for the call
363 public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) {
364 if (beginDateTime != null && endDateTime != null) {
366 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
368 Date beginDate = ecompLogDateFormat.parse(beginDateTime);
369 Date endDate = ecompLogDateFormat.parse(endDateTime);
370 String timeDifference = String.format("%d", endDate.getTime() - beginDate.getTime());
371 MDC.put(SystemProperties.MDC_TIMER, timeDifference);
372 } catch (Exception e) {
373 logger.error(EELFLoggerDelegate.errorLogger, "calculateDateTimeDifferenceForLog failed", e);
379 * Answers the protocol to use.
381 * @return Protocol name from property file; defaults to https.
383 public static String widgetMsProtocol() {
384 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_PROTOCOL, "https");
388 * Answers the host to use.
390 * @return Host name from property file; defaults to localhost.
392 public static String localOrDockerHost() {
393 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_HOSTNAME, "localhost");
397 * It returns headers where username and password of external central auth is
400 * @return header which contains external central auth username and password
403 * if unable to decrypt the password
405 public static HttpHeaders base64encodeKeyForAAFBasicAuth() throws Exception {
406 String userName = "";
407 String decryptedPass = "";
408 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME)
409 && EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD)) {
410 decryptedPass = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD);
411 userName = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
413 String decPass = decrypted(decryptedPass);
414 String usernamePass = userName + ":" + decPass;
415 String encToBase64 = String.valueOf((DatatypeConverter.printBase64Binary(usernamePass.getBytes())));
416 HttpHeaders headers = new HttpHeaders();
417 headers.add("Authorization", "Basic " + encToBase64);
418 headers.setContentType(MediaType.APPLICATION_JSON);
422 private static String decrypted(String encrypted) throws Exception {
424 if (encrypted != null && encrypted.length() > 0) {
426 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
427 } catch (Exception e) {
428 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
435 public static String truncateString(String originString, int size){
436 if(originString.length()>=size){
437 StringBuilder stringBuilder = new StringBuilder();
438 stringBuilder.append(originString);
439 stringBuilder.setLength(size);
440 stringBuilder.append("...");
441 return stringBuilder.toString();
448 * If function code value has any pipes it does pipe filter and
451 * @param functionCode
452 * @return function instance without pipe
454 public static String getFunctionCode(String functionCode) {
455 String finalFunctionCodeVal = "";
456 if (functionCode.contains(FUNCTION_PIPE)) {
457 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
459 finalFunctionCodeVal = functionCode.substring(
460 functionCode.indexOf(FUNCTION_PIPE) + 1,
461 functionCode.lastIndexOf(FUNCTION_PIPE));
463 finalFunctionCodeVal = functionCode
464 .substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
466 finalFunctionCodeVal = functionCode;
468 return finalFunctionCodeVal;
473 * If function code value has any pipes it does pipe filter and
476 * @param functionCode
477 * @return function Type without pipe
479 public static String getFunctionType(String functionCode) {
480 String finalFunctionCodeVal = "";
481 if (functionCode.contains(FUNCTION_PIPE)) {
482 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
484 String[] getTypeValue = functionCode.split("\\"+FUNCTION_PIPE);
485 finalFunctionCodeVal = getTypeValue[0];
488 finalFunctionCodeVal = functionCode;
490 return finalFunctionCodeVal;
495 * If function code value has any pipes it does pipe filter and
498 * @param functionCode
499 * @return function Action without pipe
501 public static String getFunctionAction(String functionCode) {
502 String finalFunctionCodeVal = "";
503 if (functionCode.contains(FUNCTION_PIPE)) {
504 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
506 finalFunctionCodeVal = functionCode.substring(
507 functionCode.lastIndexOf(FUNCTION_PIPE)+1);
509 finalFunctionCodeVal = functionCode;
511 return finalFunctionCodeVal;
516 * It check whether the external auth namespace is matching with current namespace exists in local DB
519 * @param appNamespaceVal
520 * @return true or false
522 public static boolean checkNameSpaceMatching(String permTypeVal, String appNamespaceVal) {
523 String[] typeNamespace = permTypeVal.split("\\.");
524 String[] appNamespace = appNamespaceVal.split("\\.");
525 boolean isNamespaceMatching = true;
526 if (appNamespace.length <= typeNamespace.length) {
527 for (int k = 0; k < appNamespace.length; k++) {
528 if (!appNamespace[k].equals(typeNamespace[k]))
529 isNamespaceMatching = false;
532 isNamespaceMatching = false;
534 return isNamespaceMatching;
537 public static boolean checkIfRemoteCentralAccessAllowed() {
538 boolean result = false;
539 String rmtCentralAccess = SystemProperties.getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS);
540 if(rmtCentralAccess == null) {
541 logger.error(EELFLoggerDelegate.errorLogger, "Please check in system.properties whether the property exists or not!");
543 }else if(new Boolean(rmtCentralAccess)){
544 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}",rmtCentralAccess);
552 * It validates whether given string is JSON or not
554 * @param jsonInString
555 * @return true or false
557 public static boolean isJSONValid(String jsonInString ) {
559 final ObjectMapper mapper = new ObjectMapper();
560 mapper.readTree(jsonInString);
562 } catch (IOException e) {
563 logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e);