<commit_before>/*
 * Copyright (C) 2006-2008  exedio GmbH (www.exedio.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package com.exedio.cronjob;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

final class Handler
{
	private final int DURATION_BETWEEN_CHECKS=2705;
	private final DateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy - HH:mm:ss");

	final String id;
	final Job job;
	final String jobName;
	final boolean activeInitially;
	private RunContext runContext = null;
	private Date lastTimeStarted;
	private long lastInterruptRequest;
	private long interruptMaximum = 0;
	private long interruptTotal = 0;
	private int interruptCount = 0;
	private Exception lastException;
	private int lastRunResult = 0;
	private boolean lastRunSuccessful;
	private boolean activated;
	private int successfulRuns;
	private long averageTimeNeeded;
	private long timeNeeded;
	private boolean runNow;
	private int fails;
	private RunningThread runningThread;
	private final Date createdAt;
	private final long initialDelayinMS;
	private final long stopTimeout;

	/**
	 * After construction use #startThread() to start running of the job.
	 */
	Handler(final Job job, final int id, final long initialDelayInMS)
	{
		this.id = "cronjob_"+String.valueOf(id);
		this.job=job;
		this.jobName = job.getName();
		this.activeInitially = job.isActiveInitially();
		lastTimeStarted=null;
		lastException=null;
		lastRunSuccessful=true;
		activated=activeInitially;
		successfulRuns=0;
		averageTimeNeeded=0;
		timeNeeded=0;
		fails=0;
		runNow=false;
		createdAt=new Date();
		this.initialDelayinMS=initialDelayInMS+job.getInitialDelayInMilliSeconds();
		this.stopTimeout = job.getStopTimeout();
	}

	private boolean timeForExcecution()
	{
		if (lastTimeStarted == null)
		{
			return true;
		}
		else
		{
			final long last = lastTimeStarted.getTime();
			final long now = new Date().getTime();
			if ((now-last)>=(job.getMinutesBetweenExecutions()*1000*60))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}

	long getLastInterruptRequest()
	{
		return lastInterruptRequest;
	}

	long getInterruptMaximum()
	{
		return interruptMaximum;
	}

	long getInterruptAverage()
	{
		return (interruptCount>0) ? (interruptTotal / interruptCount) : 0;
	}

	boolean requestsStop()
	{
		final long now = System.currentTimeMillis();
		registerInterruptRequest(now);
		lastInterruptRequest = now;
		return !activated;
	}

	private void registerInterruptRequest(final long now)
	{
		final long last = (lastInterruptRequest!=0) ? lastInterruptRequest : lastTimeStarted.getTime();
		final long elapsed = (int)(now - last);

		if(interruptMaximum<elapsed)
			interruptMaximum = elapsed;
		interruptTotal += elapsed;
		interruptCount++;
	}

	void tryToExecute()
	{
		if (canExecuteJob())
		{
			runContext = new RunContext(this);
			lastTimeStarted=new Date();
			lastInterruptRequest = 0;
			final long msb=lastTimeStarted.getTime();
			//System.out.println("\nStarting Cronjob: "+getDisplayedName()+" at "+DATE_FORMAT.format(lastTimeStarted));
			try
			{
				job.run(runContext);
				lastRunResult = runContext.getProgress();
				final Date finished =new Date();
				lastRunSuccessful=true;
				//System.out.println("Finished Cronjob: "+getDisplayedName()+" at "+DATE_FORMAT.format(finished)+"\n");
				final long msa=finished.getTime();
				timeNeeded=msa-msb;
				updateAverageTimeNeeded(timeNeeded);
				registerInterruptRequest(finished.getTime());
			}
			catch (final Exception e)
			{
				lastException=e;
				fails++;
				final Date failedAt= new Date();
				timeNeeded=failedAt.getTime()-msb;
				System.out.println("Execution of Cronjob: " + jobName + " FAILED at "+DATE_FORMAT.format(failedAt)+" !!!");
				System.out.println("******************** CronjobException - START ********************");
				e.printStackTrace();
				System.out.println("******************** CronjobException - END **********************");
				lastRunSuccessful=false;
				registerInterruptRequest(failedAt.getTime());
			}
			finally
			{
				runContext = null;
			}
		}
	}

	private void updateAverageTimeNeeded(final long timeNeeded) // TODO why this parameter is needed here?
	{
		if (successfulRuns==0)
		{
			averageTimeNeeded=timeNeeded;
		}
		else
		{
			averageTimeNeeded=(((successfulRuns*averageTimeNeeded) + timeNeeded)/(successfulRuns+1));
		}
		successfulRuns++;
	}

	private boolean canExecuteJob()
	{
		if(runNow && runContext==null)
		{
			runNow=false;
			return true;
		}
		boolean result = true;
		if ((new Date().getTime()-createdAt.getTime())<initialDelayinMS)
		{
			result=false;
		}
		if(runContext!=null)
		{
			runContext = null;<commit_msg>move catcher code into separate method, preparation for reuse<commit_after>/*
 * Copyright (C) 2006-2008  exedio GmbH (www.exedio.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package com.exedio.cronjob;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

final class Handler
{
	private final int DURATION_BETWEEN_CHECKS=2705;
	private final DateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy - HH:mm:ss");

	final String id;
	final Job job;
	final String jobName;
	final boolean activeInitially;
	private RunContext runContext = null;
	private Date lastTimeStarted;
	private long lastInterruptRequest;
	private long interruptMaximum = 0;
	private long interruptTotal = 0;
	private int interruptCount = 0;
	private Exception lastException;
	private int lastRunResult = 0;
	private boolean lastRunSuccessful;
	private boolean activated;
	private int successfulRuns;
	private long averageTimeNeeded;
	private long timeNeeded;
	private boolean runNow;
	private int fails;
	private RunningThread runningThread;
	private final Date createdAt;
	private final long initialDelayinMS;
	private final long stopTimeout;

	/**
	 * After construction use #startThread() to start running of the job.
	 */
	Handler(final Job job, final int id, final long initialDelayInMS)
	{
		this.id = "cronjob_"+String.valueOf(id);
		this.job=job;
		this.jobName = job.getName();
		this.activeInitially = job.isActiveInitially();
		lastTimeStarted=null;
		lastException=null;
		lastRunSuccessful=true;
		activated=activeInitially;
		successfulRuns=0;
		averageTimeNeeded=0;
		timeNeeded=0;
		fails=0;
		runNow=false;
		createdAt=new Date();
		this.initialDelayinMS=initialDelayInMS+job.getInitialDelayInMilliSeconds();
		this.stopTimeout = job.getStopTimeout();
	}

	private boolean timeForExcecution()
	{
		if (lastTimeStarted == null)
		{
			return true;
		}
		else
		{
			final long last = lastTimeStarted.getTime();
			final long now = new Date().getTime();
			if ((now-last)>=(job.getMinutesBetweenExecutions()*1000*60))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}

	long getLastInterruptRequest()
	{
		return lastInterruptRequest;
	}

	long getInterruptMaximum()
	{
		return interruptMaximum;
	}

	long getInterruptAverage()
	{
		return (interruptCount>0) ? (interruptTotal / interruptCount) : 0;
	}

	boolean requestsStop()
	{
		final long now = System.currentTimeMillis();
		registerInterruptRequest(now);
		lastInterruptRequest = now;
		return !activated;
	}

	private void registerInterruptRequest(final long now)
	{
		final long last = (lastInterruptRequest!=0) ? lastInterruptRequest : lastTimeStarted.getTime();
		final long elapsed = (int)(now - last);

		if(interruptMaximum<elapsed)
			interruptMaximum = elapsed;
		interruptTotal += elapsed;
		interruptCount++;
	}

	void tryToExecute()
	{
		if (canExecuteJob())
		{
			runContext = new RunContext(this);
			lastTimeStarted=new Date();
			lastInterruptRequest = 0;
			final long msb=lastTimeStarted.getTime();
			//System.out.println("\nStarting Cronjob: "+getDisplayedName()+" at "+DATE_FORMAT.format(lastTimeStarted));
			try
			{
				job.run(runContext);
				lastRunResult = runContext.getProgress();
				final Date finished =new Date();
				lastRunSuccessful=true;
				//System.out.println("Finished Cronjob: "+getDisplayedName()+" at "+DATE_FORMAT.format(finished)+"\n");
				final long msa=finished.getTime();
				timeNeeded=msa-msb;
				updateAverageTimeNeeded(timeNeeded);
				registerInterruptRequest(finished.getTime());
			}
			catch (final Exception e)
			{
				atCatch(e, msb);
			}
			finally
			{
				runContext = null;
			}
		}
	}

	private void updateAverageTimeNeeded(final long timeNeeded) // TODO why this parameter is needed here?
	{
		if (successfulRuns==0)
		{
			averageTimeNeeded=timeNeeded;
		}
		else
		{
			averageTimeNeeded=(((successfulRuns*averageTimeNeeded) + timeNeeded)/(successfulRuns+1));
		}
		successfulRuns++;
	}

	private void atCatch(final Exception e, final long msb)
	{
		lastException=e;
		fails++;
		final Date failedAt= new Date();
		timeNeeded=failedAt.getTime()-msb;
		System.out.println("Execution of Cronjob: " + jobName + " FAILED at "+DATE_FORMAT.format(failedAt)+" !!!");
		System.out.println("******************** CronjobException - START ********************");
		e.printStackTrace();
		System.out.println("******************** CronjobException - END **********************");
		lastRunSuccessful=false;
		registerInterruptRequest(failedAt.getTime());
	}

	private boolean canExecuteJob()
	{
		if(runNow && runContext==null)
		{
			runNow=false;
			return true;
		}
		boolean result = true;
		if ((new Date().getTime()-createdAt.getTime())<initialDelayinMS)
		{
			result=false;
		}
		if(runContext!=null)
		{
			runContext = null;
{'fraction_non_alphanumeric': 0.11677108871333879, 'fraction_numerical': 0.008716970852628712, 'mean_word_length': 4.375305026842362, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '110898', 'n_tokens_mistral': 3876, 'n_tokens_neox': 3389, 'n_words': 911}