001// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org> 002// 003// SPDX-License-Identifier: Apache-2.0 004 005package org.pgpainless.decryption_verification.cleartext_signatures; 006 007import java.io.File; 008import java.io.FileInputStream; 009import java.io.FileOutputStream; 010import java.io.IOException; 011import java.io.InputStream; 012import java.io.OutputStream; 013 014/** 015 * Implementation of the {@link MultiPassStrategy}. 016 * When processing signed data the first time, the data is being written out into a file. 017 * For the second pass, that file is being read again. 018 * 019 * This strategy is recommended when larger amounts of data need to be processed. 020 * For smaller files, {@link InMemoryMultiPassStrategy} yields higher efficiency. 021 */ 022public class WriteToFileMultiPassStrategy implements MultiPassStrategy { 023 024 private final File file; 025 026 /** 027 * Create a {@link MultiPassStrategy} which writes data to a file. 028 * Note that {@link #getMessageOutputStream()} will create the file if necessary. 029 * 030 * @param file file to write the data to and read from 031 */ 032 public WriteToFileMultiPassStrategy(File file) { 033 this.file = file; 034 } 035 036 @Override 037 public OutputStream getMessageOutputStream() throws IOException { 038 if (!file.exists()) { 039 boolean created = file.createNewFile(); 040 if (!created) { 041 throw new IOException("New file '" + file.getAbsolutePath() + "' was not created."); 042 } 043 } 044 return new FileOutputStream(file); 045 } 046 047 @Override 048 public InputStream getMessageInputStream() throws IOException { 049 if (!file.exists()) { 050 throw new IOException("File '" + file.getAbsolutePath() + "' does no longer exist."); 051 } 052 return new FileInputStream(file); 053 } 054}