/** 
 * 
 * Copyright 2005 Hiram Chirino
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 * 
 **/
package org.activemq.broker.impl;

import java.io.File;
import java.io.IOException;

import org.activemq.io.util.MemoryBoundedObjectManager;
import org.activemq.store.PersistenceAdapter;
import org.activemq.store.PersistenceAdapterFactory;
import org.activemq.store.cache.MemoryBoundedCachePersistenceAdapter;
import org.activemq.store.jdbc.JDBCPersistenceAdapter;
import org.activemq.store.journal.JournalPersistenceAdapter;
import org.apache.derby.jdbc.EmbeddedDataSource;

/**
 * Factory class that can create PersistenceAdapter objects.
 *
 * @version $Revision: 1.1.1.1 $
 */
public class DefaultPersistenceAdapterFactory implements PersistenceAdapterFactory {
    
    /**
     * Creates a persistence Adapter that can use a given directory to store it's data.
     * @throws IOException 
     */
    public PersistenceAdapter createPersistenceAdapter(File dataDirectory, MemoryBoundedObjectManager memManager) throws IOException {

        // Setup the Derby datasource.
        System.setProperty("derby.system.home", dataDirectory.getCanonicalPath());
        System.setProperty("derby.storage.fileSyncTransactionLog", "true");
        
        EmbeddedDataSource ds = new EmbeddedDataSource();
        ds.setDatabaseName("derbydb");
        ds.setCreateDatabase("create");        
        JDBCPersistenceAdapter jdbcAdapter = new JDBCPersistenceAdapter();
        jdbcAdapter.setDataSource(ds);
        
        // Setup the Journal
        File journalDir = new File(dataDirectory, "journal");
        JournalPersistenceAdapter journalAdapter = new JournalPersistenceAdapter(journalDir, jdbcAdapter);
        journalAdapter.setJournalType(JournalPersistenceAdapter.DEFAULT_JOURNAL_TYPE);
        
        // Add a cache layer if the memory manager is available.
        if( memManager==null )
            return journalAdapter;
        
        MemoryBoundedCachePersistenceAdapter cacheAdapter = new MemoryBoundedCachePersistenceAdapter(journalAdapter);
        cacheAdapter.setMemoryManager(memManager);        
        return cacheAdapter;
    }
}
