diff options
Diffstat (limited to 'portal-BE/src/main/java/org')
10 files changed, 1151 insertions, 15 deletions
diff --git a/portal-BE/src/main/java/org/onap/portal/controller/WidgetsController.java b/portal-BE/src/main/java/org/onap/portal/controller/WidgetsController.java new file mode 100644 index 00000000..7b4bbea0 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/controller/WidgetsController.java @@ -0,0 +1,95 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.controller; + +import java.security.Principal; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.domain.dto.transport.OnboardingWidget; +import org.onap.portal.service.WidgetService; +import org.onap.portal.service.fn.FnUserService; +import org.onap.portal.utils.EcompPortalUtils; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +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.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@Configuration +@EnableAspectJAutoProxy +public class WidgetsController { + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsController.class); + + private final FnUserService fnUserService; + private final WidgetService widgetService; + + @Autowired + public WidgetsController(FnUserService fnUserService, WidgetService widgetService) { + this.fnUserService = fnUserService; + this.widgetService = widgetService; + } + + @RequestMapping(value = { "/portalApi/widgets" }, method = RequestMethod.GET, produces = "application/json") + public List<OnboardingWidget> getOnboardingWidgets(Principal principal, HttpServletRequest request, HttpServletResponse response) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + List<OnboardingWidget> onboardingWidgets = null; + + if (user == null || user.isGuest()) { + EcompPortalUtils.setBadPermissions(user, response, "getOnboardingWidgets"); + } else { + String getType = request.getHeader("X-Widgets-Type"); + if (!getType.isEmpty() && ("managed".equals(getType) || "all".equals(getType))) { + onboardingWidgets = widgetService.getOnboardingWidgets(user, "managed".equals(getType)); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "WidgetsController.getOnboardingApps - request must contain header 'X-Widgets-Type' with 'all' or 'managed'"); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + } + + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/widgets", "GET result =", response.getStatus()); + return onboardingWidgets; + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/dao/fn/FnAppDao.java b/portal-BE/src/main/java/org/onap/portal/dao/fn/FnAppDao.java new file mode 100644 index 00000000..616ee2d1 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/dao/fn/FnAppDao.java @@ -0,0 +1,12 @@ +package org.onap.portal.dao.fn; + +import org.onap.portal.domain.db.fn.FnApp; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +@Repository +@Transactional +public interface FnAppDao extends JpaRepository<FnApp, Long> { + +} diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnApp.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnApp.java index cdc20897..399cb55c 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnApp.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnApp.java @@ -172,17 +172,9 @@ public class FnApp extends DomainVo implements Serializable { @NotNull private String appPassword; @Column(name = "open", length = 1, columnDefinition = "char(1) default 'N'") - @Pattern(regexp = "[YNyn]") - @Size(max = 1) - @NotNull - @SafeHtml - private String open; + private Boolean open; @Column(name = "ENABLED", length = 1, columnDefinition = "char(1) default 'N'") - @Pattern(regexp = "[YNyn]") - @Size(max = 1) - @NotNull - @SafeHtml - private String enabled; + private Boolean enabled; @Column(name = "active_yn", length = 1, columnDefinition = "char(1) default 'Y'") @Pattern(regexp = "[YNyn]") @Size(max = 1) @@ -211,11 +203,7 @@ public class FnApp extends DomainVo implements Serializable { @Digits(integer = 11, fraction = 0) private Long appType; @Column(name = "auth_central", length = 1, columnDefinition = "char(1) not null default 'N'", nullable = false) - @Pattern(regexp = "[YNyn]") - @Size(max = 1) - @NotNull - @SafeHtml - private String authCentral; + private Boolean authCentral; @Column(name = "auth_namespace", length = 100) @Size(max = 100) @SafeHtml @@ -283,4 +271,8 @@ public class FnApp extends DomainVo implements Serializable { fetch = FetchType.LAZY ) private Set<FnPersUserAppSel> fnPersUserAppSels; + + public Boolean isRestrictedApp() { + return (this.appType == 2); + } } diff --git a/portal-BE/src/main/java/org/onap/portal/logging/aop/EPAuditLog.java b/portal-BE/src/main/java/org/onap/portal/logging/aop/EPAuditLog.java new file mode 100644 index 00000000..43306c44 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/logging/aop/EPAuditLog.java @@ -0,0 +1,52 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.logging.aop; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface EPAuditLog { + String value() default ""; +} diff --git a/portal-BE/src/main/java/org/onap/portal/logging/aop/EPEELFLoggerAdvice.java b/portal-BE/src/main/java/org/onap/portal/logging/aop/EPEELFLoggerAdvice.java new file mode 100644 index 00000000..fa8ab5d5 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/logging/aop/EPEELFLoggerAdvice.java @@ -0,0 +1,406 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.logging.aop; + +import com.att.eelf.configuration.Configuration; +import java.net.InetAddress; +import java.security.Principal; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import org.onap.portal.domain.db.fn.FnApp; +import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.service.fn.FnUserService; +import org.onap.portal.service.fn.old.AppsCacheService; +import org.onap.portal.utils.EPCommonSystemProperties; +import org.onap.portal.utils.EcompPortalUtils; +import org.onap.portalsdk.core.exception.SessionExpiredException; +import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.onap.portalsdk.core.logging.format.AuditLogFormatter; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; + +@org.springframework.context.annotation.Configuration +public class EPEELFLoggerAdvice { + + private EELFLoggerDelegate adviceLogger = EELFLoggerDelegate.getLogger(EPEELFLoggerAdvice.class); + + private final AppsCacheService appCacheService; + private final FnUserService fnUserService; + + @Autowired + public EPEELFLoggerAdvice(AppsCacheService appCacheService, FnUserService fnUserService) { + this.appCacheService = appCacheService; + this.fnUserService = fnUserService; + } + + public static String getCurrentDateTimeUTC() { + SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + return ecompLogDateFormat.format(new Date()); + } + + public void loadServletRequestBasedDefaults(Principal principal, HttpServletRequest req, SecurityEventTypeEnum securityEventType) { + try { + setHttpRequestBasedDefaultsIntoGlobalLoggingContext(principal, req, securityEventType, req.getServletPath()); + } catch (Exception e) { + adviceLogger.error(EELFLoggerDelegate.errorLogger, "loadServletRequestBasedDefaults failed", e); + } + } + + public Object[] before(Principal principal, SecurityEventTypeEnum securityEventType, Object[] args, Object[] passOnArgs) { + String className = ""; + if (passOnArgs.length > 0 && passOnArgs[0] != null) + className = passOnArgs[0].toString(); + String methodName = EPCommonSystemProperties.ECOMP_PORTAL_BE; + if (passOnArgs.length > 1 && passOnArgs[1] != null) + methodName = passOnArgs[1].toString(); + + MDC.put(className + methodName + EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP, getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.TARGET_ENTITY, EPCommonSystemProperties.ECOMP_PORTAL_BE); + MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, methodName); + if (MDC.get(Configuration.MDC_KEY_REQUEST_ID) == null||MDC.get(Configuration.MDC_KEY_REQUEST_ID).isEmpty()){ + String requestId = UUID.randomUUID().toString(); + MDC.put(Configuration.MDC_KEY_REQUEST_ID, requestId); + } + MDC.put(EPCommonSystemProperties.PARTNER_NAME, "Unknown"); + MDC.put(Configuration.MDC_SERVICE_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE); + + if (securityEventType != null) { + MDC.put(className + methodName + EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, + getCurrentDateTimeUTC()); + HttpServletRequest req; + if (args.length > 0 && args[0] != null && args[0] instanceof HttpServletRequest) { + req = (HttpServletRequest) args[0]; + this.setHttpRequestBasedDefaultsIntoGlobalLoggingContext(principal, req, securityEventType, methodName); + } + } + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className); + logger.debug(EELFLoggerDelegate.debugLogger, "EPEELFLoggerAdvice#before: entering {}", methodName); + return new Object[] { "" }; + } + + public void after(Principal principal, SecurityEventTypeEnum securityEventType, String statusCode, String responseCode, Object[] args, + Object[] returnArgs, Object[] passOnArgs) { + String className = ""; + if (passOnArgs.length > 0 && passOnArgs[0] != null) + className = passOnArgs[0].toString(); + String methodName = EPCommonSystemProperties.ECOMP_PORTAL_BE; + if (passOnArgs.length > 1 && passOnArgs[1] != null) + methodName = passOnArgs[1].toString(); + + if (MDC.get(EPCommonSystemProperties.TARGET_SERVICE_NAME) == null + || "".equals(MDC.get(EPCommonSystemProperties.TARGET_SERVICE_NAME))) + MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, methodName); + + if (MDC.get(EPCommonSystemProperties.TARGET_ENTITY) == null + || "".equals(MDC.get(EPCommonSystemProperties.TARGET_ENTITY))) + MDC.put(EPCommonSystemProperties.TARGET_ENTITY, EPCommonSystemProperties.ECOMP_PORTAL_BE); + + if (MDC.get(Configuration.MDC_KEY_REQUEST_ID) == null||MDC.get(Configuration.MDC_KEY_REQUEST_ID).isEmpty()){ + String requestId = UUID.randomUUID().toString(); + MDC.put(Configuration.MDC_KEY_REQUEST_ID, requestId); + } + + if (MDC.get(EPCommonSystemProperties.PARTNER_NAME) == null|| MDC.get(EPCommonSystemProperties.PARTNER_NAME).isEmpty()){ + MDC.put(EPCommonSystemProperties.PARTNER_NAME, "Unknown"); + } + + MDC.put(Configuration.MDC_SERVICE_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE); + + + MDC.put(EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP, + MDC.get(className + methodName + EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP)); + MDC.put(EPCommonSystemProperties.METRICSLOG_END_TIMESTAMP, getCurrentDateTimeUTC()); + this.calculateDateTimeDifference(MDC.get(EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.METRICSLOG_END_TIMESTAMP)); + + if (securityEventType != null && args.length > 0 && args[0] != null && args[0] instanceof HttpServletRequest + && securityEventType == SecurityEventTypeEnum.INCOMING_REST_MESSAGE + && (MDC.get(EPCommonSystemProperties.FULL_URL) == null + || MDC.get(EPCommonSystemProperties.FULL_URL).isEmpty())) { + HttpServletRequest req = (HttpServletRequest) args[0]; + this.setHttpRequestBasedDefaultsIntoGlobalLoggingContext(principal, req, securityEventType, methodName); + } + + String externalAPIResponseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE); + if (externalAPIResponseCode == null || "".equals(externalAPIResponseCode) + || externalAPIResponseCode.trim().equalsIgnoreCase("200")) { + MDC.put(EPCommonSystemProperties.RESPONSE_CODE, responseCode); + MDC.put(EPCommonSystemProperties.STATUS_CODE, statusCode); + } else { + MDC.put(EPCommonSystemProperties.RESPONSE_CODE, externalAPIResponseCode); + MDC.put(EPCommonSystemProperties.STATUS_CODE, "ERROR"); + } + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className); + logger.debug(EELFLoggerDelegate.debugLogger, "EPEELFLoggerAdvice#after: finished {}", methodName); + + logger.info(EELFLoggerDelegate.metricsLogger, methodName + " operation is completed."); + + if (securityEventType != null) { + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, + MDC.get(className + methodName + EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP)); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, getCurrentDateTimeUTC()); + this.calculateDateTimeDifference(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + + this.logSecurityMessage(logger, securityEventType, methodName); + + if (securityEventType != SecurityEventTypeEnum.OUTGOING_REST_MESSAGE + && securityEventType != SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH) { + MDC.remove(Configuration.MDC_KEY_REQUEST_ID); + MDC.remove(EPCommonSystemProperties.PARTNER_NAME); + MDC.remove(Configuration.MDC_SERVICE_NAME); + MDC.remove(EPCommonSystemProperties.MDC_LOGIN_ID); + MDC.remove(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE); + }else{ + MDC.remove(Configuration.MDC_KEY_REQUEST_ID); + MDC.remove(EPCommonSystemProperties.PARTNER_NAME); + MDC.remove(Configuration.MDC_SERVICE_NAME); + } + + + MDC.remove(EPCommonSystemProperties.FULL_URL); + MDC.remove(EPCommonSystemProperties.PROTOCOL); + MDC.remove(EPCommonSystemProperties.STATUS_CODE); + MDC.remove(className + methodName + EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.RESPONSE_CODE); + } + MDC.remove(className + methodName + EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.METRICSLOG_END_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.MDC_TIMER); + MDC.remove(EPCommonSystemProperties.TARGET_ENTITY); + MDC.remove(EPCommonSystemProperties.TARGET_SERVICE_NAME); + + } + + private void logSecurityMessage(EELFLoggerDelegate logger, SecurityEventTypeEnum securityEventType, + String restMethod) { + StringBuilder additionalInfoAppender = new StringBuilder(); + String auditMessage; + + if (securityEventType == SecurityEventTypeEnum.OUTGOING_REST_MESSAGE) { + additionalInfoAppender.append(String.format("%s '%s' request was initiated.", restMethod, + MDC.get(EPCommonSystemProperties.TARGET_SERVICE_NAME))); + } else if (securityEventType == SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH) { + additionalInfoAppender.append("LDAP Phonebook search operation is performed."); + } else { + additionalInfoAppender.append(String.format("%s request was received.", restMethod)); + + if (securityEventType == SecurityEventTypeEnum.FE_LOGIN_ATTEMPT) { + String loginId; + String additionalMessage = " Successfully authenticated."; + loginId = MDC.get(EPCommonSystemProperties.MDC_LOGIN_ID); + if (loginId == null || "".equals(loginId) || EPCommonSystemProperties.UNKNOWN.equals(loginId)) { + additionalMessage = " No cookies are found."; + } + additionalInfoAppender.append(additionalMessage); + } else if (securityEventType == SecurityEventTypeEnum.FE_LOGOUT) { + additionalInfoAppender.append(" User has been successfully logged out."); + } + } + + String fullURL = MDC.get(EPCommonSystemProperties.FULL_URL); + if (fullURL != null && !"".equals(fullURL)) { + additionalInfoAppender.append(" Request-URL:").append(MDC.get(EPCommonSystemProperties.FULL_URL)); + } + + auditMessage = AuditLogFormatter.getInstance().createMessage(MDC.get(EPCommonSystemProperties.PROTOCOL), + securityEventType.name(), MDC.get(EPCommonSystemProperties.MDC_LOGIN_ID), + additionalInfoAppender.toString()); + + logger.info(EELFLoggerDelegate.auditLogger, auditMessage); + } + + private void setHttpRequestBasedDefaultsIntoGlobalLoggingContext(Principal principal, HttpServletRequest req, + SecurityEventTypeEnum securityEventType, String restMethod) { + + if (req != null) { + if (securityEventType != SecurityEventTypeEnum.OUTGOING_REST_MESSAGE + && securityEventType != SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH + && securityEventType != SecurityEventTypeEnum.INCOMING_UEB_MESSAGE) { + loadRequestId(req); + + loadPartnerName(req); + + loadLoginId(principal, req); + + loadUrlProtocol(req); + + loadServicePath(req, restMethod); + + loadClientAddress(req); + + } else if (securityEventType == SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH) { + MDC.put(EPCommonSystemProperties.TARGET_ENTITY, "Phonebook"); + MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, "search"); + } + } else { + MDC.put(Configuration.MDC_SERVICE_NAME, restMethod); + MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_FE); + } + + MDC.put(Configuration.MDC_SERVICE_INSTANCE_ID, ""); + MDC.put(Configuration.MDC_ALERT_SEVERITY, AlarmSeverityEnum.INFORMATIONAL.severity()); + try { + MDC.put(Configuration.MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName()); + MDC.put(Configuration.MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + MDC.put(Configuration.MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID)); + } catch (Exception e) { + adviceLogger.error(EELFLoggerDelegate.errorLogger, + "setHttpRequestBasedDefaultsIntoGlobalLoggingContext failed", e); + } + } + + private void loadClientAddress(HttpServletRequest req) { + String clientIPAddress; + clientIPAddress = req.getHeader("X-FORWARDED-FOR"); + if (clientIPAddress == null) { + clientIPAddress = req.getRemoteAddr(); + } + MDC.put(EPCommonSystemProperties.CLIENT_IP_ADDRESS, clientIPAddress); + } + + private void loadServicePath(HttpServletRequest req, String restMethod) { + MDC.put(Configuration.MDC_SERVICE_NAME, restMethod); + String restPath = req.getServletPath(); + if (restPath != null && restPath.trim().length()>0) { + + MDC.put(Configuration.MDC_SERVICE_NAME, restPath); + } + } + + private void loadUrlProtocol(HttpServletRequest req) { + String restURL; + MDC.put(EPCommonSystemProperties.FULL_URL, EPCommonSystemProperties.UNKNOWN); + MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTP); + restURL = UserUtils.getFullURL(req); + if (restURL.trim().length() > 0) { + MDC.put(EPCommonSystemProperties.FULL_URL, restURL); + if (restURL.toLowerCase().contains("https")) { + MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTPS); + } + } + } + + private void loadRequestId(HttpServletRequest req) { + String requestId = UserUtils.getRequestId(req); + if (requestId == null||requestId.trim().length()==0) { + requestId = UUID.randomUUID().toString(); + } + MDC.put(Configuration.MDC_KEY_REQUEST_ID, requestId); + } + + private void loadLoginId(Principal principal, HttpServletRequest req) { + String loginId = "NoUser"; + try { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + loginId = (user != null ? user.getOrgUserId(): loginId); + } catch (SessionExpiredException se) { + adviceLogger.debug(EELFLoggerDelegate.debugLogger, + "setHttpRequestBasedDefaultsIntoGlobalLoggingContext: No user found in session"); + } + + final String nameHeader = req.getHeader(EPCommonSystemProperties.USERNAME); + if (nameHeader != null) { + loginId = nameHeader; + } + + final String authHeader = req.getHeader(EPCommonSystemProperties.AUTHORIZATION); + if (authHeader != null) { + String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader); + if (accountNamePassword != null && accountNamePassword.length == 2) { + loginId = accountNamePassword[0]; + } + } + + MDC.put(EPCommonSystemProperties.MDC_LOGIN_ID, loginId ); + } + + private void loadPartnerName(HttpServletRequest req) { + + + // Load user agent into MDC context, if available. + String accessingClient = req.getHeader(SystemProperties.USERAGENT_NAME); + accessingClient = (accessingClient == null || accessingClient.trim().length()==0)?"Unknown":accessingClient; + if (accessingClient != null && accessingClient.trim().length()==0 && (accessingClient.contains("Mozilla") + || accessingClient.contains("Chrome") || accessingClient.contains("Safari"))) { + accessingClient = EPCommonSystemProperties.ECOMP_PORTAL_FE; + } + MDC.put(EPCommonSystemProperties.PARTNER_NAME, accessingClient); + + String uebVal = req.getHeader(EPCommonSystemProperties.UEB_KEY); + if(uebVal != null) { + FnApp appRecord = appCacheService.getAppFromUeb(uebVal); + MDC.put(EPCommonSystemProperties.PARTNER_NAME, appRecord.getAppName()); + } + + + } + + private void calculateDateTimeDifference(String beginDateTime, String endDateTime) { + if (beginDateTime != null && endDateTime != null && !beginDateTime.isEmpty()&&!endDateTime.isEmpty()) { + try { + SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + Date beginDate = ecompLogDateFormat.parse(beginDateTime); + Date endDate = ecompLogDateFormat.parse(endDateTime); + String timeDifference = String.format("%d", endDate.getTime() - beginDate.getTime()); + MDC.put(SystemProperties.MDC_TIMER, timeDifference); + } catch (Exception e) { + adviceLogger.error(EELFLoggerDelegate.errorLogger, "calculateDateTimeDifference failed", e); + } + } + } + + public String getInternalResponseCode() { + return MDC.get(EPCommonSystemProperties.RESPONSE_CODE); + } + +} diff --git a/portal-BE/src/main/java/org/onap/portal/logging/aop/EPMetricsLog.java b/portal-BE/src/main/java/org/onap/portal/logging/aop/EPMetricsLog.java new file mode 100644 index 00000000..4f290d9f --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/logging/aop/EPMetricsLog.java @@ -0,0 +1,52 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.logging.aop; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface EPMetricsLog { + String value() default ""; +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java b/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java new file mode 100644 index 00000000..c948ece4 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java @@ -0,0 +1,146 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.persistence.EntityManager; +import org.onap.portal.domain.db.fn.FnRole; +import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.domain.db.fn.FnUserRole; +import org.onap.portal.domain.dto.ecomp.UserRole; +import org.onap.portal.logging.format.EPAppMessagesEnum; +import org.onap.portal.logging.logic.EPLogUtil; +import org.onap.portal.service.fn.FnUserService; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class AdminRolesService { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class); + + private final Long SYS_ADMIN_ROLE_ID = 1L; + private final Long ACCOUNT_ADMIN_ROLE_ID = 999L; + private final Long ECOMP_APP_ID = 1L; + private final String ADMIN_ACCOUNT= "Is account admin for user {}"; + + private final EntityManager entityManager; + private final FnUserService fnUserService; + + @Autowired + public AdminRolesService(final EntityManager entityManager, + FnUserService fnUserService) { + this.entityManager = entityManager; + this.fnUserService = fnUserService; + } + + public boolean isSuperAdmin(FnUser user) { + if ((user != null) && (user.getOrgUserId() != null)) { + String sql = "SELECT user.USER_ID, user.org_user_id, userrole.ROLE_ID, userrole.APP_ID FROM fn_user_role userrole " + + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " + "WHERE user.org_user_id = '" + + user.getOrgUserId() + "' " + "AND userrole.ROLE_ID = '" + SYS_ADMIN_ROLE_ID + "' " + + "AND userrole.APP_ID = '" + ECOMP_APP_ID + "';"; + try { + List userRoleList = entityManager.createNativeQuery(sql, UserRole.class).getResultList(); + if (userRoleList != null && userRoleList.size() > 0) { + return true; + } + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while executing isSuperAdmin operation", e); + } + } + return false; + } + + public boolean isAccountAdmin(FnUser user) { + try { + final Map<String, Long> userParams = new HashMap<>(); + userParams.put("userId", user.getId()); + logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId()); + List<Integer> userAdminApps; + String query = "select fa.app_id from fn_user_role ur,fn_app fa where ur.user_id =:userId and ur.app_id=fa.app_id and ur.role_id= 999 and (fa.enabled = 'Y' || fa.app_id=1)"; + userAdminApps = entityManager.createQuery(query, Integer.class).setParameter("userId", user.getId()).getResultList(); + logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}", user.getOrgUserId(), userAdminApps.size()); + + + if (user.getId() != null) { + for (FnUserRole userApp : user.getFnUserRoles()) { + if (userApp.getRoleId().getId().equals(ACCOUNT_ADMIN_ROLE_ID)||(userAdminApps.size()>1)) { + logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for userAdminApps() - for user {}, found Id {}", user.getOrgUserId(), userApp.getRoleId().getId()); + return true; + } + } + } + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isAccountAdmin operation", + e); + } + return false; + } + + public boolean isUser(FnUser user) { + try { + FnUser currentUser = fnUserService.getUser(user.getId()).orElseThrow(Exception::new); + if (currentUser != null && currentUser.getId() != null) { + for (FnUserRole userApp : currentUser.getFnUserRoles()) { + if (!userApp.getAppId().getId().equals(ECOMP_APP_ID)) { + FnRole role = userApp.getRoleId(); + if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) { + if (role.getActiveYn()) { + return true; + } + } + } + } + } + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", e); + } + return false; + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/WidgetService.java b/portal-BE/src/main/java/org/onap/portal/service/WidgetService.java new file mode 100644 index 00000000..24a77ed5 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/WidgetService.java @@ -0,0 +1,102 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.service; + +import java.util.ArrayList; +import java.util.List; +import javax.persistence.EntityManager; +import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.domain.dto.transport.OnboardingWidget; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class WidgetService { + + private final AdminRolesService adminRolesService; + + private static Long ACCOUNT_ADMIN_ROLE_ID = 999L; + + private static String baseSqlToken = " widget.WIDGET_ID, widget.WDG_NAME, widget.APP_ID, app.APP_NAME, widget.WDG_WIDTH, widget.WDG_HEIGHT, widget.WDG_URL" + + " from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID"; + + private static String validAppsFilter = ""; + + private final EntityManager entityManager; + + @Autowired + public WidgetService(final AdminRolesService adminRolesService, EntityManager entityManager) { + this.adminRolesService = adminRolesService; + this.entityManager = entityManager; + } + + public List<OnboardingWidget> getOnboardingWidgets(FnUser user, boolean managed) { + List<OnboardingWidget> onboardingWidgets = new ArrayList<>(); + String sql = null; + if (adminRolesService.isSuperAdmin(user)) { + sql = this.sqlWidgetsForAllApps(); + } else if (managed) { + if (adminRolesService.isAccountAdmin(user)) { + sql = this.sqlWidgetsForAllAppsWhereUserIsAdmin(user.getId()); + } + } else if (adminRolesService.isAccountAdmin(user) || adminRolesService.isUser(user)) { + sql = this.sqlWidgetsForAllAppsWhereUserHasAnyRole(user.getId()); + } + if (sql != null) { + onboardingWidgets = (List<OnboardingWidget>) entityManager.createNativeQuery(sql, OnboardingWidget.class).getResultList(); + } + return onboardingWidgets; + } + + private String sqlWidgetsForAllApps() { + return "SELECT" + baseSqlToken + validAppsFilter; + } + + private String sqlWidgetsForAllAppsWhereUserHasAnyRole(Long userId) { + return "SELECT DISTINCT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " + + userId + validAppsFilter; + } + + private String sqlWidgetsForAllAppsWhereUserIsAdmin(Long userId) { + return "SELECT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " + userId + + " AND FN_USER_ROLE.ROLE_ID = " + ACCOUNT_ADMIN_ROLE_ID + validAppsFilter; + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/fn/FnAppService.java b/portal-BE/src/main/java/org/onap/portal/service/fn/FnAppService.java new file mode 100644 index 00000000..75b32dd3 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/fn/FnAppService.java @@ -0,0 +1,105 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.service.fn; + +import java.util.List; +import org.onap.portal.dao.fn.FnAppDao; +import org.onap.portal.domain.db.fn.FnApp; +import org.onap.portal.domain.dto.transport.OnboardingApp; +import org.onap.portal.utils.EPCommonSystemProperties; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; +import org.onap.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class FnAppService { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnAppService.class); + + private final FnAppDao fnAppDao; + + @Autowired + public FnAppService(final FnAppDao fnAppDao) { + this.fnAppDao = fnAppDao; + } + + public List<FnApp> getAppsFullList() { + return fnAppDao.findAll(); + } + + public void createOnboardingFromApp(FnApp app, OnboardingApp onboardingApp) { + onboardingApp.setId(app.getId()); + onboardingApp.setName(app.getAppName()); + onboardingApp.setImageUrl(app.getAppImageUrl()); + onboardingApp.setDescription(app.getAppDescription()); + onboardingApp.setNotes(app.getAppNotes()); + onboardingApp.setUrl(app.getAppUrl()); + onboardingApp.setAlternateUrl(app.getAppAlternateUrl()); + onboardingApp.setRestUrl(app.getAppRestEndpoint()); + onboardingApp.setIsOpen(app.getOpen()); + onboardingApp.setIsEnabled(app.getEnabled()); + onboardingApp.setUsername(app.getAppUsername()); + onboardingApp.setAppPassword((app.getAppPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD)) + ? EPCommonSystemProperties.APP_DISPLAY_PASSWORD : decryptedPassword(app.getAppPassword(), app)); + onboardingApp.setUebTopicName(app.getUebTopicName()); + onboardingApp.setUebKey(app.getUebKey()); + onboardingApp.setUebSecret(app.getUebSecret()); + onboardingApp.setIsCentralAuth(app.getAuthCentral()); + onboardingApp.setNameSpace(app.getAuthNamespace()); + onboardingApp.setRestrictedApp(app.isRestrictedApp()); + } + + private String decryptedPassword(String encryptedAppPwd, FnApp app) { + String result = ""; + if (encryptedAppPwd != null && !encryptedAppPwd.isEmpty()) { + try { + result = CipherUtil.decryptPKC(encryptedAppPwd, + SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "decryptedPassword failed for app " + app.getAppName(), e); + } + } + return result; + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/fn/old/AppsCacheService.java b/portal-BE/src/main/java/org/onap/portal/service/fn/old/AppsCacheService.java new file mode 100644 index 00000000..3c02f819 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/fn/old/AppsCacheService.java @@ -0,0 +1,174 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.service.fn.old; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; +import org.onap.portal.domain.db.fn.FnApp; +import org.onap.portal.domain.dto.transport.OnboardingApp; +import org.onap.portal.service.fn.FnAppService; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +@Service("appsCacheService") +@Configuration +@EnableAspectJAutoProxy +public class AppsCacheService { + @Autowired + private + FnAppService appsService; + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsCacheService.class); + + final class CacheConfiguration { + + private long updateTime = 0; + private int updateInterval = 10; + + public CacheConfiguration (long _updateTime, int _updateInterval) { + updateTime = _updateTime; + updateInterval = _updateInterval; + } + } + + private CacheConfiguration quickRefreshCacheConf = null; + private CacheConfiguration slowRefreshCacheConf = null; + + + private static volatile Map<Long, FnApp> appsMap; + private static volatile Map<String, FnApp> uebAppsMap; + + @PostConstruct + public void init() { + quickRefreshCacheConf = new CacheConfiguration(0, 120); + slowRefreshCacheConf = new CacheConfiguration(0, 3600); + + this.refreshAppsMap(quickRefreshCacheConf); + } + + private void refreshAppsMap(CacheConfiguration conf) { + long now = System.currentTimeMillis(); + + if(noNeedToUpdate(now, conf)) + return; + + synchronized (this) { + if(noNeedToUpdate(now, conf)) + return; + List<FnApp> allApps = appsService.getAppsFullList(); + Map<Long, FnApp> newAppsMap = new HashMap<>(); + for (FnApp app : allApps) { + newAppsMap.put(app.getId(), app); + } + + Map<String, FnApp> newUebAppsMap = new HashMap<>(); + for (FnApp app : allApps) { + newUebAppsMap.put(app.getUebKey(), app); + } + // Switch cache with the new one. + appsMap = newAppsMap; + uebAppsMap = newUebAppsMap; + conf.updateTime = now; + } + + } + + private boolean noNeedToUpdate(long now, CacheConfiguration conf) { + long secondsPassed = (now - conf.updateTime)/1000; + if(secondsPassed < conf.updateInterval){ + logger.debug(EELFLoggerDelegate.debugLogger, "no need to refresh yet, seconds since last refresh: " + secondsPassed + ", refresh interval (sec) = " + conf.updateInterval); + return true; // no need to update cache + } + return false; // its time to update + } + + public String getAppEndpoint(Long appId) { + refreshAppsMap(quickRefreshCacheConf); + FnApp app = appsMap.get(appId); + if(app != null) + return app.getAppRestEndpoint(); + return null; + } + + public List<OnboardingApp> getAppsFullList() { + refreshAppsMap(quickRefreshCacheConf); + List<FnApp> appList = new ArrayList<FnApp> (appsMap.values()); + appList.removeIf(app -> app.getId() == 1); + List<FnApp> appsFinalList = appList.stream() + .filter(app -> app.getEnabled() && !app.getOpen()).collect(Collectors.toList()); + + List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>(); + for (FnApp app : appsFinalList) { + OnboardingApp onboardingApp = new OnboardingApp(); + appsService.createOnboardingFromApp(app, onboardingApp); + onboardingAppsList.add(onboardingApp); + } + return onboardingAppsList; + } + + public FnApp getApp(Long appId) { + refreshAppsMap(quickRefreshCacheConf); + FnApp app = appsMap.get(appId); + if(app != null) + return app; + return null; + } + + public FnApp getAppFromUeb(String appKey) { + return getAppFromUeb(appKey,0); + } + + public FnApp getAppFromUeb(String appKey, Integer quickCacheRefresh) { + refreshAppsMap(quickCacheRefresh == 1 ? quickRefreshCacheConf:slowRefreshCacheConf); + FnApp app = uebAppsMap.get(appKey); + if(app != null) + return app; + return null; + } + +} |