db-derby-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From kmars...@apache.org
Subject svn commit: r1370674 [6/12] - in /db/derby/code/trunk/java/drda/org/apache/derby: drda/ impl/drda/
Date Wed, 08 Aug 2012 06:54:47 GMT
Modified: db/derby/code/trunk/java/drda/org/apache/derby/impl/drda/DRDAConnThread.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/drda/org/apache/derby/impl/drda/DRDAConnThread.java?rev=1370674&r1=1370673&r2=1370674&view=diff
==============================================================================
--- db/derby/code/trunk/java/drda/org/apache/derby/impl/drda/DRDAConnThread.java (original)
+++ db/derby/code/trunk/java/drda/org/apache/derby/impl/drda/DRDAConnThread.java Wed Aug  8 06:54:46 2012
@@ -77,104 +77,104 @@ import org.apache.derby.jdbc.InternalDri
 class DRDAConnThread extends Thread {
 
     private static final String leftBrace = "{";
-	private static final String rightBrace = "}";
-	private static final byte NULL_VALUE = (byte)0xff;
-	private static final String SYNTAX_ERR = "42X01";
+    private static final String rightBrace = "}";
+    private static final byte NULL_VALUE = (byte)0xff;
+    private static final String SYNTAX_ERR = "42X01";
 
-	// Manager Level 3 constant.
-	private static final int MGRLVL_3 = 0x03;
+    // Manager Level 3 constant.
+    private static final int MGRLVL_3 = 0x03;
 
-	// Manager Level 4 constant.
-	private static final int MGRLVL_4 = 0x04;
+    // Manager Level 4 constant.
+    private static final int MGRLVL_4 = 0x04;
 
-	// Manager Level 5 constant.
-	private static final int MGRLVL_5 = 0x05;
+    // Manager Level 5 constant.
+    private static final int MGRLVL_5 = 0x05;
 
-	// Manager level 6 constant.
-	private static final int MGRLVL_6 = 0x06;
+    // Manager level 6 constant.
+    private static final int MGRLVL_6 = 0x06;
 
-	// Manager Level 7 constant.
-	private static final int MGRLVL_7 = 0x07;
+    // Manager Level 7 constant.
+    private static final int MGRLVL_7 = 0x07;
 
 
-	// Commit or rollback UOWDSP values
-	private static final int COMMIT = 1;
-	private static final int ROLLBACK = 2;
+    // Commit or rollback UOWDSP values
+    private static final int COMMIT = 1;
+    private static final int ROLLBACK = 2;
 
 
-	private int correlationID;
-	private InputStream sockis;
-	private OutputStream sockos;
-	private DDMReader reader;
-	private DDMWriter writer;
-	private DRDAXAProtocol xaProto;
+    private int correlationID;
+    private InputStream sockis;
+    private OutputStream sockos;
+    private DDMReader reader;
+    private DDMWriter writer;
+    private DRDAXAProtocol xaProto;
 
-	private static int [] ACCRDB_REQUIRED = {CodePoint.RDBACCCL, 
-											 CodePoint.CRRTKN,
-											 CodePoint.PRDID,
-											 CodePoint.TYPDEFNAM,
-											 CodePoint.TYPDEFOVR};
+    private static int [] ACCRDB_REQUIRED = {CodePoint.RDBACCCL, 
+                                             CodePoint.CRRTKN,
+                                             CodePoint.PRDID,
+                                             CodePoint.TYPDEFNAM,
+                                             CodePoint.TYPDEFOVR};
 
-	private static int MAX_REQUIRED_LEN = 5;
+    private static int MAX_REQUIRED_LEN = 5;
 
-	private int currentRequiredLength = 0;
-	private int [] required = new int[MAX_REQUIRED_LEN];
+    private int currentRequiredLength = 0;
+    private int [] required = new int[MAX_REQUIRED_LEN];
 
 
-	private NetworkServerControlImpl server;			// server who created me
-	private Session	session;	// information about the session
+    private NetworkServerControlImpl server;            // server who created me
+    private Session    session;    // information about the session
     /** Time slice for this thread. */
     private volatile long timeSlice;
     /** Whether or not to log connections. */
     private volatile boolean logConnections;
 
-	private boolean	sendWarningsOnCNTQRY = false;	// Send Warnings for SELECT if true
+    private boolean    sendWarningsOnCNTQRY = false;    // Send Warnings for SELECT if true
     /** End this thread. */
     private volatile boolean close;
-	private static HeaderPrintWriter logStream;
-	private AppRequester appRequester;	// pointer to the application requester
-										// for the session being serviced
-	private Database database; 	// pointer to the current database
-	private int sqlamLevel;		// SQLAM Level - determines protocol
+    private static HeaderPrintWriter logStream;
+    private AppRequester appRequester;    // pointer to the application requester
+                                        // for the session being serviced
+    private Database database;     // pointer to the current database
+    private int sqlamLevel;        // SQLAM Level - determines protocol
 
-	// DRDA diagnostic level, DIAGLVL0 by default 
-	private byte diagnosticLevel = (byte)0xF0; 
+    // DRDA diagnostic level, DIAGLVL0 by default 
+    private byte diagnosticLevel = (byte)0xF0; 
 
-	// manager processing
+    // manager processing
     private List<Integer> unknownManagers;
     private List<Integer> knownManagers;
 
-	// database accessed failed
-	private SQLException databaseAccessException;
+    // database accessed failed
+    private SQLException databaseAccessException;
 
-	// these fields are needed to feed back to jcc about a statement/procedure's PKGNAMCSN
-	/** The value returned by the previous call to
-	 * <code>parsePKGNAMCSN()</code>. */
-	private Pkgnamcsn prevPkgnamcsn = null;
-	/** Current RDB Package Name. */
-	private DRDAString rdbnam = null;
-	/** Current RDB Collection Identifier. */
-	private DRDAString rdbcolid = null;
-	/** Current RDB Package Identifier. */
-	private DRDAString pkgid = null;
-	/** Current RDB Package Consistency Token. */
-	private DRDAString pkgcnstkn = null;
-	/** Current RDB Package Section Number. */
-	private int pkgsn;
+    // these fields are needed to feed back to jcc about a statement/procedure's PKGNAMCSN
+    /** The value returned by the previous call to
+     * <code>parsePKGNAMCSN()</code>. */
+    private Pkgnamcsn prevPkgnamcsn = null;
+    /** Current RDB Package Name. */
+    private DRDAString rdbnam = null;
+    /** Current RDB Collection Identifier. */
+    private DRDAString rdbcolid = null;
+    /** Current RDB Package Identifier. */
+    private DRDAString pkgid = null;
+    /** Current RDB Package Consistency Token. */
+    private DRDAString pkgcnstkn = null;
+    /** Current RDB Package Section Number. */
+    private int pkgsn;
 
     private final static String TIMEOUT_STATEMENT = "SET STATEMENT_TIMEOUT ";
 
     private int pendingStatementTimeout; // < 0 means no pending timeout to set
 
-	// this flag is for an execute statement/procedure which actually returns a result set;
-	// do not commit the statement, otherwise result set is closed
+    // this flag is for an execute statement/procedure which actually returns a result set;
+    // do not commit the statement, otherwise result set is closed
 
-	// for decryption
-	private static DecryptionManager decryptionManager;
+    // for decryption
+    private static DecryptionManager decryptionManager;
 
-	// public key generated by Deffie-Hellman algorithm, to be passed to the encrypter,
-	// as well as used to initialize the cipher
-	private byte[] myPublicKey;
+    // public key generated by Deffie-Hellman algorithm, to be passed to the encrypter,
+    // as well as used to initialize the cipher
+    private byte[] myPublicKey;
 
     // generated target seed to be used to generate the password substitute
     // as part of SECMEC_USRSSBPWD security mechanism
@@ -205,8 +205,8 @@ class DRDAConnThread extends Thread {
     // and therefore we know we won't be trying to load the class during
     // shutdown. See DERBY-1338 for more background, including pointers
     // to the apparent classloader bug in the JVM.
-	private static final DRDAProtocolExceptionInfo dummy =
-		new DRDAProtocolExceptionInfo(0,0,0,false);
+    private static final DRDAProtocolExceptionInfo dummy =
+        new DRDAProtocolExceptionInfo(0,0,0,false);
     /**
      * Tells if the reset / connect request is a deferred request.
      * This information is used to work around a bug (DERBY-3596) in a
@@ -220,76 +220,76 @@ class DRDAConnThread extends Thread {
      */
     private boolean deferredReset = false;
 
-	// constructor
-	/**
-	 * Create a new Thread for processing session requests
-	 *
-	 * @param session Session requesting processing
-	 * @param server  Server starting thread
-	 * @param timeSlice timeSlice for thread
-	 * @param logConnections
-	 **/
-
-	DRDAConnThread(Session session, NetworkServerControlImpl server, 
-						  long timeSlice,
-						  boolean logConnections) {
+    // constructor
+    /**
+     * Create a new Thread for processing session requests
+     *
+     * @param session Session requesting processing
+     * @param server  Server starting thread
+     * @param timeSlice timeSlice for thread
+     * @param logConnections
+     **/
+
+    DRDAConnThread(Session session, NetworkServerControlImpl server, 
+                          long timeSlice,
+                          boolean logConnections) {
         // Use a more meaningful name for this thread.
         super(NetworkServerControlImpl.getUniqueThreadName("DRDAConnThread"));
 
-		this.session = session;
-		this.server = server;
-		this.timeSlice = timeSlice;
-		this.logConnections = logConnections;
+        this.session = session;
+        this.server = server;
+        this.timeSlice = timeSlice;
+        this.logConnections = logConnections;
         this.pendingStatementTimeout = -1;
-		initialize();
+        initialize();
     }
 
-	/**
-	 * Main routine for thread, loops until the thread is closed
-	 * Gets a session, does work for the session
-	 */
+    /**
+     * Main routine for thread, loops until the thread is closed
+     * Gets a session, does work for the session
+     */
     @Override
     public void run() {
-		if (SanityManager.DEBUG) {
-			trace("Starting new connection thread");
+        if (SanityManager.DEBUG) {
+            trace("Starting new connection thread");
         }
 
-		Session prevSession;
-		while(!closed())
-		{
-
-			// get a new session
-			prevSession = session;
-			session = server.getNextSession(session);
-			if (session == null) {
-				close();
-            }
-
-			if (closed()) {
-				break;
-            }
-
-			if (session != prevSession)
-			{
-				initializeForSession();
-			}
-			try {
-				long timeStart = System.currentTimeMillis();
-
-				switch (session.state)
-				{
-					case Session.INIT:
-						sessionInitialState();
-						if (session == null) {
-							break;
+        Session prevSession;
+        while(!closed())
+        {
+
+            // get a new session
+            prevSession = session;
+            session = server.getNextSession(session);
+            if (session == null) {
+                close();
+            }
+
+            if (closed()) {
+                break;
+            }
+
+            if (session != prevSession)
+            {
+                initializeForSession();
+            }
+            try {
+                long timeStart = System.currentTimeMillis();
+
+                switch (session.state)
+                {
+                    case Session.INIT:
+                        sessionInitialState();
+                        if (session == null) {
+                            break;
                         }
                         // else fallthrough
-					case Session.ATTEXC:
-					case Session.SECACC:
-					case Session.CHKSEC:
-						long currentTimeSlice;
+                    case Session.ATTEXC:
+                    case Session.SECACC:
+                    case Session.CHKSEC:
+                        long currentTimeSlice;
 
-						do {
+                        do {
                             try {
                                 processCommands();
                             } catch (DRDASocketTimeoutException ste) {
@@ -298,26 +298,26 @@ class DRDAConnThread extends Thread {
                                 // DDMReader.fill(), which will happen
                                 // only when timeSlice is set.
                             }
-							currentTimeSlice = getTimeSlice();
-						} while ((currentTimeSlice <= 0)  || 
-							(System.currentTimeMillis() - timeStart < currentTimeSlice));
-
-						break;
-					default:
-						// this is an error
-						agentError("Session in invalid state:" + session.state);
-				}
-			} catch (Exception e) {
-				if (e instanceof DRDAProtocolException && 
-						((DRDAProtocolException)e).isDisconnectException())
-				{
-				 	// client went away - this is O.K. here
-					closeSession();
-				}
-				else
-				{
-					handleException(e);
-				}
+                            currentTimeSlice = getTimeSlice();
+                        } while ((currentTimeSlice <= 0)  || 
+                            (System.currentTimeMillis() - timeStart < currentTimeSlice));
+
+                        break;
+                    default:
+                        // this is an error
+                        agentError("Session in invalid state:" + session.state);
+                }
+            } catch (Exception e) {
+                if (e instanceof DRDAProtocolException && 
+                        ((DRDAProtocolException)e).isDisconnectException())
+                {
+                     // client went away - this is O.K. here
+                    closeSession();
+                }
+                else
+                {
+                    handleException(e);
+                }
             } catch (Error error) {
                 // Do as little as possible, but try to cut loose the client
                 // to avoid that it hangs in a socket read-call.
@@ -338,149 +338,149 @@ class DRDAConnThread extends Thread {
                     throw error;
                 }
             }
-		}
-		if (SanityManager.DEBUG) {
-			trace("Ending connection thread");
-        }
-		server.removeThread(this);
-
-	}
-	/**
-	 * Get input stream
-	 *
-	 * @return input stream
-	 */
-	protected InputStream getInputStream()
-	{
-		return sockis;
-	}
-
-	/**
-	 * Get output stream
-	 *
-	 * @return output stream
-	 */
-	protected OutputStream getOutputStream()
-	{
-		return sockos;
-	}
-
-	/**
-	 *  get DDMReader
-	 * @return DDMReader for this thread
-	 */
-	protected DDMReader getReader()
-	{
-		return reader;
-	}
-	
-	/** 
-	 * get  DDMWriter 
-	 * @return DDMWriter for this thread
-	 */
-	protected DDMWriter getWriter()
-	{
-		return writer;
-	}
-
-	/**
-	 * Get correlation id
-	 *
-	 * @return correlation id
-	 */
-	protected int getCorrelationID ()
-	{
-		return correlationID;
-	}
-
-	/**
-	 * Get session we are working on
-	 *
-	 * @return session
-	 */
-	protected Session getSession()
-	{
-		return session;
-	}
-
-	/**
-	 * Get Database we are working on
-	 *
-	 * @return database
-	 */
-	protected Database getDatabase()
-	{
-		return database;
-	}
-	/**
-	 * Get server
-	 *
-	 * @return server
-	 */
-	protected NetworkServerControlImpl getServer()
-	{
-		return server;
-	}
-	/**
-	 * Get correlation token
-	 *
-	 * @return crrtkn
-	 */
-	protected byte[] getCrrtkn()
-	{
+        }
+        if (SanityManager.DEBUG) {
+            trace("Ending connection thread");
+        }
+        server.removeThread(this);
+
+    }
+    /**
+     * Get input stream
+     *
+     * @return input stream
+     */
+    protected InputStream getInputStream()
+    {
+        return sockis;
+    }
+
+    /**
+     * Get output stream
+     *
+     * @return output stream
+     */
+    protected OutputStream getOutputStream()
+    {
+        return sockos;
+    }
+
+    /**
+     *  get DDMReader
+     * @return DDMReader for this thread
+     */
+    protected DDMReader getReader()
+    {
+        return reader;
+    }
+    
+    /** 
+     * get  DDMWriter 
+     * @return DDMWriter for this thread
+     */
+    protected DDMWriter getWriter()
+    {
+        return writer;
+    }
+
+    /**
+     * Get correlation id
+     *
+     * @return correlation id
+     */
+    protected int getCorrelationID ()
+    {
+        return correlationID;
+    }
+
+    /**
+     * Get session we are working on
+     *
+     * @return session
+     */
+    protected Session getSession()
+    {
+        return session;
+    }
+
+    /**
+     * Get Database we are working on
+     *
+     * @return database
+     */
+    protected Database getDatabase()
+    {
+        return database;
+    }
+    /**
+     * Get server
+     *
+     * @return server
+     */
+    protected NetworkServerControlImpl getServer()
+    {
+        return server;
+    }
+    /**
+     * Get correlation token
+     *
+     * @return crrtkn
+     */
+    protected byte[] getCrrtkn()
+    {
         return (database == null) ? null : database.crrtkn;
-	}
-	/**
-	 * Get database name
-	 *
-	 * @return database name
-	 */
-	protected String getDbName()
-	{
+    }
+    /**
+     * Get database name
+     *
+     * @return database name
+     */
+    protected String getDbName()
+    {
         return (database == null) ? null : database.getDatabaseName();
-	}
-	/**
-	 * Close DRDA  connection thread
-	 */
-	protected void close()
-	{
+    }
+    /**
+     * Close DRDA  connection thread
+     */
+    protected void close()
+    {
         close = true;
-	}
+    }
 
-	/**
-	 * Set logging of connections
-	 * 
-	 * @param value value to set for logging connections
-	 */
-	protected void setLogConnections(boolean value)
-	{
+    /**
+     * Set logging of connections
+     * 
+     * @param value value to set for logging connections
+     */
+    protected void setLogConnections(boolean value)
+    {
         logConnections = value;
-	}
-	/**
-	 * Set time slice value
-	 *
-	 * @param value new value for time slice
-	 */
-	protected void setTimeSlice(long value)
-	{
+    }
+    /**
+     * Set time slice value
+     *
+     * @param value new value for time slice
+     */
+    protected void setTimeSlice(long value)
+    {
         timeSlice = value;
-	}
-	/**
-	 * Indicate a communications failure
-	 * 
-	 * @param arg1 - info about the communications failure
-	 * @param arg2 - info about the communications failure
-	 * @param arg3 - info about the communications failure
-	 * @param arg4 - info about the communications failure
-	 *
-	 * @exception DRDAProtocolException  disconnect exception always thrown
-	 */
-	protected void markCommunicationsFailure(String arg1, String arg2, String arg3,
-		String arg4) throws DRDAProtocolException
-	{
-	    markCommunicationsFailure(null,arg1,arg2,arg3, arg4);
+    }
+    /**
+     * Indicate a communications failure
+     * 
+     * @param arg1 - info about the communications failure
+     * @param arg2 - info about the communications failure
+     * @param arg3 - info about the communications failure
+     * @param arg4 - info about the communications failure
+     *
+     * @exception DRDAProtocolException  disconnect exception always thrown
+     */
+    protected void markCommunicationsFailure(String arg1, String arg2, String arg3,
+        String arg4) throws DRDAProtocolException
+    {
+        markCommunicationsFailure(null,arg1,arg2,arg3, arg4);
 
-	}
+    }
         
         
         /**
@@ -506,76 +506,76 @@ class DRDAConnThread extends Thread {
             throw DRDAProtocolException.newDisconnectException(this,oa);
         }
 
-	/**
-	 * Syntax error
-	 *
-	 * @param errcd		Error code
-	 * @param cpArg  code point value
-	 * @exception DRDAProtocolException
-	 */
-
-	protected  void throwSyntaxrm(int errcd, int cpArg)
-		throws DRDAProtocolException
-	{
-		throw new
-			DRDAProtocolException(DRDAProtocolException.DRDA_Proto_SYNTAXRM,
-								  this,
-								  cpArg,
-								  errcd);
-	}
-	/**
-	 * Agent error - something very bad happened
-	 *
-	 * @param msg	Message describing error
-	 *
-	 * @exception DRDAProtocolException  newAgentError always thrown
-	 */
-	protected void agentError(String msg) throws DRDAProtocolException
-	{
-		throw DRDAProtocolException.newAgentError(this, CodePoint.SVRCOD_PRMDMG, 
+    /**
+     * Syntax error
+     *
+     * @param errcd        Error code
+     * @param cpArg  code point value
+     * @exception DRDAProtocolException
+     */
+
+    protected  void throwSyntaxrm(int errcd, int cpArg)
+        throws DRDAProtocolException
+    {
+        throw new
+            DRDAProtocolException(DRDAProtocolException.DRDA_Proto_SYNTAXRM,
+                                  this,
+                                  cpArg,
+                                  errcd);
+    }
+    /**
+     * Agent error - something very bad happened
+     *
+     * @param msg    Message describing error
+     *
+     * @exception DRDAProtocolException  newAgentError always thrown
+     */
+    protected void agentError(String msg) throws DRDAProtocolException
+    {
+        throw DRDAProtocolException.newAgentError(this, CodePoint.SVRCOD_PRMDMG, 
             getDbName(), msg);
-	}
-	/**
-	 * Missing code point
-	 *
-	 * @param codePoint  code point value
-	 * @exception DRDAProtocolException
-	 */
-	protected void missingCodePoint(int codePoint) throws DRDAProtocolException
-	{
-		throwSyntaxrm(CodePoint.SYNERRCD_REQ_OBJ_NOT_FOUND, codePoint);
-	}
-	/**
-	 * Print a line to the DB2j log
-	 *
-	 * @param dbname  database name
-	 * @param drdaID	DRDA identifier
-	 * @param msg	message
-	 */
-	protected static void println2Log(String dbname, String drdaID, String msg)
-	{
-		if (logStream == null) {
-			logStream = Monitor.getStream();
-        }
-
-		if (dbname != null)
-		{
-			int endOfName = dbname.indexOf(';');
-			if (endOfName != -1) {
-				dbname = dbname.substring(0, endOfName);
-            }
-		}
-		logStream.printlnWithHeader("(DATABASE = " + dbname + "), (DRDAID = " + drdaID + "), " + msg);
-	}
-	/**
-	 * Write RDBNAM
-	 *
-	 * @param rdbnam 	database name
-	 * @exception DRDAProtocolException
-	 */
-	protected void writeRDBNAM(String rdbnam)
-		throws DRDAProtocolException
-	{
+    }
+    /**
+     * Missing code point
+     *
+     * @param codePoint  code point value
+     * @exception DRDAProtocolException
+     */
+    protected void missingCodePoint(int codePoint) throws DRDAProtocolException
+    {
+        throwSyntaxrm(CodePoint.SYNERRCD_REQ_OBJ_NOT_FOUND, codePoint);
+    }
+    /**
+     * Print a line to the DB2j log
+     *
+     * @param dbname  database name
+     * @param drdaID    DRDA identifier
+     * @param msg    message
+     */
+    protected static void println2Log(String dbname, String drdaID, String msg)
+    {
+        if (logStream == null) {
+            logStream = Monitor.getStream();
+        }
+
+        if (dbname != null)
+        {
+            int endOfName = dbname.indexOf(';');
+            if (endOfName != -1) {
+                dbname = dbname.substring(0, endOfName);
+            }
+        }
+        logStream.printlnWithHeader("(DATABASE = " + dbname + "), (DRDAID = " + drdaID + "), " + msg);
+    }
+    /**
+     * Write RDBNAM
+     *
+     * @param rdbnam     database name
+     * @exception DRDAProtocolException
+     */
+    protected void writeRDBNAM(String rdbnam)
+        throws DRDAProtocolException
+    {
         CcsidManager currentManager = writer.getCurrentCcsidManager();
 
         int len = Math.max(
@@ -584,93 +584,93 @@ class DRDAConnThread extends Thread {
 
         /* Write the string padded */
         writer.writeScalarPaddedString(CodePoint.RDBNAM, rdbnam, len);
-	}
-	/***************************************************************************
-	 *                   Private methods
-	 ***************************************************************************/
-
-	/**
-	 * Initialize class
-	 */
-	private void initialize()
-	{
-		// set input and output sockets
-		// this needs to be done before creating reader
-		sockis = session.sessionInput;
-		sockos = session.sessionOutput;
-
-		reader = new DDMReader(this, session.dssTrace);
-		writer = new DDMWriter(this, session.dssTrace);
-		
-		/* At this stage we can initialize the strings as we have
-		 * the CcsidManager for the DDMWriter. */
-		rdbnam = new DRDAString(writer);
-	    rdbcolid = new DRDAString(writer);
-	    pkgid = new DRDAString(writer);
-	    pkgcnstkn = new DRDAString(writer);
-	}
-
-	/**
-	 * Initialize for a new session
-	 */
-	private void initializeForSession()
-	{
-		// set input and output sockets
-		sockis = session.sessionInput;
-		sockos = session.sessionOutput;
-
-		// intialize reader and writer
-		reader.initialize(this, session.dssTrace);
-		writer.reset(session.dssTrace);
-
-		// initialize local pointers to session info
-		database = session.database;
-		appRequester = session.appRequester;
-
-		// set sqlamLevel
-		if (session.state == Session.ATTEXC) {
-			sqlamLevel = appRequester.getManagerLevel(CodePoint.SQLAM);
+    }
+    /***************************************************************************
+     *                   Private methods
+     ***************************************************************************/
+
+    /**
+     * Initialize class
+     */
+    private void initialize()
+    {
+        // set input and output sockets
+        // this needs to be done before creating reader
+        sockis = session.sessionInput;
+        sockos = session.sessionOutput;
+
+        reader = new DDMReader(this, session.dssTrace);
+        writer = new DDMWriter(this, session.dssTrace);
+        
+        /* At this stage we can initialize the strings as we have
+         * the CcsidManager for the DDMWriter. */
+        rdbnam = new DRDAString(writer);
+        rdbcolid = new DRDAString(writer);
+        pkgid = new DRDAString(writer);
+        pkgcnstkn = new DRDAString(writer);
+    }
+
+    /**
+     * Initialize for a new session
+     */
+    private void initializeForSession()
+    {
+        // set input and output sockets
+        sockis = session.sessionInput;
+        sockos = session.sessionOutput;
+
+        // intialize reader and writer
+        reader.initialize(this, session.dssTrace);
+        writer.reset(session.dssTrace);
+
+        // initialize local pointers to session info
+        database = session.database;
+        appRequester = session.appRequester;
+
+        // set sqlamLevel
+        if (session.state == Session.ATTEXC) {
+            sqlamLevel = appRequester.getManagerLevel(CodePoint.SQLAM);
         }
 
         /* All sessions MUST start as EBCDIC */
         reader.setEbcdicCcsid();
         writer.setEbcdicCcsid();
-	}
-	/**      
-	 * In initial state for a session, 
-	 * determine whether this is a command
-	 * session or a DRDA protocol session.  A command session is for changing
-	 * the configuration of the Net server, e.g., turning tracing on
-	 * If it is a command session, process the command and close the session.
-	 * If it is a DRDA session, exchange server attributes and change session
-	 * state.
-	 */
-	private void sessionInitialState()
-		throws Exception
-	{
-		// process NetworkServerControl commands - if it is not either valid protocol  let the 
-		// DRDA error handling handle it
-		if (reader.isCmd())
-		{
-			try {
-				server.processCommands(reader, writer, session);
-				// reset reader and writer
-				reader.initialize(this, null);
-				writer.reset(null);
-				closeSession();
+    }
+    /**      
+     * In initial state for a session, 
+     * determine whether this is a command
+     * session or a DRDA protocol session.  A command session is for changing
+     * the configuration of the Net server, e.g., turning tracing on
+     * If it is a command session, process the command and close the session.
+     * If it is a DRDA session, exchange server attributes and change session
+     * state.
+     */
+    private void sessionInitialState()
+        throws Exception
+    {
+        // process NetworkServerControl commands - if it is not either valid protocol  let the 
+        // DRDA error handling handle it
+        if (reader.isCmd())
+        {
+            try {
+                server.processCommands(reader, writer, session);
+                // reset reader and writer
+                reader.initialize(this, null);
+                writer.reset(null);
+                closeSession();
             } catch (InterruptedException ie) {
                 throw ie;
-			} catch (Throwable t) {
+            } catch (Throwable t) {
                 server.consoleExceptionPrintTrace(t);
-			}
+            }
 
-		}
-		else
-		{
-			// exchange attributes with application requester
-			exchangeServerAttributes();
-		}
-	}
+        }
+        else
+        {
+            // exchange attributes with application requester
+            exchangeServerAttributes();
+        }
+    }
 
     /**
      * Cleans up and closes a result set if an exception is thrown
@@ -707,150 +707,150 @@ class DRDAConnThread extends Thread {
         errorInChain(sqle);
     }
 
-	/**
-	 * Process DRDA commands we can receive once server attributes have been
-	 * exchanged.
-	 *
-	 * @exception DRDAProtocolException
-	 */
-	private void processCommands() throws DRDAProtocolException
-	{
-		DRDAStatement stmt = null;
-		boolean PRPSQLSTTfailed = false;
-		boolean checkSecurityCodepoint = session.requiresSecurityCodepoint();
-		do
-		{
-			correlationID = reader.readDssHeader();
-			int codePoint = reader.readLengthAndCodePoint( false );
-			int writerMark = writer.markDSSClearPoint();
-			
-			if (checkSecurityCodepoint) {
-				verifyInOrderACCSEC_SECCHK(codePoint,session.getRequiredSecurityCodepoint());
-            }
-
-			switch(codePoint)
-			{
-				case CodePoint.CNTQRY:
-					try{
-						stmt = parseCNTQRY();
-						if (stmt != null)
-						{
-							writeQRYDTA(stmt);
-							if (stmt.rsIsClosed())
-							{
-								writeENDQRYRM(CodePoint.SVRCOD_WARNING);
-								writeNullSQLCARDobject();
-							}
-							// Send any warnings if JCC can handle them
-							checkWarning(null, null, stmt.getResultSet(), 0, false, sendWarningsOnCNTQRY);
+    /**
+     * Process DRDA commands we can receive once server attributes have been
+     * exchanged.
+     *
+     * @exception DRDAProtocolException
+     */
+    private void processCommands() throws DRDAProtocolException
+    {
+        DRDAStatement stmt = null;
+        boolean PRPSQLSTTfailed = false;
+        boolean checkSecurityCodepoint = session.requiresSecurityCodepoint();
+        do
+        {
+            correlationID = reader.readDssHeader();
+            int codePoint = reader.readLengthAndCodePoint( false );
+            int writerMark = writer.markDSSClearPoint();
+            
+            if (checkSecurityCodepoint) {
+                verifyInOrderACCSEC_SECCHK(codePoint,session.getRequiredSecurityCodepoint());
+            }
+
+            switch(codePoint)
+            {
+                case CodePoint.CNTQRY:
+                    try{
+                        stmt = parseCNTQRY();
+                        if (stmt != null)
+                        {
+                            writeQRYDTA(stmt);
+                            if (stmt.rsIsClosed())
+                            {
+                                writeENDQRYRM(CodePoint.SVRCOD_WARNING);
+                                writeNullSQLCARDobject();
+                            }
+                            // Send any warnings if JCC can handle them
+                            checkWarning(null, null, stmt.getResultSet(), 0, false, sendWarningsOnCNTQRY);
                             writePBSD();
-						}
-					}
-					catch(SQLException e)
-					{
-						// if we got a SQLException we need to clean up and
-						// close the result set Beetle 4758
-						cleanUpAndCloseResultSet(stmt, e, writerMark);
-					}
-					break;
-				case CodePoint.EXCSQLIMM:
-					try {
-						int updateCount = parseEXCSQLIMM();
-						// RESOLVE: checking updateCount is not sufficient
-						// since it will be 0 for creates, we need to know when
-						// any logged changes are made to the database
-						// Not getting this right for JCC is probably O.K., this
-						// will probably be a problem for ODBC and XA
-						// The problem is that JDBC doesn't provide this information
-						// so we would have to expand the JDBC API or call a
-						// builtin method to check(expensive)
-						// For now we will assume that every execute immediate
-						// does an update (that is the most conservative thing)
-						if (database.RDBUPDRM_sent == false)
-						{
-							writeRDBUPDRM();
-						}
-
-						// we need to set update count in SQLCARD
-						checkWarning(null, database.getDefaultStatement().getStatement(),
-							null, updateCount, true, true);
+                        }
+                    }
+                    catch(SQLException e)
+                    {
+                        // if we got a SQLException we need to clean up and
+                        // close the result set Beetle 4758
+                        cleanUpAndCloseResultSet(stmt, e, writerMark);
+                    }
+                    break;
+                case CodePoint.EXCSQLIMM:
+                    try {
+                        int updateCount = parseEXCSQLIMM();
+                        // RESOLVE: checking updateCount is not sufficient
+                        // since it will be 0 for creates, we need to know when
+                        // any logged changes are made to the database
+                        // Not getting this right for JCC is probably O.K., this
+                        // will probably be a problem for ODBC and XA
+                        // The problem is that JDBC doesn't provide this information
+                        // so we would have to expand the JDBC API or call a
+                        // builtin method to check(expensive)
+                        // For now we will assume that every execute immediate
+                        // does an update (that is the most conservative thing)
+                        if (database.RDBUPDRM_sent == false)
+                        {
+                            writeRDBUPDRM();
+                        }
+
+                        // we need to set update count in SQLCARD
+                        checkWarning(null, database.getDefaultStatement().getStatement(),
+                            null, updateCount, true, true);
                         writePBSD();
-					} catch (SQLException e)
-					{
-						writer.clearDSSesBackToMark(writerMark);
-						writeSQLCARDs(e, 0);
-						errorInChain(e);
-					}
-					break;
+                    } catch (SQLException e)
+                    {
+                        writer.clearDSSesBackToMark(writerMark);
+                        writeSQLCARDs(e, 0);
+                        errorInChain(e);
+                    }
+                    break;
 
-				case CodePoint.EXCSQLSET:
-					try {
+                case CodePoint.EXCSQLSET:
+                    try {
                         if (parseEXCSQLSET()) {
                             // all went well.
                             writeSQLCARDs(null, 0);
                         }
-					}
-					catch (SQLWarning w)
-					{
-						writeSQLCARD(w, 0, 0);
-					}
-					catch (SQLException e)
-					{
-						writer.clearDSSesBackToMark(writerMark);
-						writeSQLCARDs(e, 0);
-						errorInChain(e);
-					}
-					break;
-					
-				case CodePoint.PRPSQLSTT:
-					int sqldaType;
-					PRPSQLSTTfailed = false;
-					try {
-						database.getConnection().clearWarnings();
-						sqldaType = parsePRPSQLSTT();
+                    }
+                    catch (SQLWarning w)
+                    {
+                        writeSQLCARD(w, 0, 0);
+                    }
+                    catch (SQLException e)
+                    {
+                        writer.clearDSSesBackToMark(writerMark);
+                        writeSQLCARDs(e, 0);
+                        errorInChain(e);
+                    }
+                    break;
+                    
+                case CodePoint.PRPSQLSTT:
+                    int sqldaType;
+                    PRPSQLSTTfailed = false;
+                    try {
+                        database.getConnection().clearWarnings();
+                        sqldaType = parsePRPSQLSTT();
                         database.getCurrentStatement().sqldaType = sqldaType;
-						if (sqldaType > 0) {	// do write SQLDARD
-							writeSQLDARD(database.getCurrentStatement(),
-										 (sqldaType ==  CodePoint.TYPSQLDA_LIGHT_OUTPUT),
-										 database.getConnection().getWarnings());
+                        if (sqldaType > 0) {    // do write SQLDARD
+                            writeSQLDARD(database.getCurrentStatement(),
+                                         (sqldaType ==  CodePoint.TYPSQLDA_LIGHT_OUTPUT),
+                                         database.getConnection().getWarnings());
                         } else {
-							checkWarning(database.getConnection(), null, null, 0, true, true);
+                            checkWarning(database.getConnection(), null, null, 0, true, true);
                         }
 
-					} catch (SQLException e)
-					{
-						writer.clearDSSesBackToMark(writerMark);
-						writeSQLCARDs(e, 0, true);
-						PRPSQLSTTfailed = true;
-						errorInChain(e);
-					}
-					break;
-				case CodePoint.OPNQRY:
-					try {
-						if (PRPSQLSTTfailed) {
-							// read the command objects
-							// for ps with parameter
-							// Skip objects/parameters
-							skipRemainder(true);
-
-							// If we failed to prepare, then we fail
-							// to open, which  means OPNQFLRM.
-							writeOPNQFLRM(null);
-							break;
-						}
-						Pkgnamcsn pkgnamcsn = parseOPNQRY();
-						if (pkgnamcsn != null)
-						{
-							stmt = database.getDRDAStatement(pkgnamcsn);
-							PreparedStatement ps = stmt.getPreparedStatement();
-							ps.clearWarnings();
+                    } catch (SQLException e)
+                    {
+                        writer.clearDSSesBackToMark(writerMark);
+                        writeSQLCARDs(e, 0, true);
+                        PRPSQLSTTfailed = true;
+                        errorInChain(e);
+                    }
+                    break;
+                case CodePoint.OPNQRY:
+                    try {
+                        if (PRPSQLSTTfailed) {
+                            // read the command objects
+                            // for ps with parameter
+                            // Skip objects/parameters
+                            skipRemainder(true);
+
+                            // If we failed to prepare, then we fail
+                            // to open, which  means OPNQFLRM.
+                            writeOPNQFLRM(null);
+                            break;
+                        }
+                        Pkgnamcsn pkgnamcsn = parseOPNQRY();
+                        if (pkgnamcsn != null)
+                        {
+                            stmt = database.getDRDAStatement(pkgnamcsn);
+                            PreparedStatement ps = stmt.getPreparedStatement();
+                            ps.clearWarnings();
                             if (pendingStatementTimeout >= 0) {
                                 ps.setQueryTimeout(pendingStatementTimeout);
                                 pendingStatementTimeout = -1;
                             }
-							stmt.execute();
-							writeOPNQRYRM(false, stmt);
-							checkWarning(null, ps, null, 0, false, true);
+                            stmt.execute();
+                            writeOPNQRYRM(false, stmt);
+                            checkWarning(null, ps, null, 0, false, true);
 
                             long sentVersion = stmt.versionCounter;
                             long currentVersion =
@@ -873,464 +873,464 @@ class DRDAConnThread extends Thread {
                                 // this point in the protocol.
                                 writeSQLDARD(stmt, true, null);
                             }
-							writeQRYDSC(stmt, false);
+                            writeQRYDSC(stmt, false);
 
-							stmt.rsSuspend();
+                            stmt.rsSuspend();
 
-							if (stmt.getQryprctyp() == CodePoint.LMTBLKPRC &&
-									stmt.getQryrowset() != 0) {
-								// The DRDA spec allows us to send
-								// QRYDTA here if there are no LOB
-								// columns.
-								DRDAResultSet drdars =
-									stmt.getCurrentDrdaResultSet();
-								try {
-									if (drdars != null &&
-										!drdars.hasLobColumns()) {
-										writeQRYDTA(stmt);
-									}
-								} catch (SQLException sqle) {
-									cleanUpAndCloseResultSet(stmt, sqle,
-															 writerMark);
-								}
-							}
-						}
-                        writePBSD();
-					}
-					catch (SQLException e)
-					{
-						writer.clearDSSesBackToMark(writerMark);
-						// The fix for DERBY-1196 removed code 
-						// here to close the prepared statement 
-						// if OPNQRY failed.
-							writeOPNQFLRM(e);
-					}
-					break;
-				case CodePoint.RDBCMM:
-					try
-					{
-						if (SanityManager.DEBUG) {
-							trace("Received commit");
-                        }
-						if (!database.getConnection().getAutoCommit())
-						{
-							database.getConnection().clearWarnings();
-							database.commit();
-							writeENDUOWRM(COMMIT);
-							checkWarning(database.getConnection(), null, null, 0, true, true);
-						}
-						// we only want to write one of these per transaction
-						// so set to false in preparation for next command
-						database.RDBUPDRM_sent = false;
-					}
-					catch (SQLException e)
-					{
-						writer.clearDSSesBackToMark(writerMark);
-						// Even in case of error, we have to write the ENDUOWRM.
-						writeENDUOWRM(COMMIT);
-						writeSQLCARDs(e, 0);
-						errorInChain(e);
-					}
-					break;
-				case CodePoint.RDBRLLBCK:
-					try
-					{
-						if (SanityManager.DEBUG) {
-							trace("Received rollback");
-                        }
-						database.getConnection().clearWarnings();
-						database.rollback();
-						writeENDUOWRM(ROLLBACK);
-						checkWarning(database.getConnection(), null, null, 0, true, true);
-						// we only want to write one of these per transaction
-						// so set to false in preparation for next command
-						database.RDBUPDRM_sent = false;
-					}
-					catch (SQLException e)
-					{
-						writer.clearDSSesBackToMark(writerMark);
-						// Even in case of error, we have to write the ENDUOWRM.
-						writeENDUOWRM(ROLLBACK);
-						writeSQLCARDs(e, 0);
-						errorInChain(e);
-					}
-					break;
-				case CodePoint.CLSQRY:
-					try{
-						stmt = parseCLSQRY();
-						stmt.rsClose();
-						writeSQLCARDs(null, 0);
-					}
-					catch (SQLException e)
-					{
-						writer.clearDSSesBackToMark(writerMark);
-						writeSQLCARDs(e, 0);
-						errorInChain(e);
-					}
-					break;
-				case CodePoint.EXCSAT:
-					parseEXCSAT();
-					writeEXCSATRD();
-					break;
-				case CodePoint.ACCSEC:
-					int securityCheckCode = parseACCSEC();
-					writeACCSECRD(securityCheckCode); 
-					
-					/* ACCSECRD is the last reply that is mandatorily in EBCDIC */
-					if (appRequester.supportsUtf8Ccsid()) {
-					    switchToUtf8();
-					} else {
-					    /* This thread might serve several requests.
-					     * Revert if not supported by current client. */
-					    switchToEbcdic();
-					}
-					checkSecurityCodepoint = true;
-					break;
-				case CodePoint.SECCHK:
-					if (parseDRDAConnection()) {
-						// security all checked and connection ok
-						checkSecurityCodepoint = false;
-                    }
-					break;
-				/* since we don't support sqlj, we won't get bind commands from jcc, we
-				 * might get it from ccc; just skip them.
-				 */
-				case CodePoint.BGNBND:
-					reader.skipBytes();
-					writeSQLCARDs(null, 0);
-					break;
-				case CodePoint.BNDSQLSTT:
-					reader.skipBytes();
-					parseSQLSTTDss();
-					writeSQLCARDs(null, 0);
-					break;
-				case CodePoint.SQLSTTVRB:
-					// optional
-					reader.skipBytes();
-					break;
-				case CodePoint.ENDBND:
-					reader.skipBytes();
-					writeSQLCARDs(null, 0);
-					break;
-				case CodePoint.DSCSQLSTT:
-					if (PRPSQLSTTfailed) {
-						reader.skipBytes();
-						writeSQLCARDs(null, 0);
-						break;
-					}
-					try {
-						boolean rtnOutput = parseDSCSQLSTT();
-						writeSQLDARD(database.getCurrentStatement(), rtnOutput,
-									 null);
-						
-					} catch (SQLException e)
-					{
-						writer.clearDSSesBackToMark(writerMark);
-						server.consoleExceptionPrint(e);
-						try {
-							writeSQLDARD(database.getCurrentStatement(), true, e);
-						} catch (SQLException e2) {	// should not get here since doing nothing with ps
-							agentError("Why am I getting another SQLException?");
-						}
-						errorInChain(e);
-					}
-					break;
-				case CodePoint.EXCSQLSTT:
-					if (PRPSQLSTTfailed) {
-						// Skip parameters too if they are chained Beetle 4867
-						skipRemainder(true);
-						writeSQLCARDs(null, 0);
-						break;
-					}
-					try {
-						parseEXCSQLSTT();
-
-						DRDAStatement curStmt = database.getCurrentStatement();
-						if (curStmt != null) {
-							curStmt.rsSuspend();
+                            if (stmt.getQryprctyp() == CodePoint.LMTBLKPRC &&
+                                    stmt.getQryrowset() != 0) {
+                                // The DRDA spec allows us to send
+                                // QRYDTA here if there are no LOB
+                                // columns.
+                                DRDAResultSet drdars =
+                                    stmt.getCurrentDrdaResultSet();
+                                try {
+                                    if (drdars != null &&
+                                        !drdars.hasLobColumns()) {
+                                        writeQRYDTA(stmt);
+                                    }
+                                } catch (SQLException sqle) {
+                                    cleanUpAndCloseResultSet(stmt, sqle,
+                                                             writerMark);
+                                }
+                            }
                         }
                         writePBSD();
-					} catch (SQLException e)
-					{
-						skipRemainder(true);
-						writer.clearDSSesBackToMark(writerMark);
-						if (SanityManager.DEBUG) 
-						{
-							server.consoleExceptionPrint(e);
-						}
-						writeSQLCARDs(e, 0);
-						errorInChain(e);
-					}
-					break;
-				case CodePoint.SYNCCTL:
-					if (xaProto == null) {
-						xaProto = new DRDAXAProtocol(this);
-                    }
-					xaProto.parseSYNCCTL();
- 					try {
- 						writePBSD();
- 					} catch (SQLException se) {
-						server.consoleExceptionPrint(se);
- 						errorInChain(se);
- 					}
-					break;
-				default:
-					codePointNotSupported(codePoint);
-			}
-
-            if (SanityManager.DEBUG) {
-                String cpStr = new CodePointNameTable().lookup(codePoint);
-                try {
-                    PiggyBackedSessionData pbsd =
-                            database.getPiggyBackedSessionData(false);
-                    // DERBY-3596
-                    // Don't perform this assert if a deferred reset is
-                    // happening or has recently taken place, because the
-                    // connection state has been changed under the feet of the
-                    // piggy-backing mechanism.
-                    if (!this.deferredReset && pbsd != null) {
-                        // Session data has already been piggy-backed. Refresh
-                        // the data from the connection, to make sure it has
-                        // not changed behind our back.
-                        pbsd.refresh();
-                        SanityManager.ASSERT(!pbsd.isModified(),
-                              "Unexpected PBSD modification: " + pbsd +
-                              " after codePoint " + cpStr);
                     }
-                    // Not having a pbsd here is ok. No data has been
-                    // piggy-backed and the client has no cached values.
-                    // If needed it will send an explicit request to get
-                    // session data
-                } catch (SQLException sqle) {
-                    server.consoleExceptionPrint(sqle);
-                    SanityManager.THROWASSERT("Unexpected exception after " +
-                            "codePoint "+cpStr, sqle);
-                }
-            }
-
-			// Set the correct chaining bits for whatever
-			// reply DSS(es) we just wrote.  If we've reached
-			// the end of the chain, this method will send
-			// the DSS(es) across.
-			finalizeChain();
-
-		}
-		while (reader.isChainedWithSameID() || reader.isChainedWithDiffID());
-	}
-
-	/**
-	 * If there's a severe error in the DDM chain, and if the header indicates
-	 * "terminate chain on error", we stop processing further commands in the chain
-	 * nor do we send any reply for them.  In accordance to this, a SQLERRRM message 
-	 * indicating the severe error must have been sent! (otherwise application requestor,
-	 * such as JCC, would not terminate the receiving of chain replies.)
-	 *
-	 * Each DRDA command is processed independently. DRDA defines no interdependencies
-	 * across chained commands. A command is processed the same when received within
-	 * a set of chained commands or received separately.  The chaining was originally
-	 * defined as a way to save network costs.
-	 *
- 	 * @param e		the SQLException raised
-	 * @exception	DRDAProtocolException
-	 */
-	private void errorInChain(SQLException e) throws DRDAProtocolException
-	{
-		if (reader.terminateChainOnErr() && (getExceptionSeverity(e) > CodePoint.SVRCOD_ERROR))
-		{
-			if (SanityManager.DEBUG) {
-                trace("terminating the chain on error...");
-            }
-			skipRemainder(false);
-		}
-	}
-
-	/**
-	 * Exchange server attributes with application requester
-	 *
-	 * @exception DRDAProtocolException
-	 */
-	private void exchangeServerAttributes()
-		throws  DRDAProtocolException
-	{
-		int codePoint;
-		correlationID = reader.readDssHeader();
-		if (SanityManager.DEBUG) {
-		  if (correlationID == 0)
-		  {
-		    SanityManager.THROWASSERT(
-					      "Unexpected value for correlationId = " + correlationID);
-		  }
-		}
-
-		codePoint = reader.readLengthAndCodePoint( false );
-
-		// The first code point in the exchange of attributes must be EXCSAT
-		if (codePoint != CodePoint.EXCSAT)
-		{
-			//Throw PRCCNVRM 
-			throw
-			    new DRDAProtocolException(DRDAProtocolException.DRDA_Proto_PRCCNVRM,
-										  this, codePoint,
-										  CodePoint.PRCCNVCD_EXCSAT_FIRST_AFTER_CONN);
-		}
-
-		parseEXCSAT();
-		writeEXCSATRD();
-		finalizeChain();
-		session.setState(Session.ATTEXC);
-	}
-	
-
-	private boolean parseDRDAConnection() throws DRDAProtocolException
-	{
-		int codePoint;
-		boolean sessionOK = true;
-
-
-		int securityCheckCode = parseSECCHK();
-		if (SanityManager.DEBUG) {
-            trace("*** SECCHKRM securityCheckCode is: " + securityCheckCode);
-        }
-		writeSECCHKRM(securityCheckCode);
-		//at this point if the security check failed, we're done, the session failed
-		if (securityCheckCode != 0)
-		{
-			return false;
-		}
-
-		correlationID = reader.readDssHeader();
-		codePoint = reader.readLengthAndCodePoint( false );
-		verifyRequiredObject(codePoint,CodePoint.ACCRDB);
-		int svrcod = parseACCRDB();
-
-		//If network server gets a null connection form InternalDriver, reply with
-		//RDBAFLRM and SQLCARD with null SQLException 
-		if(database.getConnection() == null && databaseAccessException == null){
-			writeRDBfailure(CodePoint.RDBAFLRM);
-			return false;
-		}		
-		
-		//if earlier we couldn't access the database
-		if (databaseAccessException != null)
-		{
-
-			//if the Database was not found we will try DS
-			int failureType = getRdbAccessErrorCodePoint();
-			if (failureType == CodePoint.RDBNFNRM 
-				|| failureType == CodePoint.RDBATHRM)
-			{
-				writeRDBfailure(failureType);
-			}
-			else
-			{
-				writeRDBfailure(CodePoint.RDBAFLRM);
-			}
-			return false;
-		}
-		else if (database.accessCount > 1 )	// already in conversation with database
-		{
-			writeRDBfailure(CodePoint.RDBACCRM);
-			return false;
-		}
-		else
-        {
-            writeACCRDBRM(svrcod);
-        }
-
-		// compare this application requester with previously stored
-		// application requesters and if we have already seen this one
-		// use stored application requester 
-		session.appRequester = server.getAppRequester(appRequester);
-		return sessionOK;
-	}
-
-	/**
-	 * Switch the DDMWriter and DDMReader to UTF8 IF supported
-	 */
-	private void switchToUtf8() {
-        writer.setUtf8Ccsid();
-        reader.setUtf8Ccsid();
-	}
-	
-	/**
-	 * Switch the DDMWriter and DDMReader to EBCDIC
-	 */
-	private void switchToEbcdic() {
-        writer.setEbcdicCcsid();
-        reader.setEbcdicCcsid();
-	}
-	
-	/**
-	 * Write RDB Failure
-	 *
-	 * Instance Variables
-	 * 	SVRCOD - Severity Code - required
-	 *	RDBNAM - Relational Database name - required
-	 *  SRVDGN - Server Diagnostics - optional (not sent for now)
- 	 *
-	 * @param	codePoint	codepoint of failure
-	 */
-	private void writeRDBfailure(int codePoint) throws DRDAProtocolException
-	{
-		writer.createDssReply();
-		writer.startDdm(codePoint);
-		writer.writeScalar2Bytes(CodePoint.SVRCOD, CodePoint.SVRCOD_ERROR);
-		writeRDBNAM(database.getDatabaseName());
-    	writer.endDdmAndDss();
-    	
-    	switch(codePoint){
-    		case CodePoint.RDBAFLRM:
-    			//RDBAFLRM requires TYPDEFNAM and TYPDEFOVR
-    			writer.createDssObject();
-    			writer.writeScalarString(CodePoint.TYPDEFNAM,
-    									 CodePoint.TYPDEFNAM_QTDSQLASC);
-    			writeTYPDEFOVR();
-    			writer.endDss();
-    		case CodePoint.RDBNFNRM:
-    		case CodePoint.RDBATHRM:
-    			writeSQLCARD(databaseAccessException, 0, 0);
-    		case CodePoint.RDBACCRM:
-    			//Ignore anything that was chained to the ACCRDB.
-    			skipRemainder(false);
-
-    			// Finalize chain state for whatever we wrote in
-    			// response to ACCRDB.
-    			finalizeChain();
-    			break;
-    	}
-    	
-	}
-
-	/* Check the database access exception and return the appropriate
-	   error codepoint.
-	   RDBNFNRM - Database not found
-	   RDBATHRM - Not Authorized
-	   RDBAFLRM - Access failure
-	   @return RDB Access codepoint 
-	           
-	*/
-
-	private int getRdbAccessErrorCodePoint()
-	{
-		String sqlState = databaseAccessException.getSQLState();
-		// These tests are ok since DATABASE_NOT_FOUND and 
-		// AUTH_INVALID_USER_NAME are not ambigious error codes (on the first
-		// five characters) in SQLState. If they were, we would have to
-		// perform a similar check as done in method isAuthenticationException
-		if (sqlState.regionMatches(0,SQLState.DATABASE_NOT_FOUND,0,5)) {
-			// RDB not found codepoint
-			return CodePoint.RDBNFNRM;
-		} else {
-			if (isAuthenticationException(databaseAccessException) ||
-				sqlState.regionMatches(0,SQLState.AUTH_INVALID_USER_NAME,0,5)) {
-				// Not Authorized To RDB reply message codepoint
-				return CodePoint.RDBATHRM;
-			} else {
-				// RDB Access Failed Reply Message codepoint
-				return CodePoint.RDBAFLRM;
-            }
-        }
-	}
+                    catch (SQLException e)
+                    {
+                        writer.clearDSSesBackToMark(writerMark);
+                        // The fix for DERBY-1196 removed code 
+                        // here to close the prepared statement 
+                        // if OPNQRY failed.
+                            writeOPNQFLRM(e);
+                    }
+                    break;
+                case CodePoint.RDBCMM:
+                    try
+                    {
+                        if (SanityManager.DEBUG) {
+                            trace("Received commit");
+                        }
+                        if (!database.getConnection().getAutoCommit())
+                        {
+                            database.getConnection().clearWarnings();
+                            database.commit();
+                            writeENDUOWRM(COMMIT);
+                            checkWarning(database.getConnection(), null, null, 0, true, true);
+                        }
+                        // we only want to write one of these per transaction
+                        // so set to false in preparation for next command
+                        database.RDBUPDRM_sent = false;
+                    }
+                    catch (SQLException e)
+                    {
+                        writer.clearDSSesBackToMark(writerMark);
+                        // Even in case of error, we have to write the ENDUOWRM.
+                        writeENDUOWRM(COMMIT);
+                        writeSQLCARDs(e, 0);
+                        errorInChain(e);
+                    }
+                    break;
+                case CodePoint.RDBRLLBCK:
+                    try
+                    {
+                        if (SanityManager.DEBUG) {
+                            trace("Received rollback");
+                        }
+                        database.getConnection().clearWarnings();
+                        database.rollback();
+                        writeENDUOWRM(ROLLBACK);
+                        checkWarning(database.getConnection(), null, null, 0, true, true);
+                        // we only want to write one of these per transaction
+                        // so set to false in preparation for next command
+                        database.RDBUPDRM_sent = false;
+                    }
+                    catch (SQLException e)
+                    {
+                        writer.clearDSSesBackToMark(writerMark);
+                        // Even in case of error, we have to write the ENDUOWRM.
+                        writeENDUOWRM(ROLLBACK);
+                        writeSQLCARDs(e, 0);
+                        errorInChain(e);
+                    }
+                    break;
+                case CodePoint.CLSQRY:
+                    try{
+                        stmt = parseCLSQRY();
+                        stmt.rsClose();
+                        writeSQLCARDs(null, 0);
+                    }
+                    catch (SQLException e)
+                    {
+                        writer.clearDSSesBackToMark(writerMark);
+                        writeSQLCARDs(e, 0);
+                        errorInChain(e);
+                    }
+                    break;
+                case CodePoint.EXCSAT:
+                    parseEXCSAT();
+                    writeEXCSATRD();
+                    break;
+                case CodePoint.ACCSEC:
+                    int securityCheckCode = parseACCSEC();
+                    writeACCSECRD(securityCheckCode); 
+                    
+                    /* ACCSECRD is the last reply that is mandatorily in EBCDIC */
+                    if (appRequester.supportsUtf8Ccsid()) {
+                        switchToUtf8();
+                    } else {
+                        /* This thread might serve several requests.
+                         * Revert if not supported by current client. */
+                        switchToEbcdic();
+                    }
+                    checkSecurityCodepoint = true;
+                    break;
+                case CodePoint.SECCHK:
+                    if (parseDRDAConnection()) {
+                        // security all checked and connection ok
+                        checkSecurityCodepoint = false;
+                    }
+                    break;
+                /* since we don't support sqlj, we won't get bind commands from jcc, we
+                 * might get it from ccc; just skip them.
+                 */
+                case CodePoint.BGNBND:
+                    reader.skipBytes();
+                    writeSQLCARDs(null, 0);
+                    break;
+                case CodePoint.BNDSQLSTT:
+                    reader.skipBytes();
+                    parseSQLSTTDss();
+                    writeSQLCARDs(null, 0);
+                    break;
+                case CodePoint.SQLSTTVRB:
+                    // optional
+                    reader.skipBytes();
+                    break;
+                case CodePoint.ENDBND:
+                    reader.skipBytes();
+                    writeSQLCARDs(null, 0);
+                    break;
+                case CodePoint.DSCSQLSTT:
+                    if (PRPSQLSTTfailed) {
+                        reader.skipBytes();
+                        writeSQLCARDs(null, 0);
+                        break;
+                    }
+                    try {
+                        boolean rtnOutput = parseDSCSQLSTT();
+                        writeSQLDARD(database.getCurrentStatement(), rtnOutput,
+                                     null);
+                        
+                    } catch (SQLException e)
+                    {
+                        writer.clearDSSesBackToMark(writerMark);
+                        server.consoleExceptionPrint(e);
+                        try {
+                            writeSQLDARD(database.getCurrentStatement(), true, e);
+                        } catch (SQLException e2) {    // should not get here since doing nothing with ps
+                            agentError("Why am I getting another SQLException?");
+                        }
+                        errorInChain(e);
+                    }
+                    break;
+                case CodePoint.EXCSQLSTT:
+                    if (PRPSQLSTTfailed) {
+                        // Skip parameters too if they are chained Beetle 4867
+                        skipRemainder(true);
+                        writeSQLCARDs(null, 0);
+                        break;
+                    }
+                    try {
+                        parseEXCSQLSTT();
+
+                        DRDAStatement curStmt = database.getCurrentStatement();
+                        if (curStmt != null) {
+                            curStmt.rsSuspend();
+                        }
+                        writePBSD();
+                    } catch (SQLException e)
+                    {
+                        skipRemainder(true);
+                        writer.clearDSSesBackToMark(writerMark);
+                        if (SanityManager.DEBUG) 
+                        {
+                            server.consoleExceptionPrint(e);
+                        }
+                        writeSQLCARDs(e, 0);
+                        errorInChain(e);
+                    }
+                    break;
+                case CodePoint.SYNCCTL:
+                    if (xaProto == null) {
+                        xaProto = new DRDAXAProtocol(this);
+                    }
+                    xaProto.parseSYNCCTL();
+                     try {
+                         writePBSD();
+                     } catch (SQLException se) {
+                        server.consoleExceptionPrint(se);
+                         errorInChain(se);
+                     }
+                    break;
+                default:
+                    codePointNotSupported(codePoint);
+            }
+
+            if (SanityManager.DEBUG) {
+                String cpStr = new CodePointNameTable().lookup(codePoint);
+                try {
+                    PiggyBackedSessionData pbsd =
+                            database.getPiggyBackedSessionData(false);
+                    // DERBY-3596
+                    // Don't perform this assert if a deferred reset is
+                    // happening or has recently taken place, because the
+                    // connection state has been changed under the feet of the
+                    // piggy-backing mechanism.
+                    if (!this.deferredReset && pbsd != null) {
+                        // Session data has already been piggy-backed. Refresh
+                        // the data from the connection, to make sure it has
+                        // not changed behind our back.
+                        pbsd.refresh();
+                        SanityManager.ASSERT(!pbsd.isModified(),
+                              "Unexpected PBSD modification: " + pbsd +
+                              " after codePoint " + cpStr);
+                    }
+                    // Not having a pbsd here is ok. No data has been
+                    // piggy-backed and the client has no cached values.
+                    // If needed it will send an explicit request to get
+                    // session data
+                } catch (SQLException sqle) {
+                    server.consoleExceptionPrint(sqle);
+                    SanityManager.THROWASSERT("Unexpected exception after " +
+                            "codePoint "+cpStr, sqle);
+                }
+            }
+
+            // Set the correct chaining bits for whatever
+            // reply DSS(es) we just wrote.  If we've reached
+            // the end of the chain, this method will send
+            // the DSS(es) across.
+            finalizeChain();
+
+        }
+        while (reader.isChainedWithSameID() || reader.isChainedWithDiffID());
+    }
+
+    /**
+     * If there's a severe error in the DDM chain, and if the header indicates
+     * "terminate chain on error", we stop processing further commands in the chain
+     * nor do we send any reply for them.  In accordance to this, a SQLERRRM message 
+     * indicating the severe error must have been sent! (otherwise application requestor,
+     * such as JCC, would not terminate the receiving of chain replies.)
+     *
+     * Each DRDA command is processed independently. DRDA defines no interdependencies
+     * across chained commands. A command is processed the same when received within
+     * a set of chained commands or received separately.  The chaining was originally
+     * defined as a way to save network costs.
+     *
+      * @param e        the SQLException raised
+     * @exception    DRDAProtocolException
+     */
+    private void errorInChain(SQLException e) throws DRDAProtocolException
+    {
+        if (reader.terminateChainOnErr() && (getExceptionSeverity(e) > CodePoint.SVRCOD_ERROR))
+        {
+            if (SanityManager.DEBUG) {
+                trace("terminating the chain on error...");
+            }
+            skipRemainder(false);
+        }
+    }
+
+    /**
+     * Exchange server attributes with application requester
+     *
+     * @exception DRDAProtocolException
+     */
+    private void exchangeServerAttributes()
+        throws  DRDAProtocolException
+    {
+        int codePoint;
+        correlationID = reader.readDssHeader();
+        if (SanityManager.DEBUG) {
+          if (correlationID == 0)
+          {
+            SanityManager.THROWASSERT(
+                          "Unexpected value for correlationId = " + correlationID);
+          }
+        }
+
+        codePoint = reader.readLengthAndCodePoint( false );
+
+        // The first code point in the exchange of attributes must be EXCSAT
+        if (codePoint != CodePoint.EXCSAT)
+        {
+            //Throw PRCCNVRM 
+            throw
+                new DRDAProtocolException(DRDAProtocolException.DRDA_Proto_PRCCNVRM,
+                                          this, codePoint,
+                                          CodePoint.PRCCNVCD_EXCSAT_FIRST_AFTER_CONN);
+        }
+
+        parseEXCSAT();
+        writeEXCSATRD();
+        finalizeChain();
+        session.setState(Session.ATTEXC);
+    }
+    
+
+    private boolean parseDRDAConnection() throws DRDAProtocolException
+    {
+        int codePoint;
+        boolean sessionOK = true;
+
+
+        int securityCheckCode = parseSECCHK();
+        if (SanityManager.DEBUG) {
+            trace("*** SECCHKRM securityCheckCode is: " + securityCheckCode);
+        }
+        writeSECCHKRM(securityCheckCode);
+        //at this point if the security check failed, we're done, the session failed
+        if (securityCheckCode != 0)
+        {
+            return false;
+        }
+
+        correlationID = reader.readDssHeader();
+        codePoint = reader.readLengthAndCodePoint( false );
+        verifyRequiredObject(codePoint,CodePoint.ACCRDB);
+        int svrcod = parseACCRDB();
+
+        //If network server gets a null connection form InternalDriver, reply with
+        //RDBAFLRM and SQLCARD with null SQLException 
+        if(database.getConnection() == null && databaseAccessException == null){
+            writeRDBfailure(CodePoint.RDBAFLRM);
+            return false;
+        }        
+        
+        //if earlier we couldn't access the database
+        if (databaseAccessException != null)
+        {
+
+            //if the Database was not found we will try DS
+            int failureType = getRdbAccessErrorCodePoint();
+            if (failureType == CodePoint.RDBNFNRM 
+                || failureType == CodePoint.RDBATHRM)
+            {
+                writeRDBfailure(failureType);
+            }
+            else
+            {
+                writeRDBfailure(CodePoint.RDBAFLRM);
+            }
+            return false;
+        }
+        else if (database.accessCount > 1 )    // already in conversation with database
+        {
+            writeRDBfailure(CodePoint.RDBACCRM);
+            return false;
+        }
+        else
+        {
+            writeACCRDBRM(svrcod);
+        }
+
+        // compare this application requester with previously stored
+        // application requesters and if we have already seen this one
+        // use stored application requester 
+        session.appRequester = server.getAppRequester(appRequester);
+        return sessionOK;
+    }
+
+    /**
+     * Switch the DDMWriter and DDMReader to UTF8 IF supported
+     */
+    private void switchToUtf8() {
+        writer.setUtf8Ccsid();
+        reader.setUtf8Ccsid();
+    }
+    
+    /**
+     * Switch the DDMWriter and DDMReader to EBCDIC
+     */
+    private void switchToEbcdic() {
+        writer.setEbcdicCcsid();
+        reader.setEbcdicCcsid();
+    }
+    
+    /**
+     * Write RDB Failure
+     *
+     * Instance Variables
+     *     SVRCOD - Severity Code - required
+     *    RDBNAM - Relational Database name - required
+     *  SRVDGN - Server Diagnostics - optional (not sent for now)
+      *
+     * @param    codePoint    codepoint of failure
+     */
+    private void writeRDBfailure(int codePoint) throws DRDAProtocolException
+    {
+        writer.createDssReply();
+        writer.startDdm(codePoint);
+        writer.writeScalar2Bytes(CodePoint.SVRCOD, CodePoint.SVRCOD_ERROR);
+        writeRDBNAM(database.getDatabaseName());
+        writer.endDdmAndDss();
+        
+        switch(codePoint){
+            case CodePoint.RDBAFLRM:
+                //RDBAFLRM requires TYPDEFNAM and TYPDEFOVR
+                writer.createDssObject();
+                writer.writeScalarString(CodePoint.TYPDEFNAM,
+                                         CodePoint.TYPDEFNAM_QTDSQLASC);
+                writeTYPDEFOVR();
+                writer.endDss();
+            case CodePoint.RDBNFNRM:
+            case CodePoint.RDBATHRM:
+                writeSQLCARD(databaseAccessException, 0, 0);
+            case CodePoint.RDBACCRM:
+                //Ignore anything that was chained to the ACCRDB.
+                skipRemainder(false);
+
+                // Finalize chain state for whatever we wrote in
+                // response to ACCRDB.
+                finalizeChain();
+                break;
+        }
+        
+    }
+
+    /* Check the database access exception and return the appropriate
+       error codepoint.
+       RDBNFNRM - Database not found
+       RDBATHRM - Not Authorized
+       RDBAFLRM - Access failure
+       @return RDB Access codepoint 
+               
+    */
+
+    private int getRdbAccessErrorCodePoint()
+    {
+        String sqlState = databaseAccessException.getSQLState();
+        // These tests are ok since DATABASE_NOT_FOUND and 
+        // AUTH_INVALID_USER_NAME are not ambigious error codes (on the first
+        // five characters) in SQLState. If they were, we would have to
+        // perform a similar check as done in method isAuthenticationException
+        if (sqlState.regionMatches(0,SQLState.DATABASE_NOT_FOUND,0,5)) {
+            // RDB not found codepoint
+            return CodePoint.RDBNFNRM;
+        } else {
+            if (isAuthenticationException(databaseAccessException) ||
+                sqlState.regionMatches(0,SQLState.AUTH_INVALID_USER_NAME,0,5)) {
+                // Not Authorized To RDB reply message codepoint
+                return CodePoint.RDBATHRM;
+            } else {
+                // RDB Access Failed Reply Message codepoint
+                return CodePoint.RDBAFLRM;
+            }
+        }
+    }
 
     /**
      * There are multiple reasons for not getting a connection, and
@@ -1392,39 +1392,39 @@ class DRDAConnThread extends Thread {
         return authFail;
     }
 
-	/**
-	 * Verify userId and password
-	 *
-	 * Username and password is verified by making a connection to the
-	 * database
-	 *
-	 * @return security check code, 0 is O.K.
-	 * @exception DRDAProtocolException
-	 */
-	private int verifyUserIdPassword() throws DRDAProtocolException
-	{
-		databaseAccessException = null;
+    /**
+     * Verify userId and password
+     *
+     * Username and password is verified by making a connection to the
+     * database
+     *
+     * @return security check code, 0 is O.K.
+     * @exception DRDAProtocolException
+     */
+    private int verifyUserIdPassword() throws DRDAProtocolException
+    {
+        databaseAccessException = null;
         return getConnFromDatabaseName();
-	}
+    }
 
-	/**
-	 * Get connection from a database name
-	 *
-	 * Username and password is verified by making a connection to the
-	 * database
-	 *
-	 * @return security check code, 0 is O.K.
-	 * @exception DRDAProtocolException
-	 */
-	private int getConnFromDatabaseName() throws DRDAProtocolException
-	{
-		Properties p = new Properties();
-		databaseAccessException = null;
-		//if we haven't got the correlation token yet, use session number for drdaID
-		if (session.drdaID == null) {
+    /**
+     * Get connection from a database name
+     *
+     * Username and password is verified by making a connection to the
+     * database
+     *
+     * @return security check code, 0 is O.K.
+     * @exception DRDAProtocolException
+     */
+    private int getConnFromDatabaseName() throws DRDAProtocolException
+    {
+        Properties p = new Properties();
+        databaseAccessException = null;
+        //if we haven't got the correlation token yet, use session number for drdaID
+        if (session.drdaID == null) {
             session.drdaID = leftBrace + session.connNum + rightBrace;
         }
-		p.put(Attribute.DRDAID_ATTR, session.drdaID);
+        p.put(Attribute.DRDAID_ATTR, session.drdaID);
 
         // We pass extra property information for the authentication provider
         // to successfully re-compute the substitute (hashed) password and
@@ -1453,101 +1453,101 @@ class DRDAConnThread extends Thread {
                                                 database.secTokenOut.length));
         }
             
-	 	try {
-			database.makeConnection(p);
-	  	} catch (SQLException se) {
-			databaseAccessException = se;
-			for (; se != null; se = se.getNextException())
-			{
-				if (SanityManager.DEBUG) {
+         try {
+            database.makeConnection(p);
+          } catch (SQLException se) {
+            databaseAccessException = se;
+            for (; se != null; se = se.getNextException())
+            {
+                if (SanityManager.DEBUG) {
                     trace(se.getMessage());
                 }
-	 			println2Log(database.getDatabaseName(), session.drdaID, se.getMessage());
-			}
+                 println2Log(database.getDatabaseName(), session.drdaID, se.getMessage());
+            }
+
+            if (isAuthenticationException(databaseAccessException)) {
+                // need to set the security check code based on the
+                // reason the connection was denied, Derby doesn't say
+                // whether the userid or password caused the problem,
+                // so we will just return userid invalid
+                return CodePoint.SECCHKCD_USERIDINVALID;
+            } else {
+                return 0;
+            }
+        }
+        catch (Exception e)
+        {
+            // If Derby has shut down for some reason,
+            // we will send  an agent error and then try to 
+            // get the driver loaded again.  We have to get
+            // rid of the client first in case they are holding
+            // the DriverManager lock.
+            println2Log(database.getDatabaseName(), session.drdaID, 
+                        "Driver not loaded"
+                        + e.getMessage());
+                try {
+                    agentError("Driver not loaded");
+                }
+                catch (DRDAProtocolException dpe)
+                {
+                    // Retry starting the server before rethrowing 
+                    // the protocol exception.  Then hopfully all
+                    // will be well when they try again.
+                    try {
+                        server.startNetworkServer();
+                    } catch (Exception re) {
+                        println2Log(database.getDatabaseName(), session.drdaID, "Failed attempt to reload driver " +re.getMessage()  );
+                    }
+                    throw dpe;
+                }
+        }
+        
+    
+        // Everything worked so log connection to the database.
+        if (getLogConnections()) {
+             println2Log(database.getDatabaseName(), session.drdaID,
+                "Apache Derby Network Server connected to database " +
+                        database.getDatabaseName());
+        }
+        return 0;
+    }
+
 
-			if (isAuthenticationException(databaseAccessException)) {
-				// need to set the security check code based on the
-				// reason the connection was denied, Derby doesn't say
-				// whether the userid or password caused the problem,
-				// so we will just return userid invalid
-				return CodePoint.SECCHKCD_USERIDINVALID;
-			} else {
-				return 0;
-			}
-		}
-		catch (Exception e)
-		{
-			// If Derby has shut down for some reason,
-			// we will send  an agent error and then try to 
-			// get the driver loaded again.  We have to get
-			// rid of the client first in case they are holding
-			// the DriverManager lock.
-			println2Log(database.getDatabaseName(), session.drdaID, 
-						"Driver not loaded"
-						+ e.getMessage());
-				try {
-					agentError("Driver not loaded");
-				}
-				catch (DRDAProtocolException dpe)
-				{
-					// Retry starting the server before rethrowing 
-					// the protocol exception.  Then hopfully all
-					// will be well when they try again.
-					try {
-						server.startNetworkServer();
-					} catch (Exception re) {
-						println2Log(database.getDatabaseName(), session.drdaID, "Failed attempt to reload driver " +re.getMessage()  );
-					}
-					throw dpe;
-				}
-		}
-		
-	
-		// Everything worked so log connection to the database.
-		if (getLogConnections()) {
-	 		println2Log(database.getDatabaseName(), session.drdaID,
-				"Apache Derby Network Server connected to database " +
-						database.getDatabaseName());
-        }
-		return 0;
-	}
-
-
-	/**
-	 * Parses EXCSAT (Exchange Server Attributes)
-	 * Instance variables
-	 *	EXTNAM(External Name)	- optional
-	 *  MGRLVLLS(Manager Levels) - optional
-	 *	SPVNAM(Supervisor Name) - optional
-	 *  SRVCLSNM(Server Class Name) - optional
-	 *  SRVNAM(Server Name) - optional, ignorable
-	 *  SRVRLSLV(Server Product Release Level) - optional, ignorable
-	 *
-	 * @exception DRDAProtocolException
-	 */
-	private void parseEXCSAT() throws DRDAProtocolException
-	{
-		int codePoint;
-		String strVal;
-
-		// There are three kinds of EXCSAT's we might get.
-		// 1) Initial Exchange attributes.
-		//    For this we need to initialize the apprequester.
-		//    Session state is set to ATTEXC and then the AR must 
-		//    follow up with ACCSEC and SECCHK to get the connection.
-		//  2) Send of EXCSAT as ping or mangager level adjustment. 
-		//     (see parseEXCSAT2())
-		//     For this we just ignore the EXCSAT objects that
-		//     are already set.
-		//  3) Send of EXCSAT for connection reset. (see parseEXCSAT2())
-		//     This is treated just like ping and will be followed up 
-		//     by an ACCSEC request if in fact it is a connection reset.
+    /**
+     * Parses EXCSAT (Exchange Server Attributes)
+     * Instance variables
+     *    EXTNAM(External Name)    - optional
+     *  MGRLVLLS(Manager Levels) - optional
+     *    SPVNAM(Supervisor Name) - optional
+     *  SRVCLSNM(Server Class Name) - optional
+     *  SRVNAM(Server Name) - optional, ignorable
+     *  SRVRLSLV(Server Product Release Level) - optional, ignorable
+     *
+     * @exception DRDAProtocolException
+     */
+    private void parseEXCSAT() throws DRDAProtocolException
+    {
+        int codePoint;
+        String strVal;
+
+        // There are three kinds of EXCSAT's we might get.
+        // 1) Initial Exchange attributes.
+        //    For this we need to initialize the apprequester.
+        //    Session state is set to ATTEXC and then the AR must 
+        //    follow up with ACCSEC and SECCHK to get the connection.
+        //  2) Send of EXCSAT as ping or mangager level adjustment. 
+        //     (see parseEXCSAT2())
+        //     For this we just ignore the EXCSAT objects that
+        //     are already set.
+        //  3) Send of EXCSAT for connection reset. (see parseEXCSAT2())
+        //     This is treated just like ping and will be followed up 
+        //     by an ACCSEC request if in fact it is a connection reset.
 
-		// If we have already exchanged attributes once just 
-		// process any new manager levels and return (case 2 and 3 above)
+        // If we have already exchanged attributes once just 
+        // process any new manager levels and return (case 2 and 3 above)
         this.deferredReset = false; // Always reset, only set to true below.
-		if (appRequester != null)
-		{
+        if (appRequester != null)
+        {
             // DERBY-3596
             // Don't mess with XA requests, as the logic for these are handled
             // by the server side (embedded) objects. Note that XA requests
@@ -1556,250 +1556,250 @@ class DRDAConnThread extends Thread {
             if (!appRequester.isXARequester()) {
                 this.deferredReset = true; // Non-XA deferred reset detected.
             }
-			parseEXCSAT2();
-			return;
-		}
-
-		// set up a new Application Requester to store information about the
-		// application requester for this session
-
-		appRequester = new AppRequester();
-
-		reader.markCollection();
-
-		codePoint = reader.getCodePoint();
-		while (codePoint != -1)
-		{
-			switch (codePoint)
-			{
-				// optional
-				case CodePoint.EXTNAM:
-					appRequester.extnam = reader.readString();
-					if (SanityManager.DEBUG) {
-						trace("extName = " + appRequester.extnam);
-                    }
-					if (appRequester.extnam.length() > CodePoint.MAX_NAME) {
-						tooBig(CodePoint.EXTNAM);
-                    }
-					break;
-				// optional
-				case CodePoint.MGRLVLLS:
-					parseMGRLVLLS(1);
-					break;
-				// optional 
-				case CodePoint.SPVNAM:
-					appRequester.spvnam = reader.readString();
-					// This is specified as a null parameter so length should
-					// be zero
-					if (appRequester.spvnam != null) {
-						badObjectLength(CodePoint.SPVNAM);
-                    }
-					break;
-				// optional
-				case CodePoint.SRVNAM:
-					appRequester.srvnam = reader.readString();
-					if (SanityManager.DEBUG) {
-						trace("serverName = " +  appRequester.srvnam);
-                    }
-					if (appRequester.srvnam.length() > CodePoint.MAX_NAME) {
-						tooBig(CodePoint.SRVNAM);
-                    }
-					break;
-				// optional
-				case CodePoint.SRVRLSLV:
-					appRequester.srvrlslv = reader.readString();
-					if (SanityManager.DEBUG) {
-						trace("serverlslv = " + appRequester.srvrlslv);
-                    }
-					if (appRequester.srvrlslv.length() > CodePoint.MAX_NAME) {
-						tooBig(CodePoint.SRVRLSLV);
-                    }
-					break;
-				// optional
-				case CodePoint.SRVCLSNM:
-					appRequester.srvclsnm = reader.readString();
-					if (SanityManager.DEBUG) {
-						trace("serverClassName = " + appRequester.srvclsnm);
-                    }
-					if (appRequester.srvclsnm.length() > CodePoint.MAX_NAME) {
-						tooBig(CodePoint.SRVCLSNM);
-                    }
-					break;
-				default:
-					invalidCodePoint(codePoint);
-			}
-			codePoint = reader.getCodePoint();
-		}
-	}
-
-	/**
-	 * Parses EXCSAT2 (Exchange Server Attributes)
-	 * Instance variables
-	 *	EXTNAM(External Name)	- optional
-	 *  MGRLVLLS(Manager Levels) - optional
-	 *	SPVNAM(Supervisor Name) - optional
-	 *  SRVCLSNM(Server Class Name) - optional
-	 *  SRVNAM(Server Name) - optional, ignorable
-	 *  SRVRLSLV(Server Product Release Level) - optional, ignorable
-	 *
-	 * @exception DRDAProtocolException
-	 * 
-	 * This parses a second occurrence of an EXCSAT command
-	 * The target must ignore the values for extnam, srvclsnm, srvnam and srvrlslv.
-	 * I am also going to ignore spvnam since it should be null anyway.
-	 * Only new managers can be added.
-	 */
-	private void parseEXCSAT2() throws DRDAProtocolException
-	{
-		int codePoint;
-		reader.markCollection();
-
-		codePoint = reader.getCodePoint();
-		while (codePoint != -1)
-		{
-			switch (codePoint)
-			{
-				// optional
-				case CodePoint.EXTNAM:
-				case CodePoint.SRVNAM:
-				case CodePoint.SRVRLSLV:
-				case CodePoint.SRVCLSNM:
-				case CodePoint.SPVNAM:
-					reader.skipBytes();
-					break;
-				// optional
-				case CodePoint.MGRLVLLS:
-					parseMGRLVLLS(2);
-					break;
-				default:
-					invalidCodePoint(codePoint);
-			}
-			codePoint = reader.getCodePoint();
-		}
-	}
-
-	/**
-	 *	Parse manager levels
-	 *  Instance variables
-	 *		MGRLVL - repeatable, required
-	 *		  CODEPOINT
-	 *			CCSIDMGR - CCSID Manager
-	 *			CMNAPPC - LU 6.2 Conversational Communications Manager 
-	 *			CMNSYNCPT - SNA LU 6.2 SyncPoint Conversational Communications Manager
-	 *			CMNTCPIP - TCP/IP Communication Manager 
-	 *			DICTIONARY - Dictionary
-	 *			RDB - Relational Database 
-	 *			RSYNCMGR - Resynchronization Manager 
-	 *			SECMGR - Security Manager
-	 *			SQLAM - SQL Application Manager
-	 *			SUPERVISOR - Supervisor
-	 *			SYNCPTMGR - Sync Point Manager 
-	 *		  VALUE
-	 *
-	 *	On the second appearance of this codepoint, it can only add managers
-	 *
-	 * @param time	1 for first time this is seen, 2 for subsequent ones
-	 * @exception DRDAProtocolException
-	 * 
-	 */
-	private void parseMGRLVLLS(int time) throws DRDAProtocolException
-	{
-		int manager, managerLevel;
-		int currentLevel;
-		// set up vectors to keep track of manager information
-		unknownManagers = new ArrayList<Integer>();
-		knownManagers = new ArrayList<Integer>();
-		ArrayList<Integer> errorManagers = new ArrayList<Integer>();
-		ArrayList<Integer> errorManagersLevel = new ArrayList<Integer>();
-		if (SanityManager.DEBUG) {
-			trace("Manager Levels");
-        }
-
-		while (reader.moreDdmData())
-		{
-			manager = reader.readNetworkShort();
-			managerLevel = reader.readNetworkShort();
-			if (CodePoint.isKnownManager(manager))
-			{
-                knownManagers.add(manager);
-				//if the manager level hasn't been set, set it
-				currentLevel = appRequester.getManagerLevel(manager);
-				if (currentLevel == AppRequester.MGR_LEVEL_UNKNOWN)
-                {
-			    	appRequester.setManagerLevel(manager, managerLevel);
-                }
-				else
-				{
-					//if the level is still the same we'll ignore it
-					if (currentLevel != managerLevel)
-					{
-						//keep a list of conflicting managers
-                        errorManagers.add(manager);
-                        errorManagersLevel.add(managerLevel);
-					}
-				}
+            parseEXCSAT2();
+            return;
+        }
 
-			}
-			else
-            {
-                unknownManagers.add(manager);
-            }
+        // set up a new Application Requester to store information about the
+        // application requester for this session
 
-            if (SanityManager.DEBUG) {
-			   trace("Manager = " + java.lang.Integer.toHexString(manager) + 
-					  " ManagerLevel " + managerLevel);
+        appRequester = new AppRequester();
+
+        reader.markCollection();
+
+        codePoint = reader.getCodePoint();
+        while (codePoint != -1)
+        {
+            switch (codePoint)
+            {
+                // optional
+                case CodePoint.EXTNAM:
+                    appRequester.extnam = reader.readString();
+                    if (SanityManager.DEBUG) {
+                        trace("extName = " + appRequester.extnam);
+                    }
+                    if (appRequester.extnam.length() > CodePoint.MAX_NAME) {
+                        tooBig(CodePoint.EXTNAM);
+                    }
+                    break;
+                // optional
+                case CodePoint.MGRLVLLS:
+                    parseMGRLVLLS(1);
+                    break;
+                // optional 
+                case CodePoint.SPVNAM:
+                    appRequester.spvnam = reader.readString();
+                    // This is specified as a null parameter so length should
+                    // be zero

[... 12929 lines stripped ...]


Mime
View raw message