001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with 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, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.commons.jcs3.jcache.extras.loader; 020 021import javax.cache.configuration.Factory; 022import javax.cache.integration.CacheLoader; 023import javax.cache.integration.CacheLoaderException; 024 025import org.apache.commons.jcs3.jcache.extras.closeable.Closeables; 026 027import java.io.Closeable; 028import java.io.IOException; 029import java.util.ArrayList; 030import java.util.Collection; 031import java.util.HashMap; 032import java.util.Map; 033 034public class CompositeCacheLoader<K, V> implements CacheLoader<K, V>, Closeable, Factory<CacheLoader<K, V>> 035{ 036 private final CacheLoader<K, V>[] delegates; 037 038 public CompositeCacheLoader(final CacheLoader<K, V>... delegates) 039 { 040 this.delegates = delegates; 041 } 042 043 @Override 044 public V load(final K key) throws CacheLoaderException 045 { 046 for (final CacheLoader<K, V> delegate : delegates) 047 { 048 final V v = delegate.load(key); 049 if (v != null) 050 { 051 return v; 052 } 053 } 054 return null; 055 } 056 057 @Override 058 public Map<K, V> loadAll(final Iterable<? extends K> keys) throws CacheLoaderException 059 { 060 final Collection<K> list = new ArrayList<>(); 061 for (final K k : keys) 062 { 063 list.add(k); 064 } 065 066 final Map<K, V> result = new HashMap<>(); 067 for (final CacheLoader<K, V> delegate : delegates) 068 { 069 final Map<K, V> v = delegate.loadAll(list); 070 if (v != null) 071 { 072 result.putAll(v); 073 list.removeAll(v.keySet()); 074 if (list.isEmpty()) 075 { 076 return v; 077 } 078 } 079 } 080 081 return result; 082 } 083 084 @Override 085 public void close() throws IOException 086 { 087 Closeables.close(delegates); 088 } 089 090 @Override 091 public CacheLoader<K, V> create() 092 { 093 return this; 094 } 095}