001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.servicemix.store.memory;
018    
019    import java.io.IOException;
020    import java.util.HashMap;
021    import java.util.Map;
022    
023    import org.apache.servicemix.id.IdGenerator;
024    import org.apache.servicemix.store.Store;
025    import org.apache.servicemix.store.StoreFactory;
026    
027    /**
028     * {@link StoreFactory} for creating memory-based {@link Store} implementations
029     * 
030     * If a timeout has been specified, a {@link TimeoutMemoryStore} will be created,
031     * otherwise the factory will build a plain {@link MemoryStore}
032     */
033    public class MemoryStoreFactory implements StoreFactory {
034    
035        private IdGenerator idGenerator = new IdGenerator();
036        private Map<String, MemoryStore> stores = new HashMap<String, MemoryStore>();
037        private long timeout = -1;
038        
039        /* (non-Javadoc)
040         * @see org.apache.servicemix.store.ExchangeStoreFactory#get(java.lang.String)
041         */
042        public synchronized Store open(String name) throws IOException {
043            MemoryStore store = stores.get(name);
044            if (store == null) {
045                if (timeout <= 0) {
046                    store = new MemoryStore(idGenerator);
047                } else {
048                    store = new TimeoutMemoryStore(idGenerator, timeout);
049                }
050                stores.put(name, store);
051            }
052            return store;
053        }
054    
055        /* (non-Javadoc)
056         * @see org.apache.servicemix.store.ExchangeStoreFactory#release(org.apache.servicemix.store.ExchangeStore)
057         */
058        public synchronized void close(Store store) throws IOException {
059            stores.remove(store);
060        }
061        
062        public void setTimeout(long timeout) {
063            this.timeout = timeout;
064        }
065    }