You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@trafodion.apache.org by li...@apache.org on 2016/12/08 00:45:42 UTC

[15/38] incubator-trafodion git commit: convert trafci project into maven project

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/de7e7d4e/core/conn/trafci/src/main/java/org/trafodion/ci/QueryWrapper.java
----------------------------------------------------------------------
diff --git a/core/conn/trafci/src/main/java/org/trafodion/ci/QueryWrapper.java b/core/conn/trafci/src/main/java/org/trafodion/ci/QueryWrapper.java
new file mode 100644
index 0000000..75086c5
--- /dev/null
+++ b/core/conn/trafci/src/main/java/org/trafodion/ci/QueryWrapper.java
@@ -0,0 +1,700 @@
+// @@@ START COPYRIGHT @@@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+//
+// @@@ END COPYRIGHT @@@
+package org.trafodion.ci;
+
+import java.awt.FontMetrics;
+import java.io.IOException;
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.ParameterMetaData;
+import java.sql.PreparedStatement;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Types;
+
+import org.trafodion.jdbc.t4.TrafT4Statement;
+
+
+
+import sun.misc.Signal;
+import sun.misc.SignalHandler;
+
+/**
+ * 
+ * 
+ * Abstract class for executing queries and formatting the result sets.
+ *
+ */
+
+public abstract class QueryWrapper
+{
+
+   Session sessObj=null;
+   Writer writer=null;
+   Reader reader=null;
+   Query qryObj=null;
+   String queryStr=null;
+   Parser parser=null;
+   Connection conn=null;
+   Statement stmt=null;
+   Utils utils=null;
+   UnKnownInterfaceCommand uic=null;
+   InterfaceSyntaxError ise=null;
+   ConditionalQueryException cqe=null;
+   ConditionalSyntaxError cse=null;
+   UserInterruption ui=null;
+   boolean isMultiLine=true;
+   boolean blankLiner=true;
+   SignalHandler CTRLCHandler=null;
+   Signal INTSignal=null;
+   int i = 0;
+   HTMLObject htmlObj = null;
+   XMLObject xmlObj = null;
+   String columnName="";
+   int colCount=1;
+   String crTrigTerminator ="/";
+   FontMetrics fontMetrics = null;
+   protected int isoMapping;
+   boolean useGetUpdateCount64 = true;
+   // false-show complete msg, true-no show
+   public boolean showStatusMsg = false;
+   
+   int[] colSize   ={};
+   int[] colAlign  ={};
+   String[] columnNameArray={};   
+   
+   /**
+   * creates an empty constructor.
+   *
+   */
+   QueryWrapper()
+   {
+
+   }
+
+   /**
+   * creates the query wrapper for t
+   */
+   QueryWrapper(Session sessObj)
+   {
+      this.sessObj=sessObj;
+      this.parser=new Parser();
+      this.utils=new Utils();
+      this.uic=new UnKnownInterfaceCommand();
+      this.ise=new InterfaceSyntaxError();
+      this.cqe=new ConditionalQueryException();
+      this.cse=new ConditionalSyntaxError();
+      this.ui=new UserInterruption();
+      if (sessObj.getCaller() != SessionDefaults.PRUNI)
+      {
+         CTRLCHandler =new SignalHandler ()
+         {
+            public void handle(Signal sig)
+            {
+               cancelQuery();
+            }
+         };
+         try {
+         INTSignal=new Signal("INT");
+         } catch (Exception e) {}
+      }
+      
+      fontMetrics = MultiByteUtils.getFontMetrics();
+      isoMapping = sessObj.getISOMapping();
+    
+      
+   }
+
+
+   /**
+   * Initializes the reader and writer objects
+   *
+   */
+   void init()
+   {
+      this.writer=sessObj.getWriter();
+      this.reader=sessObj.getReader();
+      this.qryObj=sessObj.getQuery();
+      this.conn=sessObj.getConnObj();
+      this.stmt=sessObj.getStmtObj();
+      try {
+         if (CTRLCHandler != null)
+         {
+            Signal.handle(INTSignal, CTRLCHandler);
+         }
+      }catch (Exception e) {}
+      sessObj.setCurrentStmtObj(null);
+
+   }
+
+
+
+   /**
+   * Reads the query string from the console or from a file depending on the 
+   * read mode.
+   * @throws IOException
+   * @throws UserInterruption 
+   */
+   void readQuery() throws IOException, UserInterruption
+   {
+      boolean matchTrigStmt=false;
+      String[] qryLineArr = null;
+      //queryStr=qryObj.getQueryText().trim();
+      queryStr=qryObj.getQueryText();
+
+      try {
+         if (CTRLCHandler != null)
+         {
+            Signal.handle(INTSignal, CTRLCHandler);
+         }
+      }catch (Exception e) {}
+
+      matchTrigStmt = isCreateTriggerCmd(qryObj.getQueryText());
+      //This is needed if user does a repeat
+      //on create trigger
+      if ((matchTrigStmt) && (queryStr.indexOf(SessionDefaults.lineSeperator) != -1))
+      {
+         qryLineArr = queryStr.split(SessionDefaults.lineSeperator);
+         if (qryLineArr[qryLineArr.length-1].equals(crTrigTerminator))
+         {
+            isMultiLine = false;
+         }
+      }
+
+      while (isMultiLine)
+      {
+         if ((matchTrigStmt)&& (utils.rtrim(queryStr).equals(crTrigTerminator)))
+            break;
+         else if ((!matchTrigStmt) && (queryStr.trim().toUpperCase().endsWith(sessObj.getSessionSQLTerminator())))
+            break;
+         if (( (writer.getWriterMode() == SessionDefaults.CONSOLE_WRITE_MODE ||
+            writer.getWriterMode() == SessionDefaults.CONSOLE_SPOOL_WRITE_MODE))  )
+         {
+            if((reader.getReadMode() == SessionDefaults.OBEY_READ_MODE  && !sessObj.isQuietEnabled()) || !(reader.getReadMode() == SessionDefaults.OBEY_READ_MODE) )            
+                writer.getConsoleWriter().print(sessObj.getSessionCprompt());
+         }
+         try
+         {
+           
+            queryStr = reader.getNonBlankLine();
+            if (sessObj.isCmdEchoEnabled())
+               writer.getConsoleWriter().println(queryStr);
+         }
+         catch (UserInterruption ui)
+         {
+            sessObj.setQuery(null);
+            sessObj.setQueryInterrupted(false);
+            throw ui;
+         }
+
+         if ((queryStr == null))
+         {
+            if (matchTrigStmt)
+               queryStr = crTrigTerminator;
+            else
+               queryStr=sessObj.getSessionSQLTerminator();
+         }
+
+         if (writer.getWriterMode() == SessionDefaults.LOG_WRITE_MODE)
+            writer.getLogWriter().writeln(queryStr);
+         else if (reader.getReadMode() == SessionDefaults.CONSOLE_READ_MODE && writer.getWriterMode() == SessionDefaults.CONSOLE_SPOOL_WRITE_MODE)
+         {
+            if (sessObj.isLogCmdText())
+               writer.getSpoolWriter().writeln(queryStr);
+         }else if ((reader.getReadMode() == SessionDefaults.OBEY_READ_MODE ) || ( sessObj.getCaller() !=SessionDefaults.PRUNI && reader.getReadMode() == SessionDefaults.SCRIPT_READ_MODE ))
+         {
+            writer.getConsoleWriter().println(queryStr);
+            if (sessObj.isLogCmdText() && writer.getWriterMode() == SessionDefaults.CONSOLE_SPOOL_WRITE_MODE)
+               writer.getSpoolWriter().writeln(queryStr);
+         }
+
+         queryStr=parser.ignoreComments(queryStr);
+         qryObj.setQueryText(SessionDefaults.lineSeperator+queryStr);
+         matchTrigStmt = isCreateTriggerCmd(qryObj.getQueryText());
+
+         //queryStr=queryStr.trim();
+      }
+      sessObj.setTimerHold();
+      if ((blankLiner) && (sessObj.getDisplayFormat() != SessionDefaults.XML_FORMAT))
+      {
+          writer.writeln();
+      }
+      if (matchTrigStmt)
+      {
+         this.queryStr = Utils.trimSQLTerminator(sessObj.getQuery().getQueryText().trim(),"/");
+         isMultiLine = true;
+      }
+      else
+         this.queryStr = Utils.trimSQLTerminator(sessObj.getQuery().getQueryText().trim(),sessObj.getSessionSQLTerminator());
+      
+      this.queryStr = utils.rtrim(this.queryStr);
+      if (qryObj.getQueryType()==SessionDefaults.SQLQ)
+         sessObj.setPrevSQLQuery(this.queryStr);
+      parser.setRemainderStr(null);
+      parser.setRemainderStr(this.queryStr);
+
+      this.fixPopIndxUpdStatsCmds();
+   }
+   
+   protected void setQueryRowCount(Statement theStmt) throws SQLException
+   {
+       if(!useGetUpdateCount64){
+           qryObj.setRowCount(String.valueOf(theStmt.getUpdateCount()));
+           return;
+       }
+           
+       try
+       {
+           qryObj.setRowCount(String.valueOf(((TrafT4Statement)theStmt).getUpdateCount64())); 
+       }
+       catch(NoSuchMethodError nsme)
+       {
+           // for backwards compatibility
+           useGetUpdateCount64 = false;
+           qryObj.setRowCount(String.valueOf(theStmt.getUpdateCount()));
+       }
+    }
+
+   boolean isCreateTriggerCmd(String qryText)
+   {
+      if (qryText.toUpperCase().matches("(?s)^\\s*CREATE\\s+TRIGGER\\s+(.*)"))
+      {
+         return true;
+      }
+      return false;
+   }
+
+   void fixPopIndxUpdStatsCmds()
+   {
+      if ((qryObj.getQueryText().toUpperCase().matches("(?s)^\\s*POPULATE\\s+INDEX\\s+(.*)"))  
+         )
+      {
+         queryStr = queryStr.replaceAll(SessionDefaults.lineSeperator," ");
+      }
+   }
+   
+   /**
+   * cancels the current query if ctrl + C is pressed. 
+   * 
+   */
+   void cancelQuery()
+   {
+      sessObj.setQueryInterrupted(true);
+      if (sessObj.getCurrentStmtObj() != null)
+      {
+         try
+         {
+            ((Statement)sessObj.getCurrentStmtObj()).cancel();
+              sessObj.setDBConnExists(false);
+              if (sessObj.isDotModeCmd() ){
+            	sessObj.setLogCmdEcho(true);
+            	sessObj.setMode(sessObj.getPrevMode());
+              }
+         } catch (SQLException e){}
+      }
+      
+   }
+
+
+
+   public abstract void execute() throws IOException, SQLException, UnKnownInterfaceCommand, UserInterruption, ConditionalQueryException ;
+
+   boolean dbExecute(Object st ) throws SQLException, IOException
+   {
+	   boolean status=false;
+
+      try {
+         if (CTRLCHandler != null)
+         {
+            Signal.handle(INTSignal, CTRLCHandler);
+         }
+      }catch (Exception e) {}
+
+      try
+      {
+
+         sessObj.setCurrentStmtObj(st);
+         sessObj.setQueryInterrupted(false);
+
+         if (st instanceof CallableStatement)
+         {
+            status=((CallableStatement)st).execute();
+            sessObj.setSPJRS(status);
+         }else if (st instanceof PreparedStatement)
+         {
+            status=((PreparedStatement)st).execute();
+         }
+         else if (st instanceof Statement)
+         {
+            status=((Statement)st).execute(queryStr);
+         }
+
+      }catch (SQLException sqle)
+      {
+         if (sessObj.isQueryInterrupted() && sqle.getErrorCode() == -29157)
+         {
+            sessObj.setDBConnExists(false);
+
+         }
+         throw sqle;
+      }
+	   sessObj.setQryExecEndTime();
+	   
+      return status;
+   }
+   
+   boolean dbExec(Object st) throws SQLException, IOException
+   {
+	   boolean status = dbExecute(st);
+	   
+	   /*if (sessObj.getMode() == SessionDefaults.SQL_MODE &&
+	         writer != null &&
+	         qryObj.getQueryType() != SessionDefaults.IQ)
+	         writer.writeExecutionTime(sessObj, utils, writer);
+           */	   
+	   return status;
+   }
+
+   void writeSeparator() throws IOException
+   {
+      if (sessObj.getSessView() == SessionDefaults.MXCI_VIEW)
+         write(sessObj.getSessionColSep());
+      write(sessObj.getSessionColSep());
+   }
+
+   void write(String output) throws IOException
+   {
+      switch (sessObj.getDisplayFormat())
+      {
+         //HTML Format
+         case SessionDefaults.HTML_FORMAT:
+            sessObj.getHtmlObj().processHtml(output);
+            writer.writeln();
+            break;
+
+         //XML Format
+         case SessionDefaults.XML_FORMAT:
+            sessObj.getXmlObj().processXml(this.columnName,output);
+            writer.writeln();
+            break;
+
+         //CSV Format
+         case SessionDefaults.CSV_FORMAT:
+            writer.write(output);
+            if (qryObj.getColCount() != null)
+            {
+               if (colCount == Integer.parseInt(qryObj.getColCount()))
+               {
+                  writer.write(SessionDefaults.lineSeperator);
+                  colCount=1;
+                  break;
+               }
+            }
+            colCount++;
+            if (sessObj.getStrDisplayFormat().equalsIgnoreCase("COLSEP"))
+               writer.write(sessObj.getSessionColSep());
+            else
+               writer.write(",");
+            break;
+
+         //Default Raw Format
+         default: writer.write(output);
+            break;
+      }
+   }
+
+
+   void writeln(String output) throws IOException
+   {
+      write(output);
+      write(SessionDefaults.lineSeperator);
+   }
+
+   void writeln() throws IOException
+   {
+      write(SessionDefaults.lineSeperator);
+   }
+
+   void formatOutput(String output,int colWidth,char fillchar,int align) throws IOException
+   {
+
+     int outputStrLen = 0;
+      
+      if (output != null && output.length() > colWidth)
+      {
+         output=output.substring(0,colWidth);
+      } 
+      StringBuffer outBuffer=new StringBuffer(output);
+
+      if (sessObj.isMultiByteAlign() && (isoMapping == 10 || isoMapping == 15)) //SJIS or UTF8
+      {
+         try {
+         outputStrLen = getMultiByteColWidth(outBuffer);
+         }catch (Exception ex)
+         {
+            ex.printStackTrace();
+            throw new IOException(ex.getMessage());
+         }
+      }
+      else
+      {
+         outputStrLen = outBuffer.length();
+      }
+      //If the output is greater than the column width,
+      //truncate the output
+      
+      if (outputStrLen > colWidth)
+      {
+         outBuffer = new StringBuffer(outBuffer.substring(0,Math.min(colWidth, outBuffer.length())));
+         outputStrLen = outBuffer.length();
+      }
+
+      if ( outputStrLen <= colWidth)
+      {
+    	 if (colWidth > 128)
+    		 colWidth = 128;
+         for (int i=outputStrLen;i<colWidth;i++)
+         {
+            if (align == 0)
+            {
+               outBuffer.append(fillchar);
+            }
+            else
+            {
+               outBuffer.insert(0,fillchar);
+            }
+         }
+
+         write( outBuffer.toString());
+
+      }
+      outBuffer=null;
+   }
+
+   void formatHtmlOutput(String output) throws IOException
+   {
+      write(output);
+   }
+
+   void formatXmlOutput(String columnName, String output) throws IOException
+   {
+      this.columnName = columnName;
+      write(output);
+   }
+
+   void formatCsvOutput(String output) throws IOException
+   {
+      write(output);
+   }
+
+   protected int getMultiByteColWidth(StringBuffer output)
+   {
+      if (null == fontMetrics)
+         return output.length();
+      
+      int refWidth = fontMetrics.charWidth('w');
+      int width=0;
+     
+       for (int i=0; i< output.length(); i++)
+      {
+         int tmpLen=fontMetrics.charWidth(output.charAt(i));
+         //incorrect value of char width. Treat it as no-ASCII.
+         if(tmpLen==0 || tmpLen>fontMetrics.getMaxAdvance())
+         {
+        	 if(output.charAt(i)>256)
+        	 {
+        		 tmpLen=refWidth*2-1;
+        	 }
+        	 else
+        	 {
+        		 tmpLen=refWidth;
+        	 }
+         } 
+         
+         width += (tmpLen/refWidth) + (tmpLen%refWidth>0?1:0);
+      }
+      
+      return width;
+   }
+
+   void writeQryOutParams(ResultSetMetaData rsmd,int numColumns,ParameterMetaData paramMetaData,CallableStatement callStmt) throws SQLException, IOException
+   {
+	   //   sessObj.setWriteParams(true);
+	      columnNameArray = new String[numColumns];
+	      colSize=new int[numColumns];
+	      colAlign=new int[numColumns];
+	      //qryObj.setColCount(String.valueOf(numColumns));
+	      for (int i=1;i<=numColumns;i++)
+	      {
+	         if (paramMetaData.getParameterMode(i) != ParameterMetaData.parameterModeIn &&
+	            paramMetaData.getParameterMode(i) != ParameterMetaData.parameterModeUnknown)
+	         {
+	            int colNameSize = rsmd.getColumnName(i).length();
+	            if (colNameSize > rsmd.getColumnDisplaySize(i))
+	               colSize[i-1]=colNameSize;
+	            else
+	               colSize[i-1]=rsmd.getColumnDisplaySize(i);
+
+	            if (colSize[i-1] < SessionDefaults.MIN_COL_DISPLAY_SIZE)
+	            {
+	               colSize[i-1] = SessionDefaults.MIN_COL_DISPLAY_SIZE;
+	            }
+
+	            switch (sessObj.getDisplayFormat())
+	            {
+	               case SessionDefaults.RAW_FORMAT:
+	                  formatOutput(rsmd.getColumnName(i),colSize[i-1],' ',0);
+	                  if (i < numColumns)
+	                  {
+	                     writeSeparator();
+	                  }
+	                  break;
+
+	               case SessionDefaults.XML_FORMAT:
+	                  columnNameArray[i-1] = sessObj.getXmlObj().checkColumnNames(rsmd.getColumnName(i));
+	                  break;
+
+	               case SessionDefaults.HTML_FORMAT:
+	                  formatHtmlOutput(rsmd.getColumnName(i));
+	                  break;
+	               case SessionDefaults.CSV_FORMAT:
+	            	  formatCsvOutput(rsmd.getColumnName(i));
+	                  break;
+
+	               default:
+	                  break;
+	            }
+
+	            switch (rsmd.getColumnType(i))
+	            {
+	               case Types.BIGINT:
+	               case Types.BIT:
+	               case Types.DECIMAL:
+	               case Types.DOUBLE:
+	               case Types.FLOAT:
+	               case Types.INTEGER:
+	               case Types.NUMERIC:
+	               case Types.REAL:
+	               case Types.SMALLINT:
+	               case Types.TINYINT:
+	                  colAlign[i-1]=1;
+	                  break;
+	               default:
+	                  colAlign[i-1]=0;
+	                  break;
+
+	            }
+	         }
+	      }
+	      if (sessObj.getDisplayFormat() == SessionDefaults.RAW_FORMAT)
+	      {
+	         writeln();
+	         for (int i=1;i<=numColumns ;i++)
+	         {
+	            if (paramMetaData.getParameterMode(i) != ParameterMetaData.parameterModeIn &&
+	               paramMetaData.getParameterMode(i) != ParameterMetaData.parameterModeUnknown)
+	            {
+	               formatOutput("",colSize[i-1],'-',0);
+	               if (i < numColumns)
+	               {
+	                  writeSeparator();
+	               }
+	            }
+	         }
+	         writeln();
+
+	         if (sessObj.getSessView() == SessionDefaults.MXCI_VIEW)
+	            writeln();
+	      }
+	      writeQryData(callStmt,numColumns,paramMetaData);
+	      qryObj.setRowCount("1");		      
+   }
+
+   private void writeQryData(CallableStatement callStmt,int numColumns, ParameterMetaData paramMetaData) throws SQLException, IOException
+   {
+      for (int i=1;i<=numColumns ;i++)
+      {
+         if (paramMetaData.getParameterMode(i) != ParameterMetaData.parameterModeIn &&
+            paramMetaData.getParameterMode(i) != ParameterMetaData.parameterModeUnknown)
+         {
+            String value=callStmt.getString(i);
+            if (value == null)
+            {
+               value=sessObj.getSessNull();
+            }
+
+            switch (sessObj.getDisplayFormat())
+            {
+               case SessionDefaults.RAW_FORMAT :
+                  if (qryObj.isTrimOut())
+                  {
+                     formatOutput(value,value.length(),' ',0);
+                  }
+                  else
+                  {
+                     formatOutput(value,colSize[i-1],' ',colAlign[i-1]);
+                  }
+
+                  if (i < numColumns)
+                  {
+                     writeSeparator();
+                  }
+                  break;
+
+
+               case SessionDefaults.XML_FORMAT :
+                  formatXmlOutput(columnNameArray[i-1],value);
+                  break;
+
+               case SessionDefaults.HTML_FORMAT:
+                  formatHtmlOutput(value);
+                  break;
+
+               case SessionDefaults.CSV_FORMAT:
+                  formatCsvOutput(value.trim());
+                  break;
+            }
+         }
+      }
+
+      if (sessObj.getDisplayFormat() == SessionDefaults.RAW_FORMAT)
+         writeln();
+   }
+   
+   void formatOutputVertical(String colHeading, String output) throws IOException
+   {
+	   if (colHeading != null)
+		   write( colHeading + ": " + output + SessionDefaults.lineSeperator);
+	   else
+		   write( output + SessionDefaults.lineSeperator);
+   }
+   
+	public boolean getShowStatusMsg() {
+		return this.showStatusMsg;
+	}
+
+	public void setShowStatusMsg(boolean showStatusMsg) {
+		this.showStatusMsg = showStatusMsg;
+	}
+}
+
+

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/de7e7d4e/core/conn/trafci/src/main/java/org/trafodion/ci/RawDisplay.java
----------------------------------------------------------------------
diff --git a/core/conn/trafci/src/main/java/org/trafodion/ci/RawDisplay.java b/core/conn/trafci/src/main/java/org/trafodion/ci/RawDisplay.java
new file mode 100644
index 0000000..84be925
--- /dev/null
+++ b/core/conn/trafci/src/main/java/org/trafodion/ci/RawDisplay.java
@@ -0,0 +1,189 @@
+// @@@ START COPYRIGHT @@@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+//
+// @@@ END COPYRIGHT @@@
+
+package org.trafodion.ci;
+
+import java.awt.FontMetrics;
+import java.io.IOException;
+import java.util.ArrayList;
+
+public class RawDisplay implements IDisplay {
+
+	private Writer writer=null;
+	private Session sessObj=null;
+	private int isoMapping;
+	private FontMetrics fontMetrics = null;
+	
+	public RawDisplay(Session sessObj)
+	{
+		if(sessObj!=null)
+		{
+			this.sessObj = sessObj;
+			this.writer=sessObj.getWriter();
+			isoMapping = sessObj.getISOMapping();
+		}
+		fontMetrics = MultiByteUtils.getFontMetrics();
+	}
+
+	public void output(OutputContents contents) throws IOException {
+		// TODO Auto-generated method stub
+
+		if(contents!=null)
+		{
+			this.writer=sessObj.getWriter();
+			//display header
+			ArrayList<OutputColumnAttribute> columns = contents.getColumns();
+			if(columns!=null && columns.size()>0)
+			{
+				//display columns name
+				for(int i=0;i<columns.size();i++)
+				{
+					OutputColumnAttribute columnAttr = columns.get(i);
+					formatOutput(columnAttr.name,columnAttr.width,' ',columnAttr.align);					
+					writer.write(contents.getColumnSeparator());
+				}
+				writeln();
+				
+				//display column header separator
+				for(int i=0;i<columns.size();i++)
+				{
+					OutputColumnAttribute columnAttr = columns.get(i);
+					formatOutput("",columnAttr.width,'-',columnAttr.align);
+					writer.write(contents.getColumnSeparator());
+				}
+				writeln();
+			}
+			
+			//display contents
+			ArrayList<ArrayList<String>> alRows = contents.getRows();
+			if(alRows!=null && alRows.size()>0)
+			{
+				for(int i=0;i<alRows.size();i++)
+				{
+					ArrayList<String> alRow = alRows.get(i);
+					if(alRow!=null && alRow.size()>0)
+					{
+						for(int j=0;j<alRow.size();j++)
+						{
+							OutputColumnAttribute columnAttr = columns.get(j);
+							formatOutput(alRow.get(j),columnAttr.width,' ',columnAttr.align);
+							
+							writer.write(contents.getColumnSeparator());
+						}
+						writeln();
+					}
+					
+				}
+				writeln();
+			}
+		}
+	}
+
+	   void formatOutput(String output,int colWidth,char fillchar,int align) throws IOException
+	   {
+
+	     int outputStrLen = 0;
+	      
+	      if (output != null && output.length() > colWidth)
+	      {
+	         output=output.substring(0,colWidth);
+	      } 
+	      StringBuffer outBuffer=new StringBuffer(output);
+
+	      if (sessObj.isMultiByteAlign() && (isoMapping == 10 || isoMapping == 15)) //SJIS or UTF8
+	      {
+	         try {
+	         outputStrLen = getMultiByteColWidth(outBuffer);
+	         }catch (Exception ex)
+	         {
+	            ex.printStackTrace();
+	            throw new IOException(ex.getMessage());
+	         }
+	      }
+	      else
+	      {
+	         outputStrLen = outBuffer.length();
+	      }
+	      //If the output is greater than the column width,
+	      //truncate the output
+	      
+	      if (outputStrLen > colWidth)
+	      {
+	         outBuffer = new StringBuffer(outBuffer.substring(0,Math.min(colWidth, outBuffer.length())));
+	         outputStrLen = outBuffer.length();
+	      }
+
+	      if ( outputStrLen <= colWidth)
+	      {
+	         for (int i=outputStrLen;i<colWidth;i++)
+	         {
+	            if (align == 0)
+	            {
+	               outBuffer.append(fillchar);
+	            }
+	            else
+	            {
+	               outBuffer.insert(0,fillchar);
+	            }
+	         }
+
+	         writer.write( outBuffer.toString());
+
+	      }
+	      outBuffer=null;
+	   }
+
+	   protected int getMultiByteColWidth(StringBuffer output)
+	   {
+	      if (null == fontMetrics)
+	         return output.length();
+	      
+	      int refWidth = fontMetrics.charWidth('w');
+	      int width=0;
+	     
+	       for (int i=0; i< output.length(); i++)
+	      {
+	         int tmpLen=fontMetrics.charWidth(output.charAt(i));
+	         //incorrect value of char width. Treat it as no-ASCII.
+	         if(tmpLen==0 || tmpLen>fontMetrics.getMaxAdvance())
+	         {
+	        	 if(output.charAt(i)>256)
+	        	 {
+	        		 tmpLen=refWidth*2-1;
+	        	 }
+	        	 else
+	        	 {
+	        		 tmpLen=refWidth;
+	        	 }
+	         } 
+	         
+	         width += (tmpLen/refWidth) + (tmpLen%refWidth>0?1:0);
+	      }
+	      
+	      return width;
+	   }
+
+	   void writeln() throws IOException
+	   {
+		   writer.write(SessionDefaults.lineSeperator);
+	   }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/de7e7d4e/core/conn/trafci/src/main/java/org/trafodion/ci/Reader.java
----------------------------------------------------------------------
diff --git a/core/conn/trafci/src/main/java/org/trafodion/ci/Reader.java b/core/conn/trafci/src/main/java/org/trafodion/ci/Reader.java
new file mode 100644
index 0000000..f216f09
--- /dev/null
+++ b/core/conn/trafci/src/main/java/org/trafodion/ci/Reader.java
@@ -0,0 +1,286 @@
+// @@@ START COPYRIGHT @@@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+//
+// @@@ END COPYRIGHT @@@
+package org.trafodion.ci;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+public class Reader
+{
+   private ConsoleReader cReader=null;
+   private FileReader sReader=null;
+   private FileReader oReader=null;
+   private List<FileReader> nestedObeyReaders=null;
+
+//   private boolean obeyFileList = false;
+   private int readMode=SessionDefaults.CONSOLE_READ_MODE;
+   private int prevReadMode=SessionDefaults.CONSOLE_READ_MODE;
+   private String tmpString=null;
+   private FileReader tmpReader=null;
+   
+   private HashMap<String, String> obeyHashMap = null;
+   private int MAX_OBEY_DEPTH;
+   
+   Reader()
+   {
+       int defaultDepth = 10;
+       
+       MAX_OBEY_DEPTH = defaultDepth;
+       try
+       {
+           if(System.getProperty("trafci.obeydepth") != null)
+               MAX_OBEY_DEPTH = Integer.parseInt(System.getProperty("trafci.obeydepth"));
+           
+           if(MAX_OBEY_DEPTH < 0)
+               MAX_OBEY_DEPTH = defaultDepth;
+       }
+       catch(Exception ex)
+       {
+               MAX_OBEY_DEPTH = defaultDepth;
+       }
+   } 
+   
+   public String getNonBlankLine() throws IOException, UserInterruption
+   {
+      
+      switch (readMode)
+      {
+         case SessionDefaults.CONSOLE_READ_MODE:
+            return cReader.getLine();
+         case SessionDefaults.SCRIPT_READ_MODE:
+            return sReader.getNonBlankLine();
+         case SessionDefaults.OBEY_READ_MODE:
+             
+             if(isObeyDepthMax(oReader.getFileName()))
+             {
+                 obeyHashMap = null;
+                 throw new IOException("\n\nERROR: " + SessionError.OBEY_DEPTH_MAX + oReader.getFileName());
+             }
+
+            tmpString=oReader.getNonBlankLine();
+            if (tmpString == null && ((tmpReader=getLastObeyReader()) != null))
+            {
+               obeyHashMap.remove(oReader.getFileName());
+               decrementHashMap(tmpReader.getFileName());
+               oReader.close();
+               
+               oReader=tmpReader;
+               return getNonBlankLine();
+            }
+            else
+                return tmpString;
+      }
+      return null;
+   }
+
+   public String getLine() throws IOException, UserInterruption
+   {
+
+      switch (readMode)
+      {
+         case SessionDefaults.CONSOLE_READ_MODE:
+            return cReader.getLine();
+         case SessionDefaults.SCRIPT_READ_MODE:
+            return sReader.getLine();
+         case SessionDefaults.OBEY_READ_MODE:
+            tmpString=oReader.getLine();
+            if (tmpString == null && ((tmpReader=getLastObeyReader()) != null))
+            {
+               oReader=tmpReader;
+               getLine();
+            }
+            return tmpString;
+      }
+      return null;
+   }
+
+   public ConsoleReader getConsoleReader()
+   {
+      return cReader;
+   }
+
+   public void setConsoleReader(ConsoleReader reader)
+   {
+      cReader = reader;
+   }
+
+   public FileReader getObeyReader()
+   {
+      return oReader;
+   }
+   
+   public List<FileReader> getObeyReaderList()
+   {
+       return this.nestedObeyReaders;
+   }
+
+   public void setObeyReader(FileReader reader)
+   {
+      // if the current mode is already obey read mode..then push the current object to the nested buffer
+      // and set the current reader
+
+      if (reader != null && readMode == SessionDefaults.OBEY_READ_MODE)
+      {
+         this.addObeyReader(oReader);
+         //this.obeyFileList = true;
+      }
+      else
+      {
+         //this.obeyFileList = false;
+         this.nestedObeyReaders = null;
+      }
+      
+      oReader = reader;
+   }
+
+   public FileReader getScriptReader()
+   {
+      return sReader;
+   }
+
+   public void setScriptReader(FileReader reader)
+   {
+      sReader = reader;
+   }
+
+   public int getReadMode()
+   {
+      return readMode;
+   }
+
+   public int getPrevReadMode()
+   {
+      return this.prevReadMode;
+   }
+
+   public void setReadMode(int readMode)
+   {
+      this.prevReadMode=this.readMode;
+      this.readMode = readMode;
+   }
+
+   private FileReader getLastObeyReader()
+   {
+      if (this.nestedObeyReaders == null)
+      {
+         return null;
+      }
+      FileReader fr=(FileReader)this.nestedObeyReaders.get(this.nestedObeyReaders.size()-1);
+      this.nestedObeyReaders.remove(this.nestedObeyReaders.size()-1);
+      if (this.nestedObeyReaders.size() == 0)
+      {
+         this.nestedObeyReaders=null;
+      }
+      return fr;
+   }
+
+   private void addObeyReader(FileReader obeyReader)
+   {
+      if (this.nestedObeyReaders == null)
+      {
+         this.nestedObeyReaders = new ArrayList<FileReader>();
+      }
+
+      if(this.obeyHashMap == null)
+      {
+          this.obeyHashMap = new HashMap<String, String>();
+      }
+      
+      incrementHashMap(obeyReader);
+   }
+   
+   public boolean obeyMultipleFiles(){
+     /* if (this.nestedObeyReaders == null){
+			     return false; 
+      } 
+     */
+	   
+      if (oReader.getFileName().equals(""))
+	 	   return false;
+	  else
+		   return true;
+   }
+   
+   private boolean isObeyDepthMax(String path)
+   {
+       if(obeyHashMap != null)
+       {
+           String tmpHashObject = obeyHashMap.get(path);
+           
+           if(tmpHashObject != null)
+           {
+               int obeyFileCount = Integer.parseInt(tmpHashObject); 
+               if(obeyFileCount == MAX_OBEY_DEPTH)
+               {
+                   return true;
+               }
+           }
+       }
+       return false;
+   }
+   
+   private void incrementHashMap(FileReader obeyReader){
+       String path = obeyReader.getFileName();
+       int obeyFileCount = 1;
+       
+       if(obeyHashMap.get(path) == null)
+       {
+           obeyHashMap.put(path, obeyFileCount + "");
+       }
+       else
+       {
+           obeyFileCount = Integer.parseInt(obeyHashMap.get(path));
+           obeyFileCount++;
+           obeyHashMap.put(path, obeyFileCount + "");  
+       }
+       
+       if(obeyFileCount <= MAX_OBEY_DEPTH)
+           this.nestedObeyReaders.add(obeyReader);
+   }
+
+   private void decrementHashMap(String path){
+       if(obeyHashMap.get(path) != null){
+           int obeyFileCount = Integer.parseInt(obeyHashMap.get(path));
+           obeyFileCount--;
+           obeyHashMap.put(path, obeyFileCount + "");   
+       }
+   }
+   
+   public boolean isReallyObeyfile()
+   {
+	   // Try an determine if this is really an obey file or
+	   // a stream of multiple commands constructed to run .sec
+	   
+	   // No obey files are being processed right now
+	   if (oReader == null || readMode != SessionDefaults.OBEY_READ_MODE)
+		   return false;
+	   //Only one obey file see if its for .sec
+	   if (this.nestedObeyReaders == null){
+		   if ( oReader.getFileName()== "")
+			     return false; 
+	   }
+   	   // One actual obey file or nested obey files
+	   return true;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/de7e7d4e/core/conn/trafci/src/main/java/org/trafodion/ci/RepObjInterface.java
----------------------------------------------------------------------
diff --git a/core/conn/trafci/src/main/java/org/trafodion/ci/RepObjInterface.java b/core/conn/trafci/src/main/java/org/trafodion/ci/RepObjInterface.java
new file mode 100644
index 0000000..19b27b2
--- /dev/null
+++ b/core/conn/trafci/src/main/java/org/trafodion/ci/RepObjInterface.java
@@ -0,0 +1,27 @@
+// @@@ START COPYRIGHT @@@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+//
+// @@@ END COPYRIGHT @@@
+
+package org.trafodion.ci;
+
+public abstract class RepObjInterface {
+
+	public abstract String getValue(String key);
+}

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/de7e7d4e/core/conn/trafci/src/main/java/org/trafodion/ci/ReplacementObj.java
----------------------------------------------------------------------
diff --git a/core/conn/trafci/src/main/java/org/trafodion/ci/ReplacementObj.java b/core/conn/trafci/src/main/java/org/trafodion/ci/ReplacementObj.java
new file mode 100644
index 0000000..d06fac6
--- /dev/null
+++ b/core/conn/trafci/src/main/java/org/trafodion/ci/ReplacementObj.java
@@ -0,0 +1,39 @@
+// @@@ START COPYRIGHT @@@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+//
+// @@@ END COPYRIGHT @@@
+
+package org.trafodion.ci;
+
+public class ReplacementObj extends RepObjInterface {
+
+//	private String patternKey;
+	private String patternValue;
+	
+	ReplacementObj(String patternKey, String patternValue)
+	{
+//		this.patternKey = patternKey;
+		this.patternValue = patternValue;
+	}
+	
+	public String getValue(String patternKey)
+	{
+		return this.patternValue;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/de7e7d4e/core/conn/trafci/src/main/java/org/trafodion/ci/ScriptSectionNotFound.java
----------------------------------------------------------------------
diff --git a/core/conn/trafci/src/main/java/org/trafodion/ci/ScriptSectionNotFound.java b/core/conn/trafci/src/main/java/org/trafodion/ci/ScriptSectionNotFound.java
new file mode 100644
index 0000000..5456157
--- /dev/null
+++ b/core/conn/trafci/src/main/java/org/trafodion/ci/ScriptSectionNotFound.java
@@ -0,0 +1,34 @@
+// @@@ START COPYRIGHT @@@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+//
+// @@@ END COPYRIGHT @@@
+package org.trafodion.ci;
+
+public class ScriptSectionNotFound extends Exception
+{
+   /**
+   * 
+   */
+   private static final long serialVersionUID = 1L;
+
+   ScriptSectionNotFound()
+   {
+
+   }
+}

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/de7e7d4e/core/conn/trafci/src/main/java/org/trafodion/ci/ScriptsInterface.java
----------------------------------------------------------------------
diff --git a/core/conn/trafci/src/main/java/org/trafodion/ci/ScriptsInterface.java b/core/conn/trafci/src/main/java/org/trafodion/ci/ScriptsInterface.java
new file mode 100644
index 0000000..2413a2b
--- /dev/null
+++ b/core/conn/trafci/src/main/java/org/trafodion/ci/ScriptsInterface.java
@@ -0,0 +1,153 @@
+// @@@ START COPYRIGHT @@@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+//
+// @@@ END COPYRIGHT @@@
+package org.trafodion.ci;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.sql.SQLException;
+
+public class ScriptsInterface
+{
+   Session sessObj=null;
+   SessionInterface siObj=null;
+   ConsoleReader crObj=null;
+   ConsoleWriter cwObj=null;
+
+
+   public ScriptsInterface()
+   {
+
+   }
+
+   public void openConnection(String userName,
+		      String password,
+		      String serverName,
+		      String portNumber,
+		      String dsnName) throws IOException, SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException
+  {
+	   String roleName = ""; //primary role
+	   openConnection( userName, password, roleName, serverName, portNumber, dsnName);
+	   
+  }
+
+   public void openConnection(String userName,
+      String password,
+      String roleName,
+      String serverName,
+      String portNumber,
+      String dsnName) throws IOException, SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException
+   {
+
+      //System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("c:\\output.dat"))));
+      cwObj=new ConsoleWriter();
+      cwObj.setConsoleOut(false);
+      cwObj.initialize();
+      crObj=new ConsoleReader();
+      crObj.initialize();
+      siObj=new SessionInterface(crObj,cwObj);
+      if (portNumber == null || portNumber.trim().equals(""))
+      {
+         portNumber=SessionDefaults.portNumber;
+      }
+      portNumber=":"+portNumber;
+
+	  if (portNumber.endsWith("#"))
+
+	  {
+
+		  portNumber = portNumber.substring(0, portNumber.length() - 1);
+
+	  }
+
+
+        try {
+      sessObj=siObj.createSession(userName,
+         roleName,
+         password,
+         serverName,
+         portNumber,
+         dsnName,
+         0);
+  } finally {
+		  cwObj.setConsoleOut(true);
+	  }
+
+   }
+
+   public String executeQuery(String query) throws IOException
+   {
+      cwObj.resetStream();
+      cwObj.setConsoleOut(false);
+      sessObj.setCaller(SessionDefaults.USERI);
+      siObj.setScriptFile(null);
+      siObj.setLogFile(null,false);
+      if (sessObj == null)
+      {
+         System.out.println("session object is null");
+
+      }
+
+      if (sessObj.getConnObj() == null)
+      {
+         System.out.println("connection object is null");
+      }
+
+      if (sessObj.getConsoleWriter() == null)
+      {
+         System.out.println("Console writer is null");
+      }
+      siObj.setConsoleWriter(cwObj);
+      siObj.setConsoleReader(crObj);
+      siObj.setQueryOptions(true, query);
+      String cmdOutput = "";
+      
+      try {
+      siObj.invokeSession(sessObj);
+      cmdOutput = cwObj.getResult();
+      } finally {
+    	  cwObj.setConsoleOut(true);
+      }
+      
+      return cmdOutput;
+   }
+
+   public void executeScript(String scriptFile, String logFile) throws IOException
+   {
+      cwObj.setConsoleOut(true);
+      siObj.setScriptFile(scriptFile);
+      siObj.setLogFile(logFile,true);
+      siObj.setQueryOptions(false,null);
+      sessObj.setCaller(SessionDefaults.PRUNI);
+      siObj.invokeSession(sessObj);
+   }
+
+   public void disconnect() throws SQLException
+   {
+      this.sessObj.getConnObj().close();
+      this.sessObj=null;
+      this.siObj=null;
+   // This will support multiple connections
+   //     System.exit(0); 
+   }
+
+
+}