networkservercontrolimpl.java

来自「derby database source code.good for you.」· Java 代码 · 共 2,300 行 · 第 1/5 页

JAVA
2,300
字号
	/**	 * Write a message to console output stream	 *	 * @param msg	message	 */	public void consoleMessage(String msg)	{		// print to console if we have one		if (logWriter != null)		{			synchronized(logWriter) {				logWriter.println(msg);			}		}		// always print to derby.log		if (cloudscapeLogWriter != null)			synchronized(cloudscapeLogWriter)			{				Monitor.logMessage(msg);			}	}	/**	 * Start a network server.  Launches a separate thread with 	 * DRDAServerStarter.  Want to use Monitor.startModule,	 * so it can all get shutdown when cloudscape shuts down, but 	 * can't get it working right now.	 *	 * @param consoleWriter   PrintWriter to which server console will be 	 *                        output. Null will disable console output.	 *	 *		   	 * @exception Exception	throws an exception if an error occurs	 */	public void start(PrintWriter consoleWriter)		throws Exception	{		DRDAServerStarter starter = new DRDAServerStarter();		starter.setStartInfo(hostAddress,portNumber,consoleWriter);		startNetworkServer();		starter.boot(false,null);	}	/**	 * Start a network server	 *	 * @param consoleWriter   PrintWriter to which server console will be 	 *                        output. Null will disable console output.	 *	 *		   	 * @exception Exception	throws an exception if an error occurs	 */	public void blockingStart(PrintWriter consoleWriter)		throws Exception	{		startNetworkServer();		setLogWriter(consoleWriter);		cloudscapeLogWriter = Monitor.getStream().getPrintWriter();		if (SanityManager.DEBUG && debugOutput)		{			memCheck.showmem();			mc = new memCheck(200000);			mc.start();		}        // Open a server socket listener      	    try{	    	serverSocket = (ServerSocket) AccessController.doPrivileged(								new PrivilegedExceptionAction() {										public Object run() throws IOException,UnknownHostException										{											if (hostAddress == null)												hostAddress = InetAddress.getByName(hostArg);											// Make a list of valid											// InetAddresses for NetworkServerControl											// admin commands.											buildLocalAddressList(hostAddress);											return new ServerSocket(portNumber																	,0,																	hostAddress);										}									}								);		} catch (PrivilegedActionException e) {			Exception e1 = e.getException();	    	if (e1 instanceof IOException)            	consolePropertyMessage("DRDA_ListenPort.S", 									   new String [] {										   Integer.toString(portNumber), 										   hostArg}); 			if (e1 instanceof UnknownHostException) {				consolePropertyMessage("DRDA_UnknownHost.S", hostArg);			}			else				throw e1;		} catch (Exception e) {		// If we find other (unexpected) errors, we ultimately exit--so make		// sure we print the error message before doing so (Beetle 5033).			throwUnexpectedException(e);		}		consolePropertyMessage("DRDA_Ready.I", Integer.toString(portNumber));		// We accept clients on a separate thread so we don't run into a problem		// blocking on the accept when trying to process a shutdown		acceptClients = (Runnable)new ClientThread(this, serverSocket);		Thread clientThread =  (Thread) AccessController.doPrivileged(								new PrivilegedExceptionAction() {									public Object run() throws Exception									{										return new Thread(acceptClients);									}								}							);		clientThread.start();					// wait until we are told to shutdown or someone sends an InterruptedException        synchronized(shutdownSync) {            try {				shutdownSync.wait();            }            catch (InterruptedException e)            {                shutdown = true;            }        }		// Need to interrupt the memcheck thread if it is sleeping.		if (mc != null)			mc.interrupt();		//interrupt client thread		clientThread.interrupt(); 		// Close out the sessions 		synchronized(sessionTable) { 			for (Enumeration e = sessionTable.elements(); e.hasMoreElements(); ) 			{	 				Session session = (Session) e.nextElement(); 				session.close(); 			} 		}		synchronized (threadList)		{ 			//interupt any connection threads still active 			for (int i = 0; i < threadList.size(); i++) 			{ 				((DRDAConnThread)threadList.get(i)).close(); 				((DRDAConnThread)threadList.get(i)).interrupt(); 			} 			threadList.clear();		}	    		    // close the listener socket	    try{	       serverSocket.close();	    }catch(IOException e){			consolePropertyMessage("DRDA_ListenerClose.S");	    }		// Wake up those waiting on sessions, so		// they can close down		synchronized (runQueue) {			runQueue.notifyAll();		}								/*		// Shutdown Cloudscape		try {			if (cloudscapeDriver != null)				cloudscapeDriver.connect("jdbc:derby:;shutdown=true", 										 (Properties) null);		} catch (SQLException sqle) {			// If we can't shutdown cloudscape. Perhaps authentication is			// set to true or some other reason. We will just print a			// message to the console and proceed.			if (((EmbedSQLException)sqle).getMessageId() !=			  SQLState.CLOUDSCAPE_SYSTEM_SHUTDOWN)				consolePropertyMessage("DRDA_ShutdownWarning.I",									   sqle.getMessage());		}		*/		consolePropertyMessage("DRDA_ShutdownSuccess.I");		    }		/** 	 * Load Cloudscape and save driver for future use.	 * We can't call Driver Manager when the client connects, 	 * because they might be holding the DriverManager lock.	 *	 * 	 */		protected void startNetworkServer() throws Exception	{		// we start the cloudscape server here.		boolean restartCheck = this.restartFlag;		synchronized (serverStartSync) {			if (restartCheck == this.restartFlag) {			// then we can go ahead and restart the server (odds			// that some else has just done so are very slim (but not			// impossible--however, even if it does happen, things			// should still work correctly, just not as efficiently...))				try {						if (cleanupOnStart) {					// we're restarting the server (probably after a shutdown					// exception), so we need to clean up first.						// Close and remove sessions on runQueue.						for (int i = 0; i < runQueue.size(); i++)							((Session)runQueue.get(i)).close();						runQueue.clear();						// Close and remove DRDAConnThreads on threadList.						for (int i = 0; i < threadList.size(); i++)							((DRDAConnThread)threadList.get(i)).close();						threadList.clear();						freeThreads = 0;						// Unload driver, then restart the server.						cloudscapeDriver = null;	// so it gets collected.						System.gc();					}					// start the server.					Class.forName(CLOUDSCAPE_DRIVER).newInstance();					cloudscapeDriver = DriverManager.getDriver(Attribute.PROTOCOL);				}				catch (Exception e) {					consolePropertyMessage("DRDA_LoadException.S", e.getMessage());				}				cleanupOnStart = true;				this.restartFlag = !this.restartFlag;			}			// else, multiple threads hit this synchronize block at the same			// time, but one of them already executed it--so all others just			// return and do nothing (no need to restart the server multiple			// times in a row).		}	}	/**	 * Shutdown a network server	 *	 * @exception Exception	throws an exception if an error occurs	 */	public void shutdown()		throws Exception	{		setUpSocket();		writeCommandHeader(COMMAND_SHUTDOWN);		send();		readResult();		// Wait up to 10 seconds for things to really shut down		// need a quiet ping so temporarily disable the logwriter		PrintWriter savWriter = logWriter;		setLogWriter(null);		int ntry;		for (ntry = 0; ntry < SHUTDOWN_CHECK_ATTEMPTS; ntry++)		{			Thread.sleep(SHUTDOWN_CHECK_INTERVAL);			try {				ping();			} catch (Exception e) 			{				// as soon as we can't ping return				if (ntry == SHUTDOWN_CHECK_ATTEMPTS)					consolePropertyMessage("DRDA_ShutdownError.S", new String [] {						Integer.toString(portNumber), 						hostArg}); 				break;			}		}		logWriter= savWriter;		return;	}	/*	 Shutdown the server directly (If you have the original object)	 No Network communication needed.	*/	public void directShutdown() 	{		shutdown = true;		synchronized(shutdownSync) {									// wake up the server thread			shutdownSync.notifyAll();		}			}	/**	 */	public boolean isServerStarted() throws Exception	{		try {			ping();		}		catch (Exception e) {			return false;		}		return true;	}	public void ping() throws Exception	{		// database no longer used, but don't change the protocol 		// in case we add		// authorization  later.		String database = null; // no longer used but don't change the protocol		String user = null;		String password = null;			setUpSocket();			writeCommandHeader(COMMAND_TESTCONNECTION);			writeLDString(database);			writeLDString(user);			writeLDString(password);			send();			readResult();	}	/**	 * Turn tracing on or off for all sessions	 *	 * @param on			true to turn tracing on, false to turn tracing off	 *	 * @exception Exception	throws an exception if an error occurs	 */	public void trace(boolean on)		throws Exception	{		trace(0, on);	}	/**	 * Turn tracing on or off for one session or all sessions	 *	 * @param connNum	the connNum of the session, 0 if all sessions	 * @param on			true to turn tracing on, false to turn tracing off	 *	 * @exception Exception	throws an exception if an error occurs	 */	public void trace(int connNum, boolean on)		throws Exception	{		setUpSocket();		writeCommandHeader(COMMAND_TRACE);		commandOs.writeInt(connNum);		writeByte(on ? 1 : 0);		send();		readResult();		consoleTraceMessage(connNum, on);	}	/**	 * Print trace change message to console	 *	 * @param on			true to print tracing on, false to print tracing off	 *	 * @exception Exception	throws an exception if an error occurs	 */	private void consoleTraceMessage(int connNum, boolean on)		throws Exception	{		if (connNum == 0)			consolePropertyMessage("DRDA_TraceChangeAll.I", on ? "DRDA_ON.I" : "DRDA_OFF.I");		else		{			String[] args = new String[2];			args[0] = on ? "DRDA_ON.I" : "DRDA_OFF.I";			args[1] = new Integer(connNum).toString();			consolePropertyMessage("DRDA_TraceChangeOne.I", args);		}	}	/**	 * Turn logging connections on or off. When logging is turned on a message is	 * written to derby.log each time a connection connects or disconnects.	 *	 * @param on			true to turn on, false to turn  off	 *	 * @exception Exception	throws an exception if an error occurs	 */	public void logConnections(boolean on)		throws Exception	{		setUpSocket();		writeCommandHeader(COMMAND_LOGCONNECTIONS);		writeByte(on ? 1 : 0);		send();		readResult();	}	/**	 *@see NetworkServerControl#setTraceDirectory	 */	public void sendSetTraceDirectory(String traceDirectory)		throws Exception	{		setUpSocket();		writeCommandHeader(COMMAND_TRACEDIRECTORY);		writeLDString(traceDirectory);		send();		readResult();	}	/**	 *@see NetworkServerControl#getSysinfo	 */	public String sysinfo()		throws Exception	{		setUpSocket();		writeCommandHeader(COMMAND_SYSINFO);		send();		return readStringReply("DRDA_SysInfoError.S");	}	/**	 *@see NetworkServerControl#runtimeinfo	 */	public String runtimeInfo()	throws Exception 	{		setUpSocket();		writeCommandHeader(COMMAND_RUNTIME_INFO);		send();		return readStringReply("DRDA_RuntimeInfoError.S");	}	/**	 * Display usage information	 *	 */	public void usage()	{		try {		for (int i = 1; i <= NO_USAGE_MSGS; i++)

⌨️ 快捷键说明

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