2.17.2: 2011-06-17

net.sf.basedb.core
Class DbControl

java.lang.Object
  extended by net.sf.basedb.core.DbControl

public final class DbControl
extends Object

A DbControl object is the main object used for communicating with the database. It contains methods for saving and deleting items, handling transactions, etc. DbControl objects are created by the SessionControl.newDbControl() method.

Version:
2.0
Author:
Nicklas, Samuel
Last modified
$Date: 2010-12-21 11:31:46 +0100 (Tue, 21 Dec 2010) $

Nested Class Summary
private static class DbControl.SaveIf
           
 
Field Summary
private  List<Batcher> batchers
          A list of batchers that will be closed when DbControl is closed and will be flushed when commit is called.
private  Throwable calledFrom
          To keep track of the code that created this DbControl.
private  Map<BasicItem,Transactional.Action> commitQueue
          A list of items that need special handling when commit is called.
private  SessionWrapper hSession
          The Hibernate session.
private  StatelessSessionWrapper hStatelessSession
          A Hibernate stateless session.
private  org.hibernate.Transaction hTransaction
          The Hibernate transaction.
private  boolean isClosed
          Is the connection closed or not?
private  boolean isConnected
          If Hibernate is connected to the database or not.
private  boolean isRolledBack
          If the current transaction has been rolled back or not.
private  Map<BasicData,BasicItem> itemCache
          A cache of already loaded items.
private static Logger log
          Log core events.
private  LogControl logControl
          Handles logging of changes to items.
private  Map<BasicItem,List<DbControl.SaveIf>> saveIfQueue
          Lists items that are saved only if the parent item is also saved.
private  SessionControl sc
           
 
Constructor Summary
DbControl(SessionControl sc)
          Create a new object.
 
Method Summary
(package private)  void addBatcher(Batcher batcher)
          Add a Batcher to the batcher queue.
private  void cleanUp()
          Clear and close all objects.
 void close()
          Close the connection to the database.
 void commit()
          Commit all changes made to items and close the connection to the database.
 void deleteItem(BasicItem item)
          Schedule an existing item to be deleted from the database.
 void detachItem(BasicItem item)
          Detach an item from this DbControl.
 void disconnect()
          Temporarily disconnect from the database.
protected  void finalize()
          Clean up if a bad client application forgot to close the connection.
(package private)  long getDiskUsage(GroupData group, QuotaTypeData quotaType, Location location)
          Get the disk usage for the specified group at the specified location and quota type.
(package private)  long getDiskUsage(UserData user, QuotaTypeData quotaType, Location location)
          Get the disk usage for the specified user at the specified location and quota type.
(package private)  org.hibernate.Session getHibernateSession()
          Get the underlying Hibernate session.
(package private)
<I extends BasicItem>
I
getItem(Class<I> itemClass, BasicData data, Object... extraParameters)
          Get an item object for a known data object, using the cache if possible.
(package private)  LogControl getLogControl()
          Get the log controller for this db control.
 SessionControl getSessionControl()
          Get the SessionControl object that owns this DbControl object.
(package private)  org.hibernate.StatelessSession getStatelessSession()
          Get a stateless Hibernate session using the same database connection as the regular session.
 void initCollection(BasicItem item, String collectionName)
          Initialise a collection on an item.
(package private)  boolean isAttached(BasicItem item)
          Check if an item is attached to this DbControl.
 boolean isClosed()
          Check if the connection to the database has been closed.
 boolean isConnected()
          Checks if there is an active connection to the database or not.
 boolean isRolledBack()
          If the transaction was rolled back, either as a call to close() or because of an error during commit().
(package private)
<I extends BasicItem>
I
loadItem(Class<I> itemClass, int id)
          Load an item from the database when you now the id.
(package private)
<I extends BasicItem,D extends BasicData>
I
loadItemByDataClass(Class<I> itemClass, Class<D> dataClass, int id)
          Load an item from the database when you know the id.
(package private)
<I extends BasicItem>
I
newItem(Class<I> itemClass, Object... extraParameters)
          Create a new item.
 void reattachItem(BasicItem item)
          Deprecated. Use reattachItem(BasicItem, boolean) instead
<T extends BasicItem>
T
reattachItem(T item, boolean updated)
          Reattach a detached item from this DbControl.
 void reconnect()
          Reconnects to the database after a disconnect().
 void refreshItem(BasicItem item)
          Reload the item from the database.
(package private)  void removeBatcher(Batcher batcher)
          Remove a Batcher from the batcher queue.
private  void rollback()
          Rollback the transaction.
 void saveItem(BasicItem item)
          Schedule a new item to be saved in the database.
 void saveItemIf(BasicItem itemIf, BasicItem item, boolean before)
          Schedule a new item to be saved in the database if another item is also saved.
private  void updateDiskUsage(BasicItem item)
          Update the disk usage information for a DiskConsumable item.
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

log

private static final Logger log
Log core events.


sc

private final SessionControl sc

calledFrom

private final Throwable calledFrom
To keep track of the code that created this DbControl.


logControl

private LogControl logControl
Handles logging of changes to items.


hSession

private SessionWrapper hSession
The Hibernate session.


hStatelessSession

private StatelessSessionWrapper hStatelessSession
A Hibernate stateless session.


hTransaction

private org.hibernate.Transaction hTransaction
The Hibernate transaction.


itemCache

private Map<BasicData,BasicItem> itemCache
A cache of already loaded items. Maps from data object --> item object


commitQueue

private Map<BasicItem,Transactional.Action> commitQueue
A list of items that need special handling when commit is called.


saveIfQueue

private Map<BasicItem,List<DbControl.SaveIf>> saveIfQueue
Lists items that are saved only if the parent item is also saved.

See Also:
saveItemIf(BasicItem, BasicItem, boolean)

batchers

private List<Batcher> batchers
A list of batchers that will be closed when DbControl is closed and will be flushed when commit is called.


isClosed

private boolean isClosed
Is the connection closed or not?


isConnected

private boolean isConnected
If Hibernate is connected to the database or not.


isRolledBack

private boolean isRolledBack
If the current transaction has been rolled back or not.

Constructor Detail

DbControl

DbControl(SessionControl sc)
    throws BaseException
Create a new object.

Throws:
BaseException
Method Detail

isClosed

public boolean isClosed()
Check if the connection to the database has been closed. To get a new connection, you must create a new DbControl object.

Returns:
TRUE if the connection is closed, FALSE otherwise
See Also:
SessionControl.newDbControl()

getSessionControl

public SessionControl getSessionControl()
Get the SessionControl object that owns this DbControl object.

Returns:
a SessionControl object

getLogControl

LogControl getLogControl()
Get the log controller for this db control. May be null if logging has been disabled.

Since:
2.13

getHibernateSession

org.hibernate.Session getHibernateSession()
Get the underlying Hibernate session.


getStatelessSession

org.hibernate.StatelessSession getStatelessSession()
Get a stateless Hibernate session using the same database connection as the regular session. If no stateless session exists a new one is created.


disconnect

public void disconnect()
                throws ConnectionClosedException,
                       BaseException
Temporarily disconnect from the database. Uncommitted changes of regular items are not lost, but you must reconnect() before calling commit(). If you have used batch items, for example ReporterBatcher, you should call commit() or you will lose everything that has already been BasicBatcher.flush():ed to the database.

Throws:
ConnectionClosedException - If connection to database has been closed.
BaseException - If there is another error

reconnect

public void reconnect()
               throws ConnectionClosedException,
                      BaseException
Reconnects to the database after a disconnect().

Throws:
ConnectionClosedException - If connection to database has been closed.
BaseException - If there is another error.

isConnected

public boolean isConnected()
Checks if there is an active connection to the database or not.


close

public void close()
Close the connection to the database. Uncommitted changes will be rolled back. If the connection is already closed this method does nothing. Any errors in this method are written to the log file. After calling this method the DbControl cannot be used anymore.


isRolledBack

public boolean isRolledBack()
If the transaction was rolled back, either as a call to close() or because of an error during commit(). To check if a transaction was successfully committed use: dc.isClosed() && !dc.isRolledBack().

Returns:
TRUE if the transaction was rolled back, FALSE if it was committed or is still open

rollback

private void rollback()
Rollback the transaction.


cleanUp

private void cleanUp()
Clear and close all objects.


commit

public void commit()
            throws BaseException
Commit all changes made to items and close the connection to the database. If there is an error, a rollback is issued and the connection is closed.

Throws:
BaseException - If there is an error

updateDiskUsage

private void updateDiskUsage(BasicItem item)
                      throws QuotaException,
                             BaseException
Update the disk usage information for a DiskConsumable item. It is expected that the item parameter impements the DiskConsumable interface and that it's data object implements the DiskConsumableData interface.

Throws:
QuotaException - If the quota is exceeded
BaseException - If there is another error

getDiskUsage

long getDiskUsage(UserData user,
                  QuotaTypeData quotaType,
                  Location location)
            throws BaseException
Get the disk usage for the specified user at the specified location and quota type.

Throws:
BaseException

getDiskUsage

long getDiskUsage(GroupData group,
                  QuotaTypeData quotaType,
                  Location location)
            throws BaseException
Get the disk usage for the specified group at the specified location and quota type.

Throws:
BaseException

newItem

<I extends BasicItem> I newItem(Class<I> itemClass,
                                Object... extraParameters)
Create a new item.

Parameters:
itemClass - The class of the item
Returns:
An object of the itemClass class
Throws:
BaseException - If there is an error

loadItem

<I extends BasicItem> I loadItem(Class<I> itemClass,
                                 int id)
                       throws PermissionDeniedException,
                              BaseException
Load an item from the database when you now the id. If the item has already been loaded the item in the cache will be used.

Parameters:
itemClass - The Class of the item object
id - The id of the object
Returns:
An object of the itemClass class
Throws:
PermissionDeniedException - If the logged in user doesn't have read permission
BaseException - If there is another error

loadItemByDataClass

<I extends BasicItem,D extends BasicData> I loadItemByDataClass(Class<I> itemClass,
                                                                Class<D> dataClass,
                                                                int id)
                                  throws PermissionDeniedException,
                                         BaseException
Load an item from the database when you know the id. If the item has already been loaded the item in the cache will be used.

Parameters:
itemClass - The item class for the object
dataClass - The actual data class for the object which must be compatible with the item class
id - The id of the object
Returns:
An object of the itemClass class
Throws:
PermissionDeniedException
BaseException
Since:
2.17

getItem

<I extends BasicItem> I getItem(Class<I> itemClass,
                                BasicData data,
                                Object... extraParameters)
                      throws PermissionDeniedException,
                             ItemNotFoundException,
                             BaseException
Get an item object for a known data object, using the cache if possible. If the item already exists in the cache that object is returned, otherwise a new item object is created assuming that a constructor that takes a single data object as parameter exists.

Parameters:
itemClass - The Class of the item object
data - The data object, or null
Returns:
An object of the itemClass class, or null if null was passed
Throws:
PermissionDeniedException - If the logged in user doesn't have read permission
ItemNotFoundException - If the data object is a Hibernate proxy which points to a non-existing row in the database
BaseException - If there is another error

saveItem

public void saveItem(BasicItem item)
              throws PermissionDeniedException,
                     ItemAlreadyExistsException,
                     BaseException
Schedule a new item to be saved in the database. The item is saved the next time the commit() method is called.

Parameters:
item - The item to be saved
Throws:
PermissionDeniedException - If the logged in user doesn't have create permission
ItemAlreadyExistsException - If the item already exists in the database
BaseException - If there is another error

saveItemIf

public void saveItemIf(BasicItem itemIf,
                       BasicItem item,
                       boolean before)
Schedule a new item to be saved in the database if another item is also saved. If the itemIf item is saved then item is also saved, otherwise it is not. The method is useful for utility methods that creates a lot of child items to a parent item and we wan't to wait putting them in the real save queue until the parent item is saved. If the parent item is already in the database or saveItem(itemIf) has been called this method is the same as saveItem(item)

Parameters:
itemIf - The parent item that must be saved
item - The item to save when the parent item is saved
before - TRUE if the item should be saved before the itemIf, FALSE to save itemIf first
See Also:
saveItem(BasicItem)

deleteItem

public void deleteItem(BasicItem item)
                throws PermissionDeniedException,
                       ItemNotFoundException,
                       BaseException
Schedule an existing item to be deleted from the database. The item is deleted the next time the commit() method is called. If you are deleting multiple items it is better to use Trashcan.delete(SessionControl, java.util.Collection, boolean, ProgressReporter) since it will automatically select the best order to delete the items.

Parameters:
item - The item to be deleted
Throws:
PermissionDeniedException - If the logged in user doesn't have delete permission
ItemNotFoundException - If the item doesn't exist in the database
BaseException - If there is another error

detachItem

public void detachItem(BasicItem item)
                throws BaseException
Detach an item from this DbControl. The detached item will no longer be managed and changes will not be saved to the database. For some items, certain operations are forbidden for detached items. For example you are not allowed to upload files to File items.

Parameters:
item - The item to be detached
Throws:
BaseException - If there is an error
See Also:
reattachItem(BasicItem)

reattachItem

public void reattachItem(BasicItem item)
                  throws PermissionDeniedException,
                         ItemNotFoundException,
                         BaseException
Deprecated. Use reattachItem(BasicItem, boolean) instead

Reattach a detached item assuming that it has not been updated while it was detached.

Throws:
PermissionDeniedException
ItemNotFoundException
BaseException

reattachItem

public <T extends BasicItem> T reattachItem(T item,
                                            boolean updated)
                                 throws PermissionDeniedException,
                                        ItemNotFoundException,
                                        BaseException
Reattach a detached item from this DbControl. If the reattached already exists in the database it will be managed and changes will be saved to the database.

Parameters:
item - The item to be reattached
updated - If TRUE, the item has been updated while it was detached and changes will be saved to the database. If FALSE, the item will only be saved to the database if it is modified after the reattachement
Returns:
The reattached item
Throws:
PermissionDeniedException - If the logged in user doesn't have read/write permission
BaseException - If there is another error
ItemNotFoundException
Since:
2.13
See Also:
detachItem(BasicItem)

refreshItem

public void refreshItem(BasicItem item)
Reload the item from the database. If the item isn't attached to this DbControl it is automatically reattached first.

Parameters:
item - The item to reload
Since:
2.4

isAttached

boolean isAttached(BasicItem item)
Check if an item is attached to this DbControl. An item is attached if it is found in either the item cache (existing items only) or commit queue (new or existing items).


initCollection

public void initCollection(BasicItem item,
                           String collectionName)
                    throws BaseException
Initialise a collection on an item. This method is useful if you detach an item but needs to use a collection while it is detached. Since collections are not loaded until they are needed, you will get an exception if you try to access an unitialised collection of a detached item. One example is if you have detach a Quota object and calls the Quota.getQuotaValue(QuotaType, Location) method.

Parameters:
item - The item
collectionName - The name of the collection
Throws:
BaseException - If there is an error
See Also:
detachItem(BasicItem), reattachItem(BasicItem)

addBatcher

void addBatcher(Batcher batcher)
Add a Batcher to the batcher queue.

Parameters:
batcher - The Batcher to add

removeBatcher

void removeBatcher(Batcher batcher)
Remove a Batcher from the batcher queue.

Parameters:
batcher - The Batcher to remove

finalize

protected void finalize()
                 throws Throwable
Clean up if a bad client application forgot to close the connection.

Overrides:
finalize in class Object
Throws:
Throwable

2.17.2: 2011-06-17