networkservercontrolimpl.java

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

JAVA
2,300
字号
/*   Derby - Class org.apache.derby.impl.drda.NetworkServerControlImpl   Copyright 2002, 2004 The Apache Software Foundation or its licensors, as applicable.   Licensed under the Apache License, Version 2.0 (the "License");   you may not use this file except in compliance with the License.   You may obtain a copy of the License at      http://www.apache.org/licenses/LICENSE-2.0   Unless required by applicable law or agreed to in writing, software   distributed under the License is distributed on an "AS IS" BASIS,   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   See the License for the specific language governing permissions and   limitations under the License. */package org.apache.derby.impl.drda;import java.io.IOException;import java.io.InputStream;import java.io.File;import java.io.FileInputStream;import java.io.OutputStream;import java.io.PrintStream;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.DataOutputStream;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;import java.net.ServerSocket;import java.net.Socket;import java.net.InetAddress;import java.net.UnknownHostException;import java.sql.Connection;import java.sql.Driver;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;import java.sql.SQLException;import java.sql.SQLWarning;import java.util.Enumeration;import java.util.ArrayList;import java.util.Hashtable;import java.util.Locale;import java.util.Properties;import java.util.StringTokenizer;import java.util.Vector;import java.security.AccessController;import java.security.PrivilegedAction;import java.security.PrivilegedActionException;import java.security.PrivilegedExceptionAction;import org.apache.derby.iapi.reference.Attribute;import org.apache.derby.iapi.reference.Property;import org.apache.derby.iapi.services.info.ProductGenusNames;import org.apache.derby.iapi.services.info.ProductVersionHolder;import org.apache.derby.iapi.services.info.JVMInfo;import org.apache.derby.iapi.reference.SQLState;import org.apache.derby.impl.jdbc.EmbedSQLException;import org.apache.derby.iapi.jdbc.DRDAServerStarter;import org.apache.derby.iapi.tools.i18n.LocalizedResource;import org.apache.derby.iapi.tools.i18n.LocalizedOutput;import org.apache.derby.iapi.services.property.PropertyUtil;import org.apache.derby.iapi.services.sanity.SanityManager;import org.apache.derby.iapi.services.i18n.MessageService;import org.apache.derby.iapi.services.monitor.Monitor;import org.apache.derby.iapi.util.StringUtil;import org.apache.derby.drda.NetworkServerControl;/** 		NetworkServerControlImpl does all the work for NetworkServerControl	@see NetworkServerControl for description*/public final class NetworkServerControlImpl {	private final static int NO_USAGE_MSGS= 12;	private final static String [] COMMANDS = 	{"start","shutdown","trace","tracedirectory","ping", 	 "logconnections", "sysinfo", "runtimeinfo",  "maxthreads", "timeslice"};	// number of required arguments for each command	private final static int [] COMMAND_ARGS =	{0, 0, 1, 1, 0, 1, 0, 0, 1, 1};	private final static int COMMAND_START = 0;	private final static int COMMAND_SHUTDOWN = 1;	private final static int COMMAND_TRACE = 2;	private final static int COMMAND_TRACEDIRECTORY = 3;	private final static int COMMAND_TESTCONNECTION = 4;	private final static int COMMAND_LOGCONNECTIONS = 5;	private final static int COMMAND_SYSINFO = 6;	private final static int COMMAND_RUNTIME_INFO = 7;	private final static int COMMAND_MAXTHREADS = 8;	private final static int COMMAND_TIMESLICE = 9;	private final static int COMMAND_PROPERTIES = 10;	private final static int COMMAND_UNKNOWN = -1;	private final static String [] DASHARGS =	{"p","d","u","ld","ea","ep", "b", "h", "s"};	private final static int DASHARG_PORT = 0;	private final static int DASHARG_DATABASE = 1;	private final static int DASHARG_USER = 2;	private final static int DASHARG_LOADSYSIBM = 3;	private final static int DASHARG_ENCALG = 4;	private final static int DASHARG_ENCPRV = 5;	private final static int DASHARG_BOOTPASSWORD = 6;	private final static int DASHARG_HOST = 7;	private final static int DASHARG_SESSION = 8;	// command protocol version - you need to increase this number each time	// the command protocol changes 	private final static int PROTOCOL_VERSION = 1;	private final static String COMMAND_HEADER = "CMD:";	private final static String REPLY_HEADER = "RPY:";	private final static int REPLY_HEADER_LENGTH = REPLY_HEADER.length();	private final static int OK = 0;	private final static int WARNING = 1;	private final static int ERROR = 2;	private final static int SQLERROR = 3;	private final static int SQLWARNING = 4;	private final static String DRDA_PROP_MESSAGES = "org.apache.derby.loc.drda.messages";	private final static String DRDA_PROP_DEBUG = "derby.drda.debug";	private final static String CLOUDSCAPE_DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";	public final static String UNEXPECTED_ERR = "Unexpected exception";	private final static int MIN_MAXTHREADS = -1;	private final static int MIN_TIMESLICE = -1;	private final static int USE_DEFAULT = -1;	private final static int DEFAULT_MAXTHREADS = 0; //for now create whenever needed	private final static int DEFAULT_TIMESLICE = 0;	//for now never yield   private final static String DEFAULT_HOST = "localhost";	private final static String DRDA_MSG_PREFIX = "DRDA_";	private final static String DEFAULT_LOCALE= "en";	private final static String DEFAULT_LOCALE_COUNTRY="US";	// Check up to 10 seconds to see if shutdown occurred	private final static int SHUTDOWN_CHECK_ATTEMPTS = 20;	private final static int SHUTDOWN_CHECK_INTERVAL= 500;	// maximum reply size	private final static int MAXREPLY = 32767;	// Application Server Attributes.	protected static String att_srvclsnm;	protected final static String ATT_SRVNAM = "NetworkServerControl";	protected static String att_extnam;	protected static String att_srvrlslv; 	protected static String prdId;	private static String buildNumber;	// we will use single or mixed, not double byte to reduce traffic on the	// wire, this is in keeping with JCC	// Note we specify UTF8 for the single byte encoding even though it can	// be multi-byte.	protected final static int CCSIDSBC = 1208; //use UTF8	protected final static int CCSIDMBC = 1208; //use UTF8	protected final static String DEFAULT_ENCODING = "UTF8"; // use UTF8 for writing	protected final static int DEFAULT_CCSID = 1208;	protected final static byte SPACE_CHAR = 32;															// Application Server manager levels - this needs to be in sync	// with CodePoint.MGR_CODEPOINTS	protected final static int [] MGR_LEVELS = { 7, // AGENT												 4,	// CCSID Manager												 0, // CNMAPPC not implemented												 0, // CMNSYNCPT not implemented												 5, // CMNTCPIP												 0, // DICTIONARY												 7, // RDB												 0, // RSYNCMGR												 7, // SECMGR												 7, // SQLAM												 0, // SUPERVISOR												 0, // SYNCPTMGR												 7  // XAMGR												};													protected PrintWriter logWriter;                        // console	protected PrintWriter cloudscapeLogWriter;              // derby.log	private static Driver cloudscapeDriver;	// error types	private final static int ERRTYPE_SEVERE = 1;	private final static int ERRTYPE_USER = 2;	private final static int ERRTYPE_INFO = 3;	private final static int ERRTYPE_UNKNOWN = -1;	// command argument information	private Vector commandArgs = new Vector();	private String databaseArg;	private String userArg;	private String passwordArg;	private String bootPasswordArg;	private String encAlgArg;	private String encPrvArg;	private String hostArg = DEFAULT_HOST;		private InetAddress hostAddress;	private int sessionArg;	// Used to debug memory in SanityManager.DEBUG mode	private memCheck mc;	// reply buffer	private byte [] replyBuffer;		private int replyBufferCount;	//length of reply	private int replyBufferPos;		//current position in reply	//	// server configuration	//	// static values - set at start can't be changed once server has started	private int	portNumber = NetworkServerControl.DEFAULT_PORTNUMBER;	// port server listens to	// configurable values	private String traceDirectory;		// directory to place trace files in	private Object traceDirectorySync = new Object();// object to use for syncing	private boolean traceAll;			// trace all sessions	private Object traceAllSync = new Object();	// object to use for syncing reading										// and changing trace all	private Object serverStartSync = new Object();	// for syncing start of server.	private boolean logConnections;		// log connect and disconnects	private Object logConnectionsSync = new Object(); // object to use for syncing 										// logConnections value	private int minThreads;				// default minimum number of connection threads	private int maxThreads;				// default maximum number of connection threads	private Object threadsSync = new Object(); // object to use for syncing reading										// and changing default min and max threads	private int timeSlice;				// default time slice of a session to a thread	private Object timeSliceSync = new Object();// object to use for syncing reading										// and changing timeSlice	private boolean keepAlive = true;   // keepAlive value for client socket 	private int minPoolSize;			//minimum pool size for pooled connections	private int maxPoolSize;			//maximum pool size for pooled connections	private Object poolSync = new Object();	// object to use for syning reading	protected boolean debugOutput = false;	private boolean cleanupOnStart = false;	// Should we clean up when starting the server?	private boolean restartFlag = false;	//	// variables for a client command session	//	private Socket clientSocket = null;	private InputStream clientIs = null;	private OutputStream clientOs = null;	private ByteArrayOutputStream byteArrayOs = new ByteArrayOutputStream();	private DataOutputStream commandOs = new DataOutputStream(byteArrayOs);		private Object shutdownSync = new Object();	private boolean shutdown;	private int connNum;		// number of connections since server started	private ServerSocket serverSocket;	private NetworkServerControlImpl serverInstance;	private LocalizedResource langUtil;	public String clientLocale;	ArrayList  localAddresses; // list of local addresses for checking admin	                              // commands. 	// open sessions	private Hashtable sessionTable = new Hashtable();	// current session	private Session currentSession;	// DRDAConnThreads	private Vector threadList = new Vector();	// queue of sessions waiting for a free thread - the queue is managed	// in a simple first come, first serve manner - no priorities	private Vector runQueue = new Vector();	// number of DRDAConnThreads waiting for something to do	private int freeThreads;	// known application requesters	private Hashtable appRequesterTable = new Hashtable();	// accessed by inner classes for privileged action	private String propertyFileName;	private Runnable acceptClients;			// constructor	public NetworkServerControlImpl() throws Exception	{		init();		getPropertyInfo();    }	/**	 * Internal constructor for NetworkServerControl API. 	 * @param address - InetAddress to listen on, May not be null.  Throws NPE if null	 * @param portNumber - portNumber to listen on, -1 use propert or default.	 * @exception throw Exception on error	 * @see NetworkServerControl	 */	public NetworkServerControlImpl(InetAddress address, int portNumber) throws Exception	{		init();		getPropertyInfo();		this.hostAddress = address;		this.portNumber = (portNumber <= 0) ?			this.portNumber: portNumber;		this.hostArg = address.getHostAddress();	}    private void init() throws Exception    {        // adjust the application in accordance with derby.ui.locale and derby.ui.codeset		langUtil = new LocalizedResource(null,null,DRDA_PROP_MESSAGES);		serverInstance = this;				//set Server attributes to be used in EXCSAT		ProductVersionHolder myPVH = getNetProductVersionHolder();		att_extnam = ATT_SRVNAM + " " + java.lang.Thread.currentThread().getName();				att_srvclsnm = myPVH.getProductName();		String majorStr = String.valueOf(myPVH.getMajorVersion());		String minorStr = String.valueOf(myPVH.getMinorVersion());		// Maintenance version. Server protocol version.		// Only changed if client needs to recognize a new server version.		String drdaMaintStr = String.valueOf(myPVH.getDrdaMaintVersion());		// PRDID format as JCC expects it: CSSMMmx		// MM = major version		// mm = minor version		// x = drda MaintenanceVersion		prdId = "CSS";		if (majorStr.length() == 1)			prdId += "0";		prdId += majorStr;		if (minorStr.length() == 1)			prdId += "0";		prdId += minorStr;				prdId += drdaMaintStr;		att_srvrlslv = prdId + "/" + myPVH.getVersionBuildString(false);				if (SanityManager.DEBUG)		{			if (majorStr.length() > 2  || 				minorStr.length() > 2 || 				drdaMaintStr.length() > 1)				SanityManager.THROWASSERT("version values out of expected range  for PRDID");		}		buildNumber = myPVH.getBuildNumber();	}    private PrintWriter makePrintWriter( OutputStream out)    {		if (out != null)			return new PrintWriter(out, true /* flush the buffer at the end of each line */);		else			return null;    }	protected static Driver getDriver()	{		return cloudscapeDriver;	}		/********************************************************************************	 * Implementation of NetworkServerControl API	 * The server commands throw exceptions for errors, so that users can handle	 * them themselves in addition to having the errors written to the console	 * and possibly derby.log.  To turn off logging the errors to the console,	 * set the output writer to null.	 ********************************************************************************/	/**	 * Set the output stream for console messages	 * If this is set to null, no messages will be written to the console	 *	 * @param outWriter	output stream for console messages	 */	public void setLogWriter(PrintWriter outWriter)	{		logWriter = outWriter;    }		/**	 * Write an error message to console output stream	 * and throw an exception for this error	 *	 * @param msg	error message	 * @exception Exception	 */	public void consoleError(String msg)		throws Exception	{		consoleMessage(msg);		throw new Exception(msg);	}	/**	 * Write an exception to console output stream,	 * but only if debugOutput is true.	 *	 * @param e	exception 	 */	public void consoleExceptionPrint(Exception e)	{		if (debugOutput == true)			consoleExceptionPrintTrace(e);		return;	}	/**	 * Write an exception (with trace) to console	 * output stream.	 *	 * @param e	exception 	 */	public void consoleExceptionPrintTrace(Throwable e)	{		consoleMessage(e.getMessage());		if (logWriter != null)		{			synchronized (logWriter) {				e.printStackTrace(logWriter);			}		}		else		{			e.printStackTrace();		}				if (cloudscapeLogWriter != null)		{			synchronized(cloudscapeLogWriter) {				e.printStackTrace(cloudscapeLogWriter);			}		}	}

⌨️ 快捷键说明

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