langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/BaseFileManager.java
changeset 29780 8f8e54a1fa20
parent 29291 076c277565f7
child 35807 2eb1d877da0f
equal deleted inserted replaced
29779:81572cfb60a0 29780:8f8e54a1fa20
       
     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.file;
       
    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.Context;
       
    64 import com.sun.tools.javac.util.DefinedBy;
       
    65 import com.sun.tools.javac.util.DefinedBy.Api;
       
    66 import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
       
    67 import com.sun.tools.javac.util.Log;
       
    68 import com.sun.tools.javac.util.Options;
       
    69 
       
    70 /**
       
    71  * Utility methods for building a filemanager.
       
    72  * There are no references here to file-system specific objects such as
       
    73  * java.io.File or java.nio.file.Path.
       
    74  */
       
    75 public abstract class BaseFileManager implements JavaFileManager {
       
    76     protected BaseFileManager(Charset charset) {
       
    77         this.charset = charset;
       
    78         byteBufferCache = new ByteBufferCache();
       
    79         locations = createLocations();
       
    80     }
       
    81 
       
    82     /**
       
    83      * Set the context for JavacPathFileManager.
       
    84      * @param context the context containing items to be associated with the file manager
       
    85      */
       
    86     public void setContext(Context context) {
       
    87         log = Log.instance(context);
       
    88         options = Options.instance(context);
       
    89         classLoaderClass = options.get("procloader");
       
    90         locations.update(log, Lint.instance(context), FSInfo.instance(context));
       
    91     }
       
    92 
       
    93     protected Locations createLocations() {
       
    94         return new Locations();
       
    95     }
       
    96 
       
    97     /**
       
    98      * The log to be used for error reporting.
       
    99      */
       
   100     public Log log;
       
   101 
       
   102     /**
       
   103      * User provided charset (through javax.tools).
       
   104      */
       
   105     protected Charset charset;
       
   106 
       
   107     protected Options options;
       
   108 
       
   109     protected String classLoaderClass;
       
   110 
       
   111     protected Locations locations;
       
   112 
       
   113     /**
       
   114      * A flag for clients to use to indicate that this file manager should
       
   115      * be closed when it is no longer required.
       
   116      */
       
   117     public boolean autoClose;
       
   118 
       
   119     protected Source getSource() {
       
   120         String sourceName = options.get(Option.SOURCE);
       
   121         Source source = null;
       
   122         if (sourceName != null)
       
   123             source = Source.lookup(sourceName);
       
   124         return (source != null ? source : Source.DEFAULT);
       
   125     }
       
   126 
       
   127     protected ClassLoader getClassLoader(URL[] urls) {
       
   128         ClassLoader thisClassLoader = getClass().getClassLoader();
       
   129 
       
   130         // Allow the following to specify a closeable classloader
       
   131         // other than URLClassLoader.
       
   132 
       
   133         // 1: Allow client to specify the class to use via hidden option
       
   134         if (classLoaderClass != null) {
       
   135             try {
       
   136                 Class<? extends ClassLoader> loader =
       
   137                         Class.forName(classLoaderClass).asSubclass(ClassLoader.class);
       
   138                 Class<?>[] constrArgTypes = { URL[].class, ClassLoader.class };
       
   139                 Constructor<? extends ClassLoader> constr = loader.getConstructor(constrArgTypes);
       
   140                 return constr.newInstance(urls, thisClassLoader);
       
   141             } catch (ReflectiveOperationException t) {
       
   142                 // ignore errors loading user-provided class loader, fall through
       
   143             }
       
   144         }
       
   145         return new URLClassLoader(urls, thisClassLoader);
       
   146     }
       
   147 
       
   148     public boolean isDefaultBootClassPath() {
       
   149         return locations.isDefaultBootClassPath();
       
   150     }
       
   151 
       
   152     // <editor-fold defaultstate="collapsed" desc="Option handling">
       
   153     @Override @DefinedBy(Api.COMPILER)
       
   154     public boolean handleOption(String current, Iterator<String> remaining) {
       
   155         OptionHelper helper = new GrumpyHelper(log) {
       
   156             @Override
       
   157             public String get(Option option) {
       
   158                 return options.get(option.getText());
       
   159             }
       
   160 
       
   161             @Override
       
   162             public void put(String name, String value) {
       
   163                 options.put(name, value);
       
   164             }
       
   165 
       
   166             @Override
       
   167             public void remove(String name) {
       
   168                 options.remove(name);
       
   169             }
       
   170 
       
   171             @Override
       
   172             public boolean handleFileManagerOption(Option option, String value) {
       
   173                 return handleOption(option, value);
       
   174             }
       
   175         };
       
   176 
       
   177         for (Option o: javacFileManagerOptions) {
       
   178             if (o.matches(current))  {
       
   179                 if (o.hasArg()) {
       
   180                     if (remaining.hasNext()) {
       
   181                         if (!o.process(helper, current, remaining.next()))
       
   182                             return true;
       
   183                     }
       
   184                 } else {
       
   185                     if (!o.process(helper, current))
       
   186                         return true;
       
   187                 }
       
   188                 // operand missing, or process returned true
       
   189                 throw new IllegalArgumentException(current);
       
   190             }
       
   191         }
       
   192 
       
   193         return false;
       
   194     }
       
   195     // where
       
   196         private static final Set<Option> javacFileManagerOptions =
       
   197             Option.getJavacFileManagerOptions();
       
   198 
       
   199     @Override @DefinedBy(Api.COMPILER)
       
   200     public int isSupportedOption(String option) {
       
   201         for (Option o : javacFileManagerOptions) {
       
   202             if (o.matches(option))
       
   203                 return o.hasArg() ? 1 : 0;
       
   204         }
       
   205         return -1;
       
   206     }
       
   207 
       
   208     /**
       
   209      * Common back end for OptionHelper handleFileManagerOption.
       
   210      * @param option the option whose value to be set
       
   211      * @param value the value for the option
       
   212      * @return true if successful, and false otherwise
       
   213      */
       
   214     public boolean handleOption(Option option, String value) {
       
   215         return locations.handleOption(option, value);
       
   216     }
       
   217 
       
   218     /**
       
   219      * Call handleOption for collection of options and corresponding values.
       
   220      * @param map a collection of options and corresponding values
       
   221      * @return true if all the calls are successful
       
   222      */
       
   223     public boolean handleOptions(Map<Option, String> map) {
       
   224         boolean ok = true;
       
   225         for (Map.Entry<Option, String> e: map.entrySet())
       
   226             ok = ok & handleOption(e.getKey(), e.getValue());
       
   227         return ok;
       
   228     }
       
   229 
       
   230     // </editor-fold>
       
   231 
       
   232     // <editor-fold defaultstate="collapsed" desc="Encoding">
       
   233     private String defaultEncodingName;
       
   234     private String getDefaultEncodingName() {
       
   235         if (defaultEncodingName == null) {
       
   236             defaultEncodingName =
       
   237                 new OutputStreamWriter(new ByteArrayOutputStream()).getEncoding();
       
   238         }
       
   239         return defaultEncodingName;
       
   240     }
       
   241 
       
   242     public String getEncodingName() {
       
   243         String encName = options.get(Option.ENCODING);
       
   244         if (encName == null)
       
   245             return getDefaultEncodingName();
       
   246         else
       
   247             return encName;
       
   248     }
       
   249 
       
   250     @SuppressWarnings("cast")
       
   251     public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) {
       
   252         String encodingName = getEncodingName();
       
   253         CharsetDecoder decoder;
       
   254         try {
       
   255             decoder = getDecoder(encodingName, ignoreEncodingErrors);
       
   256         } catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
       
   257             log.error("unsupported.encoding", encodingName);
       
   258             return (CharBuffer)CharBuffer.allocate(1).flip();
       
   259         }
       
   260 
       
   261         // slightly overestimate the buffer size to avoid reallocation.
       
   262         float factor =
       
   263             decoder.averageCharsPerByte() * 0.8f +
       
   264             decoder.maxCharsPerByte() * 0.2f;
       
   265         CharBuffer dest = CharBuffer.
       
   266             allocate(10 + (int)(inbuf.remaining()*factor));
       
   267 
       
   268         while (true) {
       
   269             CoderResult result = decoder.decode(inbuf, dest, true);
       
   270             dest.flip();
       
   271 
       
   272             if (result.isUnderflow()) { // done reading
       
   273                 // make sure there is at least one extra character
       
   274                 if (dest.limit() == dest.capacity()) {
       
   275                     dest = CharBuffer.allocate(dest.capacity()+1).put(dest);
       
   276                     dest.flip();
       
   277                 }
       
   278                 return dest;
       
   279             } else if (result.isOverflow()) { // buffer too small; expand
       
   280                 int newCapacity =
       
   281                     10 + dest.capacity() +
       
   282                     (int)(inbuf.remaining()*decoder.maxCharsPerByte());
       
   283                 dest = CharBuffer.allocate(newCapacity).put(dest);
       
   284             } else if (result.isMalformed() || result.isUnmappable()) {
       
   285                 // bad character in input
       
   286 
       
   287                 log.error(new SimpleDiagnosticPosition(dest.limit()),
       
   288                           "illegal.char.for.encoding",
       
   289                           charset == null ? encodingName : charset.name());
       
   290 
       
   291                 // skip past the coding error
       
   292                 inbuf.position(inbuf.position() + result.length());
       
   293 
       
   294                 // undo the flip() to prepare the output buffer
       
   295                 // for more translation
       
   296                 dest.position(dest.limit());
       
   297                 dest.limit(dest.capacity());
       
   298                 dest.put((char)0xfffd); // backward compatible
       
   299             } else {
       
   300                 throw new AssertionError(result);
       
   301             }
       
   302         }
       
   303         // unreached
       
   304     }
       
   305 
       
   306     public CharsetDecoder getDecoder(String encodingName, boolean ignoreEncodingErrors) {
       
   307         Charset cs = (this.charset == null)
       
   308             ? Charset.forName(encodingName)
       
   309             : this.charset;
       
   310         CharsetDecoder decoder = cs.newDecoder();
       
   311 
       
   312         CodingErrorAction action;
       
   313         if (ignoreEncodingErrors)
       
   314             action = CodingErrorAction.REPLACE;
       
   315         else
       
   316             action = CodingErrorAction.REPORT;
       
   317 
       
   318         return decoder
       
   319             .onMalformedInput(action)
       
   320             .onUnmappableCharacter(action);
       
   321     }
       
   322     // </editor-fold>
       
   323 
       
   324     // <editor-fold defaultstate="collapsed" desc="ByteBuffers">
       
   325     /**
       
   326      * Make a byte buffer from an input stream.
       
   327      * @param in the stream
       
   328      * @return a byte buffer containing the contents of the stream
       
   329      * @throws IOException if an error occurred while reading the stream
       
   330      */
       
   331     @SuppressWarnings("cast")
       
   332     public ByteBuffer makeByteBuffer(InputStream in)
       
   333         throws IOException {
       
   334         int limit = in.available();
       
   335         if (limit < 1024) limit = 1024;
       
   336         ByteBuffer result = byteBufferCache.get(limit);
       
   337         int position = 0;
       
   338         while (in.available() != 0) {
       
   339             if (position >= limit)
       
   340                 // expand buffer
       
   341                 result = ByteBuffer.
       
   342                     allocate(limit <<= 1).
       
   343                     put((ByteBuffer)result.flip());
       
   344             int count = in.read(result.array(),
       
   345                 position,
       
   346                 limit - position);
       
   347             if (count < 0) break;
       
   348             result.position(position += count);
       
   349         }
       
   350         return (ByteBuffer)result.flip();
       
   351     }
       
   352 
       
   353     public void recycleByteBuffer(ByteBuffer bb) {
       
   354         byteBufferCache.put(bb);
       
   355     }
       
   356 
       
   357     /**
       
   358      * A single-element cache of direct byte buffers.
       
   359      */
       
   360     @SuppressWarnings("cast")
       
   361     private static class ByteBufferCache {
       
   362         private ByteBuffer cached;
       
   363         ByteBuffer get(int capacity) {
       
   364             if (capacity < 20480) capacity = 20480;
       
   365             ByteBuffer result =
       
   366                 (cached != null && cached.capacity() >= capacity)
       
   367                 ? (ByteBuffer)cached.clear()
       
   368                 : ByteBuffer.allocate(capacity + capacity>>1);
       
   369             cached = null;
       
   370             return result;
       
   371         }
       
   372         void put(ByteBuffer x) {
       
   373             cached = x;
       
   374         }
       
   375     }
       
   376 
       
   377     private final ByteBufferCache byteBufferCache;
       
   378     // </editor-fold>
       
   379 
       
   380     // <editor-fold defaultstate="collapsed" desc="Content cache">
       
   381     public CharBuffer getCachedContent(JavaFileObject file) {
       
   382         ContentCacheEntry e = contentCache.get(file);
       
   383         if (e == null)
       
   384             return null;
       
   385 
       
   386         if (!e.isValid(file)) {
       
   387             contentCache.remove(file);
       
   388             return null;
       
   389         }
       
   390 
       
   391         return e.getValue();
       
   392     }
       
   393 
       
   394     public void cache(JavaFileObject file, CharBuffer cb) {
       
   395         contentCache.put(file, new ContentCacheEntry(file, cb));
       
   396     }
       
   397 
       
   398     public void flushCache(JavaFileObject file) {
       
   399         contentCache.remove(file);
       
   400     }
       
   401 
       
   402     protected final Map<JavaFileObject, ContentCacheEntry> contentCache = new HashMap<>();
       
   403 
       
   404     protected static class ContentCacheEntry {
       
   405         final long timestamp;
       
   406         final SoftReference<CharBuffer> ref;
       
   407 
       
   408         ContentCacheEntry(JavaFileObject file, CharBuffer cb) {
       
   409             this.timestamp = file.getLastModified();
       
   410             this.ref = new SoftReference<>(cb);
       
   411         }
       
   412 
       
   413         boolean isValid(JavaFileObject file) {
       
   414             return timestamp == file.getLastModified();
       
   415         }
       
   416 
       
   417         CharBuffer getValue() {
       
   418             return ref.get();
       
   419         }
       
   420     }
       
   421     // </editor-fold>
       
   422 
       
   423     public static Kind getKind(Path path) {
       
   424         return getKind(path.getFileName().toString());
       
   425     }
       
   426 
       
   427     public static Kind getKind(String name) {
       
   428         if (name.endsWith(Kind.CLASS.extension))
       
   429             return Kind.CLASS;
       
   430         else if (name.endsWith(Kind.SOURCE.extension))
       
   431             return Kind.SOURCE;
       
   432         else if (name.endsWith(Kind.HTML.extension))
       
   433             return Kind.HTML;
       
   434         else
       
   435             return Kind.OTHER;
       
   436     }
       
   437 
       
   438     protected static <T> T nullCheck(T o) {
       
   439         return Objects.requireNonNull(o);
       
   440     }
       
   441 
       
   442     protected static <T> Collection<T> nullCheck(Collection<T> it) {
       
   443         for (T t : it)
       
   444             Objects.requireNonNull(t);
       
   445         return it;
       
   446     }
       
   447 }