Cleanup (duplication; dead code; warnings; typos)

This commit is contained in:
Roman Shevchenko
2017-04-13 11:14:27 +02:00
parent d030faf46c
commit 5e55050a49
2 changed files with 93 additions and 149 deletions
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@ package org.jetbrains.jps.incremental;
import com.intellij.execution.CommandLineWrapperUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.Nullable;
@@ -31,7 +30,7 @@ import java.util.jar.Manifest;
/**
* @author Eugene Zhuravlev
* Date: 10/28/11
* @since 28.10.2011
*/
public class ExternalProcessUtil {
private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.ExternalProcessUtil");
@@ -43,31 +42,11 @@ public class ExternalProcessUtil {
try {
aClass = Class.forName("com.intellij.rt.execution.CommandLineWrapper");
}
catch (Throwable ignored) {
}
catch (Throwable ignored) { }
ourWrapperClass = aClass;
}
}
private static final char QUOTE = '\uEFEF';
// please keep in sync with GeneralCommandLine.prepareCommand()
public static String prepareCommand(String parameter) {
if (SystemInfo.isWindows) {
if (parameter.contains("\"")) {
parameter = StringUtil.replace(parameter, "\"", "\\\"");
}
else if (parameter.length() == 0) {
parameter = "\"\"";
}
}
if (parameter.length() >= 2 && parameter.charAt(0) == QUOTE && parameter.charAt(parameter.length() - 1) == QUOTE) {
parameter = '"' + parameter.substring(1, parameter.length() - 1) + '"';
}
return parameter;
}
public static List<String> buildJavaCommandLine(String javaExecutable,
String mainClass,
List<String> bootClasspath,
@@ -78,11 +57,12 @@ public class ExternalProcessUtil {
}
public static List<String> buildJavaCommandLine(String javaExecutable,
String mainClass,
List<String> bootClasspath,
List<String> classpath,
List<String> vmParams,
List<String> programParams, final boolean useCommandLineWrapper) {
String mainClass,
List<String> bootClasspath,
List<String> classpath,
List<String> vmParams,
List<String> programParams,
boolean useCommandLineWrapper) {
return buildJavaCommandLine(javaExecutable, mainClass, bootClasspath, classpath, vmParams, programParams, useCommandLineWrapper, true);
}
@@ -91,14 +71,14 @@ public class ExternalProcessUtil {
List<String> bootClasspath,
List<String> classpath,
List<String> vmParams,
List<String> programParams, final boolean useCommandLineWrapper, boolean useClasspathJar) {
List<String> programParams,
boolean useCommandLineWrapper,
boolean useClasspathJar) {
final List<String> cmdLine = new ArrayList<>();
cmdLine.add(javaExecutable);
for (String param : vmParams) {
cmdLine.add(param);
}
cmdLine.addAll(vmParams);
if (!bootClasspath.isEmpty()) {
cmdLine.add("-bootclasspath");
@@ -108,33 +88,22 @@ public class ExternalProcessUtil {
if (!classpath.isEmpty()) {
List<String> commandLineWrapperArgs = null;
if (useCommandLineWrapper) {
final Class wrapperClass = getCommandLineWrapperClass();
Class wrapperClass = getCommandLineWrapperClass();
if (wrapperClass != null) {
try {
if (useClasspathJar) {
final String classpathFile = CommandLineWrapperUtil.createClasspathJarFile(new Manifest(), classpath).getAbsolutePath();
commandLineWrapperArgs = Arrays.asList(
"-classpath",
classpathFile
);
String classpathFile = CommandLineWrapperUtil.createClasspathJarFile(new Manifest(), classpath).getAbsolutePath();
commandLineWrapperArgs = Arrays.asList("-classpath", classpathFile);
}
else {
File classpathFile = FileUtil.createTempFile("classpath", null);
final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(classpathFile)));
try {
try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(classpathFile)))) {
for (String path : classpath) {
writer.println(path);
}
}
finally {
writer.close();
}
commandLineWrapperArgs = Arrays.asList(
"-classpath",
ClasspathBootstrap.getResourcePath(wrapperClass),
wrapperClass.getName(),
classpathFile.getAbsolutePath()
);
"-classpath", ClasspathBootstrap.getResourcePath(wrapperClass), wrapperClass.getName(), classpathFile.getAbsolutePath());
}
}
catch (IOException ex) {
@@ -159,9 +128,7 @@ public class ExternalProcessUtil {
// main class and params
cmdLine.add(mainClass);
for (String param : programParams) {
cmdLine.add(param);
}
cmdLine.addAll(programParams);
return cmdLine;
}
@@ -170,5 +137,4 @@ public class ExternalProcessUtil {
private static Class getCommandLineWrapperClass() {
return CommandLineWrapperClassHolder.ourWrapperClass;
}
}
}
@@ -52,23 +52,23 @@ import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* @author Eugene Zhuravlev
* Date: 1/22/12
* @since 2.01.2012
*/
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public class ExternalJavacManager {
private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.javac.ExternalJavacServer");
public static final GlobalContextKey<ExternalJavacManager> KEY = GlobalContextKey.create("_external_javac_server_");
public static final GlobalContextKey<ExternalJavacManager> KEY = GlobalContextKey.create("_external_javac_server_");
public static final int DEFAULT_SERVER_PORT = 7878;
public static final String STDOUT_LINE_PREFIX = "JAVAC_PROCESS[STDOUT]";
public static final String STDERR_LINE_PREFIX = "JAVAC_PROCESS[STDERR]";
private static final AttributeKey<JavacProcessDescriptor> SESSION_DESCRIPTOR = AttributeKey.valueOf("ExternalJavacServer.JavacProcessDescriptor");
@NotNull
private final File myWorkingDir;
@NotNull
private final ChannelRegistrar myChannelRegistrar;
private final Map<UUID, JavacProcessDescriptor> myMessageHandlers = new HashMap<>();
private int myListenPort = DEFAULT_SERVER_PORT;
@@ -78,26 +78,24 @@ public class ExternalJavacManager {
myChannelRegistrar = new ChannelRegistrar();
}
@NotNull
public File getWorkingDir() {
return myWorkingDir;
}
public void start(int listenPort) {
final ServerBootstrap bootstrap = new ServerBootstrap().group(new NioEventLoopGroup(1, SharedThreadPool.getInstance())).channel(NioServerSocketChannel.class);
bootstrap.childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);
final ChannelHandler compilationRequestsHandler = new CompilationRequestsHandler();
bootstrap.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(Channel channel) throws Exception {
channel.pipeline().addLast(myChannelRegistrar,
new ProtobufVarint32FrameDecoder(),
new ProtobufDecoder(JavacRemoteProto.Message.getDefaultInstance()),
new ProtobufVarint32LengthFieldPrepender(),
new ProtobufEncoder(),
compilationRequestsHandler);
}
});
final ServerBootstrap bootstrap = new ServerBootstrap()
.group(new NioEventLoopGroup(1, SharedThreadPool.getInstance()))
.channel(NioServerSocketChannel.class)
.childOption(ChannelOption.TCP_NODELAY, true)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(Channel channel) throws Exception {
channel.pipeline().addLast(myChannelRegistrar,
new ProtobufVarint32FrameDecoder(),
new ProtobufDecoder(JavacRemoteProto.Message.getDefaultInstance()),
new ProtobufVarint32LengthFieldPrepender(),
new ProtobufEncoder(),
compilationRequestsHandler);
}
});
try {
final InetAddress loopback = InetAddress.getByName(null);
myChannelRegistrar.add(bootstrap.bind(loopback, listenPort).syncUninterruptibly().channel());
@@ -108,19 +106,23 @@ public class ExternalJavacManager {
}
}
public boolean forkJavac(final String javaHome, final int heapSize, List<String> vmOptions, List<String> options,
public boolean forkJavac(String javaHome,
int heapSize,
List<String> vmOptions,
List<String> options,
Collection<File> platformCp,
Collection<File> classpath,
Collection<File> modulePath,
Collection<File> sourcePath,
Collection<File> files,
Map<File, Set<File>> outs,
final DiagnosticOutputConsumer diagnosticSink, OutputFileConsumer outputSink,
final JavaCompilingTool compilingTool,
final CanceledStatus cancelStatus) {
DiagnosticOutputConsumer diagnosticSink,
OutputFileConsumer outputSink,
JavaCompilingTool compilingTool,
CanceledStatus cancelStatus) {
final ExternalJavacMessageHandler rh = new ExternalJavacMessageHandler(diagnosticSink, outputSink, getEncodingName(options));
final JavacRemoteProto.Message.Request request = JavacProtoUtil.createCompilationRequest(options, files, classpath, platformCp, modulePath, sourcePath, outs);
final JavacRemoteProto.Message.Request request = JavacProtoUtil.createCompilationRequest(
options, files, classpath, platformCp, modulePath, sourcePath, outs);
final UUID uuid = UUID.randomUUID();
final JavacProcessDescriptor processDescriptor = new JavacProcessDescriptor(uuid, rh, request);
synchronized (myMessageHandlers) {
@@ -184,33 +186,29 @@ public class ExternalJavacManager {
@Nullable
private static String getEncodingName(List<String> options) {
boolean found = false;
for (String option : options) {
if (found) {
return option;
}
if ("-encoding".equalsIgnoreCase(option)) {
found = true;
}
}
return null;
int p = options.indexOf("-encoding");
return p >= 0 && p < options.size() - 1 ? options.get(p + 1) : null;
}
public void stop() {
myChannelRegistrar.close().awaitUninterruptibly();
}
private ExternalJavacProcessHandler launchExternalJavacProcess(UUID uuid, String sdkHomePath,
int heapSize,
int port,
File workingDir,
List<String> vmOptions,
JavaCompilingTool compilingTool) throws Exception {
private ExternalJavacProcessHandler launchExternalJavacProcess(UUID uuid,
String sdkHomePath,
int heapSize,
int port,
File workingDir,
List<String> vmOptions,
JavaCompilingTool compilingTool) throws Exception {
final List<String> cmdLine = new ArrayList<>();
appendParam(cmdLine, getVMExecutablePath(sdkHomePath));
appendParam(cmdLine, "-Djava.awt.headless=true");
//appendParam(cmdLine, "-XX:MaxPermSize=150m");
//appendParam(cmdLine, "-XX:ReservedCodeCacheSize=64m");
appendParam(cmdLine, "-Djava.awt.headless=true");
if (heapSize > 0) {
// if the value is zero or negative, use JVM default memory settings
final int xms = heapSize / 2;
@@ -225,26 +223,10 @@ public class ExternalJavacManager {
//appendParam(cmdLine, "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5009");
// javac's VM should use the same default locale that IDEA uses in order for javac to print messages in 'correct' language
final String encoding = System.getProperty("file.encoding");
if (encoding != null) {
appendParam(cmdLine, "-Dfile.encoding=" + encoding);
}
final String lang = System.getProperty("user.language");
if (lang != null) {
//noinspection HardCodedStringLiteral
appendParam(cmdLine, "-Duser.language=" + lang);
}
final String country = System.getProperty("user.country");
if (country != null) {
//noinspection HardCodedStringLiteral
appendParam(cmdLine, "-Duser.country=" + country);
}
//noinspection HardCodedStringLiteral
final String region = System.getProperty("user.region");
if (region != null) {
//noinspection HardCodedStringLiteral
appendParam(cmdLine, "-Duser.region=" + region);
}
copyProperty(cmdLine, "file.encoding");
copyProperty(cmdLine, "user.language");
copyProperty(cmdLine, "user.country");
copyProperty(cmdLine, "user.region");
appendParam(cmdLine, "-D" + ExternalJavacProcess.JPS_JAVA_COMPILING_TOOL_PROPERTY + "=" + compilingTool.getId());
@@ -258,34 +240,23 @@ public class ExternalJavacManager {
}
appendParam(cmdLine, "-classpath");
final List<File> cp = ClasspathBootstrap.getExternalJavacProcessClasspath(sdkHomePath, compilingTool);
final StringBuilder classpath = new StringBuilder();
for (File file : cp) {
if (classpath.length() > 0) {
classpath.append(File.pathSeparator);
}
classpath.append(file.getPath());
}
appendParam(cmdLine, classpath.toString());
List<File> cp = ClasspathBootstrap.getExternalJavacProcessClasspath(sdkHomePath, compilingTool);
appendParam(cmdLine, cp.stream().map(File::getPath).collect(Collectors.joining(File.pathSeparator)));
appendParam(cmdLine, ExternalJavacProcess.class.getName());
appendParam(cmdLine, uuid.toString());
appendParam(cmdLine, "127.0.0.1");
appendParam(cmdLine, Integer.toString(port));
workingDir.mkdirs();
appendParam(cmdLine, FileUtil.toSystemIndependentName(workingDir.getPath()));
if (LOG.isDebugEnabled()) {
LOG.debug("starting external compiler: " + cmdLine);
}
final ProcessBuilder builder = new ProcessBuilder(cmdLine);
builder.directory(workingDir);
FileUtil.createDirectory(workingDir);
final Process process = builder.start();
Process process = new ProcessBuilder(cmdLine).directory(workingDir).start();
return createProcessHandler(process, StringUtil.join(cmdLine, " "));
}
@@ -293,16 +264,23 @@ public class ExternalJavacManager {
return new ExternalJavacProcessHandler(process, commandLine);
}
private static void appendParam(List<String> cmdLine, String param) {
private static void appendParam(List<String> cmdLine, String parameter) {
if (SystemInfo.isWindows) {
if (param.contains("\"")) {
param = StringUtil.replace(param, "\"", "\\\"");
if (parameter.contains("\"")) {
parameter = StringUtil.replace(parameter, "\"", "\\\"");
}
else if (param.length() == 0) {
param = "\"\"";
else if (parameter.length() == 0) {
parameter = "\"\"";
}
}
cmdLine.add(param);
cmdLine.add(parameter);
}
private static void copyProperty(List<String> cmdLine, String name) {
String value = System.getProperty(name);
if (value != null) {
appendParam(cmdLine, "-D" + name + '=' + value);
}
}
private static String getVMExecutablePath(String sdkHome) {
@@ -332,7 +310,7 @@ public class ExternalJavacManager {
private class CompilationRequestsHandler extends SimpleChannelInboundHandler<JavacRemoteProto.Message> {
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
JavacProcessDescriptor descriptor = ctx.channel().attr(SESSION_DESCRIPTOR).getAndRemove();
JavacProcessDescriptor descriptor = ctx.channel().attr(SESSION_DESCRIPTOR).getAndSet(null);
if (descriptor != null) {
descriptor.setDone();
}
@@ -440,15 +418,15 @@ public class ExternalJavacManager {
}
private static class JavacProcessDescriptor {
@NotNull
final UUID sessionId;
@NotNull
final ExternalJavacMessageHandler handler;
volatile JavacRemoteProto.Message.Request request;
volatile Channel channel;
private final UUID sessionId;
private final ExternalJavacMessageHandler handler;
private volatile JavacRemoteProto.Message.Request request;
private volatile Channel channel;
private final Semaphore myDone = new Semaphore();
public JavacProcessDescriptor(@NotNull UUID sessionId, @NotNull ExternalJavacMessageHandler handler, @NotNull JavacRemoteProto.Message.Request request) {
public JavacProcessDescriptor(@NotNull UUID sessionId,
@NotNull ExternalJavacMessageHandler handler,
@NotNull JavacRemoteProto.Message.Request request) {
this.sessionId = sessionId;
this.handler = handler;
this.request = request;