001 /**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one or more
004 * contributor license agreements. See the NOTICE file distributed with
005 * this work for additional information regarding copyright ownership.
006 * The ASF licenses this file to You under the Apache License, Version 2.0
007 * (the "License"); you may not use this file except in compliance with
008 * the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018 package org.apache.camel.processor.idempotent;
019
020 import org.apache.camel.util.LRUCache;
021
022 import java.util.Set;
023 import java.util.HashSet;
024 import java.util.Map;
025 import java.util.HashMap;
026 import java.util.LinkedHashMap;
027
028 /**
029 * A memory based implementation of {@link MessageIdRepository}.
030 * Care should be taken to use a suitable underlying {@link Map} to avoid this class being a memory leak
031 *
032 * @version $Revision: 1.1 $
033 */
034 public class MemoryMessageIdRepository implements MessageIdRepository {
035 private Map cache;
036
037 /**
038 * Creates a new MemoryMessageIdRepository with a memory based respository. <b>Warning</b> this
039 * method should only really be used for testing as it will involve keeping all message IDs in RAM.
040 */
041 public static MessageIdRepository memoryMessageIdRepository() {
042 return memoryMessageIdRepository(new HashMap());
043 }
044
045 /**
046 * Creates a new MemoryMessageIdRepository with a memory based respository. <b>Warning</b> this
047 * method should only really be used for testing as it will involve keeping all message IDs in RAM.
048 */
049 public static MessageIdRepository memoryMessageIdRepository(int cacheSize) {
050 return memoryMessageIdRepository(new LRUCache(cacheSize));
051 }
052
053 /**
054 * Creates a new MemoryMessageIdRepository using the given {@link Map} to use to store the
055 * processed Message ID objects. Warning be cafeful of the implementation of Map you use as
056 * if you are not careful it could be a memory leak.
057 */
058 public static MessageIdRepository memoryMessageIdRepository(Map cache) {
059 return new MemoryMessageIdRepository(cache);
060 }
061
062 public MemoryMessageIdRepository(Map set) {
063 this.cache = set;
064 }
065
066 public boolean contains(String messageId) {
067 synchronized (cache) {
068 if (cache.containsKey(messageId)) {
069 return true;
070 }
071 else {
072 cache.put(messageId, messageId);
073 return false;
074 }
075 }
076 }
077 }