001/*-
002 * #%L
003 * HAPI FHIR Storage api
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.jpa.binary.interceptor;
021
022import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
023import ca.uhn.fhir.context.BaseRuntimeElementDefinition;
024import ca.uhn.fhir.context.FhirContext;
025import ca.uhn.fhir.i18n.Msg;
026import ca.uhn.fhir.interceptor.api.Hook;
027import ca.uhn.fhir.interceptor.api.HookParams;
028import ca.uhn.fhir.interceptor.api.IInterceptorBroadcaster;
029import ca.uhn.fhir.interceptor.api.Interceptor;
030import ca.uhn.fhir.interceptor.api.Pointcut;
031import ca.uhn.fhir.jpa.binary.api.IBinaryStorageSvc;
032import ca.uhn.fhir.jpa.binary.api.IBinaryTarget;
033import ca.uhn.fhir.jpa.binary.api.StoredDetails;
034import ca.uhn.fhir.jpa.binary.provider.BinaryAccessProvider;
035import ca.uhn.fhir.jpa.binary.svc.BaseBinaryStorageSvcImpl;
036import ca.uhn.fhir.jpa.model.util.JpaConstants;
037import ca.uhn.fhir.rest.api.server.IPreResourceShowDetails;
038import ca.uhn.fhir.rest.api.server.RequestDetails;
039import ca.uhn.fhir.rest.api.server.storage.TransactionDetails;
040import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
041import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
042import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
043import ca.uhn.fhir.rest.server.util.CompositeInterceptorBroadcaster;
044import ca.uhn.fhir.util.HapiExtensions;
045import ca.uhn.fhir.util.IModelVisitor2;
046import jakarta.annotation.Nonnull;
047import org.apache.commons.io.FileUtils;
048import org.hl7.fhir.instance.model.api.IBase;
049import org.hl7.fhir.instance.model.api.IBaseExtension;
050import org.hl7.fhir.instance.model.api.IBaseHasExtensions;
051import org.hl7.fhir.instance.model.api.IBaseResource;
052import org.hl7.fhir.instance.model.api.IIdType;
053import org.hl7.fhir.instance.model.api.IPrimitiveType;
054import org.hl7.fhir.r4.model.IdType;
055import org.slf4j.Logger;
056import org.slf4j.LoggerFactory;
057import org.springframework.beans.factory.annotation.Autowired;
058
059import java.io.ByteArrayInputStream;
060import java.io.IOException;
061import java.io.InputStream;
062import java.util.ArrayList;
063import java.util.Collection;
064import java.util.HashMap;
065import java.util.List;
066import java.util.Map;
067import java.util.Objects;
068import java.util.Optional;
069import java.util.Set;
070import java.util.concurrent.atomic.AtomicInteger;
071import java.util.function.Predicate;
072import java.util.stream.Collectors;
073
074import static ca.uhn.fhir.util.HapiExtensions.EXT_EXTERNALIZED_BINARY_HASH_SHA_256;
075import static ca.uhn.fhir.util.HapiExtensions.EXT_EXTERNALIZED_BINARY_ID;
076import static org.apache.commons.lang3.StringUtils.isNotBlank;
077
078@Interceptor
079public class BinaryStorageInterceptor<T extends IPrimitiveType<byte[]>> {
080
081        private static final Logger ourLog = LoggerFactory.getLogger(BinaryStorageInterceptor.class);
082        /**
083         * UserData key that can be set in {@link RequestDetails#getUserData()} to override
084         * the {@link #isAllowAutoInflateBinaries()} setting for a single request.
085         * <p>
086         * Possible values:
087         * <ul>
088         *   <li>{@code Boolean.TRUE}  – force binary inflation even if globally disabled</li>
089         *   <li>{@code Boolean.FALSE} – skip binary inflation even if globally enabled</li>
090         *   <li>Absent                – use the global {@code isAllowAutoInflateBinaries()} setting</li>
091         * </ul>
092         */
093        public static final String AUTO_INFLATE_BINARY_CONTENT_KEY =
094                        BinaryStorageInterceptor.class.getName() + "_AUTO_INFLATE_BINARY_CONTENT";
095
096        private static final Predicate<IBaseExtension<?, ?>> EXTENSION_FILTER_PREDICATE =
097                        ext -> ext.getUserData(JpaConstants.EXTENSION_EXT_SYSTEMDEFINED) == null;
098
099        @Autowired
100        private IBinaryStorageSvc myBinaryStorageSvc;
101
102        private final FhirContext myCtx;
103
104        @Autowired
105        private BinaryAccessProvider myBinaryAccessProvider;
106
107        @Autowired
108        private IInterceptorBroadcaster myInterceptorBroadcaster;
109
110        private Class<T> myBinaryType;
111        private String myDeferredListKey;
112        private long myAutoInflateBinariesMaximumBytes = 10 * FileUtils.ONE_MB;
113        private boolean myAllowAutoInflateBinaries = true;
114
115        public BinaryStorageInterceptor(FhirContext theCtx) {
116                myCtx = theCtx;
117                BaseRuntimeElementDefinition<?> base64Binary = myCtx.getElementDefinition("base64Binary");
118                assert base64Binary != null;
119                myBinaryType = (Class<T>) base64Binary.getImplementingClass();
120                myDeferredListKey = getClass().getName() + "_" + hashCode() + "_DEFERRED_LIST";
121        }
122
123        /**
124         * Any externalized binaries will be rehydrated if their size is below this thhreshold when
125         * reading the resource back. Default is 10MB.
126         */
127        public long getAutoInflateBinariesMaximumSize() {
128                return myAutoInflateBinariesMaximumBytes;
129        }
130
131        /**
132         * Any externalized binaries will be rehydrated if their size is below this thhreshold when
133         * reading the resource back. Default is 10MB.
134         */
135        public void setAutoInflateBinariesMaximumSize(long theAutoInflateBinariesMaximumBytes) {
136                myAutoInflateBinariesMaximumBytes = theAutoInflateBinariesMaximumBytes;
137        }
138
139        @Hook(Pointcut.STORAGE_PRESTORAGE_EXPUNGE_RESOURCE)
140        public void expungeResource(AtomicInteger theCounter, IBaseResource theResource) {
141
142                List<? extends IBase> binaryElements =
143                                myCtx.newTerser().getAllPopulatedChildElementsOfType(theResource, myBinaryType);
144
145                List<String> attachmentIds = binaryElements.stream()
146                                .flatMap(t -> ((IBaseHasExtensions) t).getExtension().stream())
147                                .filter(t -> HapiExtensions.EXT_EXTERNALIZED_BINARY_ID.equals(t.getUrl()))
148                                .map(t -> ((IPrimitiveType<?>) t.getValue()).getValueAsString())
149                                .collect(Collectors.toList());
150
151                for (String next : attachmentIds) {
152                        myBinaryStorageSvc.expungeBinaryContent(theResource.getIdElement(), next);
153                        theCounter.incrementAndGet();
154
155                        ourLog.info(
156                                        "Deleting binary blob {} because resource {} is being expunged",
157                                        next,
158                                        theResource.getIdElement().getValue());
159                }
160        }
161
162        @Hook(Pointcut.STORAGE_PRESTORAGE_RESOURCE_CREATED)
163        public void extractLargeBinariesBeforeCreate(
164                        RequestDetails theRequestDetails,
165                        TransactionDetails theTransactionDetails,
166                        IBaseResource theResource,
167                        Pointcut thePointcut)
168                        throws IOException {
169                extractLargeBinaries(theRequestDetails, theTransactionDetails, theResource, null, thePointcut);
170        }
171
172        @Hook(Pointcut.STORAGE_PRESTORAGE_RESOURCE_UPDATED)
173        public void extractLargeBinariesBeforeUpdate(
174                        RequestDetails theRequestDetails,
175                        TransactionDetails theTransactionDetails,
176                        IBaseResource thePreviousResource,
177                        IBaseResource theResource,
178                        Pointcut thePointcut)
179                        throws IOException {
180                blockIllegalExternalExtensions(thePreviousResource, theResource);
181                extractLargeBinaries(theRequestDetails, theTransactionDetails, theResource, thePreviousResource, thePointcut);
182        }
183
184        /**
185         * Prevents clients from submitting resources with binary storage ID or binary storage hash extensions,
186         * unless those extensions were already present in the existing resource. In other words, only HAPI itself
187         * may add these extensions to a resource.
188         */
189        private void blockIllegalExternalExtensions(IBaseResource thePreviousResource, IBaseResource theResource) {
190                Map<String, String> existingAttachmentIdToHashMap = buildHashAttachmentIdMap(thePreviousResource, true);
191                Set<String> existingBinaryIds = existingAttachmentIdToHashMap.keySet();
192                Collection<String> existingHashes = existingAttachmentIdToHashMap.values();
193
194                recursivelyScanResourceForBinaryData(theResource).forEach(target -> {
195                        String id =
196                                        target.getAttachmentIdFiltered(EXTENSION_FILTER_PREDICATE).orElse(null);
197                        String hash =
198                                        target.getHashExtensionFiltered(EXTENSION_FILTER_PREDICATE).orElse(null);
199
200                        // binaryId check
201                        if (id != null && !existingBinaryIds.contains(id)) {
202                                throwIllegalExtension(EXT_EXTERNALIZED_BINARY_ID, id);
203                        }
204                        // hash check
205                        if (hash != null && !existingHashes.contains(hash)) {
206                                throwIllegalExtension(EXT_EXTERNALIZED_BINARY_HASH_SHA_256, hash);
207                        }
208
209                        // binaryId - hash pair consistency check
210                        if (id != null && hash != null) {
211                                String expected = existingAttachmentIdToHashMap.get(id);
212                                if (!Objects.equals(expected, hash)) {
213                                        throwIllegalExtension(EXT_EXTERNALIZED_BINARY_HASH_SHA_256, hash);
214                                }
215                        }
216                });
217        }
218
219        private void throwIllegalExtension(String theExtensionUrl, String theValue) {
220                String msg = myCtx.getLocalizer()
221                                .getMessage(
222                                                BinaryStorageInterceptor.class,
223                                                "externalizedBinaryStorageExtensionFoundInRequestBody",
224                                                theExtensionUrl,
225                                                theValue);
226                throw new InvalidRequestException(Msg.code(1329) + msg);
227        }
228
229        private void extractLargeBinaries(
230                        RequestDetails theRequestDetails,
231                        TransactionDetails theTransactionDetails,
232                        IBaseResource theResource,
233                        IBaseResource thePreviousResource,
234                        Pointcut thePointcut)
235                        throws IOException {
236
237                IIdType resourceId = theResource.getIdElement();
238                if (!resourceId.hasResourceType() && resourceId.hasIdPart()) {
239                        String resourceType = myCtx.getResourceType(theResource);
240                        resourceId = new IdType(resourceType + "/" + resourceId.getIdPart());
241                }
242
243                Map<String, String> existingHashToAttachmentId = buildHashAttachmentIdMap(thePreviousResource, false);
244                List<IBinaryTarget> attachments = recursivelyScanResourceForBinaryData(theResource);
245                for (IBinaryTarget nextTarget : attachments) {
246                        byte[] data = nextTarget.getData();
247                        if (data != null && data.length > 0) {
248
249                                long nextPayloadLength = data.length;
250                                String nextContentType = nextTarget.getContentType();
251                                boolean shouldStoreBlob =
252                                                myBinaryStorageSvc.shouldStoreBinaryContent(nextPayloadLength, resourceId, nextContentType);
253                                if (shouldStoreBlob) {
254                                        String binaryContentHash = myBinaryAccessProvider.getBinaryContentHash(data);
255                                        String newBinaryContentId;
256                                        if (thePointcut == Pointcut.STORAGE_PRESTORAGE_RESOURCE_UPDATED) {
257                                                newBinaryContentId = storeBinaryContentIfRequired(
258                                                                theRequestDetails,
259                                                                existingHashToAttachmentId,
260                                                                binaryContentHash,
261                                                                data,
262                                                                resourceId,
263                                                                nextContentType);
264                                        } else {
265                                                assert thePointcut == Pointcut.STORAGE_PRESTORAGE_RESOURCE_CREATED : thePointcut.name();
266                                                newBinaryContentId = myBinaryStorageSvc.newBinaryContentId();
267
268                                                String prefix = invokeAssignBinaryContentPrefix(theRequestDetails, theResource);
269                                                if (isNotBlank(prefix)) {
270                                                        newBinaryContentId = prefix + newBinaryContentId;
271                                                }
272                                                if (myBinaryStorageSvc.isValidBinaryContentId(newBinaryContentId)) {
273                                                        List<DeferredBinaryTarget> deferredBinaryTargets =
274                                                                        getOrCreateDeferredBinaryStorageList(theResource);
275                                                        DeferredBinaryTarget newDeferredBinaryTarget =
276                                                                        new DeferredBinaryTarget(newBinaryContentId, nextTarget, data);
277                                                        deferredBinaryTargets.add(newDeferredBinaryTarget);
278                                                        newDeferredBinaryTarget.setBlobIdPrefixHookApplied(true);
279                                                } else {
280                                                        throw new InternalErrorException(Msg.code(2341)
281                                                                        + "Invalid binaryContent ID for backing storage service.[binaryContentId="
282                                                                        + newBinaryContentId + ",service="
283                                                                        + myBinaryStorageSvc.getClass().getName() + "]");
284                                                }
285                                        }
286
287                                        myBinaryAccessProvider.replaceDataWithExtension(nextTarget, newBinaryContentId);
288                                        myBinaryAccessProvider.addHashExtension(nextTarget, binaryContentHash);
289                                }
290                        }
291                }
292        }
293
294        /**
295         * Builds a map of SHA-256 hashes to corresponding attachment IDs from the given FHIR resource.
296         * @return A {@link Map} with keys as SHA-256 binary content hashes and values as attachment IDs.
297         */
298        private Map<String, String> buildHashAttachmentIdMap(
299                        IBaseResource thePreviousResource, boolean isAttachmentIdToHash) {
300                Map<String, String> result = new HashMap<>();
301
302                if (thePreviousResource == null) {
303                        return result;
304                }
305
306                List<IBinaryTarget> previousAttachments = recursivelyScanResourceForBinaryData(thePreviousResource);
307                for (IBinaryTarget attachment : previousAttachments) {
308                        Optional<String> hashOpt = attachment.getHashExtensionFiltered(EXTENSION_FILTER_PREDICATE);
309                        Optional<String> idOpt = attachment.getAttachmentIdFiltered(EXTENSION_FILTER_PREDICATE);
310
311                        if (isAttachmentIdToHash) {
312                                idOpt.ifPresent(id -> result.put(id, hashOpt.orElse(null)));
313                        } else {
314                                hashOpt.ifPresent(hash -> result.put(hash, idOpt.orElse(null)));
315                        }
316                }
317                return result;
318        }
319
320        /**
321         * This method checks if the given binary content (based on its SHA-256 hash) is already stored in previous
322         * resource version. If it is, it reuses the existing attachment ID to avoid saving the same content again.
323         * If it's not found, it stores the new content and returns the newly generated attachment ID.
324         */
325        private String storeBinaryContentIfRequired(
326                        RequestDetails theRequestDetails,
327                        Map<String, String> existingHashToAttachmentId,
328                        String binaryContentHash,
329                        byte[] data,
330                        IIdType resourceId,
331                        String nextContentType)
332                        throws IOException {
333                if (existingHashToAttachmentId.get(binaryContentHash) != null) {
334                        // input binary content is the same as existing binary content, reuse existing binaryId
335                        return existingHashToAttachmentId.get(binaryContentHash);
336                } else {
337                        // there is no existing binary content or content is different, store new content in binary storage
338                        ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
339                        StoredDetails storedDetails = myBinaryStorageSvc.storeBinaryContent(
340                                        resourceId, null, nextContentType, inputStream, theRequestDetails);
341                        return storedDetails.getBinaryContentId();
342                }
343        }
344
345        /**
346         * This invokes the {@link Pointcut#STORAGE_BINARY_ASSIGN_BLOB_ID_PREFIX} hook and returns the prefix to use for the blob ID, or null if there are no implementers.
347         * @return A string, which will be used to prefix the blob ID. May be null.
348         */
349        private String invokeAssignBinaryContentPrefix(RequestDetails theRequest, IBaseResource theResource) {
350                IInterceptorBroadcaster compositeBroadcaster =
351                                CompositeInterceptorBroadcaster.newCompositeBroadcaster(myInterceptorBroadcaster, theRequest);
352
353                // TODO: to be removed when pointcut STORAGE_BINARY_ASSIGN_BLOB_ID_PREFIX has exceeded the grace period
354                boolean hasStorageBinaryAssignBlobIdPrefixHooks =
355                                compositeBroadcaster.hasHooks(Pointcut.STORAGE_BINARY_ASSIGN_BLOB_ID_PREFIX);
356
357                boolean hasStorageBinaryAssignBinaryContentIdPrefixHooks =
358                                compositeBroadcaster.hasHooks(Pointcut.STORAGE_BINARY_ASSIGN_BINARY_CONTENT_ID_PREFIX);
359
360                if (!(hasStorageBinaryAssignBlobIdPrefixHooks || hasStorageBinaryAssignBinaryContentIdPrefixHooks)) {
361                        return null;
362                }
363
364                HookParams params =
365                                new HookParams().add(RequestDetails.class, theRequest).add(IBaseResource.class, theResource);
366
367                BaseBinaryStorageSvcImpl.setBinaryContentIdPrefixApplied(theRequest);
368
369                Pointcut pointcutToInvoke = Pointcut.STORAGE_BINARY_ASSIGN_BINARY_CONTENT_ID_PREFIX;
370
371                // TODO: to be removed when pointcut STORAGE_BINARY_ASSIGN_BLOB_ID_PREFIX has exceeded the grace period
372                if (hasStorageBinaryAssignBlobIdPrefixHooks) {
373                        pointcutToInvoke = Pointcut.STORAGE_BINARY_ASSIGN_BLOB_ID_PREFIX;
374                }
375
376                return (String) compositeBroadcaster.callHooksAndReturnObject(pointcutToInvoke, params);
377        }
378
379        @Nonnull
380        @SuppressWarnings("unchecked")
381        private List<DeferredBinaryTarget> getOrCreateDeferredBinaryStorageList(IBaseResource theResource) {
382                Object deferredBinaryTargetList = theResource.getUserData(getDeferredListKey());
383                if (deferredBinaryTargetList == null) {
384                        deferredBinaryTargetList = new ArrayList<>();
385                        theResource.setUserData(getDeferredListKey(), deferredBinaryTargetList);
386                }
387                return (List<DeferredBinaryTarget>) deferredBinaryTargetList;
388        }
389
390        @SuppressWarnings("unchecked")
391        @Hook(Pointcut.STORAGE_PRECOMMIT_RESOURCE_CREATED)
392        public void storeLargeBinariesBeforeCreatePersistence(
393                        TransactionDetails theTransactionDetails, IBaseResource theResource, Pointcut thePointcut)
394                        throws IOException {
395                if (theResource == null) {
396                        return;
397                }
398                Object deferredBinaryTargetList = theResource.getUserData(getDeferredListKey());
399
400                if (deferredBinaryTargetList != null) {
401                        IIdType resourceId = theResource.getIdElement();
402                        for (DeferredBinaryTarget next : (List<DeferredBinaryTarget>) deferredBinaryTargetList) {
403                                String blobId = next.getBlobId();
404                                IBinaryTarget target = next.getBinaryTarget();
405                                InputStream dataStream = next.getDataStream();
406                                String contentType = target.getContentType();
407                                RequestDetails requestDetails = initRequestDetails(next);
408                                myBinaryStorageSvc.storeBinaryContent(resourceId, blobId, contentType, dataStream, requestDetails);
409                        }
410                }
411        }
412
413        private RequestDetails initRequestDetails(DeferredBinaryTarget theDeferredBinaryTarget) {
414                ServletRequestDetails requestDetails = new ServletRequestDetails();
415                if (theDeferredBinaryTarget.isBlobIdPrefixHookApplied()) {
416                        BaseBinaryStorageSvcImpl.setBinaryContentIdPrefixApplied(requestDetails);
417                }
418                return requestDetails;
419        }
420
421        public String getDeferredListKey() {
422                return myDeferredListKey;
423        }
424
425        @Hook(Pointcut.STORAGE_PRESHOW_RESOURCES)
426        public void preShow(IPreResourceShowDetails theDetails, RequestDetails theRequestDetails) throws IOException {
427                boolean isAllowAutoInflateBinaries = isAllowAutoInflateBinaries();
428                // Override isAllowAutoInflateBinaries setting if AUTO_INFLATE_BINARY_CONTENT flag is present in userData
429                if (theRequestDetails != null && theRequestDetails.getUserData().containsKey(AUTO_INFLATE_BINARY_CONTENT_KEY)) {
430                        isAllowAutoInflateBinaries =
431                                        Boolean.TRUE.equals(theRequestDetails.getUserData().get(AUTO_INFLATE_BINARY_CONTENT_KEY));
432                }
433                if (!isAllowAutoInflateBinaries) {
434                        return;
435                }
436
437                long cumulativeInflatedBytes = 0;
438                int inflatedResourceCount = 0;
439
440                for (IBaseResource nextResource : theDetails) {
441                        if (nextResource == null) {
442                                ourLog.warn(
443                                                "Received a null resource during STORAGE_PRESHOW_RESOURCES. This is a bug and should be reported. Skipping resource.");
444                                continue;
445                        }
446                        cumulativeInflatedBytes = inflateBinariesInResource(cumulativeInflatedBytes, nextResource);
447                        inflatedResourceCount += 1;
448                        if (cumulativeInflatedBytes >= myAutoInflateBinariesMaximumBytes) {
449                                ourLog.debug(
450                                                "Exiting binary data inflation early.[byteCount={}, resourcesInflated={}, resourcesSkipped={}]",
451                                                cumulativeInflatedBytes,
452                                                inflatedResourceCount,
453                                                theDetails.size() - inflatedResourceCount);
454                                return;
455                        }
456                }
457                ourLog.debug(
458                                "Exiting binary data inflation having inflated everything.[byteCount={}, resourcesInflated={}, resourcesSkipped=0]",
459                                cumulativeInflatedBytes,
460                                inflatedResourceCount);
461        }
462
463        private long inflateBinariesInResource(long theCumulativeInflatedBytes, IBaseResource theResource)
464                        throws IOException {
465                IIdType resourceId = theResource.getIdElement();
466                List<IBinaryTarget> attachments = recursivelyScanResourceForBinaryData(theResource);
467                for (IBinaryTarget nextTarget : attachments) {
468                        Optional<String> attachmentId = nextTarget.getAttachmentId();
469                        if (attachmentId.isPresent()) {
470
471                                StoredDetails blobDetails =
472                                                myBinaryStorageSvc.fetchBinaryContentDetails(resourceId, attachmentId.get());
473                                if (blobDetails == null) {
474                                        String msg = myCtx.getLocalizer().getMessage(BinaryAccessProvider.class, "unknownBlobId");
475                                        throw new InvalidRequestException(Msg.code(1330) + msg);
476                                }
477
478                                if ((theCumulativeInflatedBytes + blobDetails.getBytes()) < myAutoInflateBinariesMaximumBytes) {
479                                        byte[] bytes = myBinaryStorageSvc.fetchBinaryContent(resourceId, attachmentId.get());
480                                        nextTarget.setData(bytes);
481                                        theCumulativeInflatedBytes += blobDetails.getBytes();
482                                }
483                        }
484                }
485                return theCumulativeInflatedBytes;
486        }
487
488        @Nonnull
489        private List<IBinaryTarget> recursivelyScanResourceForBinaryData(IBaseResource theResource) {
490                List<IBinaryTarget> binaryTargets = new ArrayList<>();
491                myCtx.newTerser().visit(theResource, new IModelVisitor2() {
492                        @Override
493                        public boolean acceptElement(
494                                        IBase theElement,
495                                        List<IBase> theContainingElementPath,
496                                        List<BaseRuntimeChildDefinition> theChildDefinitionPath,
497                                        List<BaseRuntimeElementDefinition<?>> theElementDefinitionPath) {
498
499                                if (theElement.getClass().equals(myBinaryType)) {
500                                        IBase parent = theContainingElementPath.get(theContainingElementPath.size() - 2);
501                                        Optional<IBinaryTarget> binaryTarget = myBinaryAccessProvider.toBinaryTarget(parent);
502                                        binaryTarget.ifPresent(binaryTargets::add);
503                                }
504                                return true;
505                        }
506                });
507                return binaryTargets;
508        }
509
510        public void setAllowAutoInflateBinaries(boolean theAllowAutoInflateBinaries) {
511                myAllowAutoInflateBinaries = theAllowAutoInflateBinaries;
512        }
513
514        public boolean isAllowAutoInflateBinaries() {
515                return myAllowAutoInflateBinaries;
516        }
517
518        private static class DeferredBinaryTarget {
519                private final String myBlobId;
520                private final IBinaryTarget myBinaryTarget;
521                private final InputStream myDataStream;
522                private boolean myBlobIdPrefixHookApplied;
523
524                private DeferredBinaryTarget(String theBlobId, IBinaryTarget theBinaryTarget, byte[] theData) {
525                        myBlobId = theBlobId;
526                        myBinaryTarget = theBinaryTarget;
527                        myDataStream = new ByteArrayInputStream(theData);
528                }
529
530                String getBlobId() {
531                        return myBlobId;
532                }
533
534                IBinaryTarget getBinaryTarget() {
535                        return myBinaryTarget;
536                }
537
538                InputStream getDataStream() {
539                        return myDataStream;
540                }
541
542                boolean isBlobIdPrefixHookApplied() {
543                        return myBlobIdPrefixHookApplied;
544                }
545
546                void setBlobIdPrefixHookApplied(boolean theBlobIdPrefixHookApplied) {
547                        myBlobIdPrefixHookApplied = theBlobIdPrefixHookApplied;
548                }
549        }
550}