HealthCheck & Namespace Check
[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  * Modifications Copyright © 2018 IBM.
8  * ===================================================================
9  *
10  * Unless otherwise specified, all software contained herein is licensed
11  * under the Apache License, Version 2.0 (the "License");
12  * you may not use this software except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * Unless otherwise specified, all documentation contained herein is licensed
24  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25  * you may not use this documentation except in compliance with the License.
26  * You may obtain a copy of the License at
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
30  * Unless required by applicable law or agreed to in writing, documentation
31  * distributed under the License is distributed on an "AS IS" BASIS,
32  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33  * See the License for the specific language governing permissions and
34  * limitations under the License.
35  *
36  * ============LICENSE_END============================================
37  *
38  * 
39  */
40 package org.onap.portalapp.conf;
41
42 import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY;
43 import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID;
44 import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
45 import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
46 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
47 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
48
49 import java.net.InetAddress;
50 import java.text.SimpleDateFormat;
51 import java.util.ArrayList;
52 import java.util.Calendar;
53 import java.util.HashMap;
54 import java.util.List;
55 import java.util.Map;
56
57 import javax.annotation.PostConstruct;
58
59 import org.json.JSONArray;
60 import org.json.JSONObject;
61 import org.onap.portalapp.authentication.LoginStrategy;
62 import org.onap.portalapp.authentication.OpenIdConnectLoginStrategy;
63 import org.onap.portalapp.authentication.SimpleLoginStrategy;
64 import org.onap.portalapp.controller.core.LogoutController;
65 import org.onap.portalapp.controller.core.SDKLoginController;
66 import org.onap.portalapp.music.conf.MusicSessionConfig;
67 import org.onap.portalapp.portal.domain.EPApp;
68 import org.onap.portalapp.portal.domain.EPUser;
69 import org.onap.portalapp.portal.domain.EPUserApp;
70 import org.onap.portalapp.portal.interceptor.PortalResourceInterceptor;
71 import org.onap.portalapp.portal.interceptor.SessionTimeoutInterceptor;
72 import org.onap.portalapp.portal.listener.HealthMonitor;
73 import org.onap.portalapp.portal.service.EPLoginService;
74 import org.onap.portalapp.portal.service.EPLoginServiceImpl;
75 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
76 import org.onap.portalapp.portal.service.UserRolesService;
77 import org.onap.portalapp.portal.transport.ExternalAuthUserRole;
78 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
79 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
80 import org.onap.portalapp.portal.utils.EPSystemProperties;
81 import org.onap.portalapp.scheduler.RegistryAdapter;
82 import org.onap.portalapp.uebhandler.FunctionalMenuHandler;
83 import org.onap.portalapp.uebhandler.InitUebHandler;
84 import org.onap.portalapp.uebhandler.MainUebHandler;
85 import org.onap.portalapp.uebhandler.WidgetNotificationHandler;
86 import org.onap.portalsdk.core.conf.AppConfig;
87 import org.onap.portalsdk.core.conf.Configurable;
88 import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
89 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
90 import org.onap.portalsdk.core.objectcache.AbstractCacheManager;
91 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
92 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
93 import org.onap.portalsdk.core.service.DataAccessService;
94 import org.onap.portalsdk.core.service.FnMenuService;
95 import org.onap.portalsdk.core.service.FnMenuServiceImpl;
96 import org.onap.portalsdk.core.util.CacheManager;
97 import org.onap.portalsdk.core.util.SystemProperties;
98 import org.slf4j.MDC;
99 import org.springframework.beans.factory.annotation.Autowired;
100 import org.springframework.context.annotation.Bean;
101 import org.springframework.context.annotation.ComponentScan;
102 import org.springframework.context.annotation.ComponentScan.Filter;
103 import org.springframework.context.annotation.Configuration;
104 import org.springframework.context.annotation.FilterType;
105 import org.springframework.context.annotation.Import;
106 import org.springframework.context.annotation.Profile;
107 import org.springframework.scheduling.annotation.EnableAsync;
108 import org.springframework.scheduling.annotation.EnableScheduling;
109 import org.springframework.scheduling.quartz.SchedulerFactoryBean;
110 import org.springframework.web.servlet.ViewResolver;
111 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
112 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
113 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
114
115 import com.fasterxml.jackson.databind.ObjectMapper;
116 import com.google.gson.Gson;
117
118 @Configuration
119 @EnableWebMvc
120 @ComponentScan(basePackages = {"org.onap"}, excludeFilters = {
121                 @Filter(value = { LogoutController.class, SDKLoginController.class}, type = FilterType.ASSIGNABLE_TYPE) })
122 @Profile("src")
123 @EnableAsync
124 @EnableScheduling
125 @Import({ MusicSessionConfig.class })
126 public class ExternalAppConfig extends AppConfig implements Configurable {
127
128         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppConfig.class);
129
130         @Autowired
131         private DataAccessService dataAccessService;
132
133         @Autowired
134         private UserRolesService userRolesService;
135
136         @Autowired
137         private ExternalAccessRolesService externalAccessRolesService;
138
139         private RegistryAdapter schedulerRegistryAdapter;
140
141         String uebAppKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); 
142
143         public ViewResolver viewResolver() {
144                 return super.viewResolver();
145         }
146
147         @Override
148         public void addResourceHandlers(ResourceHandlerRegistry registry) {
149                 registry.addResourceHandler("/app/fusion/**").addResourceLocations("/app/fusion/");
150                 registry.addResourceHandler("/static/**").addResourceLocations("/static/");
151                 registry.addResourceHandler("/images/**").addResourceLocations("/images/");
152                 registry.addResourceHandler("/**").addResourceLocations("/public/");
153         }
154
155         @PostConstruct
156         private void init() {
157                 String remotecentralizedsystemaccess = SystemProperties.getProperty(EPCommonSystemProperties.REMOTE_CENTRALIZED_SYSTEM_ACCESS);
158                 try {
159                         // Loading defaults
160                         MDC.put(MDC_SERVICE_NAME, EPSystemProperties.ECOMP_PORTAL_BE);
161                         MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
162                         MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
163                         MDC.put(MDC_SERVICE_INSTANCE_ID, "");
164                         MDC.put(MDC_ALERT_SEVERITY, AlarmSeverityEnum.INFORMATIONAL.severity());
165                         MDC.put(MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID));
166                         
167                                                 if("true".equalsIgnoreCase(remotecentralizedsystemaccess)){
168                                                         importFromExternalAuth();
169                                                 }                       
170                 } catch (Exception e) {
171                         logger.error(EELFLoggerDelegate.errorLogger, "init failed", e);
172                 }
173         }
174
175
176         private void importFromExternalAuth() throws Exception {
177                 JSONArray aafAppRoles = new JSONArray();
178                 JSONArray aafUserList = new JSONArray();
179                 List<EPApp> appList;
180                 //to get all centralized apps           
181                 List<EPApp> centralizedAppList = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);         
182                 if(centralizedAppList != null && !centralizedAppList.isEmpty()){
183                         for(int i = 0; i < centralizedAppList.size(); i++){
184                                 //syncRoles(does a sync on functions, roles and role functions)
185                                 externalAccessRolesService.syncApplicationRolesWithEcompDB(centralizedAppList.get(i));
186                                 //retrieve roles based on NS
187                                 aafAppRoles = externalAccessRolesService.getAppRolesJSONFromExtAuthSystem(centralizedAppList.get(i));
188                                 if(aafAppRoles != null && aafAppRoles.length() > 0){
189                                         for(int j = 0; j < aafAppRoles.length(); j++){
190                                                 ObjectMapper mapper = new ObjectMapper();
191                                                 String name = aafAppRoles.getJSONObject(j).getString("name");
192 //                                              String desc = aafAppRoles.getJSONObject(j).getString("description");
193 //                                              ExternalRoleDescription externalRoleDescription = mapper.readValue(desc, ExternalRoleDescription.class);
194                                                 aafUserList = externalAccessRolesService.getAllUsersByRole(name);       
195                                                 if(aafUserList != null && aafUserList.length() > 0){
196                                                         for(int k = 0; k < aafUserList.length(); k++){
197                                                                 EPUser user = null;
198                                                                 List<EPUser> usersList = null;                                                          
199                                                                 List<EPUserApp> userRolesList = new ArrayList<>();
200                                                                 JSONObject userRole = (JSONObject) aafUserList.get(k);
201                                                                 Gson gson = new Gson();
202                                                                 ExternalAuthUserRole userRoleObj = gson.fromJson(userRole.toString(), ExternalAuthUserRole.class);
203                                                                 if(userRoleObj.getUser() != null){
204                                                                         userRoleObj.setUser(userRoleObj.getUser().substring(0, userRoleObj.getUser().indexOf("@")));
205                                                                 }                                                       
206                                                                 //for each role and user in that role, check if user exists in fn_user. If not, add 
207                                                                 Map<String, String> orgUserId = new HashMap<>();
208                                                                 orgUserId.put("orgUserIdValue", userRoleObj.getUser());
209                                                                 usersList = dataAccessService.executeNamedQuery("epUserAppId", orgUserId, null);
210                                                                 if(usersList != null && !usersList.isEmpty()){
211                                                                         user = usersList.get(0);
212                                                                 }                                                       
213                                                                 if(user == null){
214                                                                         // add user to fn_user(needs to be revisited after getting user info from AAF PORTAL-172)                                                               
215                                                                 }
216                                                         }
217                                                 }
218
219                                         }
220                                 }
221                         }                       
222                 }
223         }
224
225         public DataAccessService dataAccessService() {
226                 return super.dataAccessService();
227         }
228
229         @Override
230         public String[] tileDefinitions() {
231                 return super.tileDefinitions();
232         }
233
234         public List<String> addTileDefinitions() {
235                 List<String> definitions = new ArrayList<>();
236                 definitions.add("/WEB-INF/defs/definitions.xml");
237                 return definitions;
238         }
239
240         @Bean
241         public AbstractCacheManager cacheManager() {
242                 return new CacheManager();
243         }
244
245         @Bean
246         public SessionTimeoutInterceptor sessionTimeoutInterceptor() {
247                 return new SessionTimeoutInterceptor();
248         }
249
250         @Bean
251         public PortalResourceInterceptor portalResourceInterceptor() {
252                 return new PortalResourceInterceptor();
253         }
254
255         @Bean
256         public EPLoginService eploginService() {
257                 return new EPLoginServiceImpl();
258         }
259
260         @Bean
261         public org.onap.portalsdk.core.auth.LoginStrategy coreLoginStrategy() {
262                 if ("OIDC".equalsIgnoreCase(SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim()))
263                         return new OpenIdConnectLoginStrategy();
264                 else
265                         return new SimpleLoginStrategy();
266         }
267
268         @Bean
269         public LoginStrategy loginStrategy() {
270
271                 if ("OIDC".equalsIgnoreCase(SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim()))
272                         return new OpenIdConnectLoginStrategy();
273                 else
274                         return new SimpleLoginStrategy();
275         }
276
277         public FnMenuService fnMenuService() {
278                 return new FnMenuServiceImpl();
279         }
280
281         @Override
282         public void addInterceptors(InterceptorRegistry registry) {
283                 registry.addInterceptor(sessionTimeoutInterceptor()).excludePathPatterns("/oid-login", "/portalApi/healthCheck",
284                                 "/portalApi/healthCheck/", "/portalApi/healthCheckSuspend", "/portalApi/healthCheckSuspend/",
285                                 "/portalApi/healthCheckResume", "/portalApi/healthCheckResume/", "/login_external",
286                                 "/login_external.htm*", "login", "/login.htm*", "/auxapi/**/*", "/context/*", "/api*",
287                                 "/single_signon.htm", "/single_signon", "/dashboard", "/OpenSourceLogin.htm");
288
289                 registry.addInterceptor(portalResourceInterceptor());
290
291         }
292
293         /**
294          * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
295          * populates it with triggers.
296          *
297          * @return New instance of {@link SchedulerFactoryBean}
298          */
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
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 }