package com.sun.tools.javac.file;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.main.OptionHelper;
import com.sun.tools.javac.main.OptionHelper.GrumpyHelper;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.util.Abort;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.DefinedBy;
import com.sun.tools.javac.util.DefinedBy.Api;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Options;
public abstract class BaseFileManager implements JavaFileManager {
protected BaseFileManager(Charset charset) {
this.charset = charset;
byteBufferCache = new ByteBufferCache();
locations = createLocations();
}
public void setContext(Context context) {
log = Log.instance(context);
options = Options.instance(context);
classLoaderClass = options.get("procloader");
boolean warn = options.isLintSet("path");
locations.update(log, warn, FSInfo.instance(context));
String s = options.get("fileManager.deferClose");
if (s != null) {
try {
deferredCloseTimeout = (int) (Float.parseFloat(s) * 1000);
} catch (NumberFormatException e) {
deferredCloseTimeout = 60 * 1000;
}
}
}
protected Locations createLocations() {
return new Locations();
}
public Log log;
protected Charset charset;
protected Options options;
protected String classLoaderClass;
protected final Locations locations;
public boolean autoClose;
protected void deferredClose() {
Thread t = new Thread(getClass().getName() + " DeferredClose") {
@Override
public void run() {
try {
synchronized (BaseFileManager.this) {
long now = System.currentTimeMillis();
while (now < lastUsedTime + deferredCloseTimeout) {
BaseFileManager.this.wait(lastUsedTime + deferredCloseTimeout - now);
now = System.currentTimeMillis();
}
deferredCloseTimeout = 0;
close();
}
} catch (InterruptedException e) {
} catch (IOException e) {
}
}
};
t.setDaemon(true);
t.start();
}
synchronized void updateLastUsedTime() {
if (deferredCloseTimeout > 0) {
lastUsedTime = System.currentTimeMillis();
}
}
private long lastUsedTime = System.currentTimeMillis();
protected long deferredCloseTimeout = 0;
protected ClassLoader getClassLoader(URL[] urls) {
ClassLoader thisClassLoader = getClass().getClassLoader();
if (classLoaderClass != null) {
try {
Class<? extends ClassLoader> loader =
Class.forName(classLoaderClass).asSubclass(ClassLoader.class);
Class<?>[] constrArgTypes = { URL[].class, ClassLoader.class };
Constructor<? extends ClassLoader> constr = loader.getConstructor(constrArgTypes);
return constr.newInstance(urls, thisClassLoader);
} catch (ReflectiveOperationException t) {
}
}
return new URLClassLoader(urls, thisClassLoader);
}
public boolean isDefaultBootClassPath() {
return locations.isDefaultBootClassPath();
}
@Override @DefinedBy(Api.COMPILER)
public boolean handleOption(String current, Iterator<String> remaining) {
OptionHelper helper = new GrumpyHelper(log) {
@Override
public String get(Option option) {
return options.get(option);
}
@Override
public void put(String name, String value) {
options.put(name, value);
}
@Override
public void remove(String name) {
options.remove(name);
}
@Override
public boolean handleFileManagerOption(Option option, String value) {
return handleOption(option, value);
}
};
Option o = Option.lookup(current, javacFileManagerOptions);
if (o == null) {
return false;
}
try {
o.handleOption(helper, current, remaining);
} catch (Option.InvalidValueException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
return true;
}
private static final Set<Option> javacFileManagerOptions =
Option.getJavacFileManagerOptions();
@Override @DefinedBy(Api.COMPILER)
public int isSupportedOption(String option) {
Option o = Option.lookup(option, javacFileManagerOptions);
return (o == null) ? -1 : o.hasArg() ? 1 : 0;
}
protected String multiReleaseValue;
public boolean handleOption(Option option, String value) {
switch (option) {
case ENCODING:
encodingName = value;
return true;
case MULTIRELEASE:
multiReleaseValue = value;
locations.setMultiReleaseValue(value);
return true;
default:
return locations.handleOption(option, value);
}
}
public boolean handleOptions(Map<Option, String> map) {
boolean ok = true;
for (Map.Entry<Option, String> e: map.entrySet()) {
try {
ok = ok & handleOption(e.getKey(), e.getValue());
} catch (IllegalArgumentException ex) {
log.error(Errors.IllegalArgumentForOption(e.getKey().getPrimaryName(), ex.getMessage()));
ok = false;
}
}
return ok;
}
private String encodingName;
private String defaultEncodingName;
private String getDefaultEncodingName() {
if (defaultEncodingName == null) {
defaultEncodingName = Charset.defaultCharset().name();
}
return defaultEncodingName;
}
public String getEncodingName() {
return (encodingName != null) ? encodingName : getDefaultEncodingName();
}
public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) {
String encName = getEncodingName();
CharsetDecoder decoder;
try {
decoder = getDecoder(encName, ignoreEncodingErrors);
} catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
log.error(Errors.UnsupportedEncoding(encName));
return CharBuffer.allocate(1).flip();
}
float factor =
decoder.averageCharsPerByte() * 0.8f +
decoder.maxCharsPerByte() * 0.2f;
CharBuffer dest = CharBuffer.
allocate(10 + (int)(inbuf.remaining()*factor));
while (true) {
CoderResult result = decoder.decode(inbuf, dest, true);
dest.flip();
if (result.isUnderflow()) {
if (dest.limit() == dest.capacity()) {
dest = CharBuffer.allocate(dest.capacity()+1).put(dest);
dest.flip();
}
return dest;
} else if (result.isOverflow()) {
int newCapacity =
10 + dest.capacity() +
(int)(inbuf.remaining()*decoder.maxCharsPerByte());
dest = CharBuffer.allocate(newCapacity).put(dest);
} else if (result.isMalformed() || result.isUnmappable()) {
StringBuilder unmappable = new StringBuilder();
int len = result.length();
for (int i = 0; i < len; i++) {
unmappable.append(String.format("%02X", inbuf.get()));
}
String charsetName = charset == null ? encName : charset.name();
log.error(dest.limit(),
Errors.IllegalCharForEncoding(unmappable.toString(), charsetName));
dest.position(dest.limit());
dest.limit(dest.capacity());
dest.put((char)0xfffd);
} else {
throw new AssertionError(result);
}
}
}
public CharsetDecoder getDecoder(String encodingName, boolean ignoreEncodingErrors) {
Charset cs = (this.charset == null)
? Charset.forName(encodingName)
: this.charset;
CharsetDecoder decoder = cs.newDecoder();
CodingErrorAction action;
if (ignoreEncodingErrors)
action = CodingErrorAction.REPLACE;
else
action = CodingErrorAction.REPORT;
return decoder
.onMalformedInput(action)
.onUnmappableCharacter(action);
}
public ByteBuffer makeByteBuffer(InputStream in)
throws IOException {
int limit = in.available();
if (limit < 1024) limit = 1024;
ByteBuffer result = byteBufferCache.get(limit);
int position = 0;
while (in.available() != 0) {
if (position >= limit)
result = ByteBuffer.
allocate(limit <<= 1).
put(result.flip());
int count = in.read(result.array(),
position,
limit - position);
if (count < 0) break;
result.position(position += count);
}
return result.flip();
}
public void recycleByteBuffer(ByteBuffer bb) {
byteBufferCache.put(bb);
}
private static class ByteBufferCache {
private ByteBuffer cached;
ByteBuffer get(int capacity) {
if (capacity < 20480) capacity = 20480;
ByteBuffer result =
(cached != null && cached.capacity() >= capacity)
? cached.clear()
: ByteBuffer.allocate(capacity + capacity>>1);
cached = null;
return result;
}
void put(ByteBuffer x) {
cached = x;
}
}
private final ByteBufferCache byteBufferCache;
public CharBuffer getCachedContent(JavaFileObject file) {
ContentCacheEntry e = contentCache.get(file);
if (e == null)
return null;
if (!e.isValid(file)) {
contentCache.remove(file);
return null;
}
return e.getValue();
}
public void cache(JavaFileObject file, CharBuffer cb) {
contentCache.put(file, new ContentCacheEntry(file, cb));
}
public void flushCache(JavaFileObject file) {
contentCache.remove(file);
}
protected final Map<JavaFileObject, ContentCacheEntry> contentCache = new HashMap<>();
protected static class ContentCacheEntry {
final long timestamp;
final SoftReference<CharBuffer> ref;
ContentCacheEntry(JavaFileObject file, CharBuffer cb) {
this.timestamp = file.getLastModified();
this.ref = new SoftReference<>(cb);
}
boolean isValid(JavaFileObject file) {
return timestamp == file.getLastModified();
}
CharBuffer getValue() {
return ref.get();
}
}
public static Kind getKind(Path path) {
return getKind(path.getFileName().toString());
}
public static Kind getKind(String name) {
if (name.endsWith(Kind.CLASS.extension))
return Kind.CLASS;
else if (name.endsWith(Kind.SOURCE.extension))
return Kind.SOURCE;
else if (name.endsWith(Kind.HTML.extension))
return Kind.HTML;
else
return Kind.OTHER;
}
protected static <T> T nullCheck(T o) {
return Objects.requireNonNull(o);
}
protected static <T> Collection<T> nullCheck(Collection<T> it) {
for (T t : it)
Objects.requireNonNull(t);
return it;
}
}