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