/**
 * Copyright (C) 2009 - 2010 by OpenGamma Inc.
 * 
 * Please see distribution for license.
 */
package com.opengamma.engine.view.cache;

import java.io.File;

import org.fudgemsg.FudgeContext;

import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;

/**
 * An implementation of {@link ViewComputationCacheSource} which will use an injected
 * {@link IdentifierMap} and construct {@link BerkeleyDBValueSpecificationBinaryDataStore}
 * instances on demand to satisfy cache requests.
 */
public class BerkeleyDBViewComputationCacheSource extends DefaultViewComputationCacheSource {

  public static Environment constructDatabaseEnvironment(File dbDir, boolean transactional) {
    if (!dbDir.exists()) {
      dbDir.mkdirs();
    }
    EnvironmentConfig envConfig = new EnvironmentConfig();
    envConfig.setAllowCreate(true);
    envConfig.setTransactional(transactional);
    Environment dbEnvironment = new Environment(dbDir, envConfig);
    return dbEnvironment;
  }

  public BerkeleyDBViewComputationCacheSource(IdentifierMap identifierMap, Environment dbEnvironment, FudgeContext fudgeContext) {
    super(identifierMap, fudgeContext, new BerkeleyDBBinaryDataStoreFactory(dbEnvironment));
  }

}

@@ -189,16 +189,73 @@
 Context;
+%0Aimport org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;
 %0A%0Aimport
@@ -327,16 +327,68 @@
 tConfig;
+%0Aimport com.sleepycat.je.EnvironmentLockedException;
 %0A%0A/**%0A *
@@ -714,21 +714,133 @@
 e %7B%0A%0A  p
-ublic
+rivate static final Logger s_logger = LoggerFactory.getLogger(BerkeleyDBViewComputationCacheSource.class);%0A%0A  private
  static 
@@ -879,17 +879,27 @@
 ironment
-(
+Impl(final 
 File dbD
@@ -901,16 +901,22 @@
 e dbDir,
+ final
  boolean
@@ -1138,40 +1138,384 @@
     
-Environment dbEnvironment = new 
+return new Environment(dbDir, envConfig);%0A  %7D%0A%0A  private static void deleteFile(final File file) %7B%0A    if (file.isDirectory()) %7B%0A      for (File subfile : file.listFiles()) %7B%0A        deleteFile(subfile);%0A      %7D%0A    %7D%0A    file.delete();%0A  %7D%0A%0A  public static Environment constructDatabaseEnvironment(File dbDir, boolean transactional) %7B%0A    try %7B%0A      return constructDatabase
 Envi
@@ -1517,32 +1517,36 @@
 eEnvironment
+Impl
 (dbDir, 
 envConfig);%0A
@@ -1537,45 +1537,258 @@
 ir, 
-envConfig);%0A    return dbEnvironment;
+transactional);%0A    %7D catch (EnvironmentLockedException e) %7B%0A      s_logger.warn(%22Error locking DB environment, deleting %7B%7D and trying again%22, dbDir);%0A      deleteFile(dbDir);%0A      return constructDatabaseEnvironmentImpl(dbDir, transactional);%0A    %7D
 %0A  %7D

Delete the BDB data area if there's a problem preventing the engine from starting