1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.basepom.mojo.dvc;
16
17 import static com.google.common.base.Preconditions.checkNotNull;
18 import static com.google.common.base.Preconditions.checkState;
19
20 import org.basepom.mojo.dvc.model.ResolverDefinition;
21 import org.basepom.mojo.dvc.strategy.Strategy;
22 import org.basepom.mojo.dvc.strategy.StrategyProvider;
23
24 import java.util.Arrays;
25 import java.util.Map;
26 import java.util.concurrent.ExecutionException;
27
28 import com.google.common.cache.Cache;
29 import com.google.common.cache.CacheBuilder;
30 import com.google.common.collect.ImmutableMap;
31
32 public final class StrategyCache {
33
34
35
36
37 private final Cache<QualifiedName, Strategy> resolverCache = CacheBuilder.newBuilder().concurrencyLevel(10).build();
38
39 private final ImmutableMap<QualifiedNameMatcher, Strategy> resolverPatterns;
40 private final Strategy defaultStrategy;
41
42 StrategyCache(final StrategyProvider strategyProvider, final ResolverDefinition[] resolvers, final String defaultStrategyName) {
43 checkNotNull(strategyProvider, "strategyProvider is null");
44 checkNotNull(resolvers, "resolvers is null");
45 checkNotNull(defaultStrategyName, "defaultStrategyName is null");
46
47 this.defaultStrategy = strategyProvider.forName(defaultStrategyName);
48 checkState(defaultStrategy != null, "Could not locate default version strategy '%s'", defaultStrategyName);
49
50 final ImmutableMap.Builder<QualifiedNameMatcher, Strategy> builder = ImmutableMap.builder();
51 Arrays.stream(resolvers).forEach(r -> {
52 final Strategy strategy = strategyProvider.forName(r.getStrategy());
53 checkState(strategy != null, "Could not locate version strategy %s! Check for typos!", r.getStrategy());
54 r.getIncludes().forEach(include -> builder.put(include, strategy));
55 });
56 this.resolverPatterns = builder.build();
57 }
58
59 public Strategy forQualifiedName(final QualifiedName name) {
60 checkNotNull(name, "name is null");
61 try {
62 return resolverCache.get(name, () -> {
63 for (final Map.Entry<QualifiedNameMatcher, Strategy> entry : resolverPatterns.entrySet()) {
64 if (entry.getKey().matches(name)) {
65 return entry.getValue();
66 }
67 }
68 return defaultStrategy;
69 });
70 } catch (ExecutionException e) {
71
72 return defaultStrategy;
73 }
74 }
75 }