BaseFileManager.java revision 3240:656b3aa4229f
1/*
2 * Copyright (c) 2009, 2016, 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
26package com.sun.tools.javac.file;
27
28import java.io.ByteArrayOutputStream;
29import java.io.IOException;
30import java.io.InputStream;
31import java.io.OutputStreamWriter;
32import java.lang.ref.SoftReference;
33import java.lang.reflect.Constructor;
34import java.net.URL;
35import java.net.URLClassLoader;
36import java.nio.ByteBuffer;
37import java.nio.CharBuffer;
38import java.nio.charset.Charset;
39import java.nio.charset.CharsetDecoder;
40import java.nio.charset.CoderResult;
41import java.nio.charset.CodingErrorAction;
42import java.nio.charset.IllegalCharsetNameException;
43import java.nio.charset.UnsupportedCharsetException;
44import java.nio.file.Path;
45import java.util.Collection;
46import java.util.HashMap;
47import java.util.Iterator;
48import java.util.Map;
49import java.util.Objects;
50import java.util.Set;
51
52import javax.tools.JavaFileManager;
53import javax.tools.JavaFileObject;
54import javax.tools.JavaFileObject.Kind;
55
56import com.sun.tools.javac.code.Lint;
57import com.sun.tools.javac.code.Source;
58import com.sun.tools.javac.main.Option;
59import com.sun.tools.javac.main.OptionHelper;
60import com.sun.tools.javac.main.OptionHelper.GrumpyHelper;
61import com.sun.tools.javac.util.Context;
62import com.sun.tools.javac.util.DefinedBy;
63import com.sun.tools.javac.util.DefinedBy.Api;
64import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
65import com.sun.tools.javac.util.Log;
66import com.sun.tools.javac.util.Options;
67
68/**
69 * Utility methods for building a filemanager.
70 * There are no references here to file-system specific objects such as
71 * java.io.File or java.nio.file.Path.
72 */
73public abstract class BaseFileManager implements JavaFileManager {
74    protected BaseFileManager(Charset charset) {
75        this.charset = charset;
76        byteBufferCache = new ByteBufferCache();
77        locations = createLocations();
78    }
79
80    /**
81     * Set the context for JavacPathFileManager.
82     * @param context the context containing items to be associated with the file manager
83     */
84    public void setContext(Context context) {
85        log = Log.instance(context);
86        options = Options.instance(context);
87        classLoaderClass = options.get("procloader");
88        locations.update(log, Lint.instance(context), FSInfo.instance(context));
89
90        // Setting this option is an indication that close() should defer actually closing
91        // the file manager until after a specified period of inactivity.
92        // This is to accomodate clients which save references to Symbols created for use
93        // within doclets or annotation processors, and which then attempt to use those
94        // references after the tool exits, having closed any internally managed file manager.
95        // Ideally, such clients should run the tool via the javax.tools API, providing their
96        // own file manager, which can be closed by the client when all use of that file
97        // manager is complete.
98        // If the option has a numeric value, it will be interpreted as the duration,
99        // in seconds, of the period of inactivity to wait for, before the file manager
100        // is actually closed.
101        // See also deferredClose().
102        String s = options.get("fileManager.deferClose");
103        if (s != null) {
104            try {
105                deferredCloseTimeout = (int) (Float.parseFloat(s) * 1000);
106            } catch (NumberFormatException e) {
107                deferredCloseTimeout = 60 * 1000;  // default: one minute, in millis
108            }
109        }
110    }
111
112    protected Locations createLocations() {
113        return new Locations();
114    }
115
116    /**
117     * The log to be used for error reporting.
118     */
119    public Log log;
120
121    /**
122     * User provided charset (through javax.tools).
123     */
124    protected Charset charset;
125
126    protected Options options;
127
128    protected String classLoaderClass;
129
130    protected Locations locations;
131
132    /**
133     * A flag for clients to use to indicate that this file manager should
134     * be closed when it is no longer required.
135     */
136    public boolean autoClose;
137
138    /**
139     * Wait for a period of inactivity before calling close().
140     * The length of the period of inactivity is given by {@code deferredCloseTimeout}
141     */
142    protected void deferredClose() {
143        Thread t = new Thread(getClass().getName() + " DeferredClose") {
144            @Override
145            public void run() {
146                try {
147                    synchronized (BaseFileManager.this) {
148                        long now = System.currentTimeMillis();
149                        while (now < lastUsedTime + deferredCloseTimeout) {
150                            BaseFileManager.this.wait(lastUsedTime + deferredCloseTimeout - now);
151                            now = System.currentTimeMillis();
152                        }
153                        deferredCloseTimeout = 0;
154                        close();
155                    }
156                } catch (InterruptedException e) {
157                } catch (IOException e) {
158                }
159            }
160        };
161        t.setDaemon(true);
162        t.start();
163    }
164
165    synchronized void updateLastUsedTime() {
166        if (deferredCloseTimeout > 0) { // avoid updating the time unnecessarily
167            lastUsedTime = System.currentTimeMillis();
168        }
169    }
170
171    private long lastUsedTime = System.currentTimeMillis();
172    protected long deferredCloseTimeout = 0;
173
174    protected Source getSource() {
175        String sourceName = options.get(Option.SOURCE);
176        Source source = null;
177        if (sourceName != null)
178            source = Source.lookup(sourceName);
179        return (source != null ? source : Source.DEFAULT);
180    }
181
182    protected ClassLoader getClassLoader(URL[] urls) {
183        ClassLoader thisClassLoader = getClass().getClassLoader();
184
185        // Allow the following to specify a closeable classloader
186        // other than URLClassLoader.
187
188        // 1: Allow client to specify the class to use via hidden option
189        if (classLoaderClass != null) {
190            try {
191                Class<? extends ClassLoader> loader =
192                        Class.forName(classLoaderClass).asSubclass(ClassLoader.class);
193                Class<?>[] constrArgTypes = { URL[].class, ClassLoader.class };
194                Constructor<? extends ClassLoader> constr = loader.getConstructor(constrArgTypes);
195                return constr.newInstance(urls, thisClassLoader);
196            } catch (ReflectiveOperationException t) {
197                // ignore errors loading user-provided class loader, fall through
198            }
199        }
200        return new URLClassLoader(urls, thisClassLoader);
201    }
202
203    public boolean isDefaultBootClassPath() {
204        return locations.isDefaultBootClassPath();
205    }
206
207    // <editor-fold defaultstate="collapsed" desc="Option handling">
208    @Override @DefinedBy(Api.COMPILER)
209    public boolean handleOption(String current, Iterator<String> remaining) {
210        OptionHelper helper = new GrumpyHelper(log) {
211            @Override
212            public String get(Option option) {
213                return options.get(option.getText());
214            }
215
216            @Override
217            public void put(String name, String value) {
218                options.put(name, value);
219            }
220
221            @Override
222            public void remove(String name) {
223                options.remove(name);
224            }
225
226            @Override
227            public boolean handleFileManagerOption(Option option, String value) {
228                return handleOption(option, value);
229            }
230        };
231
232        for (Option o: javacFileManagerOptions) {
233            if (o.matches(current))  {
234                if (o.hasArg()) {
235                    if (remaining.hasNext()) {
236                        if (!o.process(helper, current, remaining.next()))
237                            return true;
238                    }
239                } else {
240                    if (!o.process(helper, current))
241                        return true;
242                }
243                // operand missing, or process returned true
244                throw new IllegalArgumentException(current);
245            }
246        }
247
248        return false;
249    }
250    // where
251        private static final Set<Option> javacFileManagerOptions =
252            Option.getJavacFileManagerOptions();
253
254    @Override @DefinedBy(Api.COMPILER)
255    public int isSupportedOption(String option) {
256        for (Option o : javacFileManagerOptions) {
257            if (o.matches(option))
258                return o.hasArg() ? 1 : 0;
259        }
260        return -1;
261    }
262
263    /**
264     * Common back end for OptionHelper handleFileManagerOption.
265     * @param option the option whose value to be set
266     * @param value the value for the option
267     * @return true if successful, and false otherwise
268     */
269    public boolean handleOption(Option option, String value) {
270        return locations.handleOption(option, value);
271    }
272
273    /**
274     * Call handleOption for collection of options and corresponding values.
275     * @param map a collection of options and corresponding values
276     * @return true if all the calls are successful
277     */
278    public boolean handleOptions(Map<Option, String> map) {
279        boolean ok = true;
280        for (Map.Entry<Option, String> e: map.entrySet())
281            ok = ok & handleOption(e.getKey(), e.getValue());
282        return ok;
283    }
284
285    // </editor-fold>
286
287    // <editor-fold defaultstate="collapsed" desc="Encoding">
288    private String defaultEncodingName;
289    private String getDefaultEncodingName() {
290        if (defaultEncodingName == null) {
291            defaultEncodingName =
292                new OutputStreamWriter(new ByteArrayOutputStream()).getEncoding();
293        }
294        return defaultEncodingName;
295    }
296
297    public String getEncodingName() {
298        String encName = options.get(Option.ENCODING);
299        if (encName == null)
300            return getDefaultEncodingName();
301        else
302            return encName;
303    }
304
305    @SuppressWarnings("cast")
306    public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) {
307        String encodingName = getEncodingName();
308        CharsetDecoder decoder;
309        try {
310            decoder = getDecoder(encodingName, ignoreEncodingErrors);
311        } catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
312            log.error("unsupported.encoding", encodingName);
313            return (CharBuffer)CharBuffer.allocate(1).flip();
314        }
315
316        // slightly overestimate the buffer size to avoid reallocation.
317        float factor =
318            decoder.averageCharsPerByte() * 0.8f +
319            decoder.maxCharsPerByte() * 0.2f;
320        CharBuffer dest = CharBuffer.
321            allocate(10 + (int)(inbuf.remaining()*factor));
322
323        while (true) {
324            CoderResult result = decoder.decode(inbuf, dest, true);
325            dest.flip();
326
327            if (result.isUnderflow()) { // done reading
328                // make sure there is at least one extra character
329                if (dest.limit() == dest.capacity()) {
330                    dest = CharBuffer.allocate(dest.capacity()+1).put(dest);
331                    dest.flip();
332                }
333                return dest;
334            } else if (result.isOverflow()) { // buffer too small; expand
335                int newCapacity =
336                    10 + dest.capacity() +
337                    (int)(inbuf.remaining()*decoder.maxCharsPerByte());
338                dest = CharBuffer.allocate(newCapacity).put(dest);
339            } else if (result.isMalformed() || result.isUnmappable()) {
340                // bad character in input
341
342                log.error(new SimpleDiagnosticPosition(dest.limit()),
343                          "illegal.char.for.encoding",
344                          charset == null ? encodingName : charset.name());
345
346                // skip past the coding error
347                inbuf.position(inbuf.position() + result.length());
348
349                // undo the flip() to prepare the output buffer
350                // for more translation
351                dest.position(dest.limit());
352                dest.limit(dest.capacity());
353                dest.put((char)0xfffd); // backward compatible
354            } else {
355                throw new AssertionError(result);
356            }
357        }
358        // unreached
359    }
360
361    public CharsetDecoder getDecoder(String encodingName, boolean ignoreEncodingErrors) {
362        Charset cs = (this.charset == null)
363            ? Charset.forName(encodingName)
364            : this.charset;
365        CharsetDecoder decoder = cs.newDecoder();
366
367        CodingErrorAction action;
368        if (ignoreEncodingErrors)
369            action = CodingErrorAction.REPLACE;
370        else
371            action = CodingErrorAction.REPORT;
372
373        return decoder
374            .onMalformedInput(action)
375            .onUnmappableCharacter(action);
376    }
377    // </editor-fold>
378
379    // <editor-fold defaultstate="collapsed" desc="ByteBuffers">
380    /**
381     * Make a byte buffer from an input stream.
382     * @param in the stream
383     * @return a byte buffer containing the contents of the stream
384     * @throws IOException if an error occurred while reading the stream
385     */
386    @SuppressWarnings("cast")
387    public ByteBuffer makeByteBuffer(InputStream in)
388        throws IOException {
389        int limit = in.available();
390        if (limit < 1024) limit = 1024;
391        ByteBuffer result = byteBufferCache.get(limit);
392        int position = 0;
393        while (in.available() != 0) {
394            if (position >= limit)
395                // expand buffer
396                result = ByteBuffer.
397                    allocate(limit <<= 1).
398                    put((ByteBuffer)result.flip());
399            int count = in.read(result.array(),
400                position,
401                limit - position);
402            if (count < 0) break;
403            result.position(position += count);
404        }
405        return (ByteBuffer)result.flip();
406    }
407
408    public void recycleByteBuffer(ByteBuffer bb) {
409        byteBufferCache.put(bb);
410    }
411
412    /**
413     * A single-element cache of direct byte buffers.
414     */
415    @SuppressWarnings("cast")
416    private static class ByteBufferCache {
417        private ByteBuffer cached;
418        ByteBuffer get(int capacity) {
419            if (capacity < 20480) capacity = 20480;
420            ByteBuffer result =
421                (cached != null && cached.capacity() >= capacity)
422                ? (ByteBuffer)cached.clear()
423                : ByteBuffer.allocate(capacity + capacity>>1);
424            cached = null;
425            return result;
426        }
427        void put(ByteBuffer x) {
428            cached = x;
429        }
430    }
431
432    private final ByteBufferCache byteBufferCache;
433    // </editor-fold>
434
435    // <editor-fold defaultstate="collapsed" desc="Content cache">
436    public CharBuffer getCachedContent(JavaFileObject file) {
437        ContentCacheEntry e = contentCache.get(file);
438        if (e == null)
439            return null;
440
441        if (!e.isValid(file)) {
442            contentCache.remove(file);
443            return null;
444        }
445
446        return e.getValue();
447    }
448
449    public void cache(JavaFileObject file, CharBuffer cb) {
450        contentCache.put(file, new ContentCacheEntry(file, cb));
451    }
452
453    public void flushCache(JavaFileObject file) {
454        contentCache.remove(file);
455    }
456
457    protected final Map<JavaFileObject, ContentCacheEntry> contentCache = new HashMap<>();
458
459    protected static class ContentCacheEntry {
460        final long timestamp;
461        final SoftReference<CharBuffer> ref;
462
463        ContentCacheEntry(JavaFileObject file, CharBuffer cb) {
464            this.timestamp = file.getLastModified();
465            this.ref = new SoftReference<>(cb);
466        }
467
468        boolean isValid(JavaFileObject file) {
469            return timestamp == file.getLastModified();
470        }
471
472        CharBuffer getValue() {
473            return ref.get();
474        }
475    }
476    // </editor-fold>
477
478    public static Kind getKind(Path path) {
479        return getKind(path.getFileName().toString());
480    }
481
482    public static Kind getKind(String name) {
483        if (name.endsWith(Kind.CLASS.extension))
484            return Kind.CLASS;
485        else if (name.endsWith(Kind.SOURCE.extension))
486            return Kind.SOURCE;
487        else if (name.endsWith(Kind.HTML.extension))
488            return Kind.HTML;
489        else
490            return Kind.OTHER;
491    }
492
493    protected static <T> T nullCheck(T o) {
494        return Objects.requireNonNull(o);
495    }
496
497    protected static <T> Collection<T> nullCheck(Collection<T> it) {
498        for (T t : it)
499            Objects.requireNonNull(t);
500        return it;
501    }
502}
503