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.IOException; 022import java.net.ServerSocket; 023 024import org.jpos.core.Configuration; 025import org.jpos.core.ConfigurationException; 026import org.jpos.q2.QBeanSupport; 027 028/** 029 * QBean that enforces a single live Q2 instance by binding a configured TCP 030 * port at startup; a second instance fails to start when the port is taken. 031 */ 032public class QSingleInstancePortBasedManager extends QBeanSupport { 033 /** Default constructor; no instance state to initialise. */ 034 public QSingleInstancePortBasedManager() {} 035 036 ServerSocket ss; 037 038 int port; 039 040 /* 041 * (non-Javadoc) 042 * 043 * @see org.jpos.q2.QBeanSupport#initService() 044 */ 045 @Override 046 protected void initService() throws Exception { 047 048 try { 049 // attempt to bind, if another instance is already bound, an 050 // exception will get throwm 051 ss = new ServerSocket(port); 052 } 053 catch (IOException e) { 054 getLog().error("An instance of Q2 is already running. Shutting this instance"); 055 getServer().shutdown(); 056 } 057 058 } 059 060 @Override 061 public void setConfiguration(Configuration cfg) throws ConfigurationException { 062 063 super.setConfiguration(cfg); 064 065 port = cfg.getInt("port", 65000); 066 } 067 068}