1 /* |
|
2 * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. |
|
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
|
4 * |
|
5 * This code is free software; you can redistribute it and/or modify it |
|
6 * under the terms of the GNU General Public License version 2 only, as |
|
7 * published by the Free Software Foundation. Oracle designates this |
|
8 * particular file as subject to the "Classpath" exception as provided |
|
9 * by Oracle in the LICENSE file that accompanied this code. |
|
10 * |
|
11 * This code is distributed in the hope that it will be useful, but WITHOUT |
|
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
14 * version 2 for more details (a copy is included in the LICENSE file that |
|
15 * accompanied this code). |
|
16 * |
|
17 * You should have received a copy of the GNU General Public License version |
|
18 * 2 along with this work; if not, write to the Free Software Foundation, |
|
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
20 * |
|
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA |
|
22 * or visit www.oracle.com if you need additional information or have any |
|
23 * questions. |
|
24 */ |
|
25 |
|
26 package com.sun.tools.javac.util; |
|
27 |
|
28 import java.io.ByteArrayOutputStream; |
|
29 import java.io.IOException; |
|
30 import java.io.InputStream; |
|
31 import java.io.OutputStreamWriter; |
|
32 import java.lang.ref.SoftReference; |
|
33 import java.lang.reflect.Constructor; |
|
34 import java.net.URL; |
|
35 import java.net.URLClassLoader; |
|
36 import java.nio.ByteBuffer; |
|
37 import java.nio.CharBuffer; |
|
38 import java.nio.charset.Charset; |
|
39 import java.nio.charset.CharsetDecoder; |
|
40 import java.nio.charset.CoderResult; |
|
41 import java.nio.charset.CodingErrorAction; |
|
42 import java.nio.charset.IllegalCharsetNameException; |
|
43 import java.nio.charset.UnsupportedCharsetException; |
|
44 import java.nio.file.Path; |
|
45 import java.util.Collection; |
|
46 import java.util.HashMap; |
|
47 import java.util.Iterator; |
|
48 import java.util.Map; |
|
49 import java.util.Objects; |
|
50 import java.util.Set; |
|
51 |
|
52 import javax.tools.JavaFileManager; |
|
53 import javax.tools.JavaFileObject; |
|
54 import javax.tools.JavaFileObject.Kind; |
|
55 |
|
56 import com.sun.tools.javac.code.Lint; |
|
57 import com.sun.tools.javac.code.Source; |
|
58 import com.sun.tools.javac.file.FSInfo; |
|
59 import com.sun.tools.javac.file.Locations; |
|
60 import com.sun.tools.javac.main.Option; |
|
61 import com.sun.tools.javac.main.OptionHelper; |
|
62 import com.sun.tools.javac.main.OptionHelper.GrumpyHelper; |
|
63 import com.sun.tools.javac.util.DefinedBy.Api; |
|
64 import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition; |
|
65 |
|
66 /** |
|
67 * Utility methods for building a filemanager. |
|
68 * There are no references here to file-system specific objects such as |
|
69 * java.io.File or java.nio.file.Path. |
|
70 */ |
|
71 public abstract class BaseFileManager implements JavaFileManager { |
|
72 protected BaseFileManager(Charset charset) { |
|
73 this.charset = charset; |
|
74 byteBufferCache = new ByteBufferCache(); |
|
75 locations = createLocations(); |
|
76 } |
|
77 |
|
78 /** |
|
79 * Set the context for JavacPathFileManager. |
|
80 * @param context the context containing items to be associated with the file manager |
|
81 */ |
|
82 public void setContext(Context context) { |
|
83 log = Log.instance(context); |
|
84 options = Options.instance(context); |
|
85 classLoaderClass = options.get("procloader"); |
|
86 locations.update(log, Lint.instance(context), FSInfo.instance(context)); |
|
87 } |
|
88 |
|
89 protected Locations createLocations() { |
|
90 return new Locations(); |
|
91 } |
|
92 |
|
93 /** |
|
94 * The log to be used for error reporting. |
|
95 */ |
|
96 public Log log; |
|
97 |
|
98 /** |
|
99 * User provided charset (through javax.tools). |
|
100 */ |
|
101 protected Charset charset; |
|
102 |
|
103 protected Options options; |
|
104 |
|
105 protected String classLoaderClass; |
|
106 |
|
107 protected Locations locations; |
|
108 |
|
109 /** |
|
110 * A flag for clients to use to indicate that this file manager should |
|
111 * be closed when it is no longer required. |
|
112 */ |
|
113 public boolean autoClose; |
|
114 |
|
115 protected Source getSource() { |
|
116 String sourceName = options.get(Option.SOURCE); |
|
117 Source source = null; |
|
118 if (sourceName != null) |
|
119 source = Source.lookup(sourceName); |
|
120 return (source != null ? source : Source.DEFAULT); |
|
121 } |
|
122 |
|
123 protected ClassLoader getClassLoader(URL[] urls) { |
|
124 ClassLoader thisClassLoader = getClass().getClassLoader(); |
|
125 |
|
126 // Allow the following to specify a closeable classloader |
|
127 // other than URLClassLoader. |
|
128 |
|
129 // 1: Allow client to specify the class to use via hidden option |
|
130 if (classLoaderClass != null) { |
|
131 try { |
|
132 Class<? extends ClassLoader> loader = |
|
133 Class.forName(classLoaderClass).asSubclass(ClassLoader.class); |
|
134 Class<?>[] constrArgTypes = { URL[].class, ClassLoader.class }; |
|
135 Constructor<? extends ClassLoader> constr = loader.getConstructor(constrArgTypes); |
|
136 return constr.newInstance(urls, thisClassLoader); |
|
137 } catch (ReflectiveOperationException t) { |
|
138 // ignore errors loading user-provided class loader, fall through |
|
139 } |
|
140 } |
|
141 return new URLClassLoader(urls, thisClassLoader); |
|
142 } |
|
143 |
|
144 public boolean isDefaultBootClassPath() { |
|
145 return locations.isDefaultBootClassPath(); |
|
146 } |
|
147 |
|
148 // <editor-fold defaultstate="collapsed" desc="Option handling"> |
|
149 @Override @DefinedBy(Api.COMPILER) |
|
150 public boolean handleOption(String current, Iterator<String> remaining) { |
|
151 OptionHelper helper = new GrumpyHelper(log) { |
|
152 @Override |
|
153 public String get(Option option) { |
|
154 return options.get(option.getText()); |
|
155 } |
|
156 |
|
157 @Override |
|
158 public void put(String name, String value) { |
|
159 options.put(name, value); |
|
160 } |
|
161 |
|
162 @Override |
|
163 public void remove(String name) { |
|
164 options.remove(name); |
|
165 } |
|
166 |
|
167 @Override |
|
168 public boolean handleFileManagerOption(Option option, String value) { |
|
169 return handleOption(option, value); |
|
170 } |
|
171 }; |
|
172 |
|
173 for (Option o: javacFileManagerOptions) { |
|
174 if (o.matches(current)) { |
|
175 if (o.hasArg()) { |
|
176 if (remaining.hasNext()) { |
|
177 if (!o.process(helper, current, remaining.next())) |
|
178 return true; |
|
179 } |
|
180 } else { |
|
181 if (!o.process(helper, current)) |
|
182 return true; |
|
183 } |
|
184 // operand missing, or process returned true |
|
185 throw new IllegalArgumentException(current); |
|
186 } |
|
187 } |
|
188 |
|
189 return false; |
|
190 } |
|
191 // where |
|
192 private static final Set<Option> javacFileManagerOptions = |
|
193 Option.getJavacFileManagerOptions(); |
|
194 |
|
195 @Override @DefinedBy(Api.COMPILER) |
|
196 public int isSupportedOption(String option) { |
|
197 for (Option o : javacFileManagerOptions) { |
|
198 if (o.matches(option)) |
|
199 return o.hasArg() ? 1 : 0; |
|
200 } |
|
201 return -1; |
|
202 } |
|
203 |
|
204 /** |
|
205 * Common back end for OptionHelper handleFileManagerOption. |
|
206 * @param option the option whose value to be set |
|
207 * @param value the value for the option |
|
208 * @return true if successful, and false otherwise |
|
209 */ |
|
210 public boolean handleOption(Option option, String value) { |
|
211 return locations.handleOption(option, value); |
|
212 } |
|
213 |
|
214 /** |
|
215 * Call handleOption for collection of options and corresponding values. |
|
216 * @param map a collection of options and corresponding values |
|
217 * @return true if all the calls are successful |
|
218 */ |
|
219 public boolean handleOptions(Map<Option, String> map) { |
|
220 boolean ok = true; |
|
221 for (Map.Entry<Option, String> e: map.entrySet()) |
|
222 ok = ok & handleOption(e.getKey(), e.getValue()); |
|
223 return ok; |
|
224 } |
|
225 |
|
226 // </editor-fold> |
|
227 |
|
228 // <editor-fold defaultstate="collapsed" desc="Encoding"> |
|
229 private String defaultEncodingName; |
|
230 private String getDefaultEncodingName() { |
|
231 if (defaultEncodingName == null) { |
|
232 defaultEncodingName = |
|
233 new OutputStreamWriter(new ByteArrayOutputStream()).getEncoding(); |
|
234 } |
|
235 return defaultEncodingName; |
|
236 } |
|
237 |
|
238 public String getEncodingName() { |
|
239 String encName = options.get(Option.ENCODING); |
|
240 if (encName == null) |
|
241 return getDefaultEncodingName(); |
|
242 else |
|
243 return encName; |
|
244 } |
|
245 |
|
246 @SuppressWarnings("cast") |
|
247 public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) { |
|
248 String encodingName = getEncodingName(); |
|
249 CharsetDecoder decoder; |
|
250 try { |
|
251 decoder = getDecoder(encodingName, ignoreEncodingErrors); |
|
252 } catch (IllegalCharsetNameException | UnsupportedCharsetException e) { |
|
253 log.error("unsupported.encoding", encodingName); |
|
254 return (CharBuffer)CharBuffer.allocate(1).flip(); |
|
255 } |
|
256 |
|
257 // slightly overestimate the buffer size to avoid reallocation. |
|
258 float factor = |
|
259 decoder.averageCharsPerByte() * 0.8f + |
|
260 decoder.maxCharsPerByte() * 0.2f; |
|
261 CharBuffer dest = CharBuffer. |
|
262 allocate(10 + (int)(inbuf.remaining()*factor)); |
|
263 |
|
264 while (true) { |
|
265 CoderResult result = decoder.decode(inbuf, dest, true); |
|
266 dest.flip(); |
|
267 |
|
268 if (result.isUnderflow()) { // done reading |
|
269 // make sure there is at least one extra character |
|
270 if (dest.limit() == dest.capacity()) { |
|
271 dest = CharBuffer.allocate(dest.capacity()+1).put(dest); |
|
272 dest.flip(); |
|
273 } |
|
274 return dest; |
|
275 } else if (result.isOverflow()) { // buffer too small; expand |
|
276 int newCapacity = |
|
277 10 + dest.capacity() + |
|
278 (int)(inbuf.remaining()*decoder.maxCharsPerByte()); |
|
279 dest = CharBuffer.allocate(newCapacity).put(dest); |
|
280 } else if (result.isMalformed() || result.isUnmappable()) { |
|
281 // bad character in input |
|
282 |
|
283 log.error(new SimpleDiagnosticPosition(dest.limit()), |
|
284 "illegal.char.for.encoding", |
|
285 charset == null ? encodingName : charset.name()); |
|
286 |
|
287 // skip past the coding error |
|
288 inbuf.position(inbuf.position() + result.length()); |
|
289 |
|
290 // undo the flip() to prepare the output buffer |
|
291 // for more translation |
|
292 dest.position(dest.limit()); |
|
293 dest.limit(dest.capacity()); |
|
294 dest.put((char)0xfffd); // backward compatible |
|
295 } else { |
|
296 throw new AssertionError(result); |
|
297 } |
|
298 } |
|
299 // unreached |
|
300 } |
|
301 |
|
302 public CharsetDecoder getDecoder(String encodingName, boolean ignoreEncodingErrors) { |
|
303 Charset cs = (this.charset == null) |
|
304 ? Charset.forName(encodingName) |
|
305 : this.charset; |
|
306 CharsetDecoder decoder = cs.newDecoder(); |
|
307 |
|
308 CodingErrorAction action; |
|
309 if (ignoreEncodingErrors) |
|
310 action = CodingErrorAction.REPLACE; |
|
311 else |
|
312 action = CodingErrorAction.REPORT; |
|
313 |
|
314 return decoder |
|
315 .onMalformedInput(action) |
|
316 .onUnmappableCharacter(action); |
|
317 } |
|
318 // </editor-fold> |
|
319 |
|
320 // <editor-fold defaultstate="collapsed" desc="ByteBuffers"> |
|
321 /** |
|
322 * Make a byte buffer from an input stream. |
|
323 * @param in the stream |
|
324 * @return a byte buffer containing the contents of the stream |
|
325 * @throws IOException if an error occurred while reading the stream |
|
326 */ |
|
327 @SuppressWarnings("cast") |
|
328 public ByteBuffer makeByteBuffer(InputStream in) |
|
329 throws IOException { |
|
330 int limit = in.available(); |
|
331 if (limit < 1024) limit = 1024; |
|
332 ByteBuffer result = byteBufferCache.get(limit); |
|
333 int position = 0; |
|
334 while (in.available() != 0) { |
|
335 if (position >= limit) |
|
336 // expand buffer |
|
337 result = ByteBuffer. |
|
338 allocate(limit <<= 1). |
|
339 put((ByteBuffer)result.flip()); |
|
340 int count = in.read(result.array(), |
|
341 position, |
|
342 limit - position); |
|
343 if (count < 0) break; |
|
344 result.position(position += count); |
|
345 } |
|
346 return (ByteBuffer)result.flip(); |
|
347 } |
|
348 |
|
349 public void recycleByteBuffer(ByteBuffer bb) { |
|
350 byteBufferCache.put(bb); |
|
351 } |
|
352 |
|
353 /** |
|
354 * A single-element cache of direct byte buffers. |
|
355 */ |
|
356 @SuppressWarnings("cast") |
|
357 private static class ByteBufferCache { |
|
358 private ByteBuffer cached; |
|
359 ByteBuffer get(int capacity) { |
|
360 if (capacity < 20480) capacity = 20480; |
|
361 ByteBuffer result = |
|
362 (cached != null && cached.capacity() >= capacity) |
|
363 ? (ByteBuffer)cached.clear() |
|
364 : ByteBuffer.allocate(capacity + capacity>>1); |
|
365 cached = null; |
|
366 return result; |
|
367 } |
|
368 void put(ByteBuffer x) { |
|
369 cached = x; |
|
370 } |
|
371 } |
|
372 |
|
373 private final ByteBufferCache byteBufferCache; |
|
374 // </editor-fold> |
|
375 |
|
376 // <editor-fold defaultstate="collapsed" desc="Content cache"> |
|
377 public CharBuffer getCachedContent(JavaFileObject file) { |
|
378 ContentCacheEntry e = contentCache.get(file); |
|
379 if (e == null) |
|
380 return null; |
|
381 |
|
382 if (!e.isValid(file)) { |
|
383 contentCache.remove(file); |
|
384 return null; |
|
385 } |
|
386 |
|
387 return e.getValue(); |
|
388 } |
|
389 |
|
390 public void cache(JavaFileObject file, CharBuffer cb) { |
|
391 contentCache.put(file, new ContentCacheEntry(file, cb)); |
|
392 } |
|
393 |
|
394 public void flushCache(JavaFileObject file) { |
|
395 contentCache.remove(file); |
|
396 } |
|
397 |
|
398 protected final Map<JavaFileObject, ContentCacheEntry> contentCache = new HashMap<>(); |
|
399 |
|
400 protected static class ContentCacheEntry { |
|
401 final long timestamp; |
|
402 final SoftReference<CharBuffer> ref; |
|
403 |
|
404 ContentCacheEntry(JavaFileObject file, CharBuffer cb) { |
|
405 this.timestamp = file.getLastModified(); |
|
406 this.ref = new SoftReference<>(cb); |
|
407 } |
|
408 |
|
409 boolean isValid(JavaFileObject file) { |
|
410 return timestamp == file.getLastModified(); |
|
411 } |
|
412 |
|
413 CharBuffer getValue() { |
|
414 return ref.get(); |
|
415 } |
|
416 } |
|
417 // </editor-fold> |
|
418 |
|
419 public static Kind getKind(Path path) { |
|
420 return getKind(path.getFileName().toString()); |
|
421 } |
|
422 |
|
423 public static Kind getKind(String name) { |
|
424 if (name.endsWith(Kind.CLASS.extension)) |
|
425 return Kind.CLASS; |
|
426 else if (name.endsWith(Kind.SOURCE.extension)) |
|
427 return Kind.SOURCE; |
|
428 else if (name.endsWith(Kind.HTML.extension)) |
|
429 return Kind.HTML; |
|
430 else |
|
431 return Kind.OTHER; |
|
432 } |
|
433 |
|
434 protected static <T> T nullCheck(T o) { |
|
435 return Objects.requireNonNull(o); |
|
436 } |
|
437 |
|
438 protected static <T> Collection<T> nullCheck(Collection<T> it) { |
|
439 for (T t : it) |
|
440 Objects.requireNonNull(t); |
|
441 return it; |
|
442 } |
|
443 } |
|