diff options
author | 2017-05-04 07:48:42 -0400 | |
---|---|---|
committer | 2017-05-04 12:28:17 -0400 | |
commit | b54df0ddd0c6a0372327c5aa3668e5a6458fcd64 (patch) | |
tree | e69cfa9b314a801bd187cf0145d1d4306436229c /ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp | |
parent | 39d1e62c84041831bfc52cca73b5ed5efaf57d27 (diff) |
[PORTAL-7] Rebase
This rebasing includes common libraries and common overlays projects
abstraction of components
Change-Id: I9a24a338665c7cd058978e8636bc412d9e2fdce8
Signed-off-by: st782s <statta@research.att.com>
Diffstat (limited to 'ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp')
44 files changed, 5498 insertions, 0 deletions
diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/LoginStrategy.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/LoginStrategy.java new file mode 100644 index 00000000..19637515 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/LoginStrategy.java @@ -0,0 +1,27 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.authentication; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public interface LoginStrategy { + public boolean login(HttpServletRequest request, HttpServletResponse response) throws Exception; +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/OpenIdConnectLoginStrategy.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/OpenIdConnectLoginStrategy.java new file mode 100644 index 00000000..8365ebc2 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/OpenIdConnectLoginStrategy.java @@ -0,0 +1,107 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.authentication; + +import java.util.HashSet; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.mitre.openid.connect.model.UserInfo; +import org.openecomp.portalapp.command.EPLoginBean; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalapp.util.SessionCookieUtil; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.util.StringUtils; +import org.springframework.web.servlet.ModelAndView; + +public class OpenIdConnectLoginStrategy extends org.openecomp.portalsdk.core.auth.LoginStrategy implements org.openecomp.portalapp.authentication.LoginStrategy { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(OpenIdConnectLoginStrategy.class); + + private static final String GLOBAL_LOCATION_KEY = "Location"; + + @SuppressWarnings("rawtypes") + public boolean login(HttpServletRequest request, HttpServletResponse response){ + + logger.info("Attempting Login"); + + //check both authentication cookie and authentication header + UserInfo userInfo = (UserInfo) request.getAttribute("userInfo"); + + if (userInfo != null && !StringUtils.isEmpty(userInfo.getPreferredUsername())) { + //package the userid in the login form for processing + EPLoginBean commandBean = new EPLoginBean(); + commandBean.setOrgUserId(userInfo.getPreferredUsername()); + + EPUser user = new EPUser(); + + user.setOrgUserId(userInfo.getPreferredUsername()); + user.setEmail(userInfo.getEmail()); + user.setFirstName(userInfo.getName()); + user.setLastName(userInfo.getFamilyName()); + + //store the currently logged in user's information in the session + EPUserUtils.setUserSession(request, user, new HashSet(), new HashSet(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM), null); + + logger.info(EELFLoggerDelegate.errorLogger, request.getContextPath()); + SessionCookieUtil.preSetUp(request, response); + return true; + } else { + // in case authentication cookie is missing, send 401 UNAUTHORIZED to client and it will redirect to Logon + + try { + String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM); + String loginUrl = SystemProperties.getProperty(EPSystemProperties.LOGIN_URL_NO_RET_VAL); + logger.info(EELFLoggerDelegate.errorLogger, "Authentication Mechanism: '" + authentication + "'."); + + if (authentication == null || authentication.equals("") || authentication.trim().equals("OIDC")) { + response.sendRedirect("oid-login"); + } else { + logger.info(EELFLoggerDelegate.errorLogger, "No cookies are found, redirecting the request to '" + loginUrl + "'."); + response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + response.setHeader(GLOBAL_LOCATION_KEY, loginUrl); + } + } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in preHandle() while redirecting, Details: " + EcompPortalUtils.getStackTrace(e)); + } + } + return false; + } + + @Override + public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { + String message = "Method not implmented; Cannot be called"; + logger.error(EELFLoggerDelegate.errorLogger, message); + throw new Exception(message); + } + + @Override + public String getUserId(HttpServletRequest request) throws PortalAPIException { + String message = "Method not implmented; Cannot be called"; + logger.error(EELFLoggerDelegate.errorLogger, message); + throw new PortalAPIException(message); + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/SimpleLoginStrategy.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/SimpleLoginStrategy.java new file mode 100644 index 00000000..c1fee7f3 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/SimpleLoginStrategy.java @@ -0,0 +1,114 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.authentication; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.command.EPLoginBean; +import org.openecomp.portalapp.portal.service.EPLoginService; +import org.openecomp.portalapp.portal.service.EPRoleService; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalapp.util.SessionCookieUtil; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.menu.MenuProperties; +import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; +import org.openecomp.portalsdk.core.onboarding.util.*; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.StringUtils; +import org.springframework.web.servlet.ModelAndView; + +public class SimpleLoginStrategy extends org.openecomp.portalsdk.core.auth.LoginStrategy implements LoginStrategy{ + + @Autowired + private EPLoginService loginService; + @Autowired + private EPRoleService roleService; + + private static final String GLOBAL_LOCATION_KEY = "Location"; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SimpleLoginStrategy.class); + + public boolean login(HttpServletRequest request, HttpServletResponse response) throws Exception{ + logger.info("Attempting 'Simple' Login"); + + //check both authentication cookie and authentication header + String orgUserId = SessionCookieUtil.getUserIdFromCookie(request, response); + + if (!StringUtils.isEmpty(orgUserId)) { + // package the userid in the login form for processing + EPLoginBean commandBean = new EPLoginBean(); + commandBean.setOrgUserId(orgUserId); + commandBean = loginService.findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), null); + + // in case authentication has passed but user is not in the ECOMP data base, return a Guest User to the home page. + if (commandBean.getUser() == null) { + } + else { + // store the currently logged in user's information in the session + EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), "", roleService.getRoleFunctions()); + logger.info(EELFLoggerDelegate.debugLogger, commandBean.getUser().getOrgUserId() + " exists in the the system."); + } + + logger.info(EELFLoggerDelegate.errorLogger, request.getContextPath()); + SessionCookieUtil.preSetUp(request, response); + return true; + } else { + // in case authentication cookie is missing, send 401 UNAUTHORIZED to client and it will redirect to Logon + try { + String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM); + String loginUrl = SystemProperties.getProperty(EPSystemProperties.LOGIN_URL_NO_RET_VAL); + logger.info(EELFLoggerDelegate.errorLogger, "Authentication Mechanism: '" + authentication + "'."); + if (authentication == null || authentication.equals("") || authentication.trim().equals("BOTH")) { + + logger.info(EELFLoggerDelegate.errorLogger, "No cookies are found, redirecting the request to '" + loginUrl + "'."); + response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + response.setHeader(GLOBAL_LOCATION_KEY, loginUrl); //returnUrl + "/index.htm"); + }else { + logger.info(EELFLoggerDelegate.errorLogger, "No cookies are found, redirecting the request to '" + loginUrl + "'."); + response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + response.setHeader(GLOBAL_LOCATION_KEY, loginUrl); //returnUrl + "/index.htm"); + } + } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in preHandle() while redirecting, Details: " + EcompPortalUtils.getStackTrace(e)); + } + } + + return false; + + } + + @Override + public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { + String message = "Method not implmented; Cannot be called"; + logger.error(EELFLoggerDelegate.errorLogger, message); + throw new Exception(message); + } + + @Override + public String getUserId(HttpServletRequest request) throws PortalAPIException { + String message = "Method not implmented; Cannot be called"; + logger.error(EELFLoggerDelegate.errorLogger, message); + throw new PortalAPIException(message); + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java new file mode 100644 index 00000000..971c671a --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java @@ -0,0 +1,316 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.conf; + +import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY; +import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID; +import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN; +import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; + +import java.net.InetAddress; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.openecomp.portalapp.authentication.LoginStrategy; +import org.openecomp.portalapp.authentication.OpenIdConnectLoginStrategy; +import org.openecomp.portalapp.authentication.SimpleLoginStrategy; +import org.openecomp.portalapp.controller.core.LogoutController; +import org.openecomp.portalapp.controller.core.SDKLoginController; +import org.openecomp.portalapp.portal.interceptor.PortalResourceInterceptor; +import org.openecomp.portalapp.portal.interceptor.SessionTimeoutInterceptor; +import org.openecomp.portalapp.portal.listener.HealthMonitor; +import org.openecomp.portalapp.portal.service.EPLoginService; +import org.openecomp.portalapp.portal.service.EPLoginServiceImpl; +import org.openecomp.portalapp.portal.ueb.EPUebHelper; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.scheduler.RegistryAdapter; +import org.openecomp.portalapp.uebhandler.FunctionalMenuHandler; +import org.openecomp.portalapp.uebhandler.InitUebHandler; +import org.openecomp.portalapp.uebhandler.MainUebHandler; +import org.openecomp.portalapp.uebhandler.WidgetNotificationHandler; +import org.openecomp.portalsdk.core.conf.AppConfig; +import org.openecomp.portalsdk.core.conf.Configurable; +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.service.FnMenuService; +import org.openecomp.portalsdk.core.service.FnMenuServiceImpl; +import org.openecomp.portalsdk.core.util.CacheManager; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.ComponentScan.Filter; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.FilterType; +import org.springframework.context.annotation.Profile; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "org.openecomp" }, excludeFilters = { + @Filter(value = { LogoutController.class, SDKLoginController.class }, type = FilterType.ASSIGNABLE_TYPE) }) +@Profile("src") +@EnableAsync +@EnableScheduling +public class ExternalAppConfig extends AppConfig implements Configurable { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppConfig.class); + + private RegistryAdapter schedulerRegistryAdapter; + + public ViewResolver viewResolver() { + return super.viewResolver(); + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/static/**").addResourceLocations("/static/"); + registry.addResourceHandler("/images/**").addResourceLocations("/images/"); + registry.addResourceHandler("/**").addResourceLocations("/public/"); + } + + @PostConstruct + private void init() { + try { + // Loading defaults + MDC.put(MDC_SERVICE_NAME, EPSystemProperties.ECOMP_PORTAL_BE); + MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); + MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + MDC.put(MDC_SERVICE_INSTANCE_ID, ""); + MDC.put(MDC_ALERT_SEVERITY, AlarmSeverityEnum.INFORMATIONAL.toString()); + MDC.put(MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + + /* + * / + * + * @PostConstruct // file://${catalina.home}/conf/log4j.properties public + * void initLog4j() throws FileNotFoundException { try { URL[] classpathurls + * = ((URLClassLoader) + * (Thread.currentThread().getContextClassLoader())).getURLs(); for (URL url + * : classpathurls) { System.out.println(url.getFile().toString()); } + * Log4jConfigurer.initLogging( + * "file://${catalina.home}/conf/log4j.properties"); } catch + * (FileNotFoundException e) { ((URLClassLoader) + * (Thread.currentThread().getContextClassLoader())).getURLs(); + * Log4jConfigurer.initLogging("classpath:../conf/log4j.properties"); } } / + **/ + + public DataAccessService dataAccessService() { + return super.dataAccessService(); + } + + public String[] tileDefinitions() { + return super.tileDefinitions(); + } + + public List<String> addTileDefinitions() { + List<String> definitions = new ArrayList<String>(); + definitions.add("/WEB-INF/defs/definitions.xml"); + return definitions; + } + + @Bean + public AbstractCacheManager cacheManager() { + return new CacheManager(); + } + + @Bean + public SessionTimeoutInterceptor sessionTimeoutInterceptor() { + return new SessionTimeoutInterceptor(); + } + + @Bean + public PortalResourceInterceptor portalResourceInterceptor() { + return new PortalResourceInterceptor(); + } + + @Bean + public EPLoginService eploginService() { + return new EPLoginServiceImpl(); + } + + @Bean + public org.openecomp.portalsdk.core.auth.LoginStrategy coreLoginStrategy() { + if (SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")) + return new OpenIdConnectLoginStrategy(); + else + return new SimpleLoginStrategy(); + } + + @Bean + public LoginStrategy loginStrategy() { + + if (SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")) + return new OpenIdConnectLoginStrategy(); + else + return new SimpleLoginStrategy(); + } + + public FnMenuService fnMenuService() { + return new FnMenuServiceImpl(); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + // registry.addInterceptor(new + // StaticResourcesInterceptor()).addPathPatterns("/index.htm", + // "/applicationsHome", "/widgetsHome", "/admins", "/users", + // "/applications", "/widgets"); + // Excludes login/logout pages and REST endpoints used by other + // application servers. + + registry.addInterceptor(sessionTimeoutInterceptor()).excludePathPatterns("/oid-login", "/portalApi/healthCheck", + "/portalApi/healthCheck/", "/portalApi/healthCheckSuspend", "/portalApi/healthCheckSuspend/", + "/portalApi/healthCheckResume", "/portalApi/healthCheckResume/", "/login_external", + "/login_external.htm*", "login", "/login.htm*", "/auxapi/*", "/context/*", "/api*", + "/single_signon.htm", "/single_signon", "/dashboard", "/OpenSourceLogin.htm"); + + registry.addInterceptor(portalResourceInterceptor()); + + } + + /** + * Creates and returns a new instance of a {@link SchedulerFactoryBean} and + * populates it with triggers. + * + * @return New instance of {@link SchedulerFactoryBean} + */ + + @Bean + public EPUebHelper epUebHelper() { + return new EPUebHelper(); + } + + @Bean + public HealthMonitor healthMonitor() { + return new HealthMonitor(); + } + + /** + * Creates and returns a new instance of a {@link MainUebHandler}. + * + * @return New instance of {@link MainUebHandler}. + */ + @Bean + public MainUebHandler mainUebHandler() { + return new MainUebHandler(); + } + + /** + * Creates and returns a new instance of a {@link InitUebHandler}. + * + * @return New instance of {@link InitUebHandler}. + */ + @Bean + public InitUebHandler initUebHandler() { + return new InitUebHandler(); + } + + /** + * Creates and returns a new instance of a {@link WidgetNotificationHandler} + * . + * + * @return New instance of {@link WidgetNotificationHandler}. + */ + @Bean + public WidgetNotificationHandler widgetNotificationHandler() { + return new WidgetNotificationHandler(); + } + + /** + * Creates and returns a new instance of a {@link FunctionalMenuHandler} . + * + * @return New instance of {@link FunctionalMenuHandler}. + */ + @Bean + public FunctionalMenuHandler functionalMenuHandler() { + return new FunctionalMenuHandler(); + } + + /** + * Creates and returns a new instance of a {@link SchedulerFactoryBean} and + * populates it with triggers. + * + * @return New instance of {@link SchedulerFactoryBean} + * @throws Exception if dataSource fails + */ + // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION + @Bean // ANNOTATION COMMENTED OUT + public SchedulerFactoryBean schedulerFactoryBean() throws Exception { + SchedulerFactoryBean scheduler = new SchedulerFactoryBean(); + scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties")); + scheduler.setDataSource(dataSource()); + scheduler.setTriggers(schedulerRegistryAdapter.getTriggers()); + scheduler.setSchedulerName(getScheduleName()); + return scheduler; + } + + protected String getScheduleName() { + final String CRON_SITE_NAME = "cron_site_name"; + String cronSiteVal = "Default"; + try { + cronSiteVal = SystemProperties.getProperty(CRON_SITE_NAME); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + logger.warn(EELFLoggerDelegate.errorLogger, + "Cron site name not added in property file, using Default value"); + } + + String cronSiteName = cronSiteVal != null ? cronSiteVal : ""; + + SimpleDateFormat dateFormat = new SimpleDateFormat(); + dateFormat.applyPattern("YYYYMMdd"); + String currentDateStr = dateFormat.format(Calendar.getInstance().getTime()); + + return "Scheduler" + "_" + currentDateStr + "_" + cronSiteName; + } + + /** + * Sets the scheduler registry adapter. + * + * @param schedulerRegistryAdapter + * Scheduler registry adapter + */ + @Autowired + public void setSchedulerRegistryAdapter(final RegistryAdapter schedulerRegistryAdapter) { + this.schedulerRegistryAdapter = schedulerRegistryAdapter; + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java new file mode 100644 index 00000000..1c9f43df --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java @@ -0,0 +1,60 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.conf; + +import java.util.Arrays; + +import org.openecomp.portalsdk.core.conf.AppInitializer; + +public class ExternalAppInitializer extends AppInitializer{ + + + @Override + protected Class<?>[] getRootConfigClasses() { + return super.getRootConfigClasses(); + } + + @Override + protected Class<?>[] getServletConfigClasses() { +// Class<?>[] configClasses = super.getServletConfigClasses(); +// Class<?>[] additionalConfigClasses = Arrays.copyOf(configClasses, configClasses.length); +// addConfigClass(additionalConfigClasses, ExternalAppConfig.class); +// return additionalConfigClasses; +// + return new Class[] {ExternalAppConfig.class}; + } + + static Class<?>[] addConfigClass(Class<?>[] a, Class<?> e) { + a = Arrays.copyOf(a, a.length + 1); + a[a.length - 1] = e; + return a; + } + + /* + * URL request will direct to the Spring dispatcher for processing + */ + @Override + protected String[] getServletMappings() { + return super.getServletMappings(); + } + +} + + diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java new file mode 100644 index 00000000..0ebf4e38 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java @@ -0,0 +1,43 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.conf; + +import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable; +import org.springframework.context.annotation.Profile; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.stereotype.Component; + +@Component +@Profile("src") +public class HibernateMappingLocations implements HibernateMappingLocatable { + + public Resource[] getMappingLocations() { + return new Resource[] { new ClassPathResource("../fusion/orm/Fusion.hbm.xml"), + new ClassPathResource("../fusion/orm/EP.hbm.xml"), + new ClassPathResource("../fusion/orm/Workflow.hbm.xml") }; + } + + @Override + public String[] getPackagesToScan() { + return new String[] { "org.openecomp" }; + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ECOMPLogoutController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ECOMPLogoutController.java new file mode 100644 index 00000000..b4e3bee9 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ECOMPLogoutController.java @@ -0,0 +1,114 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.servlet.ModelAndView; + +@Controller +@RequestMapping("/") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@Profile("src") +public class ECOMPLogoutController extends EPUnRestrictedBaseController{ + + private EPUser user; + private static final String EP_SERVICE = "EPService"; + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ECOMPLogoutController.class); + + @EPAuditLog + @RequestMapping(value = {"/logout.htm" }, method = RequestMethod.GET) + public ModelAndView logOut(HttpServletRequest request, + HttpServletResponse response) throws Exception { + + ModelAndView modelView = null; + + chatRoomLogout(request); + logger.debug(EELFLoggerDelegate.debugLogger, "ECOMPLogoutController.handleRequestInternal - Logout request received."); + + modelView = new ModelAndView("redirect:login.htm"); + + /** + if (UserUtils.isClientMobileDevice(request)){ + modelView.setViewName(modelView.getViewName().concat("?viewType=mobile")); + } + */ + String cookieDoamin = EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN); + Cookie epCookie = new Cookie(EP_SERVICE, ""); + epCookie.setMaxAge(0); + epCookie.setDomain(cookieDoamin); + epCookie.setPath("/"); + + Cookie appHeaderCookie = new Cookie("show_app_header", ""); + appHeaderCookie.setMaxAge(0); + appHeaderCookie.setDomain(cookieDoamin); + appHeaderCookie.setPath("/"); + + Cookie appTabCookie = new Cookie("cookieTabs", ""); + appTabCookie.setMaxAge(0); + appTabCookie.setDomain(cookieDoamin); + appTabCookie.setPath("/"); + + Cookie appVisInvisTabCookie = new Cookie("visInVisCookieTabs", ""); + appVisInvisTabCookie.setMaxAge(0); + appVisInvisTabCookie.setDomain(cookieDoamin); + appVisInvisTabCookie.setPath("/"); + + response.addCookie(epCookie); + response.addCookie(appHeaderCookie); + response.addCookie(appTabCookie); + response.addCookie(appVisInvisTabCookie); + request.getSession().invalidate(); + + logger.debug(EELFLoggerDelegate.debugLogger, "ECOMPLogoutController.handleRequestInternal - Successfully processed the logout request."); + + return modelView; + } + + @EPMetricsLog + public void chatRoomLogout(HttpServletRequest request){ + request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest(); + setUser(EPUserUtils.getUserSession(request)); + } + + public EPUser getUser() { + return user; + } + + public void setUser(EPUser user) { + this.user = user; + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginController.java new file mode 100644 index 00000000..09e10e38 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginController.java @@ -0,0 +1,397 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; + +import java.net.URLDecoder; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.portalapp.command.EPLoginBean; +import org.openecomp.portalapp.portal.domain.SharedContext; +import org.openecomp.portalapp.portal.service.EPLoginService; +import org.openecomp.portalapp.portal.service.EPRoleService; +import org.openecomp.portalapp.portal.service.SharedContextService; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.service.EPProfileService; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalapp.util.SessionCookieUtil; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.menu.MenuProperties; +import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.AppUtils; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.util.StopWatch; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.util.WebUtils; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class LoginController extends EPUnRestrictedBaseController implements LoginService{ + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginController.class); + + public static final String DEFAULT_SUCCESS_VIEW = "applicationsHome"; + public static final String DEFAULT_FAILURE_VIEW = "login"; + public static final String ERROR_MESSAGE_KEY = "error"; + public static final String REDIRECT_URL = "redirectUrl"; + + @Autowired + EPProfileService service; + @Autowired + private EPLoginService loginService; + @Autowired + private SharedContextService sharedContextService; + + @Autowired + private EPRoleService roleService; + + String viewName = "login"; + private String welcomeView; + + public String getWelcomeView() { + return welcomeView; + } + + public void setWelcomeView(String welcomeView) { + this.welcomeView = welcomeView; + } + + @RequestMapping(value = {"/login.htm" }, method = RequestMethod.GET) + public ModelAndView login(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + + String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM); + + String loginPage; + + if (authentication == null || authentication.equals("") || authentication.trim().equals("OIDC")) + loginPage = "openIdLogin"; + else + loginPage = getViewName(); + + return new ModelAndView(loginPage,"model", model); + } + + @SuppressWarnings("rawtypes") + @RequestMapping(value = {"/open_source/login" }, method = RequestMethod.POST) + public @ResponseBody String loginValidate(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + EPLoginBean commandBean = new EPLoginBean(); + String loginId = root.get("loginId").textValue(); + String password = root.get("password").textValue(); + commandBean.setLoginId(loginId); + commandBean.setLoginPwd(CipherUtil.encrypt(password)); + HashMap additionalParamsMap = new HashMap(); + StringBuilder sbAdditionalInfo = new StringBuilder(); + + commandBean = getLoginService().findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), + additionalParamsMap); + String fullURL = getFullURL(request); + if (commandBean.getUser() == null) { + String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage() + : "login.error.external.invalid"; + + logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + loginId + " does not exist in the the DB."); + logger.info(EELFLoggerDelegate.errorLogger, "loginId = " + loginId + " does not exist in the the DB."); + sbAdditionalInfo.append(String.format("But the Login-Id: %s doesn't exist in the Database. Request-URL: %s", + loginId, fullURL)); + return loginErrorMessage; + } + else { + // store the currently logged in user's information in the session + EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM), + roleService.getRoleFunctions()); + + try{ + logger.info(EELFLoggerDelegate.debugLogger, "******************* store user info into share context begins"); + String sessionId = request.getSession().getId(); + List<SharedContext> existingSC = getSharedContextService().getSharedContexts(sessionId); + if(existingSC==null || existingSC.size()==0){ + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_FIRST_NAME, commandBean.getUser().getFirstName()); + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_LAST_NAME, commandBean.getUser().getLastName()); + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_EMAIL, commandBean.getUser().getEmail()); + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_ORG_USERID, commandBean.getLoginId()); + } + + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + logger.info(EELFLoggerDelegate.errorLogger, "failed the shared context adding process " + e.getMessage()); + logger.info(EELFLoggerDelegate.debugLogger, "********************** failed the shared context adding process " + e.getMessage()); + } + logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement"); + + SessionCookieUtil.preSetUp(request, response); + SessionCookieUtil.setUpUserIdCookie(request, response, loginId); + + JSONObject j = new JSONObject("{success: success}"); + + return j.toString(); + + } + + } + + @RequestMapping(value = {"/processSingleSignOn" }, method = RequestMethod.GET) + public ModelAndView processSingelSignOn(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + Map<Object, Object> model = new HashMap<Object, Object>(); + HashMap<Object, Object> additionalParamsMap = new HashMap<Object, Object>(); + EPLoginBean commandBean = new EPLoginBean(); + MDC.put(MDC_KEY_REQUEST_ID, getRequestId(request)); + String orgUserId = ""; + //get userId from cookie + orgUserId = SessionCookieUtil.getUserIdFromCookie(request, response); + logger.info(EELFLoggerDelegate.debugLogger, "******************** process_singelSignOn process begins"); + logger.info(EELFLoggerDelegate.debugLogger, "******************* We get the orgUserId " + orgUserId); + + StringBuilder sbAdditionalInfo = new StringBuilder(); + if ((orgUserId == null || orgUserId.length() == 0)) { + model.put(ERROR_MESSAGE_KEY, SystemProperties.MESSAGE_KEY_LOGIN_ERROR_COOKIE_EMPTY); + if(request.getParameter("redirectUrl")!=null && request.getParameter("redirectUrl").length()!=0){ + return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl=" + request.getParameter("redirectUrl")); + }else{ + return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm"); + } + } + else { + + StopWatch stopWatch = new StopWatch("LoginController.Login"); + stopWatch.start(); + + try { + logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is started to locate " + orgUserId + " in the database."); + logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is started to locate " + orgUserId + " in the database."); + commandBean.setLoginId(orgUserId); + commandBean.setOrgUserId(orgUserId); + commandBean = getLoginService().findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), additionalParamsMap); + + stopWatch.stop(); + MDC.put(EPSystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms"); + logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is completed."); + logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is completed."); + } catch(Exception e) { + stopWatch.stop(); + MDC.put(EPSystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms"); + logger.info(EELFLoggerDelegate.errorLogger, "Exception occurred while performing findUser " + orgUserId + ". Details: " + EcompPortalUtils.getStackTrace(e)); + logger.info(EELFLoggerDelegate.debugLogger, "Exception occurred while performing findUser " + orgUserId + ". Details: " + EcompPortalUtils.getStackTrace(e)); + logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is failed."); + } finally { + MDC.remove(EPSystemProperties.MDC_TIMER); + } + + sbAdditionalInfo.append("Login attempt is succeeded. "); + String fullURL = getFullURL(request); + if (commandBean.getUser() == null) { + logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + orgUserId + " does not exist in the the DB."); + logger.info(EELFLoggerDelegate.errorLogger, "loginId = " + orgUserId + " does not exist in the the DB."); + logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + orgUserId + " does not exist in the the DB."); + + sbAdditionalInfo.append(String.format("But the Login-Id: %s doesn't exist in the Database. Created a Guest Session. Request-URL: %s", + orgUserId, fullURL)); + if(request.getParameter("redirectUrl")!=null && request.getParameter("redirectUrl").length()!=0){ + return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl=" + request.getParameter("redirectUrl")); + }else{ + return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm"); + } + } + else { + + sbAdditionalInfo.append(String.format("Login-Id: %s, Login-Method: %s, Request-URL: %s", orgUserId, "", fullURL)); + logger.info(EELFLoggerDelegate.debugLogger, "*********************** now set up user session for " + orgUserId); + + EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM), roleService.getRoleFunctions()); + logger.info(EELFLoggerDelegate.debugLogger, "*********************** now set up user session for " + orgUserId + " finished"); + + //Store user's information into share context + try{ + logger.info(EELFLoggerDelegate.debugLogger, "******************* store user info into share context begins"); + + String sessionId = request.getSession().getId(); + List<SharedContext> existingSC = getSharedContextService().getSharedContexts(sessionId); + if(existingSC==null || existingSC.size()==0){ + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_FIRST_NAME, commandBean.getUser().getFirstName()); + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_LAST_NAME, commandBean.getUser().getLastName()); + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_EMAIL, commandBean.getUser().getEmail()); + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_ORG_USERID, commandBean.getLoginId()); + } + + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + logger.info(EELFLoggerDelegate.errorLogger, "failed the shared context adding process " + e.getMessage()); + logger.info(EELFLoggerDelegate.debugLogger, "********************** failed the shared context adding process " + e.getMessage()); + + } + + logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement"); + + SessionCookieUtil.preSetUp(request, response); + SessionCookieUtil.setUpUserIdCookie(request, response, orgUserId); + logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement completed"); + logger.info(EELFLoggerDelegate.errorLogger, commandBean.getUser().getOrgUserId() + " exists in the the system."); + logger.info(EELFLoggerDelegate.debugLogger, commandBean.getUser().getOrgUserId() + " exists in the the system."); + + String redirect = "redirectUrl"; + + //get redirectUrl from URL parameter + if(request.getParameter(redirect)!=null && request.getParameter(redirect).length()!=0){ + String forwardUrl = URLDecoder.decode(request.getParameter(redirect),"UTF-8"); + //clean cookie + Cookie cookie2 = new Cookie(redirect, ""); + cookie2.setMaxAge(0); + cookie2.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN)); + cookie2.setPath("/"); + response.addCookie(cookie2); + return new ModelAndView("redirect:" + forwardUrl); + } + + //first check if redirectUrl exists or not + if(WebUtils.getCookie(request, redirect)!=null){ + String forwardUrl = WebUtils.getCookie(request, redirect).getValue(); + //clean cookie + Cookie cookie2 = new Cookie(redirect, ""); + cookie2.setMaxAge(0); + cookie2.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN)); + cookie2.setPath("/"); + response.addCookie(cookie2); + + return new ModelAndView("redirect:" + forwardUrl); + } + } + } + + // if user has been authenticated, now take them to the welcome page. + //return new ModelAndView("redirect:" + DEFAULT_SUCCESS_VIEW + ".htm"); + logger.info(EELFLoggerDelegate.debugLogger, "********************** Now return to application home page"); + + return new ModelAndView("redirect:" + SystemProperties.getProperty(EPSystemProperties.FE_URL)); + + // + // Re-enable for BE/FE separation. For 1607, at last minute we decided to go out + // without BE/FE separation. + // + //return new ModelAndView("redirect:" + SystemProperties.getProperty(EPSystemProperties.FE_URL)); + + } + + public String getFullURL(HttpServletRequest request) { + if (request != null) { + StringBuffer requestURL = request.getRequestURL(); + String queryString = request.getQueryString(); + + if (queryString == null) { + return requestURL.toString(); + } else { + return requestURL.append('?').append(queryString).toString(); + } + } + return ""; + } + + public String getRequestId(HttpServletRequest request) { + Enumeration<String> headerNames = request.getHeaderNames(); + + String requestId = ""; + try { + while (headerNames.hasMoreElements()) { + String headerName = (String) headerNames.nextElement(); + logger.debug(EELFLoggerDelegate.debugLogger, + "One header is " + headerName + " : " + request.getHeader(headerName)); + if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) { + requestId = request.getHeader(headerName); + break; + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "HEADER!!!! Exception : " + EcompPortalUtils.getStackTrace(e)); + } + + return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId); + } + + public String getJessionId(HttpServletRequest request){ + + return request.getSession().getId(); + /* + Cookie ep = WebUtils.getCookie(request, JSESSIONID); + if(ep==null){ + return request.getSession().getId(); + } + return ep.getValue(); + */ + } + + + protected void initateSessionMgtHandler(HttpServletRequest request) { + String jSessionId = getJessionId(request); + PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request)); + } + + + public String getViewName() { + return viewName; + } + public void setViewName(String viewName) { + this.viewName = viewName; + } + public EPLoginService getLoginService() { + return loginService; + } + + public void setLoginService(EPLoginService loginService) { + this.loginService = loginService; + } + + public SharedContextService getSharedContextService() { + return sharedContextService; + } + + public void setSharedContextService(SharedContextService sharedContextService) { + this.sharedContextService = sharedContextService; + } + + + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginService.java new file mode 100644 index 00000000..7d2e4518 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginService.java @@ -0,0 +1,36 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; + +public interface LoginService { + + public ModelAndView login(HttpServletRequest request); + + public @ResponseBody String loginValidate(HttpServletRequest request, HttpServletResponse response) throws Exception; + + public ModelAndView processSingelSignOn(HttpServletRequest request, HttpServletResponse response) throws Exception; + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ONAPLoginController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ONAPLoginController.java new file mode 100644 index 00000000..1f45d982 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ONAPLoginController.java @@ -0,0 +1,81 @@ +/*-
+ * ================================================================================
+ * ECOMP Portal SDK
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file 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.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.controller;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalsdk.core.auth.LoginStrategy;
+import org.openecomp.portalsdk.core.controller.UnRestrictedBaseController;
+import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
+import org.openecomp.portalsdk.core.service.LoginService;
+import org.openecomp.portalsdk.core.service.ProfileService;
+import org.openecomp.portalsdk.core.web.support.AppUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+@Controller
+@RequestMapping("/")
+public class ONAPLoginController extends UnRestrictedBaseController {
+ @Autowired
+ ProfileService service;
+ @Autowired
+ private LoginService loginService;
+ @Autowired
+ private LoginStrategy loginStrategy;
+ String viewName;
+
+ @RequestMapping(value = { "/doLogin" }, method = RequestMethod.GET)
+ public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ return loginStrategy.doLogin(request, response);
+ }
+
+ public String getJessionId(HttpServletRequest request) {
+ return request.getSession().getId();
+ }
+
+ protected void initateSessionMgtHandler(HttpServletRequest request) {
+ String jSessionId = getJessionId(request);
+ PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request));
+ }
+
+ public String getViewName() {
+ return viewName;
+ }
+
+ public void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+
+ public LoginService getLoginService() {
+ return loginService;
+ }
+
+ public void setLoginService(LoginService loginService) {
+ this.loginService = loginService;
+ }
+
+}
diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ONAPWelcomeController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ONAPWelcomeController.java new file mode 100644 index 00000000..52473102 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ONAPWelcomeController.java @@ -0,0 +1,84 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import java.security.Principal; +import java.util.Set; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.mitre.openid.connect.client.SubjectIssuerGrantedAuthority; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +@Controller +@RequestMapping("/") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class ONAPWelcomeController extends EPRestrictedBaseController{ + String viewName; + + @RequestMapping(value = "/index.htm", method = RequestMethod.GET) + public String getIndexPage(HttpServletRequest request) { + return "/index"; + } + + @RequestMapping(value = {"/applicationsHome", "/dashboard", "/widgetsHome", "/kpidash*", "/admins", "/users", "/portalAdmins", "/applications", "/widgets", "/functionalMenu", "/contactUs", "/getAccess","/appCatalog" }, method = RequestMethod.GET) + public String getEcompSinglePage(HttpServletRequest request, HttpServletResponse response) { + return "forward:/index.html"; + } + + protected String getViewName() { + return viewName; + } + + protected void setViewName(String viewName) { + this.viewName = viewName; + } + + + @Resource(name = "namedAdmins") + private Set<SubjectIssuerGrantedAuthority> admins; + + @RequestMapping("/user") + public String user(Principal p) { + return "oid-user"; + } + + @RequestMapping("/admin") + public String admin(Model model, Principal p) { + + model.addAttribute("admins", admins); + + return "oid-admin"; + } + @RequestMapping("/oid-login") + public ModelAndView login(Principal p) { + return new ModelAndView("openIdLogin"); + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/OpenCollaborationController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/OpenCollaborationController.java new file mode 100644 index 00000000..18c89a66 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/OpenCollaborationController.java @@ -0,0 +1,23 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import java.util.HashMap; +import java.util.Map; diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/PeerBroadcastSocket.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/PeerBroadcastSocket.java new file mode 100644 index 00000000..086b69a9 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/PeerBroadcastSocket.java @@ -0,0 +1,106 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import java.io.IOException; +import java.util.Hashtable; +import java.util.Map; + +import javax.websocket.OnClose; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.ServerEndpoint; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import com.fasterxml.jackson.databind.ObjectMapper; + +@ServerEndpoint("/opencontact") +public class PeerBroadcastSocket { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PeerBroadcastSocket.class); + + public static Map<String, Object> channelMap = new Hashtable<String, Object>(); + public Map<String, String> sessionMap = new Hashtable<String, String>(); + ObjectMapper mapper = new ObjectMapper(); + + @OnMessage + public void message(String message, Session session) { + try { + // JSONObject jsonObject = new JSONObject(message); + @SuppressWarnings("unchecked") + Map<String, Object> jsonObject = mapper.readValue(message, Map.class); + try { + Object from = jsonObject.get("from"); + if (from != null) { + if(channelMap.get(from.toString()) == null) { + channelMap.put(from.toString(), session); + sessionMap.put(session.getId(), from.toString()); + } + } + } catch (Exception je) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to read value" + je.getMessage()); + } + + try { + Object to = jsonObject.get("to"); + if (to == null) + return; + Object toSessionObj = channelMap.get(to); + if (toSessionObj != null) { + Session toSession = null; + toSession = (Session) toSessionObj; + toSession.getBasicRemote().sendText(message); + } + + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to send text" + ex.getMessage()); + } + + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed" + ex.getMessage()); + } + + } + + @OnOpen + public void open(Session session) { + logger.info(EELFLoggerDelegate.debugLogger, "Channel opened"); + } + + @OnClose + public void close(Session session) { + String channel = sessionMap.get(session.getId()); + if (channel != null) { + Object sessObj = channelMap.get(channel); + if (sessObj != null) { + try { + ((Session) sessObj).close(); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to close" + e.getMessage()); + } + } + channelMap.remove(channel); + } + logger.info(EELFLoggerDelegate.debugLogger, "Channel closed"); + } + +} + diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/AppsOSController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/AppsOSController.java new file mode 100644 index 00000000..89f9fe58 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/AppsOSController.java @@ -0,0 +1,116 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.json.JSONObject; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.EPAppService; +import org.openecomp.portalapp.portal.service.PersUserAppService; +import org.openecomp.portalapp.portal.service.UserService; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class AppsOSController extends AppsController { + + static final String FAILURE = "failure"; + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsOSController.class); + + @Autowired + AdminRolesService adminRolesService; + @Autowired + EPAppService appService; + @Autowired + PersUserAppService persUserAppService; + @Autowired + UserService userService; + + + + /** + * Create new application's contact us details. + * + * @param contactUs + * @return + */ + @RequestMapping(value = "/portalApi/saveNewUser", method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse<String> saveNewUser(HttpServletRequest request,@RequestBody EPUser newUser) { + EPUser user = EPUserUtils.getUserSession(request); + if (newUser == null) + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, FAILURE, + "New User cannot be null or empty"); + + if (!(adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user))){ + if(!user.getLoginId().equalsIgnoreCase(newUser.getLoginId())) + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, FAILURE, + "UnAuthorized"); + } + + String checkDuplicate = request.getParameter("isCheck"); + String saveNewUser = FAILURE; + try { + saveNewUser = userService.saveNewUser(newUser,checkDuplicate); + } catch (Exception e) { + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, saveNewUser, e.getMessage()); + } + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, saveNewUser, ""); + } + + @RequestMapping(value = { "/portalApi/currentUserProfile/{loginId}" }, method = RequestMethod.GET, produces = "application/json") + public String getCurrentUserProfile(HttpServletRequest request, @PathVariable("loginId") String loginId) { + + Map<String,String> map = new HashMap<String,String>(); + EPUser user = null; + try { + user = (EPUser) userService.getUserByUserId(loginId).get(0); + map.put("firstName", user.getFirstName()); + map.put("lastName", user.getLastName()); + map.put("email", user.getEmail()); + map.put("loginId", user.getLoginId()); + map.put("loginPwd",user.getLoginPwd()); + map.put("middleInitial",user.getMiddleInitial()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to get user info", e); + } + + JSONObject j = new JSONObject(map);; + return j.toString(); + } + +}
\ No newline at end of file diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultController.java new file mode 100644 index 00000000..fe31066d --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultController.java @@ -0,0 +1,243 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalapp.controller.EPRestrictedBaseController; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem; +import org.openecomp.portalapp.portal.service.DashboardSearchService; +import org.openecomp.portalapp.portal.transport.CommonWidget; +import org.openecomp.portalapp.portal.transport.CommonWidgetMeta; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.domain.support.CollaborateList; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/portalApi/search") +public class DashboardSearchResultController extends EPRestrictedBaseController { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardSearchResultController.class); + + @Autowired + private DashboardSearchService searchService; + + /** + * Gets all widgets by type: NEW or RESOURCE + * + * @param request + * @param resourceType + * Request parameter. + * @return Rest response wrapped around a CommonWidgetMeta object. + */ + @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request, + @RequestParam String resourceType) { + return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.OK, "success", + searchService.getWidgetData(resourceType)); + } + + /** + * Saves all: news and resources + * + * @param commonWidgetMeta + * read from POST body. + * @return Rest response wrapped around a String; e.g., "success" or "ERROR" + */ + @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) { + logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta); + if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals("")) + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR", + "Category cannot be null or empty"); + // validate dates + for (CommonWidget cw : commonWidgetMeta.getItems()) { + String err = validateCommonWidget(cw); + if (err != null) + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null); + } + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", + searchService.saveWidgetDataBulk(commonWidgetMeta)); + } + + /** + * Saves one: news or resource + * + * @param commonWidget + * read from POST body + * @return Rest response wrapped around a String; e.g., "success" or "ERROR" + */ + @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget) { + logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget); + if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals("")) + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR", + "Cateogry cannot be null or empty"); + String err = validateCommonWidget(commonWidget); + if (err != null) + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null); + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", + searchService.saveWidgetData(commonWidget)); + } + + /** + * Used by the validate function + */ + private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd"); + + /** + * Validates the content of a common widget. + * + * @param cw + * @return null on success; an error message if validation fails. + * @throws Exception + */ + private String validateCommonWidget(CommonWidget cw) { + try { + if (cw.getEventDate() != null && cw.getEventDate().trim().length() > 0) + yearMonthDayFormat.parse(cw.getEventDate()); + } catch (ParseException ex) { + return ex.toString(); + } + return null; + } + + /** + * Deletes one: news or resource + * + * @param commonWidget + * read from POST body + * @return Rest response wrapped around a String; e.g., "success" or "ERROR" + */ + @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) { + logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget); + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", + searchService.deleteWidgetData(commonWidget)); + } + + /** + * Searches all portal for the input string. + * + * @param request + * @param searchString + * @return Rest response wrapped around a Map of String to List of Search + * Result Item. + */ + @RequestMapping(value = "/allPortal", method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request, + @RequestParam String searchString) { + + EPUser user = EPUserUtils.getUserSession(request); + try { + if (user == null) { + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, + "searchPortal: User object is null? - check logs", + new HashMap<String, List<SearchResultItem>>()); + } else if (searchString == null || searchString.trim().length() == 0) { + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null", + new HashMap<String, List<SearchResultItem>>()); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'", + user.getLoginId(), searchString); + Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(), + searchString); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.", + new HashMap<String, List<SearchResultItem>>()); + } + } + + /** + * Gets all active users. + * + * TODO: should only the superuser be allowed to use this API? + * + * @param request + * @return Rest response wrapped around a list of String + */ + @RequestMapping(value = "/activeUsers", method = RequestMethod.GET, produces = "application/json") + public List<String> getActiveUsers(HttpServletRequest request) { + List<String> activeUsers = null; + List<String> onlineUsers = new ArrayList<>(); + try { + EPUser user = EPUserUtils.getUserSession(request); + String userId = user.getOrgUserId(); + + activeUsers = searchService.getRelatedUsers(userId); + HashSet<String> usersSet = CollaborateList.getInstance().getAllUserName(); + for (String users : activeUsers) { + if (usersSet.contains(users)) { + onlineUsers.add(users); + } + } + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e); + } + return onlineUsers; + } + + /** + * Gets only those users that are 'related' to the currently logged-in user. + * + * @param request + * @return Rest response wrapped around a List of String + */ + @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) { + EPUser user = EPUserUtils.getUserSession(request); + try { + if (user == null) { + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs", + new ArrayList<>()); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId()); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", + searchService.getRelatedUsers(user.getLoginId())); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.", + new ArrayList<>()); + } + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java new file mode 100644 index 00000000..1d6b59ef --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java @@ -0,0 +1,129 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.io.IOException; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.EPLoginService; +import org.openecomp.portalapp.portal.service.FunctionalMenuService; +import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(PortalConstants.REST_AUX_API) +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseController { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppsRestfulController.class); + + @Autowired + FunctionalMenuService functionalMenuService; + + @Autowired + EPLoginService epLoginService; + + @Autowired + AdminRolesService adminRolesService; + + @RequestMapping(value={"/getFavorites"}, method = RequestMethod.GET,produces = "application/json") + public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request, HttpServletResponse response) throws Exception { + String loginId = ""; + String userAgent = ""; + List<FavoritesFunctionalMenuItemJson> favorites = null; + + loginId = request.getHeader(EPSystemProperties.MDC_LOGIN_ID); + userAgent = MDC.get(EPSystemProperties.PARTNER_NAME); + + EPUser epUser = epLoginService.findUserWithoutPwd(loginId); + logger.info(EELFLoggerDelegate.errorLogger, "getFavorites request was received from " + userAgent + " for the user " + loginId + "."); + if (epUser==null || epUser.getId()==null) { + logger.error(EELFLoggerDelegate.errorLogger, "No User record found for the LoginId '" + loginId + "' in the database."); + throw new Exception("Received null for Login-Id."); + } else { + favorites = functionalMenuService.getFavoriteItems(epUser.getId()); + FieldsValidator fieldsValidator = new FieldsValidator(); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + + EcompPortalUtils.logAndSerializeObject("/auxapi/getFavorites", "result = ", favorites); + } + + return favorites; + } + + @RequestMapping(value={"/functionalMenuItemsForUser"}, method = RequestMethod.GET,produces = "application/json") + public List<FunctionalMenuItem> getFunctionalMenuItemsForUser(HttpServletRequest request, HttpServletResponse response) throws Exception { + String loginId = ""; + String userAgent = ""; + List<FunctionalMenuItem> fnMenuItems = null; + + loginId = request.getHeader("LoginId"); + userAgent = MDC.get(EPSystemProperties.PARTNER_NAME); + + EPUser epUser = epLoginService.findUserWithoutPwd(loginId); + logger.info(EELFLoggerDelegate.errorLogger, "getFunctionalMenuItemsForUser request was received from " + userAgent + " for the user " + loginId + "."); + if (epUser==null || epUser.getId()==null) { + logger.error(EELFLoggerDelegate.errorLogger, "No User record found for the LoginId '" + loginId + "' in the database."); + throw new Exception("Received null for Login-Id."); + } else if (adminRolesService.isSuperAdmin(epUser)) { + logger.debug(EELFLoggerDelegate.debugLogger, "FunctionalMenuHandler: SuperUser, about to call getFunctionalMenuItems()"); + fnMenuItems = functionalMenuService.getFunctionalMenuItems(); + } + else { + logger.debug(EELFLoggerDelegate.debugLogger, "getMenuItemsForAuthUser: about to call getFunctionalMenuItemsForUser()"); + fnMenuItems = functionalMenuService.getFunctionalMenuItemsForUser(epUser.getOrgUserId()); + } + + FieldsValidator fieldsValidator = new FieldsValidator(); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + + EcompPortalUtils.logAndSerializeObject("/auxapi/functionalMenuItemsForUser", "result = ", fnMenuItems); + + return fnMenuItems; + } + + @ExceptionHandler(Exception.class) + protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException { + logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e); + response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage()); + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java new file mode 100644 index 00000000..76a9b40f --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java @@ -0,0 +1,117 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.controller.EPRestrictedBaseController; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.PortalAdminService; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.PortalAdmin; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class PortalAdminController extends EPRestrictedBaseController { + @Autowired + PortalAdminService portalAdminService; + @Autowired + AdminRolesService adminRolesService; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminController.class); + + @RequestMapping(value = { "/portalApi/portalAdmins" }, method = RequestMethod.GET, produces = "application/json") + public List<PortalAdmin> getPortalAdmins(HttpServletRequest request, HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + List<PortalAdmin> portalAdmins = null; + if (user == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, null user"); + EcompPortalUtils.setBadPermissions(user, response, "getPortalAdmins"); + } else if (!adminRolesService.isSuperAdmin(user)) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, bad permissions"); + EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin"); + } else { + // return the list of portal admins + portalAdmins = portalAdminService.getPortalAdmins(); + logger.debug(EELFLoggerDelegate.debugLogger, "portalAdmins: called getPortalAdmins()"); + EcompPortalUtils.logAndSerializeObject("/portalApi/getPortalAdmins", "result =", portalAdmins); + } + + return portalAdmins; + } + + /** + * RESTful service method to create a new portal admin. Requirement: you + * must be the Ecomp portal super admin user. + */ + + @RequestMapping(value = { "/portalApi/portalAdmin" }, method = RequestMethod.POST) + public FieldsValidator createPortalAdmin(HttpServletRequest request, @RequestBody String userid, + HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + FieldsValidator fieldsValidator = null; + if (user == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin, null user"); + EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin"); + } else if (!adminRolesService.isSuperAdmin(user)) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin bad permissions"); + EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin"); + } else { + fieldsValidator = portalAdminService.createPortalAdmin(userid); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + } + EcompPortalUtils.logAndSerializeObject("/portalAdmin", "POST result =", response.getStatus()); + + return fieldsValidator; + } + + @RequestMapping(value = { "/portalApi/portalAdmin/{orgUserId}" }, method = RequestMethod.DELETE) + public FieldsValidator deletePortalAdmin(HttpServletRequest request, @PathVariable("orgUserId") Long orgUserId, + HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + FieldsValidator fieldsValidator = null; + if (!adminRolesService.isSuperAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "deletePortalAdmin"); + } else { + fieldsValidator = portalAdminService.deletePortalAdmin(orgUserId); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + } + EcompPortalUtils.logAndSerializeObject("/portalAdmin", "DELETE result =", response.getStatus()); + + return fieldsValidator; + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/interceptor/SessionTimeoutInterceptor.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/interceptor/SessionTimeoutInterceptor.java new file mode 100644 index 00000000..dc18f1ff --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/interceptor/SessionTimeoutInterceptor.java @@ -0,0 +1,101 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.interceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.authentication.LoginStrategy; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalapp.util.SessionCookieUtil; +import org.openecomp.portalsdk.core.controller.FusionBaseController; +import org.openecomp.portalsdk.core.domain.support.CollaborateList; +import org.openecomp.portalsdk.core.exception.SessionExpiredException; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +public class SessionTimeoutInterceptor extends HandlerInterceptorAdapter { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionTimeoutInterceptor.class); + + @Autowired + private LoginStrategy loginStrategy; + + public SessionTimeoutInterceptor() { + } + + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + + if (!isHandlerMethod(handler)) + return false; + + HandlerMethod method = (HandlerMethod) handler; + + if (!isFusionController(method.getBean())) + return false; + + if (method.getBean() instanceof FusionBaseController) { + FusionBaseController controller = (FusionBaseController) method.getBean(); + + if (!controller.isAccessible()) { + try { + EPUser user = EPUserUtils.getUserSession(request); + + if (request.getRequestURI().indexOf("logout.htm") > -1) { + CollaborateList.delUserName(user.getOrgUserId()); + throw new SessionExpiredException(); + } else { + resetSessionMaxIdleTimeOut(request); + CollaborateList.addUserName(user.getOrgUserId()); + } + } catch (Exception see) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(see)); + // return loginStrategy.login(request, response); + return false; + } + + } + + } + + return true; + } + + private void resetSessionMaxIdleTimeOut(HttpServletRequest request) { + SessionCookieUtil.resetSessionMaxIdleTimeOut(request); + + } + + private boolean isFusionController(Object controller) { + if (controller instanceof FusionBaseController) + return true; + return false; + } + + private boolean isHandlerMethod(Object controller) { + if (controller instanceof HandlerMethod) + return true; + return false; + } +}
\ No newline at end of file diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAspect.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAspect.java new file mode 100644 index 00000000..974272d0 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAspect.java @@ -0,0 +1,204 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.logging.aop; + +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum; +import org.springframework.beans.factory.annotation.Autowired; + +@Aspect +@org.springframework.context.annotation.Configuration +public class EPEELFLoggerAspect { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPEELFLoggerAspect.class); + + @Autowired + EPEELFLoggerAdvice epAdvice; + + /* + * Point-cut expression to handle all INCOMING_REST_MESSAGES + */ + @Pointcut("execution(public * org.openecomp.portalapp.portal.controller.*.*(..))") + public void incomingAuditMessages() {} + + /* + * Handles all INCOMING_REST_MESSAGES from kpiDashboard + */ + @Pointcut("execution(public * org.openecomp.portalapp.kpidash.controller.*.*(..))") + public void kpiDashboardAuditMessages() {} + + /* + * Point-cut expression to handle all session management INCOMING_REST_MESSAGES + */ + @Pointcut("execution(public * org.openecomp.portalapp.controller.sessionmgt.*.*(..))") + public void sessionMgtIncomingAuditMessages() {} + + /* + * Point-cut expression to handle UserProfileController INCOMING_REST_MESSAGES + */ + @Pointcut("execution(public * org.openecomp.portalapp.controller.core.UserProfileController.*(..))") + public void userProfileIncomingAuditMessages() {} + + /* + * Point-cut expression to handle UserProfileController INCOMING_REST_MESSAGES + */ + @Pointcut("execution(public * org.openecomp.portalapp.controller.ONAPWelcomeController.*(..))") + public void welcomeIncomingAuditMessages() {} + + /* + * Point-cut expression to handle INCOMING Logout Rest Messages + */ + @Pointcut("execution(public * org.openecomp.portalapp.controller.ECOMPLogoutController.*(..))") + public void logoutAuditMessages() {} + + + /* + * Point-cut expression which handles all the OUTGOING_REST_MESSAGES. + */ + @Pointcut("execution(public * org.openecomp.portalapp.portal.service.ApplicationsRestClientServiceImpl.*(..))") + public void outgoingAuditMessages() {} + + /* + * Point-cut expression to handle all the session management OUTGOING_REST_MESSAGES. + */ + @Pointcut("execution(public * org.openecomp.portalapp.service.sessionmgt.SessionCommunication.*(..))") + public void sessionMgtOutgoingAuditMessages() {} + + /* + * Point-cut expression which handles all the LDAP_PHONEBOOK_USER_SEARCH calls. + */ + @Pointcut("execution(public * org.openecomp.portalapp.portal.service.EPLdapServiceImpl.*(..))") + public void phoneBookSearchAuditMessages() {} + + /* + * Handles Audit, Metrics & Debug logging for the point-cut + * expression defined at class-level + */ + @Around("(incomingAuditMessages() || kpiDashboardAuditMessages() || sessionMgtIncomingAuditMessages() || " + + "userProfileIncomingAuditMessages() || welcomeIncomingAuditMessages()) && @within(epAuditLog)") + public Object incomingAuditMessagesAroundClass(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE); + } + + /* + * Handles Audit, Metrics & Debug logging for the point-cut + * expression defined at class-level + */ + @Around("(outgoingAuditMessages() || sessionMgtOutgoingAuditMessages()) && @within(epAuditLog)") + public Object outgoingAuditMessagesAroundClass(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.OUTGOING_REST_MESSAGE); + } + + + /* + * Handles Audit, Metrics & Debug logging for the point-cut + * expression defined at method-level + */ + @Around("(outgoingAuditMessages() || sessionMgtOutgoingAuditMessages()) && @annotation(epAuditLog)") + public Object outgoingAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.OUTGOING_REST_MESSAGE); + } + + /* + * Handles Audit, Metrics & Debug logging for the point-cut + * expression defined at method-level + */ + @Around("(incomingAuditMessages() || kpiDashboardAuditMessages() || sessionMgtIncomingAuditMessages() ||" + + "userProfileIncomingAuditMessages() || welcomeIncomingAuditMessages()) && @annotation(epAuditLog)") + public Object incomingAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE); + } + + @Around("@annotation(epAuditLog)") + public Object loginAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.FE_LOGIN_ATTEMPT); + } + + @Around("logoutAuditMessages() && @annotation(epAuditLog)") + public Object logoutAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.FE_LOGOUT); + } + + @Around("phoneBookSearchAuditMessages() && @annotation(epAuditLog)") + public Object phonebookSearchAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH); + } + + private Object logAroundMethod(ProceedingJoinPoint joinPoint, SecurityEventTypeEnum securityEventType) throws Throwable { + //Before + Object[] passOnArgs = new Object[] {joinPoint.getSignature().getDeclaringType().getName(), joinPoint.getSignature().getName()}; + Object[] returnArgs = epAdvice.before(securityEventType, joinPoint.getArgs(), passOnArgs); + + //Call the actual method + Object result = null; + String statusCode = "COMPLETE"; + String responseCode = "200"; + try { + result = joinPoint.proceed(); + } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + statusCode = "ERROR"; + responseCode = "500"; //Internal server error + } + + //Check the result + if (securityEventType!=null) { + if (result==null) { + statusCode = "ERROR"; + //Check if there is an internal response code + //and use it if the caller function has configured it. + responseCode = epAdvice.getInternalResponseCode(); + if (responseCode==null||responseCode=="") { + responseCode = "500"; //Internal server error + } + } else if (result instanceof FieldsValidator) { + FieldsValidator fieldsValidator = (FieldsValidator) result; + if (fieldsValidator!=null && fieldsValidator.httpStatusCode!=null) { + responseCode = fieldsValidator.httpStatusCode.toString(); + } + } + } + + //After + epAdvice.after(securityEventType, statusCode, responseCode, joinPoint.getArgs(), returnArgs, passOnArgs); + + return result; + } + + //Metrics Logging + @Pointcut("execution(* *(..))") + public void performMetricsLogging() {} + + @Around("performMetricsLogging() && @within(epMetricsLog)") + public Object metricsLoggingAroundClass(ProceedingJoinPoint joinPoint, EPMetricsLog epMetricsLog) throws Throwable { + return this.logAroundMethod(joinPoint, null); + } + + @Around("performMetricsLogging() && @annotation(epMetricsLog)") + public Object metricsLoggingAroundMethod(ProceedingJoinPoint joinPoint, EPMetricsLog epMetricsLog) throws Throwable { + return this.logAroundMethod(joinPoint, null); + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientService.java new file mode 100644 index 00000000..71542268 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientService.java @@ -0,0 +1,28 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import org.apache.cxf.transport.http.HTTPException; + +public interface ApplicationsRestClientService { + public <T> T get(Class<T> clazz, long app, String restPath) throws HTTPException; + public <T> T post(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException ; + public <T> T put(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException ; +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientServiceImpl.java new file mode 100644 index 00000000..4626b17b --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientServiceImpl.java @@ -0,0 +1,267 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; + +import java.lang.reflect.Type; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Date; + +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.client.WebClient; +import org.apache.cxf.transport.http.HTTPException; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; + +@Service("applicationsRestClientService") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class ApplicationsRestClientServiceImpl implements ApplicationsRestClientService{ + + private static final String PASSWORD_HEADER = "password"; + + private static final String APP_USERNAME_HEADER = "username"; + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ApplicationsRestClientServiceImpl.class); + + @Autowired + private AppsCacheService appsCacheService; + Gson gson = null; + + @PostConstruct + private void init(){ + logger.debug(EELFLoggerDelegate.debugLogger, "initializing"); + GsonBuilder builder = new GsonBuilder(); + + // Register an adapter to manage the date types as long values + builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { + public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + return new Date(json.getAsJsonPrimitive().getAsLong()); + } + }); + + gson = builder.create(); + } + + // TODO: do we need to do additional logging for remote API calls? + private static WebClient createClientForPath(String baseUri, String path) { + logger.info(EELFLoggerDelegate.debugLogger, "Creating web client for " + baseUri + " + " + path); + WebClient client = WebClient.create(baseUri); + client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON); + client.path(path); + return client; + } + + @EPMetricsLog + private void verifyResponse(Response response) throws HTTPException { + int status = response.getStatus(); + logger.debug(EELFLoggerDelegate.debugLogger, "http response status=" + status); + MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(status)); + if (!isHttpSuccess(status)) { + String errMsg = "Failed. Status=" + status + "; [" + response.getStatusInfo().getReasonPhrase().toString() + "]"; + URL url = null; + try { + // must not be null to avoid NPE in HTTPException constructor + url = new URL("http://null"); + if (response.getLocation() != null) + url = response.getLocation().toURL(); + } catch (MalformedURLException e) { + // never mind. it is only for the debug message. + logger.warn(EELFLoggerDelegate.errorLogger, "Failed to build URL", e); + } + logger.error(EELFLoggerDelegate.errorLogger, "http response failed. " + errMsg + "; url=" + url); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeIncorrectHttpStatusError); + throw new HTTPException(status, errMsg, url); + } + } + + private static boolean isHttpSuccess(int status){ + return status / 100 == 2; + } + + @EPMetricsLog + private WebClient createClientForApp(long appId, String restPath) { + logger.debug(EELFLoggerDelegate.debugLogger, "creating client for appId=" + appId + "; restPath=" + restPath); + EPApp externalApp = appsCacheService.getApp(appId); + if(externalApp != null){ + String appBaseUri = externalApp.getAppRestEndpoint(); + String username = externalApp.getUsername(); + String encriptedPwd = externalApp.getAppPassword(); + String decreptedAppPwd = ""; + + //Set local context + MDC.put(EPSystemProperties.PROTOCOL, EPSystemProperties.HTTP); + if (appBaseUri!=null && appBaseUri.contains("https")) { + MDC.put(EPSystemProperties.PROTOCOL, EPSystemProperties.HTTPS); + } + MDC.put(EPSystemProperties.FULL_URL, appBaseUri + restPath); + MDC.put(EPSystemProperties.TARGET_ENTITY, externalApp.getName()); + MDC.put(EPSystemProperties.TARGET_SERVICE_NAME, restPath); + + try { + decreptedAppPwd = CipherUtil.decrypt(encriptedPwd, SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Unable to decrypt App name = " + externalApp, EcompPortalUtils.getStackTrace(e)); + logger.error(EELFLoggerDelegate.errorLogger, "Unable to decrypt App name = " + externalApp, EcompPortalUtils.getStackTrace(e)); + } + logger.debug(EELFLoggerDelegate.debugLogger, String.format("App %d found, baseUri=[%s], Headers: [%s=%s, %s=%s]", appId, appBaseUri, APP_USERNAME_HEADER, username, PASSWORD_HEADER, encriptedPwd)); + WebClient client = createClientForPath(appBaseUri, restPath); + client.header(APP_USERNAME_HEADER, username); + client.header(PASSWORD_HEADER, decreptedAppPwd); + client.header(SystemProperties.ECOMP_REQUEST_ID, MDC.get(MDC_KEY_REQUEST_ID)); + client.header(SystemProperties.USERAGENT_NAME, EPSystemProperties.ECOMP_PORTAL_BE); + + return client; + } + return null; + } + + @Override + public <T> T get(Class<T> clazz, long appId, String restPath) throws HTTPException { + + WebClient webClient = null; + Response response = null; + T t = null; + + webClient = createClientForApp(appId, restPath); + EcompPortalUtils.logAndSerializeObject(restPath, "GET request =", "no-payload"); + + try { + if (webClient!=null) { + response = webClient.get(); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Unable to create the Webclient to make the '" + restPath + "' API call."); + } + } catch (Exception e) { + MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiGeneralError); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the GET REST API call, Details: " + EcompPortalUtils.getStackTrace(e)); + } + + if (response!=null) { + verifyResponse(response); + String str = response.readEntity(String.class); + EcompPortalUtils.logAndSerializeObject(restPath, "GET result =", str); + try { t = gson.fromJson(str, clazz); } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput); + } + } + + return t; + } + + @Override + public <T> T post(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException { + WebClient client = null; + Response response = null; + T t = null; + + client = createClientForApp(appId, restPath); + EcompPortalUtils.logAndSerializeObject(restPath, "POST request =", payload); + + + try { + if (client!=null) { + response = client.post(payload); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Unable to create the Webclient to make the '" + restPath + "' API call."); + } + } catch (Exception e) { + MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiGeneralError); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the POST REST API call, Details: " + EcompPortalUtils.getStackTrace(e)); + } + + if (response!=null) { + verifyResponse(response); + + //String contentType = response.getHeaderString("Content-Type"); + if(clazz != null) { + String str = response.readEntity(String.class); + EcompPortalUtils.logAndSerializeObject(restPath, "POST result =", str); + try { t = gson.fromJson(str, clazz); } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput); + } + } + } + return t; + } + + @Override + public <T> T put(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException { + WebClient client = null; + Response response = null; + T t = null; + + client = createClientForApp(appId, restPath); + EcompPortalUtils.logAndSerializeObject(restPath, "PUT request =", payload); + + try { + if (client!=null) { + response = client.put(payload); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Unable to create the Webclient to make the '" + restPath + "' API call."); + } + } catch(Exception e) { + MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiGeneralError); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the PUT REST API call, Details: " + EcompPortalUtils.getStackTrace(e)); + } + + if (response!=null) { + verifyResponse(response); + String str = response.readEntity(String.class); + EcompPortalUtils.logAndSerializeObject(restPath, "PUT result =", str); + try { t = gson.fromJson(str, clazz); } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput); + } + } + return t; + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java new file mode 100644 index 00000000..20939a9a --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java @@ -0,0 +1,40 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ + +package org.openecomp.portalapp.portal.service; + +import org.openecomp.portalapp.portal.domain.EPApp; + +public interface AppsCacheService { + + /** + * returns an app by id from the cache + * @param appId + * @return corresponding App + */ + EPApp getApp(Long appId); + + /** + * returns the corresponding application endpoint + * @param appId + * @return if appId exists in cache, then return corresponding application endpoint, null otherwise. + */ + String getAppEndpoint(Long appId); +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java new file mode 100644 index 00000000..683017b1 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java @@ -0,0 +1,104 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.annotation.PostConstruct; + +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +@Service("appsCacheService") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class AppsCacheServiceImple implements AppsCacheService { + @Autowired + EPAppService appsService; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsCacheServiceImple.class); + + private static long updateTime = 0; + private static final int cacheUpdateIntervalInSeconds = 10; + + private static volatile Map<Long, EPApp> appsMap; + + @PostConstruct + public void init() { + this.refreshAppsMap(); + } + + private Map<Long, EPApp> refreshAppsMap() { + long now = System.currentTimeMillis(); + + if(noNeedToUpdate(now)) + return null; + + synchronized (this) { + if(noNeedToUpdate(now)) + return null; + List<EPApp> allApps = appsService.getAppsFullList(); + Map<Long, EPApp> newAppsMap = new HashMap<Long, EPApp>(); + for (EPApp app : allApps) { + newAppsMap.put(app.getId(), app); + } + // Switch cache with the new one. + appsMap = newAppsMap; + updateTime = now; + } + + return appsMap; + } + + private boolean noNeedToUpdate(long now) { + long secondsPassed = (now - updateTime)/1000; + if(secondsPassed < cacheUpdateIntervalInSeconds){ + logger.debug(EELFLoggerDelegate.debugLogger, "no need to refresh yet, seconds since last refresh: " + secondsPassed + ", refresh interval (sec) = " + cacheUpdateIntervalInSeconds); + return true; // no need to update cache + } + return false; // its time to update + } + + @Override + public String getAppEndpoint(Long appId) { + refreshAppsMap(); + EPApp app = appsMap.get(appId); + if(app != null) + return app.getAppRestEndpoint(); + return null; + } + + @Override + public EPApp getApp(Long appId) { + refreshAppsMap(); + EPApp app = appsMap.get(appId); + if(app != null) + return app; + return null; + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/EPAppServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/EPAppServiceImpl.java new file mode 100644 index 00000000..074821f6 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/EPAppServiceImpl.java @@ -0,0 +1,71 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + + +import java.util.ArrayList; +import java.util.List; +import java.util.TreeSet; + +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("epAppService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class EPAppServiceImpl extends EPAppCommonServiceImpl implements EPAppService { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + @Override + public List<EPApp> getUserRemoteApps(String id) { + + StringBuilder query = new StringBuilder(); + + query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where "); + query.append( + "FN_USER_ROLE.USER_ID = " + id + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID); + query.append(" AND FN_APP.ENABLED = 'Y'"); + + TreeSet<EPApp> distinctApps = new TreeSet<EPApp>(); + + @SuppressWarnings("unchecked") + List<EPApp> adminApps = dataAccessService.executeSQLQuery(query.toString(), EPApp.class, null); + for (EPApp app : adminApps) { + distinctApps.add(app); + } + + List<EPApp> userApps = new ArrayList<EPApp>(); + userApps.addAll(distinctApps); + return userApps; + + } +}
\ No newline at end of file diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java new file mode 100644 index 00000000..94937dc4 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java @@ -0,0 +1,40 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.transport.UserWithNameSurnameTitle; + +public interface SearchService { + + + public String searchUsersInPhoneBook(String searchString); + + public String searchUsersInFnTable(String searchString); + + public List<UserWithNameSurnameTitle> searchUsersByName(EPUser attrUser); + + public List<UserWithNameSurnameTitle> searchUsersByUserId(EPUser attrUser); + + public EPUser searchUserByUserId(String orgUserId); + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java new file mode 100644 index 00000000..35fc00bd --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java @@ -0,0 +1,192 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.transport.UserWithNameSurnameTitle; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Service("searchService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class SearchServiceImpl implements SearchService { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SearchServiceImpl.class); + + // TODO: the values below should be defined in other place + private static final int maxSizeOfSearchResult = 100; + + @Autowired + UserService userService; + + @Override + public String searchUsersInPhoneBook(String searchString) { + return searchUsersInFnTable(searchString); + } + + @Override + public String searchUsersInFnTable(String searchString) { + String orgUserId = null; + List<String> tokens = EcompPortalUtils.parsingByRegularExpression(searchString, " "); + for (int i = 0; i < tokens.size(); i++) { // find userid if possible and remove it from tokens + if (tokens.get(i).matches(".*\\d+.*")) { + orgUserId = tokens.get(i); + tokens.remove(i); + } + } + while (tokens.size() > 2) { // we use no more then first 2 tokens (userId is removed, see above) + tokens.remove(tokens.size() - 1); + } + EPUser attrUser = new EPUser(); + attrUser.setOrgUserId(orgUserId); + List<UserWithNameSurnameTitle> resultOfSearch = new ArrayList<UserWithNameSurnameTitle>(), resultOfAdditionalSearch = null; + if (tokens.size() == 2) { + attrUser.setFirstName(tokens.get(0)); + attrUser.setLastName(tokens.get(1)); + resultOfSearch = this.searchUsersByName(attrUser); + resultOfSearch = this.removeWrongFirstNames(resultOfSearch, tokens.get(0)); + resultOfSearch = this.removeWrongLastNames(resultOfSearch, tokens.get(1)); + if (resultOfSearch.size() < maxSizeOfSearchResult) { + attrUser.setFirstName(tokens.get(1)); + attrUser.setLastName(tokens.get(0)); + resultOfAdditionalSearch = this.searchUsersByName(attrUser); + resultOfAdditionalSearch = this.removeWrongFirstNames(resultOfAdditionalSearch, tokens.get(1)); + resultOfAdditionalSearch = this.removeWrongLastNames(resultOfAdditionalSearch, tokens.get(0)); + } + } else if (tokens.size() == 1) { + attrUser.setFirstName(tokens.get(0)); + resultOfSearch = this.searchUsersByName(attrUser); + resultOfSearch = this.removeWrongFirstNames(resultOfSearch, tokens.get(0)); + if (resultOfSearch.size() < maxSizeOfSearchResult) { + attrUser.setFirstName(null); + attrUser.setLastName(tokens.get(0)); + resultOfAdditionalSearch = this.searchUsersByName(attrUser); + resultOfAdditionalSearch = this.removeWrongLastNames(resultOfAdditionalSearch, tokens.get(0)); + } + } else if (orgUserId != null) { + resultOfSearch = this.searchUsersByUserId(attrUser); + } + if (resultOfAdditionalSearch != null) { + resultOfSearch.addAll(resultOfAdditionalSearch); + } + resultOfSearch = this.cutSearchResultToMaximumSize(resultOfSearch); + ObjectMapper mapper = new ObjectMapper(); + String result = "[]"; + try { + result = mapper.writeValueAsString(resultOfSearch); + } catch (JsonProcessingException e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchUsersInPhoneBook Exception = " + EcompPortalUtils.getStackTrace(e)); + } + return result; + } + + + @SuppressWarnings("rawtypes") + public List<UserWithNameSurnameTitle> searchUsersByUserId(EPUser attrUser) { + List<UserWithNameSurnameTitle> foundUsers = new ArrayList<UserWithNameSurnameTitle>(); + try { + List searchResult = this.userService.getUserByUserId(attrUser.getOrgUserId()); + for (Object obj : searchResult) { + EPUser user = (EPUser) obj; + UserWithNameSurnameTitle foundUser = new UserWithNameSurnameTitle(user.getOrgUserId(), user.getFirstName(), user.getLastName(), user.getJobTitle()); + foundUsers.add(foundUser); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchInPhoneBookWithToken Exception = " + EcompPortalUtils.getStackTrace(e)); + } + return foundUsers; + } + + @SuppressWarnings("rawtypes") + public List<UserWithNameSurnameTitle> searchUsersByName(EPUser attrUser) { + List<UserWithNameSurnameTitle> foundUsers = new ArrayList<UserWithNameSurnameTitle>(); + try { + List searchResult = this.userService.getUserByFirstLastName(attrUser.getFirstName(),attrUser.getLastName()); + for (Object obj : searchResult) { + EPUser user = (EPUser) obj; + UserWithNameSurnameTitle foundUser = new UserWithNameSurnameTitle(user.getOrgUserId(), user.getFirstName(), user.getLastName(), user.getJobTitle()); + foundUsers.add(foundUser); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchInPhoneBookWithToken Exception = " + EcompPortalUtils.getStackTrace(e)); + } + return foundUsers; + } + + private List<UserWithNameSurnameTitle> removeWrongFirstNames(List<UserWithNameSurnameTitle> resultOfSearch, String firstName) { + firstName = firstName.toUpperCase(); + for (int i = resultOfSearch.size() - 1; i >= 0; i--) { + UserWithNameSurnameTitle user = resultOfSearch.get(i); + if ((user.firstName == null) || !user.firstName.toUpperCase().startsWith(firstName)) { + resultOfSearch.remove(i); + } + } + return resultOfSearch; + } + + private List<UserWithNameSurnameTitle> removeWrongLastNames(List<UserWithNameSurnameTitle> resultOfSearch, String lastName) { + lastName = lastName.toUpperCase(); + for (int i = resultOfSearch.size() - 1; i >= 0; i--) { + UserWithNameSurnameTitle user = resultOfSearch.get(i); + if ((user.lastName == null) || !user.lastName.toUpperCase().startsWith(lastName)) { + resultOfSearch.remove(i); + } + } + return resultOfSearch; + } + + private List<UserWithNameSurnameTitle> cutSearchResultToMaximumSize(List<UserWithNameSurnameTitle> resultOfSearch) { + for (int i = resultOfSearch.size() - 1; i >= maxSizeOfSearchResult; i--) { + resultOfSearch.remove(i); + } + return resultOfSearch; + } + + + @SuppressWarnings("rawtypes") + @Override + public EPUser searchUserByUserId(String orgUserId) { + List<EPUser> foundUsers = new ArrayList<EPUser>(); + try { + List searchResult = this.userService.getUserByUserId(orgUserId); + for (Object obj : searchResult) { + EPUser user = (EPUser) obj; + foundUsers.add(user); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchInPhoneBookWithToken Exception = " + EcompPortalUtils.getStackTrace(e)); + } + return foundUsers.get(0); + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java new file mode 100644 index 00000000..b285051c --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java @@ -0,0 +1,58 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.apache.cxf.transport.http.HTTPException; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserApp; +import org.openecomp.portalapp.portal.transport.AppWithRolesForUser; +import org.openecomp.portalapp.portal.transport.RoleInAppForUser; +import org.openecomp.portalapp.portal.transport.UserApplicationRoles; + +public interface UserRolesService { + + public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId); + + public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser); + + public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException; + + public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException; + + + /** + * Gets entries from the local fn_user_role table for the specified user and + * app. + * + * @param appId + * ID of row in fn_app + * @param userid + * ID of row in fn_user + * @return List of EPRole; empty if none found. + */ + public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId); + + public String updateRemoteUserProfile(String orgUserId, Long appId); + + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesServiceImpl.java new file mode 100644 index 00000000..a0aac922 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesServiceImpl.java @@ -0,0 +1,726 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import javax.annotation.PostConstruct; + +import org.apache.commons.lang.StringUtils; +import org.apache.cxf.transport.http.HTTPException; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserApp; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.transport.AppWithRolesForUser; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.transport.FunctionalMenuRole; +import org.openecomp.portalapp.portal.transport.RemoteUserWithRoles; +import org.openecomp.portalapp.portal.transport.RoleInAppForUser; +import org.openecomp.portalapp.portal.transport.RolesInAppForUser; +import org.openecomp.portalapp.portal.transport.UserApplicationRoles; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.restful.domain.EcompRole; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.service.UserProfileService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Service("userRolesService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class UserRolesServiceImpl implements UserRolesService { + private static Long ACCOUNT_ADMIN_ROLE_ID = 999L; + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesServiceImpl.class); + + @Autowired + private SessionFactory sessionFactory; + @Autowired + private DataAccessService dataAccessService; + @Autowired + SearchService searchService; + @Autowired + EPAppService appsService; + @Autowired + EPLdapService ldapService; + @Autowired + ApplicationsRestClientService applicationsRestClientService; + @Autowired + EPRoleService epRoleService; + @Autowired + UserProfileService userProfileService; + + @PostConstruct + private void init() { + try { + ACCOUNT_ADMIN_ROLE_ID = Long + .valueOf(SystemProperties.getProperty(EPSystemProperties.ACCOUNT_ADMIN_ROLE_ID)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + + private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) { + HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>(); + if (ecompRoles != null) { + for (int i = 0; i < ecompRoles.length; i++) { + if (ecompRoles[i].getId() != null) { + result.put(ecompRoles[i].getId(), ecompRoles[i]); + } + } + } + return result; + } + + private void createLocalUserIfNecessary(String orgUserId) { + if (StringUtils.isEmpty(orgUserId)) { + logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty orgUserId!"); + return; + } + Session localSession = null; + Transaction transaction = null; + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + @SuppressWarnings("unchecked") + List<EPUser> userList = localSession + .createQuery("from " + EPUser.class.getName() + " where org_user_id='" + orgUserId + "'").list(); + if (userList.size() == 0) { + EPUser client = searchService.searchUserByUserId(orgUserId); + if (client == null) { + String msg = "cannot create user " + orgUserId + ", because he cannot be found in phonebook"; + logger.error(EELFLoggerDelegate.errorLogger, msg); + } else { + client.setLoginId(orgUserId); + client.setActive(true); + localSession.save(client); + } + } + transaction.commit(); + } catch (Exception e) { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError); + EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser"); + } + } + + private static void syncUserRoles(SessionFactory sessionFactory, String orgUserId, Long appId, + EcompRole[] userAppRoles) throws Exception { + HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles); + boolean result = false; + Session localSession = null; + Transaction transaction = null; + + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + @SuppressWarnings("unchecked") + List<EPUser> userList = localSession + .createQuery("from " + EPUser.class.getName() + " where org_user_id='" + orgUserId + "'").list(); + if (userList.size() > 0) { + EPUser client = userList.get(0); + @SuppressWarnings("unchecked") + List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName() + + " where app.id=" + appId + " and userId=" + client.getId()).list(); + for (EPUserApp userRole : userRoles) { + if (!userRole.getRoleId().equals(ACCOUNT_ADMIN_ROLE_ID)) { + + Long userAppRoleId = userRole.getAppRoleId(); + if (!newUserAppRolesMap.containsKey(userAppRoleId)) { + localSession.delete(userRole); + } else { + newUserAppRolesMap.remove(userAppRoleId); + } + } + } + Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values(); + if (newRolesToAdd.size() > 0) { + EPApp app = (EPApp) localSession.get(EPApp.class, appId); + @SuppressWarnings("unchecked") + List<EPRole> roles = localSession + .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list(); + HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>(); + for (EPRole role : roles) { + rolesMap.put(role.getAppRoleId(), role); + } + for (EcompRole userRole : newRolesToAdd) { + EPUserApp userApp = new EPUserApp(); + userApp.setUserId(client.getId()); + userApp.setApp(app); + userApp.setRole(rolesMap.get(userRole.getId())); + localSession.save(userApp); + } + } + } + transaction.commit(); + result = true; + } catch (Exception e) { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError); + EcompPortalUtils.rollbackTransaction(transaction, + "Exception occurred in syncUserRoles, Details: " + EcompPortalUtils.getStackTrace(e)); + } finally { + localSession.close(); + if (!result) { + throw new Exception( + "Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'."); + } + } + } + + // Called when getting the list of roles for the user + private List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) { + List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>(); + + Set<Long> userAppRolesMap = new HashSet<Long>(); + if (userAppRoles != null) { + for (EcompRole ecompRole : userAppRoles) { + userAppRolesMap.add(ecompRole.getId()); + } + } else { + String message = String + .format("UserRolesServiceImpl.constructRolesInAppForUserGet has received userAppRoles list empty."); + logger.info(EELFLoggerDelegate.errorLogger, message); + } + + if (appRoles != null) { + for (EcompRole ecompRole : appRoles) { + RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName()); + roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId()); + rolesInAppForUser.add(roleForUser); + } + } else { + String message = String + .format("UserRolesServiceImpl.constructRolesInAppForUser has received appRoles list empty."); + logger.info(EELFLoggerDelegate.errorLogger, message); + } + return rolesInAppForUser; + } + + public List<RoleInAppForUser> getAppRolesForUser(Long appId, String orgUserId) { + List<RoleInAppForUser> rolesInAppForUser = null; + try { + EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles"); + + // Test this error case, for generating an internal Ecomp Portal + // error + // EcompRole[] appRoles = null; + // If there is an exception in the rest client api, then null will + // be returned. + if (appRoles != null) { + syncAppRoles(sessionFactory, appId, appRoles); + EcompRole[] userAppRoles; + try { + userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId, + String.format("/user/%s/roles", orgUserId)); + if (userAppRoles == null) { + if (EcompPortalUtils.getExternalAppResponseCode() == 400) { + EcompPortalUtils.setExternalAppResponseCode(200); + logger.error(EELFLoggerDelegate.errorLogger, + "400 returned from /user/{userid}/roles, assuming user doesn't exist, app is framework SDK based, and things are ok. Overriding to 200 until framework SDK returns a useful response."); + logger.debug(EELFLoggerDelegate.debugLogger, + "400 returned from /user/{userid}/roles, assuming user doesn't exist, app is framework SDK based, and things are ok. Overriding to 200 until framework SDK returns a useful response."); + } + } + // If the remote application isn't down we MUST to sync user + // roles here in case we have this user here! + syncUserRoles(sessionFactory, orgUserId, appId, userAppRoles); + } catch (Exception e) { + // TODO: we may need to check if user exists, maybe remote + // app is down. + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + logger.error(EELFLoggerDelegate.errorLogger, + "LR: user " + orgUserId + " does not exist in remote application: " + appId + "."); + userAppRoles = new EcompRole[0]; + } + rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles); + // Test this error case, for generating an external app error + // EcompPortalUtils.setResponseCode(404); + } + } catch (Exception e) { + String message = String.format( + "Received an exception while performing getAppRolesForUser for the User %s, and for the AppId %s, Details: %s", + orgUserId, Long.toString(appId), EcompPortalUtils.getStackTrace(e)); + logger.error(EELFLoggerDelegate.errorLogger, message); + } + return rolesInAppForUser; + + } + + // copies of methods in GetAppsWithUserRoleState + private void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId); + HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles); + boolean result = false; + Session localSession = null; + Transaction transaction = null; + + try { + localSession = sessionFactory.openSession(); + 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> obsoleteRoles = new ArrayList<EPRole>(); + for (int i = 0; i < currentAppRoles.size(); i++) { + EPRole oldAppRole = currentAppRoles.get(i); + if (oldAppRole.getAppRoleId() != null) { + EcompRole role = null; + role = newRolesMap.get(oldAppRole.getAppRoleId()); + if (role != null) { + if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) { + oldAppRole.setName(role.getName()); + localSession.update(oldAppRole); + } + newRolesMap.remove(oldAppRole.getAppRoleId()); + } else { + obsoleteRoles.add(oldAppRole); + } + } else { + obsoleteRoles.add(oldAppRole); + } + } + Collection<EcompRole> newRolesToAdd = newRolesMap.values(); + for (EcompRole role : newRolesToAdd) { + logger.debug(EELFLoggerDelegate.debugLogger, "about to add missing role: " + role.toString()); + EPRole newRole = new EPRole(); + // Attention! All roles from remote application supposed to be + // active! + newRole.setActive(true); + newRole.setName(role.getName()); + newRole.setAppId(appId); + newRole.setAppRoleId(role.getId()); + localSession.save(newRole); + } + if (obsoleteRoles.size() > 0) { + logger.debug(EELFLoggerDelegate.debugLogger, "we have obsolete roles to delete"); + for (EPRole role : obsoleteRoles) { + logger.debug(EELFLoggerDelegate.debugLogger, "obsolete role: " + role.toString()); + Long roleId = role.getId(); + // delete obsolete roles here + // Must delete all records with foreign key constraints on + // fn_role: + // fn_user_role, fn_role_composite, fn_role_function, + // fn_user_pseudo_role, fn_menu_functional_roles. + // And for fn_menu_functional, if no other roles for that + // menu item, remove the url. + + // Delete from fn_user_role + @SuppressWarnings("unchecked") + List<EPUserApp> userRoles = localSession.createQuery( + "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId) + .list(); + + logger.debug(EELFLoggerDelegate.debugLogger, "number of userRoles to delete: " + userRoles.size()); + for (EPUserApp userRole : userRoles) { + logger.debug(EELFLoggerDelegate.debugLogger, + "about to delete userRole: " + userRole.toString()); + localSession.delete(userRole); + logger.debug(EELFLoggerDelegate.debugLogger, + "finished deleting userRole: " + userRole.toString()); + } + + // Delete from fn_menu_functional_roles + @SuppressWarnings("unchecked") + List<FunctionalMenuRole> funcMenuRoles = localSession + .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId) + .list(); + int numMenuRoles = funcMenuRoles.size(); + logger.debug(EELFLoggerDelegate.debugLogger, + "number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles); + for (FunctionalMenuRole funcMenuRole : funcMenuRoles) { + Long menuId = funcMenuRole.menuId; + // If this is the only role for this menu item, then the + // app and roles will be gone, + // so must null out the url too, to be consistent + @SuppressWarnings("unchecked") + List<FunctionalMenuRole> funcMenuRoles2 = localSession + .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId) + .list(); + int numMenuRoles2 = funcMenuRoles2.size(); + logger.debug(EELFLoggerDelegate.debugLogger, + "number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2); + localSession.delete(funcMenuRole); + if (numMenuRoles2 == 1) { + // If this is the only role for this menu item, then + // the app and roles will be gone, + // so must null out the url too, to be consistent + logger.debug(EELFLoggerDelegate.debugLogger, + "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) + .list(); + if (funcMenuItems.size() > 0) { + logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item"); + FunctionalMenuItem funcMenuItem = funcMenuItems.get(0); + funcMenuItem.url = ""; + localSession.update(funcMenuItem); + } + } + } + + // Delete from fn_role_function + String sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + Query query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Delete from fn_role_composite + sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Delete from fn_user_pseudo_role + sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + logger.debug(EELFLoggerDelegate.debugLogger, "about to delete the role: " + role.toString()); + localSession.delete(role); + logger.debug(EELFLoggerDelegate.debugLogger, "deleted the role"); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction"); + transaction.commit(); + logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction"); + result = true; + } catch (Exception e) { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError); + EcompPortalUtils.rollbackTransaction(transaction, + "Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e)); + } finally { + localSession.close(); + if (!result) { + throw new Exception( + "Exception occurred in syncAppRoles while closing database session for app: '" + appId + "'."); + } + } + } + + // Called when updating the list of roles for the user + private RolesInAppForUser constructRolesInAppForUserUpdate(String orgUserId, Long appId, + Set<EcompRole> userRolesInRemoteApp) { + RolesInAppForUser result; + result = new RolesInAppForUser(); + result.appId = appId; + result.orgUserId = orgUserId; + for (EcompRole role : userRolesInRemoteApp) { + RoleInAppForUser roleInAppForUser = new RoleInAppForUser(); + roleInAppForUser.roleId = role.getId(); + roleInAppForUser.roleName = role.getName(); + roleInAppForUser.isApplied = new Boolean(true); + result.roles.add(roleInAppForUser); + } + return result; + } + + private EPUser getUserFromRemoteApp(String orgUserId, EPApp app, + ApplicationsRestClientService applicationsRestClientService) throws HTTPException { + EPUser user = applicationsRestClientService.get(EPUser.class, app.getId(), + String.format("/user/%s", orgUserId)); + return user; + } + + private boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) { + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (roleInAppForUser.isApplied.booleanValue()) { + return true; + } + } + return false; + } + + private Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper, + ApplicationsRestClientService applicationsRestClientService, Long appId, String orgUserId) + throws JsonProcessingException, HTTPException { + Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList); + String userRolesAsString = mapper.writeValueAsString(updatedUserRoles); + applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString, + String.format("/user/%s/roles", orgUserId)); + // TODO: We should add code that verifies that the post operation did + // succeed. Because the SDK may still return 200 OK with an html page + // even when it fails! + return updatedUserRoles; + } + + private Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) { + Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>(); + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (roleInAppForUser.isApplied) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(roleInAppForUser.roleId); + ecompRole.setName(roleInAppForUser.roleName); + existingUserRoles.add(ecompRole); + } + } + return existingUserRoles; + } + + private static void createNewUserOnRemoteApp(String orgUserId, EPApp app, + ApplicationsRestClientService applicationsRestClientService, SearchService searchService, + ObjectMapper mapper) throws Exception { + EPUser client = searchService.searchUserByUserId(orgUserId); + if (client == null) { + String msg = "cannot create user " + orgUserId + ", because he/she cannot be found in phonebook."; + logger.error(EELFLoggerDelegate.errorLogger, msg); + throw new Exception(msg); + } + client.setLoginId(orgUserId); + client.setActive(true); + // The remote doesn't care about other apps, and this has caused + // serialization problems - infinite recursion. + client.getEPUserApps().clear(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String userAsString = mapper.writeValueAsString(client); + logger.debug(EELFLoggerDelegate.debugLogger, + "about to post new client to remote application, users json = " + userAsString); + applicationsRestClientService.post(EPUser.class, app.getId(), userAsString, String.format("/user", orgUserId)); + } + + public String updateRemoteUserProfile(String orgUserId, Long appId) { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + EPUser client = searchService.searchUserByUserId(orgUserId); + EPUser newUser = new EPUser(); + newUser.setActive(client.getActive()); + newUser.setFirstName(client.getFirstName()); + newUser.setLastName(client.getLastName()); + newUser.setLoginId(client.getLoginId()); + newUser.setLoginPwd(client.getLoginPwd()); + newUser.setMiddleInitial(client.getMiddleInitial()); + newUser.setEmail(client.getEmail()); + newUser.setOrgUserId(client.getLoginId()); + try { + String userAsString = mapper.writeValueAsString(newUser); + List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString()); + // applicationsRestClientService.post(EPUser.class, appId, + // userAsString, String.format("/user", orgUserId)); + for (EPApp eachApp : appList) { + try { + applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString, + String.format("/user/%s", orgUserId)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId() + + " in remote app. appId = " + eachApp.getId()); + } + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return "failure"; + } + + return "success"; + + } + + private static final Object syncRests = new Object(); + + @Override + public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) { + boolean result = false; + String orgUserId = ""; + if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) { + orgUserId = newAppRolesForUser.orgUserId.trim(); + } + Long appId = newAppRolesForUser.appId; + List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles; + if (orgUserId.length() > 0) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + try { + EPApp app = appsService.getApp(appId); + EPUser remoteAppUser = getUserFromRemoteApp(orgUserId, app, applicationsRestClientService); + if (remoteAppUser == null) { + if (remoteUserShouldBeCreated(roleInAppForUserList)) { + createNewUserOnRemoteApp(orgUserId, app, applicationsRestClientService, searchService, mapper); + // If we succeed, we know that the new user was + // persisted on remote app. + remoteAppUser = getUserFromRemoteApp(orgUserId, app, applicationsRestClientService); + if (remoteAppUser == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "Failed to persist new user: " + orgUserId + " in remote app. appId = " + appId); + // return null; + } + } + } + if (remoteAppUser != null) { + Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, + applicationsRestClientService, appId, orgUserId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, appId, + userRolesInRemoteApp); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser); + } + } catch (Exception e) { + String message = String.format( + "Failed to create user or update user roles for the User %s, and for the AppId %s, Details: %s", + orgUserId, Long.toString(appId), EcompPortalUtils.getStackTrace(e)); + logger.error(EELFLoggerDelegate.errorLogger, message); + result = false; + } + + } + return result; + } + + // This is for a single app + private boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser) { + boolean result = false; + String orgUserId = rolesInAppForUser.orgUserId; + Long appId = rolesInAppForUser.appId; + synchronized (syncRests) { + if (rolesInAppForUser != null) { + createLocalUserIfNecessary(orgUserId); + } + + if (rolesInAppForUser != null) { + EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.size()]; + for (int i = 0; i < rolesInAppForUser.roles.size(); i++) { + RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i); + EcompRole role = new EcompRole(); + role.setId(roleInAppForUser.roleId); + role.setName(roleInAppForUser.roleName); + userAppRoles[i] = role; + } + try { + syncUserRoles(sessionFactory, orgUserId, appId, userAppRoles); + result = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "applyChangesInUserRolesForAppToEcompDB syncUserRoles, orgUserId = " + orgUserId); + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + } + return result; + } + + @Override + public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException { + RemoteUserWithRoles[] remoteUsers = applicationsRestClientService.get(RemoteUserWithRoles[].class, appId, + "/users"); + ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>(); + for (RemoteUserWithRoles remoteUser : remoteUsers) { + UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser); + if(userWithRemoteAppRoles.getRoles()!=null && userWithRemoteAppRoles.getRoles().size()>0) { + userApplicationRoles.add(userWithRemoteAppRoles); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "User " + userWithRemoteAppRoles.getOrgUserId() + + " doesn't have any roles assigned to any app."); + + } + } + + return userApplicationRoles; + } + + private UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) { + UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles(); + userWithRemoteAppRoles.setAppId(appId); + userWithRemoteAppRoles.setOrgUserId(remoteUser.getLoginId()); + userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName()); + userWithRemoteAppRoles.setLastName(remoteUser.getLastName()); + userWithRemoteAppRoles.setRoles(remoteUser.getRoles()); + return userWithRemoteAppRoles; + } + + public static void persistExternalRoleInEcompDb(EPRole externalAppRole, Long appId, EPRoleService roleService) { + externalAppRole.setAppId(appId); + externalAppRole.setAppRoleId(externalAppRole.getId()); + externalAppRole.setId(null); // We will persist a new role, with ecomp + // role id which will be different than + // external app role id. + + roleService.saveRole(externalAppRole); + logger.debug(EELFLoggerDelegate.debugLogger, + String.format("ECOMP persists role from app:%d, app roleId: %d, roleName: %s", appId, + externalAppRole.getAppRoleId(), externalAppRole.getName())); + } + + @Override + public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException { + EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull"); + List<EPRole> rolesList = Arrays.asList(appRolesFull); + for (EPRole externalAppRole : rolesList) { + + // Try to find an existing extern role for the app in the local + // ecomp DB. If so, then use its id to update the existing external + // application role record. + Long externAppId = externalAppRole.getId(); + EPRole existingAppRole = epRoleService.getRole(appId, externAppId); + if (existingAppRole != null) { + logger.debug(EELFLoggerDelegate.debugLogger, + String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.", + appId, externAppId)); + continue; + } + // persistExternalRoleInEcompDb(externalAppRole, appId, + // roleService); + } + + return rolesList; + } + + @Override + public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) { + // Find the records for this user-app combo, if any + String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId); + @SuppressWarnings("unchecked") + List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null); + logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size()); + return roleList; + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserService.java new file mode 100644 index 00000000..bd8949f3 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserService.java @@ -0,0 +1,34 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPUser; + +public interface UserService { + + List getUserByUserId(String orgUserId); + + List getUserByFirstLastName(String firstName, String lastName); + + public String saveNewUser(EPUser newUser, String checkDuplicate) throws Exception; + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java new file mode 100644 index 00000000..225f3a7a --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java @@ -0,0 +1,260 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.FusionObject.Utilities; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("userService") +@Transactional +public class UserServiceImpl implements UserService { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + @SuppressWarnings("rawtypes") + @Override + public List getUserByUserId(String userId) { + + + if(SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")){ + List<EPUser> users=new ArrayList<EPUser>(); + List<EPUser> filterdUsers=new ArrayList<EPUser>(); + BufferedReader in = null; + HttpURLConnection con = null; + try{ + String url = EPSystemProperties.getProperty(EPSystemProperties.AUTH_USER_SERVER); + URL obj = new URL(url); + + con = (HttpURLConnection) obj.openConnection(); + + // optional default is GET + con.setRequestMethod("GET"); + con.setConnectTimeout(3000); + con.setReadTimeout(8000); + + StringBuffer response = new StringBuffer(); + + in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); + String inputLine; + while ((inputLine = in.readLine()) != null) + response.append(inputLine); + JSONObject jObject = new JSONObject(response.toString()); // json + JSONArray jsonUsers = jObject.getJSONArray("response"); // get data object + for (int i = 0; i < jsonUsers.length(); i++) { + JSONObject eachObject = jsonUsers.getJSONObject(i); + EPUser eachUser = new EPUser(); + eachUser.setOrgUserId(eachObject.get("id").toString());// getString("id")); + eachUser.setFirstName(eachObject.get("givenName").toString()); + eachUser.setLastName(eachObject.get("familyName").toString()); + eachUser.setEmail(eachObject.get("email").toString()); + users.add(eachUser); + } + + for(int i = 0 ; i < users.size(); i ++){ + + if(Utilities.nvl(userId).length() > 0){ + if(!userId.equalsIgnoreCase(users.get(i).getOrgUserId())){ + continue; + } + } + filterdUsers.add(users.get(i)); + + } + + }catch (Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + }finally{ + try { + in.close(); + con.disconnect(); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + + return filterdUsers; + + }else{ + + List list = null; + StringBuffer criteria = new StringBuffer(); + criteria.append(" where org_user_id = '").append(userId).append("'"); + list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null); + return (list == null || list.size() == 0) ? null : list; + + } + + } + + @SuppressWarnings("rawtypes") + @Override + public List getUserByFirstLastName(String firstName, String lastName) { + + if(!SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")){ + + List list = null; + StringBuffer criteria = new StringBuffer(); + if(firstName!=null) + criteria.append(" where first_name = '").append(firstName).append("'"); + if(lastName!=null) + criteria.append(" where last_name = '").append(lastName).append("'"); + list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null); + return (list == null || list.size() == 0) ? null : list; + + }else{ + + List<EPUser> users=new ArrayList<EPUser>(); + List<EPUser> filterdUsers=new ArrayList<EPUser>(); + BufferedReader in = null; + HttpURLConnection con = null; + try{ + String url = EPSystemProperties.getProperty(EPSystemProperties.AUTH_USER_SERVER); + URL obj = new URL(url); + + con = (HttpURLConnection) obj.openConnection(); + + // optional default is GET + con.setRequestMethod("GET"); + con.setConnectTimeout(3000); + con.setReadTimeout(8000); + + StringBuffer response = new StringBuffer(); + + in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); + String inputLine; + while ((inputLine = in.readLine()) != null) + response.append(inputLine); + JSONObject jObject = new JSONObject(response.toString()); // json + JSONArray jsonUsers = jObject.getJSONArray("response"); // get data object + for (int i = 0; i < jsonUsers.length(); i++) { + JSONObject eachObject = jsonUsers.getJSONObject(i); + EPUser eachUser = new EPUser(); + eachUser.setOrgUserId(eachObject.get("id").toString());// getString("id")); + eachUser.setFirstName(eachObject.get("givenName").toString()); + eachUser.setLastName(eachObject.get("familyName").toString()); + eachUser.setEmail(eachObject.get("email").toString()); + users.add(eachUser); + } + + for(int i = 0 ; i < users.size(); i ++){ + + if(Utilities.nvl(firstName).length() > 0){ + if(!firstName.equalsIgnoreCase(users.get(i).getFirstName())){ + continue; + } + } + if(Utilities.nvl(lastName).length() > 0){ + if(!lastName.equalsIgnoreCase(users.get(i).getLastName())){ + continue; + } + } + + + filterdUsers.add(users.get(i)); + + } + + }catch (Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + }finally{ + try { + in.close(); + con.disconnect(); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + + return filterdUsers; + } + + } + + public String saveNewUser(EPUser newUser, String checkDuplicate) throws Exception{ + + try{ + + List list = null; + StringBuffer criteria = new StringBuffer(); + criteria.append(" where org_user_id = '").append(newUser.getLoginId()).append("'"); + list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null); + if(list == null || list.size()==0){ + newUser.setActive(true); + newUser.setOrgUserId(newUser.getLoginId()); + newUser.setLoginPwd(CipherUtil.encrypt(newUser.getLoginPwd())); + getDataAccessService().saveDomainObject(newUser, null); + }else{ + if(checkDuplicate.equals("Yes")){ + // userId already exist in database + return "Record already exist"; + }else{ + + EPUser oldUser = (EPUser) list.get(0); + oldUser.setFirstName(newUser.getFirstName()); + oldUser.setLastName(newUser.getLastName()); + oldUser.setMiddleInitial(newUser.getMiddleInitial()); + if(!oldUser.getLoginPwd().equals(newUser.getLoginPwd())) + oldUser.setLoginPwd(CipherUtil.encrypt(newUser.getLoginPwd())); + else + oldUser.setLoginPwd(newUser.getLoginPwd()); + getDataAccessService().saveDomainObject(oldUser, null); + + } + + } + + }catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "", e); + throw new Exception(e); + } + return "success"; + }; + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java new file mode 100644 index 00000000..4c97a52d --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java @@ -0,0 +1,83 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +public class OnboardingApp { + + public Long id; + + public String name; + + public String imageUrl; + + public String description; + + public String notes; + + public String url; + + public String alternateUrl; + + public String restUrl; + + public Boolean isOpen; + + public Boolean isEnabled; + + public String username; + + public String appPassword; + + public String thumbnail; + + public String uebTopicName; + + public String uebKey; + + public String uebSecret; + + public Boolean restrictedApp; + + public void normalize() { + this.name = (this.name == null) ? "" : this.name.trim(); + this.username = (this.username == null) ? "" : this.username.trim(); + this.appPassword = (this.appPassword == null) ? "" : this.appPassword.trim(); + } + + public void setUebTopicName(String topicName) { + this.uebTopicName = topicName; + } + + public void setUebKey(String key) { + this.uebKey = key; + } + + public void setUebSecret(String secret) { + this.uebSecret = secret; + } + + // Hide the implementation of restricted and normal app from the front end. + // The json sent and received will include restrictedApp but not appType. + + public void setRestrictedApp(Boolean restrictedApp) { + this.restrictedApp = restrictedApp; + } +} + diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java new file mode 100644 index 00000000..1162cf20 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java @@ -0,0 +1,218 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.ueb; + +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.LinkedList; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EcompApp; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.service.EPAppService; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; +import org.openecomp.portalsdk.core.onboarding.ueb.Helper; +import org.openecomp.portalsdk.core.onboarding.ueb.Publisher; +import org.openecomp.portalsdk.core.onboarding.ueb.UebException; +import org.openecomp.portalsdk.core.onboarding.ueb.UebManager; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +@Component +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +public class EPUebHelper { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUebHelper.class); + + @Autowired + EPAppService appsService; + + + @Autowired + private SessionFactory sessionFactory; + + @SuppressWarnings("unused") + private Publisher epPublisher; + + public EPUebHelper() { + + } + // + // This should only be called by the ECOMP Portal App, other Apps have just one publisher and use appPublisher + // + @SuppressWarnings("unused") + @EPMetricsLog + public void refreshPublisherList() + { + Session localSession = null; + boolean addedPublisher = false; + + try { + localSession = sessionFactory.openSession(); + + List<EcompApp> apps = appsService.getEcompAppAppsFullList(); + for (int i = 0; i < apps.size(); i++) + { + if ((apps.get(i).isEnabled()) && + (apps.get(i).getUebTopicName() != null) && + !(apps.get(i).getUebTopicName().toUpperCase().contains("ECOMP-PORTAL-INBOX"))) + { + logger.debug(EELFLoggerDelegate.debugLogger, "UEBManager adding publisher for " + apps.get(i).getUebTopicName()); + UebManager.getInstance().addPublisher(apps.get(i).getUebTopicName()); + addedPublisher = true; + } + else if ((apps.get(i).getId() != 1) && // App may have been disabled, remove the publisher + !(apps.get(i).isEnabled())) + { + if(apps.get(i).getUebTopicName()!=null){ + UebManager.getInstance().removePublisher(apps.get(i).getUebTopicName()); + } + } + } + } + catch (Exception e) + { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebSystemError, "add/remove Publisher"); + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while refreshing the publisher list. Details: " + stackTrace); + } + + //publisherList.print(); + + if (addedPublisher == true) // Give publishers time to initialize + { + Helper.sleep(400); + } + } + + //@PostConstruct + //@EPMetricsLog + public void initUeb() { + try { + epPublisher = new Publisher(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY), + PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME)); + } catch (Exception e) { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebConnectionError, e.getMessage()); + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while initializing the publisher. Details: " + stackTrace); + } + + Thread thread = new Thread("EPUebManager: postConstructMethod - refreshPublisherList") { + public void run(){ + refreshPublisherList(); + } + }; + if (thread != null) { + thread.start(); + } + } + + @EPMetricsLog + public void addPublisher(EPApp app) { + // TODO Auto-generated method stub + try { + UebManager.getInstance().addPublisher(app.getUebTopicName()); + } catch (UebException e) { + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception while adding a publisher. Details: " + stackTrace); + } + } + + public boolean checkAvailability() { + + // + // Test existence of topic at UEB url + // + // + // + boolean available = true; + LinkedList<String> urlList = Helper.uebUrlList(); + if (!urlList.isEmpty()) { + String url = "http://" + urlList.getFirst() + ":3904/topics/" + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME); + if (!url.isEmpty()) { + try { + URL siteURL = new URL(url); + HttpURLConnection connection = (HttpURLConnection) siteURL.openConnection(); + connection.setRequestMethod("GET"); + connection.connect(); + + int code = connection.getResponseCode(); + if (code == 200) { + available = true; + } + else { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebConnectionError, url); + available = false; + logger.warn(EELFLoggerDelegate.errorLogger, "Warning! UEB topic existence check failed, topic = " + url ); + logger.debug(EELFLoggerDelegate.debugLogger, "Warning! UEB topic existence check failed, topic = " + url ); + } + } + catch (Exception e) { + available = false; + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the UEB Healthcheck. Details: " + stackTrace); + } + } + } + return available; + } + + public boolean MessageCanBeSentToTopic() { + + boolean sentMsgSuccessfully = false; + + UebMsg msg = new UebMsg(); + msg.putSourceTopicName(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME)); + msg.putPayload("Pinging topic for health check"); + msg.putMsgType(EPUebMsgTypes.UEB_MSG_TYPE_HEALTH_CHECK); + + try { + // epPublisher.send(msg); + sentMsgSuccessfully = true; + } + catch (Exception e) { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeHealthCheckUebClusterError); + String stackTrace = EcompPortalUtils.getStackTrace(e); + sentMsgSuccessfully = false; + logger.warn(EELFLoggerDelegate.errorLogger, "Warning! could not successfully publish a UEB msg to " + + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME) + " exception : " + stackTrace); + } + + return sentMsgSuccessfully; + } + +} + + diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java new file mode 100644 index 00000000..d6eb9eb9 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java @@ -0,0 +1,27 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.ueb; + +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsgTypes; + +public interface EPUebMsgTypes extends UebMsgTypes { + + public static final String UEB_MSG_TYPE_HEALTH_CHECK = "uebHealthCheckPing"; +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/utils/EPSystemProperties.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/utils/EPSystemProperties.java new file mode 100644 index 00000000..b187c010 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/utils/EPSystemProperties.java @@ -0,0 +1,42 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.utils; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.context.annotation.PropertySources; + +@Configuration +@PropertySources({ + @PropertySource ("/WEB-INF/conf/system.properties"), + @PropertySource ("/WEB-INF/conf/sql.properties"), + @PropertySource ("/WEB-INF/fusion/conf/fusion.properties"), + @PropertySource (value = "file:${catalina.home}/conf/system.properties", ignoreResourceNotFound = true), + @PropertySource (value = "file:${catalina.home}/conf/fusion.properties", ignoreResourceNotFound = true) + }) + +/** + * Contains properties specific to the ONAP version of the ECOMP Portal. + */ +public class EPSystemProperties extends EPCommonSystemProperties { + public static final String CONTACT_US_URL = "contact_us_link"; + public static final String ECOMP_CONTEXT_ROOT = "context_root"; + +}
\ No newline at end of file diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/LogJob.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/LogJob.java new file mode 100644 index 00000000..5b1aa159 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/LogJob.java @@ -0,0 +1,45 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.scheduler; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.quartz.DisallowConcurrentExecution; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.quartz.PersistJobDataAfterExecution; +import org.springframework.scheduling.quartz.QuartzJobBean; + +@PersistJobDataAfterExecution +@DisallowConcurrentExecution +public class LogJob extends QuartzJobBean { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LogJob.class); + + @Override + protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException { + // JobDataMap dataMap = ctx.getJobDetail().getJobDataMap(); + // int cnt = dataMap.getInt(""); + // JobKey jobKey = ctx.getJobDetail().getKey(); + logger.info(EELFLoggerDelegate.debugLogger, + (Runtime.getRuntime().maxMemory() + " " + Runtime.getRuntime().maxMemory())); + + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/LogRegistry.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/LogRegistry.java new file mode 100644 index 00000000..8d717110 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/LogRegistry.java @@ -0,0 +1,57 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.scheduler; + +import java.text.ParseException; +import java.util.HashMap; +import java.util.Map; + +import org.openecomp.portalsdk.core.scheduler.CronRegistry; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.context.annotation.DependsOn; +import org.springframework.scheduling.quartz.CronTriggerFactoryBean; +import org.springframework.scheduling.quartz.JobDetailFactoryBean; +import org.springframework.stereotype.Component; + +@Component +@DependsOn({ "systemProperties" }) +public class LogRegistry extends CronRegistry { + + private static final String groupName = "AppGroup"; + private static final String jobName = "LogJob"; + private static final String triggerName = "LogTrigger"; + + // @Autowired + // private SystemProperties systemProperties; + + // @Bean + public JobDetailFactoryBean jobDetailFactoryBean() { + Map<String, Object> map = new HashMap<String, Object>(); + map.put("units", "bytes"); + return jobDetailFactoryBean(groupName, jobName, LogJob.class, map); + } + + // @Bean + public CronTriggerFactoryBean cronTriggerFactoryBean() throws ParseException { + // "0 * * * * ? * + return cronTriggerFactoryBean(groupName, triggerName, SystemProperties.getProperty(SystemProperties.LOG_CRON)); + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/Register.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/Register.java new file mode 100644 index 00000000..43e0d818 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/Register.java @@ -0,0 +1,86 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.scheduler; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.scheduler.Registerable; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.quartz.Trigger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.DependsOn; +import org.springframework.stereotype.Component; + +@Component +@DependsOn({"logRegistry", "sessionMgtRegistry", "systemProperties"}) +public class Register implements Registerable { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(Register.class); + + private List<Trigger> scheduleTriggers = new ArrayList<Trigger>(); + Trigger trigger[] = new Trigger[0]; + + @Autowired + private LogRegistry logRegistry; + + @Autowired + private SessionMgtRegistry sessionMgtRegistry; + + @Override + public Trigger[] getTriggers() { + return getScheduleTriggers().toArray(trigger); + } + + @Override + public void registerTriggers() { + // if the property value is not available; the cron will not be added + // and can be ignored. its safe to ignore the exceptions + try { + if (SystemProperties.getProperty(SystemProperties.LOG_CRON) != null) + getScheduleTriggers().add(logRegistry.getTrigger()); + + } catch (IllegalStateException ies) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(ies)); + logger.info(EELFLoggerDelegate.debugLogger, ("Log Cron not available")); + } + + try { + if(SystemProperties.getProperty(SystemProperties.SESSIONTIMEOUT_FEED_CRON) != null) + getScheduleTriggers().add(sessionMgtRegistry.getTrigger()); + + } catch(IllegalStateException ies) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(ies)); + logger.info(EELFLoggerDelegate.debugLogger, ("Session Cron not available")); + } + + } + + public List<Trigger> getScheduleTriggers() { + return scheduleTriggers; + } + + public void setScheduleTriggers(List<Trigger> scheduleTriggers) { + this.scheduleTriggers = scheduleTriggers; + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java new file mode 100644 index 00000000..1d2d8071 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java @@ -0,0 +1,100 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.scheduler; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.openecomp.portalsdk.core.scheduler.Registerable; +import org.openecomp.portalsdk.workflow.services.WorkflowScheduleService; +import org.quartz.Trigger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; +import org.springframework.stereotype.Component; + +/** + * TODO REFACTOR moved from org.openecomp.portalsdk.core.scheduler to + * org.openecomp.portalapp.scheduler + * + */ +@Component +public class RegistryAdapter { + + @Autowired + private Registerable registry; + + @Autowired + private WorkflowScheduleService workflowScheduleService; + + private SchedulerFactoryBean schedulerBean; + + Trigger trigger[] = new Trigger[0]; + + public Trigger[] getTriggers() { + + registry.registerTriggers(); + + List<Trigger> allTriggers = new ArrayList<Trigger>(); + + List<Trigger> coreTriggers = addCoreTriggers(); + final Trigger[] extTriggerArray = registry.getTriggers(); + + allTriggers.addAll(Arrays.asList(extTriggerArray)); + allTriggers.addAll(coreTriggers); + + return allTriggers.toArray(trigger); + + } + + public List<Trigger> addCoreTriggers() { + // On startup of the application after crash recovery, invoke workflow + // schedule trigger + List<Trigger> triggers = getWorkflowScheduleService().triggerWorkflowScheduling(); + return triggers; + } + + public void setSchedulerBean(SchedulerFactoryBean _schedulerBean) { + schedulerBean = _schedulerBean; + + } + + public SchedulerFactoryBean getSchedulerBean() { + return schedulerBean; + + } + + public Registerable getRegistry() { + return registry; + } + + public void setRegistry(Registerable registry) { + this.registry = registry; + } + + public WorkflowScheduleService getWorkflowScheduleService() { + return workflowScheduleService; + } + + public void setWorkflowScheduleService(WorkflowScheduleService workflowScheduleService) { + this.workflowScheduleService = workflowScheduleService; + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/SessionMgtRegistry.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/SessionMgtRegistry.java new file mode 100644 index 00000000..315618e9 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/SessionMgtRegistry.java @@ -0,0 +1,89 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.scheduler; + +import java.text.ParseException; +import java.util.HashMap; +import java.util.Map; + +import org.openecomp.portalapp.portal.listener.UserSessionListener; +import org.openecomp.portalapp.service.sessionmgt.TimeoutHandler; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.scheduler.CronRegistry; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.annotation.DependsOn; +import org.springframework.scheduling.quartz.CronTriggerFactoryBean; +import org.springframework.scheduling.quartz.JobDetailFactoryBean; +import org.springframework.stereotype.Component; + +/** + * Extra depends-on annotation tells Spring that the system properties object + * will be used in the constructor. + */ +@Component +// @DependsOn({ "manageService", "epAppService", "systemProperties" }) +@DependsOn({ "systemProperties" }) +public class SessionMgtRegistry extends CronRegistry implements ApplicationContextAware { + + EELFLoggerDelegate logger = null; + + private static final String groupName = "AppGroup"; + private static final String jobName = "PortalSessionTimeoutFeedJob"; + private static final String triggerName = "PortalSessionTimeoutFeedTrigger"; + + // Not strictly necessary, but preparing for the day + // when the getProperty method is not static. + @Autowired + private SystemProperties systemProperties; + + private ApplicationContext applicationContext; + + public JobDetailFactoryBean jobDetailFactoryBean() { + logger = EELFLoggerDelegate.getLogger(SessionMgtRegistry.class); + Map<String, Object> map = new HashMap<String, Object>(); + return jobDetailFactoryBean(groupName, jobName, TimeoutHandler.class, map); + } + + @SuppressWarnings("static-access") + public CronTriggerFactoryBean cronTriggerFactoryBean() throws ParseException { + logger = EELFLoggerDelegate.getLogger(SessionMgtRegistry.class); + String property = "* * * * * ? 2099"; + try { + property = systemProperties.getProperty(SystemProperties.SESSIONTIMEOUT_FEED_CRON); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Failed to retrieve " + SystemProperties.SESSIONTIMEOUT_FEED_CRON + ", defaulting to " + property, + e); + } + return cronTriggerFactoryBean(groupName, triggerName, property); + } + + @Override + public void setApplicationContext(ApplicationContext _applicationContext) throws BeansException { + applicationContext = _applicationContext; + TimeoutHandler.setApplicationContext(applicationContext); + UserSessionListener.setApplicationContext(_applicationContext); + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/service/RemoteWebServiceCallServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/service/RemoteWebServiceCallServiceImpl.java new file mode 100644 index 00000000..c07d1093 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/service/RemoteWebServiceCallServiceImpl.java @@ -0,0 +1,104 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.service.AppsCacheService; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.service.WebServiceCallServiceImpl; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("remoteWebServiceCallService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +public class RemoteWebServiceCallServiceImpl extends WebServiceCallServiceImpl implements RemoteWebServiceCallService { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RemoteWebServiceCallServiceImpl.class); + @Autowired + AppsCacheService appCacheService; + + /* + * (non-Javadoc) + * @see org.openecomp.portalapp.service.sessionmgt.RemoteWebServiceCallService#verifyRESTCredential(java.lang.String, java.lang.String, java.lang.String, java.lang.String) + */ + public boolean verifyRESTCredential(String secretKey, String requestUebKey, String requestAppName, + String requestPassword) throws Exception { + EPApp appRecord = findEpApp(requestUebKey); + if (appRecord == null) { + logger.warn(EELFLoggerDelegate.errorLogger, "Failed to find application with UEB key " + requestUebKey); + return false; + } + + String encryptedPwdDB = appRecord.getAppPassword(); + String appUserName = appRecord.getUsername(); + String decryptedPwd = CipherUtil.decrypt(encryptedPwdDB, + secretKey == null ? SystemProperties.getProperty(SystemProperties.Decryption_Key) : secretKey); + if (decryptedPwd.equals(requestPassword) && appUserName.equals(requestAppName)) + return true; + else + return false; + } + + /** + * currently this method only validates the application key to fetch the application + */ + public boolean verifyAppKeyCredential(String requestUebKey) throws Exception { + String failMessage = "Failed to find application with UEB key " + requestUebKey; + if(requestUebKey == null || requestUebKey.equals("")) { + logger.warn(EELFLoggerDelegate.errorLogger, failMessage); + return false; + } + + EPApp appRecord = findEpApp(requestUebKey); + if (appRecord == null) { + logger.warn(EELFLoggerDelegate.errorLogger, failMessage); + return false; + } + + return true; + } + + /** + * Searches the FN_APP table for the specified UEB key. + * + * @return EPApp object if the key is found; else null. + */ + public EPApp findEpApp(String uebKey) { + List<?> list = null; + StringBuffer criteria = new StringBuffer(); + criteria.append(" where ueb_key = '" + uebKey + "'"); + list = getDataAccessService().getList(EPApp.class, criteria.toString(), null, null); + return (list == null || list.size() == 0) ? null : (EPApp) list.get(0); + } + + public static void main(String args[]) throws Exception { + String decryptedPwd = CipherUtil.decrypt("okYTaDrhzibcbGVq5mjkVQ==", "AGLDdG4D04BKm2IxIWEr8o=="); + System.out.print(decryptedPwd); + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/FunctionalMenuHandler.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/FunctionalMenuHandler.java new file mode 100644 index 00000000..0a360500 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/FunctionalMenuHandler.java @@ -0,0 +1,126 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.uebhandler; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.FunctionalMenuService; +import org.openecomp.portalapp.portal.service.SearchService; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.ueb.UebException; +import org.openecomp.portalsdk.core.onboarding.ueb.UebManager; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import com.google.gson.Gson; + +@Component +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class FunctionalMenuHandler { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuHandler.class); + + @Autowired + AdminRolesService adminRolesService; + + @Autowired + FunctionalMenuService functionalMenuService; + + @Autowired + SearchService searchSvc; + + @Autowired + DataAccessService dataAccessService; + + @Async + public Boolean getFunctionalMenu(UebMsg requestMsg) + { + UebMsg returnMsg = new UebMsg(); + + if (requestMsg == null) + { + logger.error(EELFLoggerDelegate.errorLogger, "handleMenuRequest received null message"); + return false; + } + else if (requestMsg.getSourceTopicName() == null) + { + logger.error(EELFLoggerDelegate.errorLogger, "A source topic name is required and not found in this msg:" + requestMsg.toString()); + return false; + } + else if (requestMsg.getUserId() == null) + { + logger.debug(EELFLoggerDelegate.debugLogger, "Error getting functional menu. A userId is required and not found in this msg: " + requestMsg.toString()); + returnMsg.putMsgId(requestMsg.getMsgId()); // echo tells requester this is a response + returnMsg.putPayload("Error: A userId is required. Call msg.putUserId() with an userId"); + } + else + { + logger.debug(EELFLoggerDelegate.debugLogger, "Getting functional menu for user = " + requestMsg.getUserId()); + EPUser user = searchSvc.searchUserByUserId(requestMsg.getUserId()); + + List<FunctionalMenuItem> menuItems = null; + if (user == null) + { + logger.debug(EELFLoggerDelegate.debugLogger, "Error getting functional menu. userId not found in directory or is guest: " + requestMsg.toString()); + } + else if (adminRolesService.isSuperAdmin(user)) + { + logger.debug(EELFLoggerDelegate.debugLogger, "FunctionalMenuHandler: SuperUser, about to call getFunctionalMenuItems()"); + menuItems = functionalMenuService.getFunctionalMenuItems(); + } + else + { + logger.debug(EELFLoggerDelegate.debugLogger, "getMenuItemsForAuthUser: about to call getFunctionalMenuItemsForUser()"); + menuItems = functionalMenuService.getFunctionalMenuItemsForUser(requestMsg.getUserId()); + } + + if ( menuItems != null ) + { + String functionalMenuJsonString = new Gson().toJson(menuItems); + logger.debug(EELFLoggerDelegate.debugLogger, "returning functional menu : " + functionalMenuJsonString); + returnMsg.putMsgId(requestMsg.getMsgId()); // echo tells requester this is a response + returnMsg.putPayload(functionalMenuJsonString); + } else { + returnMsg.putMsgId(requestMsg.getMsgId()); // echo tells requester this is a response + returnMsg.putPayload("Error: Not found for userId = " + requestMsg.getUserId()); + } + } + + try { + UebManager.getInstance().publishReplyEP(returnMsg, requestMsg.getSourceTopicName()); + } catch (UebException e) { + logger.error(EELFLoggerDelegate.errorLogger, "UebException occurred while responding to the Ueb message, Details:" + EcompPortalUtils.getStackTrace(e)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while responding to the Ueb message, Details:" + EcompPortalUtils.getStackTrace(e)); + } + + return true; + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/InitUebHandler.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/InitUebHandler.java new file mode 100644 index 00000000..2ba27549 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/InitUebHandler.java @@ -0,0 +1,75 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.uebhandler; + +import java.util.concurrent.ConcurrentLinkedQueue; + +import javax.annotation.PostConstruct; + +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; +import org.openecomp.portalsdk.core.onboarding.ueb.UebManager; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; + +// +// Adding this class for the sole purpose of insuring that the MainUebHandler really +// honors @Async and kicks off a thread. For more info google @Async and read about +// @Async only working if called from different class. +// +//@Configuration +//@EnableAspectJAutoProxy +//@EPMetricsLog +public class InitUebHandler { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(InitUebHandler.class); + + //@Autowired + MainUebHandler mainUebHandler; + + public InitUebHandler() { + + } + + //@PostConstruct + public void initUeb() { + + try { + String enableListenerThread = PortalApiProperties.getProperty(PortalApiConstants.UEB_LISTENERS_ENABLE); + if (enableListenerThread.equalsIgnoreCase("true")) { + ConcurrentLinkedQueue<UebMsg> inboxQueue = new ConcurrentLinkedQueue<UebMsg>(); + UebManager.getInstance().initListener(inboxQueue); + mainUebHandler.runHandler(inboxQueue); + logger.info(EELFLoggerDelegate.errorLogger, "Returned from initiating mainUebHandler..."); + } + else { + logger.info(EELFLoggerDelegate.errorLogger, "Not starting UEB listening thread because ueb_listeners_enable is not set to true in the properties file."); + } + } + catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + logger.info(EELFLoggerDelegate.errorLogger, "Not starting UEB listening thread because property could not be read " + PortalApiConstants.UEB_LISTENERS_ENABLE + e.getMessage()); + } + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/MainUebHandler.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/MainUebHandler.java new file mode 100644 index 00000000..5edf04b4 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/MainUebHandler.java @@ -0,0 +1,115 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.uebhandler; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.concurrent.ConcurrentLinkedQueue; + +import org.openecomp.portalapp.portal.ueb.EPUebMsgTypes; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsgTypes; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import com.att.eelf.configuration.Configuration; + + +//------------------------------------------------------------------------- +// Listens for received UEB messages and handles the messages +// +// Note: To implement a synchronous reply call getMsgId on the request +// and putMsgId on the reply (echoing the request MsgId). +// +//------------------------------------------------------------------------- +@Component("MainUebHandler") +public class MainUebHandler +{ + final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MainUebHandler.class); + + ConcurrentLinkedQueue<UebMsg> inboxQueue = null; + + @Autowired + FunctionalMenuHandler funcMenuHandler; + + @Autowired + WidgetNotificationHandler widgetNotificationHandler; + + @Async + public void runHandler(ConcurrentLinkedQueue<UebMsg> queue) + { + inboxQueue = queue; + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "==> MainUebHandler started"); + while (true) + { + UebMsg msg = null; + while ((msg = inboxQueue.poll()) != null) + { + if ((msg.getMsgType() != null) && (!msg.getMsgType().equalsIgnoreCase(EPUebMsgTypes.UEB_MSG_TYPE_HEALTH_CHECK))) + { + // TODO: switch this back to debug + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== Received UEB message : " + msg.toString()); + logger.info(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== Received UEB message : " + msg.toString()); + MDC.put(EPSystemProperties.PARTNER_NAME, msg.getSourceTopicName()); + MDC.put(Configuration.MDC_SERVICE_NAME, msg.getMsgType().toString()); + switch(msg.getMsgType()) + { + case UebMsgTypes.UEB_MSG_TYPE_GET_FUNC_MENU: + { + funcMenuHandler.getFunctionalMenu(msg); + break; + } + case UebMsgTypes.UEB_MSG_TYPE_WIDGET_NOTIFICATION: + { + widgetNotificationHandler.handleWidgetNotification(msg); + break; + } + default: + { + logger.info(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "Unknown UEB message type " + msg.toString()); + break; + } + } + } + } + + if (Thread.interrupted()) + { + logger.info(EELFLoggerDelegate.errorLogger, "==> UebMainHandler exiting"); + break; + } + + try { + Thread.sleep(10); + } catch (InterruptedException e) { + logger.error(EELFLoggerDelegate.errorLogger, "UebMainHandler interrupted during sleep" + EcompPortalUtils.getStackTrace(e)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred during sleep" + EcompPortalUtils.getStackTrace(e)); + } + } + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/WidgetNotificationHandler.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/WidgetNotificationHandler.java new file mode 100644 index 00000000..e6f3089c --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/WidgetNotificationHandler.java @@ -0,0 +1,93 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.uebhandler; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.service.EPAppService; +import org.openecomp.portalapp.portal.service.SearchService; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.ueb.UebException; +import org.openecomp.portalsdk.core.onboarding.ueb.UebManager; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +@Component +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class WidgetNotificationHandler { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetNotificationHandler.class); + + final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + @Autowired + EPAppService appSvc; + + @Autowired + SearchService searchSvc; + + + public WidgetNotificationHandler() + { + } + + @Async + public void handleWidgetNotification(UebMsg requestMsg) + { + if (requestMsg.getUserId() != null) { + logger.debug(EELFLoggerDelegate.debugLogger, "handleWidgetNotification: getting widgets/apps for user = " + requestMsg.getUserId()); + EPUser user = searchSvc.searchUserByUserId(requestMsg.getUserId()); + if (user != null && (appSvc != null)) { + logger.debug(EELFLoggerDelegate.debugLogger, "Debug mytag: " + appSvc); + List<EPApp> apps = appSvc.getUserApps(user); + for (EPApp app : apps) { + if (app.getUebTopicName() != null) { + UebMsg widgetMsg = new UebMsg(); + widgetMsg.putSourceTopicName(app.getUebTopicName()); + logger.debug(EELFLoggerDelegate.debugLogger, "app.getUebTopicName was invoked"); + widgetMsg.putPayload(requestMsg.getPayload()); + try { + logger.debug(EELFLoggerDelegate.debugLogger, "Sending widget notification from " + requestMsg.getSourceTopicName() + " to " + app.getUebTopicName()); + UebManager.getInstance().publishEP(widgetMsg, app.getUebTopicName()); + } catch (UebException e) { + logger.error(EELFLoggerDelegate.errorLogger, "handleWidgetNotification publishEP exception" + EcompPortalUtils.getStackTrace(e)); + } + } + } + } else { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "handleWidgetNotification: user " + + requestMsg.getUserId() + " not found" + " source = " + requestMsg.getSourceTopicName() + + ". This widget notification cannot be posted to other widgets"); + } + } + } + +} |