1   package org.apache.maven.plugins.shade.resource;
2   
3   
4   
5   
6   
7   
8   
9   
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  import org.apache.maven.plugins.shade.relocation.Relocator;
23  import org.codehaus.plexus.util.IOUtil;
24  
25  import java.io.IOException;
26  import java.io.InputStream;
27  import java.util.Iterator;
28  import java.util.List;
29  import java.util.Map;
30  import java.util.jar.Attributes;
31  import java.util.jar.JarEntry;
32  import java.util.jar.JarFile;
33  import java.util.jar.JarOutputStream;
34  import java.util.jar.Manifest;
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  public class ManifestResourceTransformer
45      implements ResourceTransformer
46  {
47  
48      
49      private String mainClass;
50  
51      private Map manifestEntries;
52  
53      
54      private boolean manifestDiscovered;
55  
56      private Manifest manifest;
57  
58      public boolean canTransformResource( String resource )
59      {
60          if ( JarFile.MANIFEST_NAME.equalsIgnoreCase( resource ) )
61          {
62              return true;
63          }
64  
65          return false;
66      }
67  
68      public void processResource( String resource, InputStream is, List<Relocator> relocators )
69          throws IOException
70      {
71          
72          
73          
74          if ( !manifestDiscovered )
75          {
76              manifest = new Manifest( is );
77              manifestDiscovered = true;
78              IOUtil.close( is );
79          }
80      }
81  
82      public boolean hasTransformedResource()
83      {
84          return true;
85      }
86  
87      public void modifyOutputStream( JarOutputStream jos )
88          throws IOException
89      {
90          
91          if ( manifest == null )
92          {
93              manifest = new Manifest();
94          }
95  
96          Attributes attributes = manifest.getMainAttributes();
97  
98          if ( mainClass != null )
99          {
100             attributes.put( Attributes.Name.MAIN_CLASS, mainClass );
101         }
102 
103         if ( manifestEntries != null )
104         {
105             for ( Iterator i = manifestEntries.keySet().iterator(); i.hasNext(); )
106             {
107                 String key = (String) i.next();
108                 attributes.put( new Attributes.Name( key ), manifestEntries.get( key ) );
109             }
110         }
111 
112         jos.putNextEntry( new JarEntry( JarFile.MANIFEST_NAME ) );
113         manifest.write( jos );
114     }
115 }