001/*
002 *  Copyright 2019 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.core.impl.schedule;
017
018import org.apache.avalon.framework.configuration.Configuration;
019import org.apache.avalon.framework.configuration.ConfigurationException;
020import org.apache.avalon.framework.configuration.DefaultConfiguration;
021
022import org.ametys.runtime.config.Config;
023
024/**
025 * A {@link Runnable} is launched every N minutes where N is defined by the config parameter defined into param-period.
026 */
027public class ConfigBasedEveryNMinutesRunnable extends StaticRunnable
028{
029    @Override
030    public void configure(Configuration configuration) throws ConfigurationException
031    {
032        DefaultConfiguration modifiedConfiguration = new DefaultConfiguration(configuration);
033        
034        // FireProcess = cron
035        DefaultConfiguration fireProcessConfig = new DefaultConfiguration("fire-process");
036        fireProcessConfig.setValue("cron");
037        modifiedConfiguration.addChild(fireProcessConfig);
038
039        // Get the config parameter value
040        String periodParamName = configuration.getChild("param-period").getValue("").trim();
041        Long periodCfg = Config.getInstance().getValue(periodParamName);
042        
043        // If the value is 60, it's mean that it should be executed each hour, then we force minutes to 0
044        if (periodCfg == 60)
045        {
046            periodCfg = Long.valueOf(0);
047        }
048        
049        // Set our custom cron
050        String cronExpression = "0 0/" + periodCfg + " * * * ?";
051        DefaultConfiguration cronConfig = new DefaultConfiguration("cron");
052        cronConfig.setValue(cronExpression);
053        modifiedConfiguration.addChild(cronConfig);
054        
055        _superConfigure(modifiedConfiguration);
056    }
057    
058    /**
059     * Call the configure method of the superclass.
060     * @param configuration The modified configuration
061     * @throws ConfigurationException if an error occurs
062     */
063    protected void _superConfigure(Configuration configuration) throws ConfigurationException
064    {
065        // Call configure of StaticRunnable
066        super.configure(configuration);
067    }
068}