⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 raplasql.java

📁 Rapla是一个灵活的多用户资源管理系统。它提供的一些功能有:日历GUI
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/*--------------------------------------------------------------------------*
 | Copyright (C) 2006 Christopher Kohlhaas                                  |
 |                                                                          |
 | This program is free software; you can redistribute it and/or modify     |
 | it under the terms of the GNU General Public License as published by the |
 | Free Software Foundation. A copy of the license has been included with   |
 | these distribution in the COPYING file, if not go to www.fsf.org .       |
 |                                                                          |
 | As a special exception, you are granted the permissions to link this     |
 | program with every library, of which license fullfill the Open Source     |
 | Definition as published by the Open Source Initiative (OSI).             |
 *--------------------------------------------------------------------------*/
package org.rapla.storage.dbsql;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.TreeMap;

import org.apache.avalon.framework.logger.Logger;
import org.rapla.components.util.Assert;
import org.rapla.entities.Category;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.internal.PreferencesImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.RepeatingType;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.domain.internal.AppointmentImpl;
import org.rapla.entities.domain.internal.PeriodImpl;
import org.rapla.entities.domain.internal.PermissionImpl;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.Classifiable;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.internal.AttributeImpl;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.entities.internal.UserImpl;
import org.rapla.entities.storage.RefEntity;
import org.rapla.entities.storage.internal.SimpleIdentifier;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.storage.xml.CategoryReader;
import org.rapla.storage.xml.PreferenceReader;
import org.rapla.storage.xml.RaplaXMLReader;
import org.rapla.storage.xml.RaplaXMLWriter;
import org.xml.sax.SAXException;

class RaplaSQL {
    private List stores = new ArrayList();
    private Logger logger;
    
    RaplaSQL( RaplaContext context, boolean oldResourceTable) throws RaplaException{
        logger = ( Logger) context.lookup( Logger.class.getName());
        // The order is important. e.g. appointments can only be loaded if the reservation they are refering to are already loaded.
	    stores.add(new CategoryStorage( context));
	    stores.add(new DynamicTypeStorage( context));
		stores.add(new UserStorage( context));
	    stores.add(new AllocatableStorage( context, oldResourceTable));
	    stores.add(new PreferenceStorage( context));
		stores.add(new PeriodStorage( context));
	    stores.add(new ReservationStorage( context));
		stores.add(new AppointmentStorage( context));
	}


    protected Logger getLogger() {
    	return logger;
    }

/***************************************************
 *   Create everything                             *
 ***************************************************/
    synchronized public void createAll(Connection con)
        throws SQLException,RaplaException
    {
		getLogger().info("Inserting Data in Database");
		Iterator it = stores.iterator();
		while (it.hasNext()) {
		    Storage storage = (Storage) it.next();
		    storage.setConnection(con);
		    ((RaplaTypeStorage) storage).insertAll();
		}
    }

    synchronized public void removeAll(Connection con)
    throws SQLException,RaplaException
    {
        getLogger().info("Deleting all Data in Database");
        ListIterator listIt = stores.listIterator(stores.size());
        while (listIt.hasPrevious()) {
            Storage storage = (Storage) listIt.previous();
            storage.setConnection(con);
            storage.deleteAll();
        }
    }

    synchronized public void loadAll(Connection con) throws SQLException,RaplaException {
		Iterator it = stores.iterator();
		while (it.hasNext()) {
		    Storage storage = (Storage) it.next();
		    storage.setConnection(con);
		    storage.loadAll();
		}
    }

    synchronized public void remove(Connection con,RefEntity entity) throws SQLException,RaplaException {
    	if ( Attribute.TYPE.equals(  entity.getRaplaType() ))
			return;
    	Iterator it = stores.iterator();
		while (it.hasNext()) {
		    Storage storage = (Storage) it.next();
		    if (((RaplaTypeStorage)storage).canStore(entity)) {
		    	storage.setConnection(con);
		    	storage.delete((RefEntity)entity);
		    	return;
		    }
		}
		throw new RaplaException("No Storage-Sublass matches this object: " + entity.getClass());
    }

    synchronized public void store(Connection con, RaplaObject entity) throws SQLException,RaplaException {
        if ( Attribute.TYPE.equals(  entity.getRaplaType() ))
            return;
    	Iterator it = stores.iterator();
		while (it.hasNext()) {
		    Storage storage = (Storage)it.next();
		    if (((RaplaTypeStorage)storage).canStore(entity)) {
		    	storage.setConnection(con);
		    	storage.save((RefEntity)entity);
		    	return;
		    }
		}
		throw new RaplaException("No Storage-Sublass matches this object: " + entity.getClass());
    }
}

abstract class RaplaTypeStorage extends EntityStorage {
	RaplaType raplaType;

	RaplaTypeStorage( RaplaContext context, RaplaType raplaType, String tableName, String[] entries) throws RaplaException {
		super( context,tableName, entries );
		this.raplaType = raplaType;
	}
    boolean canStore(RaplaObject entity) {
    	return entity.getRaplaType().is(raplaType);
    }
    void insertAll() throws SQLException,RaplaException {
        insert(cache.getCollection( raplaType ));
    }

    protected String getXML(RaplaObject type) throws RaplaException {
		RaplaXMLWriter dynamicTypeWriter = getWriterFor( type.getRaplaType());
		StringWriter stringWriter = new StringWriter();
	    BufferedWriter bufferedWriter = new BufferedWriter(stringWriter);
	    dynamicTypeWriter.setWriter( bufferedWriter );
	    try {
	        dynamicTypeWriter.writeObject(type);
	        bufferedWriter.flush();
	    } catch (IOException ex) {
	        throw new RaplaException( ex);
	    }
	    return stringWriter.getBuffer().toString();

	}

	protected RaplaXMLReader processXML(RaplaType type, String xml) throws RaplaException {
	    RaplaXMLReader contentHandler = getReaderFor( type);
	    if ( xml== null ||  xml.trim().length() <= 10) {
	        throw new RaplaException("Can't load " + type);
	    }
	    try {
	        getReader().readWithNamespaces( xml, contentHandler);
	    } catch (IOException ex) {
	        throw new RaplaException( ex );
	    }
	    return contentHandler;
	}

}


class PeriodStorage extends RaplaTypeStorage {
    public PeriodStorage(RaplaContext context) throws RaplaException {
    	super(context, Period.TYPE,"PERIOD",new String[] {"ID","NAME","PERIOD_START","PERIOD_END"});
    }

    protected void write(PreparedStatement stmt,RefEntity entity) throws SQLException {
		Period s = (Period) entity;
		if ( getLogger().isDebugEnabled())
		    getLogger().debug("Inserting Period " + s.getName());
		stmt.setInt(1,getId(entity));
		stmt.setString(2,s.getName());
		stmt.setTimestamp(3,new java.sql.Timestamp(s.getStart().getTime()));
		stmt.setTimestamp(4,new java.sql.Timestamp(s.getEnd().getTime()));
		stmt.executeUpdate();
    }

    protected void load(ResultSet rset) throws SQLException {
		SimpleIdentifier id = new SimpleIdentifier(Period.TYPE, rset.getInt(1));
		String name = getString(rset,2);
		java.util.Date von  = new java.util.Date(rset.getTimestamp(3).getTime());
		java.util.Date bis  = new java.util.Date(rset.getTimestamp(4).getTime());
		PeriodImpl period = new PeriodImpl(von,bis);
		period.setName( name );
		period.setId( id );
		put( period );
		if ( getLogger().isDebugEnabled()) {
		    getLogger().debug("  " + name );
		    getLogger().debug("    start: " + von);
		    getLogger().debug("    end: " + bis);
		}
    }
}

class CategoryStorage extends RaplaTypeStorage {
	Map orderMap =  new HashMap();
    Map categoriesWithoutParent = new TreeMap(new Comparator()
        {
            public int compare( Object o1, Object o2 )
            {
                if ( o1.equals( o2))
                {
                    return 0;
                }
                int ordering1 = ((Integer) orderMap.get( o1 )).intValue();
                int ordering2 = ((Integer) orderMap.get( o2 )).intValue();
                if ( ordering1 < ordering2)
                {
                    return -1;
                }
                if ( ordering1 > ordering2)
                {
                    return 1;
                }
                RefEntity e1 = (RefEntity) o1;
                RefEntity e2 = (RefEntity) o2;
                if (e1.hashCode() > e2.hashCode())
                {
                    return -1;
                }
                else
                {
                    return 1;
                }
            }
        
        }    
    );

    public CategoryStorage(RaplaContext context) throws RaplaException {
    	super(context,Category.TYPE, "CATEGORY",new String[] {"ID","PARENT_ID","CATEGORY_KEY","LABEL","DEFINITION", "PARENT_ORDER"});
    }

    protected void write(PreparedStatement stmt,RefEntity entity) throws SQLException, RaplaException {
        Category root = getSuperCategory();
        if ( entity.equals( root ))
            return;
		Category category = (Category) entity;
		String name = category.getName( getLocale() );
		int id = getId(entity);
		int parentId = getId((RefEntity)category.getParent());
		if ( getLogger().isDebugEnabled())
		    getLogger().debug("Inserting Category " + name);
		stmt.setInt(1, id);
		if ( root.equals( category.getParent())) 
        {
		    stmt.setObject( 2,null );
		} 
        else 
        {
		    stmt.setInt(2, parentId);
		}
        int order = getOrder( category);
        String xml = getXML( category );
        stmt.setString(3, category.getKey());
		stmt.setString(4, name );
		stmt.setString(5, xml);
        stmt.setInt( 6, order);
		stmt.executeUpdate();
    }

    

    private int getOrder( Category category )
    {
        Category parent = category.getParent();
        if ( parent == null)
        {
            return 0;
        }
        Category[] childs = parent.getCategories();;
        for ( int i=0;i<childs.length;i++)
        {
            if ( childs[i].equals( category))
            {
                return i;
            }
        }
        getLogger().error("Category not found in parent");
        return 0;
    }

    public RaplaXMLReader getReaderFor( RaplaType type) throws RaplaException {
        RaplaXMLReader reader = super.getReaderFor( type );
        if ( type.equals( Category.TYPE ) ) {
            ((CategoryReader) reader).setReadOnlyThisCategory( true);
        }
        return reader;
    }

    protected void load(ResultSet rset) throws SQLException, RaplaException {
        int idInt = rset.getInt(1);
    	String key = getString( rset, 3 );
		String name = getString( rset, 4 );
        String xml = getString( rset, 5 );
    	Object id = new SimpleIdentifier(Category.TYPE, idInt);
    	int order = rset.getInt( 6 );
        CategoryImpl category;
    	if ( xml != null && xml.length() > 10 )
    	{
    	    category = ((CategoryReader)processXML( Category.TYPE, xml )).getCurrentCategory();
            //cache.remove( category );
            category.setId( id );
    	}
    	else
    	{
    		// for compatibility with version prior to 1.0rc1
    		category = new CategoryImpl();
			category.setId( id);
	    	category.setKey( key );
	    	category.getName().setName( getLocale().getLanguage(), name);
    	}
      
        put( category );

    	int parentIdInt = rset.getInt(2);
        orderMap.put( category, new Integer( order));
    	if ( !rset.wasNull() ) 
        {
            categoriesWithoutParent.put( category, new SimpleIdentifier(Category.TYPE, parentIdInt));
    	} 
        else 
        {
    	    categoriesWithoutParent.put( category, null );
    	}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -