/** * Syntactic sugar for writing {@code stage.handle(fn).toCompletableFuture().unsafeJoin()}. * * @param stage the stage to handle the results * @param fn called to handle the result * @param <T> the type returned by the stage * @param <R> the type to be returned * @return the result of calling <tt>fn</tt> on the stage outcome. */ public static <T, R> R fold(CompletionStage<T> stage, BiFunction<T, Throwable, R> fn) { return unsafeJoin(stage.handle(fn)); } }
@Test public void getOperation() { final Optional<String> result = fold(offlineCache.get("key"), t -> t, err -> Optional.of("failed")); assertThat(result, is(equalTo(Optional.of("failed")))); }
/** * Gets all the properties for a given page id */ @SuppressWarnings("unchecked") public ImmutableMap<String, ImmutableList<ImmutableMap<String, PageProperty>>> get(final long pageId, Supplier<ImmutableMap<String, ImmutableList<ImmutableMap<String, PageProperty>>>> loader) { return join(cacheRef.get().get(Long.toString(pageId), loader)); }
/** * Syntactic sugar for handling the result (either success or failure) from a {@link CompletionStage}. * * @param stage the stage to handle the results * @param success called if the stage returned a successful result * @param failure called if the stage failed * @param <T> the type returned by the stage * @param <R> the type to be returned * @return if the stage is successful, then the result of calling <tt>success</tt>, otherwise the result of * calling <tt>failure</tt> */ public static <T, R> R fold(CompletionStage<T> stage, Function<T, R> success, Function<Throwable, R> failure) { return unsafeJoin(stage.handle((val, err) -> (err != null) ? failure.apply(err) : success.apply(val))); }
@Test public void getBulkOperation() { final Map<String, Optional<String>> result = fold(offlineCache.getBulk("key1", "key2"), t -> t, err -> Collections.emptyMap()); assertThat(result, is(equalTo(Collections.emptyMap()))); }
public void clearCache() { join(cacheRef.get().removeAll()); }
@SuppressWarnings("unchecked") @Test public void simple_getBulk() throws ExecutionException, InterruptedException { final CompletionStage<Map<String, Optional<String>>> get1 = cache.getBulk("claira", "jasmin", "josie", "josie"); assertThat(get1, successful()); assertThat(unsafeJoin(get1).keySet(), containsInAnyOrder("claira", "jasmin", "josie")); assertThat(unsafeJoin(get1).values(), containsInAnyOrder(Optional.empty(), Optional.empty(), Optional.empty())); final CompletionStage<Boolean> put1 = cache.put("claira", "youtube", PutPolicy.PUT_ALWAYS); assertThat(put1, successfulWith(is(true))); final CompletionStage<Map<String, Optional<String>>> get2 = cache.getBulk("jasmin", "claira", "josie", "claira"); assertThat(get2, successful()); assertThat(unsafeJoin(get2).keySet(), containsInAnyOrder("claira", "jasmin", "josie")); assertThat(unsafeJoin(get2).values(), containsInAnyOrder(Optional.of("youtube"), Optional.empty(), Optional.empty())); final Map<MetricLabel, ? extends LongMetric> cacheMetrics = requestMetrics().allExternalCacheLongMetrics().get(CACHE_NAME); assertThat(cacheMetrics, hasMetric(MetricLabel.TIMED_GET_CALL, is(2L), greaterThan(0L))); assertThat(cacheMetrics, hasMetric(MetricLabel.TIMED_PUT_CALL, is(1L), greaterThan(0L))); assertThat(cacheMetrics, hasMetric(MetricLabel.TIMED_REMOVE_ALL_CALL, is(1L), greaterThan(0L))); assertThat(cacheMetrics, hasMetric(MetricLabel.NUMBER_OF_HITS, is(1L), is(1L))); assertThat(cacheMetrics, hasMetric(MetricLabel.NUMBER_OF_MISSES, is(2L), is(5L))); assertThat(cacheMetrics, hasSize(is(5))); }
@Test public void getWithSupplierOperation() { final String result = fold(offlineCache.get("key", () -> "value"), t -> t, err -> "failed"); assertThat(result, is(equalTo("failed"))); }
private Void removeFromCache(String statusId) { return join(cacheRef.get().remove(statusId)); }
@Test public void simple_getBulkFactory() throws ExecutionException, InterruptedException { final CompletionStage<Map<String, String>> get1 = cache.getBulk( strings -> strings.stream().collect(Collectors.toMap(k -> k, k -> k + "-1")), "claira", "josie", "josie"); assertThat(get1, successful()); assertThat(unsafeJoin(get1).keySet(), containsInAnyOrder("claira", "josie")); assertThat(unsafeJoin(get1).values(), containsInAnyOrder("claira-1", "josie-1")); final CompletionStage<Map<String, String>> get2 = cache.getBulk( strings -> strings.stream().collect(Collectors.toMap(k -> k, k -> k + "-2")), "claira", "josie", "jasmin"); assertThat(get2, successful()); assertThat(unsafeJoin(get2).keySet(), containsInAnyOrder("claira", "josie", "jasmin")); assertThat(unsafeJoin(get2).values(), containsInAnyOrder("claira-1", "josie-1", "jasmin-2")); final Map<MetricLabel, ? extends LongMetric> cacheMetrics = requestMetrics().allExternalCacheLongMetrics().get(CACHE_NAME); assertThat(cacheMetrics, hasMetric(MetricLabel.TIMED_GET_CALL, is(2L), greaterThan(0L))); assertThat(cacheMetrics, hasMetric(MetricLabel.TIMED_FACTORY_CALL, is(2L), greaterThan(0L))); assertThat(cacheMetrics, hasMetric(MetricLabel.TIMED_REMOVE_ALL_CALL, is(1L), greaterThan(0L))); assertThat(cacheMetrics, hasMetric(MetricLabel.NUMBER_OF_FACTORY_KEYS, is(2L), is(3L))); assertThat(cacheMetrics, hasMetric(MetricLabel.NUMBER_OF_HITS, is(1L), is(2L))); assertThat(cacheMetrics, hasMetric(MetricLabel.NUMBER_OF_MISSES, is(2L), is(3L))); assertThat(cacheMetrics, hasSize(is(6))); }
@Test public void getIdentifiedOperation() { final IdentifiedValue<String> result = fold(offlineCache.getIdentified("key", () -> "value"), t -> t, err -> null); assertThat(result, is(equalTo(null))); }
public String getEmbedData(String url, Pattern pattern, String cacheName) { final StableReadExternalCache<String> cache = getCache(cacheName); final Optional<String> result = join(cache.get(url)); if (result.isPresent()) return result.get(); HttpResponse response = getResponse(url); String line; try { if (response == null) return null; BufferedReader br = new BufferedReader(new InputStreamReader(response.getResponse())); Matcher m; while ((line = br.readLine()) != null) { m = pattern.matcher(line); if (m.find()) { br.close(); String embedId = m.group(1); join(getCache(cacheName).put(url, embedId, PUT_ALWAYS)); return embedId; } } br.close(); } catch (IOException e) { log.error("An error occured parsing the response from: " + url); } finally { if (response != null) response.finish(); } return null; }
@SuppressWarnings("ConstantConditions") @Test public void check_null_detection_with_cas() { final CompletionStage<IdentifiedValue<String>> geti = cache.getIdentified("temp", () -> "value"); assertThat(geti, successful()); assertThat(cache.replaceIf("temp", unsafeJoin(geti).identifier(), null), not(successful())); final Map<MetricLabel, ? extends LongMetric> cacheMetrics = requestMetrics().allExternalCacheLongMetrics().get(CACHE_NAME); assertThat(cacheMetrics, hasMetric(MetricLabel.TIMED_IDENTIFIED_GET_CALL, is(1L), greaterThan(0L))); assertThat(cacheMetrics, hasMetric(MetricLabel.TIMED_IDENTIFIED_REPLACE_CALL, is(1L), greaterThan(0L))); assertThat(cacheMetrics, hasMetric(MetricLabel.TIMED_SUPPLIER_CALL, is(1L), greaterThan(0L))); assertThat(cacheMetrics, hasMetric(MetricLabel.TIMED_REMOVE_ALL_CALL, is(1L), greaterThan(0L))); assertThat(cacheMetrics, hasMetric(MetricLabel.NUMBER_OF_FAILED_IDENTIFIED_REPLACE, is(1L), is(1L))); assertThat(cacheMetrics, hasMetric(MetricLabel.NUMBER_OF_MISSES, is(1L), is(1L))); assertThat(cacheMetrics, hasSize(is(6))); }
@Test public void putOperation() { final boolean result = fold(offlineCache.put("key", "value", PutPolicy.PUT_ALWAYS), t -> t, err -> false); assertThat(result, is(equalTo(false))); }
private void invalidateCacheOnContentEvent(final Object event) { if (event instanceof Contented) join(cacheRef.get().remove(((Contented)event).getContent().getIdAsString())); }
final Map<String, Optional<V>> existingValues = unsafeJoin(getBulk(internalKeys));
@Test public void getBulkOperation() { final Map<String, Optional<String>> result = fold(offlineCache.getBulk("key1", "key2"), t -> t, err -> Collections.emptyMap()); assertThat(result, is(equalTo(Collections.emptyMap()))); }
@Nonnull private TweetRetrievalResult getTweetRetrievalResultFromCache(String statusId, Supplier<TweetRetrievalResult> loader) { try { final TweetRetrievalResult result = join(cacheRef.get().get(statusId, loader::get)); if (result.isExpiredFailureResult()) // The cache contains a failure result that has now expired, so remove it removeFromCache(statusId); return result; } catch (ClassCastException | VCacheException pluginUpgraded) { LOG.debug("Removed cached Tweet retrieval result by a previously installed version of the Widget Connector Plugin.", pluginUpgraded); removeFromCache(statusId); return loader.get(); } }
@Test public void simple_getBulkIdentified() throws ExecutionException, InterruptedException { final CompletionStage<Boolean> put1 = cache.put("josie", "football", PutPolicy.PUT_ALWAYS); assertThat(put1, successfulWith(is(true))); final CompletionStage<Optional<IdentifiedValue<String>>> get1 = cache.getIdentified("josie"); assertThat(get1, successful()); final IdentifiedValue<String> iv1 = unsafeJoin(get1).get(); assertThat(iv1.identifier(), notNullValue()); assertThat(iv1.value(), is("football")); final CompletionStage<Map<String, Optional<IdentifiedValue<String>>>> get2 = cache.getBulkIdentified("claira", "josie", "jasmin"); assertThat(get2, successful()); final Map<String, Optional<IdentifiedValue<String>>> ivMap1 = unsafeJoin(get2); assertThat(ivMap1.keySet(), containsInAnyOrder("jasmin", "claira", "josie")); assertThat(ivMap1.get("claira"), is(Optional.empty())); assertThat(ivMap1.get("jasmin"), is(Optional.empty())); final IdentifiedValue<String> iv2 = ivMap1.get("josie").get(); assertThat(iv2.identifier(), notNullValue()); assertThat(iv2.identifier(), equalTo(iv1.identifier())); assertThat(iv2.value(), is("football")); final Map<MetricLabel, ? extends LongMetric> cacheMetrics = requestMetrics().allExternalCacheLongMetrics().get(CACHE_NAME); assertThat(cacheMetrics, hasMetric(MetricLabel.TIMED_IDENTIFIED_GET_CALL, is(2L), greaterThan(0L))); assertThat(cacheMetrics, hasMetric(MetricLabel.TIMED_PUT_CALL, is(1L), greaterThan(0L))); assertThat(cacheMetrics, hasMetric(MetricLabel.TIMED_REMOVE_ALL_CALL, is(1L), greaterThan(0L))); assertThat(cacheMetrics, hasMetric(MetricLabel.NUMBER_OF_HITS, is(2L), is(2L))); assertThat(cacheMetrics, hasMetric(MetricLabel.NUMBER_OF_MISSES, is(1L), is(2L))); assertThat(cacheMetrics, hasSize(is(5))); }
@Test public void getOperation() { final Optional<String> result = fold(offlineCache.get("key"), t -> t, err -> Optional.of("failed")); assertThat(result, is(equalTo(Optional.of("failed")))); }