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.qbean; 020 021import java.io.File; 022import java.io.FileOutputStream; 023import java.io.RandomAccessFile; 024import java.nio.channels.FileChannel; 025import java.nio.channels.FileLock; 026 027import org.jpos.q2.QBeanSupport; 028 029public class QSingleInstanceFileBasedManager extends QBeanSupport { 030 031 File lockFile; 032 FileChannel lockChannel; 033 FileLock lock; 034 FileOutputStream lockFileOS; 035 036 /* 037 * (non-Javadoc) 038 * 039 * @see org.jpos.q2.QBeanSupport#initService() 040 */ 041 @Override 042 protected void initService() throws Exception { 043 044 try { 045 lockFile = new File("./" + getServer().getDeployDir(), "instance.lock"); 046 if (lockFile.exists()) { 047 // Either an orphan lock or lock from another instance. Orphan 048 // lock will get deleted, the latter will not get a lock on it. 049 lockFile.delete(); 050 } 051 lockFileOS = new FileOutputStream(lockFile); 052 lockFileOS.close(); 053 lockChannel = new RandomAccessFile(lockFile, "rw").getChannel(); 054 lock = lockChannel.tryLock(); 055 if (lock == null) { 056 throw new Exception("Unable to obtain lock"); 057 } 058 } 059 catch (Exception e) { 060 getLog().error("An instance of Q2 is already running. Shutting this instance"); 061 if (lock != null) { 062 lock.release(); 063 } 064 if (lockChannel != null) { 065 lockChannel.close(); 066 } 067 if (lockFile != null) { 068 lockFile.delete(); 069 } 070 getServer().shutdown(); 071 } 072 073 } 074 075 @Override 076 protected void stopService() throws Exception { 077 078 lock.release(); 079 lockChannel.close(); 080 lockFile.delete(); 081 } 082 083}