View Javadoc

1   package com.atlassian.plugin;
2   
3   import java.util.jar.JarFile;
4   import java.util.zip.ZipEntry;
5   import java.io.*;
6   
7   /**
8    * The implementation of PluginJar which reads from a specified file on disk.
9    *
10   * @see PluginJar
11   */
12  public class FilePluginJar implements PluginJar
13  {
14      private final File jarFile;
15  
16      public FilePluginJar(File jarFile)
17      {
18          this.jarFile = jarFile;
19      }
20  
21      /**
22       * @return an input stream for the this file in the jar. Closing this stream also closes the jar file this stream comes from.
23       */
24      public InputStream getFile(String fileName) throws PluginParseException
25      {
26          final JarFile jar;
27          try
28          {
29              jar = new JarFile(jarFile);
30          }
31          catch (IOException e)
32          {
33              throw new PluginParseException("Cannot open JAR file for reading: " + jarFile, e);
34          }
35  
36          ZipEntry entry = jar.getEntry(fileName);
37          if (entry == null)
38          {
39              throw new PluginParseException("File " + fileName + " not found in plugin JAR [" + jarFile + "]");
40          }
41  
42          InputStream descriptorStream;
43          try
44          {
45              descriptorStream = new BufferedInputStream(jar.getInputStream(entry)) {
46  
47                  // because we do not expose a handle to the jar file this stream is associated with, we need to make sure
48                  // we explicitly close the jar file when we're done with the stream (else we'll have a file handle leak)
49                  public void close() throws IOException
50                  {
51                      super.close();
52                      jar.close();
53                  }
54              };
55          }
56          catch (IOException e)
57          {
58              throw new PluginParseException("Cannot retrieve " + fileName + " from plugin JAR [" + jarFile + "]", e);
59          }
60          return descriptorStream;
61      }
62  
63      public String getFileName()
64      {
65          return jarFile.getName();
66      }
67  
68      /**
69       * @return a buffered file input stream of the file on disk. This input stream
70       * is not resettable.
71       */
72      public InputStream getInputStream()
73      {
74          try
75          {
76              return new BufferedInputStream(new FileInputStream(jarFile));
77          }
78          catch (FileNotFoundException e)
79          {
80              throw new RuntimeException("Could not open JAR file for reading: " + jarFile, e);
81          }
82      }
83  }