From b7f1906e2c9edd390834a8431ba9c6903efc3977 Mon Sep 17 00:00:00 2001
From: Mike McKay <mfmckay@wustl.edu>
Date: Tue, 24 May 2016 12:28:30 -0500
Subject: [PATCH] Created events for changing site config preferences and
 updated how often alias token timeout was checked based on timeout interval.
 Also added sessionTimeout back in.

---
 .../xnat/configuration/SchedulerConfig.java   | 47 +++++-----
 .../SiteConfigPreferenceHandler.java          | 91 +++++++++++++++++++
 2 files changed, 116 insertions(+), 22 deletions(-)
 create mode 100644 src/main/java/org/nrg/xnat/event/listeners/SiteConfigPreferenceHandler.java

diff --git a/src/main/java/org/nrg/xnat/configuration/SchedulerConfig.java b/src/main/java/org/nrg/xnat/configuration/SchedulerConfig.java
index fd420602..0814d438 100644
--- a/src/main/java/org/nrg/xnat/configuration/SchedulerConfig.java
+++ b/src/main/java/org/nrg/xnat/configuration/SchedulerConfig.java
@@ -3,9 +3,11 @@ package org.nrg.xnat.configuration;
 import org.nrg.config.exceptions.SiteConfigurationException;
 import org.nrg.framework.exceptions.NrgServiceError;
 import org.nrg.framework.exceptions.NrgServiceRuntimeException;
+import org.nrg.framework.services.NrgEventService;
 import org.nrg.mail.services.EmailRequestLogService;
 import org.nrg.xdat.XDAT;
 import org.nrg.xdat.preferences.InitializerSiteConfiguration;
+import org.nrg.xdat.preferences.SiteConfigPreferenceEvent;
 import org.nrg.xdat.preferences.SiteConfigPreferences;
 import org.nrg.xnat.helpers.prearchive.SessionXMLRebuilder;
 import org.nrg.xnat.security.DisableInactiveUsers;
@@ -59,28 +61,28 @@ public class SchedulerConfig implements SchedulingConfigurer {
     public TriggerTask resetEmailRequests() {
         return new TriggerTask(new ResetEmailRequests(_emailRequestLogService), new PeriodicTrigger(900000));
     }
-
-    @Bean
-    public TriggerTask clearExpiredAliasTokens() throws SiteConfigurationException {
-        return new TriggerTask(new ClearExpiredAliasTokens(_template), new Trigger() {
-            @Override public Date nextExecutionTime(TriggerContext triggerContext) {
-                Calendar nextExecutionTime =  new GregorianCalendar();
-                Date lastActualExecutionTime = triggerContext.lastActualExecutionTime();
-                nextExecutionTime.setTime(lastActualExecutionTime != null ? lastActualExecutionTime : new Date());
-                long expirationInterval = XDAT.getSiteConfigPreferences().getAliasTokenTimeout();
-                if(expirationInterval<120){//Check every minute if interval is 2 hours or less
-                    nextExecutionTime.add(Calendar.MINUTE, 1);
-                }
-                else if(expirationInterval<2880){//Check every hour if interval is 2 days or less
-                    nextExecutionTime.add(Calendar.HOUR, 1);
-                }
-                else{//Check every day
-                    nextExecutionTime.add(Calendar.DAY_OF_MONTH, 1);
-                }
-                return nextExecutionTime.getTime();
-            }
-        });
-    }
+//
+//    @Bean
+//    public TriggerTask clearExpiredAliasTokens() throws SiteConfigurationException {
+//        return new TriggerTask(new ClearExpiredAliasTokens(_template), new Trigger() {
+//            @Override public Date nextExecutionTime(TriggerContext triggerContext) {
+//                Calendar nextExecutionTime =  new GregorianCalendar();
+//                Date lastActualExecutionTime = triggerContext.lastActualExecutionTime();
+//                nextExecutionTime.setTime(lastActualExecutionTime != null ? lastActualExecutionTime : new Date());
+//                long expirationInterval = XDAT.getSiteConfigPreferences().getAliasTokenTimeout();
+//                if(expirationInterval<120){//Check every minute if interval is 2 hours or less
+//                    nextExecutionTime.add(Calendar.MINUTE, 1);
+//                }
+//                else if(expirationInterval<2880){//Check every hour if interval is 2 days or less
+//                    nextExecutionTime.add(Calendar.HOUR, 1);
+//                }
+//                else{//Check every day
+//                    nextExecutionTime.add(Calendar.DAY_OF_MONTH, 1);
+//                }
+//                return nextExecutionTime.getTime();
+//            }
+//        });
+//    }
 
     @Bean
     public TriggerTask rebuildSessionXmls() throws SiteConfigurationException {
@@ -102,6 +104,7 @@ public class SchedulerConfig implements SchedulingConfigurer {
 //        taskRegistrar.addTriggerTask(resetEmailRequests());
 //        taskRegistrar.addTriggerTask(clearExpiredAliasTokens());
 //        taskRegistrar.addTriggerTask(rebuildSessionXmls());
+        XDAT.getContextService().getBean(NrgEventService.class).triggerEvent(new SiteConfigPreferenceEvent("aliasTokenTimeout", String.valueOf(XDAT.getSiteConfigPreferences().getAliasTokenTimeout())));
         for (final TriggerTask triggerTask : _triggerTasks) {
             taskRegistrar.addTriggerTask(triggerTask);
         }
diff --git a/src/main/java/org/nrg/xnat/event/listeners/SiteConfigPreferenceHandler.java b/src/main/java/org/nrg/xnat/event/listeners/SiteConfigPreferenceHandler.java
new file mode 100644
index 00000000..09327d68
--- /dev/null
+++ b/src/main/java/org/nrg/xnat/event/listeners/SiteConfigPreferenceHandler.java
@@ -0,0 +1,91 @@
+package org.nrg.xnat.event.listeners;
+
+import org.apache.commons.codec.binary.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nrg.framework.event.entities.EventSpecificFields;
+import org.nrg.xdat.XDAT;
+import org.nrg.xdat.preferences.SiteConfigPreferenceEvent;
+import org.nrg.xnat.security.alias.ClearExpiredAliasTokens;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.scheduling.Trigger;
+import org.springframework.scheduling.TriggerContext;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
+import org.springframework.stereotype.Service;
+import reactor.bus.Event;
+import reactor.bus.EventBus;
+import reactor.fn.Consumer;
+
+import javax.inject.Inject;
+import java.util.*;
+import java.util.concurrent.ScheduledFuture;
+
+import static reactor.bus.selector.Selectors.type;
+
+@Service
+public class SiteConfigPreferenceHandler implements Consumer<Event<SiteConfigPreferenceEvent>> {
+
+	@Inject public SiteConfigPreferenceHandler( EventBus eventBus ){
+		eventBus.on(type(SiteConfigPreferenceEvent.class), this);
+	}
+
+	@Override
+	public void accept(Event<SiteConfigPreferenceEvent> event) {
+		final SiteConfigPreferenceEvent scpEvent = event.getData();
+		handleEvent(scpEvent);
+	}
+
+    public void handleEvent(SiteConfigPreferenceEvent e) {
+    	Set<EventSpecificFields> fields = e.getEventSpecificFields();
+		if(fields!=null) {
+			for (EventSpecificFields field : fields) {
+				if (StringUtils.equals(field.getFieldName(), "aliasTokenTimeout")) {
+					updateAliasTokenTimeout(e);	
+				}
+			}
+		}
+    }
+	
+	private void updateAliasTokenTimeout(SiteConfigPreferenceEvent e){
+		try {
+			//SchedulerConfig.removeClearExpiredAliasTokensTask();
+			XDAT.getContextService().getBeansOfType(ThreadPoolTaskScheduler.class).get("taskScheduler").getScheduledThreadPoolExecutor().setRemoveOnCancelPolicy(true);
+			Iterator<Runnable> iter = XDAT.getContextService().getBeansOfType(ThreadPoolTaskScheduler.class).get("taskScheduler").getScheduledThreadPoolExecutor().getQueue().iterator();
+
+			for(ScheduledFuture temp: scheduledAliasTokenTimeouts){
+				temp.cancel(false);
+			}
+
+			scheduledAliasTokenTimeouts.add(XDAT.getContextService().getBeansOfType(ThreadPoolTaskScheduler.class).get("taskScheduler").schedule(new ClearExpiredAliasTokens(_template),new Trigger() {
+				@Override public Date nextExecutionTime(TriggerContext triggerContext) {
+					Calendar nextExecutionTime =  new GregorianCalendar();
+					Date lastActualExecutionTime = triggerContext.lastActualExecutionTime();
+					nextExecutionTime.setTime(lastActualExecutionTime != null ? lastActualExecutionTime : new Date());
+					long expirationInterval = XDAT.getSiteConfigPreferences().getAliasTokenTimeout();
+					if(expirationInterval<120){//Check every minute if interval is 2 hours or less
+						nextExecutionTime.add(Calendar.MINUTE, 1);
+					}
+					else if(expirationInterval<2880){//Check every hour if interval is 2 days or less
+						nextExecutionTime.add(Calendar.HOUR, 1);
+					}
+					else{//Check every day
+						nextExecutionTime.add(Calendar.DAY_OF_MONTH, 1);
+					}
+					return nextExecutionTime.getTime();
+				}}));
+
+		} catch (Exception e1) {
+			_log.error("", e1);
+		}	
+	}
+
+	@Autowired
+	@Lazy
+	private JdbcTemplate _template;
+
+	private static final Log _log = LogFactory.getLog(SiteConfigPreferenceHandler.class);
+
+	private ArrayList<ScheduledFuture> scheduledAliasTokenTimeouts = new ArrayList<ScheduledFuture>();
+}
-- 
GitLab