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.cache.example;
28  
29  import java.util.concurrent.Future;
30  
31  import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
32  import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
33  import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
34  import org.apache.hc.client5.http.async.methods.SimpleRequestProducer;
35  import org.apache.hc.client5.http.async.methods.SimpleResponseConsumer;
36  import org.apache.hc.client5.http.cache.CacheContextBuilder;
37  import org.apache.hc.client5.http.cache.HttpCacheContext;
38  import org.apache.hc.client5.http.cache.HttpCacheEntry;
39  import org.apache.hc.client5.http.cache.RequestCacheControl;
40  import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
41  import org.apache.hc.client5.http.impl.cache.CacheConfig;
42  import org.apache.hc.client5.http.impl.cache.CachingHttpAsyncClients;
43  import org.apache.hc.client5.http.impl.cache.HeapResourceFactory;
44  import org.apache.hc.core5.concurrent.FutureCallback;
45  import org.apache.hc.core5.http.HttpHost;
46  import org.apache.hc.core5.http.message.StatusLine;
47  import org.apache.hc.core5.io.CloseMode;
48  
49  /**
50   * This is an example demonstrating how to control execution of cache
51   * operation and determine its outcome using the async HTTP cache API.
52   */
53  public class AsyncClientCacheControl {
54  
55      public static void main(final String[] args) throws Exception {
56  
57          final HttpHost target = new HttpHost("https", "www.apache.org");
58  
59          try (final CloseableHttpAsyncClient httpclient = CachingHttpAsyncClients.custom()
60                  .setCacheConfig(CacheConfig.custom()
61                          .setMaxObjectSize(200000)
62                          .setHeuristicCachingEnabled(true)
63                          .build())
64                  .setResourceFactory(HeapResourceFactory.INSTANCE)
65                  .build()) {
66  
67              httpclient.start();
68  
69              final SimpleHttpRequest httpget1 = SimpleRequestBuilder.get()
70                      .setHttpHost(target)
71                      .setPath("/")
72                      .build();
73  
74              // Use default cache control
75              final HttpCacheContext context = CacheContextBuilder.create()
76                      .setCacheControl(RequestCacheControl.DEFAULT)
77                      .build();
78  
79              System.out.println("Executing request " + httpget1.getMethod() + " " + httpget1.getUri());
80              final Future<SimpleHttpResponse> future = httpclient.execute(
81                      SimpleRequestProducer.create(httpget1),
82                      SimpleResponseConsumer.create(),
83                      context,
84                      new FutureCallback<SimpleHttpResponse>() {
85  
86                          @Override
87                          public void completed(final SimpleHttpResponse response) {
88                              System.out.println(httpget1 + "->" + new StatusLine(response));
89                              System.out.println("Cache status: " + context.getCacheResponseStatus());
90                              System.out.println("Request cache control: " + context.getRequestCacheControlOrDefault());
91                              System.out.println("Response cache control: " + context.getResponseCacheControlOrDefault());
92                              final HttpCacheEntry cacheEntry = context.getCacheEntry();
93                              if (cacheEntry != null) {
94                                  System.out.println("Cache entry resource: " + cacheEntry.getResource());
95                                  System.out.println("Date: " + cacheEntry.getInstant());
96                                  System.out.println("Expires: " + cacheEntry.getExpires());
97                                  System.out.println("Last modified: " + cacheEntry.getLastModified());
98                              }
99                          }
100 
101                         @Override
102                         public void failed(final Exception ex) {
103                             System.out.println(httpget1 + "->" + ex);
104                         }
105 
106                         @Override
107                         public void cancelled() {
108                             System.out.println(httpget1 + " cancelled");
109                         }
110 
111                     });
112             future.get();
113 
114             final SimpleHttpRequest httpget2 = SimpleRequestBuilder.get()
115                     .setHttpHost(target)
116                     .setPath("/")
117                     .build();
118 
119             // Ensure a custom freshness for the cache entry
120             context.setRequestCacheControl(RequestCacheControl.builder()
121                     .setMinFresh(100)
122                     .build());
123 
124             System.out.println("Executing request " + httpget2.getMethod() + " " + httpget2.getUri());
125             final Future<SimpleHttpResponse> future2 = httpclient.execute(
126                     SimpleRequestProducer.create(httpget2),
127                     SimpleResponseConsumer.create(),
128                     context,
129                     new FutureCallback<SimpleHttpResponse>() {
130 
131                         @Override
132                         public void completed(final SimpleHttpResponse response) {
133                             System.out.println(httpget2 + "->" + new StatusLine(response));
134                             System.out.println("Cache status: " + context.getCacheResponseStatus());
135                             System.out.println("Request cache control: " + context.getRequestCacheControlOrDefault());
136                             System.out.println("Response cache control: " + context.getResponseCacheControlOrDefault());
137                             final HttpCacheEntry cacheEntry = context.getCacheEntry();
138                             if (cacheEntry != null) {
139                                 System.out.println("Cache entry resource: " + cacheEntry.getResource());
140                                 System.out.println("Date: " + cacheEntry.getInstant());
141                                 System.out.println("Expires: " + cacheEntry.getExpires());
142                                 System.out.println("Last modified: " + cacheEntry.getLastModified());
143                             }
144                         }
145 
146                         @Override
147                         public void failed(final Exception ex) {
148                             System.out.println(httpget2 + "->" + ex);
149                         }
150 
151                         @Override
152                         public void cancelled() {
153                             System.out.println(httpget2 + " cancelled");
154                         }
155 
156                     });
157             future2.get();
158 
159             Thread.sleep(2000);
160 
161             final SimpleHttpRequest httpget3 = SimpleRequestBuilder.get()
162                     .setHttpHost(target)
163                     .setPath("/")
164                     .build();
165 
166             // Try to force cache entry re-validation
167             context.setRequestCacheControl(RequestCacheControl.builder()
168                     .setMaxAge(0)
169                     .build());
170 
171             System.out.println("Executing request " + httpget3.getMethod() + " " + httpget3.getUri());
172             final Future<SimpleHttpResponse> future3 = httpclient.execute(
173                     SimpleRequestProducer.create(httpget3),
174                     SimpleResponseConsumer.create(),
175                     context,
176                     new FutureCallback<SimpleHttpResponse>() {
177 
178                         @Override
179                         public void completed(final SimpleHttpResponse response) {
180                             System.out.println(httpget3 + "->" + new StatusLine(response));
181                             System.out.println("Cache status: " + context.getCacheResponseStatus());
182                             System.out.println("Request cache control: " + context.getRequestCacheControlOrDefault());
183                             System.out.println("Response cache control: " + context.getResponseCacheControlOrDefault());
184                             final HttpCacheEntry cacheEntry = context.getCacheEntry();
185                             if (cacheEntry != null) {
186                                 System.out.println("Cache entry resource: " + cacheEntry.getResource());
187                                 System.out.println("Date: " + cacheEntry.getInstant());
188                                 System.out.println("Expires: " + cacheEntry.getExpires());
189                                 System.out.println("Last modified: " + cacheEntry.getLastModified());
190                             }
191                         }
192 
193                         @Override
194                         public void failed(final Exception ex) {
195                             System.out.println(httpget3 + "->" + ex);
196                         }
197 
198                         @Override
199                         public void cancelled() {
200                             System.out.println(httpget3 + " cancelled");
201                         }
202 
203                     });
204             future3.get();
205 
206             httpclient.close(CloseMode.GRACEFUL);
207         }
208     }
209 }