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 */ 017package org.apache.camel.spring.processor.idempotent; 018 019import org.apache.camel.api.management.ManagedAttribute; 020import org.apache.camel.api.management.ManagedOperation; 021import org.apache.camel.api.management.ManagedResource; 022import org.apache.camel.spi.IdempotentRepository; 023import org.apache.camel.support.ServiceSupport; 024import org.springframework.cache.Cache; 025import org.springframework.cache.CacheManager; 026 027@ManagedResource(description = "SpringCache based message id repository") 028public class SpringCacheIdempotentRepository extends ServiceSupport implements IdempotentRepository<Object> { 029 private final CacheManager manager; 030 private final String cacheName; 031 private Cache cache; 032 033 public SpringCacheIdempotentRepository(CacheManager manager, String cacheName) { 034 this.manager = manager; 035 this.cacheName = cacheName; 036 this.cache = null; 037 } 038 039 @Override 040 @ManagedOperation(description = "Adds the key to the store") 041 public boolean add(Object key) { 042 return cache.putIfAbsent(key, true) == null; 043 } 044 045 @Override 046 @ManagedOperation(description = "Does the store contain the given key") 047 public boolean contains(Object key) { 048 return cache.get(key) != null; 049 } 050 051 @Override 052 @ManagedOperation(description = "Remove the key from the store") 053 public boolean remove(Object key) { 054 cache.evict(key); 055 return true; 056 } 057 058 @Override 059 @ManagedOperation(description = "Clear the store") 060 public void clear() { 061 cache.clear(); 062 } 063 064 @ManagedAttribute(description = "The processor name") 065 public String getCacheName() { 066 return cacheName; 067 } 068 069 @Override 070 public boolean confirm(Object key) { 071 return true; 072 } 073 074 @Override 075 protected void doStart() throws Exception { 076 if (cache == null) { 077 cache = manager.getCache(cacheName); 078 } 079 } 080 081 @Override 082 protected void doStop() throws Exception { 083 cache = null; 084 } 085}