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