All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.cedarsoft.gdao.caching.CachingDaoManager Maven / Gradle / Ivy

The newest version!
package com.cedarsoft.gdao.caching;

import com.cedarsoft.gdao.GenericDao;
import com.cedarsoft.gdao.GenericDaoManager;
import com.cedarsoft.gdao.LockProvider;
import com.cedarsoft.utils.Cache;
import com.cedarsoft.utils.HashedCache;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Iterator;

/**
 *
 */
public class CachingDaoManager implements GenericDaoManager {
  @NotNull
  private final GenericDaoManager backingDaoManager;

  @SuppressWarnings( {"MismatchedQueryAndUpdateOfCollection"} )
  private final Cache, CachingDao> daoCache = new HashedCache, CachingDao>( new Cache.Factory, CachingDao>() {
    @NotNull
    public CachingDao create( @NotNull Class key ) {
      GenericDao backingDao = backingDaoManager.getDao( key );
      CachingDao dao = new CachingDao( backingDao );
      dao.initializeCache( backingDao.findAll() );
      return dao;
    }
  } );

  public CachingDaoManager( @NotNull GenericDaoManager backingDaoManager ) {
    this.backingDaoManager = backingDaoManager;
  }

  @NotNull
  public  GenericDao getDao( @NotNull Class type ) {
    return ( GenericDao ) daoCache.get( type );
  }

  @NotNull
  public  GenericDao getDao( @NotNull Class type, @Nullable LockProvider lockProvider ) {
    if ( lockProvider == null ) {
      return getDao( type );
    } else {
      throw new UnsupportedOperationException( "Lock provider not supported" );
    }
  }

  public void shutdown() {
    for ( Iterator> it = daoCache.values().iterator(); it.hasNext(); ) {
      CachingDao dao = it.next();
      dao.shutdown();
      it.remove();
    }
    backingDaoManager.shutdown();
  }
}