| Method from net.bereza.db.GenericDatabaseItemFactory Detail: |
public synchronized void close() throws DatabaseException {
if(connectionCount > 0)
{
log.println("GDBIF: connectionCount = "+connectionCount);
return;
}
closeConnection=true;
if(conn != null)
{
DatabaseException except=null;
try
{
conn.close();
}
catch(SQLException e)
{
e.printStackTrace(log);
except=new DatabaseException("close():"+e.getMessage());
}
try
{
sequenceConn.close();
}
catch(SQLException e)
{
e.printStackTrace(log);
except=new DatabaseException("close():"+e.getMessage());
}
log.flush();
conn=null;
sequenceConn=null;
if(except != null)
{
throw except;
}
log.println("GenericDatabaseItemFactory: closed connection successfully");
} // if conn != null
}
|
public void deleteFromDatabase(DatabaseItem item) throws DatabaseException {
Connection con=null;
Statement s;
try
{
con=getConnection();
s = con.createStatement();
String query="DELETE FROM "+
item.getTableName()+
" WHERE "+
item.getAttributeFieldNames()[0]+
" = "+item.getId();
log.println("\nGeneric:executing query:"+new java.util.Date()+":\n"+query);
int num = s.executeUpdate(query);
s.close();
if(num==0)
{
throw new DatabaseNoUpdateWarning("DELETE matched no rows:\n"+
query);
}
}
catch(SQLException e)
{
e.printStackTrace(log);
throw new DatabaseException("Problem selecting item", e);
}
catch(DatabaseException dbe)
{
throw dbe;
}
catch(Exception e)
{
e.printStackTrace(log);
throw new DatabaseException("Unknown problem", e);
}
finally
{
releaseConnection(con);
}
}
Delete this item from the database. |
protected Connection getConnection() throws SQLException {
return getConnection(true);
}
Get a shared connection object. |
protected synchronized Connection getConnection(boolean shared) throws SQLException {
touch();
if(conn==null || closeConnection)
{
closeConnection=false;
if(conn!=null)
{
try
{
conn.close();
}
catch(SQLException e)
{
e.printStackTrace(log);
}
conn=null;
}
if(sequenceConn != null)
{
try
{
sequenceConn.close();
}
catch(SQLException e)
{
e.printStackTrace(log);
}
sequenceConn=null;
}
log.println("Getting Connection to:"+dbUrl);
if(dbProps!=null)
{
conn=DriverManager.getConnection(dbUrl, dbProps);
sequenceConn=DriverManager.getConnection(dbUrl, dbProps);
}
else
{
conn=DriverManager.getConnection(dbUrl);
sequenceConn=DriverManager.getConnection(dbUrl);
}
DatabaseMetaData md=conn.getMetaData();
dbMetaData=md;
log.println("Generic:opening connection to DB:"+new java.util.Date()+
":\n\t"+md.getURL()+"\n\t"+md.getUserName()+
"\n\t"+md.getDatabaseProductName()+"\n\t"+
md.getDatabaseProductVersion()+"\n\t"+
md.getDriverName()+"\n\t"+
md.getDriverVersion());
/* only thing from old PostgresDatabaseItemFactory not generic
try
{
Statement s=conn.createStatement();
// set the style
s.executeUpdate("set datestyle='ISO'");
// Now because the driver needs to know what the current style is,
// we have to run the following:
s.executeUpdate("show datestyle");
// This is a limitation, but there is no real way around this.
s.close();
}
catch(SQLException e)
{
e.printStackTrace(log);
}
*/
}
connectionCount++;
if(shared)
{
return conn;
}
else
{
return sequenceConn;
}
}
Get the Connection object used in this Factory. If the connection
is null the Factory will try to reconnect. |
public DateFormat getDateFormat() {
return dateFormatter;
}
Get the DateFormat object that DatabaseItems should
use for parsing date strings. |
public synchronized DatabaseItem getInstance(String name) throws DatabaseException {
String query;
DatabaseItem item=null;
Connection con=null;
try
{
item=newItem(name);
con=getConnection(false); // get an unshared connection
con.setAutoCommit(false);
Statement s = con.createStatement();
query="UPDATE "+item.getSequenceName()+" SET "+
"last_value = last_value + increment_by";
int upd=s.executeUpdate(query);
if(upd == 0)
{
s.close();
throw new DatabaseNoUpdateWarning("Problem incrementing sequence: "+
item.getSequenceName());
}
query="SELECT last_value FROM "+item.getSequenceName();
log.println("\nGeneric:executing query:"+new java.util.Date()+":\n"+query);
ResultSet r = s.executeQuery(query);
if(r.next()) // success
{
item.setId(r.getInt("last_value"));
r.close();
s.close();
con.commit();
}
else
{
r.close();
s.close();
throw new DatabaseSequenceException("Problem getting id from sequence "+
item.getSequenceName());
}
}
catch(SQLException e)
{
if(con != null)
{
try
{
con.rollback();
}
catch(SQLException se)
{
// what'ya gonna do?
}
}
e.printStackTrace(log);
throw new DatabaseException("JDBC SQL problem", e);
}
catch(DatabaseException dbe)
{
if(con != null)
{
try
{
con.rollback();
}
catch(SQLException e)
{
// what'ya gonna do?
}
}
throw dbe;
}
catch(Exception e)
{
if(con != null)
{
try
{
con.rollback();
}
catch(SQLException se)
{
// what'ya gonna do?
}
}
e.printStackTrace(log);
throw new DatabaseException("Unknown problem", e);
}
finally
{
if(con != null)
{
try
{
con.setAutoCommit(true);
}
catch(SQLException e)
{
// what'ya gonna do?
}
}
releaseConnection(con);
}
return item;
}
Create a new DatabaseItem and insert into the database. |
public DatabaseItem getInstance(String name,
int id) throws DatabaseException {
DatabaseItem item=newItem(name);
String fields[]=item.getAttributeFieldNames();
Vector items;
items=getInstances(name, (" WHERE "+fields[0]+" = "+id),
null, false);
if(!items.isEmpty())
{
item=(DatabaseItem)items.firstElement();
}
else
{
throw new DatabaseNoReturnWarning("SELECT "+name+":"+id+
"returned nothing");
}
return item;
}
Get a DatabaseItem from the database. |
public Vector getInstances(String name,
String where) throws DatabaseException {
return getInstances(name, where, null, false);
}
Get an unsorted Vector of DatabaseItems from the database. |
public Hashtable getInstances(String name,
String where,
String field) throws DatabaseException {
Hashtable items=new Hashtable();
Vector itemVec;
DatabaseItem item;
itemVec=getInstances(name, where);
for(Enumeration el=itemVec.elements();el.hasMoreElements();)
{
item=(DatabaseItem)el.nextElement();
items.put(item.getAttributes().get(field), item);
}
return items;
}
Get a Hashtable of DatabaseItems where the key is a String
representation of the value of the specified field. |
public Vector getInstances(String name,
String where,
String field,
boolean up) throws DatabaseException {
Connection con=null;
DatabaseItem item=newItem(name);
String query;
Vector items=new Vector();
String fieldList="";
String fields[]=item.getAttributeFieldNames();
int loop=0;
for(loop=0;loop< fields.length;loop++)
{
if(loop >0)
{
fieldList+=", ";
}
fieldList+=fields[loop];
}
try
{
con=getConnection();
Statement s = con.createStatement();
query="SELECT "+fieldList+" FROM "+
item.getTableName()+" "+
where+
((field!=null)
? (" ORDER by "+field+" "+ ((up) ? "ASC" : "DESC"))
: (""));
log.println("\nGeneric:executing query:"+new java.util.Date()+":\n"+query);
ResultSet r = s.executeQuery(query);
log.println("\nQuery finished.");
ResultSetMetaData rm = r.getMetaData();
while(r.next())
{
item=newItem(name);
Hashtable atts=new Hashtable();
Object obj;
for(loop=0;loop< fields.length;loop++)
{
try
{
if(rm.getColumnType(loop+1) == Types.NUMERIC)
{
// hack to get around libpgjava's ridiculous scale size
obj=r.getBigDecimal(loop+1, 6);
}
else
{
obj=r.getObject(loop+1);
}
atts.put(fields[loop], obj);
}
catch(NullPointerException ne)
{
}
}
log.println(atts);
item.setAttributes(atts);
items.addElement(item);
}
r.close();
s.close();
}
catch(SQLException e)
{
e.printStackTrace(log);
throw new DatabaseException("Problem selecting item", e);
}
catch(DatabaseException dbe)
{
throw dbe;
}
catch(Exception e)
{
e.printStackTrace(log);
throw new DatabaseException("Unknown problem", e);
}
finally
{
releaseConnection(con);
}
return items;
}
Get a Vector of DatabaseItems from the database. |
public TimeZone getTimeZone() {
return java.util.TimeZone.getDefault();
}
Get the default TimeZone used by the Database. |
protected static DatabaseItem newItem(String name) throws DatabaseException {
try
{
Class dbClass=Class.forName(name);
return (DatabaseItem)dbClass.newInstance();
}
catch(ClassNotFoundException e)
{
throw new DatabaseException("Class "+name+" not found", e);
}
catch(IllegalAccessException e)
{
throw new DatabaseException("Could not access class or constructor", e);
}
catch(InstantiationException e)
{
throw new DatabaseException("Could not instantiate item", e);
}
}
Construct a new DatabaseItem object with the specified class name. |
public synchronized void releaseConnection(Connection conObj) {
if(conObj != null)
{
connectionCount--;
}
}
Release the connection object. |
public void setConnectionAttributes(String url,
Properties props) throws DatabaseException {
dbUrl=url;
dbProps=props;
if(dbUrl != null)
{
try
{
getConnection();
}
catch(SQLException sqe)
{
sqe.printStackTrace(System.err);
throw new AuthenticationException(getClass().getName()+
".setConnectionAttributes():"+
sqe.getMessage()+" : "+
sqe.getSQLState()+" "+sqe.getErrorCode(),
sqe);
}
}
}
Set the connection attributes for the Database Connections. |
public synchronized void setLog(PrintWriter logStream) {
if(logStream == null)
{
throw new NullPointerException("Generic:logStream must be non-null");
}
log=logStream;
}
Set the PrintStream to write logging info to. |
public void updateToDatabase(DatabaseItem item) throws DatabaseException {
Connection con=null;
Hashtable atts=item.getAttributes();
String query;
String fieldList="";
String valList="";
String attList="";
String fields[]=item.getAttributeFieldNames();
int loop=0;
int param;
for(loop=0;loop< fields.length;loop++)
{
//if(atts.get(fields[loop]) != null)
//{
if(loop != 0)
{
fieldList+=", ";
valList+=", ";
attList+=", ";
}
fieldList+=fields[loop];
valList+="?";
//"'"+
//DBEncoder.encode(atts.get(fields[loop]).toString())+
//"'";
attList+=fields[loop]+" = ?";
//" = '"+
//DBEncoder.encode(atts.get(fields[loop]).toString())+"' ";
//}
}
try
{
con=getConnection();
Statement s = con.createStatement();
query="SELECT DISTINCT("+fields[0]+") FROM "+
item.getTableName()+
" WHERE "+fields[0]+" = "+
item.getId();
log.println("\nGeneric:executing query:"+new java.util.Date()+":\n"+query);
ResultSet r = s.executeQuery(query);
if(r.next())
{
query="UPDATE "+
item.getTableName()+
" SET "+
attList+
" WHERE "+
fields[0] + " = "+
item.getId();
}
else
{
query="INSERT INTO "+
item.getTableName()+
"("+fieldList+") VALUES "+
"("+valList+")";
}
r.close();
s.close();
log.println("\nGeneric:executing query:"+new java.util.Date()+":\n"+query);
PreparedStatement ps=con.prepareStatement(query);
for(param=1, loop=0;loop< fields.length;loop++)
{
try
{
Object att=atts.get(fields[loop]);
if(att != null)
{
ps.setObject(param++, att);
}
else
{
ps.setNull(param++, Types.NULL);
}
}
catch(SQLException se)
{
String ex=("Problem setting parameter "+(loop+1)+
" with "+fields[loop]+":="+
atts.get(fields[loop]));
log.println(ex);
se.printStackTrace(log);
throw new DatabaseException(ex, se);
}
}
int num = ps.executeUpdate();
ps.close();
if(num==0)
{
throw new DatabaseNoUpdateWarning("UPDATE or INSERT matched no rows:\n"+
query);
}
}
catch(SQLException e)
{
e.printStackTrace(log);
throw new DatabaseException("Problem selecting item", e);
}
catch(DatabaseException dbe)
{
throw dbe;
}
catch(Exception e)
{
e.printStackTrace(log);
throw new DatabaseException("Unknown problem", e);
}
finally
{
releaseConnection(con);
}
}
Update this item to the database. |