fixes for supporting non-gui application access provisioning
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / service / sessionmgt / TimeoutHandler.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.service.sessionmgt;
39
40 import java.util.Hashtable;
41 import java.util.List;
42 import java.util.Map;
43
44 import javax.servlet.http.HttpSession;
45
46 import org.quartz.DisallowConcurrentExecution;
47 import org.quartz.JobExecutionContext;
48 import org.quartz.JobExecutionException;
49 import org.quartz.PersistJobDataAfterExecution;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.context.ApplicationContext;
52 import org.springframework.context.annotation.EnableAspectJAutoProxy;
53 import org.springframework.scheduling.quartz.QuartzJobBean;
54 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
55 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
56 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
57 import org.onap.portalapp.portal.service.AppsCacheService;
58 import org.onap.portalapp.portal.service.EPAppService;
59 import org.onap.portalapp.portal.transport.OnboardingApp;
60 import org.onap.portalsdk.core.domain.sessionmgt.TimeoutVO;
61 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
62 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
63
64 import com.fasterxml.jackson.core.JsonParseException;
65 import com.fasterxml.jackson.core.JsonProcessingException;
66 import com.fasterxml.jackson.core.type.TypeReference;
67 import com.fasterxml.jackson.databind.JsonMappingException;
68 import com.fasterxml.jackson.databind.ObjectMapper;
69
70 /**
71  * Executed periodically by Quartz to discover remote application sessions and
72  * update timeouts suitably.
73  */
74 @PersistJobDataAfterExecution
75 @DisallowConcurrentExecution
76 @org.springframework.context.annotation.Configuration
77 @EnableAspectJAutoProxy
78 @EPMetricsLog
79 public class TimeoutHandler extends QuartzJobBean {
80         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(TimeoutHandler.class);
81         
82         private ObjectMapper mapper = new ObjectMapper();
83
84         /**
85          * Supports static call {@link #timeoutSessions(HttpSession)}
86          */
87         private static List<OnboardingApp> onboardedAppList = null;
88         
89         @Autowired
90         private SessionCommunication sessionCommunication;
91         
92         
93         @Override
94         protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
95                 try {
96                         //Create a request id if there is none available,
97                         //and which will internally be used when making
98                         //session extended timeout calls to the partner applications.
99                         if (getSessionCommunication()!=null) {
100                                 getSessionCommunication().setRequestId();
101                         }
102                         logger.info(EELFLoggerDelegate.debugLogger, "Quartz Cronjob for Session Management begins");
103                         
104                         ManageService manageService = (ManageService) applicationContext.getBean("manageService");
105                         EPAppService appService = (EPAppService) applicationContext.getBean("epAppService");
106                         AppsCacheService appsCacheService = (AppsCacheService)applicationContext.getBean("appsCacheService");
107                         
108                         List<OnboardingApp> appList = appsCacheService.getAppsFullList();
109                         onboardedAppList = appList;
110                         TypeReference<Hashtable<String, TimeoutVO>> typeRef = new TypeReference<Hashtable<String, TimeoutVO>>() {
111                         };
112                         String portalJsonSessionStr;
113                         Map<String, TimeoutVO> portalSessionTimeoutMap = null;
114
115                         portalJsonSessionStr = manageService.gatherSessionExtenstions();
116                         if (portalJsonSessionStr == null || portalJsonSessionStr == "") {
117                                 logger.error(EELFLoggerDelegate.errorLogger, "Session Management: Portal session information is empty.");
118                                 return;
119                         }
120                         
121                         try {
122                                 portalSessionTimeoutMap = mapper.readValue(portalJsonSessionStr, typeRef);
123                         } catch (JsonMappingException | JsonParseException je) {
124                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, je);
125                                 logger.error(EELFLoggerDelegate.errorLogger, "Session Management: JSON Mapping Exception occurred while gathering the Session", je);
126                                 return;
127                         } catch (Exception e) {
128                                 logger.error(EELFLoggerDelegate.errorLogger, "Session Management: Error while gather Session from portal", e);
129                                 return;
130                         }
131                         
132                         Map<Long, Map<String, TimeoutVO>> appSessionTimeOutMap = new Hashtable<Long, Map<String, TimeoutVO>>();
133                         // determine the Max TimeOut Time for each of the managed sessions
134                         for (OnboardingApp app : appList) {
135                                 if (app.getRestUrl() == null) {
136                                         logger.info(EELFLoggerDelegate.debugLogger, "Session Management: null restUrl, not fetching from app " + app.getAppName());
137                                         continue;
138                                 }
139                                 logger.info(EELFLoggerDelegate.debugLogger, "Session Management: Calling App " + app.getAppName() + " at URL " + app.getRestUrl());
140                                 String jsonSessionStr = fetchAppSessions(app);
141                                 logger.info(EELFLoggerDelegate.debugLogger, "Session Management: App " + app.getAppName() + " returned  " + jsonSessionStr);
142                                 if (jsonSessionStr == null || jsonSessionStr.isEmpty())
143                                         continue;
144
145                                 try {
146                                         Map<String, TimeoutVO> sessionTimeoutMap = mapper.readValue(jsonSessionStr, typeRef);
147                                         appSessionTimeOutMap.put(app.getId(), sessionTimeoutMap);
148                                         for (String portalJSessionId : sessionTimeoutMap.keySet()) {
149                                                 final TimeoutVO maxTimeoutVO = portalSessionTimeoutMap.get(portalJSessionId);
150                                                 final TimeoutVO compareTimeoutVO = sessionTimeoutMap.get(portalJSessionId);
151                                                 if (maxTimeoutVO != null && compareTimeoutVO != null) {
152                                                         if (maxTimeoutVO.compareTo(compareTimeoutVO) < 0)
153                                                                 portalSessionTimeoutMap.get(portalJSessionId)
154                                                                                 .setSessionTimOutMilliSec(compareTimeoutVO.getSessionTimOutMilliSec());
155                                                 }
156                                         }
157                                 } catch (JsonParseException | JsonMappingException e) {
158                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
159                                         logger.error(EELFLoggerDelegate.errorLogger, 
160                                                         "JSON Mapping/Processing Exception occurred while mapping/parsing the jsonSessionStr", e);
161                                         continue;
162                                 } catch (Exception e) {
163                                         logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while mapping/parsing the jsonSessionStr", e);
164                                         continue;
165                                 }
166
167                         }
168
169                         // post the updated session timeouts back to the Apps
170                         for (OnboardingApp app : appList) {
171                                 if (app.getRestUrl() == null) {
172                                         logger.warn(EELFLoggerDelegate.errorLogger, "Session Management: null restUrl, not posting back to app " + app.getAppName());
173                                         continue;
174                                 }
175
176                                 Map<String, TimeoutVO> sessionTimeoutMap = appSessionTimeOutMap.get(app.getId());
177                                 if (sessionTimeoutMap == null || sessionTimeoutMap.isEmpty())
178                                         continue;
179
180                                 for (String portalJSessionId : sessionTimeoutMap.keySet()) {
181                                         try {
182                                                 final TimeoutVO maxTimeoutVO = portalSessionTimeoutMap.get(portalJSessionId);
183                                                 final TimeoutVO setTimeoutVO = sessionTimeoutMap.get(portalJSessionId);
184                                                 if (maxTimeoutVO == null || setTimeoutVO == null) {
185                                                         String message = String.format(
186                                                                         "Session Management: Failed to update the session timeouts for the app: %s and the sessionId: %s.",
187                                                                         app.getAppName(), portalJSessionId);
188                                                         logger.warn(EELFLoggerDelegate.errorLogger, message);
189                                                         continue;
190                                                 }
191                                                 setTimeoutVO.setSessionTimOutMilliSec(maxTimeoutVO.getSessionTimOutMilliSec());
192                                         } catch (Exception e) {
193                                                 logger.error(EELFLoggerDelegate.errorLogger, "Session Management:  error while updating the session timeout map", e);
194                                                 continue;
195                                         }
196                                 }
197                                 logger.info(EELFLoggerDelegate.debugLogger, "Session Management: Updating App " + app.getRestUrl());
198                                 String sessionTimeoutMapStr = "";
199                                 try {
200                                         sessionTimeoutMapStr = mapper.writeValueAsString(sessionTimeoutMap);
201                                 } catch (JsonProcessingException je) {
202                                         logger.error(EELFLoggerDelegate.errorLogger, "executeInternal failed while processing sessionTimeOutMap object to a String", je);
203                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, je);
204                                 }
205                                 pingAppSessions(app, sessionTimeoutMapStr);
206                         }
207                         String portalSessionTimeoutMapStr = "";
208                         try {
209                                 portalSessionTimeoutMapStr = mapper.writeValueAsString(portalSessionTimeoutMap);
210                         } catch (JsonProcessingException je) {
211                                 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while processing portalSessionTimeOutMap object to a String", je);
212                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, je);
213                         }
214                         manageService.updateSessionExtensions(portalSessionTimeoutMapStr);
215                 } catch (Exception e) {
216                         logger.error(EELFLoggerDelegate.errorLogger, "************************ Session Management:  error in managing session timeouts", e);
217                 } finally {
218                         getSessionCommunication().clear(true);
219                 }
220         }
221
222         private String fetchAppSessions(OnboardingApp app) throws Exception {
223                 String jsonSessionValue = getSessionCommunication().sendGet(app);
224                 getSessionCommunication().clear(false);
225                 return jsonSessionValue;
226         }
227
228         private void pingAppSessions(OnboardingApp app, String sessionTimeoutMapStr) throws Exception {
229                 getSessionCommunication().pingSession(app, sessionTimeoutMapStr);
230                 getSessionCommunication().clear(false);
231         }
232
233         public void timeoutSessions(HttpSession session) throws Exception {
234                 String portalJSessionId = portalJSessionId(session);
235                 if (onboardedAppList == null)
236                         return;
237
238                 for (OnboardingApp app : onboardedAppList) {
239                         getSessionCommunication().timeoutSession(app, portalJSessionId);
240                         getSessionCommunication().clear(false);
241                 }
242         }
243
244         protected static String portalJSessionId(HttpSession session) {
245                 final Object attribute = session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID);
246                 if (attribute == null)
247                         return "";
248                 String jSessionKey = (String) attribute;
249                 return jSessionKey.split("-")[0];
250                 //return jSessionKey;
251         }
252
253         private static ApplicationContext applicationContext;
254
255         public static void setApplicationContext(ApplicationContext _applicationContext) {
256                 applicationContext = _applicationContext;
257         }
258
259         public SessionCommunication getSessionCommunication() {
260                 if(sessionCommunication == null){
261                         if (applicationContext != null)                         
262                                 sessionCommunication = (SessionCommunication)applicationContext.getBean("sessionCommunication");
263                 }
264                 
265                 return sessionCommunication;
266         }
267
268         public void setSessionCommunication(SessionCommunication sessionCommunication) {
269                 this.sessionCommunication = sessionCommunication;
270         }
271
272 }