home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Symantec Visual Cafe for Java 2.5
/
symantec-visual-cafe-2.5-database-dev-edition.iso
/
VCafe
/
prosrc.bin
/
RecordDefinition.java
< prev
next >
Encoding:
Amiga
Atari
Commodore
DOS
FM Towns/JPY
Macintosh
Macintosh JP
Macintosh to JP
NeXTSTEP
RISC OS/Acorn
Shift JIS
UTF-8
Wrap
Java Source
|
1998-03-19
|
87.9 KB
|
2,364 lines
/*
* @(#)RecordDefinition.java
*
* Copyright (c) 1997 Symantec Corporation. All Rights Reserved.
*
*/
package symantec.itools.db.beans.jdbc;
import java.util.*;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.DatabaseMetaData;
import symantec.itools.db.beans.binding.*;
import java.lang.*;
public class RecordDefinition implements PersistentObject, Cloneable
{
//internal constants
protected static final int INSERT_SQL=100;
protected static final int UPDATE_SQL=101;
protected static final int DELETE_SQL=102;
protected static final String CLASS_NAME="RecordDefinition";
protected static final String UNEXPECTED_ERROR_MESSAGE="Unexpected error in " + CLASS_NAME + " : ";
protected static final String IS_NULL=" IS NULL ";
protected PreparedStatement m_Statement=null;
/*this class implements the following logical table:
----------------------------------------------------------------------------------------------------------------
State(Inserted) State(Modified) State(Deleted) State(MisplacedDetail) ExternalState Operation
----------------------------------------------------------------------------------------------------------------
true true true true DELETED NOTHING
true true true false DELETED NOTHING
true true false true INSERTED_MISPLACED INSERT & REMOVE_INTERNAL(in QN)
true true false false INSERTED INSERT
true false true true ERROR-INVALID CASE
true false true false DELETED NOTHING
true false false true ERROR-INVALID CASE
true false false false INSERTED INSERT
false true true true DELETED DELETE & REMOVE_INTERNAL(in QN)
false true true false DELETED DELETE & REMOVE_INTERNAL(in QN)
false true false true MODIFIED_MISPLACED UPDATE & REMOVE_INTERNAL(in QN)
false true false false MODIFIED UPDATE
false false true true ERROR-INVALID CASE
false false true false DELETED DELETE & REMOVE_INTERNAL(in QN)
false false false true ERROR-INVALID CASE
false false false false EXISTING NOTHING
*/
private RecordState recordState=new RecordState();
//this class
public static class RecordState{
//these are the states of a record
//original state, modified, inserted, deleted and any combination of these states
public static final int ORIGINAL=0;
public static final int INSERTED=1;
public static final int MODIFIED=2;
public static final int DELETED=4;
public static final int MISPLACED=8;
public static final int INSERTED_MODIFIED=INSERTED+MODIFIED;
public static final int INSERTED_DELETED=INSERTED+DELETED;
public static final int MODIFIED_DELETED=MODIFIED+DELETED;
public static final int INSERTED_MODIFIED_DELETED=INSERTED+MODIFIED+DELETED;
public static final int NUMBER_OF_STATES=4;
public static final int FIRST_VALUE=ORIGINAL;
public static final int LAST_VALUE=ORIGINAL+INSERTED+MODIFIED+DELETED+MISPLACED;
//the external state for a row
public static final int EXISTING_STATE=109;
public static final int INSERTED_STATE=110;
public static final int MODIFIED_STATE=111;
public static final int DELETED_STATE=112;
public static final int INSERTED_MISPLACED=113;
public static final int MODIFIED_MISPLACED=114;
//the operations that the save() method implements
public static final int NOTHING_OPERATION=13;
public static final int INSERTED_OPERATION=14;
public static final int MODIFIED_OPERATION=15;
public static final int DELETED_OPERATION=16;
int state;
RecordState(){
state=ORIGINAL;
}
synchronized void reset(){
state=ORIGINAL;
}
public synchronized boolean equals(RecordState rs){
return ( rs.state==state);
}
synchronized int getOperation() throws StateException {
int stateRet=NOTHING_OPERATION;
// get rid of MISPLACED state; we don't need that for the RD save();
int stateWhMisplaced=((state>=MISPLACED)? state-MISPLACED:state);
switch(stateWhMisplaced){
case ORIGINAL:
stateRet= NOTHING_OPERATION;
break;
case INSERTED:
stateRet= INSERTED_OPERATION;
break;
case MODIFIED:
stateRet= MODIFIED_OPERATION;
break;
case INSERTED_MODIFIED:
stateRet= INSERTED_OPERATION;
break;
case DELETED:
stateRet= DELETED_OPERATION;
break;
case INSERTED_DELETED:
stateRet= NOTHING_OPERATION;
break;
case MODIFIED_DELETED:
stateRet= DELETED_OPERATION;
break;
case INSERTED_MODIFIED_DELETED:
stateRet= NOTHING_OPERATION;
break;
default:
throw new StateException("Invalid call to getOperation()");
}
return stateRet;
}
synchronized void setState(int newState) throws StateException
{
int tempState=0;
if((state & newState)> 0){
return;
}
if(state==DELETED && newState==MODIFIED)
return ;//throw new StateException("Modify not allow after Delete");
// MISPLACED comes down only after a modification
if(((state & MODIFIED)==0) && newState==MISPLACED)
throw new StateException("Invalid try to set the State of the Record to MISPLACED.");
tempState=state+newState;
if (tempState>LAST_VALUE || tempState< FIRST_VALUE)
throw new StateException("Invalid try to set the State");
state+=newState;
}
synchronized void setStateUndo(int newState) throws StateException
{
int tempState=0;
if((state & newState)> 0)
tempState=state-newState;
else
return;
if (tempState>LAST_VALUE || tempState< FIRST_VALUE)
throw new StateException("Invalid try to set the State");
state=tempState;
}
synchronized boolean isMisplaced(){
return (state & MISPLACED) >0;
}
synchronized int getExternalState() {
int stateRet;
// get rid of MISPLACED state; we don't need that for the QN save();
int stateWhMisplaced=((state>=MISPLACED)? state-MISPLACED:state);
switch(stateWhMisplaced){
case 0:{
stateRet= EXISTING_STATE;
break;
}
case 1:{
stateRet= INSERTED_STATE;
break;
}
case 2:{
stateRet= MODIFIED_STATE;
break;
}
case 3:{
stateRet= INSERTED_STATE;
break;
}
case 4:{
stateRet= DELETED_STATE;
break;
}
case 5:{
stateRet= DELETED_STATE;
break;
}
case 6:{
stateRet= DELETED_STATE;
break;
}
case 7:{
stateRet= DELETED_STATE;
break;
}
default:
throw new StateException("Invalid try to call getState");
}
return stateRet;
}
class StateException extends RuntimeException{
StateException(String text){
super(text);
}
}
}
// this class defines the RecordDefinition internal misfunction
//and raise an exception
public class RecordDefinitionException extends PersistentObject.RecordException
{
RecordDefinitionException(String text){
new RuntimeException(text);
}
}
public final static String TableSeparator=Name.TableSeparator;
//the state of on RecordDefinition is set up through these parameters
//Note: they are exclusive, it means that only one can be true at once
// internal storage for the RecordDefinition data.
protected Vector m_OriginalValues;
protected Vector m_ModifiedValues;
protected final static int COLUMN_VALUE=0;
protected final static int JOIN_VALUE=1;
protected final static int OPERATOR_VALUE=2;
//how many elements are different between m_ModifiedValues and m_OriginalValues
private int colModif=0;
boolean debug=true;
protected synchronized Statement getInsertStatement() throws SQLException
{
throw new RuntimeException("This method must be over-ridden.");
}
protected synchronized Statement getUpdateStatement() throws SQLException
{
throw new RuntimeException("This method must be over-ridden.");
}
protected synchronized Statement getDeleteStatement() throws SQLException
{
throw new RuntimeException("This method must be over-ridden.");
}
public RecordDefinition() {
}
public int getValueIndex(String name)
{
return 0;
}
public synchronized PersistentObjectModel getDataModel()
{
throw new RuntimeException("This method must be over-ridden.");
}
public synchronized void setDataModel(PersistentObjectModel model)
{
throw new RuntimeException("This method must be over-ridden.");
}
public synchronized Enumeration querySimilarObjects()
{
try {
return querySimilarObjects(null,null);
}
catch (java.sql.SQLException ex) {
throw new RuntimeException(ex.getMessage());
}
}
protected synchronized int getColModif(){
return colModif;
}
private synchronized void setColModif(int modifiedOccurences){
colModif=modifiedOccurences;
}
protected void errorTreaten(Exception e,String procName) {
final String classNameErrorMessage="ERROR in " + CLASS_NAME + " in the method " + procName+ ": ";
if(debug){
System.out.println(classNameErrorMessage+"error message: " + e.getMessage()+" ; instance of : " +e.getClass());
}
}
public int getColumnIndex(String name)
{
if(name == null) {
return -1;
}
int colIndex=-1;
int column;
ColumnMetaData colMD;
for (column = 0, colMD = (ColumnMetaData)getDataModel().getMemberModel(column);
colMD != null;
column++, colMD = (ColumnMetaData)getDataModel().getMemberModel(column)) {
if (colMD.getColumnName().equals(name)) {
colIndex=column;
break;
}
}
if (colIndex == -1) {
String newValue;
if (name.startsWith("[") && name.endsWith("]")) {
newValue = name.substring(1, name.length() -1);
}
else if (!(name.startsWith("[") || name.endsWith("]"))) {
newValue = "[" + name + "]";
}
else {
newValue = name;
}
for (column = 0, colMD = (ColumnMetaData)getDataModel().getMemberModel(column);
colMD != null;
column++, colMD = (ColumnMetaData)getDataModel().getMemberModel(column)) {
if (colMD.getColumnName().equals(newValue)) {
colIndex=column;
break;
}
}
}
return colIndex;
}
/**
* Gets the object stored in the RecordDefinition at the given position as a String
* @param index. The position inside the RecordDefinition.
* @param orig_modif. The modified value or the .
* @return String. The value of the object.
*/
public String getValueAsString(int index, int orig_modif) {
final String PROCEDURE_NAME="getValueAsString";
Object ret=null;
try{
int type=getMemberModel(index).getType();
ret=getValueAsObject(index,orig_modif);
if(ret==null){
ret=new String();
}
if(type==java.sql.Types.VARBINARY || type==java.sql.Types.BINARY){
byte bRet[]= (byte[])ret;
StringBuffer buff=null;
for(int i=0;i<bRet.length;i++){
buff.append(bRet[i]);
}
ret=buff;
}
}
catch(ArrayIndexOutOfBoundsException e){
throw e;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
return ret.toString();
}
/**
* Sets the object stored in the RecordDefinition at the given position
* @param index. The position inside the RecordDefinition.
* @param value. The value
*/
public void setValueAsString(int index, String value) throws NumberFormatException{
setValueAsObject(index, value);
}
public void setValueAsInteger(int index, Integer value)throws NumberFormatException{
setValueAsObject(index, value);
}
/**
* Gets the object stored in the RecordDefinition at the given position as an object
* @param index. The position inside the RecordDefinition.
* @param orig_modif. The modified value or the .
* @return Object. The value of the object.
*/
public synchronized Object getValueAsObject(int index, int orig_modif)
{
final String PROCEDURE_NAME="getValueAsObject";
Object retObject=null;
try{
switch(orig_modif) {
case ORIGINAL_VALUE:
retObject= m_OriginalValues.elementAt(index);
break;
case MODIFIED_VALUE:
int type=getMemberModel(index).getType();
retObject = m_ModifiedValues.elementAt(index);
if(type==java.sql.Types.LONGVARBINARY && retObject != null) {
if (retObject instanceof java.io.ByteArrayOutputStream) {
java.io.ByteArrayOutputStream stream = (java.io.ByteArrayOutputStream)retObject;
retObject= new java.io.ByteArrayInputStream(((java.io.ByteArrayOutputStream)stream).toByteArray());
}
}
break;
default:
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
catch(ArrayIndexOutOfBoundsException e){
throw e;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
return retObject;
}
/**
* Sets the object stored in the RecordDefinition at the given position as an Object
* @param index. The position inside the RecordDefinition.
* @param value. The value.
*/
public synchronized void setValueAsObject(int index, Object value) throws NumberFormatException
{
final String PROCEDURE_NAME="setValueAsObject";
try{
if (m_ModifiedValues == null) {
m_ModifiedValues = new Vector(getDataModel().getMemberCount());
}
value=setCastJDBCToJava(value,index);
m_ModifiedValues.setElementAt(value, index);
if (!equalsVector(m_OriginalValues,m_ModifiedValues)){
setMarkedAsModified(true);
}
else if(getMarkedAsModified()){
recordState.setStateUndo(RecordState.MODIFIED);
}
}
catch(ArrayIndexOutOfBoundsException e){
throw e;
}
catch(NumberFormatException e){
throw e;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
Enumeration resultSetToEnum( ResultSet rs ) throws SQLException{
final String PROCEDURE_NAME="resultSetToEnum";
ResultSetEnumeration m_ResultSetEnum ;
try {
ResultSetMetaData md = rs.getMetaData();
int numColumns = md.getColumnCount();
m_ResultSetEnum = new ResultSetEnumeration(rs, md, this.getClass(),getDataModel().getModelName());
return m_ResultSetEnum;
}
catch(SQLException e){
throw e;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
/**
* Saves the current row in the Data Base.
*/
public synchronized int save()
{
final String PROCEDURE_NAME="save";
final String insert="INSERT";
final String update="UPDATE";
final String delete="DELETE";
int rowsUpdated=0;
String sStatement="";
int currentOperation;
Statement statement=null;
JdbcConnection conBean = (JdbcConnection)getConnection();
if (conBean==null){
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
try{
currentOperation=recordState.getOperation();
}
catch(RecordState.StateException e){
throw new RecordDefinitionException("The row was found in an invalid state");
}
try{
if(conBean.isConnectionClosed()){
conBean.connect();
}
switch(currentOperation){
case RecordState.INSERTED_OPERATION:
statement = getInsertStatement() ;
sStatement=insert;
break;
case RecordState.DELETED_OPERATION:
statement = getDeleteStatement();
sStatement=delete;
break;
case RecordState.MODIFIED_OPERATION:
statement = getUpdateStatement();
sStatement=update;
break;
case RecordState.NOTHING_OPERATION:
return rowsUpdated;
default:
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
rowsUpdated=conBean.executeStatement(statement, sStatement);
//if no rows were updated throws a SQLException
if(rowsUpdated==0){
throw new SQLException("0 row updated");
}
//if the execute succeed then the m_OriginalValues is changed to the new value
if (conBean.isAutoCommit()){
recordState.reset();
Enumeration enum = m_ModifiedValues.elements();
m_OriginalValues = new Vector();
while (enum.hasMoreElements()) {
Object value = enum.nextElement();
m_OriginalValues.addElement(value);
}
}
return rowsUpdated;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(e.getMessage()+UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
finally{
if(statement!=null){
try {
statement.close();
}
catch (SQLException e) {
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
}
}
public void resetState(){
recordState.reset();
Enumeration enum = m_ModifiedValues.elements();
m_OriginalValues = new Vector();
while (enum.hasMoreElements()) {
Object value = enum.nextElement();
m_OriginalValues.addElement(value);
}
}
protected PreparedStatement getStatement(PreparedStatement pstmt, int index) throws SQLException
{
final String PROCEDURE_NAME="getStatement";
String m_SQLString=null;
try {
if (pstmt == null) {
switch(index){
case INSERT_SQL:
m_SQLString = makeInsertSQLString();
break;
case UPDATE_SQL:
m_SQLString = makeUpdateSQLString();
break;
case DELETE_SQL:
m_SQLString = makeDeleteSQLString();
break;
default:
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
pstmt = prepareStatement(m_SQLString);
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
return pstmt;
}
private boolean columnModifiedCondition(int i){
final String PROCEDURE_NAME="columnModifiedCondition";
try{
Object original= m_OriginalValues.elementAt(i);
Object modified=m_ModifiedValues.elementAt(i);
if(original==null && modified ==null)
return false;
else if (original==null && modified !=null)
return !modified.equals(original);
else if (original!=null && modified ==null)
return !original.equals(modified);
else if (original!=null && modified !=null)
return !modified.equals(original);
else
return false;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
private boolean isColumnNull(int i){
return (m_OriginalValues.elementAt(i)==null);
}
protected synchronized void setParameterValues(PreparedStatement statement) throws SQLException {
final String PROCEDURE_NAME="setParameterValues";
int parameterIndex = 1;
int length=getDataModel().getMemberCount();
try{
int modifCol=0;
for (int index = 0; index < length; index++) {
if (columnModifiedCondition(index)){
if(getValueAsObject(index,MODIFIED_VALUE)==null){
statement.setNull(modifCol +1,(getDataModel().getMemberModel(index)).getType());
}
else{
setObjectInStatement(statement,getValueAsObject(index,MODIFIED_VALUE),index,0,modifCol);
}
modifCol++;
}
}
}
catch(SQLException e){
throw e;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
protected void setObjectInStatement(PreparedStatement stmt, Object value, int col,int offset,int modifCol) throws SQLException{
final String PROCEDURE_NAME="setObjectInStatement";
try{
int type=(getDataModel().getMemberModel(col)).getType();
if(value==null){
stmt.setNull(modifCol+1+offset,type);
return;
}
switch(type){
case java.sql.Types.TINYINT:
short objByte;
if (value instanceof Byte){
objByte=((Short)value).shortValue();
stmt.setShort(modifCol+1+offset,objByte);
break;
}
else if (value instanceof Short){
objByte=((Short)value).shortValue();
stmt.setShort(modifCol+1+offset,objByte);
break;
}
else if (value instanceof Integer){
objByte=((Integer)value).shortValue();
stmt.setShort(modifCol+1+offset,objByte);
break;
}
else if (value instanceof String){
objByte = (Short.valueOf((String)value)).shortValue();
stmt.setShort(modifCol+1+offset,objByte);
break;
}
else if (value instanceof Number){
objByte=((Number)value).shortValue();
stmt.setShort(modifCol+1+offset,objByte);
break;
}
else if (value instanceof Object){
stmt.setObject(modifCol+1+offset,value);
break;
}
case java.sql.Types.SMALLINT:
short objShort;
if (value instanceof Short){
objShort= ((Short)value).shortValue();
stmt.setShort(modifCol+1+offset,objShort);
break;
}else if (value instanceof Integer){
objShort=((Integer)value).shortValue();
stmt.setShort(modifCol+1+offset,objShort);
break;
}
else if (value instanceof String){
objShort = (Short.valueOf((String)value)).shortValue();
stmt.setShort(modifCol+1+offset,objShort);
break;
}
else if (value instanceof Number){
objShort=((Number)value).shortValue();
stmt.setShort(modifCol+1+offset,objShort);
break;
}
else if (value instanceof Object){
stmt.setObject(modifCol+1+offset,value);
break;
}
case java.sql.Types.INTEGER:
int objInt;
if (value instanceof Integer){
objInt=((Integer)value).intValue();
stmt.setInt(modifCol+1+offset,objInt);
break;
}
else if (value instanceof String){
objInt = (Integer.valueOf((String)value)).intValue();
stmt.setInt(modifCol+1+offset,objInt);
break;
}
else if(value instanceof Number){
objInt=((Number)value).intValue();
stmt.setInt(modifCol+1+offset,objInt);
break;
}
else if (value instanceof Object){
stmt.setObject(modifCol+1+offset,value);
break;
}
case java.sql.Types.BIGINT:
long objBigInt;
if (value instanceof Long){
objBigInt=((Long)value).longValue();
stmt.setLong(modifCol+1+offset,objBigInt);
break;
}
else if (value instanceof Integer){
objBigInt=((Integer)value).longValue();
stmt.setLong(modifCol+1+offset,objBigInt);
break;
}
else if (value instanceof String){
objBigInt = (Integer.valueOf((String)value)).longValue();
stmt.setLong(modifCol+1+offset,objBigInt);
break;
}
else if (value instanceof Number){
objBigInt=((Number)value).longValue();
stmt.setLong(modifCol+1+offset,objBigInt);
break;
}
else if (value instanceof Object){
stmt.setObject(modifCol+1+offset,value);
break;
}
case java.sql.Types.REAL:
float objDouble;
if (value instanceof Float){
objDouble=((Float)value).floatValue();
stmt.setDouble(modifCol+1+offset,objDouble);
break;
}
else if (value instanceof String){
objDouble = (Float.valueOf((String)value)).floatValue();
stmt.setDouble(modifCol+1+offset,objDouble);
break;
}
else if(value instanceof Number){
objDouble=((Number)value).floatValue();
stmt.setDouble(modifCol+1+offset,objDouble);
break;
}
else if (value instanceof Object){
stmt.setObject(modifCol+1+offset,value);
break;
}
case java.sql.Types.DOUBLE:
double objDoub;
if (value instanceof Double){
objDoub=((Double)value).doubleValue();
stmt.setDouble(modifCol+1+offset,objDoub);
break;
}
else if (value instanceof String){
objDoub = (Double.valueOf((String)value)).doubleValue();
stmt.setDouble(modifCol+1+offset,objDoub);
break;
}
else if(value instanceof Number){
objDoub=((Number)value).doubleValue();
stmt.setDouble(modifCol+1+offset,objDoub);
break;
}
else if (value instanceof Object){
stmt.setObject(modifCol+1+offset,value);
break;
}
case java.sql.Types.FLOAT:
double objDoubleFloat;
if (value instanceof Double){
objDoubleFloat=((Double)value).doubleValue();
stmt.setDouble(modifCol+1+offset,objDoubleFloat);
break;
}
else if (value instanceof String){
objDoubleFloat = (Double.valueOf((String)value)).doubleValue();
stmt.setDouble(modifCol+1+offset,objDoubleFloat);
break;
}
else if(value instanceof Number){
objDoubleFloat=((Number)value).doubleValue();
stmt.setDouble(modifCol+1+offset,objDoubleFloat);
break;
}
else if (value instanceof Object){
stmt.setObject(modifCol+1+offset,value);
break;
}
case java.sql.Types.DECIMAL:
java.math.BigDecimal objDecimal;
if (value instanceof java.math.BigDecimal){
stmt.setBigDecimal(modifCol+1+offset,(java.math.BigDecimal)value);
break;
}
else if (value instanceof String){
double l = Double.valueOf((String)value).doubleValue();
objDecimal =new java.math.BigDecimal(l);
stmt.setBigDecimal(modifCol+1+offset,objDecimal);
break;
}
else if (value instanceof Number){
double doub=((Number)value).doubleValue();
objDecimal=new java.math.BigDecimal(doub);
stmt.setBigDecimal(modifCol+1+offset,objDecimal);
break;
}
else if (value instanceof Object){
stmt.setObject(modifCol+1+offset,value);
break;
}
case java.sql.Types.NUMERIC:
java.math.BigDecimal objNumeric;
if (value instanceof java.math.BigDecimal){
stmt.setBigDecimal(modifCol+1+offset,(java.math.BigDecimal)value);
break;
}
else if (value instanceof String){
double l = Double.valueOf((String)value).doubleValue();
objNumeric = new java.math.BigDecimal(l);
stmt.setBigDecimal(modifCol+1+offset,objNumeric);
break;
}
else if (value instanceof Number){
double doub=((Number)value).doubleValue();
objDecimal=new java.math.BigDecimal(doub);
stmt.setBigDecimal(modifCol+1+offset,objDecimal);
break;
}
else if (value instanceof Object){
stmt.setObject(modifCol+1+offset,value);
break;
}
case java.sql.Types.BIT:
boolean objBool;
if (value instanceof Boolean){
objBool= ((Boolean)value).booleanValue();
stmt.setBoolean(modifCol+1+offset,objBool);
break;
}
else if (value instanceof String){
objBool = (Boolean.valueOf((String)value)).booleanValue();
stmt.setBoolean(modifCol+1+offset,objBool);
break;
}
else if (value instanceof Object){
stmt.setObject(modifCol+1+offset,value);
break;
}
case java.sql.Types.CHAR:
String objChar;
if (value instanceof String){
stmt.setString(modifCol+1+offset,(String)value);
break;
}
else if (value instanceof Object){
stmt.setObject(modifCol+1+offset,value);
break;
}
case java.sql.Types.VARCHAR:
String objVarChar;
if (value instanceof String){
stmt.setString(modifCol+1+offset,(String)value);
break;
}
else if (value instanceof Object){
stmt.setObject(modifCol+1+offset,value);
break;
}
case java.sql.Types.LONGVARCHAR:
java.io.InputStream objInputStream;
if (value instanceof java.io.InputStream){
objInputStream=(java.io.InputStream)value;
stmt.setAsciiStream(modifCol+1+offset,objInputStream,((String)value).length());
break;
}
else if (value instanceof String){
stmt.setString(modifCol+1+offset,(String)value);
break;
}
else if (value instanceof Object){
objInputStream=(java.io.InputStream)value;
stmt.setAsciiStream(modifCol+1+offset,objInputStream,((String)value).length());
break;
}
case java.sql.Types.BINARY:
stmt.setBytes(modifCol+1+offset,(byte[])value);
break;
case java.sql.Types.VARBINARY:
stmt.setBytes(modifCol+1+offset,(byte[])value);
break;
case java.sql.Types.LONGVARBINARY:
java.io.ByteArrayInputStream stream = (java.io.ByteArrayInputStream)value;
stmt.setBinaryStream(modifCol+1+offset,stream,stream.available());
break;
case java.sql.Types.DATE:
java.sql.Date objDate;
if (value instanceof java.sql.Date){
stmt.setDate(modifCol+1+offset,(java.sql.Date)value);
break;
}
else if (value instanceof String){
objDate = java.sql.Date.valueOf((String)value);
stmt.setDate(modifCol+1+offset,objDate);
break;
}
else if (value instanceof Object){
stmt.setObject(modifCol+1+offset,value);
break;
}
case java.sql.Types.TIME:
java.sql.Time objTime;
if (value instanceof java.sql.Time){
stmt.setTime(modifCol+1+offset,(java.sql.Time)value);
break;
}
else if (value instanceof String){
objTime = java.sql.Time.valueOf((String)value);
stmt.setTime(modifCol+1+offset,objTime);
break;
}
else if (value instanceof Object){
stmt.setObject(modifCol+1+offset,value);
break;
}
case java.sql.Types.TIMESTAMP:
java.sql.Timestamp objTimestamp;
if (value instanceof java.sql.Timestamp){
stmt.setTimestamp(modifCol+1+offset,(java.sql.Timestamp)value);
break;
}
else if (value instanceof String){
objTimestamp = java.sql.Timestamp.valueOf((String)value);
stmt.setTimestamp(modifCol+1+offset,objTimestamp);
break;
}
else if (value instanceof Object){
stmt.setObject(modifCol+1+offset,value);
break;
}
case java.sql.Types.OTHER:
stmt.setObject(modifCol+1+offset, value,type);
break;
default:
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
catch(SQLException e){
throw e;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
String modifyStatement(int x, String statement, int modifiedOccurences, String sep, String data){
if (columnModifiedCondition(x)) {
if (modifiedOccurences > 0)
statement += sep;
statement += data;
}
return statement;
}
//adiacon 07.29
//The syntax for a prepared Insert SQL is:
// INSERT INTO table_name (col1,col2...) VALUES (?,?,)
//Note: We assume that there is not an auto-incremental field in the row
String makeInsertSQLString()
{
final String PROCEDURE_NAME="makeInsertSQLString";
try{
String statement = new String();
int modifiedOccurences=0;
int colCount=getDataModel().getMemberCount();
statement += "INSERT INTO ";
statement += getDataModel().getModelName();
statement += "( ";
String resStatement=statement;
for (int x = 0; x < colCount; x++, statement=resStatement)
{
resStatement=modifyStatement( x, resStatement,modifiedOccurences,",",getDataModel().getMemberModel(x).getName());
if(!(resStatement.equals(statement)))
modifiedOccurences++;
}
modifiedOccurences=0;
statement += " ) VALUES( ";
resStatement=statement;
for (int x = 0; x < colCount; x++,statement=resStatement)
{
resStatement= modifyStatement( x, statement,modifiedOccurences,",","?");
if(!(resStatement.equals(statement)))
modifiedOccurences++;
}
statement += " )";
return statement;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
//adiacon 07.29
//The syntax for a prepared Update SQL is:
// UPDATE table_name SET col1=?,col2=?... WHERE col1 like ?,col2 like ?...
//Note: The row is identified by all its components. For now we ignore a possible primary(s) key(s)
String makeUpdateSQLString()
{
final String PROCEDURE_NAME="makeUpdateSQLString";
try{
String statement = new String();
statement += "UPDATE ";
statement += getDataModel().getModelName();
statement += " SET ";
int length=getDataModel().getMemberCount();
int modifiedOccurences=0;
for (int x = 0; x < length; x++)
{
if (columnModifiedCondition(x)){
if (modifiedOccurences > 0) statement += ",";
statement += getDataModel().getMemberModel(x).getName();
statement += " = ?";
modifiedOccurences++;
}
}
setColModif(modifiedOccurences);
statement += " WHERE ";
statement += getQueryPredicate("=");
return statement;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
//adiacon 07.29
//The syntax for a prepared Delete SQL is:
// DELETE FROM table_name WHERE col1 like ?,col2 like ?...
//Note: The row is identified by all its components. For now we ignore a possible primary(s) key(s)
String makeDeleteSQLString()
{
final String PROCEDURE_NAME="makeDeleteSQLString";
try{
String statement = new String();
statement += "DELETE FROM ";
statement += getDataModel().getModelName();
statement += " WHERE ";
statement += getQueryPredicate("=");
return statement;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
public Enumeration querySimilarObjects(String whereClause, String[] sortOrder ) throws SQLException
{
return querySimilarObjects(whereClause,null,sortOrder);
}
public Enumeration querySimilarObjects(String whereClause,Synchronizable.JoinRecordList joinList, String[] sortOrder ) throws SQLException
{
final String PROCEDURE_NAME="querySimilarObjects";
//PreparedStatement query;
StringBuffer query = new StringBuffer(getSelectSQL());
boolean isWhereClauseEmpty=true;
if (whereClause != null) {
StringTokenizer tokens = new StringTokenizer(whereClause, " ");
if (tokens.countTokens() >= 2) {
String token1 = tokens.nextToken();
isWhereClauseEmpty=false;
if (!token1.equalsIgnoreCase("where")) {
query.append(" where ");
}
}
else {
query.append(" where ");
}
query.append(whereClause);
}
Enumeration joinEnum=null;
if(joinList != null){
joinEnum=joinList.getJoinRecords();
}
if(joinList != null && joinEnum.hasMoreElements()){
if (isWhereClauseEmpty) {
query.append(" WHERE ");
}
int index=0;
while(joinEnum.hasMoreElements()){
Synchronizable.JoinRecord joinItem=(Synchronizable.JoinRecord)joinEnum.nextElement();
Object masterValue=joinItem.getMasterCurrentValue();
if(index >0 || !isWhereClauseEmpty){
query.append(" AND ");
}
if(masterValue!=null){
query.append(joinItem.getDetailColumnName() +" " + joinItem.getOperator()+" "+ " ? ");
}
else{
query.append(joinItem.getDetailColumnName() +" IS NULL ");
}
index++;
}
}
if (sortOrder != null && sortOrder.length > 0) {
query.append(" order by ");
for (int index = 0; index < sortOrder.length; index++) {
if (index > 0) {
query.append(",");
}
query.append(sortOrder[index]);
}
}
JdbcConnection conBean = (JdbcConnection)getConnection();
ResultSet rs=null;
Enumeration rste=null;
try {
if(conBean.isConnectionClosed())
conBean.connect();
//query=conBean.getJdbcConnection().prepareStatement(queryString);
//setWhereClauseParameters(query,MODIFIED_VALUE,0,true);
if(m_Statement!=null){
m_Statement.close();
}
m_Statement = prepareStatement(query.toString());
if(joinList!=null)
{
setQueryParameters(m_Statement,joinList);
}
rs = ((JdbcConnection)getConnection()).executeQuery(m_Statement, null);
rste=resultSetToEnum(rs);
return rste;
}
catch(SQLException e){
throw e;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
public void setQueryParameters(PreparedStatement stmt) throws SQLException
{
setQueryParameters(stmt,null);
}
public void setQueryParameters(PreparedStatement stmt,Synchronizable.JoinRecordList joinList) throws SQLException
{
Enumeration joinEnum=joinList.getJoinRecords();
int index=0;
while(joinEnum.hasMoreElements()){
Synchronizable.JoinRecord joinItem=(Synchronizable.JoinRecord)joinEnum.nextElement();
Object masterValue=joinItem.getMasterCurrentValue();
if(masterValue!=null){
setObjectInStatement(stmt,masterValue,joinItem.getDetailColumnNumber() , index,0);
index++;
}
}
}
String getQueryString(String comparisonOperator) {
final String PROCEDURE_NAME="getQueryString";
final String where="WHERE";
final int whereLength=where.length();
final String orderby="ORDER BY";
final int orderbyLength=orderby.length();
String mdWhere="";
String query = new String();
String sql=getSelectSQL();
String predicateWhere ="";
String beforeOrderBy="";
String beforeWhere="";
String afterWhere="";
String afterOrderby="";
try{
String predicate = getQueryPredicate(comparisonOperator);
if (predicate.length() > 0) {
}
int posWhere=sql.indexOf(where);
int posOrderby=sql.indexOf(orderby);
if (posOrderby!=-1){
afterOrderby=sql.substring(posOrderby);
beforeOrderBy=sql.substring(0,posOrderby);
}
if (posWhere!=-1){
beforeWhere=sql.substring(0,posWhere);
afterWhere=sql.substring(posWhere +whereLength);
}
if (posWhere!=-1 && posOrderby!=-1){
query+=beforeOrderBy;
if (predicate.length() > 0) {
query+=" AND " + predicate;
}
query+=" " +afterOrderby;
}
else if (posWhere!=-1 && posOrderby==-1){
query+=sql;
if (predicate.length() > 0) {
query+=" AND " + predicate;
}
}
else if (posWhere==-1 && posOrderby!=-1){
query+=beforeOrderBy;
if (predicate.length() > 0) {
query+=" " + where + " " + predicate;
}
query+=" " +afterOrderby;
}
else if (posOrderby==-1) {
query += sql;
if (predicate.length() > 0) {
predicateWhere += " "+ where +" " +predicate;
query+=predicateWhere;
}
}
return query;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
protected boolean shouldColumnBeInWhereClause(ColumnMetaData colMD, int columnNumber)
{
return isColumnNeeded(colMD, columnNumber) && canColumnBeUsed(colMD);
}
protected boolean isColumnNeeded(ColumnMetaData colMD, int columnNumber)
{
DataModel model = (DataModel)getDataModel();
boolean useAllColumns = !model.isUnique();
return useAllColumns || columnModifiedCondition(columnNumber) || colMD.isPrimaryKey();
}
protected boolean canColumnBeUsed(ColumnMetaData colMD)
{
return colMD.canBeIncludedInWhereClause();
}
String getQueryPredicate(String comparisonOperator) {
final String PROCEDURE_NAME="getQueryPredicate";
String predicate = new String();
try{
ColumnMetaData colMD;
int column;
for (column = 0, colMD = getMemberModel(column);
colMD != null;
column++, colMD = getMemberModel(column)) {
if (shouldColumnBeInWhereClause(colMD, column)){
if (predicate.length() > 0) {
predicate += " AND ";
}
predicate += colMD.getColumnName();
if (isColumnNull(column)){
predicate+=IS_NULL;
}
else
{
predicate += " ";
predicate += comparisonOperator;
predicate += " ?";
}
}
}
return predicate;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
ColumnMetaData getMemberModel(int column) {
return (ColumnMetaData)getDataModel().getMemberModel(column);
}
// in the prepared statement replace the '?' pattern in the where clause by the values
// from the m_ModifiedValues vector or from m_OriginalValues
//if one value is null we replace with the '%'
protected void setParameters(PreparedStatement stmt, int orig_modif, int offset,boolean queryByExample) throws SQLException{
final String PROCEDURE_NAME="setParameters";
ColumnMetaData colMD;
Object value=null;
int column,colIndex;
try{
for (column = colIndex=0, colMD = getMemberModel(column);
colMD != null;
column++,colIndex++, colMD = getMemberModel(column)) {
if (shouldColumnBeInWhereClause(colMD, column)) {
//the value from m_ModifiedValues vector or from m_OriginalValues
value = getValueAsObject(column, orig_modif);
if(value==null){
colIndex--;
}
else{
setObjectInStatement(stmt,value,column,offset,colIndex);
}
}
else
{
colIndex--;
}
}
}
catch(SQLException e){
throw e;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
public String getDataName(String pattern){
final String PROCEDURE_NAME="getDataName";
try{
if (getDataModel()==null) return "";
String strName=getDataModel().getModelName()+TableSeparator;
int i;
for(i=0;i<getDataModel().getMemberCount()-1;i++)
strName+=getDataModel().getMemberModel(i).getName()+pattern;
strName+=getDataModel().getMemberModel(i).getName();
//System.out.println("**"+strName);
return strName;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
public void initDataStorage() {
int colCount=getDataModel().getMemberCount();
m_OriginalValues = new Vector(colCount);
m_ModifiedValues = new Vector(colCount);
for (int x = 0; x < colCount; x++) {
m_OriginalValues.addElement(null);
m_ModifiedValues.addElement(null);
}
}
private Object setCastJDBCToJava(Object objSwitch,int colIndex)throws NumberFormatException
{
final String PROCEDURE_NAME="setCastJDBCToJava";
Object objReturn=null;
try{
if(objSwitch==null){
return null;
}
switch(getMemberModel(colIndex).getType()){
case java.sql.Types.BIT:
if (objSwitch instanceof String){
objReturn= new Boolean((String)objSwitch);
break;
}
else if (objSwitch instanceof Object){
objReturn=(Boolean)objSwitch;
break;
}
case java.sql.Types.TINYINT:
if (objSwitch instanceof String){
objReturn= new Short ((String)objSwitch);
break;
}
else if (objSwitch instanceof Number){
objReturn=new Short(((Number)objSwitch).shortValue());
break;
}
else if (objSwitch instanceof Object){
objReturn=new Short(objSwitch.toString());
break;
}
case java.sql.Types.SMALLINT:
if (objSwitch instanceof String){
objReturn= new Short ((String)objSwitch);
break;
}
else if (objSwitch instanceof Number){
objReturn=new Short(((Number)objSwitch).shortValue());
break;
}
else if (objSwitch instanceof Object){
objReturn=(Short)objSwitch;
break;
}
case java.sql.Types.BIGINT:
if (objSwitch instanceof String){
objReturn= new Long ((String)objSwitch);
break;
}
else if (objSwitch instanceof Number){
objReturn=new Long(((Number)objSwitch).longValue());
break;
}
else if (objSwitch instanceof Object){
objReturn=(Long)objSwitch;
break;
}
case java.sql.Types.FLOAT:
if (objSwitch instanceof String){
objReturn= new Double ((String)objSwitch);
break;
}
else if (objSwitch instanceof Number){
objReturn=new Double(((Number)objSwitch).doubleValue());
break;
}
else if (objSwitch instanceof Object){
objReturn=(Double)objSwitch;
break;
}
case java.sql.Types.DOUBLE:
if (objSwitch instanceof String){
objReturn= new Double ((String)objSwitch);
break;
}
else if (objSwitch instanceof Number){
objReturn=new Double(((Number)objSwitch).doubleValue());
break;
}
else if (objSwitch instanceof Object){
objReturn=(Double)objSwitch;
break;
}
case java.sql.Types.REAL:
if (objSwitch instanceof String){
objReturn= new Float ((String)objSwitch);
break;
}
else if (objSwitch instanceof Number){
objReturn=new Float(((Number)objSwitch).floatValue());
break;
}
else if (objSwitch instanceof Object){
objReturn=(Float)objSwitch;
break;
}
case java.sql.Types.INTEGER:
if (objSwitch instanceof String){
objReturn=Integer.valueOf((String)objSwitch);
break;
}
else if (objSwitch instanceof Integer){
objReturn=objSwitch;
break;
}
else if (objSwitch instanceof Number){
objReturn=new Integer(((Number)objSwitch).intValue());
break;
}
else if (objSwitch instanceof Object){
objReturn=(Integer)objSwitch;
break;
}
case java.sql.Types.CHAR:
if (objSwitch instanceof String){
objReturn=objSwitch;
break;
}
else if (objSwitch instanceof Object){
objReturn=(String)objSwitch;
break;
}
case java.sql.Types.VARCHAR:
objReturn=(String)objSwitch;
break;
case java.sql.Types.LONGVARCHAR:
objReturn=objSwitch;
break;
case java.sql.Types.BINARY:
if (objSwitch instanceof String){
objReturn=((String)objSwitch).getBytes();
}
else{
objReturn=objSwitch;
}
break;
case java.sql.Types.VARBINARY:
if (objSwitch instanceof String){
objReturn=((String)objSwitch).getBytes();
}
else{
objReturn=objSwitch;
}
break;
case java.sql.Types.LONGVARBINARY:
objReturn=objSwitch;
break;
case java.sql.Types.NUMERIC:
if (objSwitch instanceof java.math.BigDecimal){
objReturn=(java.math.BigDecimal)objSwitch;
break;
}
else if (objSwitch instanceof String){
objReturn=new java.math.BigDecimal((String)objSwitch);
break;
}
else if (objSwitch instanceof Number){
objReturn=new java.math.BigDecimal(((Number)objSwitch).doubleValue());
break;
}
else if (objSwitch instanceof Object){
objReturn=(java.math.BigDecimal)objSwitch;
break;
}
case java.sql.Types.DECIMAL:
if (objSwitch instanceof java.math.BigDecimal){
objReturn=(java.math.BigDecimal)objSwitch;
break;
}
else if (objSwitch instanceof String){
objReturn=new java.math.BigDecimal((String)objSwitch);
break;
}
else if (objSwitch instanceof Number){
objReturn=new java.math.BigDecimal(((Number)objSwitch).doubleValue());
break;
}
else if (objSwitch instanceof Object){
objReturn=(java.math.BigDecimal)objSwitch;
break;
}
case java.sql.Types.DATE:
if (objSwitch instanceof java.sql.Date){
objReturn=objSwitch;
break;
}
else if (objSwitch instanceof String){
try{
objReturn=java.sql.Date.valueOf((String)objSwitch);
}
catch(Exception e){
throw new NumberFormatException("Can't convert to a date");
}
break;
}
else if (objSwitch instanceof Object){
objReturn=(java.sql.Date)objSwitch;
break;
}
break;
case java.sql.Types.TIME:
if (objSwitch instanceof java.sql.Time){
objReturn=objSwitch;
break;
}
else if (objSwitch instanceof String){
try{
objReturn=java.sql.Time.valueOf((String)objSwitch);
}
catch(Exception e){
throw new NumberFormatException("Can't convert to a date");
}
break;
}
else if (objSwitch instanceof Object){
objReturn=(java.sql.Time)objSwitch;
break;
}
break;
case java.sql.Types.TIMESTAMP:
if (objSwitch instanceof java.sql.Timestamp){
objReturn=objSwitch;
break;
}
if (objSwitch instanceof String){
try{
objReturn=java.sql.Timestamp.valueOf((String)objSwitch);
}
catch(Exception e){
throw new NumberFormatException("Can't convert to a date");
}
break;
}
else if (objSwitch instanceof Object){
objReturn=(java.sql.Timestamp)objSwitch;
}
break;
case java.sql.Types.OTHER:
objReturn=objSwitch;
break;
}
}
catch(NumberFormatException e){
throw e;
}
catch(ClassCastException e){
throw e;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
return objReturn;
}
synchronized Object getObjectFromResultSet(int colIndex,ResultSet m_ResultSet) throws SQLException
{
final String PROCEDURE_NAME="getObjectFromResultSet";
int scale=0;
Object retObject=null;
int type=getMemberModel(colIndex).getType();
try{
switch(type){
case java.sql.Types.TINYINT:
retObject=new Short(m_ResultSet.getShort(colIndex+1));
//retObject=new Short(modifyValue(retObject,colIndex, Byte.MAX_VALUE).shortValue());
break;
case java.sql.Types.SMALLINT:
retObject=new Short(m_ResultSet.getShort(colIndex+1));
break;
case java.sql.Types.INTEGER:
retObject=new Integer(m_ResultSet.getInt(colIndex+1));
break;
case java.sql.Types.BIGINT:
retObject=new Long(m_ResultSet.getLong(colIndex+1));
break;
case java.sql.Types.REAL:
retObject=new Float(m_ResultSet.getFloat(colIndex+1));
break;
case java.sql.Types.FLOAT:
retObject=new Double(m_ResultSet.getDouble(colIndex+1));
break;
case java.sql.Types.DOUBLE:
retObject=new Double(m_ResultSet.getDouble(colIndex+1));
break;
case java.sql.Types.DECIMAL:
scale=m_ResultSet.getMetaData().getScale(colIndex+1);
retObject=m_ResultSet.getBigDecimal(colIndex+1,scale);
break;
case java.sql.Types.NUMERIC:
scale=m_ResultSet.getMetaData().getScale(colIndex);
retObject=m_ResultSet.getBigDecimal(colIndex+1,scale);
break;
case java.sql.Types.BIT:
retObject=new Boolean(m_ResultSet.getBoolean(colIndex+1));
break;
case java.sql.Types.CHAR:
retObject=m_ResultSet.getString(colIndex+1);
break;
case java.sql.Types.VARCHAR:
retObject=m_ResultSet.getString(colIndex+1);
break;
case java.sql.Types.LONGVARCHAR:
StringBuffer buf=null;
String value=null;
java.io.InputStream ras=m_ResultSet.getAsciiStream(colIndex+1);
java.io.DataInputStream dis = new java.io.DataInputStream(ras);
String s = dis.readLine();
buf = new StringBuffer();
while(s != null){
buf.append(s);
buf.append("\n");
s = dis.readLine();
}
value = buf.toString();
retObject=value;
break;
case java.sql.Types.BINARY:
retObject=m_ResultSet.getBytes(colIndex+1);
break;
case java.sql.Types.VARBINARY:
retObject=m_ResultSet.getBytes(colIndex+1);
break;
case java.sql.Types.LONGVARBINARY:
java.io.InputStream in= m_ResultSet.getBinaryStream(colIndex+1);
java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream ();
byte buff[]=new byte[4096];
for(;;){
int size=in.read(buff);
if(size==-1){
break;
}
baos.write(buff,0,size);
}
retObject=baos;
break;
case java.sql.Types.DATE:
retObject=m_ResultSet.getDate(colIndex+1);
break;
case java.sql.Types.TIME:
retObject=m_ResultSet.getTime(colIndex+1);
break;
case java.sql.Types.TIMESTAMP:
retObject=m_ResultSet.getTimestamp(colIndex+1);
break;
case java.sql.Types.OTHER:
retObject=m_ResultSet.getObject(colIndex+1);
break;
default:
throw new SQLException("Call getObjectFromResultSet with an invalid java.sql.Type");
}
return retObject;
}
catch(SQLException e){
throw e;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
/**
* Undoes the changes on the current row .
*/
public synchronized void undoChanges() {
Enumeration enum = m_OriginalValues.elements();
m_ModifiedValues = new Vector();
while (enum.hasMoreElements()) {
Object value = enum.nextElement();
m_ModifiedValues.addElement(value);
}
setMarkedAsModified(false);
setMarkedAsDeleted(false);
setMarkedAsDisplaced(false);
}
public synchronized void setMarkedAsNew(boolean markedAsNew) {
try{
if(markedAsNew)
recordState.setState(RecordState.INSERTED);
else
recordState.setStateUndo(RecordState.INSERTED);
}
catch(RecordState.StateException e){
throw new RecordDefinitionException("The row was found in a invalid state");
}
}
public synchronized boolean getMarkedAsNew() {
return (recordState.getExternalState()==RecordState.INSERTED_STATE);
}
public synchronized void setMarkedAsDeleted(boolean markedAsDeleted) {
try{
if(markedAsDeleted)
recordState.setState(RecordState.DELETED);
else
recordState.setStateUndo(RecordState.DELETED);
}
catch(RecordState.StateException e){
throw new RecordDefinitionException("The row was found in a invalid state");
}
}
public boolean getMarkedAsDeleted() {
return (recordState.getExternalState()==RecordState.DELETED_STATE);
}
public boolean getMarkedAsMisplaced() {
return (recordState.isMisplaced());
}
public synchronized void setMarkedAsDisplaced(boolean markedAsMisplaced) {
try{
if(markedAsMisplaced)
recordState.setState(RecordState.MISPLACED);
else
recordState.setStateUndo(RecordState.MISPLACED);
}
catch(RecordState.StateException e){
throw new RecordDefinitionException("The row was found in a invalid state");
}
}
public synchronized void setMarkedAsModified(boolean markedAsModified) {
try{
if(markedAsModified)
recordState.setState(RecordState.MODIFIED);
else
recordState.setStateUndo(RecordState.MODIFIED);
}
catch(RecordState.StateException e){
throw new RecordDefinitionException("The row was found in a invalid state");
}
}
public synchronized boolean getMarkedAsModified() {
return (recordState.getExternalState()==RecordState.MODIFIED_STATE);
}
void bringUpToDate() {
Enumeration enum = m_ModifiedValues.elements();
m_OriginalValues = new Vector();
while (enum.hasMoreElements()) {
Object value = enum.nextElement();
m_OriginalValues.addElement(value);
}
setMarkedAsModified(false);
}
public DataModel generateDataModel() throws SQLException
{
final String PROCEDURE_NAME="getMetaData";
Vector primaryKeyNames=new Vector(0);
Vector indexUniqueNames=new Vector(0);
DataModel model = new DataModel();
String tableName=getTableName();
String col[]=getColumns();
Statement stmt =null;
ResultSet rs=null;
try {
model.setTableName(tableName);
ColumnMetaData colMetaData;
DatabaseMetaData dbMetaData = getDatabaseMetaData();
ResultSet primaryKeysMetaDataResultSet = null;
ResultSet indexMetaDataResultSet = null;
try {
primaryKeysMetaDataResultSet = dbMetaData.getPrimaryKeys(null,null,tableName.substring(tableName.indexOf(".")+1));
while (primaryKeysMetaDataResultSet.next()){
String primaryKeyName = primaryKeysMetaDataResultSet.getString(4);
primaryKeyNames.addElement(removeBrackets(primaryKeyName));
}
}
catch (SQLException ex) {
// swallow it.
}
finally {
if (primaryKeysMetaDataResultSet != null) {
primaryKeysMetaDataResultSet.close();
}
}
try {
if (primaryKeyNames.isEmpty()){
indexMetaDataResultSet = dbMetaData.getIndexInfo(null,null,tableName.substring(tableName.indexOf(".")+1),true,false);
while (indexMetaDataResultSet.next()){
String indexUniqueName = indexMetaDataResultSet.getString(9);
indexUniqueNames.addElement(removeBrackets(indexUniqueName));
}
}
}
catch (SQLException ex) {
// swallow it.
}
finally {
if (indexMetaDataResultSet != null) {
indexMetaDataResultSet.close();
}
}
stmt = createStatement();
rs = ((JdbcConnection)getConnection()).executeQuery(stmt, getSelectSQL());
ResultSetMetaData rsMetaData = rs.getMetaData();
int numCols =rsMetaData.getColumnCount();
for(int i=1;i<=numCols;i++) {
colMetaData = new ColumnMetaData();
String columnName = "";
try {
columnName = rsMetaData.getColumnName(i);
}
catch (SQLException ex) {
// swallow it.
}
colMetaData.setColumnName(columnName);
if (!primaryKeyNames.isEmpty() && primaryKeyNames.contains(columnName)){
colMetaData.setPrimaryKey(true);
model.setUnique(true);
}
else {
if (!indexUniqueNames.isEmpty() && indexUniqueNames.contains(columnName)){
colMetaData.setPrimaryKey(true);
model.setUnique(true);
}
}
try {
int columnType = rsMetaData.getColumnType(i);
colMetaData.setColumnDataType(columnType);
}
catch(SQLException e){
//swallow it; for flat DB
}
try{
colMetaData.setIsComparable(rsMetaData.isSearchable(i));
}
catch(SQLException e){
//swallow it; for flat DB
}
try{
colMetaData.setIsAutoIncrement(rsMetaData.isAutoIncrement(i));
}
catch(SQLException e){
//swallow it; for flat DB
}
try{
colMetaData.setIsReadOnly(rsMetaData.isReadOnly(i));
}
catch(SQLException e){
//swallow it; for flat DB
}
try{
colMetaData.setIsSigned(rsMetaData.isSigned(i));
}
catch(SQLException e){
//swallow it; for flat DB
}
model.addColumnMetaData(colMetaData);
}
setDataModel(model);
return model;
}
catch(SQLException e){
throw e;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
finally{
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
}
}
String removeBrackets(String text)
{
if(text==null){
return null;
}
if (text.startsWith("[") && text.endsWith("]")) {
text = text.substring(1, text.length() -1);
}
return text;
}
private boolean equalsColumn(Vector orig, int i, Vector modif){
Object original= orig.elementAt(i);
Object modified=modif.elementAt(i);
try{
if(original==null && modified ==null)
return true;
else if (original==null && modified !=null)
return modified.equals(original);
else if (original!=null && modified ==null)
return original.equals(modified);
else if (original!=null && modified !=null)
return modified.toString().equals(original.toString());
else
return false;
}
catch(Exception e){
//if something wrong we'd rather to assume that the values are different
return false;
}
}
public boolean isDirty(){
return (!equalsVector(m_OriginalValues,m_ModifiedValues) || recordState.getExternalState()!=RecordState.EXISTING_STATE);
}
private synchronized boolean equalsVector(Vector orig,Vector modif){
final String PROCEDURE_NAME="equalsVector";
boolean valRet=true;
if(orig==null && modif==null){
return true;
}
else if((orig==null && modif!=null)||(orig!=null && modif==null)){
return false;
}
int sizeOrig=orig.size();
int sizeModif=modif.size();
if (sizeOrig!=sizeModif){
return false;
}
for(int i=0; i<sizeOrig;i++){
valRet=valRet && equalsColumn(orig,i,modif);
if(!valRet){
break;
}
}
return valRet;
}
public boolean equals(RecordDefinition rDef){
final String PROCEDURE_NAME="equals";
boolean valRet=false;
int size=rDef.m_OriginalValues.size();
try{
boolean condModVector=false;
boolean condOrigVector=(rDef.m_OriginalValues.size()==m_OriginalValues.size());
if(condOrigVector){
for(int i=0;i<size;i++){
condOrigVector=(condOrigVector && equalsColumn(rDef.m_OriginalValues,i,m_OriginalValues));
if (!condOrigVector)
break;
}
}
if(condOrigVector){
condModVector=(rDef.m_ModifiedValues.size()==m_ModifiedValues.size());
if(condModVector){
for(int i=0;i<size;i++){
condModVector=(condModVector && equalsColumn(rDef.m_ModifiedValues,i,m_ModifiedValues));
if (!condModVector)
break;
}
}
}
valRet=condOrigVector && condModVector ;
return valRet;
}
catch(Exception e){
errorTreaten(e,PROCEDURE_NAME);
throw new RecordDefinitionException(UNEXPECTED_ERROR_MESSAGE + PROCEDURE_NAME);
}
}
public String getSelectSQL()
{
String sql = null;
if (sql == null) {
sql = "SELECT ";
String tableName=getTableName();
String col[]=getColumns();
if (col == null || col.length==0){
sql+=" * FROM ";
}
else {
for(int i=0; i<col.length-1;i++){
sql+=col[i] + ",";
}
sql+=col[col.length-1] + " FROM ";
}
sql+=tableName;
}
return sql;
}
public Object getKey()
{
return getClass().getName();
}
protected class DesignTimeProperties
{
String connectionName = "";
String managerClassName = "";
String tableName;
String[] columns = null;
}
protected static Hashtable m_DesignTimePropertiesTable = new Hashtable();
protected DesignTimeProperties getDesignTimeProperties()
{
DesignTimeProperties properties = null;
if (m_DesignTimePropertiesTable.containsKey(getKey())) {
properties = (DesignTimeProperties)m_DesignTimePropertiesTable.get(getKey());
}
else {
properties = new DesignTimeProperties();
m_DesignTimePropertiesTable.put(getKey(), properties);
}
return properties;
}
protected void replaceDesignTimeProperties(DesignTimeProperties newProperties)
{
DesignTimeProperties oldProperties = getDesignTimeProperties();
oldProperties.connectionName = newProperties.connectionName;
oldProperties.managerClassName = newProperties.managerClassName;
oldProperties.tableName = newProperties.tableName;
oldProperties.columns = newProperties.columns;
}
public synchronized void setConnectionName(String propertyValue)
{
DesignTimeProperties properties = getDesignTimeProperties();
properties.connectionName = propertyValue;
replaceDesignTimeProperties(properties);
}
public synchronized String getConnectionName()
{
DesignTimeProperties properties = getDesignTimeProperties();
return properties.connectionName;
}
public synchronized void setConnectionManagerClassName(String propertyValue)
{
DesignTimeProperties properties = getDesignTimeProperties();
properties.managerClassName = propertyValue;
replaceDesignTimeProperties(properties);
}
public synchronized String getConnectionManagerClassName()
{
DesignTimeProperties properties = getDesignTimeProperties();
return properties.managerClassName;
}
public synchronized void setTableName(String propertyValue)
{
DesignTimeProperties properties = getDesignTimeProperties();
properties.tableName = propertyValue;
replaceDesignTimeProperties(properties);
}
public synchronized String getTableName()
{
DesignTimeProperties properties = getDesignTimeProperties();
return properties.tableName;
}
public synchronized void addColumn(String propertyValue)
{
DesignTimeProperties properties = getDesignTimeProperties();
if (properties.columns == null) {
properties.columns = new String[1];
properties.columns[0] = propertyValue;
}
else {
int length = properties.columns.length;
String[] temp = new String[length + 1];
System.arraycopy(properties.columns, 0, temp, 0, length);
temp[length] = propertyValue;
properties.columns = temp;
}
replaceDesignTimeProperties(properties);
}
public synchronized void setColumns(String[] propertyValue)
{
DesignTimeProperties properties = getDesignTimeProperties();
properties.columns = propertyValue;
replaceDesignTimeProperties(properties);
}
public synchronized String[] getColumns()
{
DesignTimeProperties properties = getDesignTimeProperties();
return properties.columns;
}
protected class RunTimeProperties
{
ConnectionManager connectionManager = null;
JdbcConnection jdbcConnection = null;
}
protected static Hashtable m_RunTimePropertiesTable = new Hashtable();
protected RunTimeProperties getRunTimeProperties()
{
RunTimeProperties properties = null;
if (m_RunTimePropertiesTable.containsKey(getKey())) {
properties = (RunTimeProperties)m_RunTimePropertiesTable.get(getKey());
}
else {
properties = new RunTimeProperties();
m_RunTimePropertiesTable.put(getKey(), properties);
}
return properties;
}
protected void replaceRunTimeProperties(RunTimeProperties newProperties)
{
RunTimeProperties oldProperties = getRunTimeProperties();
oldProperties.connectionManager = newProperties.connectionManager;
oldProperties.jdbcConnection = newProperties.jdbcConnection;
}
public ConnectionManager getConnectionManager()
{
RunTimeProperties runTimeProperties = getRunTimeProperties();
if (runTimeProperties.connectionManager == null) {
String className = getConnectionManagerClassName();
runTimeProperties.connectionManager = ConnectionManager.getManager(className);
replaceRunTimeProperties(runTimeProperties);
}
return runTimeProperties.connectionManager;
}
public Connection getConnection()
{
RunTimeProperties properties = getRunTimeProperties();
if (properties.jdbcConnection == null) {
try {
ConnectionManager connectionManager = getConnectionManager();
String connectionName = getConnectionName();
properties.jdbcConnection = connectionManager.getConnectionBean(connectionName);
}
catch (SQLException ex) {
throw new RuntimeException(ex.getMessage());
}
replaceRunTimeProperties(properties);
}
return properties.jdbcConnection;
}
public void releaseConnection()
{
getConnectionManager().releaseConnection(getConnectionName());
}
protected PreparedStatement prepareStatement(String sql) throws SQLException
{
JdbcConnection connection = (JdbcConnection)getConnection();
return connection.prepareStatement(sql);
}
protected Statement createStatement() throws SQLException
{
JdbcConnection connection = (JdbcConnection)getConnection();
return connection.createStatement();
}
protected DatabaseMetaData getDatabaseMetaData() throws SQLException
{
JdbcConnection connection = (JdbcConnection)getConnection();
return connection.getMetaData();
}
}