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.util.SystemProperties;
63 import org.springframework.http.HttpHeaders;
64 import org.springframework.http.MediaType;
66 import com.fasterxml.jackson.core.JsonProcessingException;
67 import com.fasterxml.jackson.databind.ObjectMapper;
69 public class EcompPortalUtils {
71 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class);
73 private static final String FUNCTION_PIPE = "|";
75 // TODO: GLOBAL_LOGIN_URL is the same as in SessionTimeoutInterceptor.
76 // It should be defined in SystemProperties.
77 private static final String GLOBAL_LOGIN_URL = "global-login-url";
79 // It is a regular expression used for while creating a External Central Auth Role
80 public static final String EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS = "([^A-Z^a-z^0-9^\\.^%^(^)^=^:])";
85 * @return true if orgUserId is not empty and contains only alphanumeric, false
88 public static boolean legitimateUserId(String orgUserId) {
89 return orgUserId.matches("^[a-zA-Z0-9/_/-/@]+$");
93 * Splits the string into a list of tokens using the specified regular
100 * @return List of tokens split from the source
102 public static List<String> parsingByRegularExpression(String source, String regex) {
103 List<String> tokens = new ArrayList<String>();
104 if (source != null && source.length() > 0) {
105 String[] parsed = source.split(regex);
106 for (String token : parsed) {
107 if (token.length() > 0) {
116 * Builds a JSON object with error code and message information.
120 * @param errorMessage
122 * @return JSON object as a String
124 public static String jsonErrorMessageResponse(int errorCode, String errorMessage) {
125 return "{\"error\":{\"code\":" + errorCode + "," + "\"message\":\"" + errorMessage + "\"}}";
129 * Builds a JSON object with the specified message
133 * @return JSON object as a String
135 public static String jsonMessageResponse(String message) {
136 return String.format("{\"message\":\"%s\"}", message);
140 * Serializes the specified object as JSON and writes the result to the debug
141 * log. If serialization fails, logs a message to the error logger.
144 * Logger for the class where the object was built; the logger
145 * carries the class name.
147 * First portion of the log message
149 * Second portion of the log message
151 * Object to serialize as JSON
153 public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) {
155 String objectAsJson = new ObjectMapper().writeValueAsString(obj);
156 logger.debug(EELFLoggerDelegate.debugLogger,
157 String.format("source= [%s]; %s [%s];", source, msg, objectAsJson));
158 } catch (JsonProcessingException e) {
159 logger.warn(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed to serialize", e);
160 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
161 } catch (Exception e) {
162 logger.error(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed", e);
163 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
168 * Serializes the specified object as JSON and writes the result to the debug
169 * log. If serialization fails, logs a message to the error logger.
172 * First portion of the log message
174 * Second portion of the log message
176 * Object to serialize as JSON
178 public static void logAndSerializeObject(String source, String msg, Object obj) {
179 logAndSerializeObject(logger, source, msg, obj);
182 public static void rollbackTransaction(Transaction transaction, String errorMessage) {
183 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
185 if (transaction != null) {
186 transaction.rollback();
188 } catch (Exception e) {
189 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
190 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing a rollback transaction",
195 public static void closeLocalSession(Session localSession, String errorMessage) {
196 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
198 if (localSession != null) {
199 localSession.close();
201 } catch (Exception e) {
202 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
203 logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception", e);
208 * Set response status to Unauthorized if user == null and to Forbidden in all
209 * (!) other cases. Logging is not performed if invocator == null
214 * HttpServletResponse
218 public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) {
220 String loginUrl = SystemProperties.getProperty(EPCommonSystemProperties.LOGIN_URL_NO_RET_VAL);
221 response.setHeader(GLOBAL_LOGIN_URL, loginUrl);
222 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
223 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_UNAUTHORIZED));
225 response.setStatus(HttpServletResponse.SC_FORBIDDEN);
226 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN));
228 if (invocator != null) {
229 logger.warn(EELFLoggerDelegate.errorLogger,
230 invocator + ", permissions problem, response status = " + response.getStatus());
234 public static int getExternalAppResponseCode() {
235 String responseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
236 int responseCodeInt = 0;
238 if (responseCode != null && responseCode != "") {
239 responseCodeInt = Integer.valueOf(responseCode);
241 } catch (Exception e) {
242 logger.error(EELFLoggerDelegate.errorLogger, "getExternalAppResponseCode failed", e);
244 return responseCodeInt;
247 // This method might be just for testing purposes.
248 public static void setExternalAppResponseCode(int responseCode) {
250 String code = String.valueOf(responseCode);
251 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code );
252 code=StringUtils.EMPTY;
253 } catch (Exception e) {
254 logger.error(EELFLoggerDelegate.errorLogger, "setExternalAppResponseCode failed", e);
258 public static String getHTTPStatusString(int httpStatusCode) {
259 String httpStatusString = "unknown_error";
261 httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
262 if (httpStatusString != null) {
263 httpStatusString = httpStatusString.toLowerCase();
265 } catch (Exception e) {
266 logger.error(EELFLoggerDelegate.errorLogger, "getHTTPStatusString failed", e);
268 return httpStatusString;
271 public static String getFEErrorString(Boolean internal, int responseCode) {
272 // Return a String like the following:
273 // "Internal Onap Error: 500 internal_server_error" or
274 // "External App Error: 404 not_found"
275 // TODO: create our own Ecomp error codes, starting with 1000 and up.
276 String internalExternalString = internal ? "Ecomp Error: " : "App Error: ";
277 String httpStatusString = "unknown_error";
279 if (responseCode < 1000) {
280 httpStatusString = getHTTPStatusString(responseCode);
282 } catch (Exception e) {
283 logger.error(EELFLoggerDelegate.errorLogger, "getFEErrorString failed", e);
285 String responseString = internalExternalString + responseCode + " " + httpStatusString;
286 return responseString;
289 public static boolean isProductionBuild() {
290 boolean productionBuild = true;
291 String epVersion = EcompVersion.buildNumber;
292 if (epVersion != null) {
293 int buildNum = epVersion.lastIndexOf('.');
295 int buildNumber = Integer.parseInt(epVersion.substring(buildNum + 1));
296 if (buildNumber < 3000) // Production versions are 3000+, (ie
299 productionBuild = false;
303 return productionBuild;
306 public static String getMyIpAdddress() {
310 ip = InetAddress.getLocalHost();
311 localIp = ip.getHostAddress();
312 } catch (UnknownHostException e) {
314 logger.error(EELFLoggerDelegate.errorLogger, "getMyIpAdddress failed ", e);
319 public static String getMyHostName() {
323 ip = InetAddress.getLocalHost();
324 hostName = ip.getHostName();
325 } catch (UnknownHostException e) {
326 hostName = "unknown";
327 logger.error(EELFLoggerDelegate.errorLogger, "getMyHostName failed", e);
333 * Returns a default property if the expected one is not available
337 * @param defaultValue
339 * @return Default value if property is not defined or yields the empty string;
340 * else the property value.
342 public static String getPropertyOrDefault(String property, String defaultValue) {
343 if (!SystemProperties.containsProperty(property))
345 String value = SystemProperties.getProperty(property);
346 if (value == null || "".equals(value))
352 * Calculates the time duration of a function call for logging purpose. It
353 * stores the result by using "MDC.put(SystemProperties.MDC_TIMER,
354 * timeDifference);" It is important to call
355 * "MDC.remove(SystemProperties.MDC_TIMER);" after this method call to clean up
358 * @param beginDateTime
359 * the given begin time for the call
361 * the given end time for the call
364 public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) {
365 if (beginDateTime != null && endDateTime != null) {
367 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
369 Date beginDate = ecompLogDateFormat.parse(beginDateTime);
370 Date endDate = ecompLogDateFormat.parse(endDateTime);
371 String timeDifference = String.format("%d", endDate.getTime() - beginDate.getTime());
372 MDC.put(SystemProperties.MDC_TIMER, timeDifference);
373 } catch (Exception e) {
374 logger.error(EELFLoggerDelegate.errorLogger, "calculateDateTimeDifferenceForLog failed", e);
380 * Answers the protocol to use.
382 * @return Protocol name from property file; defaults to https.
384 public static String widgetMsProtocol() {
385 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_PROTOCOL, "https");
389 * Answers the host to use.
391 * @return Host name from property file; defaults to localhost.
393 public static String localOrDockerHost() {
394 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_HOSTNAME, "localhost");
398 * It returns headers where username and password of external central auth is
401 * @return header which contains external central auth username and password
404 * if unable to decrypt the password
406 public static HttpHeaders base64encodeKeyForAAFBasicAuth() throws Exception {
407 String userName = "";
408 String decryptedPass = "";
409 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME)
410 && EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD)) {
411 decryptedPass = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD);
412 userName = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
414 String decPass = decrypted(decryptedPass);
415 String usernamePass = userName + ":" + decPass;
416 String encToBase64 = String.valueOf((DatatypeConverter.printBase64Binary(usernamePass.getBytes())));
417 HttpHeaders headers = new HttpHeaders();
418 headers.add("Authorization", "Basic " + encToBase64);
419 headers.setContentType(MediaType.APPLICATION_JSON);
423 private static String decrypted(String encrypted) throws Exception {
425 if (encrypted != null && encrypted.length() > 0) {
427 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
428 } catch (Exception e) {
429 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
436 public static String truncateString(String originString, int size){
437 if(originString.length()>=size){
438 StringBuilder stringBuilder = new StringBuilder();
439 stringBuilder.append(originString);
440 stringBuilder.setLength(size);
441 stringBuilder.append("...");
442 return stringBuilder.toString();
449 * If function code value has any pipes it does pipe filter and
452 * @param functionCode
453 * @return function instance without pipe
455 public static String getFunctionCode(String functionCode) {
456 String finalFunctionCodeVal = "";
457 if (functionCode.contains(FUNCTION_PIPE)) {
458 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
460 finalFunctionCodeVal = functionCode.substring(
461 functionCode.indexOf(FUNCTION_PIPE) + 1,
462 functionCode.lastIndexOf(FUNCTION_PIPE));
464 finalFunctionCodeVal = functionCode
465 .substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
467 finalFunctionCodeVal = functionCode;
469 return finalFunctionCodeVal;
474 * If function code value has any pipes it does pipe filter and
477 * @param functionCode
478 * @return function Type without pipe
480 public static String getFunctionType(String functionCode) {
481 String finalFunctionCodeVal = "";
482 if (functionCode.contains(FUNCTION_PIPE)) {
483 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
485 String[] getTypeValue = functionCode.split("\\"+FUNCTION_PIPE);
486 finalFunctionCodeVal = getTypeValue[0];
489 finalFunctionCodeVal = functionCode;
491 return finalFunctionCodeVal;
496 * If function code value has any pipes it does pipe filter and
499 * @param functionCode
500 * @return function Action without pipe
502 public static String getFunctionAction(String functionCode) {
503 String finalFunctionCodeVal = "";
504 if (functionCode.contains(FUNCTION_PIPE)) {
505 int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
507 finalFunctionCodeVal = functionCode.substring(
508 functionCode.lastIndexOf(FUNCTION_PIPE)+1);
510 finalFunctionCodeVal = functionCode;
512 return finalFunctionCodeVal;
517 * It check whether the external auth namespace is matching with current namespace exists in local DB
520 * @param appNamespaceVal
521 * @return true or false
523 public static boolean checkNameSpaceMatching(String permTypeVal, String appNamespaceVal) {
524 String[] typeNamespace = permTypeVal.split("\\.");
525 String[] appNamespace = appNamespaceVal.split("\\.");
526 boolean isNamespaceMatching = true;
527 if (appNamespace.length <= typeNamespace.length) {
528 for (int k = 0; k < appNamespace.length; k++) {
529 if (!appNamespace[k].equals(typeNamespace[k]))
530 isNamespaceMatching = false;
533 isNamespaceMatching = false;
535 return isNamespaceMatching;
538 public static boolean checkIfRemoteCentralAccessAllowed() {
539 boolean result = false;
540 String rmtCentralAccess = SystemProperties.getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS);
541 if(rmtCentralAccess == null) {
542 logger.error(EELFLoggerDelegate.errorLogger, "Please check in system.properties whether the property exists or not!");
544 }else if(new Boolean(rmtCentralAccess)){
545 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}",rmtCentralAccess);
553 * It validates whether given string is JSON or not
555 * @param jsonInString
556 * @return true or false
558 public static boolean isJSONValid(String jsonInString ) {
560 final ObjectMapper mapper = new ObjectMapper();
561 mapper.readTree(jsonInString);
563 } catch (IOException e) {
564 logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e);
570 * It retrieves account information from input String
573 * @return Array of Account information
576 public static String[] getUserNamePassword(String authValue) {
577 String base64Credentials = authValue.substring("Basic".length()).trim();
578 String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
579 final String[] values = credentials.split(":", 2);