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