|
| 1 | +package com.stubbornjava.common.seo; |
| 2 | + |
| 3 | +import java.util.List; |
| 4 | +import java.util.Map; |
| 5 | +import java.util.Map.Entry; |
| 6 | +import java.util.concurrent.TimeUnit; |
| 7 | +import java.util.function.Supplier; |
| 8 | + |
| 9 | +import org.jooq.lambda.Seq; |
| 10 | + |
| 11 | +import com.google.common.base.Suppliers; |
| 12 | +import com.google.common.collect.Maps; |
| 13 | + |
| 14 | +// {{start:inMemorySitemap}} |
| 15 | +public class InMemorySitemap { |
| 16 | + private final Supplier<Map<String, String>> indexSupplier; |
| 17 | + private InMemorySitemap(Supplier<Map<String, String>> indexSupplier) { |
| 18 | + this.indexSupplier = indexSupplier; |
| 19 | + } |
| 20 | + |
| 21 | + public String getIndex(String sitemapName) { |
| 22 | + return indexSupplier.get().get(sitemapName); |
| 23 | + } |
| 24 | + |
| 25 | + public List<String> getIndexNames() { |
| 26 | + return Seq.seq(indexSupplier.get().keySet()) |
| 27 | + .sorted() |
| 28 | + .toList(); |
| 29 | + } |
| 30 | + |
| 31 | + // Cache the sitemap for the lifetime of the JVM |
| 32 | + public static InMemorySitemap fromSupplier(Supplier<Map<String, List<String>>> supplier) { |
| 33 | + Supplier<Map<String, String>> sup = mapSupplier(supplier); |
| 34 | + Supplier<Map<String, String>> memoized = Suppliers.memoize(sup::get); |
| 35 | + return new InMemorySitemap(memoized); |
| 36 | + } |
| 37 | + |
| 38 | + // Cache the sitemap but refresh after the given duration. |
| 39 | + public static InMemorySitemap fromSupplierWithExpiration( |
| 40 | + Supplier<Map<String, List<String>>> supplier, |
| 41 | + long duration, |
| 42 | + TimeUnit unit) { |
| 43 | + Supplier<Map<String, String>> sup = mapSupplier(supplier); |
| 44 | + Supplier<Map<String, String>> memoized = Suppliers.memoizeWithExpiration(sup::get, duration, unit); |
| 45 | + return new InMemorySitemap(memoized); |
| 46 | + } |
| 47 | + |
| 48 | + private static Supplier<Map<String, String>> mapSupplier(Supplier<Map<String, List<String>>> supplier) { |
| 49 | + return () -> { |
| 50 | + Map<String, List<String>> originalMap = supplier.get(); |
| 51 | + Map<String, String> newIndex = Maps.newHashMap(); |
| 52 | + for (Entry<String, List<String>> entry : originalMap.entrySet()) { |
| 53 | + for (int i = 0; i < entry.getValue().size(); i++) { |
| 54 | + newIndex.put(entry.getKey() + "-" + i + ".xml", entry.getValue().get(i)); |
| 55 | + } |
| 56 | + } |
| 57 | + return newIndex; |
| 58 | + }; |
| 59 | + } |
| 60 | +} |
| 61 | +// {{end:inMemorySitemap}} |
| 62 | + |
0 commit comments