diff options
Diffstat (limited to 'ecomp-portal-BE-common/src/main/java')
9 files changed, 220 insertions, 288 deletions
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java index cecbd9bd..6818d505 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java @@ -123,7 +123,7 @@ public class HealthCheckController extends EPUnRestrictedBaseController { HealthStatus healthStatus = new HealthStatus(500, ""); // Return the status as 500 if it suspended due to manual fail over - if (HealthMonitor.isSuspended) { + if (HealthMonitor.isSuspended()) { healthStatus.body = "Suspended"; response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); MDC.put(EPCommonSystemProperties.RESPONSE_CODE, @@ -171,16 +171,15 @@ public class HealthCheckController extends EPUnRestrictedBaseController { // dbInfo.dbClusterStatus = statusOk; // } - if (!HealthMonitor.isDatabasePermissionsOk()) { + if (!HealthMonitor.isDbPermissionsOk()) { dbInfo.dbPermissions = "Problem, check the logs for more details"; EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError); } else { dbInfo.dbPermissions = statusOk; } statusCollection.add(dbInfo); - - org.onap.portalapp.music.util.MusicUtil MusicUtilSDK = new org.onap.portalapp.music.util.MusicUtil(); - if(MusicUtilSDK.isMusicEnable()){ + + if(org.onap.portalapp.music.util.MusicUtil.isMusicEnable()){ HealthStatusInfo CassandraStatusInfo = new HealthStatusInfo("Music-Cassandra"); //CassandraStatusInfo.hostName = EcompPortalUtils.getMyHostName(); CassandraStatusInfo.ipAddress = MusicUtil.getMyCassaHost(); @@ -234,7 +233,7 @@ public class HealthCheckController extends EPUnRestrictedBaseController { public HealthStatus healthCheckSuspend(HttpServletRequest request, HttpServletResponse response) { HealthStatus healthStatus = new HealthStatus(500, "Suspended for manual failover mechanism"); - HealthMonitor.isSuspended = true; + HealthMonitor.setSuspended(true); healthStatus.statusCode = 200; EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/healthCheckSuspend", "GET result =", @@ -248,7 +247,7 @@ public class HealthCheckController extends EPUnRestrictedBaseController { public HealthStatus healthCheckResume(HttpServletRequest request, HttpServletResponse response) { HealthStatus healthStatus = new HealthStatus(500, "Resumed from manual failover mechanism"); - HealthMonitor.isSuspended = false; + HealthMonitor.setSuspended(false); healthStatus.statusCode = 200; EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/healthCheckResume", "GET result =", response.getStatus()); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/PortalAdminController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/PortalAdminController.java index 1186f444..32b28c7d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/PortalAdminController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/PortalAdminController.java @@ -56,12 +56,15 @@ import org.onap.portalapp.portal.transport.PortalAdmin; import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.util.EPUserUtils; +import org.onap.portalapp.validation.DataValidator; +import org.onap.portalapp.validation.SecureString; import org.onap.portalsdk.core.domain.AuditLog; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.service.AuditService; import org.onap.portalsdk.core.util.SystemProperties; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; @@ -70,18 +73,24 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController -@org.springframework.context.annotation.Configuration +@Configuration @EnableAspectJAutoProxy @EPAuditLog public class PortalAdminController extends EPRestrictedBaseController { - @Autowired - PortalAdminService portalAdminService; - @Autowired - AdminRolesService adminRolesService; - @Autowired - AuditService auditService; + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminController.class); + private static final DataValidator DATA_VALIDATOR = new DataValidator(); - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminController.class); + private PortalAdminService portalAdminService; + private AdminRolesService adminRolesService; + private AuditService auditService; + + @Autowired + public PortalAdminController(PortalAdminService portalAdminService, + AdminRolesService adminRolesService, AuditService auditService){ + this.portalAdminService = portalAdminService; + this.adminRolesService = adminRolesService; + this.auditService = auditService; + } @RequestMapping(value = { "/portalApi/portalAdmins" }, method = RequestMethod.GET, produces = "application/json") public List<PortalAdmin> getPortalAdmins(HttpServletRequest request, HttpServletResponse response) { @@ -116,7 +125,10 @@ public class PortalAdminController extends EPRestrictedBaseController { HttpServletResponse response) { EPUser user = EPUserUtils.getUserSession(request); FieldsValidator fieldsValidator = null; - if (user == null) { + if(!DATA_VALIDATOR.isValid(new SecureString(userId))){ + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin not valid userId"); + EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin"); + }else if (user == null) { logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin, null user"); EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin"); } else if (!adminRolesService.isSuperAdmin(user)) { @@ -158,6 +170,12 @@ public class PortalAdminController extends EPRestrictedBaseController { @RequestMapping(value = { "/portalApi/portalAdmin/{userInfo}" }, method = RequestMethod.DELETE) public FieldsValidator deletePortalAdmin(HttpServletRequest request, @PathVariable("userInfo") String userInfo, HttpServletResponse response) { + + if(!DATA_VALIDATOR.isValid(new SecureString(userInfo))){ + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.deletePortalAdmin not valid userId"); + return null; + } + int userIdIdx = userInfo.indexOf("-"); Long userId = null; String sbcid = null; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserRolesController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserRolesController.java index 97888e56..0d665a98 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserRolesController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserRolesController.java @@ -2,7 +2,7 @@ * ============LICENSE_START========================================== * ONAP Portal * =================================================================== - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -354,18 +354,18 @@ public class UserRolesController extends EPRestrictedBaseController { PortalRestResponse<String> portalResponse = new PortalRestResponse<>(); StringBuilder sbUserApps = new StringBuilder(); if (newAppRolesForUser != null) { - sbUserApps.append("User '" + newAppRolesForUser.orgUserId); - if (newAppRolesForUser.appRoles != null && newAppRolesForUser.appRoles.size() >= 1) { + sbUserApps.append("User '" + newAppRolesForUser.getOrgUserId()); + if (newAppRolesForUser.getAppId() != null && !newAppRolesForUser.getAppRoles().isEmpty()) { sbUserApps.append("' has roles = { "); - for (RoleInAppForUser appRole : newAppRolesForUser.appRoles) { + for (RoleInAppForUser appRole : newAppRolesForUser.getAppRoles()) { if (appRole.isApplied) { sbUserApps.append(appRole.roleName + " ,"); } } sbUserApps.deleteCharAt(sbUserApps.length() - 1); - sbUserApps.append("} assigned for the app " + newAppRolesForUser.appId); + sbUserApps.append("} assigned for the app " + newAppRolesForUser.getAppId()); } else { - sbUserApps.append("' has no roles assigned for app " + newAppRolesForUser.appId); + sbUserApps.append("' has no roles assigned for app " + newAppRolesForUser.getAppId()); } } logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}", sbUserApps.toString()); @@ -383,14 +383,14 @@ public class UserRolesController extends EPRestrictedBaseController { try{ if (changesApplied.isResult()) { logger.info(EELFLoggerDelegate.applicationLogger, - "putAppWithUserRoleStateForUser: succeeded for app {}, user {}", newAppRolesForUser.appId, - newAppRolesForUser.orgUserId); + "putAppWithUserRoleStateForUser: succeeded for app {}, user {}", newAppRolesForUser.getAppId(), + newAppRolesForUser.getAppId()); MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); AuditLog auditLog = new AuditLog(); auditLog.setUserId(user.getId()); auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_USER); - auditLog.setAffectedRecordId(newAppRolesForUser.orgUserId); + auditLog.setAffectedRecordId(newAppRolesForUser.getOrgUserId()); auditLog.setComments(EcompPortalUtils.truncateString(sbUserApps.toString(), PortalConstants.AUDIT_LOG_COMMENT_SIZE)); auditService.logActivity(auditLog, null); @@ -401,7 +401,7 @@ public class UserRolesController extends EPRestrictedBaseController { logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("UserRolesController.putAppWithUserRoleStateForUser", EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(), - newAppRolesForUser.orgUserId, sbUserApps.toString())); + newAppRolesForUser.getOrgUserId(), sbUserApps.toString())); MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); MDC.remove(SystemProperties.MDC_TIMER); @@ -413,8 +413,8 @@ public class UserRolesController extends EPRestrictedBaseController { }catch (Exception e){ logger.error(EELFLoggerDelegate.errorLogger, - "putAppWithUserRoleStateForUser: failed for app {}, user {}", newAppRolesForUser.appId, - newAppRolesForUser.orgUserId); + "putAppWithUserRoleStateForUser: failed for app {}, user {}", newAppRolesForUser.getAppId(), + newAppRolesForUser.getOrgUserId()); portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), null); } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java index 743cbc9a..f1192f92 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java @@ -2,7 +2,7 @@ * ============LICENSE_START========================================== * ONAP Portal * =================================================================== - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -37,13 +37,15 @@ */ package org.onap.portalapp.portal.controller; +import io.swagger.annotations.ApiOperation; +import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; - +import java.util.Objects; import javax.servlet.http.HttpServletRequest; - +import lombok.NoArgsConstructor; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.onap.portalapp.controller.EPRestrictedRESTfulBaseController; @@ -60,7 +62,6 @@ import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.portal.utils.PortalConstants; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse; -import org.onap.portalsdk.core.service.AuditService; import org.onap.portalsdk.core.util.SystemProperties; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; @@ -81,48 +82,29 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.AsyncRestTemplate; -import io.swagger.annotations.ApiOperation; - @RestController @RequestMapping(PortalConstants.REST_AUX_API) @Configuration @EnableAspectJAutoProxy @EPAuditLog +@NoArgsConstructor public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController { - - @Autowired private ConsulHealthService consulHealthService; + private AppsCacheService appCacheService; private static final String MACHINE_LEARNING_SERVICE_CTX = "/ml_api"; private static final String REGISTER_ACTION = MACHINE_LEARNING_SERVICE_CTX + "/" + "registerAction"; private static final String CONSUL_ML_SERVICE_ID = "machine-learning"; private static final String APP_KEY = "uebkey"; - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class); - private AsyncRestTemplate restTemplate = new AsyncRestTemplate(); - + private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class); + private final AsyncRestTemplate restTemplate = new AsyncRestTemplate(); + private final SuccessCallback<ResponseEntity<String>> successCallback = arg -> logger.info(EELFLoggerDelegate.debugLogger, arg.getBody()); + private final FailureCallback failureCallback = arg -> logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg); @Autowired - AuditService auditService; - - @Autowired - AppsCacheService appCacheService; - - SuccessCallback<ResponseEntity<String>> successCallback = new SuccessCallback<ResponseEntity<String>>() { - @Override - public void onSuccess(ResponseEntity<String> arg) { - logger.info(EELFLoggerDelegate.debugLogger, arg.getBody()); - } - }; - - FailureCallback failureCallback = new FailureCallback() { - @Override - public void onFailure(Throwable arg) { - logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg); - } - }; - - protected boolean isAuxRESTfulCall() { - return true; + public WebAnalyticsExtAppController(AppsCacheService appCacheService, ConsulHealthService consulHealthService) { + this.appCacheService = appCacheService; + this.consulHealthService = consulHealthService; } /** @@ -132,12 +114,10 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl * @param request * HttpServletRequest * @return String - * @throws Exception - * on failure */ @ApiOperation(value = "Gets javascript with functions that support gathering and reporting web analytics.", response = String.class) @RequestMapping(value = { "/analytics" }, method = RequestMethod.GET, produces = "application/javascript") - public String getAnalyticsScript(HttpServletRequest request) throws Exception { + public String getAnalyticsScript(HttpServletRequest request) { String responseText = ""; EPApp app = null; String version = ""; @@ -149,31 +129,26 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl } if (app != null) { String restEndPoint = app.getAppRestEndpoint(); - if(restEndPoint.indexOf("/api")!=-1) { + if(restEndPoint.contains("/api")) { version = restEndPoint.substring(restEndPoint.indexOf("/api")+4); } } - String END_POINT = "/storeAnalytics"; + String endPoint = "/storeAnalytics"; if(StringUtils.isNotBlank(version)) { - END_POINT = version + "/storeAnalytics"; + endPoint = version + "/storeAnalytics"; } final String fileName = "analytics.txt"; - InputStream analyticsFileStream = null; - try { - analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName); - responseText = IOUtils.toString(analyticsFileStream, StandardCharsets.UTF_8.name()); - } catch (Exception e) { + try (InputStream analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName)) { + responseText = IOUtils.toString(Objects.requireNonNull(analyticsFileStream), StandardCharsets.UTF_8.name()); + } catch (IOException e) { logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e); - } finally { - if (analyticsFileStream != null) - analyticsFileStream.close(); } String feURLContext = SystemProperties.getProperty("frontend_url"); String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/')); responseText = responseText.replace("PORTAL_ENV_URL", feURL); - responseText = responseText.replace("$END_POINT", END_POINT); + responseText = responseText.replace("$END_POINT", endPoint); return responseText; } @@ -185,14 +160,11 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl * @param analyticsMap * Analytics * @return PortalAPIResponse - * @throws Exception - * on failure */ @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json") @ResponseBody @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class) - public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap) - throws Exception { + public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap) { try { MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); String appName = ""; @@ -225,16 +197,14 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); MDC.remove(SystemProperties.MDC_TIMER); - PortalAPIResponse response = new PortalAPIResponse(true, "success"); - return response; + return new PortalAPIResponse(true, "success"); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e); - PortalAPIResponse response = new PortalAPIResponse(true, "error"); - return response; + return new PortalAPIResponse(true, "error"); } } - protected String getAppName(HttpServletRequest request, String appName) { + private String getAppName(HttpServletRequest request, String appName) { EPApp appRecord = getApp(request); if (appRecord != null) { @@ -243,7 +213,7 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl return appName; } - protected EPApp getApp(HttpServletRequest request) { + private EPApp getApp(HttpServletRequest request) { String appKeyValue = request.getHeader(APP_KEY); EPApp appRecord = null; if (appKeyValue == null || appKeyValue.equals("")) { @@ -254,12 +224,12 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl return appRecord; } - protected void storeAuxAnalytics(Analytics analyticsMap, String appName) { + private void storeAuxAnalytics(Analytics analyticsMap, String appName) { logger.info(EELFLoggerDelegate.debugLogger, " Registering an action for recommendation: AppName/Function/UserId " + appName + "/" + analyticsMap.getFunction() + "/" + analyticsMap.getUserid()); - Map<String, String> requestMapping = new HashMap<String, String>(); + Map<String, String> requestMapping = new HashMap<>(); requestMapping.put("id", analyticsMap.getUserid()); requestMapping.put("action", appName + "|" + analyticsMap.getFunction()); @@ -267,7 +237,7 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl headers.setContentType(MediaType.APPLICATION_JSON); // set your entity to send - HttpEntity<Map<String, String>> entity = new HttpEntity<Map<String, String>>(requestMapping, headers); + HttpEntity<Map<String, String>> entity = new HttpEntity<>(requestMapping, headers); // send it! ListenableFuture<ResponseEntity<String>> out = restTemplate.exchange( diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java index 146050a4..39c906a1 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java @@ -40,6 +40,7 @@ package org.onap.portalapp.portal.interceptor; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.regex.Matcher; @@ -246,7 +247,7 @@ public class PortalResourceInterceptor extends ResourceInterceptor { logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the loop as the uri contains auxapi : {}"); String nameSpace=PortalApiProperties.getProperty(PortalApiConstants.AUTH_NAMESPACE); logger.debug(EELFLoggerDelegate.debugLogger, "namespace form the portal properties : {}",nameSpace); - Boolean accessallowed=AuthUtil.isAccessAllowed(request, nameSpace); + Boolean accessallowed=AuthUtil.isAccessAllowed(request, nameSpace, new HashMap<>()); logger.debug(EELFLoggerDelegate.debugLogger, "AccessAllowed for the request and namespace : {}",accessallowed); if(accessallowed){ logger.debug(EELFLoggerDelegate.debugLogger, "AccessAllowed is allowed: {}",accessallowed); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java index 45b5323c..4805a77d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java @@ -43,8 +43,8 @@ import java.util.List; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; +import lombok.NoArgsConstructor; import org.apache.commons.lang3.StringUtils; -import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.client.FourLetterWordMain; import org.hibernate.Query; import org.hibernate.Session; @@ -61,6 +61,7 @@ import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.transaction.annotation.Transactional; @@ -68,19 +69,14 @@ import org.springframework.transaction.annotation.Transactional; @Transactional -@org.springframework.context.annotation.Configuration +@Configuration @EnableAspectJAutoProxy @EPMetricsLog +@NoArgsConstructor public class HealthMonitor { - - - ZooKeeper zookeeper = null; - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthMonitor.class); - - @Autowired - private SessionFactory sessionFactory; - + private Thread healthMonitorThread; + private static SessionFactory sessionFactory; private static boolean databaseUp; private static boolean uebUp; @@ -89,50 +85,17 @@ public class HealthMonitor { private static boolean dbPermissionsOk; private static boolean zookeeperStatusOk; private static boolean cassandraStatusOk; - private static String APPLICATION = "Portal"; - - /** - * Read directly by external classes. - */ - public static boolean isSuspended = false; - - private Thread healthMonitorThread; - - public HealthMonitor() { - } - - public static boolean isDatabaseUp() { - return databaseUp; - } - - public static boolean isDatabasePermissionsOk() { - return dbPermissionsOk; - } + private static String application = "Portal"; + private static boolean isSuspended = false; - public static boolean isUebUp() { - return uebUp; - } - - public static boolean isFrontEndUp() { - return frontEndUp; - } - - public static boolean isBackEndUp() { - return backEndUp; - } - - public static boolean isZookeeperStatusOk() { - return zookeeperStatusOk; - } - - public static boolean isCassandraStatusOk() { - return cassandraStatusOk; + @Autowired + public HealthMonitor(SessionFactory sessionFactory) { + HealthMonitor.sessionFactory = sessionFactory; } - private void monitorEPHealth() throws InterruptedException { + private static void monitorEPHealth() { int numIntervalsDatabaseHasBeenDown = 0; - int numIntervalsClusterNotHealthy = 0; int numIntervalsDatabasePermissionsIncorrect = 0; int numIntervalsZookeeperNotHealthy = 0; int numIntervalsCassandraNotHealthy = 0; @@ -141,9 +104,9 @@ public class HealthMonitor { long sleepInterval = (Long - .valueOf(SystemProperties.getProperty(EPCommonSystemProperties.HEALTH_POLL_INTERVAL_SECONDS)) * 1000); + .parseLong(SystemProperties.getProperty(EPCommonSystemProperties.HEALTH_POLL_INTERVAL_SECONDS)) * 1000); long numIntervalsBetweenAlerts = Long - .valueOf(SystemProperties.getProperty(EPCommonSystemProperties.HEALTHFAIL_ALERT_EVERY_X_INTERVALS)); + .parseLong(SystemProperties.getProperty(EPCommonSystemProperties.HEALTHFAIL_ALERT_EVERY_X_INTERVALS)); logger.debug(EELFLoggerDelegate.debugLogger, "monitorEPHealth: Polling health every " + sleepInterval + " milliseconds. Alerting every " + (sleepInterval * numIntervalsBetweenAlerts) / 1000 + " seconds when component remains down."); @@ -154,8 +117,8 @@ public class HealthMonitor { // // Get DB status. If down, signal alert once every X intervals. // - databaseUp = this.checkIfDatabaseUp(); - if (databaseUp == false) { + databaseUp = checkIfDatabaseUp(); + if (databaseUp) { if ((numIntervalsDatabaseHasBeenDown % numIntervalsBetweenAlerts) == 0) { logger.debug(EELFLoggerDelegate.debugLogger, "monitorEPHealth: database down, logging to error log to trigger alert."); @@ -167,8 +130,8 @@ public class HealthMonitor { } } - dbPermissionsOk = this.checkDatabasePermissions(); - if (dbPermissionsOk == false) { + dbPermissionsOk = checkDatabasePermissions(); + if (!dbPermissionsOk) { if ((numIntervalsDatabasePermissionsIncorrect % numIntervalsBetweenAlerts) == 0) { logger.debug(EELFLoggerDelegate.debugLogger, "monitorEPHealth: database permissions incorrect, logging to error log to trigger alert."); @@ -178,12 +141,11 @@ public class HealthMonitor { numIntervalsDatabasePermissionsIncorrect = 0; } } - org.onap.portalapp.music.util.MusicUtil MusicUtilSDK = new org.onap.portalapp.music.util.MusicUtil(); - if(MusicUtilSDK.isMusicEnable()){ + if(org.onap.portalapp.music.util.MusicUtil.isMusicEnable()){ - zookeeperStatusOk = this.checkZookeeperStatus(); + zookeeperStatusOk = checkZookeeperStatus(); - if (zookeeperStatusOk == false) { + if (!zookeeperStatusOk) { if ((numIntervalsZookeeperNotHealthy % numIntervalsBetweenAlerts) == 0) { logger.debug(EELFLoggerDelegate.debugLogger, "monitorEPHealth: cluster nodes down, logging to error log to trigger alert."); @@ -194,8 +156,8 @@ public class HealthMonitor { } } - cassandraStatusOk = this.checkCassandraStatus(); - if (cassandraStatusOk == false) { + cassandraStatusOk = checkCassandraStatus(); + if (!cassandraStatusOk) { if ((numIntervalsCassandraNotHealthy % numIntervalsBetweenAlerts) == 0) { logger.debug(EELFLoggerDelegate.debugLogger, "monitorEPHealth: cluster nodes down, logging to error log to trigger alert."); @@ -206,45 +168,9 @@ public class HealthMonitor { } } } - - - // - // Get UEB status. Publish a bogus message to EP inbox, if 200 OK - // returned, status is Up. - // If down, signal alert once every X intervals. - // EP will ignore this bogus message. - // Commenting this out as Dependency on UEB is being deprecated - /* - * uebUp = this.checkIfUebUp(); if (uebUp == false) { - * - * if ((numIntervalsUebHasBeenDown % numIntervalsBetweenAlerts) == 0) { - * logger.debug(EELFLoggerDelegate.debugLogger, - * "monitorEPHealth: UEB down, logging to error log to trigger alert"); // Write - * a Log entry that will generate an alert EPLogUtil.logEcompError(logger, - * EPAppMessagesEnum.BeHealthCheckUebClusterError); - * numIntervalsUebHasBeenDown++; } else { numIntervalsUebHasBeenDown = 0; } } - */ - - // The front end should be up because the API is called through - // proxy front end server. frontEndUp = true; - - // If the rest API called, the backend is always up backEndUp = true; - // - // future nice to have...get Partner status - // - // For all apps exposing a rest url, query one of the rest - // urls(/roles?) and manage a list - // of app name/status. We might not return back a non 200 OK in - // health check, but we - // could return information in the json content of a health check. - // - - // - // Get DB status. If down, signal alert once every X intervals. - // if (Thread.interrupted()) { logger.info(EELFLoggerDelegate.errorLogger, "monitorEPHealth: thread interrupted"); break; @@ -262,12 +188,11 @@ public class HealthMonitor { @PostConstruct public void initHealthMonitor() { healthMonitorThread = new Thread("EP HealthMonitor thread") { + @Override public void run() { try { monitorEPHealth(); - } catch (InterruptedException e) { - logger.debug(EELFLoggerDelegate.debugLogger, "healthMonitorThread interrupted", e); - } + } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "healthMonitorThread failed", e); } @@ -292,7 +217,7 @@ public class HealthMonitor { * * @return true if the database can be read. */ - private boolean checkIfDatabaseUp() { + private static boolean checkIfDatabaseUp() { boolean isUp = false; Session localSession = null; try { @@ -316,25 +241,26 @@ public class HealthMonitor { return isUp; } - private boolean checkZookeeperStatus() { + private static boolean checkZookeeperStatus() { String[] zookeeperNodes = MusicUtil.getMyZkHost().split(","); logger.info(EELFLoggerDelegate.applicationLogger, "MusicUtil.getMyZkHost()---- :" + MusicUtil.getMyZkHost()); - for (int i = 0; i < zookeeperNodes.length; i++) { + for (String zookeeperNode : zookeeperNodes) { try { - logger.info(EELFLoggerDelegate.applicationLogger, "server ip--zookeeper :" + zookeeperNodes[i].trim()); - String[] iport = zookeeperNodes[i].split(":"); + logger.info(EELFLoggerDelegate.applicationLogger, "server ip--zookeeper :" + zookeeperNode.trim()); + String[] iport = zookeeperNode.split(":"); String zkNodeStatistics = FourLetterWordMain.send4LetterWord(iport[0].trim(), - Integer.parseInt(iport[1].trim()), "stat"); + Integer.parseInt(iport[1].trim()), "stat"); logger.info(EELFLoggerDelegate.applicationLogger, - "Getting Status for Zookeeper zkNodeStatistics :" + zkNodeStatistics); + "Getting Status for Zookeeper zkNodeStatistics :" + zkNodeStatistics); if (StringUtils.isNotBlank(zkNodeStatistics)) { String state = zkNodeStatistics.substring(zkNodeStatistics.indexOf("Mode:"), - zkNodeStatistics.indexOf("Node")); + zkNodeStatistics.indexOf("Node")); logger.info(EELFLoggerDelegate.applicationLogger, - "Getting Status for zookeeper :" + zookeeperNodes[i].trim() + ":------:" + state); - if (state.contains("leader") || state.contains("follower")) + "Getting Status for zookeeper :" + zookeeperNode.trim() + ":------:" + state); + if (state.contains("leader") || state.contains("follower")) { return true; + } } } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "ZookeeperStatus Service is not responding", e.getCause()); @@ -345,9 +271,9 @@ public class HealthMonitor { } - public boolean checkCassandraStatus() { + private static boolean checkCassandraStatus() { logger.info(EELFLoggerDelegate.applicationLogger, "Getting Status for Cassandra"); - if (this.getAdminKeySpace()) { + if (getAdminKeySpace()) { return true; } else { logger.error(EELFLoggerDelegate.errorLogger, "Cassandra Service is not responding"); @@ -355,17 +281,18 @@ public class HealthMonitor { } } - private Boolean getAdminKeySpace() { + private static Boolean getAdminKeySpace() { String musicKeySpace = MusicProperties.getProperty(MusicProperties.MUSIC_SESSION_KEYSPACE); Instant creationTime = Instant.now(); PreparedQueryObject pQuery = new PreparedQueryObject(); pQuery.appendQueryString( "UPDATE " + musicKeySpace + ".health_check SET creation_time = ? WHERE primary_id = ?"); pQuery.addValue(creationTime.toString()); - pQuery.addValue(APPLICATION); + pQuery.addValue(application); try { MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.CRITICAL); } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getErrorMessage(), e); return Boolean.FALSE; } return Boolean.TRUE; @@ -373,7 +300,7 @@ public class HealthMonitor { } - private boolean checkDatabasePermissions() { + private static boolean checkDatabasePermissions() { boolean isUp = false; Session localSession = null; try { @@ -391,7 +318,7 @@ public class HealthMonitor { break; } } - if (isUp == false) { + if (!isUp) { logger.error(EELFLoggerDelegate.errorLogger, "checkDatabasePermissions returning false. SHOW GRANTS FOR CURRENT_USER being dumped:"); for (String str : grantsList) { @@ -412,5 +339,40 @@ public class HealthMonitor { } return isUp; } - + + public static boolean isDatabaseUp() { + return databaseUp; + } + + public static boolean isUebUp() { + return uebUp; + } + + public static boolean isFrontEndUp() { + return frontEndUp; + } + + public static boolean isBackEndUp() { + return backEndUp; + } + + public static boolean isDbPermissionsOk() { + return dbPermissionsOk; + } + + public static boolean isZookeeperStatusOk() { + return zookeeperStatusOk; + } + + public static boolean isCassandraStatusOk() { + return cassandraStatusOk; + } + + public static boolean isSuspended() { + return isSuspended; + } + + public static void setSuspended(boolean isSuspended) { + HealthMonitor.isSuspended = isSuspended; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLdapService.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLdapService.java index ef3cb5ad..c1dba221 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLdapService.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLdapService.java @@ -40,7 +40,7 @@ package org.onap.portalapp.portal.service; import org.onap.portalsdk.core.command.support.SearchResult; import org.onap.portalsdk.core.domain.support.DomainVo; - +@FunctionalInterface public interface EPLdapService { // search POST for users based on the criteria selected in the Request diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java index 1904d8e2..b41dcd7a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java @@ -2,7 +2,7 @@ * ============LICENSE_START========================================== * ONAP Portal * =================================================================== - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -283,13 +283,20 @@ public class UserRolesCommonServiceImpl { transaction = localSession.beginTransaction(); @SuppressWarnings("unchecked") List<EPUser> userList = localSession - .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list(); + .createQuery("from :name where orgUserId=:userId") + .setParameter("name",EPUser.class.getName()) + .setParameter("userId",userId) + .list(); if (userList.size() > 0) { EPUser client = userList.get(0); roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'"; @SuppressWarnings("unchecked") - List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName() - + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list(); + List<EPUserApp> userRoles = localSession.createQuery("from :name where app.id=:appId :roleActive and userId=:userId") + .setParameter("name",EPUserApp.class.getName()) + .setParameter("appId",appId) + .setParameter("roleActive",roleActive) + .setParameter("userId",client.getId()) + .list(); if ("DELETE".equals(reqType)) { for (EPUserApp userAppRoleList : userRoles) { @@ -335,7 +342,10 @@ public class UserRolesCommonServiceImpl { } else { // remote app @SuppressWarnings("unchecked") List<EPRole> roles = localSession - .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list(); + .createQuery("from :name where appId=:appId") + .setParameter("name",EPRole.class.getName()) + .setParameter("appId",appId) + .list(); for (EPRole role : roles) { if (!extRequestValue && app.getCentralAuth()) { rolesMap.put(role.getId(), role); @@ -495,9 +505,13 @@ public class UserRolesCommonServiceImpl { transaction = localSession.beginTransaction(); // Attention! All roles from remote application supposed to be // active! + @SuppressWarnings("unchecked") - List<EPRole> currentAppRoles = localSession - .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list(); + List<EPRole> currentAppRoles = localSession.createQuery("from :name where appId = :appId") + .setParameter("name",EPRole.class.getName()) + .setParameter("appId",appId) + .list(); + List<EPRole> obsoleteRoles = new ArrayList<EPRole>(); for (int i = 0; i < currentAppRoles.size(); i++) { EPRole oldAppRole = currentAppRoles.get(i); @@ -535,7 +549,10 @@ public class UserRolesCommonServiceImpl { // Delete from fn_user_role @SuppressWarnings("unchecked") List<EPUserApp> userRoles = localSession.createQuery( - "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId) + "from :name where app.id=:appId and role_id=:roleId") + .setParameter("name",EPUserApp.class.getName()) + .setParameter("appId",appId) + .setParameter("roleId",roleId) .list(); logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size()); @@ -550,7 +567,9 @@ public class UserRolesCommonServiceImpl { // Delete from fn_menu_functional_roles @SuppressWarnings("unchecked") List<FunctionalMenuRole> funcMenuRoles = localSession - .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId) + .createQuery("from :name where roleId=:roleId") + .setParameter("name",FunctionalMenuRole.class.getName()) + .setParameter("roleId",roleId) .list(); int numMenuRoles = funcMenuRoles.size(); logger.debug(EELFLoggerDelegate.debugLogger, @@ -562,7 +581,9 @@ public class UserRolesCommonServiceImpl { // so must null out the url too, to be consistent @SuppressWarnings("unchecked") List<FunctionalMenuRole> funcMenuRoles2 = localSession - .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId) + .createQuery("from :name where menuId=:menuId") + .setParameter("name",FunctionalMenuRole.class.getName()) + .setParameter("menuId",menuId) .list(); int numMenuRoles2 = funcMenuRoles2.size(); logger.debug(EELFLoggerDelegate.debugLogger, @@ -576,8 +597,9 @@ public class UserRolesCommonServiceImpl { "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url"); @SuppressWarnings("unchecked") List<FunctionalMenuItem> funcMenuItems = localSession - .createQuery( - "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId) + .createQuery("from :name where menuId=:menuId") + .setParameter("name",FunctionalMenuItem.class.getName()) + .setParameter("menuId",menuId) .list(); if (funcMenuItems.size() > 0) { logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item"); @@ -1001,11 +1023,11 @@ public class UserRolesCommonServiceImpl { boolean epRequestValue = false; String userId = ""; String reqMessage = ""; - if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) { - userId = newAppRolesForUser.orgUserId.trim(); + if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) { + userId = newAppRolesForUser.getOrgUserId().trim(); } - Long appId = newAppRolesForUser.appId; - List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles; + Long appId = newAppRolesForUser.getAppId(); + List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles(); if (userId.length() > 0 ) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); @@ -1014,7 +1036,7 @@ public class UserRolesCommonServiceImpl { EPApp app = appsService.getApp(appId); applyChangesToUserAppRolesForMyLoginsRequest(user, appId); - boolean systemUser = newAppRolesForUser.isSystemUser; + boolean systemUser = newAppRolesForUser.isSystemUser(); if ((app.getCentralAuth() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) { Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, @@ -2056,17 +2078,18 @@ public class UserRolesCommonServiceImpl { List<EPUserAppRoles> appRole= null; try { logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined"); - boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId()); + boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, + userAppRolesData.getAppId(), user.getId()); logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result); - params.put("appId", userAppRolesData.appId); + params.put("appId", userAppRolesData.getAppId()); EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest(); epAppRolesRequestData.setCreatedDate(new Date()); epAppRolesRequestData.setUpdatedDate(new Date()); epAppRolesRequestData.setUserId(user.getId()); - epAppRolesRequestData.setAppId(userAppRolesData.appId); + epAppRolesRequestData.setAppId(userAppRolesData.getAppId()); epAppRolesRequestData.setRequestStatus("P"); - List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles; + List<RoleInAppForUser> appRoleIdList = userAppRolesData.getAppRoles(); Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>(); dataAccessService.saveDomainObject(epAppRolesRequestData, null); for (RoleInAppForUser userAppRoles : appRoleIdList) { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java index e2336dbd..cbfe1787 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java @@ -2,7 +2,7 @@ * ============LICENSE_START========================================== * ONAP Portal * =================================================================== - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -38,65 +38,24 @@ package org.onap.portalapp.portal.transport; import java.util.List; - +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@EqualsAndHashCode +@ToString public class AppWithRolesForUser { - - public String orgUserId; - - public boolean isSystemUser; - - public Long appId; - - public String appName; - - public List<RoleInAppForUser> appRoles; - - public String getOrgUserId() { - return orgUserId; - } - - public void setOrgUserId(String orgUserId) { - this.orgUserId = orgUserId; - } - - public Long getAppId() { - return appId; - } - - public void setAppId(Long appId) { - this.appId = appId; - } - - public String getAppName() { - return appName; - } - - public void setAppName(String appName) { - this.appName = appName; - } - - public List<RoleInAppForUser> getAppRoles() { - return appRoles; - } - - public void setAppRoles(List<RoleInAppForUser> appRoles) { - this.appRoles = appRoles; - } - - - - public boolean isSystemUser() { - return isSystemUser; - } - - public void setSystemUser(boolean isSystemUser) { - this.isSystemUser = isSystemUser; - } - - @Override - public String toString() { - return "AppWithRolesForUser [orgUserId=" + orgUserId + ", isSystemUser=" + isSystemUser + ", appId=" + appId - + ", appName=" + appName + ", appRoles=" + appRoles + "]"; - } + private String orgUserId; + private boolean isSystemUser; + private Long appId; + private String appName; + private List<RoleInAppForUser> appRoles; } |