⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jremserver.java

📁 JRemoteControl is a simple Java&#8482 driven bluetooth remote control.It allows you to initiate virt
💻 JAVA
字号:
/* * Copyright (C) 2007 Filippo Di Vattimo - See LICENSE * */package fildiv.jremcntl.server.core;import javax.bluetooth.RemoteDevice;import fildiv.jremcntl.common.core.Command;import fildiv.jremcntl.common.core.Config;import fildiv.jremcntl.common.core.JRemBTConstants;import fildiv.jremcntl.common.core.JRemBluetoothUnavailableException;import fildiv.jremcntl.common.core.JRemCommandData;import fildiv.jremcntl.common.core.JRemConnectorException;import fildiv.jremcntl.common.core.JRemRuntimeException;import fildiv.jremcntl.common.core.JRemServerConnectionListener;import fildiv.jremcntl.common.core.JRemVersion;import fildiv.jremcntl.common.core.Logger;import fildiv.jremcntl.common.proto.JRemDataTransferException;import fildiv.jremcntl.common.proto.JRemProtocolMessagesType;import fildiv.jremcntl.common.util.JRemUtils;import fildiv.jremcntl.server.gui.core.ConsoleLogger;import fildiv.jremcntl.server.utils.JRemServerUtils;public class JRemServer {		private JRemEnv env;	private boolean useAuthentication;	private boolean useAuthorization;	private boolean useEncryption;	private JRemServerConnector connector;	private ServerCmdMgnFactory cmf;	private JRemServerListeners listeners;		private RemoteDevice rd;	private Config config;		private boolean inShutingdown;	private boolean stopped = true;	private Object mutex;		/*	 * ConnectionListener 	 */		private JRemServerConnectionListener clistener = new JRemServerConnectionListener() {				public void incomingConnection(RemoteDevice rd) {			JRemServer.this.rd = rd;		}		public void inProgress() {		}				public void interrupt() {					}		public void exceptionOccurred(Exception e) {			if (!inShutingdown)				listeners.onServerExceptionOccurred(e);		}			};				/*	 * Static	 */		public static String getVersion() {		return JRemVersion.VERSION;	}		/*	 * Public	 */		public JRemServer() {		this(null);	}	public JRemServer(Config config) {						this.env = JRemEnv.getInstance();		listeners = new JRemServerListeners();		this.config = config;				this.cmf = createCmdMgnFactory();	}				public void addServerEventsListener(JRemServerEventsListener listener) {		listeners.addServerEventsListener(listener);	}		public void removeServerEventsListener(JRemServerEventsListener listener) {		listeners.removeServerEventsListener(listener);	}	public void addCommandEventsListener(JRemServerEventsListener listener) {		listeners.addCommandEventsListener(listener);	}		public void removeCommandEventsListener(JRemServerEventsListener listener) {		listeners.removeCommandEventsListener(listener);	}		public boolean isShutingDown() {		return inShutingdown;	}	public boolean isRunning() {		return !stopped && !inShutingdown;	}		public boolean isBluetoothUp() {				if (connector == null)			connector = new JRemServerConnector(clistener);		return connector.isBluetoothUp();	}	public Config getConfig() {		return config;	}		public void setConfig(Config config) {				if (config == null)			throw new IllegalArgumentException("Config cannot be null");		/*		if (!config.checkValid().isValid())			throw new IllegalArgumentException("Config is not valid");		*/				if (isRunning())			throw new IllegalStateException(					"You must stop the server before calling this mehod");				this.config = config;	}		public void start() throws JRemConnectorException,		JRemDataTransferException, JRemBluetoothUnavailableException {		if (config == null)			throw new IllegalStateException(					"You must set a configuration before starting the server");				if (!isBluetoothUp())			throw new JRemBluetoothUnavailableException(				"Bluetooth is unavailable, check your configuration ...");		synchronized (this) {						if (isRunning())				return;				inShutingdown = false;			stopped = false;		}		onServerStarting();		waitAndLock();								try {					onServerStarted();						while(!inShutingdown) {				connectionListening();												try {									commandListening();								} catch(Exception e) {										if (!inShutingdown)						listeners.onServerExceptionOccurred(e);				}								release();				onDeviceDisconnected();			}					} catch(JRemConnectorException e) {						if (!inShutingdown)				throw e;				} catch(JRemDataTransferException e) {			if (!inShutingdown)				throw e;					} catch(Exception e) {						if (!inShutingdown)				throw new JRemRuntimeException(e);		} catch(Throwable e) {						if (!inShutingdown)				throw new JRemRuntimeException(e.getMessage());		} finally {									stopped = true;			inShutingdown = false;						release();												onServerStopped();			releaseLock();		}	}	public synchronized void stop() {			if (!isRunning() || connector == null)			return;		onServerStopping();				closeClientConnection();						inShutingdown = true;				connector.close();				waitForLock();			}	public void dispose() {		listeners.removeAllListeners();		release();	}	/*	 * Override	 */		protected void closeClientConnection() {				if (connector == null)			return;				JRemServerProtocol proto = (JRemServerProtocol) connector.getProtocol();		if (proto != null)			proto.closeClientConnection();	}	protected ServerCmdMgnFactory createCmdMgnFactory() {		if (System.getProperty("os.name").toLowerCase().startsWith("windows"))			return new WindowsServerCmdMngFactory(listeners);		return new LinuxServerCmdFactory(listeners);	}	protected String getURL() {		String url = JRemBTConstants.JREM_SERVICE_URL;		if (useAuthentication)			url += ";authenticate=true";		else			url += ";authenticate=false";		if (useAuthorization)			url += ";authorize=true";		else			url += ";authorize=false";		if (useEncryption)			url += ";encrypt=true";		else			url += ";encrypt=false";		url += ";name=" + JRemBTConstants.JREM_SERVICE_NAME;		return url;	}	/*	 * Implementation	 */  	private void waitForLock() {				if (mutex == null)			return;				synchronized(mutex) {			try {				mutex.wait();			} catch (InterruptedException e) {							}		}			}	private void releaseLock() {		if (mutex == null)			return;				synchronized(mutex) {						try {				mutex.wait(500);			} catch (InterruptedException e) {				// Ignored			}						mutex.notify();						mutex = null;		}	}	private void waitAndLock() {				waitForLock();			mutex = new Object();	}	private void connectionListening() throws JRemConnectorException, JRemDataTransferException {				onConnectionListening();				connector = new JRemServerConnector(clistener);		connector.acceptAndOpen(getURL());		JRemServerProtocol proto = (JRemServerProtocol) connector.getProtocol(); 				cmf.setProtocol(proto);						onDeviceConnected();	}		protected void commandListening() throws JRemDataTransferException {				onClientCommandListening();				JRemServerProtocol prot = (JRemServerProtocol) connector.getProtocol();				boolean closeConnection = false;				while(!closeConnection) {						int cmdID = retrieveCommand(prot);			closeConnection = 				cmdID == JRemProtocolMessagesType.MSG_TYPE_CLOSE_CONNECTION;						if (!closeConnection)				processCommand(cmdID);		}	}	private void runExternalExe(String exePath) {				Command c = new JRemCommandData(exePath);		runCommand(c);				}	private void processCommand(int cmdID) {				Command cmd = config.findCommand(cmdID);		if (cmd == null)			return;			runCommand(cmd);	}	protected void runCommand(Command c) {				try {						onRunCommand(c);			ServerCmdProcessor cp = cmf.createCmdProcessor(c);			cp.process();				} catch(Exception e) {			onRunCommandException(c, e);		}	}		protected int retrieveCommand(JRemServerProtocol prot) throws JRemDataTransferException {		int cmdID = prot.retrieveCommandID();		return cmdID;	}		private void release() {						if (connector != null)			connector.close();				connector = null;	}		protected void finalize() throws Throwable {				super.finalize();		release();	}	/*	 *  Listener events	 */	protected void onServerStarting() {	}	protected void onServerStopping() {			}	protected void onServerStopped() {		listeners.onServerStopped();	}	protected void onServerStarted() {		listeners.onServerStarted();	}	protected void onConnectionListening() {		listeners.onConnectionListening();	}	protected void onDeviceDisconnected() {				listeners.onDeviceDisconnected();		String exePath = config.getOnDisconnectExePath();		if (JRemUtils.isEmptyString(exePath))			return;		runExternalExe(exePath);	}		protected void onClientCommandListening() {				listeners.onClientCommandListening();			}		protected void onRunCommand(Command c) {		listeners.onCommandRun(c);	}	protected void onDeviceConnected() throws JRemDataTransferException {		String deviceName = JRemServerUtils.getRemoteDeviceDesc(rd);		JRemServerProtocol proto = (JRemServerProtocol) connector.getProtocol();		proto.sendConfig(config);				listeners.onDeviceConnected(deviceName);		String exePath = config.getOnConnectExePath();		if (JRemUtils.isEmptyString(exePath))			return;		runExternalExe(exePath);	}		protected void onRunCommandException(Command c, Exception e) {		listeners.onCommandRunException(c, e);	}	/*	 * Main	 */		public static void main(String[] args) {				        if (args.length != 2) {            System.out.println(            		"Usage: JRemServer <config filename path>" +            		" <properties file path>");            System.exit(1);        }        String confFilePath = args[0];        String propFilePath = args[1];                        JRemEnv env = JRemEnv.createEnvironment(        		propFilePath, new ConsoleLogger(), false);        Logger logger = env.getLogger();        ConsoleServerListener csl = new ConsoleServerListener(logger);                        logger.info("JRemote Control Server " + JRemServer.getVersion());		        logger.info("Reading configuration ...");		        JRemConfigReader cr = new JRemConfigReader(confFilePath);        		JRemServer server = new JRemServer(cr.getConfig());		server.addServerEventsListener(csl);		server.addCommandEventsListener(csl);		try {			server.start();				} catch (Exception e) {			logger.error("Unable to start server");			logger.error(e);					} finally {			server.release();		}	}}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -