View Javadoc

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