1 package org.apache.maven.doxia.macro.snippet;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.BufferedReader;
23 import java.io.IOException;
24 import java.io.InputStreamReader;
25 import java.net.URL;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Locale;
29
30 import org.codehaus.plexus.util.IOUtil;
31
32
33
34
35
36
37 public class SnippetReader
38 {
39
40 private static final String EOL = System.getProperty( "line.separator" );
41
42
43 private URL source;
44
45
46
47
48
49
50 public SnippetReader( URL src )
51 {
52 this.source = src;
53 }
54
55
56
57
58
59
60
61
62 public StringBuffer readSnippet( String snippetId )
63 throws IOException
64 {
65 List<String> lines = readLines( snippetId );
66 int minIndent = minIndent( lines );
67 StringBuffer result = new StringBuffer();
68 for ( String line : lines )
69 {
70 result.append( line.substring( minIndent ) );
71 result.append( EOL );
72 }
73 return result;
74 }
75
76
77
78
79
80
81
82 int minIndent( List<String> lines )
83 {
84 int minIndent = Integer.MAX_VALUE;
85 for ( String line : lines )
86 {
87 minIndent = Math.min( minIndent, indent( line ) );
88 }
89 return minIndent;
90 }
91
92
93
94
95
96
97
98 int indent( String line )
99 {
100 char[] chars = line.toCharArray();
101 int indent = 0;
102 for ( ; indent < chars.length; indent++ )
103 {
104 if ( chars[indent] != ' ' )
105 {
106 break;
107 }
108 }
109 return indent;
110 }
111
112
113
114
115
116
117
118
119 private List<String> readLines( String snippetId )
120 throws IOException
121 {
122
123 BufferedReader reader = new BufferedReader( new InputStreamReader( source.openStream() ) );
124 List<String> lines = new ArrayList<String>();
125 try
126 {
127 boolean capture = false;
128 String line;
129 while ( ( line = reader.readLine() ) != null )
130 {
131 if ( snippetId == null || "".equals( snippetId.trim() ) )
132 {
133 lines.add( line );
134 }
135 else
136 {
137 if ( isStart( snippetId, line ) )
138 {
139 capture = true;
140 }
141 else if ( isEnd( snippetId, line ) )
142 {
143 break;
144 }
145 else if ( capture )
146 {
147 lines.add( line );
148 }
149 }
150 }
151 }
152 finally
153 {
154 IOUtil.close( reader );
155 }
156 return lines;
157 }
158
159
160
161
162
163
164
165
166 protected boolean isStart( String snippetId, String line )
167 {
168 return isDemarcator( snippetId, "START", line );
169 }
170
171
172
173
174
175
176
177
178
179 protected boolean isDemarcator( String snippetId, String what, String line )
180 {
181 String upper = line.toUpperCase( Locale.ENGLISH );
182 return upper.contains( what.toUpperCase( Locale.ENGLISH ) )
183 && upper.contains( "SNIPPET" )
184 && line.contains( snippetId );
185 }
186
187
188
189
190
191
192
193
194 protected boolean isEnd( String snippetId, String line )
195 {
196 return isDemarcator( snippetId, "END", line );
197 }
198 }