001/* 002 * (C) Copyright 2019 Nuxeo (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Florent Guillaume 018 */ 019package org.nuxeo.ecm.core.blob; 020 021import java.io.IOException; 022import java.io.InputStream; 023import java.nio.file.Files; 024import java.nio.file.Path; 025import java.util.function.Supplier; 026 027import org.nuxeo.ecm.core.blob.KeyStrategy.WriteObserver; 028 029/** 030 * Context available when a blob is written. 031 * 032 * @since 11.1 033 */ 034public class BlobWriteContext { 035 036 public final BlobContext blobContext; 037 038 public final WriteObserver writeObserver; 039 040 public final Supplier<String> keyComputer; 041 042 public final KeyStrategy keyStrategy; 043 044 protected Path file; 045 046 public BlobWriteContext(BlobContext blobContext, WriteObserver writeObserver, Supplier<String> keyComputer, KeyStrategy keyStrategy) { 047 this.blobContext = blobContext; 048 this.writeObserver = writeObserver; 049 this.keyComputer = keyComputer; 050 this.keyStrategy = keyStrategy; 051 } 052 053 public BlobWriteContext copyWithKey(String key) { 054 BlobWriteContext context = new BlobWriteContext(blobContext, writeObserver, () -> key, 055 KeyStrategyDocId.instance()); // KeyStrategyDocId is used to mean "no deduplication" 056 context.setFile(file); 057 return context; 058 } 059 060 public BlobWriteContext copyWithNoWriteObserverAndKey(String key) { 061 BlobWriteContext context = new BlobWriteContext(blobContext, null, () -> key, null); 062 context.setFile(file); 063 return context; 064 } 065 066 public boolean useDeDuplication() { 067 return keyStrategy.useDeDuplication(); 068 } 069 070 public String getKey() { 071 return keyComputer.get(); 072 } 073 074 public void setFile(Path file) { 075 this.file = file; 076 } 077 078 public Path getFile() { 079 return file; 080 } 081 082 public InputStream getStream() throws IOException { 083 return file == null ? blobContext.blob.getStream() : Files.newInputStream(file); 084 } 085 086}