View Javadoc
1   /*
2    * Copyright (c) 2009, 2013, 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.Closeable;
30  import java.io.IOException;
31  import java.io.InputStream;
32  import java.io.OutputStreamWriter;
33  import java.lang.ref.SoftReference;
34  import java.lang.reflect.Constructor;
35  import java.net.URL;
36  import java.net.URLClassLoader;
37  import java.nio.ByteBuffer;
38  import java.nio.CharBuffer;
39  import java.nio.charset.Charset;
40  import java.nio.charset.CharsetDecoder;
41  import java.nio.charset.CoderResult;
42  import java.nio.charset.CodingErrorAction;
43  import java.nio.charset.IllegalCharsetNameException;
44  import java.nio.charset.UnsupportedCharsetException;
45  import java.util.Collection;
46  import java.util.HashMap;
47  import java.util.Iterator;
48  import java.util.Map;
49  import java.util.Set;
50  import javax.tools.JavaFileObject;
51  import javax.tools.JavaFileObject.Kind;
52  
53  import com.sun.tools.javac.code.Lint;
54  import com.sun.tools.javac.code.Source;
55  import com.sun.tools.javac.file.FSInfo;
56  import com.sun.tools.javac.file.Locations;
57  import com.sun.tools.javac.main.Option;
58  import com.sun.tools.javac.main.OptionHelper;
59  import com.sun.tools.javac.main.OptionHelper.GrumpyHelper;
60  import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
61  
62  /**
63   * Utility methods for building a filemanager.
64   * There are no references here to file-system specific objects such as
65   * java.io.File or java.nio.file.Path.
66   */
67  public abstract class BaseFileManager {
68      protected BaseFileManager(Charset charset) {
69          this.charset = charset;
70          byteBufferCache = new ByteBufferCache();
71          locations = createLocations();
72      }
73  
74      /**
75       * Set the context for JavacPathFileManager.
76       */
77      public void setContext(Context context) {
78          log = Log.instance(context);
79          options = Options.instance(context);
80          classLoaderClass = options.get("procloader");
81          locations.update(log, options, Lint.instance(context), FSInfo.instance(context));
82      }
83  
84      protected Locations createLocations() {
85          return new Locations();
86      }
87  
88      /**
89       * The log to be used for error reporting.
90       */
91      public Log log;
92  
93      /**
94       * User provided charset (through javax.tools).
95       */
96      protected Charset charset;
97  
98      protected Options options;
99  
100     protected String classLoaderClass;
101 
102     protected Locations locations;
103 
104     protected Source getSource() {
105         String sourceName = options.get(Option.SOURCE);
106         Source source = null;
107         if (sourceName != null)
108             source = Source.lookup(sourceName);
109         return (source != null ? source : Source.DEFAULT);
110     }
111 
112     protected ClassLoader getClassLoader(URL[] urls) {
113         ClassLoader thisClassLoader = getClass().getClassLoader();
114 
115         // Allow the following to specify a closeable classloader
116         // other than URLClassLoader.
117 
118         // 1: Allow client to specify the class to use via hidden option
119         if (classLoaderClass != null) {
120             try {
121                 Class<? extends ClassLoader> loader =
122                         Class.forName(classLoaderClass).asSubclass(ClassLoader.class);
123                 Class<?>[] constrArgTypes = { URL[].class, ClassLoader.class };
124                 Constructor<? extends ClassLoader> constr = loader.getConstructor(constrArgTypes);
125                 return constr.newInstance(new Object[] { urls, thisClassLoader });
126             } catch (Throwable t) {
127                 // ignore errors loading user-provided class loader, fall through
128             }
129         }
130         return new URLClassLoader(urls, thisClassLoader);
131     }
132 
133     // <editor-fold defaultstate="collapsed" desc="Option handling">
134     public boolean handleOption(String current, Iterator<String> remaining) {
135         OptionHelper helper = new GrumpyHelper(log) {
136             @Override
137             public String get(Option option) {
138                 return options.get(option.getText());
139             }
140 
141             @Override
142             public void put(String name, String value) {
143                 options.put(name, value);
144             }
145 
146             @Override
147             public void remove(String name) {
148                 options.remove(name);
149             }
150         };
151         for (Option o: javacFileManagerOptions) {
152             if (o.matches(current))  {
153                 if (o.hasArg()) {
154                     if (remaining.hasNext()) {
155                         if (!o.process(helper, current, remaining.next()))
156                             return true;
157                     }
158                 } else {
159                     if (!o.process(helper, current))
160                         return true;
161                 }
162                 // operand missing, or process returned false
163                 throw new IllegalArgumentException(current);
164             }
165         }
166 
167         return false;
168     }
169     // where
170         private static final Set<Option> javacFileManagerOptions =
171             Option.getJavacFileManagerOptions();
172 
173     public int isSupportedOption(String option) {
174         for (Option o : javacFileManagerOptions) {
175             if (o.matches(option))
176                 return o.hasArg() ? 1 : 0;
177         }
178         return -1;
179     }
180 
181     public abstract boolean isDefaultBootClassPath();
182 
183     // </editor-fold>
184 
185     // <editor-fold defaultstate="collapsed" desc="Encoding">
186     private String defaultEncodingName;
187     private String getDefaultEncodingName() {
188         if (defaultEncodingName == null) {
189             defaultEncodingName =
190                 new OutputStreamWriter(new ByteArrayOutputStream()).getEncoding();
191         }
192         return defaultEncodingName;
193     }
194 
195     public String getEncodingName() {
196         String encName = options.get(Option.ENCODING);
197         if (encName == null)
198             return getDefaultEncodingName();
199         else
200             return encName;
201     }
202 
203     public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) {
204         String encodingName = getEncodingName();
205         CharsetDecoder decoder;
206         try {
207             decoder = getDecoder(encodingName, ignoreEncodingErrors);
208         } catch (IllegalCharsetNameException e) {
209             log.error("unsupported.encoding", encodingName);
210             return (CharBuffer)CharBuffer.allocate(1).flip();
211         } catch (UnsupportedCharsetException e) {
212             log.error("unsupported.encoding", encodingName);
213             return (CharBuffer)CharBuffer.allocate(1).flip();
214         }
215 
216         // slightly overestimate the buffer size to avoid reallocation.
217         float factor =
218             decoder.averageCharsPerByte() * 0.8f +
219             decoder.maxCharsPerByte() * 0.2f;
220         CharBuffer dest = CharBuffer.
221             allocate(10 + (int)(inbuf.remaining()*factor));
222 
223         while (true) {
224             CoderResult result = decoder.decode(inbuf, dest, true);
225             dest.flip();
226 
227             if (result.isUnderflow()) { // done reading
228                 // make sure there is at least one extra character
229                 if (dest.limit() == dest.capacity()) {
230                     dest = CharBuffer.allocate(dest.capacity()+1).put(dest);
231                     dest.flip();
232                 }
233                 return dest;
234             } else if (result.isOverflow()) { // buffer too small; expand
235                 int newCapacity =
236                     10 + dest.capacity() +
237                     (int)(inbuf.remaining()*decoder.maxCharsPerByte());
238                 dest = CharBuffer.allocate(newCapacity).put(dest);
239             } else if (result.isMalformed() || result.isUnmappable()) {
240                 // bad character in input
241 
242                 // report coding error (warn only pre 1.5)
243                 if (!getSource().allowEncodingErrors()) {
244                     log.error(new SimpleDiagnosticPosition(dest.limit()),
245                               "illegal.char.for.encoding",
246                               charset == null ? encodingName : charset.name());
247                 } else {
248                     log.warning(new SimpleDiagnosticPosition(dest.limit()),
249                                 "illegal.char.for.encoding",
250                                 charset == null ? encodingName : charset.name());
251                 }
252 
253                 // skip past the coding error
254                 inbuf.position(inbuf.position() + result.length());
255 
256                 // undo the flip() to prepare the output buffer
257                 // for more translation
258                 dest.position(dest.limit());
259                 dest.limit(dest.capacity());
260                 dest.put((char)0xfffd); // backward compatible
261             } else {
262                 throw new AssertionError(result);
263             }
264         }
265         // unreached
266     }
267 
268     public CharsetDecoder getDecoder(String encodingName, boolean ignoreEncodingErrors) {
269         Charset cs = (this.charset == null)
270             ? Charset.forName(encodingName)
271             : this.charset;
272         CharsetDecoder decoder = cs.newDecoder();
273 
274         CodingErrorAction action;
275         if (ignoreEncodingErrors)
276             action = CodingErrorAction.REPLACE;
277         else
278             action = CodingErrorAction.REPORT;
279 
280         return decoder
281             .onMalformedInput(action)
282             .onUnmappableCharacter(action);
283     }
284     // </editor-fold>
285 
286     // <editor-fold defaultstate="collapsed" desc="ByteBuffers">
287     /**
288      * Make a byte buffer from an input stream.
289      */
290     public ByteBuffer makeByteBuffer(InputStream in)
291         throws IOException {
292         int limit = in.available();
293         if (limit < 1024) limit = 1024;
294         ByteBuffer result = byteBufferCache.get(limit);
295         int position = 0;
296         while (in.available() != 0) {
297             if (position >= limit)
298                 // expand buffer
299                 result = ByteBuffer.
300                     allocate(limit <<= 1).
301                     put((ByteBuffer)result.flip());
302             int count = in.read(result.array(),
303                 position,
304                 limit - position);
305             if (count < 0) break;
306             result.position(position += count);
307         }
308         return (ByteBuffer)result.flip();
309     }
310 
311     public void recycleByteBuffer(ByteBuffer bb) {
312         byteBufferCache.put(bb);
313     }
314 
315     /**
316      * A single-element cache of direct byte buffers.
317      */
318     private static class ByteBufferCache {
319         private ByteBuffer cached;
320         ByteBuffer get(int capacity) {
321             if (capacity < 20480) capacity = 20480;
322             ByteBuffer result =
323                 (cached != null && cached.capacity() >= capacity)
324                 ? (ByteBuffer)cached.clear()
325                 : ByteBuffer.allocate(capacity + capacity>>1);
326             cached = null;
327             return result;
328         }
329         void put(ByteBuffer x) {
330             cached = x;
331         }
332     }
333 
334     private final ByteBufferCache byteBufferCache;
335     // </editor-fold>
336 
337     // <editor-fold defaultstate="collapsed" desc="Content cache">
338     public CharBuffer getCachedContent(JavaFileObject file) {
339         ContentCacheEntry e = contentCache.get(file);
340         if (e == null)
341             return null;
342 
343         if (!e.isValid(file)) {
344             contentCache.remove(file);
345             return null;
346         }
347 
348         return e.getValue();
349     }
350 
351     public void cache(JavaFileObject file, CharBuffer cb) {
352         contentCache.put(file, new ContentCacheEntry(file, cb));
353     }
354 
355     public void flushCache(JavaFileObject file) {
356         contentCache.remove(file);
357     }
358 
359     protected final Map<JavaFileObject, ContentCacheEntry> contentCache
360             = new HashMap<JavaFileObject, ContentCacheEntry>();
361 
362     protected static class ContentCacheEntry {
363         final long timestamp;
364         final SoftReference<CharBuffer> ref;
365 
366         ContentCacheEntry(JavaFileObject file, CharBuffer cb) {
367             this.timestamp = file.getLastModified();
368             this.ref = new SoftReference<CharBuffer>(cb);
369         }
370 
371         boolean isValid(JavaFileObject file) {
372             return timestamp == file.getLastModified();
373         }
374 
375         CharBuffer getValue() {
376             return ref.get();
377         }
378     }
379     // </editor-fold>
380 
381     public static Kind getKind(String name) {
382         if (name.endsWith(Kind.CLASS.extension))
383             return Kind.CLASS;
384         else if (name.endsWith(Kind.SOURCE.extension))
385             return Kind.SOURCE;
386         else if (name.endsWith(Kind.HTML.extension))
387             return Kind.HTML;
388         else
389             return Kind.OTHER;
390     }
391 
392     protected static <T> T nullCheck(T o) {
393         o.getClass(); // null check
394         return o;
395     }
396 
397     protected static <T> Collection<T> nullCheck(Collection<T> it) {
398         for (T t : it)
399             t.getClass(); // null check
400         return it;
401     }
402 }