This commit is contained in:
Lana Steuck 2014-11-06 15:13:39 -08:00
commit 6b9913f667
47 changed files with 970 additions and 515 deletions

@ -191,7 +191,7 @@ public class BasicJavacTask extends JavacTask {
}
}
for (List<String> p: pluginsToCall) {
Log.instance(context).error("msg.plugin.not.found", p.head);
Log.instance(context).error("plugin.not.found", p.head);
}
}

@ -25,6 +25,7 @@
package com.sun.tools.javac.api;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.*;
import java.util.concurrent.Callable;
@ -67,6 +68,7 @@ import com.sun.tools.javac.util.Log.WriterKind;
public class JavacTaskImpl extends BasicJavacTask {
private final Arguments args;
private JavaCompiler compiler;
private JavaFileManager fileManager;
private Locale locale;
private Map<JavaFileObject, JCCompilationUnit> notYetEntered;
private ListBuffer<Env<AttrContext>> genList;
@ -76,6 +78,7 @@ public class JavacTaskImpl extends BasicJavacTask {
JavacTaskImpl(Context context) {
super(context, true);
args = Arguments.instance(context);
fileManager = context.get(JavaFileManager.class);
}
@Override @DefinedBy(Api.COMPILER)
@ -202,6 +205,12 @@ public class JavacTaskImpl extends BasicJavacTask {
void cleanup() {
if (compiler != null)
compiler.close();
if (fileManager instanceof BaseFileManager && ((BaseFileManager) fileManager).autoClose) {
try {
fileManager.close();
} catch (IOException ignore) {
}
}
compiler = null;
context = null;
notYetEntered = null;

@ -43,6 +43,7 @@ import com.sun.source.util.JavacTask;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.main.Arguments;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.util.BaseFileManager;
import com.sun.tools.javac.util.ClientCodeException;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.DefinedBy;
@ -151,8 +152,12 @@ public final class JavacTool implements JavaCompiler {
else
context.put(Log.outKey, new PrintWriter(out, true));
if (fileManager == null)
if (fileManager == null) {
fileManager = getStandardFileManager(diagnosticListener, null, null);
if (fileManager instanceof BaseFileManager) {
((BaseFileManager) fileManager).autoClose = true;
}
}
fileManager = ccw.wrap(fileManager);
context.put(JavaFileManager.class, fileManager);

@ -2677,10 +2677,19 @@ public class Types {
while (t.hasTag(TYPEVAR))
t = t.getUpperBound();
TypeSymbol c = t.tsym;
Symbol bestSoFar = null;
for (Symbol sym : c.members().getSymbolsByName(ms.name, implFilter)) {
if (sym != null &&
sym.overrides(ms, origin, Types.this, checkResult))
return (MethodSymbol)sym;
if (sym != null && sym.overrides(ms, origin, Types.this, checkResult)) {
bestSoFar = sym;
if ((sym.flags() & ABSTRACT) == 0) {
//if concrete impl is found, exit immediately
break;
}
}
}
if (bestSoFar != null) {
//return either the (only) concrete implementation or the first abstract one
return (MethodSymbol)bestSoFar;
}
}
return null;

@ -676,13 +676,19 @@ public class Infer {
ListBuffer<Pair<Type, Type>> commonSupertypes = new ListBuffer<>();
for (Type sup : supertypesToCheck) {
if (sup.isParameterized()) {
Type asSuperOfT = types.asSuper(t, sup.tsym);
Type asSuperOfS = types.asSuper(s, sup.tsym);
Type asSuperOfT = asSuper(t, sup);
Type asSuperOfS = asSuper(s, sup);
commonSupertypes.add(new Pair<>(asSuperOfT, asSuperOfS));
}
}
return commonSupertypes.toList();
}
//where
private Type asSuper(Type t, Type sup) {
return (sup.hasTag(ARRAY)) ?
new ArrayType(asSuper(types.elemtype(t), types.elemtype(sup)), syms.arrayClass) :
types.asSuper(t, sup.tsym);
}
/**
* This enumeration defines an entry point for doing inference variable

@ -2033,10 +2033,11 @@ public class Resolve {
// Return the type variable if we have it, and have no
// immediate member, OR the type variable is for a method.
if (tyvar != typeNotFound) {
if (sym == typeNotFound ||
if (env.baseClause || sym == typeNotFound ||
(tyvar.kind == TYP && tyvar.exists() &&
tyvar.owner.kind == MTH))
tyvar.owner.kind == MTH)) {
return tyvar;
}
}
// If the environment is a class def, finish up,

@ -130,8 +130,6 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
if (register)
context.put(JavaFileManager.class, this);
setContext(context);
if (System.getProperty("show.fm.open.close") != null)
System.err.println("JavacFileManager.open " + this.hashCode());
}
/**
@ -573,8 +571,6 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
*/
@DefinedBy(Api.COMPILER)
public void close() {
if (System.getProperty("show.fm.open.close") != null)
System.err.println("JavacFileManager.close " + this.hashCode());
for (Iterator<Archive> i = archives.values().iterator(); i.hasNext(); ) {
Archive a = i.next();
i.remove();

@ -1133,6 +1133,10 @@ compiler.err.error=\
compiler.err.cant.read.file=\
cannot read: {0}
# 0: string
compiler.err.plugin.not.found=\
plug-in not found: {0}
#####
# Fatal Errors

@ -289,8 +289,7 @@ javac.err.file.not.directory=\
not a directory: {0}
javac.err.file.not.file=\
not a file: {0}
javac.msg.plugin.not.found=\
plug-in not found: {0}
## messages
javac.msg.usage.header=\

@ -104,6 +104,12 @@ public abstract class BaseFileManager implements JavaFileManager {
protected Locations locations;
/**
* A flag for clients to use to indicate that this file manager should
* be closed when it is no longer required.
*/
public boolean autoClose;
protected Source getSource() {
String sourceName = options.get(Option.SOURCE);
Source source = null;

@ -413,17 +413,17 @@ public class JavapTask implements DisassemblerTool.DisassemblerTask, Messages {
int run(String[] args) {
try {
handleOptions(args);
// the following gives consistent behavior with javac
if (classes == null || classes.size() == 0) {
if (options.help || options.version || options.fullVersion)
return EXIT_OK;
else
return EXIT_CMDERR;
}
try {
handleOptions(args);
// the following gives consistent behavior with javac
if (classes == null || classes.size() == 0) {
if (options.help || options.version || options.fullVersion)
return EXIT_OK;
else
return EXIT_CMDERR;
}
return run();
} finally {
if (defaultFileManager != null) {

@ -91,7 +91,7 @@ public class CompileJavaPackages implements Transformer {
// Get maximum heap size from the server!
SysInfo sysinfo = sjavac.getSysInfo();
if (sysinfo.numCores == -1) {
if (sysinfo == null) {
Log.error("Could not query server for sysinfo!");
return false;
}

@ -25,31 +25,33 @@
package com.sun.tools.sjavac.client;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import com.sun.tools.sjavac.Log;
import com.sun.tools.sjavac.ProblemException;
import com.sun.tools.sjavac.Util;
import com.sun.tools.sjavac.options.OptionHelper;
import com.sun.tools.sjavac.options.Options;
import com.sun.tools.sjavac.server.CompilationResult;
import com.sun.tools.sjavac.server.PortFile;
import com.sun.tools.sjavac.server.Sjavac;
import com.sun.tools.sjavac.server.SjavacServer;
import com.sun.tools.sjavac.server.SysInfo;
import com.sun.tools.sjavac.options.Options;
/**
* Sjavac implementation that delegates requests to a SjavacServer.
@ -64,10 +66,9 @@ public class SjavacClient implements Sjavac {
// The id can perhaps be used in the future by the javac server to reuse the
// JavaCompiler instance for several compiles using the same id.
private final String id;
private final String portfileName;
private final PortFile portFile;
private final String logfile;
private final String stdouterrfile;
private final boolean background;
// Default keepalive for server is 120 seconds.
// I.e. it will accept 120 seconds of inactivity before quitting.
@ -88,16 +89,27 @@ public class SjavacClient implements Sjavac {
// Store the server conf settings here.
private final String settings;
public SjavacClient(Options options) {
// This constructor should not throw FileNotFoundException (to be resolved
// in JDK-8060030)
public SjavacClient(Options options) throws FileNotFoundException {
String tmpServerConf = options.getServerConf();
String serverConf = (tmpServerConf!=null)? tmpServerConf : "";
String tmpId = Util.extractStringOption("id", serverConf);
id = (tmpId!=null) ? tmpId : "id"+(((new java.util.Random()).nextLong())&Long.MAX_VALUE);
String p = Util.extractStringOption("portfile", serverConf);
portfileName = (p!=null) ? p : options.getStateDir().toFile().getAbsolutePath()+File.separatorChar+"javac_server";
String defaultPortfile = options.getStateDir()
.resolve("javac_server")
.toAbsolutePath()
.toString();
String portfileName = Util.extractStringOption("portfile", serverConf, defaultPortfile);
try {
portFile = SjavacServer.getPortFile(portfileName);
} catch (FileNotFoundException e) {
// Reached for instance if directory of port file does not exist
Log.error("Port file inaccessable: " + e);
throw e;
}
logfile = Util.extractStringOption("logfile", serverConf, portfileName + ".javaclog");
stdouterrfile = Util.extractStringOption("stdouterrfile", serverConf, portfileName + ".stdouterr");
background = Util.extractBooleanOption("background", serverConf, true);
sjavacForkCmd = Util.extractStringOption("sjavac", serverConf, "sjavac");
int poolsize = Util.extractIntOption("poolsize", serverConf);
keepalive = Util.extractIntOption("keepalive", serverConf, 120);
@ -138,8 +150,11 @@ public class SjavacClient implements Sjavac {
return (SysInfo) ois.readObject();
} catch (IOException | ClassNotFoundException ex) {
Log.error("[CLIENT] Exception caught: " + ex);
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
Log.debug(Util.getStackTrace(ex));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // Restore interrupt
Log.error("[CLIENT] getSysInfo interrupted.");
Log.debug(Util.getStackTrace(ie));
}
return null;
}
@ -170,106 +185,127 @@ public class SjavacClient implements Sjavac {
oos.flush();
result = (CompilationResult) ois.readObject();
} catch (IOException | ClassNotFoundException ex) {
Log.error("Exception caught: " + ex);
Log.error("[CLIENT] Exception caught: " + ex);
result = new CompilationResult(CompilationResult.ERROR_FATAL);
result.stderr = Util.getStackTrace(ex);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // Restore interrupt
Log.error("[CLIENT] compile interrupted.");
result = new CompilationResult(CompilationResult.ERROR_FATAL);
result.stderr = Util.getStackTrace(ie);
}
return result;
}
private Socket tryConnect() throws IOException {
PortFile portFile;
try {
// This should be taken care of at a higher level (JDK-8048451)
portFile = SjavacServer.getPortFile(portfileName);
} catch (FileNotFoundException e) {
// Reached for instance if directory of port file does not exist
Log.error("Port file inaccessable: " + e);
throw new RuntimeException(e);
}
for (int i = 0; i < MAX_CONNECT_ATTEMPTS; i++) {
Log.info(String.format("Trying to connect (attempt %d of %d)",
i+1, MAX_CONNECT_ATTEMPTS));
/*
* Makes MAX_CONNECT_ATTEMPTS attepmts to connect to server.
*/
private Socket tryConnect() throws IOException, InterruptedException {
makeSureServerIsRunning(portFile);
int attempt = 0;
while (true) {
Log.info("Trying to connect. Attempt " + (++attempt) + " of " + MAX_CONNECT_ATTEMPTS);
try {
if (!makeSureServerIsRunning(portFile))
continue;
Socket socket = new Socket();
InetAddress localhost = InetAddress.getByName(null);
socket.connect(new InetSocketAddress(localhost, portFile.getPort()),
CONNECTION_TIMEOUT);
return socket;
} catch (ProblemException | IOException ex) {
Log.error("Caught exception during tryConnect: " + ex);
}
try {
Thread.sleep(WAIT_BETWEEN_CONNECT_ATTEMPTS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
throw new IOException("Could not connect to server");
}
private boolean makeSureServerIsRunning(PortFile portFile)
throws IOException, ProblemException, FileNotFoundException {
synchronized (portFile) {
portFile.lock();
portFile.getValues();
portFile.unlock();
}
if (!portFile.containsPortInfo()) {
String forkCmd = SjavacServer.fork(sjavacForkCmd,
portFile.getFilename(),
logfile,
poolsize,
keepalive,
System.err,
stdouterrfile,
background);
if (!portFile.waitForValidValues()) {
// This can be simplified once JDK-8048457 has been addressed
// since we won't have an SjavacClient if background = false
if (background) {
// There seems be some problem with spawning the external
// process (for instance no fork command provided and no
// sjavac on path)
StringWriter sw = new StringWriter();
SjavacClient.printFailedAttempt(forkCmd,
stdouterrfile,
new PrintWriter(sw));
Log.error(sw.toString());
return makeConnectionAttempt();
} catch (IOException ex) {
Log.error("Connection attempt failed: " + ex.getMessage());
if (attempt >= MAX_CONNECT_ATTEMPTS) {
Log.error("Giving up");
throw new IOException("Could not connect to server", ex);
}
}
Thread.sleep(WAIT_BETWEEN_CONNECT_ATTEMPTS);
}
return portFile.containsPortInfo();
}
private Socket makeConnectionAttempt() throws IOException {
Socket socket = new Socket();
InetAddress localhost = InetAddress.getByName(null);
InetSocketAddress address = new InetSocketAddress(localhost, portFile.getPort());
socket.connect(address, CONNECTION_TIMEOUT);
Log.info("Connected");
return socket;
}
public static void printFailedAttempt(String cmd, String f, PrintWriter err) {
err.println("---- Failed to start javac server with this command -----");
err.println(cmd);
try {
BufferedReader in = new BufferedReader(new FileReader(f));
err.println("---- stdout/stderr output from attempt to start javac server -----");
for (;;) {
String l = in.readLine();
if (l == null) {
break;
}
err.println(l);
}
err.println("------------------------------------------------------------------");
} catch (Exception e) {
err.println("The stdout/stderr output in file " + f + " does not exist and the server did not start.");
/*
* Will return immediately if a server already seems to be running,
* otherwise fork a new server and block until it seems to be running.
*/
private void makeSureServerIsRunning(PortFile portFile)
throws IOException, InterruptedException {
portFile.lock();
portFile.getValues();
portFile.unlock();
if (portFile.containsPortInfo()) {
// Server seems to already be running
return;
}
// Fork a new server and wait for it to start
SjavacClient.fork(sjavacForkCmd,
portFile,
logfile,
poolsize,
keepalive,
System.err,
stdouterrfile);
}
@Override
public void shutdown() {
// Nothing to clean up
}
/*
* Fork a server process process and wait for server to come around
*/
public static void fork(String sjavacCmd,
PortFile portFile,
String logfile,
int poolsize,
int keepalive,
final PrintStream err,
String stdouterrfile)
throws IOException, InterruptedException {
List<String> cmd = new ArrayList<>();
cmd.addAll(Arrays.asList(OptionHelper.unescapeCmdArg(sjavacCmd).split(" ")));
cmd.add("--startserver:"
+ "portfile=" + portFile.getFilename()
+ ",logfile=" + logfile
+ ",stdouterrfile=" + stdouterrfile
+ ",poolsize=" + poolsize
+ ",keepalive="+ keepalive);
Process p = null;
Log.info("Starting server. Command: " + String.join(" ", cmd));
try {
// If the cmd for some reason can't be executed (file not found, or
// is not executable) this will throw an IOException with a decent
// error message.
p = new ProcessBuilder(cmd)
.redirectErrorStream(true)
.redirectOutput(new File(stdouterrfile))
.start();
// Throws an IOException if no valid values materialize
portFile.waitForValidValues();
} catch (IOException ex) {
// Log and rethrow exception
Log.error("Faild to launch server.");
Log.error(" Message: " + ex.getMessage());
String rc = p == null || p.isAlive() ? "n/a" : "" + p.exitValue();
Log.error(" Server process exit code: " + rc);
Log.error("Server log:");
Log.error("------- Server log start -------");
try (Scanner s = new Scanner(new File(stdouterrfile))) {
while (s.hasNextLine())
Log.error(s.nextLine());
}
Log.error("------- Server log end ---------");
throw ex;
}
}
}

@ -25,6 +25,7 @@
package com.sun.tools.sjavac.comp;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
@ -76,90 +77,93 @@ public class SjavacImpl implements Sjavac {
Set<URI> sourcesToCompile,
Set<URI> visibleSources) {
JavacTool compiler = JavacTool.create();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
SmartFileManager smartFileManager = new SmartFileManager(fileManager);
Context context = new Context();
try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
SmartFileManager smartFileManager = new SmartFileManager(fileManager);
Context context = new Context();
// Now setup the actual compilation....
CompilationResult compilationResult = new CompilationResult(0);
// Now setup the actual compilation....
CompilationResult compilationResult = new CompilationResult(0);
// First deal with explicit source files on cmdline and in at file.
ListBuffer<JavaFileObject> compilationUnits = new ListBuffer<>();
for (JavaFileObject i : fileManager.getJavaFileObjectsFromFiles(explicitSources)) {
compilationUnits.append(i);
}
// Now deal with sources supplied as source_to_compile.
ListBuffer<File> sourcesToCompileFiles = new ListBuffer<>();
for (URI u : sourcesToCompile) {
sourcesToCompileFiles.append(new File(u));
}
for (JavaFileObject i : fileManager.getJavaFileObjectsFromFiles(sourcesToCompileFiles)) {
compilationUnits.append(i);
}
// Create a new logger.
StringWriter stdoutLog = new StringWriter();
StringWriter stderrLog = new StringWriter();
PrintWriter stdout = new PrintWriter(stdoutLog);
PrintWriter stderr = new PrintWriter(stderrLog);
com.sun.tools.javac.main.Main.Result rc = com.sun.tools.javac.main.Main.Result.OK;
DependencyCollector depsCollector = new DependencyCollector();
PublicApiCollector pubApiCollector = new PublicApiCollector();
PathAndPackageVerifier papVerifier = new PathAndPackageVerifier();
try {
if (compilationUnits.size() > 0) {
smartFileManager.setVisibleSources(visibleSources);
smartFileManager.cleanArtifacts();
smartFileManager.setLog(stdout);
// Do the compilation!
JavacTaskImpl task =
(JavacTaskImpl) compiler.getTask(stderr,
smartFileManager,
null,
Arrays.asList(args),
null,
compilationUnits,
context);
smartFileManager.setSymbolFileEnabled(!Options.instance(context).isSet("ignore.symbol.file"));
task.addTaskListener(depsCollector);
task.addTaskListener(pubApiCollector);
task.addTaskListener(papVerifier);
rc = task.doCall();
smartFileManager.flush();
// First deal with explicit source files on cmdline and in at file.
ListBuffer<JavaFileObject> compilationUnits = new ListBuffer<>();
for (JavaFileObject i : fileManager.getJavaFileObjectsFromFiles(explicitSources)) {
compilationUnits.append(i);
}
} catch (Exception e) {
stderrLog.append(Util.getStackTrace(e));
rc = com.sun.tools.javac.main.Main.Result.ERROR;
}
compilationResult.packageArtifacts = smartFileManager.getPackageArtifacts();
Dependencies deps = Dependencies.instance(context);
for (PackageSymbol from : depsCollector.getSourcePackages()) {
for (PackageSymbol to : depsCollector.getDependenciesForPkg(from))
deps.collect(from.fullname, to.fullname);
}
for (ClassSymbol cs : pubApiCollector.getClassSymbols())
deps.visitPubapi(cs);
if (papVerifier.getMisplacedCompilationUnits().size() > 0) {
for (CompilationUnitTree cu : papVerifier.getMisplacedCompilationUnits()) {
System.err.println("Misplaced compilation unit.");
System.err.println(" Directory: " + Paths.get(cu.getSourceFile().toUri()).getParent());
System.err.println(" Package: " + cu.getPackageName());
// Now deal with sources supplied as source_to_compile.
ListBuffer<File> sourcesToCompileFiles = new ListBuffer<>();
for (URI u : sourcesToCompile) {
sourcesToCompileFiles.append(new File(u));
}
rc = com.sun.tools.javac.main.Main.Result.ERROR;
for (JavaFileObject i : fileManager.getJavaFileObjectsFromFiles(sourcesToCompileFiles)) {
compilationUnits.append(i);
}
// Create a new logger.
StringWriter stdoutLog = new StringWriter();
StringWriter stderrLog = new StringWriter();
PrintWriter stdout = new PrintWriter(stdoutLog);
PrintWriter stderr = new PrintWriter(stderrLog);
com.sun.tools.javac.main.Main.Result rc = com.sun.tools.javac.main.Main.Result.OK;
DependencyCollector depsCollector = new DependencyCollector();
PublicApiCollector pubApiCollector = new PublicApiCollector();
PathAndPackageVerifier papVerifier = new PathAndPackageVerifier();
try {
if (compilationUnits.size() > 0) {
smartFileManager.setVisibleSources(visibleSources);
smartFileManager.cleanArtifacts();
smartFileManager.setLog(stdout);
// Do the compilation!
JavacTaskImpl task =
(JavacTaskImpl) compiler.getTask(stderr,
smartFileManager,
null,
Arrays.asList(args),
null,
compilationUnits,
context);
smartFileManager.setSymbolFileEnabled(!Options.instance(context).isSet("ignore.symbol.file"));
task.addTaskListener(depsCollector);
task.addTaskListener(pubApiCollector);
task.addTaskListener(papVerifier);
rc = task.doCall();
smartFileManager.flush();
}
} catch (Exception e) {
stderrLog.append(Util.getStackTrace(e));
rc = com.sun.tools.javac.main.Main.Result.ERROR;
}
compilationResult.packageArtifacts = smartFileManager.getPackageArtifacts();
Dependencies deps = Dependencies.instance(context);
for (PackageSymbol from : depsCollector.getSourcePackages()) {
for (PackageSymbol to : depsCollector.getDependenciesForPkg(from))
deps.collect(from.fullname, to.fullname);
}
for (ClassSymbol cs : pubApiCollector.getClassSymbols())
deps.visitPubapi(cs);
if (papVerifier.getMisplacedCompilationUnits().size() > 0) {
for (CompilationUnitTree cu : papVerifier.getMisplacedCompilationUnits()) {
System.err.println("Misplaced compilation unit.");
System.err.println(" Directory: " + Paths.get(cu.getSourceFile().toUri()).getParent());
System.err.println(" Package: " + cu.getPackageName());
}
rc = com.sun.tools.javac.main.Main.Result.ERROR;
}
compilationResult.packageDependencies = deps.getDependencies();
compilationResult.packagePubapis = deps.getPubapis();
compilationResult.stdout = stdoutLog.toString();
compilationResult.stderr = stderrLog.toString();
compilationResult.returnCode = rc.exitCode;
return compilationResult;
} catch (IOException e) {
throw new Error(e);
}
compilationResult.packageDependencies = deps.getDependencies();
compilationResult.packagePubapis = deps.getPubapis();
compilationResult.stdout = stdoutLog.toString();
compilationResult.stderr = stderrLog.toString();
compilationResult.returnCode = rc.exitCode;
return compilationResult;
}
@Override

@ -25,7 +25,6 @@
package com.sun.tools.sjavac.options;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
@ -159,4 +158,9 @@ public abstract class OptionHelper {
}
}
}
public static String unescapeCmdArg(String arg) {
return arg.replaceAll("%20", " ")
.replaceAll("%2C", ",");
}
}

@ -33,6 +33,8 @@ import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.FileLockInterruptionException;
import java.util.concurrent.Semaphore;
import com.sun.tools.javac.util.Assert;
import com.sun.tools.sjavac.Log;
@ -61,7 +63,12 @@ public class PortFile {
private File stopFile;
private RandomAccessFile rwfile;
private FileChannel channel;
// FileLock used to solve inter JVM synchronization, lockSem used to avoid
// JVM internal OverlappingFileLockExceptions.
// Class invariant: lock.isValid() <-> lockSem.availablePermits() == 0
private FileLock lock;
private Semaphore lockSem = new Semaphore(1);
private boolean containsPortInfo;
private int serverPort;
@ -88,7 +95,8 @@ public class PortFile {
/**
* Lock the port file.
*/
public void lock() throws IOException {
public void lock() throws IOException, InterruptedException {
lockSem.acquire();
lock = channel.lock();
}
@ -195,34 +203,37 @@ public class PortFile {
Assert.check(lock != null);
lock.release();
lock = null;
lockSem.release();
}
/**
* Wait for the port file to contain values that look valid.
* Return true, if a-ok, false if the valid values did not materialize within 5 seconds.
*/
public synchronized boolean waitForValidValues() throws IOException, FileNotFoundException {
for (int tries = 0; tries < 50; tries++) {
public void waitForValidValues() throws IOException, InterruptedException {
final int MAX_ATTEMPTS = 10;
final int MS_BETWEEN_ATTEMPTS = 500;
long startTime = System.currentTimeMillis();
for (int attempt = 0; ; attempt++) {
Log.debug("Looking for valid port file values...");
lock();
getValues();
unlock();
if (containsPortInfo) {
Log.debug("Found valid values in port file after waiting "+(tries*100)+"ms");
return true;
Log.debug("Valid port file values found after " + (System.currentTimeMillis() - startTime) + " ms");
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e)
{}
if (attempt >= MAX_ATTEMPTS) {
throw new IOException("No port file values materialized. Giving up after " +
(System.currentTimeMillis() - startTime) + " ms");
}
Thread.sleep(MS_BETWEEN_ATTEMPTS);
}
Log.debug("Gave up waiting for valid values in port file");
return false;
}
/**
* Check if the portfile still contains my values, assuming that I am the server.
*/
public synchronized boolean stillMyValues() throws IOException, FileNotFoundException {
public boolean stillMyValues() throws IOException, FileNotFoundException, InterruptedException {
for (;;) {
try {
lock();

@ -75,6 +75,10 @@ public class PortFileMonitor {
} catch (IOException e) {
e.printStackTrace(server.theLog);
server.flushLog();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace(server.theLog);
server.flushLog();
}
}
};

@ -46,8 +46,8 @@ public class ServerMain {
try {
SjavacServer server = new SjavacServer(args[0], System.err);
exitCode = server.startServer();
} catch (IOException ioex) {
ioex.printStackTrace();
} catch (IOException | InterruptedException ex) {
ex.printStackTrace();
exitCode = -1;
}

@ -24,7 +24,6 @@
*/
package com.sun.tools.sjavac.server;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
@ -34,16 +33,14 @@ import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import com.sun.tools.sjavac.ProblemException;
import com.sun.tools.sjavac.Util;
import com.sun.tools.sjavac.comp.SjavacImpl;
import com.sun.tools.sjavac.comp.PooledSjavac;
import com.sun.tools.sjavac.comp.SjavacImpl;
/**
* The JavacServer class contains methods both to setup a server that responds to requests and methods to connect to this server.
@ -95,13 +92,26 @@ public class SjavacServer implements Terminable {
private static Map<String, Long> maxServerMemory;
public SjavacServer(String settings, PrintStream err) throws FileNotFoundException {
// Extract options. TODO: Change to proper constructor args
portfilename = Util.extractStringOption("portfile", settings);
logfile = Util.extractStringOption("logfile", settings);
stdouterrfile = Util.extractStringOption("stdouterrfile", settings);
keepalive = Util.extractIntOption("keepalive", settings, 120);
poolsize = Util.extractIntOption("poolsize", settings,
Runtime.getRuntime().availableProcessors());
this(Util.extractStringOption("portfile", settings),
Util.extractStringOption("logfile", settings),
Util.extractStringOption("stdouterrfile", settings),
Util.extractIntOption("poolsize", settings, Runtime.getRuntime().availableProcessors()),
Util.extractIntOption("keepalive", settings, 120),
err);
}
public SjavacServer(String portfilename,
String logfile,
String stdouterrfile,
int poolsize,
int keepalive,
PrintStream err)
throws FileNotFoundException {
this.portfilename = portfilename;
this.logfile = logfile;
this.stdouterrfile = stdouterrfile;
this.poolsize = poolsize;
this.keepalive = keepalive;
this.err = err;
myCookie = new Random().nextLong();
@ -180,7 +190,7 @@ public class SjavacServer implements Terminable {
* Start a server using a settings string. Typically: "--startserver:portfile=/tmp/myserver,poolsize=3" and the string "portfile=/tmp/myserver,poolsize=3"
* is sent as the settings parameter. Returns 0 on success, -1 on failure.
*/
public int startServer() throws IOException {
public int startServer() throws IOException, InterruptedException {
long serverStart = System.currentTimeMillis();
// The port file is locked and the server port and cookie is written into it.
@ -250,64 +260,6 @@ public class SjavacServer implements Terminable {
return 0;
}
/**
* Fork a background process. Returns the command line used that can be printed if something failed.
*/
public static String fork(String sjavac, String portfile, String logfile, int poolsize, int keepalive,
final PrintStream err, String stdouterrfile, boolean background)
throws IOException, ProblemException {
if (stdouterrfile != null && stdouterrfile.trim().equals("")) {
stdouterrfile = null;
}
final String startserver = "--startserver:portfile=" + portfile + ",logfile=" + logfile + ",stdouterrfile=" + stdouterrfile + ",poolsize=" + poolsize + ",keepalive="+ keepalive;
if (background) {
sjavac += "%20" + startserver;
sjavac = sjavac.replaceAll("%20", " ");
sjavac = sjavac.replaceAll("%2C", ",");
// If the java/sh/cmd launcher fails the failure will be captured by stdouterr because of the redirection here.
String[] cmd = {"/bin/sh", "-c", sjavac + " >> " + stdouterrfile + " 2>&1"};
if (!(new File("/bin/sh")).canExecute()) {
ArrayList<String> wincmd = new ArrayList<>();
wincmd.add("cmd");
wincmd.add("/c");
wincmd.add("start");
wincmd.add("cmd");
wincmd.add("/c");
wincmd.add(sjavac + " >> " + stdouterrfile + " 2>&1");
cmd = wincmd.toArray(new String[wincmd.size()]);
}
Process pp = null;
try {
pp = Runtime.getRuntime().exec(cmd);
} catch (Exception e) {
e.printStackTrace(err);
e.printStackTrace(new PrintWriter(stdouterrfile));
}
StringBuilder rs = new StringBuilder();
for (String s : cmd) {
rs.append(s + " ");
}
return rs.toString();
}
// Do not spawn a background server, instead run it within the same JVM.
Thread t = new Thread() {
@Override
public void run() {
try {
SjavacServer server = new SjavacServer(startserver, err);
server.startServer();
} catch (Throwable t) {
t.printStackTrace(err);
}
}
};
t.setDaemon(true);
t.start();
return "";
}
@Override
public void shutdown(String quitMsg) {
if (!keepAcceptingRequests.compareAndSet(true, false)) {

@ -656,6 +656,9 @@ public class VisibleMemberMap {
// properties aren't named setA* or getA*
private final Pattern pattern = Pattern.compile("[sg]et\\p{Upper}.*");
private boolean isPropertyMethod(MethodDoc method) {
if (!configuration.javafx) {
return false;
}
if (!method.name().endsWith("Property")) {
return false;
}
@ -667,7 +670,9 @@ public class VisibleMemberMap {
if (pattern.matcher(method.name()).matches()) {
return false;
}
if (method.typeParameters().length > 0) {
return false;
}
return 0 == method.parameters().length
&& !"void".equals(method.returnType().simpleTypeName());
}

@ -89,7 +89,6 @@ public class Start extends ToolOption.Helper {
private boolean apiMode;
private JavaFileManager fileManager;
private boolean closeFileManagerOnExit;
Start(String programName,
PrintWriter errWriter,
@ -242,7 +241,9 @@ public class Start extends ToolOption.Helper {
messager.error(Messager.NOPOS, "main.fatal.exception");
failed = true;
} finally {
if (fileManager != null && closeFileManagerOnExit) {
if (fileManager != null
&& fileManager instanceof BaseFileManager
&& ((BaseFileManager) fileManager).autoClose) {
try {
fileManager.close();
} catch (IOException ignore) {
@ -343,7 +344,9 @@ public class Start extends ToolOption.Helper {
if (fileManager == null) {
JavacFileManager.preRegister(context);
fileManager = context.get(JavaFileManager.class);
closeFileManagerOnExit = true;
if (fileManager instanceof BaseFileManager) {
((BaseFileManager) fileManager).autoClose = true;
}
}
if (fileManager instanceof BaseFileManager) {
((BaseFileManager) fileManager).handleOptions(fileManagerOpts);

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -45,6 +45,7 @@ import javax.tools.StandardJavaFileManager;
import com.sun.tools.javac.api.ClientCodeWrapper;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.BaseFileManager;
import com.sun.tools.javac.util.ClientCodeException;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.DefinedBy;
@ -111,8 +112,12 @@ public class JavadocTool implements DocumentationTool {
else
context.put(Log.outKey, new PrintWriter(out, true));
if (fileManager == null)
if (fileManager == null) {
fileManager = getStandardFileManager(diagnosticListener, null, null);
if (fileManager instanceof BaseFileManager) {
((BaseFileManager) fileManager).autoClose = true;
}
}
fileManager = ccw.wrap(fileManager);
context.put(JavaFileManager.class, fileManager);

@ -186,6 +186,10 @@ ifdef JTREG_TIMEOUT_FACTOR
JTREG_OPTIONS += -timeoutFactor:$(JTREG_TIMEOUT_FACTOR)
endif
ifdef JCK_TIMEOUT_FACTOR
JCK_OPTIONS += -timeout:$(JCK_TIMEOUT_FACTOR)
endif
# Default verbosity setting for jtreg
JTREG_VERBOSE = fail,error,nopass
@ -298,7 +302,7 @@ ifdef JTREG_REFERENCE
endif
jtreg-summary: FRC
if [ -r $(JTREG_OUTPUT_DIR)/status.txt ]; then \
@if [ -r $(JTREG_OUTPUT_DIR)/status.txt ]; then \
echo ; echo "Summary of jtreg test failures" ; \
cat $(JTREG_OUTPUT_DIR)/JTreport/text/summary.txt | \
grep -v 'Not run' | grep -v 'Passed' ; \
@ -336,8 +340,8 @@ jck-compiler-tests: check-jck FRC
$(JCK_COMPILER_OUTPUT_DIR)/diff.html $(JCK_COMPILER_OUTPUT_DIR)/status.txt
@mkdir -p $(JCK_COMPILER_OUTPUT_DIR)
$(JT_JAVA)/bin/java -Xmx512m \
-jar $(JCK_HOME)/JCK-compiler-8/lib/jtjck.jar \
$(if $(JCK_VERBOSE),-v:$(JCK_VERBOSE)) \
-jar $(JCK_HOME)/JCK-compiler-9/lib/jtjck.jar \
$(if $(JCK_VERBOSE),$(if $(filter $(JCK_VERBOSE),summary),-v,-v:$(JCK_VERBOSE))) \
-r:$(JCK_COMPILER_OUTPUT_DIR)/report \
-w:$(JCK_COMPILER_OUTPUT_DIR)/work \
-jdk:$(TESTJAVA) \
@ -353,7 +357,7 @@ ifdef JCK_COMPILER_REFERENCE
endif
jck-compiler-summary: FRC
if [ -r $(JCK_COMPILER_OUTPUT_DIR)/status.txt ]; then \
@if [ -r $(JCK_COMPILER_OUTPUT_DIR)/status.txt ]; then \
echo ; echo "Summary of JCK-compiler test failures" ; \
cat $(JCK_COMPILER_OUTPUT_DIR)/report/text/summary.txt | \
grep -v 'Not run' | grep -v 'Passed' ; \
@ -387,8 +391,8 @@ jck-runtime-tests: check-jck FRC
$(JCK_RUNTIME_OUTPUT_DIR)/diff.html $(JCK_RUNTIME_OUTPUT_DIR)/status.txt
@mkdir -p $(JCK_RUNTIME_OUTPUT_DIR)
$(JT_JAVA)/bin/java -Xmx512m \
-jar $(JCK_HOME)/JCK-runtime-8/lib/jtjck.jar \
$(if $(JCK_VERBOSE),-v:$(JCK_VERBOSE)) \
-jar $(JCK_HOME)/JCK-runtime-9/lib/jtjck.jar \
$(if $(JCK_VERBOSE),$(if $(filter $(JCK_VERBOSE),summary),-v,-v:$(JCK_VERBOSE))) \
-r:$(JCK_RUNTIME_OUTPUT_DIR)/report \
-w:$(JCK_RUNTIME_OUTPUT_DIR)/work \
-jdk:$(TESTJAVA) \
@ -405,7 +409,7 @@ ifdef JCK_RUNTIME_REFERENCE
endif
jck-runtime-summary: FRC
if [ -r $(JCK_RUNTIME_OUTPUT_DIR)/status.txt ]; then \
@if [ -r $(JCK_RUNTIME_OUTPUT_DIR)/status.txt ]; then \
echo ; echo "Summary of JCK-runtime test failures" ; \
cat $(JCK_RUNTIME_OUTPUT_DIR)/report/text/summary.txt | \
grep -v 'Not run' | grep -v 'Passed' ; \
@ -417,7 +421,7 @@ jck-runtime-summary: FRC
check-jck: $(JCK_HOME) $(PRODUCT_HOME)
all-summary: FRC
if [ -n "`find $(TEST_OUTPUT_DIR) -name status.txt`" ]; then
@if [ -n "`find $(TEST_OUTPUT_DIR) -name status.txt`" ]; then
echo ; echo "Summary of test failures" ; \
cat `find $(TEST_OUTPUT_DIR) -name summary.txt` | \
grep -v 'Not run' | grep -v 'Passed' ; \

@ -23,7 +23,7 @@
/*
* @test
* @bug 7112427 8012295 8025633 8026567
* @bug 7112427 8012295 8025633 8026567 8061305
* @summary Test of the JavaFX doclet features.
* @author jvalenta
* @library ../lib
@ -39,44 +39,143 @@ public class TestJavaFX extends JavadocTester {
}
@Test
void test() {
javadoc("-d", "out",
void test1() {
javadoc("-d", "out1",
"-sourcepath", testSrc,
"-javafx",
testSrc("C.java"), testSrc("D.java"));
checkExit(Exit.FAILED); // should be EXIT_OK -- need to fix C.java
"-package",
"pkg1");
checkExit(Exit.OK);
checkOutput("C.html", true,
checkOutput("pkg1/C.html", true,
"<dt><span class=\"seeLabel\">See Also:</span></dt>\n"
+ "<dd><a href=\"C.html#getRate--\"><code>getRate()</code></a>, \n"
+ "<a href=\"C.html#setRate-double-\"><code>setRate(double)</code></a></dd>",
+ "<dd><a href=\"../pkg1/C.html#getRate--\"><code>getRate()</code></a>, \n"
+ "<a href=\"../pkg1/C.html#setRate-double-\">"
+ "<code>setRate(double)</code></a></dd>",
"<pre>public final&nbsp;void&nbsp;setRate(double&nbsp;value)</pre>\n"
+ "<div class=\"block\">Sets the value of the property rate.</div>\n"
+ "<dl>\n"
+ "<dt><span class=\"simpleTagLabel\">Property description:</span></dt>",
+ "<div class=\"block\">Sets the value of the property rate.</div>\n"
+ "<dl>\n"
+ "<dt><span class=\"simpleTagLabel\">Property description:</span></dt>",
"<pre>public final&nbsp;double&nbsp;getRate()</pre>\n"
+ "<div class=\"block\">Gets the value of the property rate.</div>\n"
+ "<dl>\n"
+ "<dt><span class=\"simpleTagLabel\">Property description:</span></dt>",
"<td class=\"colLast\"><code><span class=\"memberNameLink\"><a href=\"C.html#rateProperty\">rate</a></span></code>\n"
+ "<div class=\"block\">Defines the direction/speed at which the <code>Timeline</code> is expected to",
+ "<div class=\"block\">Gets the value of the property rate.</div>\n"
+ "<dl>\n"
+ "<dt><span class=\"simpleTagLabel\">Property description:</span></dt>",
"<td class=\"colLast\"><code><span class=\"memberNameLink\">"
+ "<a href=\"../pkg1/C.html#rateProperty\">rate</a></span></code>\n"
+ "<div class=\"block\">Defines the direction/speed at which the "
+ "<code>Timeline</code> is expected to",
"<span class=\"simpleTagLabel\">Default value:</span>",
"<span class=\"simpleTagLabel\">Since:</span></dt>\n"
+ "<dd>JavaFX 8.0</dd>",
+ "<dd>JavaFX 8.0</dd>",
"<p>Sets the value of the property <code>Property</code>",
"<p>Gets the value of the property <code>Property</code>",
"<span class=\"simpleTagLabel\">Property description:</span>",
"<td class=\"colLast\"><code><span class=\"memberNameLink\"><a href=\"C.html#setTestMethodProperty--\">setTestMethodProperty</a></span>()</code>&nbsp;</td>",
"<td class=\"colLast\"><code><span class=\"memberNameLink\">"
+ "<a href=\"../pkg1/C.html#setTestMethodProperty--\">"
+ "setTestMethodProperty</a></span>()</code>&nbsp;</td>",
"<h4>isPaused</h4>\n"
+ "<pre>public final&nbsp;double&nbsp;isPaused()</pre>\n"
+ "<div class=\"block\">Gets the value of the property paused.</div>");
+ "<pre>public final&nbsp;double&nbsp;isPaused()</pre>\n"
+ "<div class=\"block\">Gets the value of the property paused.</div>");
checkOutput("C.html", false,
checkOutput("pkg1/C.html", false,
"A()");
checkOutput("D.html", true,
"<h3>Properties inherited from class&nbsp;<a href=\"C.html\" title=\"class in &lt;Unnamed&gt;\">C</a></h3>\n"
+ "<code><a href=\"C.html#pausedProperty\">paused</a>, <a href=\"C.html#rateProperty\">rate</a></code></li>");
checkOutput("pkg1/D.html", true,
"<h3>Properties inherited from class&nbsp;pkg1."
+ "<a href=\"../pkg1/C.html\" title=\"class in pkg1\">C</a></h3>\n"
+ "<code><a href=\"../pkg1/C.html#pausedProperty\">"
+ "paused</a>, <a href=\"../pkg1/C.html#rateProperty\">rate</a></code></li>");
}
/*
* Test with -javafx option enabled, to ensure property getters and setters
* are treated correctly.
*/
@Test
void test2() {
javadoc("-d", "out2a",
"-sourcepath", testSrc,
"-javafx",
"-package",
"pkg2");
checkExit(Exit.OK);
checkOutput("pkg2/Test.html", true,
"<li class=\"blockList\"><a name=\"property.detail\">\n"
+ "<!-- -->\n"
+ "</a>\n"
+ "<h3>Property Detail</h3>\n"
+ "<a name=\"betaProperty\">\n"
+ "<!-- -->\n"
+ "</a>\n"
+ "<ul class=\"blockList\">\n"
+ "<li class=\"blockList\">\n"
+ "<h4>beta</h4>\n"
+ "<pre>public&nbsp;java.lang.Object betaProperty</pre>\n"
+ "</li>\n"
+ "</ul>\n"
+ "<a name=\"gammaProperty\">\n"
+ "<!-- -->\n"
+ "</a>\n"
+ "<ul class=\"blockList\">\n"
+ "<li class=\"blockList\">\n"
+ "<h4>gamma</h4>\n"
+ "<pre>public final&nbsp;java.util.List&lt;"
+ "java.lang.String&gt; gammaProperty</pre>\n"
+ "</li>\n"
+ "</ul>\n"
+ "<a name=\"deltaProperty\">\n"
+ "<!-- -->\n"
+ "</a>\n"
+ "<ul class=\"blockListLast\">\n"
+ "<li class=\"blockList\">\n"
+ "<h4>delta</h4>\n"
+ "<pre>public final&nbsp;java.util.List&lt;"
+ "java.util.Set&lt;? super java.lang.Object&gt;&gt; deltaProperty</pre>\n"
+ "</li>\n"
+ "</ul>\n"
+ "</li>");
}
/*
* Test without -javafx option, to ensure property getters and setters
* are treated just like any other java method.
*/
@Test
void test3() {
javadoc("-d", "out2b",
"-sourcepath", testSrc,
"-package",
"pkg2");
checkExit(Exit.OK);
checkOutput("pkg2/Test.html", false, "<h3>Property Summary</h3>");
checkOutput("pkg2/Test.html", true,
"<th class=\"colFirst\" scope=\"col\">Modifier and Type</th>\n"
+ "<th class=\"colLast\" scope=\"col\">Method and Description</th>\n"
+ "</tr>\n"
+ "<tr id=\"i0\" class=\"altColor\">\n"
+ "<td class=\"colFirst\"><code>&lt;T&gt;&nbsp;java.lang.Object</code></td>\n"
+ "<td class=\"colLast\"><code><span class=\"memberNameLink\">"
+ "<a href=\"../pkg2/Test.html#alphaProperty-java.util.List-\">"
+ "alphaProperty</a></span>(java.util.List&lt;T&gt;&nbsp;foo)</code>&nbsp;</td>\n"
+ "</tr>\n"
+ "<tr id=\"i1\" class=\"rowColor\">\n"
+ "<td class=\"colFirst\"><code>java.lang.Object</code></td>\n"
+ "<td class=\"colLast\"><code><span class=\"memberNameLink\">"
+ "<a href=\"../pkg2/Test.html#betaProperty--\">betaProperty</a></span>()</code>"
+ "&nbsp;</td>\n"
+ "</tr>\n"
+ "<tr id=\"i2\" class=\"altColor\">\n"
+ "<td class=\"colFirst\"><code>"
+ "java.util.List&lt;java.util.Set&lt;? super java.lang.Object&gt;&gt;"
+ "</code></td>\n"
+ "<td class=\"colLast\"><code><span class=\"memberNameLink\">"
+ "<a href=\"../pkg2/Test.html#deltaProperty--\">"
+ "deltaProperty</a></span>()</code>&nbsp;</td>\n"
+ "</tr>\n"
+ "<tr id=\"i3\" class=\"rowColor\">\n"
+ "<td class=\"colFirst\"><code>java.util.List&lt;java.lang.String&gt;"
+ "</code></td>\n"
+ "<td class=\"colLast\"><code><span class=\"memberNameLink\">"
+ "<a href=\"../pkg2/Test.html#gammaProperty--\">gammaProperty</a>"
+ "</span>()</code>&nbsp;</td>"
);
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -20,10 +20,7 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @expert Expert tag text
*/
package pkg1;
public class C {
@ -35,7 +32,6 @@ public class C {
/**
* @propertyGetter Property
* @expert Expert tag text
*
*/
public void B() {}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -20,9 +20,6 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @expert Expert tag text
*/
package pkg1;
public class D extends C {}

@ -0,0 +1,34 @@
/*
* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package pkg2;
import java.util.List;
import java.util.Set;
public class Test {
public <T> Object alphaProperty(List<T> foo) { return null; }
public Object betaProperty() { return null; }
public final List<String> gammaProperty() {return null;}
public final List<Set<? super Object>> deltaProperty() {return null;}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -245,21 +245,22 @@ public abstract class JavacTemplateTestBase {
private File compile(List<File> classpaths, List<JavaFileObject> files, boolean generate) throws IOException {
JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = systemJavaCompiler.getStandardFileManager(null, null, null);
if (classpaths.size() > 0)
fm.setLocation(StandardLocation.CLASS_PATH, classpaths);
JavacTask ct = (JavacTask) systemJavaCompiler.getTask(null, fm, diags, compileOptions, null, files);
if (generate) {
File destDir = new File(root, Integer.toString(counter.incrementAndGet()));
// @@@ Assert that this directory didn't exist, or start counter at max+1
destDir.mkdirs();
fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
ct.generate();
return destDir;
}
else {
ct.analyze();
return nullDir;
try (StandardJavaFileManager fm = systemJavaCompiler.getStandardFileManager(null, null, null)) {
if (classpaths.size() > 0)
fm.setLocation(StandardLocation.CLASS_PATH, classpaths);
JavacTask ct = (JavacTask) systemJavaCompiler.getTask(null, fm, diags, compileOptions, null, files);
if (generate) {
File destDir = new File(root, Integer.toString(counter.incrementAndGet()));
// @@@ Assert that this directory didn't exist, or start counter at max+1
destDir.mkdirs();
fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
ct.generate();
return destDir;
}
else {
ct.analyze();
return nullDir;
}
}
}

@ -0,0 +1,41 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @summary Incorrect shadowing of classes vs type parameters
* @bug 8035259
* @run compile TypeVarShadow.java
*/
public class TypeVarShadow {
class T<E> {}
abstract class One<E> {
abstract E foo();
}
abstract class Two<T> extends One<T> {
abstract T foo();
}
}

@ -44,6 +44,7 @@ import javax.lang.model.element.ElementKind;
import javax.lang.model.type.TypeKind;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
@ -52,22 +53,26 @@ public class VerifyErroneousAnnotationsAttributed {
new VerifyErroneousAnnotationsAttributed().run();
}
void run() {
int failCount = 0;
for (String ann : generateAnnotations()) {
String code = PATTERN.replace("PLACEHOLDER", ann);
try {
validate(code);
} catch (Throwable t) {
System.out.println("Failed for: ");
System.out.println(code);
t.printStackTrace(System.out);
failCount++;
void run() throws IOException {
try {
int failCount = 0;
for (String ann : generateAnnotations()) {
String code = PATTERN.replace("PLACEHOLDER", ann);
try {
validate(code);
} catch (Throwable t) {
System.out.println("Failed for: ");
System.out.println(code);
t.printStackTrace(System.out);
failCount++;
}
}
}
if (failCount > 0) {
throw new IllegalStateException("failed sub-tests: " + failCount);
if (failCount > 0) {
throw new IllegalStateException("failed sub-tests: " + failCount);
}
} finally {
fm.close();
}
}
@ -221,13 +226,14 @@ public class VerifyErroneousAnnotationsAttributed {
}
final JavacTool tool = JavacTool.create();
final JavaFileManager fm = tool.getStandardFileManager(null, null, null);
final DiagnosticListener<JavaFileObject> devNull = new DiagnosticListener<JavaFileObject>() {
@Override public void report(Diagnostic<? extends JavaFileObject> diagnostic) {}
};
void validate(String code) throws IOException, URISyntaxException {
JavacTask task = tool.getTask(null,
null,
fm,
devNull,
Arrays.asList("-XDshouldStopPolicy=FLOW"),
null,

@ -1,5 +1,5 @@
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -34,19 +34,20 @@ import java.util.HashSet;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.DeclaredType;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import com.sun.source.util.JavacTask;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
public class TestContainTypes {
@ -127,22 +128,28 @@ public class TestContainTypes {
}
}
static final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
static final JavaFileManager fm = tool.getStandardFileManager(null, null, null);
public static void main(String... args) throws Exception {
for (ClassType ctA : ClassType.values()) {
for (ParameterType ptA : ParameterType.values()) {
for (ClassType ctB : ClassType.values()) {
for (ParameterType ptB : ParameterType.values()) {
compileAndCheck(ptA, ctA, ptB, ctB);
try {
for (ClassType ctA : ClassType.values()) {
for (ParameterType ptA : ParameterType.values()) {
for (ClassType ctB : ClassType.values()) {
for (ParameterType ptB : ParameterType.values()) {
compileAndCheck(ptA, ctA, ptB, ctB);
}
}
}
}
} finally {
fm.close();
}
}
static void compileAndCheck(ParameterType ptA, ClassType ctA, ParameterType ptB, ClassType ctB) throws Exception {
JavaSource source = new JavaSource(ptA.instantiate(ctA), ptB.instantiate(ctB));
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask)tool.getTask(null, null, null,
JavacTask ct = (JavacTask)tool.getTask(null, fm, null,
null, null, Arrays.asList(source));
ct.setProcessors(Arrays.asList(new ContainTypesTester(ParameterType.contains(ptA, ctA, ptB, ctB), source)));
System.err.println("A = " + ptA +" / " + ptA.instantiate(ctA));

@ -100,14 +100,18 @@ class ArgTypeCompilerFactory implements Example.Compiler.Factory {
JavacTool tool = JavacTool.create();
StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
if (fmOpts != null)
fm = new FileManager(fm, fmOpts);
try {
if (fmOpts != null)
fm = new FileManager(fm, fmOpts);
Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(files);
Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(files);
Context c = initContext();
JavacTaskImpl t = (JavacTaskImpl) tool.getTask(out, fm, null, opts, null, fos, c);
return t.call();
Context c = initContext();
JavacTaskImpl t = (JavacTaskImpl) tool.getTask(out, fm, null, opts, null, fos, c);
return t.call();
} finally {
close(fm);
}
}
}
@ -136,9 +140,14 @@ class ArgTypeCompilerFactory implements Example.Compiler.Factory {
Main main = new Main("javac", out);
Context c = initContext();
JavacFileManager.preRegister(c); // can't create it until Log has been set up
Main.Result result = main.compile(args.toArray(new String[args.size()]), c);
return result.isOK();
try {
Main.Result result = main.compile(args.toArray(new String[args.size()]), c);
return result.isOK();
} finally {
close(c.get(JavaFileManager.class));
}
}
}
@ -160,10 +169,15 @@ class ArgTypeCompilerFactory implements Example.Compiler.Factory {
Context c = initContext();
JavacFileManager.preRegister(c); // can't create it until Log has been set up
Main m = new Main("javac", out);
Main.Result result = m.compile(args.toArray(new String[args.size()]), c);
return result.isOK();
try {
Main m = new Main("javac", out);
Main.Result result = m.compile(args.toArray(new String[args.size()]), c);
return result.isOK();
} finally {
close(c.get(JavaFileManager.class));
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -31,6 +31,7 @@ import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
@ -311,24 +312,24 @@ class Example implements Comparable<Example> {
static class DefaultFactory implements Factory {
public Compiler getCompiler(List<String> opts, boolean verbose) {
String first;
String[] rest;
if (opts == null || opts.isEmpty()) {
first = null;
rest = new String[0];
} else {
first = opts.get(0);
rest = opts.subList(1, opts.size()).toArray(new String[opts.size() - 1]);
}
if (first == null || first.equals("jsr199"))
return new Jsr199Compiler(verbose, rest);
else if (first.equals("simple"))
return new SimpleCompiler(verbose);
else if (first.equals("backdoor"))
return new BackdoorCompiler(verbose);
else
throw new IllegalArgumentException(first);
String first;
String[] rest;
if (opts == null || opts.isEmpty()) {
first = null;
rest = new String[0];
} else {
first = opts.get(0);
rest = opts.subList(1, opts.size()).toArray(new String[opts.size() - 1]);
}
if (first == null || first.equals("jsr199"))
return new Jsr199Compiler(verbose, rest);
else if (first.equals("simple"))
return new SimpleCompiler(verbose);
else if (first.equals("backdoor"))
return new BackdoorCompiler(verbose);
else
throw new IllegalArgumentException(first);
}
}
static Factory factory;
@ -351,6 +352,14 @@ class Example implements Comparable<Example> {
loader = cl;
}
protected void close(JavaFileManager fm) {
try {
fm.close();
} catch (IOException e) {
throw new Error(e);
}
}
protected ClassLoader loader;
protected boolean verbose;
}
@ -399,21 +408,25 @@ class Example implements Comparable<Example> {
JavaCompiler c = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = c.getStandardFileManager(dc, null, null);
if (fmOpts != null)
fm = new FileManager(fm, fmOpts);
try {
if (fmOpts != null)
fm = new FileManager(fm, fmOpts);
Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(files);
Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(files);
CompilationTask t = c.getTask(out, fm, dc, opts, null, fos);
Boolean ok = t.call();
CompilationTask t = c.getTask(out, fm, dc, opts, null, fos);
Boolean ok = t.call();
if (keys != null) {
for (Diagnostic<? extends JavaFileObject> d: dc.getDiagnostics()) {
scanForKeys(unwrap(d), keys);
if (keys != null) {
for (Diagnostic<? extends JavaFileObject> d: dc.getDiagnostics()) {
scanForKeys(unwrap(d), keys);
}
}
}
return ok;
return ok;
} finally {
close(fm);
}
}
/**
@ -526,14 +539,19 @@ class Example implements Comparable<Example> {
Context c = new Context();
JavacFileManager.preRegister(c); // can't create it until Log has been set up
MessageTracker.preRegister(c, keys);
Main m = new Main("javac", pw);
Main.Result rc = m.compile(args.toArray(new String[args.size()]), c);
if (keys != null) {
pw.close();
try {
Main m = new Main("javac", pw);
Main.Result rc = m.compile(args.toArray(new String[args.size()]), c);
if (keys != null) {
pw.close();
}
return rc.isOK();
} finally {
close(c.get(JavaFileManager.class));
}
return rc.isOK();
}
static class MessageTracker extends JavacMessages {

@ -0,0 +1,28 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
// key: compiler.err.plugin.not.found
// options: -Xplugin:MissingPlugin
class PluginNotFound { }

@ -0,0 +1,29 @@
/*
* @test /nodynamiccopyright/
* @bug 6987475
*
* @summary Order of declarations affects whether abstract method considered overridden
* @compile/fail/ref=T6987475neg.out -XDrawDiagnostics T6987475neg.java
*/
class T6987475neg {
static abstract class Base<A> {
public void go(String s) { }
public abstract void go(A a);
}
static abstract class BaseReverse<A> {
public abstract void go(A a);
public void go(String s) { }
}
static abstract class Sub<A> extends Base<A> {
public abstract void go(A a);
}
static abstract class SubReverse<A> extends BaseReverse<A> {
public abstract void go(A a);
}
static class Impl1 extends Sub<String> { }
static class Impl2 extends SubReverse<String> { }
}

@ -0,0 +1,3 @@
T6987475neg.java:27:12: compiler.err.does.not.override.abstract: T6987475neg.Impl1, go(java.lang.String), T6987475neg.Sub
T6987475neg.java:28:12: compiler.err.does.not.override.abstract: T6987475neg.Impl2, go(java.lang.String), T6987475neg.SubReverse
2 errors

@ -0,0 +1,47 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6987475
*
* @summary Order of declarations affects whether abstract method considered overridden
* @compile T6987475pos.java
*/
class T6987475pos {
static abstract class Base<A> {
public void go(String s) { }
public abstract void go(A a);
}
static abstract class BaseReverse<A> {
public abstract void go(A a);
public void go(String s) { }
}
static class Impl1 extends Base<String> { }
static class Impl2 extends BaseReverse<String> { }
}

@ -0,0 +1,29 @@
/*
* @test /nodynamiccopyright/
* @bug 8062977
* @summary Inference: NullPointerException during bound incorporation
*
* @compile/fail/ref=T8062977.out -XDrawDiagnostics T8062977.java
*/
import java.util.List;
class T8062977 {
<T extends B, B> T m(Class<B> cb) { return null; }
void test1(Class<Iterable<?>> cb) {
List<Integer>[] r1 = m(cb); //fail
List<Integer> r2 = m(cb); //ok
}
void test2(Class<Iterable<?>[]> cb) {
List<Integer>[] r1 = m(cb); //ok
List<Integer> r2 = m(cb); //fail
}
void test3(Class<Iterable<?>[][]> cb) {
List<Integer>[][] r1 = m(cb); //ok
List<Integer>[] r2 = m(cb); //fail
List<Integer> r3 = m(cb); //fail
}
}

@ -0,0 +1,5 @@
T8062977.java:15:31: compiler.err.prob.found.req: (compiler.misc.inferred.do.not.conform.to.upper.bounds: java.util.List<java.lang.Integer>[]&java.lang.Iterable<?>, java.util.List<java.lang.Integer>[],java.lang.Iterable<?>,java.lang.Object)
T8062977.java:21:29: compiler.err.prob.found.req: (compiler.misc.inferred.do.not.conform.to.upper.bounds: java.lang.Iterable<?>[]&java.util.List<java.lang.Integer>, java.util.List<java.lang.Integer>,java.lang.Iterable<?>[],java.lang.Object)
T8062977.java:26:31: compiler.err.prob.found.req: (compiler.misc.inferred.do.not.conform.to.upper.bounds: java.util.List<java.lang.Integer>[], java.util.List<java.lang.Integer>[],java.lang.Iterable<?>[][],java.lang.Object)
T8062977.java:27:29: compiler.err.prob.found.req: (compiler.misc.inferred.do.not.conform.to.upper.bounds: java.lang.Iterable<?>[][]&java.util.List<java.lang.Integer>, java.util.List<java.lang.Integer>,java.lang.Iterable<?>[][],java.lang.Object)
4 errors

@ -35,6 +35,7 @@ import java.net.URI;
import java.util.Arrays;
import javax.tools.Diagnostic;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
@ -206,9 +207,8 @@ public class SamConversionComboTest {
String clientFileStr = clientSourceFile.toString();
System.out.println(clientFileStr.substring(0, clientFileStr.indexOf("\n\n")));
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
DiagnosticChecker dc = new DiagnosticChecker();
JavacTask ct = (JavacTask)tool.getTask(null, null, dc, null, null, Arrays.asList(samSourceFile, clientSourceFile));
JavacTask ct = (JavacTask)comp.getTask(null, fm, dc, null, null, Arrays.asList(samSourceFile, clientSourceFile));
try {
ct.analyze();
} catch (Exception e) {
@ -255,6 +255,9 @@ public class SamConversionComboTest {
ReturnValue returnValue;
static int count = 0;
static JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
static JavaFileManager fm = comp.getStandardFileManager(null, null, null);
SamConversionComboTest(FInterface f, Context c, LambdaBody lb, LambdaKind lk, ReturnValue rv) {
fInterface = f;
context = c;
@ -264,17 +267,21 @@ public class SamConversionComboTest {
}
public static void main(String[] args) throws Exception {
for(Context ct : Context.values()) {
for (FInterface fi : FInterface.values()) {
for (LambdaKind lk: LambdaKind.values()) {
for (LambdaBody lb : LambdaBody.values()) {
for(ReturnValue rv : ReturnValue.values()) {
new SamConversionComboTest(fi, ct, lb, lk, rv).test();
try {
for(Context ct : Context.values()) {
for (FInterface fi : FInterface.values()) {
for (LambdaKind lk: LambdaKind.values()) {
for (LambdaBody lb : LambdaBody.values()) {
for(ReturnValue rv : ReturnValue.values()) {
new SamConversionComboTest(fi, ct, lb, lk, rv).test();
}
}
}
}
}
}
System.out.println("total tests: " + count);
} finally {
fm.close();
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -67,17 +67,23 @@ import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class JavacParserTest extends TestCase {
static final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
static final JavaFileManager fm = tool.getStandardFileManager(null, null, null);
private JavacParserTest(){}
public static void main(String... args) throws Exception {
new JavacParserTest().run(args);
try {
new JavacParserTest().run(args);
} finally {
fm.close();
}
}
class MyFileObject extends SimpleJavaFileObject {
@ -103,7 +109,7 @@ public class JavacParserTest extends TestCase {
CompilationUnitTree getCompilationUnitTree(String code) throws IOException {
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
return cut;
@ -129,7 +135,7 @@ public class JavacParserTest extends TestCase {
String code = "package test; public class Test {public Test() {super();}}";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
SourcePositions pos = Trees.instance(ct).getSourcePositions();
@ -168,7 +174,7 @@ public class JavacParserTest extends TestCase {
final String theString = "public";
String code = "package test; " + theString + " enum Test {A;}";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
SourcePositions pos = Trees.instance(ct).getSourcePositions();
@ -191,7 +197,7 @@ public class JavacParserTest extends TestCase {
"class d {} private void method() { " +
"Object o = " + theString + "; } }";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
SourcePositions pos = Trees.instance(ct).getSourcePositions();
@ -238,7 +244,7 @@ public class JavacParserTest extends TestCase {
final List<Diagnostic<? extends JavaFileObject>> errors =
new LinkedList<Diagnostic<? extends JavaFileObject>>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm,
new DiagnosticListener<JavaFileObject>() {
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
errors.add(diagnostic);
@ -261,7 +267,7 @@ public class JavacParserTest extends TestCase {
String code = "\n@interface Test {}";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
@ -300,7 +306,7 @@ public class JavacParserTest extends TestCase {
final List<Diagnostic<? extends JavaFileObject>> errors =
new LinkedList<Diagnostic<? extends JavaFileObject>>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm,
new DiagnosticListener<JavaFileObject>() {
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
@ -443,7 +449,7 @@ public class JavacParserTest extends TestCase {
final List<Diagnostic<? extends JavaFileObject>> errors =
new LinkedList<Diagnostic<? extends JavaFileObject>>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm,
new DiagnosticListener<JavaFileObject>() {
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
errors.add(diagnostic);
@ -482,7 +488,7 @@ public class JavacParserTest extends TestCase {
String code = "package t; class Test { <T> void t() {} }";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
@ -505,7 +511,7 @@ public class JavacParserTest extends TestCase {
DiagnosticCollector<JavaFileObject> coll =
new DiagnosticCollector<JavaFileObject>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
null, Arrays.asList(new MyFileObject(code)));
ct.parse();
@ -529,7 +535,7 @@ public class JavacParserTest extends TestCase {
"if (name != null) class X {} } }";
DiagnosticCollector<JavaFileObject> coll =
new DiagnosticCollector<JavaFileObject>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
null, Arrays.asList(new MyFileObject(code)));
ct.parse();
@ -552,7 +558,7 @@ public class JavacParserTest extends TestCase {
"if (true) abstract class F {} }}";
DiagnosticCollector<JavaFileObject> coll =
new DiagnosticCollector<JavaFileObject>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
null, Arrays.asList(new MyFileObject(code)));
ct.parse();
@ -575,7 +581,7 @@ public class JavacParserTest extends TestCase {
"if (name != null) interface X {} } }";
DiagnosticCollector<JavaFileObject> coll =
new DiagnosticCollector<JavaFileObject>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
null, Arrays.asList(new MyFileObject(code)));
ct.parse();
@ -598,7 +604,7 @@ public class JavacParserTest extends TestCase {
"if (true) } }";
DiagnosticCollector<JavaFileObject> coll =
new DiagnosticCollector<JavaFileObject>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
null, Arrays.asList(new MyFileObject(code)));
ct.parse();
@ -620,7 +626,7 @@ public class JavacParserTest extends TestCase {
String code = "\nclass Test { { System.err.println(0e); } }";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
null, Arrays.asList(new MyFileObject(code)));
assertNotNull(ct.parse().iterator().next());
@ -820,7 +826,7 @@ public class JavacParserTest extends TestCase {
+ " };\n"
+ " }\n"
+ "}";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null,
null, null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
@ -861,7 +867,7 @@ public class JavacParserTest extends TestCase {
+ " }\n"
+ "}";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null,
null, null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
@ -886,7 +892,7 @@ public class JavacParserTest extends TestCase {
String code = "package t; enum Test { AAA; }";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
@ -905,7 +911,7 @@ public class JavacParserTest extends TestCase {
"}";
DiagnosticCollector<JavaFileObject> coll =
new DiagnosticCollector<>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();

@ -0,0 +1,33 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8063039
* @summary incorrect message reference or broken message file
* @compile/fail/ref=PluginNotFound.out -Xplugin:MissingPlugin PluginNotFound.java
*/
class PluginNotFound { }

@ -0,0 +1,2 @@
error: plug-in not found: MissingPlugin
1 error

@ -24,6 +24,9 @@
/**
* @test
* @bug 8001098 8004961 8004082
* @library /tools/lib
* @build ToolBox
* @run main Test
* @summary Provide a simple light-weight "plug-in" mechanism for javac
*/
@ -58,14 +61,16 @@ public class Test {
final List<String> ref2;
final JavaCompiler compiler;
final StandardJavaFileManager fm;
ToolBox tb = new ToolBox();
Test() throws Exception {
testSrc = new File(System.getProperty("test.src"));
testSrc = new File(tb.testSrc);
pluginSrc = new File(testSrc, "ShowTypePlugin.java");
pluginClasses = new File("plugin");
tb.createDirectories(pluginClasses.toPath());
pluginJar = new File("plugin.jar");
ref1 = readFile(testSrc, "Identifiers.out");
ref2 = readFile(testSrc, "Identifiers_PI.out");
ref1 = tb.readAllLines((new File(testSrc,"Identifiers.out")).toPath());
ref2 = tb.readAllLines((new File(testSrc,"Identifiers_PI.out")).toPath());
compiler = ToolProvider.getSystemJavaCompiler();
fm = compiler.getStandardFileManager(null, null, null);
}
@ -74,11 +79,15 @@ public class Test {
try {
// compile the plugin explicitly, to a non-standard directory
// so that we don't find it on the wrong path by accident
pluginClasses.mkdirs();
compile("-d", pluginClasses.getPath(), pluginSrc.getPath());
writeFile(new File(pluginClasses, "META-INF/services/com.sun.source.util.Plugin"),
"ShowTypePlugin\n");
jar("cf", pluginJar.getPath(), "-C", pluginClasses.getPath(), ".");
tb.new JavacTask()
.options("-d", pluginClasses.getPath())
.files(pluginSrc.getPath())
.run();
File plugin = new File(pluginClasses.getPath(), "META-INF/services/com.sun.source.util.Plugin");
tb.writeFile(plugin.getPath(), "ShowTypePlugin\n");
tb.new JarTask()
.run("cf", pluginJar.getPath(), "-C", pluginClasses.getPath(), ".");
testCommandLine("-Xplugin:showtype", ref1);
testCommandLine("-Xplugin:showtype PI", ref2);
@ -100,14 +109,13 @@ public class Test {
Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(identifiers);
System.err.println("test api: " + options + " " + files);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
boolean ok = compiler.getTask(pw, fm, null, options, null, files).call();
String out = sw.toString();
System.err.println(out);
if (!ok)
error("testCommandLine: compilation failed");
ToolBox.Result result = tb.new JavacTask(ToolBox.Mode.API)
.fileManager(fm)
.options(opt)
.files(identifiers.toPath())
.run(ToolBox.Expect.SUCCESS)
.writeAll();
String out = result.getOutput(ToolBox.OutputKind.DIRECT);
checkOutput(out, ref);
}
@ -120,14 +128,11 @@ public class Test {
identifiers.getPath() };
System.err.println("test command line: " + Arrays.asList(args));
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
int rc = com.sun.tools.javac.Main.compile(args, pw);
String out = sw.toString();
System.err.println(out);
if (rc != 0)
error("testCommandLine: compilation failed");
ToolBox.Result result = tb.new JavacTask(ToolBox.Mode.CMDLINE)
.options(args)
.run(ToolBox.Expect.SUCCESS)
.writeAll();
String out = result.getOutput(ToolBox.OutputKind.DIRECT);
checkOutput(out, ref);
}
@ -140,31 +145,6 @@ public class Test {
}
}
private void compile(String... args) throws Exception {
System.err.println("compile: " + Arrays.asList(args));
int rc = com.sun.tools.javac.Main.compile(args);
if (rc != 0)
throw new Exception("compiled failed, rc=" + rc);
}
private void jar(String... args) throws Exception {
System.err.println("jar: " + Arrays.asList(args));
boolean ok = new sun.tools.jar.Main(System.out, System.err, "jar").run(args);
if (!ok)
throw new Exception("jar failed");
}
private List<String> readFile(File dir, String name) throws IOException {
return Files.readAllLines(new File(dir, name).toPath(), Charset.defaultCharset());
}
private void writeFile(File f, String body) throws IOException {
f.getParentFile().mkdirs();
try (FileWriter out = new FileWriter(f)) {
out.write(body);
}
}
private void error(String msg) {
System.err.println(msg);
errors++;

@ -1,5 +1,5 @@
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -40,6 +40,7 @@ import java.util.List;
import java.util.LinkedList;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
@ -114,13 +115,15 @@ public class TypeAnnotationsPretty {
code + "; }" +
postfix;
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
null, Arrays.asList(new MyFileObject(src)));
try (JavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
null, Arrays.asList(new MyFileObject(src)));
for (CompilationUnitTree cut : ct.parse()) {
JCTree.JCVariableDecl var =
(JCTree.JCVariableDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
checkMatch(code, var);
for (CompilationUnitTree cut : ct.parse()) {
JCTree.JCVariableDecl var =
(JCTree.JCVariableDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
checkMatch(code, var);
}
}
}
@ -129,14 +132,16 @@ public class TypeAnnotationsPretty {
code + "}" +
postfix;
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
null, Arrays.asList(new MyFileObject(src)));
try (JavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
null, Arrays.asList(new MyFileObject(src)));
for (CompilationUnitTree cut : ct.parse()) {
JCTree.JCMethodDecl meth =
(JCTree.JCMethodDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
checkMatch(code, meth);
for (CompilationUnitTree cut : ct.parse()) {
JCTree.JCMethodDecl meth =
(JCTree.JCMethodDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
checkMatch(code, meth);
}
}
}

@ -1475,7 +1475,11 @@ public class ToolBox {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
try {
JarEntry e = new JarEntry(base.relativize(file).toString());
String p = base.relativize(file)
.normalize()
.toString()
.replace(File.separatorChar, '/');
JarEntry e = new JarEntry(p);
jos.putNextEntry(e);
jos.write(Files.readAllBytes(file));
jos.closeEntry();

@ -32,6 +32,7 @@
* @run main Wrapper DependencyCollection
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
@ -55,7 +56,7 @@ import com.sun.tools.sjavac.comp.dependencies.DependencyCollector;
public class DependencyCollection {
public static void main(String[] args) {
public static void main(String[] args) throws IOException {
Path src = Paths.get(ToolBox.testSrc, "test-input", "src");
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();