-
Notifications
You must be signed in to change notification settings - Fork 389
/
MarkupCache.java
740 lines (660 loc) · 19.4 KB
/
MarkupCache.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.markup;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.wicket.Application;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.listener.IChangeListener;
import org.apache.wicket.util.watch.IModifiable;
import org.apache.wicket.util.watch.IModificationWatcher;
import org.apache.wicket.util.watch.ModificationWatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is Wicket's default IMarkupCache implementation. It will load the markup and cache it for
* fast retrieval.
* <p>
* If the application is in development mode and a markup file changes, it'll automatically be
* removed from the cache and reloaded when needed.
* <p>
* MarkupCache is registered with {@link MarkupFactory} which in turn is registered with
* {@link org.apache.wicket.settings.MarkupSettings} and thus can be replaced with a sub-classed version.
*
* @see org.apache.wicket.settings.MarkupSettings
* @see MarkupFactory
*
* @author Jonathan Locke
* @author Juergen Donnerstag
*/
public class MarkupCache implements IMarkupCache
{
/** Log for reporting. */
private static final Logger log = LoggerFactory.getLogger(MarkupCache.class);
/** The actual cache: location => Markup */
private final ICache<String, Markup> markupCache;
/**
* Add extra indirection to the cache: key => location
* <p>
* Since ConcurrentHashMap does not allow to store null values, we are using Markup.NO_MARKUP
* instead.
*/
private final ICache<String, String> markupKeyCache;
/** The markup cache key provider used by MarkupCache */
private IMarkupCacheKeyProvider markupCacheKeyProvider;
/**
* Note that you can not use Application.get() since removeMarkup() will be called from a
* ModificationWatcher thread which has no associated Application.
*/
private final Application application;
/**
* A convenient helper to get the markup cache registered with the application.
*
* @see {@link Application#getMarkupSettings()}
* @see {@link MarkupFactory#getMarkupCache()}
*
* @return The markup cache registered with the {@link Application}
*/
public static IMarkupCache get()
{
return Application.get().getMarkupSettings().getMarkupFactory().getMarkupCache();
}
/**
* Constructor.
*/
protected MarkupCache()
{
application = Application.get();
markupCache = newCacheImplementation();
if (markupCache == null)
{
throw new WicketRuntimeException("The map used to cache markup must not be null");
}
markupKeyCache = newCacheImplementation();
}
@Override
public void clear()
{
markupCache.clear();
markupKeyCache.clear();
}
@Override
public void shutdown()
{
markupCache.shutdown();
markupKeyCache.shutdown();
}
/**
* Note that this method will be called from a "cleanup" thread which might not have a thread
* local application.
*/
@Override
public final IMarkupFragment removeMarkup(final String cacheKey)
{
Args.notNull(cacheKey, "cacheKey");
if (log.isDebugEnabled())
{
log.debug("Removing from cache: " + cacheKey);
}
// Remove the markup from the cache
String locationString = markupKeyCache.get(cacheKey);
IMarkupFragment markup = (locationString != null ? markupCache.get(locationString) : null);
if (markup == null)
{
return null;
}
// Found an entry: actual markup or Markup.NO_MARKUP. Null values are not possible
// because of ConcurrentHashMap.
markupCache.remove(locationString);
if (log.isDebugEnabled())
{
log.debug("Removed from cache: " + locationString);
}
// If a base markup file has been removed from the cache then
// the derived markup should be removed as well.
removeMarkupWhereBaseMarkupIsNoLongerInTheCache();
// And now remove all watcher entries associated with markup
// resources no longer in the cache.
// Note that you can not use Application.get() since removeMarkup() will be called from a
// ModificationWatcher thread which has no associated Application.
IModificationWatcher watcher = application.getResourceSettings().getResourceWatcher(false);
if (watcher != null)
{
Iterator<IModifiable> iter = watcher.getEntries().iterator();
while (iter.hasNext())
{
IModifiable modifiable = iter.next();
if (modifiable instanceof MarkupResourceStream)
{
if (!isMarkupCached((MarkupResourceStream)modifiable))
{
iter.remove();
if (log.isDebugEnabled())
{
log.debug("Removed from watcher: " + modifiable);
}
}
}
}
}
return markup;
}
private void removeMarkupWhereBaseMarkupIsNoLongerInTheCache()
{
// Repeat until all dependent resources have been removed (count == 0)
int count = 1;
while (count > 0)
{
// Reset prior to next round
count = 0;
// Iterate though all entries of the cache
Iterator<Markup> iter = markupCache.getValues().iterator();
while (iter.hasNext())
{
Markup markup = iter.next();
if ((markup != null) && (markup != Markup.NO_MARKUP))
{
// Check if the markup associated with key has a base markup. And if yes, test
// if that is cached. If the base markup has been removed, than remove the
// derived markup as well.
MarkupResourceStream resourceStream = markup.getMarkupResourceStream();
if (resourceStream != null)
{
resourceStream = resourceStream.getBaseMarkupResourceStream();
}
// Is the base markup available in the cache?
if ((resourceStream != null) && !isMarkupCached(resourceStream))
{
iter.remove();
count++;
if (log.isDebugEnabled())
{
log.debug("Removed derived markup from cache: " +
markup.getMarkupResourceStream());
}
}
}
}
}
}
/**
* @param resourceStream
* @return True if the markup is cached
*/
private boolean isMarkupCached(final MarkupResourceStream resourceStream)
{
if (resourceStream != null)
{
String key = resourceStream.getCacheKey();
if (key != null)
{
String locationString = markupKeyCache.get(key);
if ((locationString != null) && (markupCache.get(locationString) != null))
{
return true;
}
}
}
return false;
}
@Override
public final int size()
{
return markupCache.size();
}
/**
* Get a unmodifiable map which contains the cached data. The map key is of type String and the
* value is of type Markup.
* <p>
* May be used to debug or iterate the cache content.
*
* @return cache implementation
*/
public final ICache<String, Markup> getMarkupCache()
{
return markupCache;
}
@Override
public final Markup getMarkup(final MarkupContainer container, final Class<?> clazz,
final boolean enforceReload)
{
Class<?> containerClass = MarkupFactory.get().getContainerClass(container, clazz);
// Get the cache key to be associated with the markup resource stream.
// If the cacheKey returned == null, than caching is disabled for the resource stream.
final String cacheKey = getMarkupCacheKeyProvider(container).getCacheKey(container,
containerClass);
// Is the markup already in the cache?
Markup markup = null;
if ((enforceReload == false) && (cacheKey != null))
{
markup = getMarkupFromCache(cacheKey, container);
}
// If markup not found in cache or cache disabled, than ...
if (markup == null)
{
if (log.isDebugEnabled())
{
log.debug("Load markup: cacheKey=" + cacheKey);
}
// Get the markup resource stream for the container
final MarkupResourceStream resourceStream = MarkupFactory.get()
.getMarkupResourceStream(container, containerClass);
// Found markup?
if (resourceStream != null)
{
resourceStream.setCacheKey(cacheKey);
// load the markup and watch for changes
markup = loadMarkupAndWatchForChanges(container, resourceStream, enforceReload);
}
else
{
markup = onMarkupNotFound(cacheKey, container, Markup.NO_MARKUP);
}
}
// NO_MARKUP should only be used inside the Cache.
if (markup == Markup.NO_MARKUP)
{
markup = null;
}
return markup;
}
/**
* Will be called if the markup was not in the cache yet and could not be found either.
* <p>
* Subclasses may change the default implementation. E.g. they might choose not to update the
* cache to enforce reloading of any markup not found. This might be useful in very dynamic
* environments. Additionally a non-caching IResourceStreamLocator should be used.
*
* @param cacheKey
* @param container
* @param markup
* Markup.NO_MARKUP
* @return Same as parameter "markup"
* @see org.apache.wicket.settings.ResourceSettings#setResourceStreamLocator(org.apache.wicket.core.util.resource.locator.IResourceStreamLocator)
*/
protected Markup onMarkupNotFound(final String cacheKey, final MarkupContainer container,
final Markup markup)
{
if (log.isDebugEnabled())
{
log.debug("Markup not found: " + cacheKey);
}
// If cacheKey == null then caching is disabled for the component
if (cacheKey != null)
{
// flag markup as non-existent
markupKeyCache.put(cacheKey, cacheKey);
putIntoCache(cacheKey, container, markup);
}
return markup;
}
/**
* Put the markup into the cache if cacheKey is not null and the cache does not yet contain the
* cacheKey. Return the markup stored in the cache if cacheKey is present already.
*
* More sophisticated implementations may call a container method to e.g. cache it per container
* instance.
*
* @param locationString
* If {@code null} then ignore the cache
* @param container
* The container this markup is for.
* @param markup
* @return markup The markup provided, except if the cacheKey already existed in the cache, then
* the markup from the cache is provided.
*/
protected Markup putIntoCache(final String locationString, final MarkupContainer container,
Markup markup)
{
if (locationString != null)
{
if (markupCache.containsKey(locationString) == false)
{
// The default cache implementation is a ConcurrentHashMap. Thus neither the key nor
// the value can be null.
if (markup == null)
{
markup = Markup.NO_MARKUP;
}
markupCache.put(locationString, markup);
}
else
{
// We don't lock the cache while loading a markup. Thus it may
// happen that the very same markup gets loaded twice (the first
// markup being loaded, but not yet in the cache, and another
// request requesting the very same markup). Since markup
// loading in avg takes less than 100ms, it is not really an
// issue. For consistency reasons however, we should always use
// the markup loaded first which is why it gets returned.
markup = markupCache.get(locationString);
}
}
return markup;
}
/**
* Wicket's default implementation just uses the cacheKey to retrieve the markup from the cache.
* More sophisticated implementations may call a container method to e.g. ignore the cached
* markup under certain situations.
*
* @param cacheKey
* If null, than the cache will be ignored
* @param container
* @return null, if not found or to enforce reloading the markup
*/
protected Markup getMarkupFromCache(final String cacheKey, final MarkupContainer container)
{
if (cacheKey != null)
{
String locationString = markupKeyCache.get(cacheKey);
if (locationString != null)
{
return markupCache.get(locationString);
}
}
return null;
}
/**
* Loads markup from a resource stream.
*
* @param container
* The original requesting markup container
* @param markupResourceStream
* The markup resource stream to load
* @param enforceReload
* The cache will be ignored and all, including inherited markup files, will be
* reloaded. Whatever is in the cache, it will be ignored
* @return The markup. Markup.NO_MARKUP, if not found.
*/
private Markup loadMarkup(final MarkupContainer container,
final MarkupResourceStream markupResourceStream, final boolean enforceReload)
{
String cacheKey = markupResourceStream.getCacheKey();
String locationString = markupResourceStream.locationAsString();
if (locationString == null)
{
// set the cache key as location string, because location string
// couldn't be resolved.
locationString = cacheKey;
}
Markup markup = MarkupFactory.get().loadMarkup(container, markupResourceStream,
enforceReload);
if (markup != null)
{
if (cacheKey != null)
{
String temp = markup.locationAsString();
if (temp != null)
{
locationString = temp;
}
// add the markup to the cache.
markupKeyCache.put(cacheKey, locationString);
return putIntoCache(locationString, container, markup);
}
return markup;
}
// In case the markup could not be loaded (without exception) then ..
if (cacheKey != null)
{
removeMarkup(cacheKey);
}
return Markup.NO_MARKUP;
}
/**
* Load markup from an IResourceStream and add an {@link IChangeListener}to the
* {@link ModificationWatcher} so that if the resource changes, we can remove it from the cache
* automatically and subsequently reload when needed.
*
* @param container
* The original requesting markup container
* @param markupResourceStream
* The markup stream to load and begin to watch
* @param enforceReload
* The cache will be ignored and all, including inherited markup files, will be
* reloaded. Whatever is in the cache, it will be ignored
* @return The markup in the stream
*/
private Markup loadMarkupAndWatchForChanges(final MarkupContainer container,
final MarkupResourceStream markupResourceStream, final boolean enforceReload)
{
// @TODO the following code sequence looks very much like in loadMarkup. Can it be
// optimized?
final String cacheKey = markupResourceStream.getCacheKey();
if (cacheKey != null)
{
if (enforceReload == false)
{
// get the location String
String locationString = markupResourceStream.locationAsString();
if (locationString == null)
{
// set the cache key as location string, because location string
// couldn't be resolved.
locationString = cacheKey;
}
Markup markup = markupCache.get(locationString);
if (markup != null)
{
markupKeyCache.put(cacheKey, locationString);
return markup;
}
}
// Watch file in the future
final IModificationWatcher watcher = application.getResourceSettings()
.getResourceWatcher(true);
if (watcher != null)
{
watcher.add(markupResourceStream, new IChangeListener()
{
@Override
public void onChange()
{
if (log.isDebugEnabled())
{
log.debug("Remove markup from watcher: " + markupResourceStream);
}
// Remove the markup from the cache. It will be reloaded
// next time when the markup is requested.
watcher.remove(markupResourceStream);
removeMarkup(cacheKey);
}
});
}
}
if (log.isDebugEnabled())
{
log.debug("Loading markup from " + markupResourceStream);
}
return loadMarkup(container, markupResourceStream, enforceReload);
}
/**
* Get the markup cache key provider to be used
*
* @param container
* The MarkupContainer requesting the markup resource stream
* @return IMarkupResourceStreamProvider
*/
public IMarkupCacheKeyProvider getMarkupCacheKeyProvider(final MarkupContainer container)
{
if (container instanceof IMarkupCacheKeyProvider)
{
return (IMarkupCacheKeyProvider)container;
}
if (markupCacheKeyProvider == null)
{
markupCacheKeyProvider = new DefaultMarkupCacheKeyProvider();
}
return markupCacheKeyProvider;
}
/**
* Allows you to change the map implementation which will hold the cache data. By default it is
* a ConcurrentHashMap() in order to allow multiple thread to access the data in a secure way.
*
* @param <K>
* @param <V>
* @return new instance of cache implementation
*/
protected <K, V> ICache<K, V> newCacheImplementation()
{
return new DefaultCacheImplementation<K, V>();
}
/**
* MarkupCache allows you to implement you own cache implementation. ICache is the interface the
* implementation must comply with.
*
* @param <K>
* The key type
* @param <V>
* The value type
*/
public interface ICache<K, V>
{
/**
* Clear the cache
*/
void clear();
/**
* Remove an entry from the cache.
*
* @param key
* @return true, if found and removed
*/
boolean remove(K key);
/**
* Get the cache element associated with the key
*
* @param key
* @return cached object for key <code>key</code> or null if no matches
*/
V get(K key);
/**
* Get all the keys referencing cache entries
*
* @return collection of cached keys
*/
Collection<K> getKeys();
/**
* Get all the values referencing cache entries
*
* @return collection of cached keys
*/
Collection<V> getValues();
/**
* Check if key is in the cache
*
* @param key
* @return true if cache contains key <code>key</code>
*/
boolean containsKey(K key);
/**
* Get the number of cache entries
*
* @return number of cache entries
*/
int size();
/**
* Put an entry into the cache
*
* @param key
* The reference key to find the element. Must not be null.
* @param value
* The element to be cached. Must not be null.
*/
void put(K key, V value);
/**
* Cleanup and shutdown
*/
void shutdown();
}
/**
* @param <K>
* @param <V>
*/
public static class DefaultCacheImplementation<K, V> implements ICache<K, V>
{
// Neither key nor value are allowed to be null with ConcurrentHashMap
private final ConcurrentHashMap<K, V> cache = new ConcurrentHashMap<K, V>();
/**
* Construct.
*/
public DefaultCacheImplementation()
{
}
@Override
public void clear()
{
cache.clear();
}
@Override
public boolean containsKey(final Object key)
{
if (key == null)
{
return false;
}
return cache.containsKey(key);
}
@Override
public V get(final Object key)
{
if (key == null)
{
return null;
}
return cache.get(key);
}
@Override
public Collection<K> getKeys()
{
return cache.keySet();
}
@Override
public Collection<V> getValues()
{
return cache.values();
}
@Override
public void put(K key, V value)
{
// Note that neither key nor value are allowed to be null with ConcurrentHashMap
cache.put(key, value);
}
@Override
public boolean remove(K key)
{
if (key == null)
{
return false;
}
return cache.remove(key) == null;
}
@Override
public int size()
{
return cache.size();
}
@Override
public void shutdown()
{
clear();
}
}
}