View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.client5.http.impl.cache;
28  
29  import java.util.ArrayList;
30  import java.util.Collection;
31  import java.util.HashMap;
32  import java.util.List;
33  import java.util.Map;
34  
35  import org.apache.hc.client5.http.cache.HttpCacheCASOperation;
36  import org.apache.hc.client5.http.cache.HttpCacheEntry;
37  import org.apache.hc.client5.http.cache.HttpCacheEntrySerializer;
38  import org.apache.hc.client5.http.cache.HttpCacheStorage;
39  import org.apache.hc.client5.http.cache.HttpCacheStorageEntry;
40  import org.apache.hc.client5.http.cache.HttpCacheUpdateException;
41  import org.apache.hc.client5.http.cache.ResourceIOException;
42  import org.apache.hc.core5.util.Args;
43  
44  /**
45   * Abstract cache backend for serialized objects capable of CAS (compare-and-swap) updates.
46   *
47   * @since 5.0
48   */
49  public abstract class AbstractSerializingCacheStorage<T, CAS> implements HttpCacheStorage {
50  
51      private final int maxUpdateRetries;
52      private final HttpCacheEntrySerializer<T> serializer;
53  
54      public AbstractSerializingCacheStorage(final int maxUpdateRetries, final HttpCacheEntrySerializer<T> serializer) {
55          this.maxUpdateRetries = Args.notNegative(maxUpdateRetries, "Max retries");
56          this.serializer = Args.notNull(serializer, "Cache entry serializer");
57      }
58  
59      protected abstract String digestToStorageKey(String key);
60  
61      protected abstract void store(String storageKey, T storageObject) throws ResourceIOException;
62  
63      protected abstract T restore(String storageKey) throws ResourceIOException;
64  
65      protected abstract CAS getForUpdateCAS(String storageKey) throws ResourceIOException;
66  
67      protected abstract T getStorageObject(CAS cas) throws ResourceIOException;
68  
69      protected abstract boolean updateCAS(String storageKey, CAS cas, T storageObject) throws ResourceIOException;
70  
71      protected abstract void delete(String storageKey) throws ResourceIOException;
72  
73      protected abstract Map<String, T> bulkRestore(Collection<String> storageKeys) throws ResourceIOException;
74  
75      @Override
76      public final void putEntry(final String key, final HttpCacheEntry entry) throws ResourceIOException {
77          final String storageKey = digestToStorageKey(key);
78          final T storageObject = serializer.serialize(new HttpCacheStorageEntry(key, entry));
79          store(storageKey, storageObject);
80      }
81  
82      @Override
83      public final HttpCacheEntry getEntry(final String key) throws ResourceIOException {
84          final String storageKey = digestToStorageKey(key);
85          final T storageObject = restore(storageKey);
86          if (storageObject == null) {
87              return null;
88          }
89          final HttpCacheStorageEntry entry = serializer.deserialize(storageObject);
90          if (key.equals(entry.getKey())) {
91              return entry.getContent();
92          } else {
93              return null;
94          }
95      }
96  
97      @Override
98      public final void removeEntry(final String key) throws ResourceIOException {
99          final String storageKey = digestToStorageKey(key);
100         delete(storageKey);
101     }
102 
103     @Override
104     public final void updateEntry(
105             final String key,
106             final HttpCacheCASOperation casOperation) throws HttpCacheUpdateException, ResourceIOException {
107         int numRetries = 0;
108         final String storageKey = digestToStorageKey(key);
109         for (;;) {
110             final CAS cas = getForUpdateCAS(storageKey);
111             HttpCacheStorageEntry storageEntry = cas != null ? serializer.deserialize(getStorageObject(cas)) : null;
112             if (storageEntry != null && !key.equals(storageEntry.getKey())) {
113                 storageEntry = null;
114             }
115             final HttpCacheEntry existingEntry = storageEntry != null ? storageEntry.getContent() : null;
116             final HttpCacheEntry updatedEntry = casOperation.execute(existingEntry);
117 
118             if (existingEntry == null) {
119                 putEntry(key, updatedEntry);
120                 return;
121 
122             }
123             final T storageObject = serializer.serialize(new HttpCacheStorageEntry(key, updatedEntry));
124             if (!updateCAS(storageKey, cas, storageObject)) {
125                 numRetries++;
126                 if (numRetries >= maxUpdateRetries) {
127                     throw new HttpCacheUpdateException("Cache update failed after " + numRetries + " retries");
128                 }
129             } else {
130                 return;
131             }
132         }
133     }
134 
135     @Override
136     public final Map<String, HttpCacheEntry> getEntries(final Collection<String> keys) throws ResourceIOException {
137         Args.notNull(keys, "Storage keys");
138         final List<String> storageKeys = new ArrayList<>(keys.size());
139         for (final String key: keys) {
140             storageKeys.add(digestToStorageKey(key));
141         }
142         final Map<String, T> storageObjectMap = bulkRestore(storageKeys);
143         final Map<String, HttpCacheEntry> resultMap = new HashMap<>();
144         for (final String key: keys) {
145             final String storageKey = digestToStorageKey(key);
146             final T storageObject = storageObjectMap.get(storageKey);
147             if (storageObject != null) {
148                 final HttpCacheStorageEntry entry = serializer.deserialize(storageObject);
149                 if (key.equals(entry.getKey())) {
150                     resultMap.put(key, entry.getContent());
151                 }
152             }
153         }
154         return resultMap;
155     }
156 
157 }