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 java.io.ByteArrayInputStream;
23 import java.io.ByteArrayOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.StringReader;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.jar.JarEntry;
31 import java.util.jar.JarOutputStream;
32
33 import org.apache.commons.io.IOUtils;
34 import org.apache.maven.plugins.shade.relocation.Relocator;
35 import org.codehaus.plexus.util.IOUtil;
36
37 import com.google.common.io.LineReader;
38
39
40
41
42
43
44
45
46 public class ServicesResourceTransformer
47 implements ResourceTransformer
48 {
49
50 private static final String SERVICES_PATH = "META-INF/services";
51
52 private Map<String, ServiceStream> serviceEntries = new HashMap<String, ServiceStream>();
53
54 public boolean canTransformResource( String resource )
55 {
56 if ( resource.startsWith( SERVICES_PATH ) )
57 {
58 return true;
59 }
60
61 return false;
62 }
63
64 public void processResource( String resource, InputStream is, final List<Relocator> relocators )
65 throws IOException
66 {
67 ServiceStream out = serviceEntries.get( resource );
68 if ( out == null )
69 {
70 out = new ServiceStream();
71 serviceEntries.put( resource, out );
72 }
73
74 final ServiceStream fout = out;
75
76 final String content = IOUtils.toString( is );
77 StringReader reader = new StringReader( content );
78 LineReader lineReader = new LineReader( reader );
79 String line;
80 while ( ( line = lineReader.readLine() ) != null )
81 {
82 String relContent = line;
83 for ( Relocator relocator : relocators )
84 {
85 relContent = relocator.applyToSourceContent( relContent );
86 }
87 fout.append( relContent + "\n" );
88 }
89 }
90 public boolean hasTransformedResource()
91 {
92 return serviceEntries.size() > 0;
93 }
94
95 public void modifyOutputStream( JarOutputStream jos )
96 throws IOException
97 {
98 for ( Map.Entry<String, ServiceStream> entry : serviceEntries.entrySet() )
99 {
100 String key = entry.getKey();
101 ServiceStream data = entry.getValue();
102
103 jos.putNextEntry( new JarEntry( key ) );
104 IOUtil.copy( data.toInputStream(), jos );
105 data.reset();
106 }
107 }
108
109 static class ServiceStream
110 extends ByteArrayOutputStream
111 {
112
113 public ServiceStream()
114 {
115 super( 1024 );
116 }
117
118 public void append( String content )
119 throws IOException
120 {
121 if ( count > 0 && buf[count - 1] != '\n' && buf[count - 1] != '\r' )
122 {
123 write( '\n' );
124 }
125
126 byte[] contentBytes = content.getBytes( "UTF-8" );
127 this.write( contentBytes );
128 }
129
130 public InputStream toInputStream()
131 {
132 return new ByteArrayInputStream( buf, 0, count );
133 }
134
135 }
136
137 }