001/*- 002 * #%L 003 * HAPI FHIR - Core Library 004 * %% 005 * Copyright (C) 2014 - 2025 Smile CDR, Inc. 006 * %% 007 * Licensed under the Apache License, Version 2.0 (the "License"); 008 * you may not use this file except in compliance with the License. 009 * You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 * #L% 019 */ 020package ca.uhn.fhir.interceptor.executor; 021 022import ca.uhn.fhir.interceptor.api.IBaseInterceptorBroadcaster.IInterceptorFilterHook; 023 024import java.util.function.Supplier; 025 026/** 027 * Wraps a Supplier with advice from a filter hook. 028 */ 029public class SupplierFilterHookWrapper<T> implements Supplier<T> { 030 private final IInterceptorFilterHook myAdvice; 031 private final Supplier<T> myTarget; 032 private final Supplier<String> myMessageSupplier; 033 034 public SupplierFilterHookWrapper( 035 Supplier<T> theTarget, IInterceptorFilterHook theAdvice, Supplier<String> theCauseDescriptionSupplier) { 036 myAdvice = theAdvice; 037 myTarget = theTarget; 038 myMessageSupplier = theCauseDescriptionSupplier; 039 } 040 041 @Override 042 public T get() { 043 SupplierRunnable<T> trackingSupplierWrapper = new SupplierRunnable<>(myTarget); 044 045 myAdvice.wrapCall(trackingSupplierWrapper); 046 047 if (!trackingSupplierWrapper.wasExecuted()) { 048 throw new IllegalStateException( 049 "Supplier was not executed in filter produced by " + myMessageSupplier.get()); 050 } 051 052 return trackingSupplierWrapper.getResult(); 053 } 054 055 /** 056 * Adapt a Supplier to Runnable. 057 * We use a Runnable for a simpler api for callers. 058 * @param <T> 059 */ 060 static class SupplierRunnable<T> implements Runnable { 061 private final Supplier<T> myTarget; 062 private boolean myExecutedFlag = false; 063 private T myResult = null; 064 065 SupplierRunnable(Supplier<T> theTarget) { 066 myTarget = theTarget; 067 } 068 069 public void run() { 070 myExecutedFlag = true; 071 myResult = myTarget.get(); 072 } 073 074 public boolean wasExecuted() { 075 return myExecutedFlag; 076 } 077 078 public T getResult() { 079 return myResult; 080 } 081 } 082}