View Javadoc
1   /* 
2    * Copyright (C) 2016 Hobrasoft s.r.o.
3    *
4    * This program is free software: you can redistribute it and/or modify
5    * it under the terms of the GNU Affero General Public License as published by
6    * the Free Software Foundation, either version 3 of the License, or
7    * (at your option) any later version.
8    *
9    * This program is distributed in the hope that it will be useful,
10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   * GNU Affero General Public License for more details.
13   *
14   * You should have received a copy of the GNU Affero General Public License
15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16   */
17  package cz.hobrasoft.pdfmu;
18  
19  import java.io.File;
20  import java.io.FileOutputStream;
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.io.OutputStream;
24  import org.apache.commons.io.IOUtils;
25  import org.junit.rules.TemporaryFolder;
26  
27  /**
28   * @author Filip Bártek
29   */
30  class FileResource {
31  
32      private final String resourceName;
33      public final String fileName;
34  
35      public FileResource(String resourceName, String fileName) {
36          assert resourceName != null;
37          this.resourceName = resourceName;
38          this.fileName = fileName;
39      }
40  
41      public FileResource(String resourceName) {
42          this(resourceName, resourceName);
43      }
44  
45      public File getFile(TemporaryFolder folder) throws IOException {
46          File file;
47          try (InputStream in = getStream()) {
48              assert in != null;
49              file = MainTest.newFile(folder, fileName, true);
50              assert file.exists();
51              try (OutputStream out = new FileOutputStream(file)) {
52                  assert out != null;
53                  IOUtils.copy(in, out);
54              }
55          }
56          return file;
57      }
58  
59      public InputStream getStream() {
60          ClassLoader classLoader = this.getClass().getClassLoader();
61          assert resourceName != null;
62          InputStream in = classLoader.getResourceAsStream(resourceName);
63          assert in != null;
64          return in;
65      }
66  
67  }