Merge "Sonar Issues for ExtractJar.java"
[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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
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 UEB_APP_KEY = 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(remotecentralizedsystemaccess.equalsIgnoreCase("true")){
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.size() > 0){
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<EPUserApp>();
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.size() > 0){
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                                                                 //for each role and user in that role, check if user exists in fn_user_role. If not, add 
220                                                                 /*userRolesList = userRolesService.getUserRolesList(centralizedAppList.get(0).getId(), user.getId(), Long.valueOf(externalRoleDescription.getId()));
221                                                                 if(userRolesList == null || userRolesList.isEmpty()){                                                           
222                                                                         // add userRole to fn_user_role(needs to be revisited after getting user info from AAF PORTAL-172)
223                                                                 }*/
224                                                         }
225                                                 }
226                                                 
227                                         }
228                                 }
229                         }                       
230                 }
231         }
232                         
233         public DataAccessService dataAccessService() {
234                 return super.dataAccessService();
235         }
236
237         public String[] tileDefinitions() {
238                 return super.tileDefinitions();
239         }
240
241         public List<String> addTileDefinitions() {
242                 List<String> definitions = new ArrayList<String>();
243                 definitions.add("/WEB-INF/defs/definitions.xml");
244                 return definitions;
245         }
246
247         @Bean
248         public AbstractCacheManager cacheManager() {
249                 return new CacheManager();
250         }
251
252         @Bean
253         public SessionTimeoutInterceptor sessionTimeoutInterceptor() {
254                 return new SessionTimeoutInterceptor();
255         }
256
257         @Bean
258         public PortalResourceInterceptor portalResourceInterceptor() {
259                 return new PortalResourceInterceptor();
260         }
261
262         @Bean
263         public EPLoginService eploginService() {
264                 return new EPLoginServiceImpl();
265         }
266
267         @Bean
268         public org.onap.portalsdk.core.auth.LoginStrategy coreLoginStrategy() {
269                 if (SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC"))
270                         return new OpenIdConnectLoginStrategy();
271                 else
272                         return new SimpleLoginStrategy();
273         }
274
275         @Bean
276         public LoginStrategy loginStrategy() {
277
278                 if (SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC"))
279                         return new OpenIdConnectLoginStrategy();
280                 else
281                         return new SimpleLoginStrategy();
282         }
283
284         public FnMenuService fnMenuService() {
285                 return new FnMenuServiceImpl();
286         }
287
288         @Override
289         public void addInterceptors(InterceptorRegistry registry) {
290                 // registry.addInterceptor(new
291                 // StaticResourcesInterceptor()).addPathPatterns("/index.htm",
292                 // "/applicationsHome", "/widgetsHome", "/admins", "/users",
293                 // "/applications", "/widgets");
294                 // Excludes login/logout pages and REST endpoints used by other
295                 // application servers.
296
297                 registry.addInterceptor(sessionTimeoutInterceptor()).excludePathPatterns("/oid-login", "/portalApi/healthCheck",
298                                 "/portalApi/healthCheck/", "/portalApi/healthCheckSuspend", "/portalApi/healthCheckSuspend/",
299                                 "/portalApi/healthCheckResume", "/portalApi/healthCheckResume/", "/login_external",
300                                 "/login_external.htm*", "login", "/login.htm*", "/auxapi/*", "/context/*", "/api*",
301                                 "/single_signon.htm", "/single_signon", "/dashboard", "/OpenSourceLogin.htm");
302
303                 registry.addInterceptor(portalResourceInterceptor());
304
305         }
306
307         /**
308          * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
309          * populates it with triggers.
310          *
311          * @return New instance of {@link SchedulerFactoryBean}
312          */
313
314         @Bean
315         public EPUebHelper epUebHelper() {
316                 return new EPUebHelper();
317         }
318
319         @Bean
320         public HealthMonitor healthMonitor() {
321                 return new HealthMonitor();
322         }
323
324         /**
325          * Creates and returns a new instance of a {@link MainUebHandler}.
326          * 
327          * @return New instance of {@link MainUebHandler}.
328          */
329         @Bean
330         public MainUebHandler mainUebHandler() {
331                 return new MainUebHandler();
332         }
333
334         /**
335          * Creates and returns a new instance of a {@link InitUebHandler}.
336          * 
337          * @return New instance of {@link InitUebHandler}.
338          */
339         @Bean
340         public InitUebHandler initUebHandler() {
341                 return new InitUebHandler();
342         }
343
344         /**
345          * Creates and returns a new instance of a {@link WidgetNotificationHandler}
346          * .
347          * 
348          * @return New instance of {@link WidgetNotificationHandler}.
349          */
350         @Bean
351         public WidgetNotificationHandler widgetNotificationHandler() {
352                 return new WidgetNotificationHandler();
353         }
354
355         /**
356          * Creates and returns a new instance of a {@link FunctionalMenuHandler} .
357          * 
358          * @return New instance of {@link FunctionalMenuHandler}.
359          */
360         @Bean
361         public FunctionalMenuHandler functionalMenuHandler() {
362                 return new FunctionalMenuHandler();
363         }
364
365         /**
366          * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
367          * populates it with triggers.
368          *
369          * @return New instance of {@link SchedulerFactoryBean}
370          * @throws Exception if dataSource fails
371          */
372         // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION
373         @Bean // ANNOTATION COMMENTED OUT
374         public SchedulerFactoryBean schedulerFactoryBean() throws Exception {
375                 SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
376                 scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties"));
377                 scheduler.setDataSource(dataSource());
378                 scheduler.setTriggers(schedulerRegistryAdapter.getTriggers());
379                 scheduler.setSchedulerName(getScheduleName());
380                 return scheduler;
381         }
382
383         protected String getScheduleName() {
384                 final String CRON_SITE_NAME = "cron_site_name";
385                 String cronSiteVal = "Default";
386                 try {
387                         cronSiteVal = SystemProperties.getProperty(CRON_SITE_NAME);
388                 } catch (Exception e) {
389                         logger.error(EELFLoggerDelegate.errorLogger, "getScheduleName failed", e);
390                         logger.warn(EELFLoggerDelegate.errorLogger,
391                                         "Cron site name not added in property file, using Default value");
392                 }
393
394                 String cronSiteName = cronSiteVal != null ? cronSiteVal : "";
395
396                 SimpleDateFormat dateFormat = new SimpleDateFormat();
397                 dateFormat.applyPattern("YYYYMMdd");
398                 String currentDateStr = dateFormat.format(Calendar.getInstance().getTime());
399
400                 return "Scheduler" + "_" + currentDateStr + "_" + cronSiteName;
401         }
402
403         /**
404          * Sets the scheduler registry adapter.
405          *
406          * @param schedulerRegistryAdapter
407          *            Scheduler registry adapter
408          */
409         @Autowired
410         public void setSchedulerRegistryAdapter(final RegistryAdapter schedulerRegistryAdapter) {
411                 this.schedulerRegistryAdapter = schedulerRegistryAdapter;
412         }
413
414 }