001/*
002 * jPOS Project [http://jpos.org]
003 * Copyright (C) 2000-2026 jPOS Software SRL
004 *
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jpos.q2;
020
021import org.jpos.core.Configuration;
022import org.jpos.core.ConfigurationException;
023
024import java.util.concurrent.ScheduledFuture;
025import java.util.concurrent.TimeUnit;
026
027public abstract class QBeanAsyncSupport extends QBeanSupport {
028
029    private long startMaxWait;
030    private long stopMaxWait;
031
032    @Override
033    protected final void startService() throws Exception {
034        ScheduledFuture<?> future = getScheduledThreadPoolExecutor().schedule(() -> {
035            try {
036                doStart();
037            } catch (Exception e) {
038                setState(QBean.FAILED);
039                log.error(e);
040            }
041        }, 0, TimeUnit.MILLISECONDS);
042        if (startMaxWait > 0) {
043            future.get(startMaxWait, TimeUnit.MILLISECONDS);
044        }
045    }
046
047    protected abstract void doStart() throws Exception;
048
049    @Override
050    protected final void stopService() throws Exception {
051        ScheduledFuture<?> future = getScheduledThreadPoolExecutor().schedule(() -> {
052            try {
053                doStop();
054            } catch (Exception e) {
055                log.error(e);
056            }
057        }, 0, TimeUnit.MILLISECONDS);
058        if (stopMaxWait > 0) {
059            future.get(stopMaxWait, TimeUnit.MILLISECONDS);
060        }
061    }
062
063    protected abstract void doStop() throws Exception;
064
065    @Override
066    public void setConfiguration(Configuration cfg) throws ConfigurationException {
067        super.setConfiguration(cfg);
068        startMaxWait = cfg.getLong("startMaxWait", 0L);
069        stopMaxWait = cfg.getLong("stopMaxWait", 0L);
070    }
071}