449N/A/*
1093N/A * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
449N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
449N/A *
449N/A * This code is free software; you can redistribute it and/or modify it
449N/A * under the terms of the GNU General Public License version 2 only, as
553N/A * published by the Free Software Foundation. Oracle designates this
449N/A * particular file as subject to the "Classpath" exception as provided
553N/A * by Oracle in the LICENSE file that accompanied this code.
449N/A *
449N/A * This code is distributed in the hope that it will be useful, but WITHOUT
449N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
449N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
449N/A * version 2 for more details (a copy is included in the LICENSE file that
449N/A * accompanied this code).
449N/A *
449N/A * You should have received a copy of the GNU General Public License version
449N/A * 2 along with this work; if not, write to the Free Software Foundation,
449N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
449N/A *
553N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
553N/A * or visit www.oracle.com if you need additional information or have any
553N/A * questions.
449N/A */
449N/A
449N/Apackage com.sun.tools.javac.util;
449N/A
449N/Aimport com.sun.tools.javac.code.Source;
449N/Aimport com.sun.tools.javac.main.JavacOption;
449N/Aimport com.sun.tools.javac.main.OptionName;
449N/Aimport com.sun.tools.javac.main.RecognizedOptions;
449N/Aimport com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
449N/Aimport java.io.ByteArrayOutputStream;
449N/Aimport java.io.Closeable;
449N/Aimport java.io.IOException;
449N/Aimport java.io.InputStream;
449N/Aimport java.io.OutputStreamWriter;
449N/Aimport java.lang.ref.SoftReference;
449N/Aimport java.lang.reflect.Constructor;
449N/Aimport java.net.URL;
449N/Aimport java.net.URLClassLoader;
449N/Aimport java.nio.ByteBuffer;
449N/Aimport java.nio.CharBuffer;
449N/Aimport java.nio.charset.Charset;
449N/Aimport java.nio.charset.CharsetDecoder;
449N/Aimport java.nio.charset.CoderResult;
449N/Aimport java.nio.charset.CodingErrorAction;
449N/Aimport java.nio.charset.IllegalCharsetNameException;
449N/Aimport java.nio.charset.UnsupportedCharsetException;
449N/Aimport java.util.Collection;
449N/Aimport java.util.HashMap;
449N/Aimport java.util.Iterator;
449N/Aimport java.util.Map;
449N/Aimport javax.tools.JavaFileObject;
449N/Aimport javax.tools.JavaFileObject.Kind;
449N/A
449N/A/**
449N/A * Utility methods for building a filemanager.
449N/A * There are no references here to file-system specific objects such as
449N/A * java.io.File or java.nio.file.Path.
449N/A */
756N/Apublic abstract class BaseFileManager {
449N/A protected BaseFileManager(Charset charset) {
449N/A this.charset = charset;
449N/A byteBufferCache = new ByteBufferCache();
449N/A }
449N/A
449N/A /**
449N/A * Set the context for JavacPathFileManager.
449N/A */
449N/A protected void setContext(Context context) {
449N/A log = Log.instance(context);
449N/A options = Options.instance(context);
449N/A classLoaderClass = options.get("procloader");
449N/A }
449N/A
449N/A /**
449N/A * The log to be used for error reporting.
449N/A */
449N/A public Log log;
449N/A
449N/A /**
449N/A * User provided charset (through javax.tools).
449N/A */
449N/A protected Charset charset;
449N/A
449N/A protected Options options;
449N/A
449N/A protected String classLoaderClass;
449N/A
449N/A protected Source getSource() {
449N/A String sourceName = options.get(OptionName.SOURCE);
449N/A Source source = null;
449N/A if (sourceName != null)
449N/A source = Source.lookup(sourceName);
449N/A return (source != null ? source : Source.DEFAULT);
449N/A }
449N/A
449N/A protected ClassLoader getClassLoader(URL[] urls) {
449N/A ClassLoader thisClassLoader = getClass().getClassLoader();
449N/A
449N/A // Bug: 6558476
449N/A // Ideally, ClassLoader should be Closeable, but before JDK7 it is not.
449N/A // On older versions, try the following, to get a closeable classloader.
449N/A
449N/A // 1: Allow client to specify the class to use via hidden option
449N/A if (classLoaderClass != null) {
449N/A try {
449N/A Class<? extends ClassLoader> loader =
449N/A Class.forName(classLoaderClass).asSubclass(ClassLoader.class);
449N/A Class<?>[] constrArgTypes = { URL[].class, ClassLoader.class };
449N/A Constructor<? extends ClassLoader> constr = loader.getConstructor(constrArgTypes);
449N/A return constr.newInstance(new Object[] { urls, thisClassLoader });
449N/A } catch (Throwable t) {
449N/A // ignore errors loading user-provided class loader, fall through
449N/A }
449N/A }
449N/A
449N/A // 2: If URLClassLoader implements Closeable, use that.
449N/A if (Closeable.class.isAssignableFrom(URLClassLoader.class))
449N/A return new URLClassLoader(urls, thisClassLoader);
449N/A
449N/A // 3: Try using private reflection-based CloseableURLClassLoader
449N/A try {
449N/A return new CloseableURLClassLoader(urls, thisClassLoader);
449N/A } catch (Throwable t) {
449N/A // ignore errors loading workaround class loader, fall through
449N/A }
449N/A
449N/A // 4: If all else fails, use plain old standard URLClassLoader
449N/A return new URLClassLoader(urls, thisClassLoader);
449N/A }
449N/A
449N/A // <editor-fold defaultstate="collapsed" desc="Option handling">
449N/A public boolean handleOption(String current, Iterator<String> remaining) {
449N/A for (JavacOption o: javacFileManagerOptions) {
449N/A if (o.matches(current)) {
449N/A if (o.hasArg()) {
449N/A if (remaining.hasNext()) {
449N/A if (!o.process(options, current, remaining.next()))
449N/A return true;
449N/A }
449N/A } else {
449N/A if (!o.process(options, current))
449N/A return true;
449N/A }
449N/A // operand missing, or process returned false
449N/A throw new IllegalArgumentException(current);
449N/A }
449N/A }
449N/A
449N/A return false;
449N/A }
449N/A // where
449N/A private static JavacOption[] javacFileManagerOptions =
449N/A RecognizedOptions.getJavacFileManagerOptions(
449N/A new RecognizedOptions.GrumpyHelper());
449N/A
449N/A public int isSupportedOption(String option) {
449N/A for (JavacOption o : javacFileManagerOptions) {
449N/A if (o.matches(option))
449N/A return o.hasArg() ? 1 : 0;
449N/A }
449N/A return -1;
449N/A }
756N/A
756N/A public abstract boolean isDefaultBootClassPath();
756N/A
449N/A // </editor-fold>
449N/A
449N/A // <editor-fold defaultstate="collapsed" desc="Encoding">
449N/A private String defaultEncodingName;
449N/A private String getDefaultEncodingName() {
449N/A if (defaultEncodingName == null) {
449N/A defaultEncodingName =
449N/A new OutputStreamWriter(new ByteArrayOutputStream()).getEncoding();
449N/A }
449N/A return defaultEncodingName;
449N/A }
449N/A
449N/A public String getEncodingName() {
449N/A String encName = options.get(OptionName.ENCODING);
449N/A if (encName == null)
449N/A return getDefaultEncodingName();
449N/A else
449N/A return encName;
449N/A }
449N/A
449N/A public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) {
449N/A String encodingName = getEncodingName();
449N/A CharsetDecoder decoder;
449N/A try {
449N/A decoder = getDecoder(encodingName, ignoreEncodingErrors);
449N/A } catch (IllegalCharsetNameException e) {
449N/A log.error("unsupported.encoding", encodingName);
449N/A return (CharBuffer)CharBuffer.allocate(1).flip();
449N/A } catch (UnsupportedCharsetException e) {
449N/A log.error("unsupported.encoding", encodingName);
449N/A return (CharBuffer)CharBuffer.allocate(1).flip();
449N/A }
449N/A
449N/A // slightly overestimate the buffer size to avoid reallocation.
449N/A float factor =
449N/A decoder.averageCharsPerByte() * 0.8f +
449N/A decoder.maxCharsPerByte() * 0.2f;
449N/A CharBuffer dest = CharBuffer.
449N/A allocate(10 + (int)(inbuf.remaining()*factor));
449N/A
449N/A while (true) {
449N/A CoderResult result = decoder.decode(inbuf, dest, true);
449N/A dest.flip();
449N/A
449N/A if (result.isUnderflow()) { // done reading
449N/A // make sure there is at least one extra character
449N/A if (dest.limit() == dest.capacity()) {
449N/A dest = CharBuffer.allocate(dest.capacity()+1).put(dest);
449N/A dest.flip();
449N/A }
449N/A return dest;
449N/A } else if (result.isOverflow()) { // buffer too small; expand
449N/A int newCapacity =
449N/A 10 + dest.capacity() +
449N/A (int)(inbuf.remaining()*decoder.maxCharsPerByte());
449N/A dest = CharBuffer.allocate(newCapacity).put(dest);
449N/A } else if (result.isMalformed() || result.isUnmappable()) {
449N/A // bad character in input
449N/A
449N/A // report coding error (warn only pre 1.5)
449N/A if (!getSource().allowEncodingErrors()) {
449N/A log.error(new SimpleDiagnosticPosition(dest.limit()),
449N/A "illegal.char.for.encoding",
449N/A charset == null ? encodingName : charset.name());
449N/A } else {
449N/A log.warning(new SimpleDiagnosticPosition(dest.limit()),
449N/A "illegal.char.for.encoding",
449N/A charset == null ? encodingName : charset.name());
449N/A }
449N/A
449N/A // skip past the coding error
449N/A inbuf.position(inbuf.position() + result.length());
449N/A
449N/A // undo the flip() to prepare the output buffer
449N/A // for more translation
449N/A dest.position(dest.limit());
449N/A dest.limit(dest.capacity());
449N/A dest.put((char)0xfffd); // backward compatible
449N/A } else {
449N/A throw new AssertionError(result);
449N/A }
449N/A }
449N/A // unreached
449N/A }
449N/A
449N/A public CharsetDecoder getDecoder(String encodingName, boolean ignoreEncodingErrors) {
449N/A Charset cs = (this.charset == null)
449N/A ? Charset.forName(encodingName)
449N/A : this.charset;
449N/A CharsetDecoder decoder = cs.newDecoder();
449N/A
449N/A CodingErrorAction action;
449N/A if (ignoreEncodingErrors)
449N/A action = CodingErrorAction.REPLACE;
449N/A else
449N/A action = CodingErrorAction.REPORT;
449N/A
449N/A return decoder
449N/A .onMalformedInput(action)
449N/A .onUnmappableCharacter(action);
449N/A }
449N/A // </editor-fold>
449N/A
449N/A // <editor-fold defaultstate="collapsed" desc="ByteBuffers">
449N/A /**
449N/A * Make a byte buffer from an input stream.
449N/A */
449N/A public ByteBuffer makeByteBuffer(InputStream in)
449N/A throws IOException {
449N/A int limit = in.available();
449N/A if (limit < 1024) limit = 1024;
449N/A ByteBuffer result = byteBufferCache.get(limit);
449N/A int position = 0;
449N/A while (in.available() != 0) {
449N/A if (position >= limit)
449N/A // expand buffer
449N/A result = ByteBuffer.
449N/A allocate(limit <<= 1).
449N/A put((ByteBuffer)result.flip());
449N/A int count = in.read(result.array(),
449N/A position,
449N/A limit - position);
449N/A if (count < 0) break;
449N/A result.position(position += count);
449N/A }
449N/A return (ByteBuffer)result.flip();
449N/A }
449N/A
449N/A public void recycleByteBuffer(ByteBuffer bb) {
449N/A byteBufferCache.put(bb);
449N/A }
449N/A
449N/A /**
449N/A * A single-element cache of direct byte buffers.
449N/A */
449N/A private static class ByteBufferCache {
449N/A private ByteBuffer cached;
449N/A ByteBuffer get(int capacity) {
449N/A if (capacity < 20480) capacity = 20480;
449N/A ByteBuffer result =
449N/A (cached != null && cached.capacity() >= capacity)
449N/A ? (ByteBuffer)cached.clear()
449N/A : ByteBuffer.allocate(capacity + capacity>>1);
449N/A cached = null;
449N/A return result;
449N/A }
449N/A void put(ByteBuffer x) {
449N/A cached = x;
449N/A }
449N/A }
449N/A
449N/A private final ByteBufferCache byteBufferCache;
449N/A // </editor-fold>
449N/A
449N/A // <editor-fold defaultstate="collapsed" desc="Content cache">
449N/A public CharBuffer getCachedContent(JavaFileObject file) {
1093N/A ContentCacheEntry e = contentCache.get(file);
1093N/A if (e == null)
1093N/A return null;
1093N/A
1093N/A if (!e.isValid(file)) {
1093N/A contentCache.remove(file);
1093N/A return null;
1093N/A }
1093N/A
1093N/A return e.getValue();
449N/A }
449N/A
449N/A public void cache(JavaFileObject file, CharBuffer cb) {
1093N/A contentCache.put(file, new ContentCacheEntry(file, cb));
1093N/A }
1093N/A
1093N/A public void flushCache(JavaFileObject file) {
1093N/A contentCache.remove(file);
449N/A }
449N/A
1093N/A protected final Map<JavaFileObject, ContentCacheEntry> contentCache
1093N/A = new HashMap<JavaFileObject, ContentCacheEntry>();
1093N/A
1093N/A protected static class ContentCacheEntry {
1093N/A final long timestamp;
1093N/A final SoftReference<CharBuffer> ref;
1093N/A
1093N/A ContentCacheEntry(JavaFileObject file, CharBuffer cb) {
1093N/A this.timestamp = file.getLastModified();
1093N/A this.ref = new SoftReference<CharBuffer>(cb);
1093N/A }
1093N/A
1093N/A boolean isValid(JavaFileObject file) {
1093N/A return timestamp == file.getLastModified();
1093N/A }
1093N/A
1093N/A CharBuffer getValue() {
1093N/A return ref.get();
1093N/A }
1093N/A }
449N/A // </editor-fold>
449N/A
449N/A public static Kind getKind(String name) {
449N/A if (name.endsWith(Kind.CLASS.extension))
449N/A return Kind.CLASS;
449N/A else if (name.endsWith(Kind.SOURCE.extension))
449N/A return Kind.SOURCE;
449N/A else if (name.endsWith(Kind.HTML.extension))
449N/A return Kind.HTML;
449N/A else
449N/A return Kind.OTHER;
449N/A }
449N/A
449N/A protected static <T> T nullCheck(T o) {
449N/A o.getClass(); // null check
449N/A return o;
449N/A }
449N/A
449N/A protected static <T> Collection<T> nullCheck(Collection<T> it) {
449N/A for (T t : it)
449N/A t.getClass(); // null check
449N/A return it;
449N/A }
449N/A}