Replace ecomp references
[portal.git] / ecomp-portal-BE-os / src / main / java / org / onap / portalapp / conf / ExternalAppConfig.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalapp.conf;
39
40 import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY;
41 import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID;
42 import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
43 import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
44 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
45 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
46
47 import java.net.InetAddress;
48 import java.text.SimpleDateFormat;
49 import java.util.ArrayList;
50 import java.util.Calendar;
51 import java.util.HashMap;
52 import java.util.List;
53 import java.util.Map;
54
55 import javax.annotation.PostConstruct;
56
57 import org.json.JSONArray;
58 import org.json.JSONObject;
59 import org.onap.portalapp.authentication.LoginStrategy;
60 import org.onap.portalapp.authentication.OpenIdConnectLoginStrategy;
61 import org.onap.portalapp.authentication.SimpleLoginStrategy;
62 import org.onap.portalapp.controller.core.LogoutController;
63 import org.onap.portalapp.controller.core.SDKLoginController;
64 import org.onap.portalapp.music.conf.MusicSessionConfig;
65 import org.onap.portalapp.portal.domain.EPApp;
66 import org.onap.portalapp.portal.domain.EPUser;
67 import org.onap.portalapp.portal.domain.EPUserApp;
68 import org.onap.portalapp.portal.interceptor.PortalResourceInterceptor;
69 import org.onap.portalapp.portal.interceptor.SessionTimeoutInterceptor;
70 import org.onap.portalapp.portal.listener.HealthMonitor;
71 import org.onap.portalapp.portal.service.EPLoginService;
72 import org.onap.portalapp.portal.service.EPLoginServiceImpl;
73 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
74 import org.onap.portalapp.portal.service.UserRolesService;
75 import org.onap.portalapp.portal.transport.ExternalAuthUserRole;
76 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
77 import org.onap.portalapp.portal.ueb.EPUebHelper;
78 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
79 import org.onap.portalapp.portal.utils.EPSystemProperties;
80 import org.onap.portalapp.scheduler.RegistryAdapter;
81 import org.onap.portalapp.uebhandler.FunctionalMenuHandler;
82 import org.onap.portalapp.uebhandler.InitUebHandler;
83 import org.onap.portalapp.uebhandler.MainUebHandler;
84 import org.onap.portalapp.uebhandler.WidgetNotificationHandler;
85 import org.onap.portalsdk.core.conf.AppConfig;
86 import org.onap.portalsdk.core.conf.Configurable;
87 import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
88 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
89 import org.onap.portalsdk.core.objectcache.AbstractCacheManager;
90 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
91 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
92 import org.onap.portalsdk.core.service.DataAccessService;
93 import org.onap.portalsdk.core.service.FnMenuService;
94 import org.onap.portalsdk.core.service.FnMenuServiceImpl;
95 import org.onap.portalsdk.core.util.CacheManager;
96 import org.onap.portalsdk.core.util.SystemProperties;
97 import org.slf4j.MDC;
98 import org.springframework.beans.factory.annotation.Autowired;
99 import org.springframework.context.annotation.Bean;
100 import org.springframework.context.annotation.ComponentScan;
101 import org.springframework.context.annotation.ComponentScan.Filter;
102 import org.springframework.context.annotation.Configuration;
103 import org.springframework.context.annotation.FilterType;
104 import org.springframework.context.annotation.Import;
105 import org.springframework.context.annotation.Profile;
106 import org.springframework.scheduling.annotation.EnableAsync;
107 import org.springframework.scheduling.annotation.EnableScheduling;
108 import org.springframework.scheduling.quartz.SchedulerFactoryBean;
109 import org.springframework.web.servlet.ViewResolver;
110 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
111 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
112 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
113
114 import com.fasterxml.jackson.databind.ObjectMapper;
115 import com.google.gson.Gson;
116
117 @Configuration
118 @EnableWebMvc
119 @ComponentScan(basePackages = {"org.onap"}, excludeFilters = {
120                 @Filter(value = { LogoutController.class, SDKLoginController.class}, type = FilterType.ASSIGNABLE_TYPE) })
121 @Profile("src")
122 @EnableAsync
123 @EnableScheduling
124 @Import({ MusicSessionConfig.class })
125 public class ExternalAppConfig extends AppConfig implements Configurable {
126
127         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppConfig.class);
128
129         @Autowired
130         private DataAccessService dataAccessService;
131
132         @Autowired
133         private UserRolesService userRolesService;
134
135         @Autowired
136         private ExternalAccessRolesService externalAccessRolesService;
137
138         private RegistryAdapter schedulerRegistryAdapter;
139
140         String uebAppKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); 
141
142         public ViewResolver viewResolver() {
143                 return super.viewResolver();
144         }
145
146         @Override
147         public void addResourceHandlers(ResourceHandlerRegistry registry) {
148                 registry.addResourceHandler("/app/fusion/**").addResourceLocations("/app/fusion/");
149                 registry.addResourceHandler("/static/**").addResourceLocations("/static/");
150                 registry.addResourceHandler("/images/**").addResourceLocations("/images/");
151                 registry.addResourceHandler("/**").addResourceLocations("/public/");
152         }
153
154         @PostConstruct
155         private void init() {
156                 String remotecentralizedsystemaccess = SystemProperties.getProperty(EPCommonSystemProperties.REMOTE_CENTRALIZED_SYSTEM_ACCESS);
157                 try {
158                         // Loading defaults
159                         MDC.put(MDC_SERVICE_NAME, EPSystemProperties.ECOMP_PORTAL_BE);
160                         MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
161                         MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
162                         MDC.put(MDC_SERVICE_INSTANCE_ID, "");
163                         MDC.put(MDC_ALERT_SEVERITY, AlarmSeverityEnum.INFORMATIONAL.severity());
164                         MDC.put(MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID));
165                         if("true".equalsIgnoreCase(remotecentralizedsystemaccess)){
166                                 importFromExternalAuth();
167                         }                       
168                 } catch (Exception e) {
169                         logger.error(EELFLoggerDelegate.errorLogger, "init failed", e);
170                 }
171         }
172
173         /**
174          * Does a sync on functions, roles and role functions based on namespace 
175          * for all the centralized applications between AAF and ONAP, updates
176          * fn_user and fn_user_role with user information from AAF.
177          * 
178          */
179         private void importFromExternalAuth() throws Exception {
180                 JSONArray aafAppRoles = new JSONArray();
181                 JSONArray aafUserList = new JSONArray();
182                 List<EPApp> appList;
183                 //to get all centralized apps           
184                 List<EPApp> centralizedAppList = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);         
185                 if(centralizedAppList != null && !centralizedAppList.isEmpty()){
186                         for(int i = 0; i < centralizedAppList.size(); i++){
187                                 //syncRoles(does a sync on functions, roles and role functions)
188                                 externalAccessRolesService.syncApplicationRolesWithEcompDB(centralizedAppList.get(i));
189                                 //retrieve roles based on NS
190                                 aafAppRoles = externalAccessRolesService.getAppRolesJSONFromExtAuthSystem(centralizedAppList.get(i));
191                                 if(aafAppRoles != null && aafAppRoles.length() > 0){
192                                         for(int j = 0; j < aafAppRoles.length(); j++){
193                                                 ObjectMapper mapper = new ObjectMapper();
194                                                 String name = aafAppRoles.getJSONObject(j).getString("name");
195                                                 String desc = aafAppRoles.getJSONObject(j).getString("description");
196                                                 ExternalRoleDescription externalRoleDescription = mapper.readValue(desc, ExternalRoleDescription.class);
197                                                 aafUserList = externalAccessRolesService.getAllUsersByRole(name);       
198                                                 if(aafUserList != null && aafUserList.length() > 0){
199                                                         for(int k = 0; k < aafUserList.length(); k++){
200                                                                 EPUser user = null;
201                                                                 List<EPUser> usersList = null;                                                          
202                                                                 List<EPUserApp> userRolesList = new ArrayList<>();
203                                                                 JSONObject userRole = (JSONObject) aafUserList.get(k);
204                                                                 Gson gson = new Gson();
205                                                                 ExternalAuthUserRole userRoleObj = gson.fromJson(userRole.toString(), ExternalAuthUserRole.class);
206                                                                 if(userRoleObj.getUser() != null){
207                                                                         userRoleObj.setUser(userRoleObj.getUser().substring(0, userRoleObj.getUser().indexOf("@")));
208                                                                 }                                                       
209                                                                 //for each role and user in that role, check if user exists in fn_user. If not, add 
210                                                                 Map<String, String> orgUserId = new HashMap<>();
211                                                                 orgUserId.put("orgUserIdValue", userRoleObj.getUser());
212                                                                 usersList = dataAccessService.executeNamedQuery("epUserAppId", orgUserId, null);
213                                                                 if(usersList != null && !usersList.isEmpty()){
214                                                                         user = usersList.get(0);
215                                                                 }                                                       
216                                                                 if(user == null){
217                                                                         // add user to fn_user(needs to be revisited after getting user info from AAF PORTAL-172)                                                               
218                                                                 }
219                                                         }
220                                                 }
221
222                                         }
223                                 }
224                         }                       
225                 }
226         }
227
228         public DataAccessService dataAccessService() {
229                 return super.dataAccessService();
230         }
231
232         @Override
233         public String[] tileDefinitions() {
234                 return super.tileDefinitions();
235         }
236
237         public List<String> addTileDefinitions() {
238                 List<String> definitions = new ArrayList<>();
239                 definitions.add("/WEB-INF/defs/definitions.xml");
240                 return definitions;
241         }
242
243         @Bean
244         public AbstractCacheManager cacheManager() {
245                 return new CacheManager();
246         }
247
248         @Bean
249         public SessionTimeoutInterceptor sessionTimeoutInterceptor() {
250                 return new SessionTimeoutInterceptor();
251         }
252
253         @Bean
254         public PortalResourceInterceptor portalResourceInterceptor() {
255                 return new PortalResourceInterceptor();
256         }
257
258         @Bean
259         public EPLoginService eploginService() {
260                 return new EPLoginServiceImpl();
261         }
262
263         @Bean
264         public org.onap.portalsdk.core.auth.LoginStrategy coreLoginStrategy() {
265                 if ("OIDC".equalsIgnoreCase(SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim()))
266                         return new OpenIdConnectLoginStrategy();
267                 else
268                         return new SimpleLoginStrategy();
269         }
270
271         @Bean
272         public LoginStrategy loginStrategy() {
273
274                 if ("OIDC".equalsIgnoreCase(SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim()))
275                         return new OpenIdConnectLoginStrategy();
276                 else
277                         return new SimpleLoginStrategy();
278         }
279
280         public FnMenuService fnMenuService() {
281                 return new FnMenuServiceImpl();
282         }
283
284         @Override
285         public void addInterceptors(InterceptorRegistry registry) {
286                 registry.addInterceptor(sessionTimeoutInterceptor()).excludePathPatterns("/oid-login", "/portalApi/healthCheck",
287                                 "/portalApi/healthCheck/", "/portalApi/healthCheckSuspend", "/portalApi/healthCheckSuspend/",
288                                 "/portalApi/healthCheckResume", "/portalApi/healthCheckResume/", "/login_external",
289                                 "/login_external.htm*", "login", "/login.htm*", "/auxapi/*", "/context/*", "/api*",
290                                 "/single_signon.htm", "/single_signon", "/dashboard", "/OpenSourceLogin.htm");
291
292                 registry.addInterceptor(portalResourceInterceptor());
293
294         }
295
296         /**
297          * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
298          * populates it with triggers.
299          *
300          * @return New instance of {@link SchedulerFactoryBean}
301          */
302
303         @Bean
304         public EPUebHelper epUebHelper() {
305                 return new EPUebHelper();
306         }
307
308         @Bean
309         public HealthMonitor healthMonitor() {
310                 return new HealthMonitor();
311         }
312
313         /**
314          * Creates and returns a new instance of a {@link MainUebHandler}.
315          * 
316          * @return New instance of {@link MainUebHandler}.
317          */
318         @Bean
319         public MainUebHandler mainUebHandler() {
320                 return new MainUebHandler();
321         }
322
323         /**
324          * Creates and returns a new instance of a {@link InitUebHandler}.
325          * 
326          * @return New instance of {@link InitUebHandler}.
327          */
328         @Bean
329         public InitUebHandler initUebHandler() {
330                 return new InitUebHandler();
331         }
332
333         /**
334          * Creates and returns a new instance of a {@link WidgetNotificationHandler}
335          * .
336          * 
337          * @return New instance of {@link WidgetNotificationHandler}.
338          */
339         @Bean
340         public WidgetNotificationHandler widgetNotificationHandler() {
341                 return new WidgetNotificationHandler();
342         }
343
344         /**
345          * Creates and returns a new instance of a {@link FunctionalMenuHandler} .
346          * 
347          * @return New instance of {@link FunctionalMenuHandler}.
348          */
349         @Bean
350         public FunctionalMenuHandler functionalMenuHandler() {
351                 return new FunctionalMenuHandler();
352         }
353
354         /**
355          * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
356          * populates it with triggers.
357          *
358          * @return New instance of {@link SchedulerFactoryBean}
359          * @throws Exception if dataSource fails
360          */
361         // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION
362         @Bean // ANNOTATION COMMENTED OUT
363         public SchedulerFactoryBean schedulerFactoryBean() throws Exception {
364                 SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
365                 scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties"));
366                 scheduler.setDataSource(dataSource());
367                 scheduler.setTriggers(schedulerRegistryAdapter.getTriggers());
368                 scheduler.setSchedulerName(getScheduleName());
369                 return scheduler;
370         }
371
372         protected String getScheduleName() {
373                 final String CRON_SITE_NAME = "cron_site_name";
374                 String cronSiteVal = "Default";
375                 try {
376                         cronSiteVal = SystemProperties.getProperty(CRON_SITE_NAME);
377                 } catch (Exception e) {
378                         logger.error(EELFLoggerDelegate.errorLogger, "getScheduleName failed", e);
379                         logger.warn(EELFLoggerDelegate.errorLogger,
380                                         "Cron site name not added in property file, using Default value");
381                 }
382
383                 String cronSiteName = cronSiteVal != null ? cronSiteVal : "";
384
385                 SimpleDateFormat dateFormat = new SimpleDateFormat();
386                 dateFormat.applyPattern("YYYYMMdd");
387                 String currentDateStr = dateFormat.format(Calendar.getInstance().getTime());
388
389                 return "Scheduler" + "_" + currentDateStr + "_" + cronSiteName;
390         }
391
392         /**
393          * Sets the scheduler registry adapter.
394          *
395          * @param schedulerRegistryAdapter
396          *            Scheduler registry adapter
397          */
398         @Autowired
399         public void setSchedulerRegistryAdapter(final RegistryAdapter schedulerRegistryAdapter) {
400                 this.schedulerRegistryAdapter = schedulerRegistryAdapter;
401         }
402
403 }