baliuka 02/02/07 08:25:36
Added: simplestore/src/sample/org/apache/commons/simplestore/jdbc
DBStorage.java DriverDataSource.java
simplestore/src/sample/org/apache/commons/simplestore/persistence
AbstractStorage.java InternalTransaction.java
MetaObject.java PersistenceManager.java
Persistent.java PersistentProxy.java Storage.java
StorageException.java Transaction.java
TransactionImpl.java TransactionManager.java
Log:
Added sample
Revision Changes Path
1.1
jakarta-commons-sandbox/simplestore/src/sample/org/apache/commons/simplestore/jdbc/DBStorage.java
Index: DBStorage.java
===================================================================
/*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.commons.simplestore.jdbc;
import org.apache.commons.simplestore.persistence.*;
import org.apache.commons.simplestore.*;
// TODO Synchronization
/**
*
* @author Juozas Baliuka <a href="mailto:[EMAIL PROTECTED]">
* [EMAIL PROTECTED]</a>
* @version $Id: DBStorage.java,v 1.1 2002/02/07 16:25:36 baliuka Exp $
*/
public class DBStorage extends AbstractStorage{
private static final boolean DEBUG = true;
private static final String CONNECTION =
"org.apache.commons.simplestore.jdbc.DBStorage.connection";
private static java.util.Map defaults = new java.util.Hashtable();
private Store store = null;
private javax.sql.DataSource ds;
private static java.util.Properties procedures = new java.util.Properties();
static {
defaults.put( byte.class,new java.lang.Byte((byte)0) );
defaults.put( short.class,new java.lang.Short((short)0) );
defaults.put( int.class,new java.lang.Integer(0) );
defaults.put( long.class,new java.lang.Long(0) );
defaults.put( float.class,new java.lang.Float(0) );
defaults.put( double.class,new java.lang.Double(0) );
defaults.put( char.class,new java.lang.Character('\u0000') );
defaults.put( boolean.class,new java.lang.Boolean(false) );
}
interface ResultSetHandler {
public void nextResult(int index,String name,Object value ,int type)throws
StorageException;
}
class QueryHandler implements ResultSetHandler{
java.util.Map map;
java.util.Set objects;
Class clasz;
InternalTransaction transaction = getTransaction();
QueryHandler(java.util.Set objects, Class clasz){
this.objects = objects;
this.clasz = clasz;
}
public void nextResult( int index,String name,Object value , int type
)throws StorageException{
try{
if( index == 1 ){
Persistent p = (Persistent)store.get( value );
if( p != null ){
map = null;
objects.add(p);
transaction.add(p.getMetaObject());
return;
}
p =
PersistentProxy.getPersitent(clasz,value,false,DBStorage.this);
MetaObject pc = p.getMetaObject();
map = pc.getProperties();
objects.add(p);
transaction.add(pc);
return;
}
String property = toPropertyName(name);
if( property.equals("Id") || map == null )
return;
map.put(property , convert(value,getReturnType(clasz,"get" +
property)) );
}catch( java.lang.Throwable t ){
t.printStackTrace();
throw new StorageException( t.getMessage(), t );
}
}
}
/** Creates new DBStorageManager */
public DBStorage(javax.sql.DataSource ds) {
this.ds = ds;
}
public void registerClass( Class clasz ){
try{
java.util.ResourceBundle bundle =
java.util.ResourceBundle.getBundle(clasz.getName() + "Procedures");
java.util.Enumeration enum = bundle.getKeys();
while( enum.hasMoreElements() ){
Object key = enum.nextElement();
procedures.setProperty(key.toString(),bundle.getString(key.toString()));
}
}catch(Exception e){
e.printStackTrace();
}
}
protected void createObject( MetaObject properties ) throws StorageException{
final java.sql.Connection connection = getConnection();
final Class clasz = properties.getPersistentClass();
final Object id = properties.getOID();
final java.lang.reflect.Method methods[] = clasz.getMethods();
final java.util.Map map = properties.getProperties();
final java.util.List values = new java.util.ArrayList( methods.length/2 + 1
);
String names = "";
String params = "";
values.add(id);
for( int i = 0; i < methods.length; i++ ){
String name = methods[i].getName();
if( name.startsWith("set")){
name = name.substring( 3 );
Object value = toSQLType(map.get(name));
if( value == null )continue;
names += "," + toSQLName(name);
values.add(value);
params += ",?";
}
}
final String sql = "INSERT INTO " + toSQLName(clasz.getName()) + "(ID" +
names + ")VALUES(?" + params + ")" ;
excecute(connection,sql,values.toArray(),null);
}
// TODO must be converter interface
public static Object convertNumber(Number number,Class cls){
if(cls.equals(Byte.class))
return new Byte(number.byteValue());
else if( cls.equals(Short.class) )
return new Short(number.shortValue());
else if(cls.equals(Integer.class))
return new Integer(number.intValue());
else if( cls.equals( Long.class ) )
return new Long(number.longValue());
else if( cls.equals( Float.class ) )
return new Float(number.floatValue());
else if( cls.equals( Double.class ) )
return new Double(number.doubleValue());
else if( cls.equals( Boolean.class ) )
return new Boolean( number.intValue() != 0 );
else if( cls.equals( Character.TYPE ) )
return new Character( number.toString().charAt(0) );
else
throw new java.lang.UnsupportedOperationException( "Number class = " +
number.getClass().getName() + " Target Class " + cls.getName());
}
// TODO must be converter interface
public static Object convertPrimityve(Number number,Class cls){
if(cls.equals(Byte.TYPE))
return new Byte(number.byteValue());
else if (cls.equals(Short.TYPE))
return new Short( number.shortValue());
else if(cls.equals(Integer.TYPE))
return new Integer(number.intValue());
else if ( cls.equals( Long.TYPE ) )
return new Long(number.longValue());
else if ( cls.equals( Float.TYPE ) )
return new Float(number.floatValue());
else if ( cls.equals( Double.TYPE ) )
return new Double(number.doubleValue());
else if ( cls.equals( Boolean.TYPE ) )
return new Boolean( number.intValue() != 0 );
else if ( cls.equals( Character.TYPE ) )
return new Character( number.toString().charAt(0) );
else
throw new java.lang.UnsupportedOperationException( "Number class = " +
number.getClass().getName() + " Target Class " + cls.getName());
}
// TODO must be converter interface
public static Object convert(Object object,Class cls){
try{
if( cls.isPrimitive() ){
if( object == null ){
return defaults.get(cls);
}
if( object instanceof Number ){
return convertPrimityve((Number)object,cls);
}
}
if(object == null){
return null;
}
if( cls.isAssignableFrom(object.getClass()) ){
return object;
}
if( object instanceof String ){
return
org.apache.commons.beanutils.ConvertUtils.convert((String)object,cls);
}
if( cls.isAssignableFrom(Number.class ) && object instanceof Number ){
return convertNumber((Number)object,cls);
}
if( cls.equals( Boolean.class ) && object instanceof Number ){
return new Boolean((( Number )object).intValue() != 0 );
}
if( cls.equals( Character.TYPE ) ){
return new Character( object.toString().charAt(0) );
}
throw new java.lang.UnsupportedOperationException( cls.getName() + ":" +
object );
}catch(Throwable t){
// TODO
t.printStackTrace();
throw new RuntimeException( t.getClass().getName() + ":" +
t.getMessage() );
}
}
// TODO must be converter interface
public static Object toSQLType(Object object){
if( object == null )
return null;
if( object instanceof Boolean ){
boolean value = ((Boolean)object).booleanValue();
return ( value ? new Short((short)1) : new Short((short)0) );
}
if( object instanceof java.util.Date && !(object instanceof java.sql.Date) ){
return new java.sql.Date(((java.util.Date)object).getTime());
}
return object;
}
public Class getReturnType( Class clasz, String name )throws java.lang.Throwable{
try{
return clasz.getMethod(name,null).getReturnType();
}catch( java.lang.NoSuchMethodException nsme ){
throw new java.lang.NoSuchMethodException("Method " + name + " not found
in class " + clasz.getName() +" " + nsme.getMessage() );
}
}
public Object retrieveObject(final Class clasz, Object id) throws
StorageException {
final InternalTransaction transaction = getTransaction();
Persistent result = (Persistent)store.get(id);
if( result != null ){
transaction.add(result.getMetaObject());
return result;
}
final java.sql.Connection connection = getConnection();
final String sql = "SELECT * FROM " + toSQLName(clasz.getName()) + " WHERE
ID=?";
result = (Persistent)PersistentProxy.getPersitent(clasz,id,false,this);
final MetaObject pc = result.getMetaObject();
final java.util.Map map = pc.getProperties();
ResultSetHandler rsh = new ResultSetHandler(){
public void nextResult( int index,String name,Object value , int type
)throws StorageException{
try{
if(value != null ){
String property = toPropertyName(name);
if( property.equals("Id") )
return;
map.put(property , convert(value,getReturnType(clasz,"get" +
property)) );
}
}catch(java.lang.Throwable t){
t.printStackTrace();
throw new StorageException(t.getMessage(),t);
}
}
};
if( excecute(connection,sql,new Object[]{id}, rsh ) == 0 )
throw new ObjectNotFound( pc.getOID().toString(), null );
transaction.add(pc);
store.put(id,result);
return result;
}
public java.util.Set retrieveAll(final Class clasz) throws StorageException{
final java.sql.Connection connection = getConnection();
final String sql = "SELECT ID AS INTERNAL_OID, * FROM " + toSQLName(
clasz.getName() );
final java.util.Set objects = new java.util.HashSet();
final InternalTransaction transaction = getTransaction();
excecute(connection,sql,null,new QueryHandler( objects, clasz ));
return objects;
}
public java.util.Set query(final Class clasz, String proc, Object[] args) throws
StorageException{
final java.sql.Connection connection = getConnection();
final java.util.Set objects = new java.util.HashSet();
final InternalTransaction transaction = getTransaction();
proc = procedures.getProperty(proc);
excecute(connection,proc,args, new QueryHandler(objects,clasz) );
return objects;
}
// TODO must be mapping interface
public static String toSQLName(String clName){
String result = clName.substring(clName.lastIndexOf('.') + 1,
clName.length() );
StringBuffer sb = new StringBuffer();
char cbuff [] = result.toCharArray();
for(int i = 0; i < cbuff.length; i++ ){
if( Character.isUpperCase( cbuff[i] )){
if( i != 0 ){
sb.append( "_" + cbuff[i] );
}else sb.append( cbuff[i] );
}else{
sb.append( Character.toUpperCase(cbuff[i]) );
}
}
return sb.toString();
}
// TODO must be mapping interface
public static String toPropertyName(String tblName){
final String result = tblName;
final StringBuffer sb = new StringBuffer();
final char cbuff [] = result.toCharArray();
for( int i = 0; i < cbuff.length; i++ ){
if( cbuff[i] == '_' ){
sb.append( Character.toUpperCase(cbuff[ ++i ]) );
}else{
if( i == 0 )
sb.append( Character.toUpperCase(cbuff[i]) );
else sb.append( Character.toLowerCase(cbuff[i]) );
}
}
return sb.toString();
}
protected void removeObject( MetaObject obj )throws StorageException{
final java.sql.Connection connection = getConnection();
final String name = toSQLName(obj.getPersistentClass().getName());
final Object id = obj.getOID();
final String sql = "DELETE FROM " + name + " WHERE ID=?";
excecute(connection,sql, new Object[]{id}, null );
}
public void storeObject(MetaObject properties) throws StorageException {
final java.sql.Connection connection = getConnection();
final Class clasz = properties.getPersistentClass();
final String name = toSQLName(clasz.getName());
final java.lang.reflect.Method methods[] = clasz.getMethods();
final java.util.List values = new java.util.ArrayList( methods.length/2 + 1
);
final java.util.Map map = properties.getProperties();
final StringBuffer names = new StringBuffer(methods.length*10);
for( int i = 0; i < methods.length; i++ ){
String mName = methods[i].getName();
if( mName.startsWith("set")){
mName = mName.substring(3);
Object value = toSQLType(map.get( mName ));
names.append(toSQLName( mName ));
names.append("=?,");
values.add( value );
}
}
names.setCharAt(names.length() - 1,' ');
names.append("WHERE ID=?");
values.add(properties.getOID());
final String sql = "UPDATE " + name + " SET " + names;
excecute(connection,sql,values.toArray(),null);
}
protected void internalCommit() throws StorageException {
try{
java.sql.Connection connection = getConnection();
try{
connection.commit();
}finally{
connection.close();
}
}catch( java.sql.SQLException se){
throw new StorageException(se.getMessage() ,se);
}
}
protected void internalRollback() throws StorageException {
try{
java.sql.Connection connection = getConnection();
try{
connection.rollback();
}finally{
connection.close();
}
}catch( java.sql.SQLException se){
throw new StorageException(se.getMessage() ,se);
}
}
protected void internalBegin() throws StorageException {
try{
java.sql.Connection connection = ds.getConnection();
getTransaction().setAttribute(CONNECTION,connection);
}catch( java.sql.SQLException se){
throw new StorageException(se.getMessage() ,se);
}
}
static public int excecute(java.sql.Connection connection,String sql,Object[]
args,ResultSetHandler eh )throws StorageException{
int result = 0;
try{
final java.sql.PreparedStatement statement =
connection.prepareStatement(sql);
java.sql.ResultSet rs = null;
if( DEBUG ){
System.out.println(sql);
}
try{
if(args != null){
for(int i = 1 ; i <= args.length; i++ ){
if(args[ i - 1 ] == null ){
statement.setNull(i , java.sql.Types.OTHER);
}else{
statement.setObject(i,args[i - 1]);
}
}
}
if( statement.execute()){
rs = statement.getResultSet();
}else{
return statement.getUpdateCount();
}
do{
if(rs != null && eh != null){
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int cnt = rsmd.getColumnCount();
while(rs.next()){
result++;
for(int i = 1; i <= cnt; i++ ){
String name = rsmd.getColumnName(i);
Object val = rs.getObject(i);
eh.nextResult(i,name,val,rsmd.getColumnType(i));
}
}
}
if(statement.getMoreResults())
rs = statement.getResultSet();
else break;
}while(rs != null);
}finally{
if( rs != null)
rs.close();
if(statement != null)
statement.close();
}
}catch( java.sql.SQLException se ){
throw new StorageException(sql,se);
}
return result;
}
public void close() {
try{
java.sql.Connection connection =
(java.sql.Connection)getTransaction().getAttribute(CONNECTION);
if( connection != null )
connection.close();
}catch( Exception e){
e.printStackTrace();
// TODO
}
}
public void setContext(Store store) {
this.store = store;
}
private java.sql.Connection getConnection(){
java.sql.Connection connection =
(java.sql.Connection)getTransaction().getAttribute(CONNECTION);
if( connection == null )
throw new java.lang.IllegalStateException("Transaction not Started");
return connection;
}
}
1.1
jakarta-commons-sandbox/simplestore/src/sample/org/apache/commons/simplestore/jdbc/DriverDataSource.java
Index: DriverDataSource.java
===================================================================
/*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.commons.simplestore.jdbc;
import java.sql.*;
import java.util.*;
/**
*
* @author Juozas Baliuka <a href="mailto:[EMAIL PROTECTED]">
* [EMAIL PROTECTED]</a>
* @version $Id: DriverDataSource.java,v 1.1 2002/02/07 16:25:36 baliuka Exp $
*
* This is light weight Read Only Datasource implementation, asumes Driver returns
reentrant connections
* it tested and designed for PostgresSQL JDBC driver only.
*
*/
public class DriverDataSource implements javax.sql.DataSource {
private final java.util.Properties properties = new java.util.Properties();
private ConnectionWrapper connection[] = null;
private int counter = 0;
private java.sql.Driver driver;
/** Holds value of property user. */
private String user;
/** Holds value of property password. */
private String password;
/** Holds value of property url. */
private String url;
/** Holds value of property maxConnections. */
private int maxConnections = 5;
/** Creates new DriverDataSourceFactoryImpl */
public DriverDataSource() {
}
/** Getter for property user.
* @return Value of property user.
*/
public String getUser() {
return user;
}
/** Setter for property user.
* @param user New value of property user.
*/
public void setUser(String user) {
if( this.user != null )
throw new java.lang.IllegalStateException();
this.user = user;
properties.setProperty("user",user);
}
/** Getter for property password.
* @return Value of property password.
*/
public String getPassword() {
return password;
}
/** Setter for property password.
* @param password New value of property password.
*/
public void setPassword(String password) {
if( this.password != null )
throw new java.lang.IllegalStateException();
properties.setProperty("password",password);
this.password = password;
}
/** Getter for property url.
* @return Value of property url.
*/
public String getUrl() {
return url;
}
/** Setter for property url.
* @param url New value of property url.
*/
public void setUrl(String url) {
if( this.url != null )
throw new java.lang.IllegalStateException();
this.url = url;
}
private ConnectionWrapper newConnection() throws java.sql.SQLException{
java.sql.Connection con = driver.connect(url,properties);
con.setAutoCommit(false);
return new ConnectionWrapper(con);
}
public java.sql.Connection getConnection() throws java.sql.SQLException{
synchronized(this){
if( connection == null )
connection = new ConnectionWrapper[maxConnections];
counter = (counter + 1)%maxConnections;
for(int i = 0; i < maxConnections; i++ )
if(connection[i] != null)
if(!connection[i].isUsed()){
counter = i;
break;
}
if(connection[counter] == null)
connection[counter] = newConnection();
if(connection[counter].isClosed()){
try{
connection[counter].release();
}catch(Exception ignore){
}
connection[counter] = newConnection();
}
connection[counter].setUsed(true);
return connection[counter];
}
}
public java.io.PrintWriter getLogWriter() throws java.sql.SQLException {
return new java.io.PrintWriter(System.out);
}
public void setLogWriter(java.io.PrintWriter printWriter) throws
java.sql.SQLException {
}
public void setLoginTimeout(int param) throws java.sql.SQLException {
}
public java.sql.Connection getConnection(java.lang.String str, java.lang.String
str1) throws java.sql.SQLException {
return getConnection();
}
public int getLoginTimeout() throws java.sql.SQLException {
return 0;
}
/** Getter for property maxConnections.
* @return Value of property maxConnections.
*/
public int getMaxConnections() {
return maxConnections;
}
/** Setter for property maxConnections.
* @param maxConnections New value of property maxConnections.
*/
public void setMaxConnections(int maxConnections) {
if(connection != null)
throw new java.lang.IllegalStateException();
this.maxConnections = maxConnections;
}
/** Setter for property driver.
* @param driver New value of property driver.
*/
public void setDriver(String driver) {
if( this.driver != null )
throw new java.lang.IllegalStateException();
try{
this.driver = (java.sql.Driver)Class.forName(driver).newInstance();
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
}
/**
*
* @author Juozas Baliuka
* @version $Id: DriverDataSource.java,v 1.1 2002/02/07 16:25:36 baliuka Exp $
*/
class ConnectionWrapper implements Connection {
boolean used = true;
private Connection connection;
public void release()throws SQLException {
connection.close();
}
public boolean isUsed(){
return used;
}
public void setUsed(boolean used){
this.used = used;
}
public ConnectionWrapper(Connection connection ) {
this.connection = connection;
}
public void close() throws SQLException {
setUsed(false);
}
public Statement createStatement() throws SQLException {
return connection.createStatement();
}
public PreparedStatement prepareStatement(String sql) throws SQLException {
return connection.prepareStatement(sql);
}
public CallableStatement prepareCall(String sql) throws SQLException {
return connection.prepareCall(sql);
}
public String nativeSQL(String sql) throws SQLException {
return connection.nativeSQL(sql);
}
public void setAutoCommit(boolean autoCommit) throws SQLException {
connection.setAutoCommit(autoCommit);
}
public boolean getAutoCommit() throws SQLException {
return connection.getAutoCommit();
}
public void commit() throws SQLException {
connection.commit();
}
public void rollback() throws SQLException {
connection.rollback();
}
public boolean isClosed() throws SQLException {
if( connection == null ){
return true;
}
try{
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT 1");
rs.next();
rs.getInt(1);
rs.close();
stmt.close();
}catch(Exception sqle){
try{
connection.close();
}catch(Exception ignore){}
return true;
}
return connection.isClosed();
}
public DatabaseMetaData getMetaData() throws SQLException {
return connection.getMetaData();
}
public void setReadOnly(boolean readOnly) throws SQLException {
connection.setReadOnly(readOnly);
}
public boolean isReadOnly() throws SQLException {
return connection.isReadOnly();
}
public void setCatalog(String catalog) throws SQLException {
connection.setCatalog(catalog);
}
public String getCatalog() throws SQLException {
return connection.getCatalog();
}
public void setTransactionIsolation(int level) throws SQLException {
connection.setTransactionIsolation(level);
}
public int getTransactionIsolation() throws SQLException {
return connection.getTransactionIsolation();
}
public SQLWarning getWarnings() throws SQLException {
return connection.getWarnings();
}
public void clearWarnings() throws SQLException {
connection.clearWarnings();
}
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException {
return connection.createStatement(resultSetType,resultSetConcurrency);
}
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
return connection.prepareStatement(sql, resultSetType, resultSetConcurrency);
}
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
return connection.prepareCall(sql, resultSetType, resultSetConcurrency);
}
public java.util.Map getTypeMap() throws java.sql.SQLException {
return connection.getTypeMap();
}
public void setTypeMap(Map map) throws SQLException {
connection.setTypeMap(map);
}
}
1.1
jakarta-commons-sandbox/simplestore/src/sample/org/apache/commons/simplestore/persistence/AbstractStorage.java
Index: AbstractStorage.java
===================================================================
/*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.commons.simplestore.persistence;
import com.mw.persist.*;
/**
*
* @author Juozas Baliuka <a href="mailto:[EMAIL PROTECTED]">
* [EMAIL PROTECTED]</a>
* @version $Id: AbstractStorage.java,v 1.1 2002/02/07 16:25:36 baliuka Exp $
*/
public abstract class AbstractStorage implements Storage, InternalTransaction,
TransactionManager{
java.util.Map attributes = new java.util.HashMap();
protected abstract void createObject( MetaObject properties )throws
StorageException;
protected abstract void removeObject( MetaObject properties )throws
StorageException;
protected abstract void internalCommit()throws StorageException;
protected abstract void internalRollback()throws StorageException;
protected abstract void internalBegin()throws StorageException;
public InternalTransaction getTransaction() {
return TransactionImpl.getInstance(this);
}
public void begin(java.util.Set objects) {
try{
internalBegin();
}catch(java.lang.Throwable t){
// TODO
t.printStackTrace();
throw new RuntimeException(t.getClass() + ":" + t.getMessage());
}
}
public void add(MetaObject props) {
((InternalTransaction)getTransaction()).add(props);
}
public void commit() {
try{
getTransaction().commit();
internalCommit();
}catch(java.lang.Throwable t){
// TODO
t.printStackTrace();
throw new RuntimeException(t.getClass() + ":" + t.getMessage());
}
}
public void begin() {
try{
getTransaction().begin();
internalBegin();
}catch(java.lang.Throwable t){
// TODO
throw new RuntimeException(t.getClass() + ":" + t.getMessage());
}
}
public void rollback(java.util.Set objects) {
try{
//TODO implement roolback
internalRollback();
objects.clear();
}catch(java.lang.Throwable t){
throw new RuntimeException(t.getClass() + ":" + t.getMessage());
}
}
public void rollback() {
try{
getTransaction().rollback();
internalRollback();
}catch(java.lang.Throwable t){
// TODO
throw new RuntimeException(t.getClass() + ":" + t.getMessage());
}
}
public void commit(java.util.Set objects) {
try{
java.util.Iterator iterator = objects.iterator();
while(iterator.hasNext()){
MetaObject pp = (MetaObject)iterator.next();
if( pp.isNew() ){
createObject(pp);
}
if( pp.isDirty() && ! pp.isNew() ){
storeObject(pp);
}
if( pp.isDeleted() ){
removeObject(pp);
}
pp.setDirty(false);
}
objects.clear();
internalCommit();
}catch( Throwable t ){
// TODO
t.printStackTrace();
throw new java.lang.RuntimeException("Error");
}
}
public Object getAttribute(String name) {
return attributes.get(name);
}
public void removeAttribute(String name) {
attributes.remove(name);
}
public void setAttribute(String name, Object value) {
attributes.put(name,value);
}
}
1.1
jakarta-commons-sandbox/simplestore/src/sample/org/apache/commons/simplestore/persistence/InternalTransaction.java
Index: InternalTransaction.java
===================================================================
/*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.commons.simplestore.persistence;
/**
*
* @author Juozas Baliuka <a href="mailto:[EMAIL PROTECTED]">
* [EMAIL PROTECTED]</a>
* @version $Id: InternalTransaction.java,v 1.1 2002/02/07 16:25:36 baliuka Exp $
*/
public interface InternalTransaction extends Transaction {
public void begin(java.util.Set objects);
public void commit(java.util.Set objects);
public void rollback(java.util.Set objects);
void add( MetaObject props);
void setAttribute(String name,Object value);
Object getAttribute(String name );
void removeAttribute(String name );
}
1.1
jakarta-commons-sandbox/simplestore/src/sample/org/apache/commons/simplestore/persistence/MetaObject.java
Index: MetaObject.java
===================================================================
/*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.commons.simplestore.persistence;
/**
*
* @author Juozas Baliuka <a href="mailto:[EMAIL PROTECTED]">
* [EMAIL PROTECTED]</a>
* @version $Id: MetaObject.java,v 1.1 2002/02/07 16:25:36 baliuka Exp $
*/
public interface MetaObject {
public Object getOID();
public Object getProperty(String name);
public void setProperty(String name,Object value);
public java.util.Map getProperties();
public Class getPersistentClass();
public boolean isDirty();
public boolean isNew();
public boolean isDeleted();
public void remove();
public boolean isLoaded();
public void setDirty(boolean dirty);
}
1.1
jakarta-commons-sandbox/simplestore/src/sample/org/apache/commons/simplestore/persistence/PersistenceManager.java
Index: PersistenceManager.java
===================================================================
/*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.commons.simplestore.persistence;
import org.apache.commons.simplestore.*;
/**
*
* @author Juozas Baliuka <a href="mailto:[EMAIL PROTECTED]">
* [EMAIL PROTECTED]</a>
* @version $Id: PersistenceManager.java,v 1.1 2002/02/07 16:25:36 baliuka Exp $
*/
public class PersistenceManager {
private static PersistenceManager pm;
private Storage storage;
private TransactionManager transactionManager;
private Store store = SoftRefMemoryStore.getInstance( new java.util.HashMap(),
null , 0xFF );
/** Creates new PersiatenceManager */
protected PersistenceManager( Storage storage, TransactionManager
transactionManager ) {
this.storage = storage;
this.transactionManager = transactionManager;
}
static public PersistenceManager getPersistenceManager( Storage
storage,TransactionManager transactions ){
if( pm == null ){
pm = new PersistenceManager( storage,transactions );
storage.setContext(pm.store);
}
return pm;
}
public Transaction getTransaction(){
return transactionManager.getTransaction();
}
public Object createInstance( Class aclass ){
Object id = generateOID(aclass);
Persistent p =
PersistentProxy.getPersitent(aclass,id,true,transactionManager);
return p;
}
public Object findInstance( Class clasz,Object oid )throws StorageException{
return storage.retrieveObject(clasz, oid );
}
public java.util.Set findAll( Class clasz )throws StorageException{
return storage.retrieveAll( clasz );
}
public void removeInstance(Object pc){
MetaObject p = ((Persistent)pc).getMetaObject();
if( p != null )
p.remove();
}
public Object getOID( Object pc ){
return ((Persistent)pc).getOID();
}
public void registerClass( Class clasz )throws StorageException{
storage.registerClass(clasz);
}
private static java.security.SecureRandom seeder = new
java.security.SecureRandom();
private synchronized Object generateOID( Class aclass ){
//TODO ADD interface OIDGenerator
byte[] bytes = new byte[8];
int value = seeder.nextInt();
int i = 0;
bytes[i++] = (byte) ((value >>> 24) & 0xFF);
bytes[i++] = (byte) ((value >>> 16) & 0xFF);
bytes[i++] = (byte) ((value >>> 8) & 0xFF);
bytes[i++] = (byte) (value & 0xFF);
value = (int) System.currentTimeMillis() & 0xFFFFFFFF;
bytes[i++] = (byte) ((value >>> 24) & 0xFF);
bytes[i++] = (byte) ((value >>> 16) & 0xFF);
bytes[i++] = (byte) ((value >>> 8) & 0xFF);
bytes[i++] = (byte) (value & 0xFF);
return new Long( new java.math.BigInteger(bytes).longValue());
}
}
1.1
jakarta-commons-sandbox/simplestore/src/sample/org/apache/commons/simplestore/persistence/Persistent.java
Index: Persistent.java
===================================================================
/*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.commons.simplestore.persistence;
/**
*
* @author Juozas Baliuka <a href="mailto:[EMAIL PROTECTED]">
* [EMAIL PROTECTED]</a>
* @version $Id: Persistent.java,v 1.1 2002/02/07 16:25:36 baliuka Exp $
*/
public interface Persistent {
public Object getOID();
public MetaObject getMetaObject();
}
1.1
jakarta-commons-sandbox/simplestore/src/sample/org/apache/commons/simplestore/persistence/PersistentProxy.java
Index: PersistentProxy.java
===================================================================
/*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.commons.simplestore.persistence;
import java.lang.reflect.*;
/**
*
* @author Juozas Baliuka <a href="mailto:[EMAIL PROTECTED]">
* [EMAIL PROTECTED]</a>
* @version $Id: PersistentProxy.java,v 1.1 2002/02/07 16:25:36 baliuka Exp $
*/
public class PersistentProxy implements MetaObject, InvocationHandler,
java.io.Serializable {
static Method HASH_CODE;
static Method EQUALS;
static Method TO_STRING;
static Method GET_OID;
static Method GET_META_OBJECT;
static{
try{
GET_OID = Persistent.class.getMethod("getOID",null);
GET_META_OBJECT = Persistent.class.getMethod("getMetaObject",null);
HASH_CODE = Object.class.getMethod("hashCode",null);
TO_STRING = Object.class.getMethod("toString",null);
EQUALS = Object.class.getMethod("equals",new
Class[]{Object.class});
}catch(Exception e){
e.printStackTrace();
throw new Error(e.getMessage());
}
}
java.util.Map map = new java.util.HashMap();
Object oid = null;
Class pClass;
TransactionManager transactionManager;
boolean dirty = false;
boolean deleted = false;
boolean newCreated ;
/** Creates new ValueProxy */
public PersistentProxy(Class pClass,Object oid, boolean newCreated,
TransactionManager transactionManager) {
this.oid = oid;
this.newCreated = newCreated;
this.transactionManager = transactionManager;
this.pClass = pClass;
}
public java.lang.Object handleEquals(java.lang.Object obj ){
if( obj == null ){
return new Boolean(false);
}
if(! (obj instanceof Persistent ) ){
return new Boolean(false);
}
Persistent object = (Persistent)obj;
if( oid == null ){
return new Boolean( oid == object.getOID() );
}else{
return new Boolean( oid.equals( object.getOID() ) );
}
}
public java.lang.Object invoke(Object obj, Method method, Object[] obj2) throws
java.lang.Throwable {
synchronized( this ){
if ( GET_META_OBJECT.equals( method) ){
return this;
}else if( TO_STRING.equals( method ) ){
return oid;
}else if( GET_OID.equals( method ) ){
return oid;
}else if ( HASH_CODE.equals( method ) ){
if(oid == null){
return new Integer(0);
}
return new Integer(oid.hashCode());
}else if( EQUALS.equals(method) ){
return handleEquals(obj2[0]);
} else{
return handleProperty(obj,method,obj2);
}
}
}
public java.lang.Object handleProperty(java.lang.Object obj,
java.lang.reflect.Method method, java.lang.Object[] obj2) throws java.lang.Throwable {
String name = method.getName();
if( name.startsWith("set")){
setProperty(name.substring(3), obj2[0] );
return null;
}else if( name.startsWith("get") || name.startsWith("is") ){
if(method.getName().startsWith("get"))
name = method.getName().substring(3);
else name = method.getName().substring(2);
return getProperty(name);
}
throw new java.lang.IllegalStateException("pure method " + method.getName());
}
public static Persistent getPersitent(Class persistent,Object oid,boolean
newCreated, TransactionManager transactionManager){
Persistent p = (Persistent)Proxy.newProxyInstance(
ClassLoader.getSystemClassLoader(),new Class[]{persistent,Persistent.class},
new PersistentProxy(persistent,oid,newCreated, transactionManager));
if( newCreated ) {
MetaObject mo = p.getMetaObject();
transactionManager.getTransaction().add(mo);
}
return p;
}
public boolean isDeleted() {
return deleted;
}
public boolean isNew() {
return newCreated;
}
public MetaObject getMetaObject() {
return this;
}
public void setProperty( String name, Object value ) {
Object old = map.put(name,value);
if( old == null || !old.equals(value )){
dirty = true;
transactionManager.getTransaction().add( this );
}
}
public java.util.Map getProperties() {
return map;
}
public Object getProperty(String name) {
return map.get(name);
}
public boolean isLoaded() {
return true;
}
public void remove() {
deleted = true;
}
public Class getPersistentClass() {
return pClass;
}
public Object getOID() {
return oid;
}
public boolean isDirty() {
return dirty;
}
public void setDirty(boolean dirty) {
this.dirty = dirty;
this.newCreated = false;
}
}
1.1
jakarta-commons-sandbox/simplestore/src/sample/org/apache/commons/simplestore/persistence/Storage.java
Index: Storage.java
===================================================================
/*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.commons.simplestore.persistence;
import org.apache.commons.simplestore.*;
/**
*
* @author Juozas Baliuka <a href="mailto:[EMAIL PROTECTED]">
* [EMAIL PROTECTED]</a>
* @version $Id: Storage.java,v 1.1 2002/02/07 16:25:36 baliuka Exp $
*/
public interface Storage {
public void storeObject( MetaObject properties )throws StorageException;
public Object retrieveObject( Class clasz, Object id )throws StorageException;
public void registerClass( Class clasz )throws StorageException;
public void setContext( Store store );
public java.util.Set retrieveAll( Class clasz )throws StorageException;
public java.util.Set query( Class clasz, String procName,Object[] args )throws
StorageException;
public void close()throws StorageException;
}
1.1
jakarta-commons-sandbox/simplestore/src/sample/org/apache/commons/simplestore/persistence/StorageException.java
Index: StorageException.java
===================================================================
/*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.commons.simplestore.persistence;
/**
*
* @author Juozas Baliuka <a href="mailto:[EMAIL PROTECTED]">
* [EMAIL PROTECTED]</a>
* @version $Id: StorageException.java,v 1.1 2002/02/07 16:25:36 baliuka Exp $
*/
public class StorageException extends java.lang.Exception {
public Throwable detail;
/**
* Creates new <code>StorageException</code> without detail message.
*/
public StorageException() {
}
/**
* Constructs an <code>StorageException</code> with the specified detail message.
* @param msg the detail message.
* @param detail the detail Throwable.
*/
public StorageException(String msg,Throwable detail ) {
super(msg);
this.detail = detail;
}
public java.lang.String getMessage() {
return super.getMessage() + ( detail == null ? "" : " : " +
detail.getMessage() ) ;
}
}
1.1
jakarta-commons-sandbox/simplestore/src/sample/org/apache/commons/simplestore/persistence/Transaction.java
Index: Transaction.java
===================================================================
/*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.commons.simplestore.persistence;
/**
*
* @author Juozas Baliuka <a href="mailto:[EMAIL PROTECTED]">
* [EMAIL PROTECTED]</a>
* @version $Id: Transaction.java,v 1.1 2002/02/07 16:25:36 baliuka Exp $
*/
public interface Transaction {
void begin();
void commit();
void rollback();
// TODO Transaction Synchronization
}
1.1
jakarta-commons-sandbox/simplestore/src/sample/org/apache/commons/simplestore/persistence/TransactionImpl.java
Index: TransactionImpl.java
===================================================================
/*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.commons.simplestore.persistence;
import org.apache.commons.simplestore.*;
/**
*
* @author Juozas Baliuka <a href="mailto:[EMAIL PROTECTED]">
* [EMAIL PROTECTED]</a>
* @version $Id: TransactionImpl.java,v 1.1 2002/02/07 16:25:36 baliuka Exp $
*/
public class TransactionImpl implements InternalTransaction{
static private Store instances = SoftRefMemoryStore.getInstance( new
java.util.HashMap(), null , 0x00 );
int threadId = getCurrentThreadId();
InternalTransaction transaction;
java.util.Set objects;
java.util.Map attributes = new java.util.HashMap();
boolean complete = true;
/** Creates new TransactionImpl */
public TransactionImpl( InternalTransaction transaction, java.util.Set objects) {
this.objects = objects;
this.transaction = transaction;
}
private static int getCurrentThreadId(){
return System.identityHashCode( Thread.currentThread() );
}
public static InternalTransaction getInstance(InternalTransaction transaction){
Number threadId = new Integer(getCurrentThreadId());
InternalTransaction tr = (InternalTransaction) instances.get(threadId);
if( tr != null )return tr;
tr = new TransactionImpl(transaction,new java.util.HashSet());
instances.put(threadId,tr);
return tr;
}
public void commit() {
checkState();
checkState(!complete);
transaction.commit(objects);
complete = true;
}
public void begin() {
checkState();
checkState( complete );
transaction.begin( objects );
complete = false;
}
public void rollback() {
checkState();
checkState( !complete );
transaction.rollback( objects );
complete = true;
}
public int getThreadId(){
return threadId;
}
void checkState( boolean b ){
if( !b )
throw new java.lang.IllegalStateException("Illegal Transaction state");
}
void checkState(){
int id = getCurrentThreadId();
if( threadId != id )
throw new java.lang.IllegalStateException("Accessed Transaction " +
threadId + " in " + id);
}
public void add(MetaObject props) {
checkState();
objects.add(props);
}
public void begin(java.util.Set objects) {
transaction.begin(objects);
}
public void rollback(java.util.Set objects) {
transaction.rollback(objects);
}
public void commit(java.util.Set objects) {
transaction.commit(objects);
}
public Object getAttribute(String name) {
return attributes.get(name);
}
public void removeAttribute(String name) {
attributes.remove(name);
}
public void setAttribute(String name, Object value) {
attributes.put(name,value);
}
}
1.1
jakarta-commons-sandbox/simplestore/src/sample/org/apache/commons/simplestore/persistence/TransactionManager.java
Index: TransactionManager.java
===================================================================
/*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.commons.simplestore.persistence;
/**
*
* @author Juozas Baliuka <a href="mailto:[EMAIL PROTECTED]">
* [EMAIL PROTECTED]</a>
* @version $Id: TransactionManager.java,v 1.1 2002/02/07 16:25:36 baliuka Exp $
*/
public interface TransactionManager {
public InternalTransaction getTransaction();
}
--
To unsubscribe, e-mail: <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>