/*
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 * 
 *
 *
 * $Log: SessionCleaningJob.java,v $
 * Revision 1.2  2007/02/07 15:30:32  lawern
 * cleaningPeriod auf 30 min erhöht
 *
 * Revision 1.1  2007/02/06 13:04:26  korowa
 * Ein Job hinzugefügt der die Überfählige Sessions entfernt
 *
 * 
 *
 */
package vkc.server.jobs;

import java.util.ArrayList;
import java.util.Date;
import javax.servlet.http.HttpSession;

import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import vkc.misc.VKCLogManager;
import vkc.view.WebShare;
import vkc.view.bean.UserTrackingInfo;

/**
 * Dieser Job dient dazu, die abgelaufene Sessions dessen Timeout nicht Funktioniert hat, nachträglich zu entfernen.
 * @author Alexander Bühler
 */
public class SessionCleaningJob implements Job {

	public static final String NAME = "SESSIONS_CLEANING";

	public static final int cleaningPeriod = 30 * 60 * 1000;

	public static final Date startTime = new Date(System.currentTimeMillis());

	/** 
	 * (non-Javadoc)
	 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
	 */
	public void execute(JobExecutionContext context)
			throws JobExecutionException {

		JobDetail job = context.getJobDetail();

		VKCLogManager.infoLog(this, "Executing Job " + job.getFullName());
		try {
			// Aktive sessions holen
			UserTrackingInfo[] userInfos = WebShare.getActiveUsers();
			ArrayList userInfosToRemove = new ArrayList();
			for (int i = 0; i < userInfos.length; i++) {
				HttpSession session = userInfos[i].getSession();
				//getMaxInactiveInterval() liefert Zeit in Sekunden
				if (System.currentTimeMillis() - session.getLastAccessedTime() > session
						.getMaxInactiveInterval() * 1000) {
					userInfosToRemove.add(userInfos[i]);
				}
			}
			//Abgelaufene Sessions entfernen
			for (int i = 0; i < userInfosToRemove.size(); i++) {
				UserTrackingInfo temp = (UserTrackingInfo) userInfosToRemove
						.get(i);
				temp.getSession().invalidate();
			}
		} catch (Exception e) {
			VKCLogManager.errorLog(this, "", "Error occured while executing "
					+ job.getFullName(), e);
		}

	}
}
