You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by gn...@apache.org on 2022/02/24 16:01:27 UTC
[maven-mvnd] 02/02: Switch a few core plugins to the new api
This is an automated email from the ASF dual-hosted git repository.
gnodet pushed a commit to branch mvn4
in repository https://gitbox.apache.org/repos/asf/maven-mvnd.git
commit 7522fcc2200b56d66234b3a457ced983e0f43470
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Thu Feb 24 17:00:55 2022 +0100
Switch a few core plugins to the new api
---
.../main/java/org/mvndaemon/mvnd/agent/Agent.java | 47 +-
.../org/mvndaemon/mvnd/plugin/doc/DocMojo.java | 150 +-
build/eclipse-formatter-config.xml | 281 ----
.../java/org/mvndaemon/mvnd/client/Client.java | 10 +-
.../java/org/mvndaemon/mvnd/client/Completion.java | 29 +-
.../mvnd/client/DaemonClientConnection.java | 168 ++-
.../org/mvndaemon/mvnd/client/DaemonConnector.java | 621 +++++----
.../mvndaemon/mvnd/client/DaemonDiagnostics.java | 79 +-
.../mvndaemon/mvnd/client/DaemonParameters.java | 674 +++++----
.../org/mvndaemon/mvnd/client/DefaultClient.java | 515 ++++---
.../org/mvndaemon/mvnd/client/ExecutionResult.java | 13 +-
.../mvnd/client/svm/ReflectionRegistration.java | 7 +-
.../client/svm/StaticMDCBinderSubstitution.java | 8 +-
.../mvnd/client/CompletionGeneratorTest.java | 62 +-
.../mvndaemon/mvnd/client/DaemonConnectorTest.java | 10 +-
.../org/mvndaemon/mvnd/client/EnvironmentTest.java | 149 +-
.../org/mvndaemon/mvnd/client/OsUtilsTest.java | 10 +-
.../org/mvndaemon/mvnd/common/BufferCaster.java | 11 +-
.../org/mvndaemon/mvnd/common/BuildProperties.java | 43 +-
.../mvndaemon/mvnd/common/ByteChannelWrapper.java | 22 +-
.../mvnd/common/DaemonCompatibilitySpec.java | 82 +-
.../mvndaemon/mvnd/common/DaemonConnection.java | 284 ++--
.../org/mvndaemon/mvnd/common/DaemonException.java | 97 +-
.../mvnd/common/DaemonExpirationStatus.java | 3 +-
.../java/org/mvndaemon/mvnd/common/DaemonInfo.java | 89 +-
.../org/mvndaemon/mvnd/common/DaemonRegistry.java | 334 +++--
.../org/mvndaemon/mvnd/common/DaemonState.java | 3 +-
.../org/mvndaemon/mvnd/common/DaemonStopEvent.java | 41 +-
.../org/mvndaemon/mvnd/common/Environment.java | 427 +++---
.../java/org/mvndaemon/mvnd/common/IoUtils.java | 27 +-
.../org/mvndaemon/mvnd/common/JavaVersion.java | 11 +-
.../org/mvndaemon/mvnd/common/MavenDaemon.java | 94 +-
.../java/org/mvndaemon/mvnd/common/Message.java | 903 +++++++-----
.../java/org/mvndaemon/mvnd/common/OptionType.java | 38 +-
.../main/java/org/mvndaemon/mvnd/common/Os.java | 59 +-
.../java/org/mvndaemon/mvnd/common/OsUtils.java | 212 ++-
.../org/mvndaemon/mvnd/common/ProcessHelper.java | 6 +-
.../org/mvndaemon/mvnd/common/SocketFamily.java | 150 +-
.../org/mvndaemon/mvnd/common/SocketHelper.java | 18 +-
.../java/org/mvndaemon/mvnd/common/TimeUtils.java | 103 +-
.../mvnd/common/logging/ClientOutput.java | 13 +-
.../mvnd/common/logging/TerminalOutput.java | 901 +++++++-----
.../mvndaemon/mvnd/common/DaemonRegistryTest.java | 99 +-
.../org/mvndaemon/mvnd/common/MessageTest.java | 52 +-
.../org/mvndaemon/mvnd/common/OsUtilsTest.java | 19 +-
.../mvndaemon/mvnd/common/SocketFamilyTest.java | 56 +-
.../org/mvndaemon/mvnd/common/TimeUtilsTest.java | 28 +-
.../java/org/apache/maven/cli/DaemonMavenCli.java | 1452 ++++++++++++--------
.../org/apache/maven/cli/MvndHelpFormatter.java | 197 +--
.../maven/graph/DefaultProjectDependencyGraph.java | 126 +-
.../maven/lifecycle/internal/MojoExecutor.java | 372 +++--
.../maven/project/CachingProjectBuilder.java | 850 +++++++-----
.../apache/maven/project/SnapshotModelCache.java | 21 +-
.../mvndaemon/mvnd/builder/DependencyGraph.java | 297 ++--
.../mvndaemon/mvnd/builder/ProjectComparator.java | 91 +-
.../mvnd/builder/ProjectExecutorService.java | 70 +-
.../mvndaemon/mvnd/builder/ReactorBuildQueue.java | 78 +-
.../mvndaemon/mvnd/builder/ReactorBuildStats.java | 181 ++-
.../org/mvndaemon/mvnd/builder/SmartBuilder.java | 102 +-
.../mvndaemon/mvnd/builder/SmartBuilderImpl.java | 148 +-
.../main/java/org/mvndaemon/mvnd/cache/Cache.java | 13 +-
.../org/mvndaemon/mvnd/cache/CacheFactory.java | 3 +-
.../java/org/mvndaemon/mvnd/cache/CacheRecord.java | 3 +-
.../mvnd/cache/impl/DefaultCacheFactory.java | 11 +-
.../mvnd/cache/impl/TimestampCacheFactory.java | 141 +-
.../mvnd/cache/impl/WatchServiceCacheFactory.java | 237 ++--
.../InvalidatingExtensionRealmCache.java | 53 +-
.../InvalidatingPluginArtifactsCache.java | 65 +-
.../InvalidatingPluginDescriptorCache.java | 103 +-
.../invalidating/InvalidatingPluginRealmCache.java | 93 +-
.../InvalidatingProjectArtifactsCache.java | 176 ++-
.../InvalidatingRealmCacheEventSpy.java | 158 ++-
.../java/org/mvndaemon/mvnd/cli/EnvHelper.java | 200 +--
.../mvndaemon/mvnd/daemon/ClientDispatcher.java | 145 +-
.../java/org/mvndaemon/mvnd/daemon/Connection.java | 17 +-
.../mvndaemon/mvnd/daemon/DaemonExpiration.java | 343 +++--
.../mvndaemon/mvnd/daemon/DaemonMemoryStatus.java | 153 ++-
.../java/org/mvndaemon/mvnd/daemon/Server.java | 717 ++++++----
.../mvnd/interactivity/DaemonPrompter.java | 191 ++-
.../logging/internal/MvndSlf4jConfiguration.java | 10 +-
.../mvnd/logging/internal/SimpleAppender.java | 45 +-
.../mvnd/logging/internal/Slf4jLogger.java | 91 +-
.../mvnd/logging/internal/Slf4jLoggerManager.java | 38 +-
.../mvnd/logging/smart/BuildEventListener.java | 63 +-
.../logging/smart/LoggingExecutionListener.java | 179 ++-
.../mvnd/logging/smart/LoggingOutputStream.java | 78 +-
.../logging/smart/ProjectBuildLogAppender.java | 115 +-
.../mvnd/plugin/CachingPluginVersionResolver.java | 56 +-
.../mvnd/plugin/CliMavenPluginManager.java | 785 ++++++-----
.../plugin/ValidatingConfigurationListener.java | 48 +-
.../mvnd/sync/MvndSyncContextFactory.java | 137 +-
.../mvndaemon/mvnd/timing/BuildTimeEventSpy.java | 178 ++-
.../mvnd/transfer/DaemonMavenTransferListener.java | 48 +-
.../mvnd/builder/AbstractSmartBuilderTest.java | 18 +-
.../org/mvndaemon/mvnd/builder/DagWidthTest.java | 253 ++--
.../mvnd/builder/ProjectComparatorTest.java | 63 +-
.../mvnd/builder/ProjectExecutorServiceTest.java | 101 +-
.../mvnd/builder/ReactorBuildQueueTest.java | 66 +-
.../mvnd/builder/TestProjectDependencyGraph.java | 43 +-
.../mvnd/cache/impl/CacheFactoryTest.java | 105 +-
.../java/org/mvndaemon/mvnd/cli/EnvHelperTest.java | 58 +-
.../mvnd/daemon/ClientDispatcherTest.java | 21 +-
.../java/org/mvndaemon/mvnd/daemon/ServerTest.java | 26 +-
.../java/org/mvndaemon/mvnd/pump/AgentHelper.java | 9 +-
.../mvnd/assertj/MatchInOrderAmongOthers.java | 48 +-
.../mvndaemon/mvnd/assertj/TestClientOutput.java | 50 +-
.../mvnd/it/AttachedArtifactResolutionTest.java | 10 +-
.../org/mvndaemon/mvnd/it/BootstrapPluginTest.java | 43 +-
.../org/mvndaemon/mvnd/it/CompletionNativeIT.java | 19 +-
.../java/org/mvndaemon/mvnd/it/CompletionTest.java | 5 +-
.../mvndaemon/mvnd/it/ConcurrentDownloadsTest.java | 34 +-
.../org/mvndaemon/mvnd/it/DaemonCrashTest.java | 34 +-
.../org/mvndaemon/mvnd/it/DeleteRepoNativeIT.java | 29 +-
.../java/org/mvndaemon/mvnd/it/DeleteRepoTest.java | 5 +-
.../test/java/org/mvndaemon/mvnd/it/DistroIT.java | 133 +-
.../test/java/org/mvndaemon/mvnd/it/DupGATest.java | 10 +-
.../org/mvndaemon/mvnd/it/EnvironmentTest.java | 44 +-
.../java/org/mvndaemon/mvnd/it/ExecOutputTest.java | 14 +-
.../org/mvndaemon/mvnd/it/ExtensionsNativeIT.java | 33 +-
.../java/org/mvndaemon/mvnd/it/ExtensionsTest.java | 5 +-
.../java/org/mvndaemon/mvnd/it/ForkedTest.java | 14 +-
.../org/mvndaemon/mvnd/it/InteractiveTest.java | 32 +-
.../org/mvndaemon/mvnd/it/InvokerNativeIT.java | 52 +-
.../java/org/mvndaemon/mvnd/it/InvokerTest.java | 5 +-
.../org/mvndaemon/mvnd/it/JUnitPlatformTest.java | 23 +-
.../org/mvndaemon/mvnd/it/JvmConfigNativeIT.java | 18 +-
.../org/mvndaemon/mvnd/it/MavenConfNativeIT.java | 18 +-
.../java/org/mvndaemon/mvnd/it/MavenConfTest.java | 18 +-
.../mvndaemon/mvnd/it/ModuleAndPluginNativeIT.java | 68 +-
.../org/mvndaemon/mvnd/it/ModuleAndPluginTest.java | 5 +-
.../org/mvndaemon/mvnd/it/MultiLookupTest.java | 20 +-
.../org/mvndaemon/mvnd/it/MultiModuleTest.java | 88 +-
.../java/org/mvndaemon/mvnd/it/MvndTestUtil.java | 34 +-
.../mvnd/it/NewManagedModuleNativeIT.java | 71 +-
.../mvndaemon/mvnd/it/NewManagedModuleTest.java | 5 +-
.../java/org/mvndaemon/mvnd/it/RawStreamsTest.java | 29 +-
.../mvndaemon/mvnd/it/ResidentExtensionsTest.java | 45 +-
.../mvndaemon/mvnd/it/SingleModuleNativeIT.java | 66 +-
.../org/mvndaemon/mvnd/it/SingleModuleTest.java | 39 +-
.../mvndaemon/mvnd/it/SpecificFileNativeIT.java | 25 +-
.../org/mvndaemon/mvnd/it/SpecificFileTest.java | 9 +-
.../java/org/mvndaemon/mvnd/it/StopStatusTest.java | 47 +-
.../mvndaemon/mvnd/it/ThreadOptionNativeIT.java | 43 +-
.../org/mvndaemon/mvnd/it/ThreadOptionTest.java | 8 +-
.../org/mvndaemon/mvnd/it/TypeDescriptionTest.java | 10 +-
.../mvndaemon/mvnd/it/UpgradesInBomNativeIT.java | 61 +-
.../org/mvndaemon/mvnd/it/UpgradesInBomTest.java | 5 +-
.../org/mvndaemon/mvnd/it/VersionNativeIT.java | 23 +-
.../java/org/mvndaemon/mvnd/it/VersionTest.java | 9 +-
.../org/mvndaemon/mvnd/junit/ClientFactory.java | 6 +-
.../org/mvndaemon/mvnd/junit/JvmTestClient.java | 78 +-
.../org/mvndaemon/mvnd/junit/MvndNativeTest.java | 9 +-
.../java/org/mvndaemon/mvnd/junit/MvndTest.java | 10 +-
.../mvndaemon/mvnd/junit/MvndTestExtension.java | 344 +++--
.../org/mvndaemon/mvnd/junit/NativeTestClient.java | 141 +-
.../org/mvndaemon/mvnd/junit/TestParameters.java | 48 +-
.../org/mvndaemon/mvnd/junit/TestRegistry.java | 63 +-
.../java/org/mvndaemon/mvnd/junit/TestUtils.java | 71 +-
.../java/org/mvndaemon/mvnd/nativ/CLibrary.java | 14 +-
.../org/mvndaemon/mvnd/nativ/MvndNativeLoader.java | 344 +++--
.../main/java/org/mvndaemon/mvnd/nativ/OSInfo.java | 218 +--
.../org/mvndaemon/mvnd/nativ/CLibraryTest.java | 28 +-
.../mvndaemon/mvnd/nativ/MvndNativeLoaderTest.java | 6 +-
pom.xml | 2 +-
.../java/org/mvndaemon/mvnd/sync/IpcClient.java | 459 ++++---
.../java/org/mvndaemon/mvnd/sync/IpcMessages.java | 3 +-
.../java/org/mvndaemon/mvnd/sync/IpcServer.java | 450 +++---
.../org/mvndaemon/mvnd/sync/IpcSyncContext.java | 62 +-
.../mvndaemon/mvnd/sync/IpcSyncContextFactory.java | 30 +-
.../mvndaemon/mvnd/sync/IpcSyncContextTest.java | 132 +-
170 files changed, 12113 insertions(+), 8310 deletions(-)
diff --git a/agent/src/main/java/org/mvndaemon/mvnd/agent/Agent.java b/agent/src/main/java/org/mvndaemon/mvnd/agent/Agent.java
index 3c33984..67190f3 100644
--- a/agent/src/main/java/org/mvndaemon/mvnd/agent/Agent.java
+++ b/agent/src/main/java/org/mvndaemon/mvnd/agent/Agent.java
@@ -22,7 +22,8 @@ import java.security.ProtectionDomain;
import javassist.ClassPool;
import javassist.CtClass;
-public class Agent {
+public class Agent
+{
public static final String START_WITH_PIPES = "if (redirects != null\n"
+ " && redirects[1] == ProcessBuilder$Redirect.INHERIT\n"
@@ -34,31 +35,43 @@ public class Agent {
+ " return p;\n"
+ "}";
- public static void premain(String args, Instrumentation instrumentation) throws Exception {
- instrumentation.addTransformer(new ClassFileTransformer() {
+ public static void premain( String args, Instrumentation instrumentation ) throws Exception
+ {
+ instrumentation.addTransformer( new ClassFileTransformer()
+ {
+
@Override
- public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
- ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
- if ("java/lang/ProcessBuilder".equals(className)) {
- try {
+ public byte[] transform( ClassLoader loader, String className, Class<?> classBeingRedefined,
+ ProtectionDomain protectionDomain, byte[] classfileBuffer ) throws IllegalClassFormatException
+ {
+ if ( "java/lang/ProcessBuilder".equals( className ) )
+ {
+ try
+ {
ClassPool pool = ClassPool.getDefault();
- CtClass clazz = pool.get("java.lang.ProcessBuilder");
- pool.importPackage("org.mvndaemon.mvnd.pump");
- clazz.getDeclaredMethod("start",
- new CtClass[] { clazz.getClassPool().get("java.lang.ProcessBuilder$Redirect[]") })
- .insertBefore(START_WITH_PIPES);
+ CtClass clazz = pool.get( "java.lang.ProcessBuilder" );
+ pool.importPackage( "org.mvndaemon.mvnd.pump" );
+ clazz.getDeclaredMethod( "start",
+ new CtClass[]
+ { clazz.getClassPool().get( "java.lang.ProcessBuilder$Redirect[]" )
+ } )
+ .insertBefore( START_WITH_PIPES );
byte[] data = clazz.toBytecode();
clazz.detach();
return data;
- } catch (Throwable e) {
- System.err.println(e);
- throw new IllegalClassFormatException(e.toString());
}
- } else {
+ catch ( Throwable e )
+ {
+ System.err.println( e );
+ throw new IllegalClassFormatException( e.toString() );
+ }
+ }
+ else
+ {
return classfileBuffer;
}
}
- });
+ } );
}
}
diff --git a/build-plugin/src/main/java/org/mvndaemon/mvnd/plugin/doc/DocMojo.java b/build-plugin/src/main/java/org/mvndaemon/mvnd/plugin/doc/DocMojo.java
index 46285f3..342e13c 100644
--- a/build-plugin/src/main/java/org/mvndaemon/mvnd/plugin/doc/DocMojo.java
+++ b/build-plugin/src/main/java/org/mvndaemon/mvnd/plugin/doc/DocMojo.java
@@ -46,135 +46,169 @@ import org.jboss.forge.roaster.model.source.JavaEnumSource;
/**
* Extracts JavaDoc blocks from enum entries and stores them into a properties file.
*/
-@Mojo(name = "doc", defaultPhase = LifecyclePhase.NONE, threadSafe = true, requiresProject = true, requiresDependencyResolution = ResolutionScope.NONE)
-public class DocMojo extends AbstractMojo {
+@Mojo( name = "doc", defaultPhase = LifecyclePhase.NONE, threadSafe = true, requiresProject = true, requiresDependencyResolution = ResolutionScope.NONE )
+public class DocMojo extends AbstractMojo
+{
/**
* The current project's <code>${basedir}</code>
*/
- @Parameter(readonly = true, defaultValue = "${project.basedir}")
+ @Parameter( readonly = true, defaultValue = "${project.basedir}" )
File baseDir;
/** A list of fully qualified enum names to process */
- @Parameter(defaultValue = "org.mvndaemon.mvnd.common.Environment,org.mvndaemon.mvnd.common.OptionType")
+ @Parameter( defaultValue = "org.mvndaemon.mvnd.common.Environment,org.mvndaemon.mvnd.common.OptionType" )
String[] enums;
/** If {@code true} the execution of this mojo will be skipped altogether; otherwise this mojo will be executed. */
- @Parameter(defaultValue = "false", property = "mvnd.build.doc.skip")
+ @Parameter( defaultValue = "false", property = "mvnd.build.doc.skip" )
boolean skip;
@Override
- public void execute() throws MojoExecutionException, MojoFailureException {
+ public void execute() throws MojoExecutionException, MojoFailureException
+ {
final Log log = getLog();
- if (skip) {
- log.info(getClass().getSimpleName() + " skipped per skip parameter");
+ if ( skip )
+ {
+ log.info( getClass().getSimpleName() + " skipped per skip parameter" );
return;
}
final Path basePath = baseDir.toPath();
- for (String enumClassName : enums) {
- extractEnumJavaDoc(basePath, enumClassName);
+ for ( String enumClassName : enums )
+ {
+ extractEnumJavaDoc( basePath, enumClassName );
}
}
- static void extractEnumJavaDoc(Path basePath, String enumClassName) throws MojoFailureException {
- final String classRelPath = enumClassName.replace('.', '/');
- final Path enumClassLocation = basePath.resolve("src/main/java")
- .resolve(classRelPath + ".java");
- final Path propsPath = basePath.resolve("target/classes/" + classRelPath + ".javadoc.properties");
- try {
- Files.createDirectories(propsPath.getParent());
- } catch (IOException e) {
- throw new IllegalStateException("Could not create " + propsPath.getParent(), e);
+ static void extractEnumJavaDoc( Path basePath, String enumClassName ) throws MojoFailureException
+ {
+ final String classRelPath = enumClassName.replace( '.', '/' );
+ final Path enumClassLocation = basePath.resolve( "src/main/java" )
+ .resolve( classRelPath + ".java" );
+ final Path propsPath = basePath.resolve( "target/classes/" + classRelPath + ".javadoc.properties" );
+ try
+ {
+ Files.createDirectories( propsPath.getParent() );
+ }
+ catch ( IOException e )
+ {
+ throw new IllegalStateException( "Could not create " + propsPath.getParent(), e );
}
- if (!Files.isRegularFile(enumClassLocation)) {
- throw new IllegalStateException(enumClassLocation + " does not exist: ");
+ if ( !Files.isRegularFile( enumClassLocation ) )
+ {
+ throw new IllegalStateException( enumClassLocation + " does not exist: " );
}
- try {
- final JavaEnumSource source = Roaster.parse(JavaEnumSource.class, enumClassLocation.toFile());
+ try
+ {
+ final JavaEnumSource source = Roaster.parse( JavaEnumSource.class, enumClassLocation.toFile() );
final Properties optionsProperties = new SortedProperties();
- for (EnumConstantSource enumConst : source.getEnumConstants()) {
+ for ( EnumConstantSource enumConst : source.getEnumConstants() )
+ {
final JavaDocSource<EnumConstantSource> javaDoc = enumConst.getJavaDoc();
final String javadocText = javaDoc.getText()
- .replaceAll("/", "/");
- optionsProperties.setProperty(enumConst.getName(), javadocText);
+ .replaceAll( "/", "/" );
+ optionsProperties.setProperty( enumConst.getName(), javadocText );
}
- optionsProperties.store(Files.newOutputStream(propsPath), null);
- } catch (IOException e) {
- throw new MojoFailureException("Could not parse " + enumClassLocation, e);
+ optionsProperties.store( Files.newOutputStream( propsPath ), null );
+ }
+ catch ( IOException e )
+ {
+ throw new MojoFailureException( "Could not parse " + enumClassLocation, e );
}
}
/**
* A {@link Properties} with a binarily reproducible {@code store()} operation.
*/
- static class SortedProperties extends Properties {
+ static class SortedProperties extends Properties
+ {
+
private static final long serialVersionUID = 5983297690254771479L;
@Override
- public synchronized Enumeration<Object> keys() {
- final Iterator<Object> it = new TreeSet<>(keySet()).iterator();
- return new Enumeration<Object>() {
- public boolean hasMoreElements() {
+ public synchronized Enumeration<Object> keys()
+ {
+ final Iterator<Object> it = new TreeSet<>( keySet() ).iterator();
+ return new Enumeration<Object>()
+ {
+
+ public boolean hasMoreElements()
+ {
return it.hasNext();
}
- public Object nextElement() {
+ public Object nextElement()
+ {
return it.next();
}
};
}
- public Set<Map.Entry<Object, Object>> entrySet() {
- Comparator<Map.Entry<Object, Object>> comparator = Comparator.comparing(e -> (Comparable) e.getKey());
- final Set<Map.Entry<Object, Object>> result = new TreeSet<>(comparator);
- result.addAll(super.entrySet());
+ public Set<Map.Entry<Object, Object>> entrySet()
+ {
+ Comparator<Map.Entry<Object, Object>> comparator = Comparator.comparing( e -> ( Comparable ) e.getKey() );
+ final Set<Map.Entry<Object, Object>> result = new TreeSet<>( comparator );
+ result.addAll( super.entrySet() );
return result;
}
@Override
- public void store(Writer writer, String comments)
- throws IOException {
- super.store(new SkipFirstLineBufferedWriter(writer), null);
+ public void store( Writer writer, String comments )
+ throws IOException
+ {
+ super.store( new SkipFirstLineBufferedWriter( writer ), null );
}
@Override
- public void store(OutputStream out, String comments)
- throws IOException {
- this.store(new OutputStreamWriter(out, "8859_1"), comments);
+ public void store( OutputStream out, String comments )
+ throws IOException
+ {
+ this.store( new OutputStreamWriter( out, "8859_1" ), comments );
}
- static class SkipFirstLineBufferedWriter extends BufferedWriter {
+ static class SkipFirstLineBufferedWriter extends BufferedWriter
+ {
+
private boolean firstLine = true;
- public SkipFirstLineBufferedWriter(Writer out) {
- super(out);
+ public SkipFirstLineBufferedWriter( Writer out )
+ {
+ super( out );
}
@Override
- public void newLine() throws IOException {
- if (firstLine) {
+ public void newLine() throws IOException
+ {
+ if ( firstLine )
+ {
firstLine = false;
- } else {
- write('\n');
+ }
+ else
+ {
+ write( '\n' );
}
}
@Override
- public void write(String s, int off, int len) throws IOException {
- if (!firstLine) {
- super.write(s, off, len);
+ public void write( String s, int off, int len ) throws IOException
+ {
+ if ( !firstLine )
+ {
+ super.write( s, off, len );
}
}
@Override
- public void write(char cbuf[], int off, int len) throws IOException {
- if (!firstLine) {
- super.write(cbuf, off, len);
+ public void write( char cbuf[], int off, int len ) throws IOException
+ {
+ if ( !firstLine )
+ {
+ super.write( cbuf, off, len );
}
}
diff --git a/build/eclipse-formatter-config.xml b/build/eclipse-formatter-config.xml
deleted file mode 100644
index 330afe8..0000000
--- a/build/eclipse-formatter-config.xml
+++ /dev/null
@@ -1,281 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-
--->
-<profiles version="8">
- <profile name="Camel Java Conventions" version="8" kind="CodeFormatterProfile">
- <setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="end_of_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="end_of_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="end_of_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="end_of_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="end_of_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="end_of_line"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.align_tags_names_descriptions" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.align_tags_descriptions_grouped" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.format_comments" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.indent_return_description" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="120"/>
- <setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/>
- <setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/>
- <setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.indentation.size" value="8"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_enum_constant" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.lineSplit" value="128"/>
- <setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/>
- <setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>
- <setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/>
- <setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="CHECKSTYLE:OFF"/>
- <setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="CHECKSTYLE:ON"/>
- </profile>
-</profiles>
diff --git a/client/src/main/java/org/mvndaemon/mvnd/client/Client.java b/client/src/main/java/org/mvndaemon/mvnd/client/Client.java
index 34b79b0..c5337fe 100644
--- a/client/src/main/java/org/mvndaemon/mvnd/client/Client.java
+++ b/client/src/main/java/org/mvndaemon/mvnd/client/Client.java
@@ -19,12 +19,14 @@ import java.util.Arrays;
import java.util.List;
import org.mvndaemon.mvnd.common.logging.ClientOutput;
-public interface Client {
+public interface Client
+{
- ExecutionResult execute(ClientOutput output, List<String> args) throws InterruptedException;
+ ExecutionResult execute( ClientOutput output, List<String> args ) throws InterruptedException;
- default ExecutionResult execute(ClientOutput output, String... args) throws InterruptedException {
- return execute(output, Arrays.asList(args));
+ default ExecutionResult execute( ClientOutput output, String... args ) throws InterruptedException
+ {
+ return execute( output, Arrays.asList( args ) );
}
}
diff --git a/client/src/main/java/org/mvndaemon/mvnd/client/Completion.java b/client/src/main/java/org/mvndaemon/mvnd/client/Completion.java
index 765e5e4..00c24d3 100644
--- a/client/src/main/java/org/mvndaemon/mvnd/client/Completion.java
+++ b/client/src/main/java/org/mvndaemon/mvnd/client/Completion.java
@@ -21,20 +21,27 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
-public class Completion {
+public class Completion
+{
- public static String getCompletion(String shell, DaemonParameters daemonParameters) {
- if (!"bash".equals(shell)) {
- throw new IllegalArgumentException("Unexpected --completion value: '" + shell + "'; expected: 'bash'");
+ public static String getCompletion( String shell, DaemonParameters daemonParameters )
+ {
+ if ( !"bash".equals( shell ) )
+ {
+ throw new IllegalArgumentException( "Unexpected --completion value: '" + shell + "'; expected: 'bash'" );
}
- final Path bashCompletionPath = daemonParameters.mvndHome().resolve("bin/mvnd-bash-completion.bash");
- if (!Files.isRegularFile(bashCompletionPath)) {
- throw new IllegalStateException("Bash completion file does not exist: " + bashCompletionPath);
+ final Path bashCompletionPath = daemonParameters.mvndHome().resolve( "bin/mvnd-bash-completion.bash" );
+ if ( !Files.isRegularFile( bashCompletionPath ) )
+ {
+ throw new IllegalStateException( "Bash completion file does not exist: " + bashCompletionPath );
}
- try {
- return new String(Files.readAllBytes(bashCompletionPath), StandardCharsets.UTF_8);
- } catch (IOException e) {
- throw new UncheckedIOException("Could not read " + bashCompletionPath, e);
+ try
+ {
+ return new String( Files.readAllBytes( bashCompletionPath ), StandardCharsets.UTF_8 );
+ }
+ catch ( IOException e )
+ {
+ throw new UncheckedIOException( "Could not read " + bashCompletionPath, e );
}
}
diff --git a/client/src/main/java/org/mvndaemon/mvnd/client/DaemonClientConnection.java b/client/src/main/java/org/mvndaemon/mvnd/client/DaemonClientConnection.java
index 210fbbd..858a455 100644
--- a/client/src/main/java/org/mvndaemon/mvnd/client/DaemonClientConnection.java
+++ b/client/src/main/java/org/mvndaemon/mvnd/client/DaemonClientConnection.java
@@ -39,9 +39,10 @@ import org.slf4j.LoggerFactory;
* File origin:
* https://github.com/gradle/gradle/blob/v5.6.2/subprojects/launcher/src/main/java/org/gradle/launcher/daemon/client/DaemonClientConnection.java
*/
-public class DaemonClientConnection implements Closeable {
+public class DaemonClientConnection implements Closeable
+{
- private final static Logger LOG = LoggerFactory.getLogger(DaemonClientConnection.class);
+ private final static Logger LOG = LoggerFactory.getLogger( DaemonClientConnection.class );
private final DaemonConnection connection;
private final DaemonInfo daemon;
@@ -49,127 +50,170 @@ public class DaemonClientConnection implements Closeable {
private final boolean newDaemon;
private boolean hasReceived;
private final Lock dispatchLock = new ReentrantLock();
- private final BlockingQueue<Message> queue = new ArrayBlockingQueue<>(16);
+ private final BlockingQueue<Message> queue = new ArrayBlockingQueue<>( 16 );
private final Thread receiver;
- private final AtomicBoolean running = new AtomicBoolean(true);
+ private final AtomicBoolean running = new AtomicBoolean( true );
private final AtomicReference<Exception> exception = new AtomicReference<>();
private final long maxKeepAliveMs;
private final DaemonParameters parameters;
- public DaemonClientConnection(DaemonConnection connection, DaemonInfo daemon,
- StaleAddressDetector staleAddressDetector, boolean newDaemon, DaemonParameters parameters) {
+ public DaemonClientConnection( DaemonConnection connection, DaemonInfo daemon,
+ StaleAddressDetector staleAddressDetector, boolean newDaemon, DaemonParameters parameters )
+ {
this.connection = connection;
this.daemon = daemon;
this.staleAddressDetector = staleAddressDetector;
this.newDaemon = newDaemon;
- this.receiver = new Thread(this::doReceive);
+ this.receiver = new Thread( this::doReceive );
this.receiver.start();
this.parameters = parameters;
this.maxKeepAliveMs = parameters.keepAlive().toMillis() * parameters.maxLostKeepAlive();
}
- public DaemonInfo getDaemon() {
+ public DaemonInfo getDaemon()
+ {
return daemon;
}
- public void dispatch(Message message) throws DaemonException.ConnectException {
- LOG.debug("thread {}: dispatching {}", Thread.currentThread().getId(), message.getClass());
- try {
+ public void dispatch( Message message ) throws DaemonException.ConnectException
+ {
+ LOG.debug( "thread {}: dispatching {}", Thread.currentThread().getId(), message.getClass() );
+ try
+ {
dispatchLock.lock();
- try {
- connection.dispatch(message);
+ try
+ {
+ connection.dispatch( message );
connection.flush();
- } finally {
+ }
+ finally
+ {
dispatchLock.unlock();
}
- } catch (DaemonException.MessageIOException e) {
- LOG.debug("Problem dispatching message to the daemon. Performing 'on failure' operation...");
- if (!hasReceived && staleAddressDetector.maybeStaleAddress(e)) {
- throw new DaemonException.StaleAddressException("Could not dispatch a message to the daemon.", e);
+ }
+ catch ( DaemonException.MessageIOException e )
+ {
+ LOG.debug( "Problem dispatching message to the daemon. Performing 'on failure' operation..." );
+ if ( !hasReceived && staleAddressDetector.maybeStaleAddress( e ) )
+ {
+ throw new DaemonException.StaleAddressException( "Could not dispatch a message to the daemon.", e );
}
- throw new DaemonException.ConnectException("Could not dispatch a message to the daemon.", e);
+ throw new DaemonException.ConnectException( "Could not dispatch a message to the daemon.", e );
}
// in case we dispatch a cancelation request, also forward it to the main thread to exit asap
- try {
- if (message.getType() == Message.CANCEL_BUILD) {
- queue.put(message);
+ try
+ {
+ if ( message.getType() == Message.CANCEL_BUILD )
+ {
+ queue.put( message );
}
- } catch (InterruptedException e) {
- throw new DaemonException.InterruptedException(e);
+ }
+ catch ( InterruptedException e )
+ {
+ throw new DaemonException.InterruptedException( e );
}
}
- public List<Message> receive() throws ConnectException, StaleAddressException {
- while (true) {
- try {
- final Message m = queue.poll(maxKeepAliveMs, TimeUnit.MILLISECONDS);
+ public List<Message> receive() throws ConnectException, StaleAddressException
+ {
+ while ( true )
+ {
+ try
+ {
+ final Message m = queue.poll( maxKeepAliveMs, TimeUnit.MILLISECONDS );
{
Exception e = exception.get();
- if (e != null) {
+ if ( e != null )
+ {
throw e;
- } else if (m == null) {
- throw new IOException("No message received within " + maxKeepAliveMs
- + "ms, daemon may have crashed. You may want to check its status using mvnd --status");
+ }
+ else if ( m == null )
+ {
+ throw new IOException( "No message received within " + maxKeepAliveMs
+ + "ms, daemon may have crashed. You may want to check its status using mvnd --status" );
}
}
- final List<Message> result = new ArrayList<>(4);
- result.add(m);
- queue.drainTo(result);
+ final List<Message> result = new ArrayList<>( 4 );
+ result.add( m );
+ queue.drainTo( result );
Exception e = exception.get();
- if (e != null) {
+ if ( e != null )
+ {
throw e;
}
return result;
- } catch (Exception e) {
- DaemonDiagnostics diag = new DaemonDiagnostics(daemon.getId(), parameters);
- LOG.debug("Problem receiving message to the daemon. Performing 'on failure' operation...");
- if (!hasReceived && newDaemon) {
- throw new ConnectException("Could not receive a message from the daemon.\n" + diag.describe(), e);
- } else if (staleAddressDetector.maybeStaleAddress(e)) {
- throw new StaleAddressException("Could not receive a message from the daemon.\n" + diag.describe(), e);
+ }
+ catch ( Exception e )
+ {
+ DaemonDiagnostics diag = new DaemonDiagnostics( daemon.getId(), parameters );
+ LOG.debug( "Problem receiving message to the daemon. Performing 'on failure' operation..." );
+ if ( !hasReceived && newDaemon )
+ {
+ throw new ConnectException( "Could not receive a message from the daemon.\n" + diag.describe(), e );
}
- } finally {
+ else if ( staleAddressDetector.maybeStaleAddress( e ) )
+ {
+ throw new StaleAddressException( "Could not receive a message from the daemon.\n" + diag.describe(),
+ e );
+ }
+ }
+ finally
+ {
hasReceived = true;
}
}
}
- public void enqueue(Message message) {
- try {
- queue.put(message);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
+ public void enqueue( Message message )
+ {
+ try
+ {
+ queue.put( message );
+ }
+ catch ( InterruptedException e )
+ {
+ throw new RuntimeException( e );
}
}
- protected void doReceive() {
- try {
- while (running.get()) {
+ protected void doReceive()
+ {
+ try
+ {
+ while ( running.get() )
+ {
Message m = connection.receive();
- if (m == null) {
+ if ( m == null )
+ {
break;
}
- queue.put(m);
+ queue.put( m );
}
- } catch (Exception e) {
- if (running.get()) {
- exception.set(e);
+ }
+ catch ( Exception e )
+ {
+ if ( running.get() )
+ {
+ exception.set( e );
}
}
}
- public void close() {
- LOG.debug("thread {}: connection stop", Thread.currentThread().getId());
- running.set(false);
+ public void close()
+ {
+ LOG.debug( "thread {}: connection stop", Thread.currentThread().getId() );
+ running.set( false );
receiver.interrupt();
connection.close();
}
- public interface StaleAddressDetector {
+ public interface StaleAddressDetector
+ {
+
/**
* @return true if the failure should be considered due to a stale address.
*/
- boolean maybeStaleAddress(Exception failure);
+ boolean maybeStaleAddress( Exception failure );
}
}
diff --git a/client/src/main/java/org/mvndaemon/mvnd/client/DaemonConnector.java b/client/src/main/java/org/mvndaemon/mvnd/client/DaemonConnector.java
index 83ef674..50f813d 100644
--- a/client/src/main/java/org/mvndaemon/mvnd/client/DaemonConnector.java
+++ b/client/src/main/java/org/mvndaemon/mvnd/client/DaemonConnector.java
@@ -60,441 +60,557 @@ import static org.mvndaemon.mvnd.common.DaemonState.Canceled;
* File origin:
* https://github.com/gradle/gradle/blob/v5.6.2/subprojects/launcher/src/main/java/org/gradle/launcher/daemon/client/DefaultDaemonConnector.java
*/
-public class DaemonConnector {
+public class DaemonConnector
+{
public static final int DEFAULT_CONNECT_TIMEOUT = 30000;
public static final int CANCELED_WAIT_TIMEOUT = 3000;
private static final int CONNECT_TIMEOUT = 10000;
- private static final Logger LOGGER = LoggerFactory.getLogger(DaemonConnector.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger( DaemonConnector.class );
private final DaemonRegistry registry;
private final DaemonParameters parameters;
- public DaemonConnector(DaemonParameters parameters, DaemonRegistry registry) {
+ public DaemonConnector( DaemonParameters parameters, DaemonRegistry registry )
+ {
this.parameters = parameters;
this.registry = registry;
}
- public DaemonClientConnection maybeConnect(DaemonCompatibilitySpec constraint) {
- return findConnection(getCompatibleDaemons(registry.getAll(), constraint));
+ public DaemonClientConnection maybeConnect( DaemonCompatibilitySpec constraint )
+ {
+ return findConnection( getCompatibleDaemons( registry.getAll(), constraint ) );
}
- public DaemonClientConnection maybeConnect(DaemonInfo daemon) {
- try {
- return connectToDaemon(daemon, new CleanupOnStaleAddress(daemon), false);
- } catch (DaemonException.ConnectException e) {
- LOGGER.debug("Cannot connect to daemon {} due to {}. Ignoring.", daemon, e);
+ public DaemonClientConnection maybeConnect( DaemonInfo daemon )
+ {
+ try
+ {
+ return connectToDaemon( daemon, new CleanupOnStaleAddress( daemon ), false );
+ }
+ catch ( DaemonException.ConnectException e )
+ {
+ LOGGER.debug( "Cannot connect to daemon {} due to {}. Ignoring.", daemon, e );
}
return null;
}
- public DaemonClientConnection connect(ClientOutput output) {
- if (parameters.noDaemon()) {
+ public DaemonClientConnection connect( ClientOutput output )
+ {
+ if ( parameters.noDaemon() )
+ {
return connectNoDaemon();
}
final DaemonCompatibilitySpec constraint = new DaemonCompatibilitySpec(
- parameters.javaHome(), parameters.getDaemonOpts());
- output.accept(Message.buildStatus("Looking up daemon..."));
+ parameters.javaHome(), parameters.getDaemonOpts() );
+ output.accept( Message.buildStatus( "Looking up daemon..." ) );
Map<Boolean, List<DaemonInfo>> idleBusy = registry.getAll().stream()
- .collect(Collectors.groupingBy(di -> di.getState() == DaemonState.Idle));
- final Collection<DaemonInfo> idleDaemons = idleBusy.getOrDefault(true, Collections.emptyList());
- final Collection<DaemonInfo> busyDaemons = idleBusy.getOrDefault(false, Collections.emptyList());
+ .collect( Collectors.groupingBy( di -> di.getState() == DaemonState.Idle ) );
+ final Collection<DaemonInfo> idleDaemons = idleBusy.getOrDefault( true, Collections.emptyList() );
+ final Collection<DaemonInfo> busyDaemons = idleBusy.getOrDefault( false, Collections.emptyList() );
// Check to see if there are any compatible idle daemons
- DaemonClientConnection connection = connectToIdleDaemon(idleDaemons, constraint);
- if (connection != null) {
+ DaemonClientConnection connection = connectToIdleDaemon( idleDaemons, constraint );
+ if ( connection != null )
+ {
return connection;
}
// Check to see if there are any compatible canceled daemons and wait to see if one becomes idle
- connection = connectToCanceledDaemon(busyDaemons, constraint);
- if (connection != null) {
+ connection = connectToCanceledDaemon( busyDaemons, constraint );
+ if ( connection != null )
+ {
return connection;
}
// No compatible daemons available - start a new daemon
final String daemonId = newId();
- String message = handleStopEvents(daemonId, idleDaemons, busyDaemons);
- output.accept(Message.buildStatus(message));
- return startDaemon(daemonId);
+ String message = handleStopEvents( daemonId, idleDaemons, busyDaemons );
+ output.accept( Message.buildStatus( message ) );
+ return startDaemon( daemonId );
}
- private DaemonClientConnection connectNoDaemon() {
- if (Environment.isNative()) {
+ private DaemonClientConnection connectNoDaemon()
+ {
+ if ( Environment.isNative() )
+ {
throw new UnsupportedOperationException(
- "The " + Environment.MVND_NO_DAEMON.getProperty() + " property is not supported in native mode.");
+ "The " + Environment.MVND_NO_DAEMON.getProperty() + " property is not supported in native mode." );
}
String daemon = ProcessHandle.current().pid() + "-" + System.currentTimeMillis();
Properties properties = new Properties();
- properties.put(Environment.JAVA_HOME.getProperty(), parameters.javaHome().toString());
- properties.put(Environment.USER_DIR.getProperty(), parameters.userDir().toString());
- properties.put(Environment.USER_HOME.getProperty(), parameters.userHome().toString());
- properties.put(Environment.MVND_HOME.getProperty(), parameters.mvndHome().toString());
- properties.put(Environment.MVND_ID.getProperty(), daemon);
- properties.put(Environment.MVND_DAEMON_STORAGE.getProperty(), parameters.daemonStorage().toString());
- properties.put(Environment.MVND_REGISTRY.getProperty(), parameters.registry().toString());
- properties.putAll(parameters.getDaemonOptsMap());
- Environment.setProperties(properties);
+ properties.put( Environment.JAVA_HOME.getProperty(), parameters.javaHome().toString() );
+ properties.put( Environment.USER_DIR.getProperty(), parameters.userDir().toString() );
+ properties.put( Environment.USER_HOME.getProperty(), parameters.userHome().toString() );
+ properties.put( Environment.MVND_HOME.getProperty(), parameters.mvndHome().toString() );
+ properties.put( Environment.MVND_ID.getProperty(), daemon );
+ properties.put( Environment.MVND_DAEMON_STORAGE.getProperty(), parameters.daemonStorage().toString() );
+ properties.put( Environment.MVND_REGISTRY.getProperty(), parameters.registry().toString() );
+ properties.putAll( parameters.getDaemonOptsMap() );
+ Environment.setProperties( properties );
AtomicReference<Throwable> throwable = new AtomicReference<>();
- Thread serverThread = new Thread(() -> {
- try {
- Class<?> clazz = getClass().getClassLoader().loadClass("org.mvndaemon.mvnd.daemon.Server");
- try (AutoCloseable server = (AutoCloseable) clazz.getConstructor().newInstance()) {
- ((Runnable) server).run();
+ Thread serverThread = new Thread( () ->
+ {
+ try
+ {
+ Class<?> clazz = getClass().getClassLoader().loadClass( "org.mvndaemon.mvnd.daemon.Server" );
+ try ( AutoCloseable server = ( AutoCloseable ) clazz.getConstructor().newInstance() )
+ {
+ ( ( Runnable ) server ).run();
}
- } catch (Throwable t) {
- throwable.set(t);
}
- });
+ catch ( Throwable t )
+ {
+ throwable.set( t );
+ }
+ } );
serverThread.start();
long start = System.currentTimeMillis();
- do {
- DaemonClientConnection daemonConnection = connectToDaemonWithId(daemon, true);
- if (daemonConnection != null) {
+ do
+ {
+ DaemonClientConnection daemonConnection = connectToDaemonWithId( daemon, true );
+ if ( daemonConnection != null )
+ {
return daemonConnection;
}
- try {
- sleep(50L);
- } catch (InterruptedException e) {
- throw new DaemonException.InterruptedException(e);
+ try
+ {
+ sleep( 50L );
+ }
+ catch ( InterruptedException e )
+ {
+ throw new DaemonException.InterruptedException( e );
}
- } while (serverThread.isAlive() && System.currentTimeMillis() - start < DEFAULT_CONNECT_TIMEOUT);
- throw new RuntimeException("Unable to connect to internal daemon", throwable.get());
+ }
+ while ( serverThread.isAlive() && System.currentTimeMillis() - start < DEFAULT_CONNECT_TIMEOUT );
+ throw new RuntimeException( "Unable to connect to internal daemon", throwable.get() );
}
- private String handleStopEvents(String daemonId, Collection<DaemonInfo> idleDaemons, Collection<DaemonInfo> busyDaemons) {
+ private String handleStopEvents( String daemonId, Collection<DaemonInfo> idleDaemons,
+ Collection<DaemonInfo> busyDaemons )
+ {
final List<DaemonStopEvent> stopEvents = registry.getStopEvents();
// Clean up old stop events
- long time = System.currentTimeMillis() - TimeUnit.HOURS.toMillis(1);
+ long time = System.currentTimeMillis() - TimeUnit.HOURS.toMillis( 1 );
List<DaemonStopEvent> oldStopEvents = stopEvents.stream()
- .filter(e -> e.getTimestamp() < time)
- .collect(Collectors.toList());
- registry.removeStopEvents(oldStopEvents);
+ .filter( e -> e.getTimestamp() < time )
+ .collect( Collectors.toList() );
+ registry.removeStopEvents( oldStopEvents );
final List<DaemonStopEvent> recentStopEvents = stopEvents.stream()
- .filter(e -> e.getTimestamp() >= time)
- .collect(Collectors.groupingBy(DaemonStopEvent::getDaemonId,
- Collectors.minBy(this::compare)))
+ .filter( e -> e.getTimestamp() >= time )
+ .collect( Collectors.groupingBy( DaemonStopEvent::getDaemonId,
+ Collectors.minBy( this::compare ) ) )
.values()
.stream()
- .map(Optional::get)
- .collect(Collectors.toList());
- for (DaemonStopEvent stopEvent : recentStopEvents) {
- LOGGER.debug("Previous Daemon ({}) stopped at {} {}",
- stopEvent.getDaemonId(), stopEvent.getTimestamp(), stopEvent.getReason());
+ .map( Optional::get )
+ .collect( Collectors.toList() );
+ for ( DaemonStopEvent stopEvent : recentStopEvents )
+ {
+ LOGGER.debug( "Previous Daemon ({}) stopped at {} {}",
+ stopEvent.getDaemonId(), stopEvent.getTimestamp(), stopEvent.getReason() );
}
- return generate(daemonId, busyDaemons.size(), idleDaemons.size(), recentStopEvents.size());
+ return generate( daemonId, busyDaemons.size(), idleDaemons.size(), recentStopEvents.size() );
}
- public static String generate(final String daemonId, final int numBusy, final int numIncompatible, final int numStopped) {
+ public static String generate( final String daemonId, final int numBusy, final int numIncompatible,
+ final int numStopped )
+ {
final int totalUnavailableDaemons = numBusy + numIncompatible + numStopped;
- if (totalUnavailableDaemons > 0) {
+ if ( totalUnavailableDaemons > 0 )
+ {
final List<String> reasons = new ArrayList<>();
- if (numBusy > 0) {
- reasons.add(numBusy + " busy");
+ if ( numBusy > 0 )
+ {
+ reasons.add( numBusy + " busy" );
}
- if (numIncompatible > 0) {
- reasons.add(numIncompatible + " incompatible");
+ if ( numIncompatible > 0 )
+ {
+ reasons.add( numIncompatible + " incompatible" );
}
- if (numStopped > 0) {
- reasons.add(numStopped + " stopped");
+ if ( numStopped > 0 )
+ {
+ reasons.add( numStopped + " stopped" );
}
return "Starting new daemon " + daemonId + ", "
- + String.join(" and ", reasons) + " daemon" + (totalUnavailableDaemons > 1 ? "s" : "")
+ + String.join( " and ", reasons ) + " daemon" + ( totalUnavailableDaemons > 1 ? "s" : "" )
+ " could not be reused, use --status for details";
- } else {
+ }
+ else
+ {
return "Starting new daemon " + daemonId + " (subsequent builds will be faster)...";
}
}
- private int compare(DaemonStopEvent event1, DaemonStopEvent event2) {
- if (event1.getStatus() != null && event2.getStatus() == null) {
+ private int compare( DaemonStopEvent event1, DaemonStopEvent event2 )
+ {
+ if ( event1.getStatus() != null && event2.getStatus() == null )
+ {
return -1;
- } else if (event1.getStatus() == null && event2.getStatus() != null) {
+ }
+ else if ( event1.getStatus() == null && event2.getStatus() != null )
+ {
return 1;
- } else if (event1.getStatus() != null && event2.getStatus() != null) {
- return event2.getStatus().compareTo(event1.getStatus());
+ }
+ else if ( event1.getStatus() != null && event2.getStatus() != null )
+ {
+ return event2.getStatus().compareTo( event1.getStatus() );
}
return 0;
}
- private DaemonClientConnection connectToIdleDaemon(Collection<DaemonInfo> idleDaemons, DaemonCompatibilitySpec constraint) {
- final List<DaemonInfo> compatibleIdleDaemons = getCompatibleDaemons(idleDaemons, constraint);
- LOGGER.debug("Found {} idle daemons, {} compatibles", idleDaemons.size(), compatibleIdleDaemons.size());
- return findConnection(compatibleIdleDaemons);
+ private DaemonClientConnection connectToIdleDaemon( Collection<DaemonInfo> idleDaemons,
+ DaemonCompatibilitySpec constraint )
+ {
+ final List<DaemonInfo> compatibleIdleDaemons = getCompatibleDaemons( idleDaemons, constraint );
+ LOGGER.debug( "Found {} idle daemons, {} compatibles", idleDaemons.size(), compatibleIdleDaemons.size() );
+ return findConnection( compatibleIdleDaemons );
}
- private DaemonClientConnection connectToCanceledDaemon(Collection<DaemonInfo> busyDaemons,
- DaemonCompatibilitySpec constraint) {
+ private DaemonClientConnection connectToCanceledDaemon( Collection<DaemonInfo> busyDaemons,
+ DaemonCompatibilitySpec constraint )
+ {
DaemonClientConnection connection = null;
List<DaemonInfo> canceledBusy = busyDaemons.stream()
- .filter(di -> di.getState() == Canceled)
- .collect(Collectors.toList());
+ .filter( di -> di.getState() == Canceled )
+ .collect( Collectors.toList() );
final List<DaemonInfo> compatibleCanceledDaemons = getCompatibleDaemons(
- canceledBusy, constraint);
- LOGGER.debug("Found {} busy daemons, {} cancelled, {} compatibles", busyDaemons.size(), canceledBusy.size(),
- compatibleCanceledDaemons.size());
- if (!compatibleCanceledDaemons.isEmpty()) {
- LOGGER.debug("Waiting for daemons with canceled builds to become available");
+ canceledBusy, constraint );
+ LOGGER.debug( "Found {} busy daemons, {} cancelled, {} compatibles", busyDaemons.size(), canceledBusy.size(),
+ compatibleCanceledDaemons.size() );
+ if ( !compatibleCanceledDaemons.isEmpty() )
+ {
+ LOGGER.debug( "Waiting for daemons with canceled builds to become available" );
long start = System.currentTimeMillis();
- while (connection == null && System.currentTimeMillis() - start < CANCELED_WAIT_TIMEOUT) {
- try {
- sleep(200);
- connection = connectToIdleDaemon(registry.getIdle(), constraint);
- } catch (InterruptedException e) {
- throw new DaemonException.InterruptedException(e);
+ while ( connection == null && System.currentTimeMillis() - start < CANCELED_WAIT_TIMEOUT )
+ {
+ try
+ {
+ sleep( 200 );
+ connection = connectToIdleDaemon( registry.getIdle(), constraint );
+ }
+ catch ( InterruptedException e )
+ {
+ throw new DaemonException.InterruptedException( e );
}
}
}
return connection;
}
- private List<DaemonInfo> getCompatibleDaemons(Iterable<DaemonInfo> daemons, DaemonCompatibilitySpec constraint) {
+ private List<DaemonInfo> getCompatibleDaemons( Iterable<DaemonInfo> daemons, DaemonCompatibilitySpec constraint )
+ {
List<DaemonInfo> compatibleDaemons = new LinkedList<>();
- for (DaemonInfo daemon : daemons) {
- final Result result = constraint.isSatisfiedBy(daemon);
- if (result.isCompatible()) {
- compatibleDaemons.add(daemon);
- } else {
- LOGGER.debug("{} daemon {} does not match the desired criteria: "
- + result.getWhy(), daemon.getState(), daemon.getId());
+ for ( DaemonInfo daemon : daemons )
+ {
+ final Result result = constraint.isSatisfiedBy( daemon );
+ if ( result.isCompatible() )
+ {
+ compatibleDaemons.add( daemon );
+ }
+ else
+ {
+ LOGGER.debug( "{} daemon {} does not match the desired criteria: "
+ + result.getWhy(), daemon.getState(), daemon.getId() );
}
}
return compatibleDaemons;
}
- private DaemonClientConnection findConnection(List<DaemonInfo> compatibleDaemons) {
- for (DaemonInfo daemon : compatibleDaemons) {
- try {
- return connectToDaemon(daemon, new CleanupOnStaleAddress(daemon), false);
- } catch (DaemonException.ConnectException e) {
- LOGGER.debug("Cannot connect to daemon {} due to {}. Trying a different daemon...", daemon, e);
+ private DaemonClientConnection findConnection( List<DaemonInfo> compatibleDaemons )
+ {
+ for ( DaemonInfo daemon : compatibleDaemons )
+ {
+ try
+ {
+ return connectToDaemon( daemon, new CleanupOnStaleAddress( daemon ), false );
+ }
+ catch ( DaemonException.ConnectException e )
+ {
+ LOGGER.debug( "Cannot connect to daemon {} due to {}. Trying a different daemon...", daemon, e );
}
}
return null;
}
- public DaemonClientConnection startDaemon(String daemonId) {
- final Process process = startDaemonProcess(daemonId);
- LOGGER.debug("Started Maven daemon {}", daemonId);
+ public DaemonClientConnection startDaemon( String daemonId )
+ {
+ final Process process = startDaemonProcess( daemonId );
+ LOGGER.debug( "Started Maven daemon {}", daemonId );
long start = System.currentTimeMillis();
- do {
- DaemonClientConnection daemonConnection = connectToDaemonWithId(daemonId, true);
- if (daemonConnection != null) {
+ do
+ {
+ DaemonClientConnection daemonConnection = connectToDaemonWithId( daemonId, true );
+ if ( daemonConnection != null )
+ {
return daemonConnection;
}
- try {
- sleep(200L);
- } catch (InterruptedException e) {
- throw new DaemonException.InterruptedException(e);
+ try
+ {
+ sleep( 200L );
+ }
+ catch ( InterruptedException e )
+ {
+ throw new DaemonException.InterruptedException( e );
}
- } while (process.isAlive() && System.currentTimeMillis() - start < DEFAULT_CONNECT_TIMEOUT);
- DaemonDiagnostics diag = new DaemonDiagnostics(daemonId, parameters);
- throw new DaemonException.ConnectException("Timeout waiting to connect to the Maven daemon.\n" + diag.describe());
+ }
+ while ( process.isAlive() && System.currentTimeMillis() - start < DEFAULT_CONNECT_TIMEOUT );
+ DaemonDiagnostics diag = new DaemonDiagnostics( daemonId, parameters );
+ throw new DaemonException.ConnectException(
+ "Timeout waiting to connect to the Maven daemon.\n" + diag.describe() );
}
- static String newId() {
- return String.format("%08x", new Random().nextInt());
+ static String newId()
+ {
+ return String.format( "%08x", new Random().nextInt() );
}
- private Process startDaemonProcess(String daemonId) {
+ private Process startDaemonProcess( String daemonId )
+ {
final Path mvndHome = parameters.mvndHome();
final Path workingDir = parameters.userDir();
String command = "";
- try (DirectoryStream<Path> jarPaths = Files.newDirectoryStream(mvndHome.resolve("mvn/lib/ext"))) {
+ try ( DirectoryStream<Path> jarPaths = Files.newDirectoryStream( mvndHome.resolve( "mvn/lib/ext" ) ) )
+ {
List<String> args = new ArrayList<>();
// executable
final String java = Os.current().isUnixLike() ? "bin/java" : "bin\\java.exe";
- args.add(parameters.javaHome().resolve(java).toString());
+ args.add( parameters.javaHome().resolve( java ).toString() );
// classpath
String mvndCommonPath = null;
String mvndAgentPath = null;
- for (Path jar : jarPaths) {
+ for ( Path jar : jarPaths )
+ {
String s = jar.getFileName().toString();
- if (s.endsWith(".jar")) {
- if (s.startsWith("mvnd-common-")) {
+ if ( s.endsWith( ".jar" ) )
+ {
+ if ( s.startsWith( "mvnd-common-" ) )
+ {
mvndCommonPath = jar.toString();
- } else if (s.startsWith("mvnd-agent-")) {
+ }
+ else if ( s.startsWith( "mvnd-agent-" ) )
+ {
mvndAgentPath = jar.toString();
}
}
}
- if (mvndCommonPath == null) {
- throw new IllegalStateException("Could not find mvnd-common jar in mvn/lib/ext/");
+ if ( mvndCommonPath == null )
+ {
+ throw new IllegalStateException( "Could not find mvnd-common jar in mvn/lib/ext/" );
}
- if (mvndAgentPath == null) {
- throw new IllegalStateException("Could not find mvnd-agent jar in mvn/lib/ext/");
+ if ( mvndAgentPath == null )
+ {
+ throw new IllegalStateException( "Could not find mvnd-agent jar in mvn/lib/ext/" );
}
- args.add("-classpath");
- args.add(mvndCommonPath + File.pathSeparator + mvndAgentPath);
- args.add("-javaagent:" + mvndAgentPath);
+ args.add( "-classpath" );
+ args.add( mvndCommonPath + File.pathSeparator + mvndAgentPath );
+ args.add( "-javaagent:" + mvndAgentPath );
// debug options
- if (parameters.property(Environment.MVND_DEBUG).asBoolean()) {
- args.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=8000");
+ if ( parameters.property( Environment.MVND_DEBUG ).asBoolean() )
+ {
+ args.add( "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=8000" );
}
// jvm args
String jvmArgs = parameters.jvmArgs();
- if (jvmArgs != null) {
- for (String arg : jvmArgs.split(" ")) {
- if (!arg.isEmpty()) {
- args.add(arg);
+ if ( jvmArgs != null )
+ {
+ for ( String arg : jvmArgs.split( " " ) )
+ {
+ if ( !arg.isEmpty() )
+ {
+ args.add( arg );
}
}
}
// memory
String minHeapSize = parameters.minHeapSize();
- if (minHeapSize != null) {
- args.add("-Xms" + minHeapSize);
+ if ( minHeapSize != null )
+ {
+ args.add( "-Xms" + minHeapSize );
}
String maxHeapSize = parameters.maxHeapSize();
- if (maxHeapSize != null) {
- args.add("-Xmx" + maxHeapSize);
+ if ( maxHeapSize != null )
+ {
+ args.add( "-Xmx" + maxHeapSize );
}
String threadStackSize = parameters.threadStackSize();
- if (threadStackSize != null) {
- args.add("-Xss" + threadStackSize);
+ if ( threadStackSize != null )
+ {
+ args.add( "-Xss" + threadStackSize );
}
- Environment.MVND_HOME.addCommandLineOption(args, mvndHome.toString());
- args.add("-Dmaven.home=" + mvndHome.resolve("mvn"));
- args.add("-Dmaven.conf=" + mvndHome.resolve("mvn/conf"));
+ Environment.MVND_HOME.addCommandLineOption( args, mvndHome.toString() );
+ args.add( "-Dmaven.home=" + mvndHome.resolve( "mvn" ) );
+ args.add( "-Dmaven.conf=" + mvndHome.resolve( "mvn/conf" ) );
- Environment.MVND_JAVA_HOME.addCommandLineOption(args, parameters.javaHome().toString());
+ Environment.MVND_JAVA_HOME.addCommandLineOption( args, parameters.javaHome().toString() );
Environment.LOGBACK_CONFIGURATION_FILE
- .addCommandLineOption(args, parameters.logbackConfigurationPath().toString());
- Environment.MVND_ID.addCommandLineOption(args, daemonId);
- Environment.MVND_DAEMON_STORAGE.addCommandLineOption(args, parameters.daemonStorage().toString());
- Environment.MVND_REGISTRY.addCommandLineOption(args, parameters.registry().toString());
- Environment.MVND_SOCKET_FAMILY.addCommandLineOption(args,
+ .addCommandLineOption( args, parameters.logbackConfigurationPath().toString() );
+ Environment.MVND_ID.addCommandLineOption( args, daemonId );
+ Environment.MVND_DAEMON_STORAGE.addCommandLineOption( args, parameters.daemonStorage().toString() );
+ Environment.MVND_REGISTRY.addCommandLineOption( args, parameters.registry().toString() );
+ Environment.MVND_SOCKET_FAMILY.addCommandLineOption( args,
parameters.socketFamily().orElseGet(
- () -> getJavaVersion() >= 16.0f ? SocketFamily.unix : SocketFamily.inet)
- .toString());
- parameters.discriminatingCommandLineOptions(args);
- args.add(MavenDaemon.class.getName());
- command = String.join(" ", args);
-
- LOGGER.debug("Starting daemon process: id = {}, workingDir = {}, daemonArgs: {}", daemonId, workingDir, command);
- ProcessBuilder.Redirect redirect = ProcessBuilder.Redirect.appendTo(parameters.daemonOutLog(daemonId).toFile());
+ () -> getJavaVersion() >= 16.0f ? SocketFamily.unix : SocketFamily.inet )
+ .toString() );
+ parameters.discriminatingCommandLineOptions( args );
+ args.add( MavenDaemon.class.getName() );
+ command = String.join( " ", args );
+
+ LOGGER.debug( "Starting daemon process: id = {}, workingDir = {}, daemonArgs: {}", daemonId, workingDir,
+ command );
+ ProcessBuilder.Redirect redirect = ProcessBuilder.Redirect
+ .appendTo( parameters.daemonOutLog( daemonId ).toFile() );
ProcessBuilder processBuilder = new ProcessBuilder();
- processBuilder.environment().put(Environment.JDK_JAVA_OPTIONS.getEnvironmentVariable(), parameters.jdkJavaOpts());
+ processBuilder.environment().put( Environment.JDK_JAVA_OPTIONS.getEnvironmentVariable(),
+ parameters.jdkJavaOpts() );
Process process = processBuilder
- .directory(workingDir.toFile())
- .command(args)
- .redirectOutput(redirect)
- .redirectError(redirect)
+ .directory( workingDir.toFile() )
+ .command( args )
+ .redirectOutput( redirect )
+ .redirectError( redirect )
.start();
return process;
- } catch (Exception e) {
+ }
+ catch ( Exception e )
+ {
throw new DaemonException.StartException(
- String.format("Error starting daemon: id = %s, workingDir = %s, daemonArgs: %s",
- daemonId, workingDir, command),
- e);
+ String.format( "Error starting daemon: id = %s, workingDir = %s, daemonArgs: %s",
+ daemonId, workingDir, command ),
+ e );
}
}
- private float getJavaVersion() {
- try {
+ private float getJavaVersion()
+ {
+ try
+ {
final String java = Os.current().isUnixLike() ? "bin/java" : "bin\\java.exe";
- Path javaExec = parameters.javaHome().resolve(java);
+ Path javaExec = parameters.javaHome().resolve( java );
List<String> args = new ArrayList<>();
- args.add(javaExec.toString());
- args.add("-version");
+ args.add( javaExec.toString() );
+ args.add( "-version" );
Process process = new ProcessBuilder()
- .directory(parameters.mvndHome().toFile())
- .command(args)
+ .directory( parameters.mvndHome().toFile() )
+ .command( args )
.start();
process.waitFor();
- Scanner sc = new Scanner(process.getErrorStream());
+ Scanner sc = new Scanner( process.getErrorStream() );
sc.next();
sc.next();
String version = sc.next();
- LOGGER.warn("JAVA VERSION: " + version);
- int is = version.charAt(0) == '"' ? 1 : 0;
- int ie = version.indexOf('.', version.indexOf('.', is));
- return Float.parseFloat(version.substring(is, ie));
- } catch (Exception e) {
- throw new IllegalStateException("Unable to detect java version", e);
+ LOGGER.warn( "JAVA VERSION: " + version );
+ int is = version.charAt( 0 ) == '"' ? 1 : 0;
+ int ie = version.indexOf( '.', version.indexOf( '.', is ) );
+ return Float.parseFloat( version.substring( is, ie ) );
+ }
+ catch ( Exception e )
+ {
+ throw new IllegalStateException( "Unable to detect java version", e );
}
}
- private DaemonClientConnection connectToDaemonWithId(String daemon, boolean newDaemon)
- throws DaemonException.ConnectException {
+ private DaemonClientConnection connectToDaemonWithId( String daemon, boolean newDaemon )
+ throws DaemonException.ConnectException
+ {
// Look for 'our' daemon among the busy daemons - a daemon will start in busy state so that nobody else will
// grab it.
- DaemonInfo daemonInfo = registry.get(daemon);
- if (daemonInfo != null) {
- try {
- return connectToDaemon(daemonInfo, new CleanupOnStaleAddress(daemonInfo), newDaemon);
- } catch (DaemonException.ConnectException e) {
- DaemonDiagnostics diag = new DaemonDiagnostics(daemon, parameters);
- throw new DaemonException.ConnectException("Could not connect to the Maven daemon.\n" + diag.describe(), e);
+ DaemonInfo daemonInfo = registry.get( daemon );
+ if ( daemonInfo != null )
+ {
+ try
+ {
+ return connectToDaemon( daemonInfo, new CleanupOnStaleAddress( daemonInfo ), newDaemon );
+ }
+ catch ( DaemonException.ConnectException e )
+ {
+ DaemonDiagnostics diag = new DaemonDiagnostics( daemon, parameters );
+ throw new DaemonException.ConnectException(
+ "Could not connect to the Maven daemon.\n" + diag.describe(), e );
}
}
return null;
}
- private DaemonClientConnection connectToDaemon(DaemonInfo daemon,
- DaemonClientConnection.StaleAddressDetector staleAddressDetector, boolean newDaemon)
- throws DaemonException.ConnectException {
- LOGGER.debug("Connecting to Daemon");
- try {
- DaemonConnection connection = connect(daemon.getAddress(), daemon.getToken());
- return new DaemonClientConnection(connection, daemon, staleAddressDetector, newDaemon, parameters);
- } catch (DaemonException.ConnectException e) {
- staleAddressDetector.maybeStaleAddress(e);
+ private DaemonClientConnection connectToDaemon( DaemonInfo daemon,
+ DaemonClientConnection.StaleAddressDetector staleAddressDetector, boolean newDaemon )
+ throws DaemonException.ConnectException
+ {
+ LOGGER.debug( "Connecting to Daemon" );
+ try
+ {
+ DaemonConnection connection = connect( daemon.getAddress(), daemon.getToken() );
+ return new DaemonClientConnection( connection, daemon, staleAddressDetector, newDaemon, parameters );
+ }
+ catch ( DaemonException.ConnectException e )
+ {
+ staleAddressDetector.maybeStaleAddress( e );
throw e;
- } finally {
- LOGGER.debug("Connected");
+ }
+ finally
+ {
+ LOGGER.debug( "Connected" );
}
}
- private class CleanupOnStaleAddress implements DaemonClientConnection.StaleAddressDetector {
+ private class CleanupOnStaleAddress implements DaemonClientConnection.StaleAddressDetector
+ {
+
private final DaemonInfo daemon;
- public CleanupOnStaleAddress(DaemonInfo daemon) {
+ public CleanupOnStaleAddress( DaemonInfo daemon )
+ {
this.daemon = daemon;
}
@Override
- public boolean maybeStaleAddress(Exception failure) {
- LOGGER.debug("Removing daemon from the registry due to communication failure. Daemon information: {}", daemon);
+ public boolean maybeStaleAddress( Exception failure )
+ {
+ LOGGER.debug( "Removing daemon from the registry due to communication failure. Daemon information: {}",
+ daemon );
final long timestamp = System.currentTimeMillis();
- final DaemonStopEvent stopEvent = new DaemonStopEvent(daemon.getId(), timestamp, null,
- "by user or operating system");
- registry.storeStopEvent(stopEvent);
- registry.remove(daemon.getId());
+ final DaemonStopEvent stopEvent = new DaemonStopEvent( daemon.getId(), timestamp, null,
+ "by user or operating system" );
+ registry.storeStopEvent( stopEvent );
+ registry.remove( daemon.getId() );
return true;
}
}
- public DaemonConnection connect(String str, byte[] token) throws DaemonException.ConnectException {
- SocketAddress address = SocketFamily.fromString(str);
- try {
- LOGGER.debug("Trying to connect to address {}.", address);
- SocketFamily family = SocketFamily.familyOf(address);
+ public DaemonConnection connect( String str, byte[] token ) throws DaemonException.ConnectException
+ {
+ SocketAddress address = SocketFamily.fromString( str );
+ try
+ {
+ LOGGER.debug( "Trying to connect to address {}.", address );
+ SocketFamily family = SocketFamily.familyOf( address );
SocketChannel socketChannel = family.openSocket();
- socketChannel.configureBlocking(false);
- boolean connected = socketChannel.connect(address);
- if (!connected) {
+ socketChannel.configureBlocking( false );
+ boolean connected = socketChannel.connect( address );
+ if ( !connected )
+ {
long t0 = System.nanoTime();
- long t1 = t0 + TimeUnit.MICROSECONDS.toNanos(CONNECT_TIMEOUT);
- while (!connected && t0 < t1) {
- Thread.sleep(10);
+ long t1 = t0 + TimeUnit.MICROSECONDS.toNanos( CONNECT_TIMEOUT );
+ while ( !connected && t0 < t1 )
+ {
+ Thread.sleep( 10 );
connected = socketChannel.finishConnect();
- if (!connected) {
+ if ( !connected )
+ {
t0 = System.nanoTime();
}
}
- if (!connected) {
- throw new IOException("Timeout");
+ if ( !connected )
+ {
+ throw new IOException( "Timeout" );
}
}
- socketChannel.configureBlocking(true);
+ socketChannel.configureBlocking( true );
// Socket socket = socketChannel.socket();
// socket.connect(address, CONNECT_TIMEOUT);
@@ -502,19 +618,26 @@ public class DaemonConnector {
// socketChannel.close();
// throw new DaemonException.ConnectException(String.format("Socket connected to itself on %s.", address));
// }
- LOGGER.debug("Connected to address {}.", socketChannel.getRemoteAddress());
+ LOGGER.debug( "Connected to address {}.", socketChannel.getRemoteAddress() );
- ByteBuffer tokenBuffer = ByteBuffer.wrap(token);
- do {
- socketChannel.write(tokenBuffer);
- } while (tokenBuffer.remaining() > 0);
- LOGGER.debug("Exchanged token successfully");
+ ByteBuffer tokenBuffer = ByteBuffer.wrap( token );
+ do
+ {
+ socketChannel.write( tokenBuffer );
+ }
+ while ( tokenBuffer.remaining() > 0 );
+ LOGGER.debug( "Exchanged token successfully" );
- return new DaemonConnection(socketChannel);
- } catch (DaemonException.ConnectException e) {
+ return new DaemonConnection( socketChannel );
+ }
+ catch ( DaemonException.ConnectException e )
+ {
throw e;
- } catch (Exception e) {
- throw new DaemonException.ConnectException(String.format("Could not connect to server %s.", address), e);
+ }
+ catch ( Exception e )
+ {
+ throw new DaemonException.ConnectException( String.format( "Could not connect to server %s.", address ),
+ e );
}
}
diff --git a/client/src/main/java/org/mvndaemon/mvnd/client/DaemonDiagnostics.java b/client/src/main/java/org/mvndaemon/mvnd/client/DaemonDiagnostics.java
index 4c22c2c..f104031 100644
--- a/client/src/main/java/org/mvndaemon/mvnd/client/DaemonDiagnostics.java
+++ b/client/src/main/java/org/mvndaemon/mvnd/client/DaemonDiagnostics.java
@@ -30,47 +30,58 @@ import java.util.stream.Collector;
* File origin:
* https://github.com/gradle/gradle/blob/v5.6.2/subprojects/launcher/src/main/java/org/gradle/launcher/daemon/diagnostics/DaemonDiagnostics.java
*/
-public class DaemonDiagnostics {
+public class DaemonDiagnostics
+{
private final static int TAIL_SIZE = 200;
private final String id;
private final DaemonParameters parameters;
- public DaemonDiagnostics(String id, DaemonParameters parameters) {
+ public DaemonDiagnostics( String id, DaemonParameters parameters )
+ {
this.id = id;
this.parameters = parameters;
}
@Override
- public String toString() {
+ public String toString()
+ {
return "{"
+ "id=" + id
+ ", parameters=" + parameters
+ '}';
}
- public String describe() {
+ public String describe()
+ {
StringBuilder sb = new StringBuilder();
- sb.append("Daemon id: ").append(id).append("\n");
- tail(sb, "log file", parameters.daemonLog(id));
- tail(sb, "output", parameters.daemonOutLog(id));
+ sb.append( "Daemon id: " ).append( id ).append( "\n" );
+ tail( sb, "log file", parameters.daemonLog( id ) );
+ tail( sb, "output", parameters.daemonOutLog( id ) );
return sb.toString();
}
- static void tail(StringBuilder sb, String name, Path log) {
- try {
- String tail = tail(log);
- sb.append(" ").append(name).append(": ").append(log).append("\n");
- sb.append("----- Last " + TAIL_SIZE + " lines from daemon ").append(name).append(" - ").append(log)
- .append(" -----\n");
- sb.append(tail);
- sb.append("----- End of the daemon ").append(name).append(" -----\n");
- } catch (NoSuchFileException e) {
- sb.append(" no ").append(name).append(" at: ").append(log).append("\n");
- } catch (IOException e) {
- sb.append(" unable to read from the daemon ").append(name).append(": ").append(log).append(", because of: ")
- .append(e);
+ static void tail( StringBuilder sb, String name, Path log )
+ {
+ try
+ {
+ String tail = tail( log );
+ sb.append( " " ).append( name ).append( ": " ).append( log ).append( "\n" );
+ sb.append( "----- Last " + TAIL_SIZE + " lines from daemon " ).append( name ).append( " - " ).append( log )
+ .append( " -----\n" );
+ sb.append( tail );
+ sb.append( "----- End of the daemon " ).append( name ).append( " -----\n" );
+ }
+ catch ( NoSuchFileException e )
+ {
+ sb.append( " no " ).append( name ).append( " at: " ).append( log ).append( "\n" );
+ }
+ catch ( IOException e )
+ {
+ sb.append( " unable to read from the daemon " ).append( name ).append( ": " ).append( log )
+ .append( ", because of: " )
+ .append( e );
}
}
@@ -79,23 +90,29 @@ public class DaemonDiagnostics {
* @return tail content
* @throws IOException when reading failed
*/
- static String tail(Path path) throws IOException {
- try (BufferedReader r = Files.newBufferedReader(path)) {
- return String.join("\n", r.lines().collect(lastN(TAIL_SIZE))) + "\n";
+ static String tail( Path path ) throws IOException
+ {
+ try ( BufferedReader r = Files.newBufferedReader( path ) )
+ {
+ return String.join( "\n", r.lines().collect( lastN( TAIL_SIZE ) ) ) + "\n";
}
}
- static <T> Collector<T, ?, List<T>> lastN(int n) {
- return Collector.<T, Deque<T>, List<T>> of(ArrayDeque::new, (acc, t) -> {
- if (acc.size() == n)
+ static <T> Collector<T, ?, List<T>> lastN( int n )
+ {
+ return Collector.<T, Deque<T>, List<T>> of( ArrayDeque::new, ( acc, t ) ->
+ {
+ if ( acc.size() == n )
acc.pollFirst();
- acc.add(t);
- }, (acc1, acc2) -> {
- while (acc2.size() < n && !acc1.isEmpty()) {
- acc2.addFirst(acc1.pollLast());
+ acc.add( t );
+ }, ( acc1, acc2 ) ->
+ {
+ while ( acc2.size() < n && !acc1.isEmpty() )
+ {
+ acc2.addFirst( acc1.pollLast() );
}
return acc2;
- }, ArrayList::new);
+ }, ArrayList::new );
}
}
diff --git a/client/src/main/java/org/mvndaemon/mvnd/client/DaemonParameters.java b/client/src/main/java/org/mvndaemon/mvnd/client/DaemonParameters.java
index 7ba11f9..70861e4 100644
--- a/client/src/main/java/org/mvndaemon/mvnd/client/DaemonParameters.java
+++ b/client/src/main/java/org/mvndaemon/mvnd/client/DaemonParameters.java
@@ -52,75 +52,87 @@ import org.slf4j.LoggerFactory;
/**
* Hold all daemon configuration
*/
-public class DaemonParameters {
+public class DaemonParameters
+{
public static final String LOG_EXTENSION = ".log";
- private static final Logger LOG = LoggerFactory.getLogger(DaemonParameters.class);
+ private static final Logger LOG = LoggerFactory.getLogger( DaemonParameters.class );
private static final String EXT_CLASS_PATH = "maven.ext.class.path";
private static final String EXTENSIONS_FILENAME = ".mvn/extensions.xml";
protected final Map<Path, Properties> mvndProperties = new ConcurrentHashMap<>();
- protected final Function<Path, Properties> provider = path -> mvndProperties.computeIfAbsent(path,
- p -> loadProperties(path));
+ protected final Function<Path, Properties> provider = path -> mvndProperties.computeIfAbsent( path,
+ p -> loadProperties( path ) );
private final Map<String, String> properties;
- public DaemonParameters() {
+ public DaemonParameters()
+ {
this.properties = Collections.emptyMap();
}
- protected DaemonParameters(PropertiesBuilder propertiesBuilder) {
+ protected DaemonParameters( PropertiesBuilder propertiesBuilder )
+ {
this.properties = propertiesBuilder.build();
}
- public List<String> getDaemonOpts() {
+ public List<String> getDaemonOpts()
+ {
return discriminatingValues()
- .map(envValue -> envValue.envKey.asDaemonOpt(envValue.asString()))
- .collect(Collectors.toList());
+ .map( envValue -> envValue.envKey.asDaemonOpt( envValue.asString() ) )
+ .collect( Collectors.toList() );
}
- public Map<String, String> getDaemonOptsMap() {
+ public Map<String, String> getDaemonOptsMap()
+ {
return discriminatingValues()
- .collect(Collectors.toMap(
+ .collect( Collectors.toMap(
envValue -> envValue.envKey.getProperty(),
- EnvValue::asString));
+ EnvValue::asString ) );
}
- Stream<EnvValue> discriminatingValues() {
- return Arrays.stream(Environment.values())
- .filter(Environment::isDiscriminating)
- .map(this::property)
- .filter(EnvValue::isSet);
+ Stream<EnvValue> discriminatingValues()
+ {
+ return Arrays.stream( Environment.values() )
+ .filter( Environment::isDiscriminating )
+ .map( this::property )
+ .filter( EnvValue::isSet );
}
- public void discriminatingCommandLineOptions(List<String> args) {
+ public void discriminatingCommandLineOptions( List<String> args )
+ {
discriminatingValues()
- .forEach(envValue -> envValue.envKey.addCommandLineOption(args, envValue.asString()));
+ .forEach( envValue -> envValue.envKey.addCommandLineOption( args, envValue.asString() ) );
}
- public Path mvndHome() {
- return value(Environment.MVND_HOME)
- .or(new ValueSource(
- description -> description.append("path relative to the mvnd executable"),
- this::mvndHomeFromExecutable))
+ public Path mvndHome()
+ {
+ return value( Environment.MVND_HOME )
+ .or( new ValueSource(
+ description -> description.append( "path relative to the mvnd executable" ),
+ this::mvndHomeFromExecutable ) )
.orSystemProperty()
.orEnvironmentVariable()
- .orLocalProperty(provider, suppliedPropertiesPath())
- .orLocalProperty(provider, localPropertiesPath())
- .orLocalProperty(provider, userPropertiesPath())
+ .orLocalProperty( provider, suppliedPropertiesPath() )
+ .orLocalProperty( provider, localPropertiesPath() )
+ .orLocalProperty( provider, userPropertiesPath() )
.orFail()
.asPath()
.toAbsolutePath().normalize();
}
- private String mvndHomeFromExecutable() {
+ private String mvndHomeFromExecutable()
+ {
Optional<String> cmd = ProcessHandle.current().info().command();
- if (Environment.isNative() && cmd.isPresent()) {
- final Path mvndH = Paths.get(cmd.get()).getParent().getParent();
- if (mvndH != null) {
+ if ( Environment.isNative() && cmd.isPresent() )
+ {
+ final Path mvndH = Paths.get( cmd.get() ).getParent().getParent();
+ if ( mvndH != null )
+ {
final Path mvndDaemonLib = mvndH
- .resolve("mvn/lib/ext/mvnd-daemon-" + BuildProperties.getInstance().getVersion() + ".jar");
- if (Files.exists(mvndDaemonLib)) {
+ .resolve( "mvn/lib/ext/mvnd-daemon-" + BuildProperties.getInstance().getVersion() + ".jar" );
+ if ( Files.exists( mvndDaemonLib ) )
+ {
return mvndH.toString();
}
}
@@ -128,41 +140,48 @@ public class DaemonParameters {
return null;
}
- public Path javaHome() {
- final Path result = value(Environment.JAVA_HOME)
+ public Path javaHome()
+ {
+ final Path result = value( Environment.JAVA_HOME )
.orEnvironmentVariable()
- .orLocalProperty(provider, suppliedPropertiesPath())
- .orLocalProperty(provider, localPropertiesPath())
- .orLocalProperty(provider, userPropertiesPath())
- .orLocalProperty(provider, globalPropertiesPath())
+ .orLocalProperty( provider, suppliedPropertiesPath() )
+ .orLocalProperty( provider, localPropertiesPath() )
+ .orLocalProperty( provider, userPropertiesPath() )
+ .orLocalProperty( provider, globalPropertiesPath() )
.orSystemProperty()
.orFail()
.asPath();
- try {
+ try
+ {
return result.toRealPath();
- } catch (IOException e) {
- throw new RuntimeException("Could not get a real path from path " + result);
+ }
+ catch ( IOException e )
+ {
+ throw new RuntimeException( "Could not get a real path from path " + result );
}
}
- public Path userDir() {
- return value(Environment.USER_DIR)
+ public Path userDir()
+ {
+ return value( Environment.USER_DIR )
.orSystemProperty()
.orFail()
.asPath()
.toAbsolutePath();
}
- public Path userHome() {
- return value(Environment.USER_HOME)
+ public Path userHome()
+ {
+ return value( Environment.USER_HOME )
.orSystemProperty()
.orFail()
.asPath()
.toAbsolutePath();
}
- public Path suppliedPropertiesPath() {
- return value(Environment.MVND_PROPERTIES_PATH)
+ public Path suppliedPropertiesPath()
+ {
+ return value( Environment.MVND_PROPERTIES_PATH )
.orEnvironmentVariable()
.orSystemProperty()
.asPath();
@@ -173,125 +192,148 @@ public class DaemonParameters {
* and used as arguments when starting a daemon JVM.
* See {@link Environment#MVND_JVM_ARGS}.
*/
- public Path jvmConfigPath() {
- return multiModuleProjectDirectory().resolve(".mvn/jvm.config");
+ public Path jvmConfigPath()
+ {
+ return multiModuleProjectDirectory().resolve( ".mvn/jvm.config" );
}
- public Path localPropertiesPath() {
- return multiModuleProjectDirectory().resolve(".mvn/mvnd.properties");
+ public Path localPropertiesPath()
+ {
+ return multiModuleProjectDirectory().resolve( ".mvn/mvnd.properties" );
}
- public Path userPropertiesPath() {
- return userHome().resolve(".m2/mvnd.properties");
+ public Path userPropertiesPath()
+ {
+ return userHome().resolve( ".m2/mvnd.properties" );
}
- public Path globalPropertiesPath() {
- return mvndHome().resolve("conf/mvnd.properties");
+ public Path globalPropertiesPath()
+ {
+ return mvndHome().resolve( "conf/mvnd.properties" );
}
- public Path daemonStorage() {
- return value(Environment.MVND_DAEMON_STORAGE)
+ public Path daemonStorage()
+ {
+ return value( Environment.MVND_DAEMON_STORAGE )
.orSystemProperty()
.orDefault(
- () -> userHome().resolve(".m2/mvnd/registry/" + BuildProperties.getInstance().getVersion()).toString())
+ () -> userHome().resolve( ".m2/mvnd/registry/" + BuildProperties.getInstance().getVersion() )
+ .toString() )
.asPath();
}
- public Path registry() {
- return daemonStorage().resolve("registry.bin");
+ public Path registry()
+ {
+ return daemonStorage().resolve( "registry.bin" );
}
- public Path daemonLog(String daemon) {
- return daemonStorage().resolve("daemon-" + daemon + LOG_EXTENSION);
+ public Path daemonLog( String daemon )
+ {
+ return daemonStorage().resolve( "daemon-" + daemon + LOG_EXTENSION );
}
- public Path daemonOutLog(String daemon) {
- return daemonStorage().resolve("daemon-" + daemon + ".out" + LOG_EXTENSION);
+ public Path daemonOutLog( String daemon )
+ {
+ return daemonStorage().resolve( "daemon-" + daemon + ".out" + LOG_EXTENSION );
}
- public Path multiModuleProjectDirectory() {
- return value(Environment.MAVEN_MULTIMODULE_PROJECT_DIRECTORY)
+ public Path multiModuleProjectDirectory()
+ {
+ return value( Environment.MAVEN_MULTIMODULE_PROJECT_DIRECTORY )
.orSystemProperty()
- .orDefault(() -> findDefaultMultimoduleProjectDirectory(userDir()))
+ .orDefault( () -> findDefaultMultimoduleProjectDirectory( userDir() ) )
.asPath()
.toAbsolutePath().normalize();
}
- public Path multiModuleProjectDirectory(Path projectDir) {
- return Path.of(findDefaultMultimoduleProjectDirectory(projectDir))
+ public Path multiModuleProjectDirectory( Path projectDir )
+ {
+ return Path.of( findDefaultMultimoduleProjectDirectory( projectDir ) )
.toAbsolutePath().normalize();
}
- public Path logbackConfigurationPath() {
- return property(Environment.MVND_LOGBACK)
- .orDefault(() -> mvndHome().resolve("conf/logback.xml").toString())
+ public Path logbackConfigurationPath()
+ {
+ return property( Environment.MVND_LOGBACK )
+ .orDefault( () -> mvndHome().resolve( "conf/logback.xml" ).toString() )
.orFail()
.asPath();
}
- public String minHeapSize() {
- return property(Environment.MVND_MIN_HEAP_SIZE).asString();
+ public String minHeapSize()
+ {
+ return property( Environment.MVND_MIN_HEAP_SIZE ).asString();
}
- public String maxHeapSize() {
- return property(Environment.MVND_MAX_HEAP_SIZE).asString();
+ public String maxHeapSize()
+ {
+ return property( Environment.MVND_MAX_HEAP_SIZE ).asString();
}
- public String threadStackSize() {
- return property(Environment.MVND_THREAD_STACK_SIZE).asString();
+ public String threadStackSize()
+ {
+ return property( Environment.MVND_THREAD_STACK_SIZE ).asString();
}
- public String jvmArgs() {
- return property(Environment.MVND_JVM_ARGS).asString();
+ public String jvmArgs()
+ {
+ return property( Environment.MVND_JVM_ARGS ).asString();
}
- public String jdkJavaOpts() {
- return property(Environment.JDK_JAVA_OPTIONS).asString();
+ public String jdkJavaOpts()
+ {
+ return property( Environment.JDK_JAVA_OPTIONS ).asString();
}
/**
* @return the number of threads (same syntax as Maven's {@code -T}/{@code --threads} option) to pass to the daemon
* unless the user passes his own `-T` or `--threads`.
*/
- public String threads() {
- return property(Environment.MVND_THREADS)
- .orDefault(() -> String.valueOf(property(Environment.MVND_MIN_THREADS)
- .asInt(m -> Math.max(Runtime.getRuntime().availableProcessors() - 1, m))))
+ public String threads()
+ {
+ return property( Environment.MVND_THREADS )
+ .orDefault( () -> String.valueOf( property( Environment.MVND_MIN_THREADS )
+ .asInt( m -> Math.max( Runtime.getRuntime().availableProcessors() - 1, m ) ) ) )
.orFail()
.asString();
}
- public String builder() {
- return property(Environment.MVND_BUILDER).orFail().asString();
+ public String builder()
+ {
+ return property( Environment.MVND_BUILDER ).orFail().asString();
}
/**
* @return absolute normalized path to {@code settings.xml} or {@code null}
*/
- public Path settings() {
- return property(Environment.MAVEN_SETTINGS).asPath();
+ public Path settings()
+ {
+ return property( Environment.MAVEN_SETTINGS ).asPath();
}
/**
* @return path to {@code pom.xml} or {@code null}
*/
- public Path file() {
- return value(Environment.MAVEN_FILE).asPath();
+ public Path file()
+ {
+ return value( Environment.MAVEN_FILE ).asPath();
}
/**
* @return absolute normalized path to local Maven repository or {@code null} if the server is supposed to use the
* default
*/
- public Path mavenRepoLocal() {
- return property(Environment.MAVEN_REPO_LOCAL).asPath();
+ public Path mavenRepoLocal()
+ {
+ return property( Environment.MAVEN_REPO_LOCAL ).asPath();
}
/**
* @return <code>true</code> if maven should be executed within this process instead of spawning a daemon.
*/
- public boolean noDaemon() {
- return value(Environment.MVND_NO_DAEMON)
+ public boolean noDaemon()
+ {
+ return value( Environment.MVND_NO_DAEMON )
.orSystemProperty()
.orEnvironmentVariable()
.orDefault()
@@ -302,8 +344,9 @@ public class DaemonParameters {
*
* @return if mvnd should behave as maven
*/
- public boolean serial() {
- return value(Environment.SERIAL)
+ public boolean serial()
+ {
+ return value( Environment.SERIAL )
.orSystemProperty()
.orDefault()
.asBoolean();
@@ -313,61 +356,75 @@ public class DaemonParameters {
* @param newUserDir where to change the current directory to
* @return a new {@link DaemonParameters} with {@code userDir} set to the given {@code newUserDir}
*/
- public DaemonParameters cd(Path newUserDir) {
- return derive(b -> b.put(Environment.USER_DIR, newUserDir)
- .put(Environment.MAVEN_MULTIMODULE_PROJECT_DIRECTORY, newUserDir));
+ public DaemonParameters cd( Path newUserDir )
+ {
+ return derive( b -> b.put( Environment.USER_DIR, newUserDir )
+ .put( Environment.MAVEN_MULTIMODULE_PROJECT_DIRECTORY, newUserDir ) );
}
- public DaemonParameters withJdkJavaOpts(String opts, boolean before) {
- String org = this.properties.getOrDefault(Environment.JDK_JAVA_OPTIONS.getProperty(), "");
- return derive(b -> b.put(Environment.JDK_JAVA_OPTIONS,
- org.isEmpty() ? opts : before ? opts + " " + org : org + " " + opts));
+ public DaemonParameters withJdkJavaOpts( String opts, boolean before )
+ {
+ String org = this.properties.getOrDefault( Environment.JDK_JAVA_OPTIONS.getProperty(), "" );
+ return derive( b -> b.put( Environment.JDK_JAVA_OPTIONS,
+ org.isEmpty() ? opts : before ? opts + " " + org : org + " " + opts ) );
}
- public DaemonParameters withJvmArgs(String opts, boolean before) {
- String org = this.properties.getOrDefault(Environment.MVND_JVM_ARGS.getProperty(), "");
- return derive(b -> b.put(Environment.MVND_JVM_ARGS,
- org.isEmpty() ? opts : before ? opts + " " + org : org + " " + opts));
+ public DaemonParameters withJvmArgs( String opts, boolean before )
+ {
+ String org = this.properties.getOrDefault( Environment.MVND_JVM_ARGS.getProperty(), "" );
+ return derive( b -> b.put( Environment.MVND_JVM_ARGS,
+ org.isEmpty() ? opts : before ? opts + " " + org : org + " " + opts ) );
}
- protected DaemonParameters derive(Consumer<PropertiesBuilder> customizer) {
- PropertiesBuilder builder = new PropertiesBuilder().putAll(this.properties);
- customizer.accept(builder);
- return new DaemonParameters(builder);
+ protected DaemonParameters derive( Consumer<PropertiesBuilder> customizer )
+ {
+ PropertiesBuilder builder = new PropertiesBuilder().putAll( this.properties );
+ customizer.accept( builder );
+ return new DaemonParameters( builder );
}
- public Duration keepAlive() {
- return property(Environment.MVND_KEEP_ALIVE).orFail().asDuration();
+ public Duration keepAlive()
+ {
+ return property( Environment.MVND_KEEP_ALIVE ).orFail().asDuration();
}
- public int maxLostKeepAlive() {
- return property(Environment.MVND_MAX_LOST_KEEP_ALIVE).orFail().asInt();
+ public int maxLostKeepAlive()
+ {
+ return property( Environment.MVND_MAX_LOST_KEEP_ALIVE ).orFail().asInt();
}
- public boolean noBuffering() {
- return property(Environment.MVND_NO_BUFERING).orFail().asBoolean();
+ public boolean noBuffering()
+ {
+ return property( Environment.MVND_NO_BUFERING ).orFail().asBoolean();
}
- public int rollingWindowSize() {
- return property(Environment.MVND_ROLLING_WINDOW_SIZE).orFail().asInt();
+ public int rollingWindowSize()
+ {
+ return property( Environment.MVND_ROLLING_WINDOW_SIZE ).orFail().asInt();
}
- public Duration purgeLogPeriod() {
- return property(Environment.MVND_LOG_PURGE_PERIOD).orFail().asDuration();
+ public Duration purgeLogPeriod()
+ {
+ return property( Environment.MVND_LOG_PURGE_PERIOD ).orFail().asDuration();
}
- public Optional<SocketFamily> socketFamily() {
- return property(Environment.MVND_SOCKET_FAMILY).asOptional().map(SocketFamily::valueOf);
+ public Optional<SocketFamily> socketFamily()
+ {
+ return property( Environment.MVND_SOCKET_FAMILY ).asOptional().map( SocketFamily::valueOf );
}
- public static String findDefaultMultimoduleProjectDirectory(Path pwd) {
+ public static String findDefaultMultimoduleProjectDirectory( Path pwd )
+ {
Path dir = pwd;
- do {
- if (Files.isDirectory(dir.resolve(".mvn"))) {
+ do
+ {
+ if ( Files.isDirectory( dir.resolve( ".mvn" ) ) )
+ {
return dir.toString();
}
dir = dir.getParent();
- } while (dir != null);
+ }
+ while ( dir != null );
/*
* Return pwd if .mvn directory was not found in the hierarchy.
* Maven does the same thing in mvn shell script's find_maven_basedir()
@@ -376,131 +433,169 @@ public class DaemonParameters {
return pwd.toString();
}
- public EnvValue property(Environment env) {
- return value(env)
+ public EnvValue property( Environment env )
+ {
+ return value( env )
.orSystemProperty()
- .orLocalProperty(provider, suppliedPropertiesPath())
- .orLocalProperty(provider, localPropertiesPath())
- .orLocalProperty(provider, userPropertiesPath())
- .orLocalProperty(provider, globalPropertiesPath())
- .orDefault(() -> defaultValue(env));
+ .orLocalProperty( provider, suppliedPropertiesPath() )
+ .orLocalProperty( provider, localPropertiesPath() )
+ .orLocalProperty( provider, userPropertiesPath() )
+ .orLocalProperty( provider, globalPropertiesPath() )
+ .orDefault( () -> defaultValue( env ) );
}
- protected EnvValue value(Environment env) {
- return new EnvValue(env, new ValueSource(
- description -> description.append("value: ").append(env.getProperty()),
- () -> properties.get(env.getProperty())));
+ protected EnvValue value( Environment env )
+ {
+ return new EnvValue( env, new ValueSource(
+ description -> description.append( "value: " ).append( env.getProperty() ),
+ () -> properties.get( env.getProperty() ) ) );
}
- public static EnvValue systemProperty(Environment env) {
- return new EnvValue(env, EnvValue.systemPropertySource(env));
+ public static EnvValue systemProperty( Environment env )
+ {
+ return new EnvValue( env, EnvValue.systemPropertySource( env ) );
}
- public static EnvValue environmentVariable(Environment env) {
- return new EnvValue(env, EnvValue.environmentVariableSource(env));
+ public static EnvValue environmentVariable( Environment env )
+ {
+ return new EnvValue( env, EnvValue.environmentVariableSource( env ) );
}
- public static EnvValue fromValueSource(Environment env, ValueSource valueSource) {
- return new EnvValue(env, valueSource);
+ public static EnvValue fromValueSource( Environment env, ValueSource valueSource )
+ {
+ return new EnvValue( env, valueSource );
}
- private String defaultValue(Environment env) {
- if (env == Environment.MVND_EXT_CLASSPATH) {
- List<String> cp = parseExtClasspath(userHome());
- return String.join(",", cp);
- } else if (env == Environment.MVND_CORE_EXTENSIONS) {
- try {
- List<String> extensions = readCoreExtensionsDescriptor(multiModuleProjectDirectory()).stream()
- .map(e -> e.getGroupId() + ":" + e.getArtifactId() + ":" + e.getVersion())
- .collect(Collectors.toList());
- return String.join(";", extensions);
- } catch (IOException | XmlPullParserException e) {
- throw new RuntimeException("Unable to parse core extensions", e);
+ private String defaultValue( Environment env )
+ {
+ if ( env == Environment.MVND_EXT_CLASSPATH )
+ {
+ List<String> cp = parseExtClasspath( userHome() );
+ return String.join( ",", cp );
+ }
+ else if ( env == Environment.MVND_CORE_EXTENSIONS )
+ {
+ try
+ {
+ List<String> extensions = readCoreExtensionsDescriptor( multiModuleProjectDirectory() ).stream()
+ .map( e -> e.getGroupId() + ":" + e.getArtifactId() + ":" + e.getVersion() )
+ .collect( Collectors.toList() );
+ return String.join( ";", extensions );
+ }
+ catch ( IOException | XmlPullParserException e )
+ {
+ throw new RuntimeException( "Unable to parse core extensions", e );
}
- } else {
+ }
+ else
+ {
return env.getDefault();
}
}
- private static List<String> parseExtClasspath(Path userDir) {
- String extClassPath = System.getProperty(EXT_CLASS_PATH);
+ private static List<String> parseExtClasspath( Path userDir )
+ {
+ String extClassPath = System.getProperty( EXT_CLASS_PATH );
List<String> jars = new ArrayList<>();
- if (StringUtils.isNotEmpty(extClassPath)) {
- for (String jar : StringUtils.split(extClassPath, File.pathSeparator)) {
- Path path = userDir.resolve(jar).toAbsolutePath();
- jars.add(path.toString());
+ if ( StringUtils.isNotEmpty( extClassPath ) )
+ {
+ for ( String jar : StringUtils.split( extClassPath, File.pathSeparator ) )
+ {
+ Path path = userDir.resolve( jar ).toAbsolutePath();
+ jars.add( path.toString() );
}
}
return jars;
}
- private static List<CoreExtension> readCoreExtensionsDescriptor(Path multiModuleProjectDirectory)
- throws IOException, XmlPullParserException {
- if (multiModuleProjectDirectory == null) {
+ private static List<CoreExtension> readCoreExtensionsDescriptor( Path multiModuleProjectDirectory )
+ throws IOException, XmlPullParserException
+ {
+ if ( multiModuleProjectDirectory == null )
+ {
return Collections.emptyList();
}
- Path extensionsFile = multiModuleProjectDirectory.resolve(EXTENSIONS_FILENAME);
- if (!Files.exists(extensionsFile)) {
+ Path extensionsFile = multiModuleProjectDirectory.resolve( EXTENSIONS_FILENAME );
+ if ( !Files.exists( extensionsFile ) )
+ {
return Collections.emptyList();
}
CoreExtensionsXpp3Reader parser = new CoreExtensionsXpp3Reader();
- try (InputStream is = Files.newInputStream(extensionsFile)) {
- return parser.read(is).getExtensions();
+ try ( InputStream is = Files.newInputStream( extensionsFile ) )
+ {
+ return parser.read( is ).getExtensions();
}
}
- private static Properties loadProperties(Path path) {
+ private static Properties loadProperties( Path path )
+ {
Properties result = new Properties();
- if (Files.exists(path)) {
- try (InputStream in = Files.newInputStream(path)) {
- result.load(in);
- } catch (IOException e) {
- throw new RuntimeException("Could not read " + path);
+ if ( Files.exists( path ) )
+ {
+ try ( InputStream in = Files.newInputStream( path ) )
+ {
+ result.load( in );
+ }
+ catch ( IOException e )
+ {
+ throw new RuntimeException( "Could not read " + path );
}
}
return result;
}
- public static class PropertiesBuilder {
+ public static class PropertiesBuilder
+ {
+
private Map<String, String> properties = new LinkedHashMap<>();
- public PropertiesBuilder put(Environment envKey, Object value) {
- if (value == null) {
- properties.remove(envKey.getProperty());
- } else {
- properties.put(envKey.getProperty(), value.toString());
+ public PropertiesBuilder put( Environment envKey, Object value )
+ {
+ if ( value == null )
+ {
+ properties.remove( envKey.getProperty() );
+ }
+ else
+ {
+ properties.put( envKey.getProperty(), value.toString() );
}
return this;
}
- public PropertiesBuilder putAll(Map<String, String> props) {
- properties.putAll(props);
+ public PropertiesBuilder putAll( Map<String, String> props )
+ {
+ properties.putAll( props );
return this;
}
- public Map<String, String> build() {
+ public Map<String, String> build()
+ {
Map<String, String> props = properties;
properties = null;
- return Collections.unmodifiableMap(props);
+ return Collections.unmodifiableMap( props );
}
}
/**
* A source of an environment value with a description capability.
*/
- public static class ValueSource {
+ public static class ValueSource
+ {
+
final Function<StringBuilder, StringBuilder> descriptionFunction;
final Supplier<String> valueSupplier;
- public ValueSource(Function<StringBuilder, StringBuilder> descriptionFunction, Supplier<String> valueSupplier) {
+ public ValueSource( Function<StringBuilder, StringBuilder> descriptionFunction, Supplier<String> valueSupplier )
+ {
this.descriptionFunction = descriptionFunction;
this.valueSupplier = valueSupplier;
}
/** Mostly for debugging */
@Override
- public String toString() {
- return descriptionFunction.apply(new StringBuilder()).toString();
+ public String toString()
+ {
+ return descriptionFunction.apply( new StringBuilder() ).toString();
}
}
@@ -508,7 +603,8 @@ public class DaemonParameters {
/**
* A chained lazy environment value.
*/
- public static class EnvValue {
+ public static class EnvValue
+ {
static Map<String, String> env = System.getenv();
@@ -516,160 +612,200 @@ public class DaemonParameters {
private final ValueSource valueSource;
protected EnvValue previous;
- public EnvValue(Environment envKey, ValueSource valueSource) {
+ public EnvValue( Environment envKey, ValueSource valueSource )
+ {
this.previous = null;
this.envKey = envKey;
this.valueSource = valueSource;
}
- public EnvValue(EnvValue previous, Environment envKey, ValueSource valueSource) {
+ public EnvValue( EnvValue previous, Environment envKey, ValueSource valueSource )
+ {
this.previous = previous;
this.envKey = envKey;
this.valueSource = valueSource;
}
- private static ValueSource systemPropertySource(Environment env) {
+ private static ValueSource systemPropertySource( Environment env )
+ {
String property = env.getProperty();
- if (property == null) {
- throw new IllegalStateException("Cannot use " + Environment.class.getName() + " for getting a system property");
+ if ( property == null )
+ {
+ throw new IllegalStateException(
+ "Cannot use " + Environment.class.getName() + " for getting a system property" );
}
return new ValueSource(
- description -> description.append("system property ").append(property),
- () -> Environment.getProperty(property));
+ description -> description.append( "system property " ).append( property ),
+ () -> Environment.getProperty( property ) );
}
- private static ValueSource environmentVariableSource(Environment env) {
+ private static ValueSource environmentVariableSource( Environment env )
+ {
String envVar = env.getEnvironmentVariable();
- if (envVar == null) {
+ if ( envVar == null )
+ {
throw new IllegalStateException(
"Cannot use " + Environment.class.getName() + "." + env.name()
- + " for getting an environment variable");
+ + " for getting an environment variable" );
}
return new ValueSource(
- description -> description.append("environment variable ").append(envVar),
- () -> EnvValue.env.get(envVar));
+ description -> description.append( "environment variable " ).append( envVar ),
+ () -> EnvValue.env.get( envVar ) );
}
- public EnvValue orSystemProperty() {
- return new EnvValue(this, envKey, systemPropertySource(envKey));
+ public EnvValue orSystemProperty()
+ {
+ return new EnvValue( this, envKey, systemPropertySource( envKey ) );
}
- public EnvValue orLocalProperty(Function<Path, Properties> provider, Path localPropertiesPath) {
- if (localPropertiesPath != null) {
- return new EnvValue(this, envKey, new ValueSource(
- description -> description.append("property ").append(envKey.getProperty()).append(" in ")
- .append(localPropertiesPath),
- () -> provider.apply(localPropertiesPath).getProperty(envKey.getProperty())));
- } else {
+ public EnvValue orLocalProperty( Function<Path, Properties> provider, Path localPropertiesPath )
+ {
+ if ( localPropertiesPath != null )
+ {
+ return new EnvValue( this, envKey, new ValueSource(
+ description -> description.append( "property " ).append( envKey.getProperty() ).append( " in " )
+ .append( localPropertiesPath ),
+ () -> provider.apply( localPropertiesPath ).getProperty( envKey.getProperty() ) ) );
+ }
+ else
+ {
return this;
}
}
- public EnvValue orEnvironmentVariable() {
- return new EnvValue(this, envKey, environmentVariableSource(envKey));
+ public EnvValue orEnvironmentVariable()
+ {
+ return new EnvValue( this, envKey, environmentVariableSource( envKey ) );
}
- public EnvValue or(ValueSource source) {
- return new EnvValue(this, envKey, source);
+ public EnvValue or( ValueSource source )
+ {
+ return new EnvValue( this, envKey, source );
}
- public EnvValue orDefault() {
- return orDefault(envKey::getDefault);
+ public EnvValue orDefault()
+ {
+ return orDefault( envKey::getDefault );
}
- public EnvValue orDefault(Supplier<String> defaultSupplier) {
- return new EnvValue(this, envKey,
- new ValueSource(sb -> sb.append("default: ").append(defaultSupplier.get()), defaultSupplier));
+ public EnvValue orDefault( Supplier<String> defaultSupplier )
+ {
+ return new EnvValue( this, envKey,
+ new ValueSource( sb -> sb.append( "default: " ).append( defaultSupplier.get() ),
+ defaultSupplier ) );
}
- public EnvValue orFail() {
- return new EnvValue(this, envKey, new ValueSource(sb -> sb, () -> {
+ public EnvValue orFail()
+ {
+ return new EnvValue( this, envKey, new ValueSource( sb -> sb, () ->
+ {
throw couldNotgetValue();
- }));
+ } ) );
}
- IllegalStateException couldNotgetValue() {
+ IllegalStateException couldNotgetValue()
+ {
EnvValue val = this;
- final StringBuilder sb = new StringBuilder("Could not get value for ")
- .append(Environment.class.getSimpleName())
- .append(".").append(envKey.name()).append(" from any of the following sources: ");
+ final StringBuilder sb = new StringBuilder( "Could not get value for " )
+ .append( Environment.class.getSimpleName() )
+ .append( "." ).append( envKey.name() ).append( " from any of the following sources: " );
/*
* Compose the description functions to invert the order thus getting the resolution order in the
* message
*/
- Function<StringBuilder, StringBuilder> description = (s -> s);
- while (val != null) {
- description = description.compose(val.valueSource.descriptionFunction);
+ Function<StringBuilder, StringBuilder> description = ( s -> s );
+ while ( val != null )
+ {
+ description = description.compose( val.valueSource.descriptionFunction );
val = val.previous;
- if (val != null) {
- description = description.compose(s -> s.append(", "));
+ if ( val != null )
+ {
+ description = description.compose( s -> s.append( ", " ) );
}
}
- description.apply(sb);
- return new IllegalStateException(sb.toString());
+ description.apply( sb );
+ return new IllegalStateException( sb.toString() );
}
- String get() {
- if (previous != null) {
+ String get()
+ {
+ if ( previous != null )
+ {
final String result = previous.get();
- if (result != null) {
+ if ( result != null )
+ {
return result;
}
}
final String result = valueSource.valueSupplier.get();
- if (result != null && LOG.isTraceEnabled()) {
- StringBuilder sb = new StringBuilder("Loaded environment value for key [")
- .append(envKey.name())
- .append("] from ");
- valueSource.descriptionFunction.apply(sb);
- sb.append(": [")
- .append(result)
- .append(']');
- LOG.trace(sb.toString());
+ if ( result != null && LOG.isTraceEnabled() )
+ {
+ StringBuilder sb = new StringBuilder( "Loaded environment value for key [" )
+ .append( envKey.name() )
+ .append( "] from " );
+ valueSource.descriptionFunction.apply( sb );
+ sb.append( ": [" )
+ .append( result )
+ .append( ']' );
+ LOG.trace( sb.toString() );
}
return result;
}
- public String asString() {
+ public String asString()
+ {
return get();
}
- public Optional<String> asOptional() {
- return Optional.ofNullable(get());
+ public Optional<String> asOptional()
+ {
+ return Optional.ofNullable( get() );
}
- public Path asPath() {
+ public Path asPath()
+ {
String result = get();
- if (result != null && Os.current().isCygwin()) {
- result = Environment.cygpath(result);
+ if ( result != null && Os.current().isCygwin() )
+ {
+ result = Environment.cygpath( result );
}
- return result == null ? null : Paths.get(result);
+ return result == null ? null : Paths.get( result );
}
- public boolean asBoolean() {
+ public boolean asBoolean()
+ {
final String val = get();
- return "".equals(val) || Boolean.parseBoolean(val);
+ return "".equals( val ) || Boolean.parseBoolean( val );
}
- public int asInt() {
- return Integer.parseInt(get());
+ public int asInt()
+ {
+ return Integer.parseInt( get() );
}
- public int asInt(IntUnaryOperator function) {
- return function.applyAsInt(asInt());
+ public int asInt( IntUnaryOperator function )
+ {
+ return function.applyAsInt( asInt() );
}
- public Duration asDuration() {
- return TimeUtils.toDuration(get());
+ public Duration asDuration()
+ {
+ return TimeUtils.toDuration( get() );
}
- public boolean isSet() {
- if (get() != null) {
+ public boolean isSet()
+ {
+ if ( get() != null )
+ {
return true;
- } else if (envKey.isOptional()) {
+ }
+ else if ( envKey.isOptional() )
+ {
return false;
- } else {
+ }
+ else
+ {
throw couldNotgetValue();
}
}
diff --git a/client/src/main/java/org/mvndaemon/mvnd/client/DefaultClient.java b/client/src/main/java/org/mvndaemon/mvnd/client/DefaultClient.java
index 146e73f..ac74ef9 100644
--- a/client/src/main/java/org/mvndaemon/mvnd/client/DefaultClient.java
+++ b/client/src/main/java/org/mvndaemon/mvnd/client/DefaultClient.java
@@ -57,107 +57,132 @@ import org.slf4j.LoggerFactory;
import static org.mvndaemon.mvnd.client.DaemonParameters.LOG_EXTENSION;
-public class DefaultClient implements Client {
+public class DefaultClient implements Client
+{
- private static final Logger LOGGER = LoggerFactory.getLogger(DefaultClient.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger( DefaultClient.class );
private final DaemonParameters parameters;
- public static void main(String[] argv) throws Exception {
- final List<String> args = new ArrayList<>(Arrays.asList(argv));
+ public static void main( String[] argv ) throws Exception
+ {
+ final List<String> args = new ArrayList<>( Arrays.asList( argv ) );
// Log file
Path logFile = null;
- String sLogFile = Environment.MAVEN_LOG_FILE.removeCommandLineOption(args);
- if (sLogFile != null) {
- if (sLogFile.isEmpty()) {
- throw new IllegalArgumentException("-l and --log-file need to be followed by a path");
- } else {
- logFile = Paths.get(sLogFile);
+ String sLogFile = Environment.MAVEN_LOG_FILE.removeCommandLineOption( args );
+ if ( sLogFile != null )
+ {
+ if ( sLogFile.isEmpty() )
+ {
+ throw new IllegalArgumentException( "-l and --log-file need to be followed by a path" );
+ }
+ else
+ {
+ logFile = Paths.get( sLogFile );
}
}
// Serial
- if (Environment.SERIAL.removeCommandLineOption(args) != null) {
- System.setProperty(Environment.SERIAL.getProperty(), Boolean.toString(true));
+ if ( Environment.SERIAL.removeCommandLineOption( args ) != null )
+ {
+ System.setProperty( Environment.SERIAL.getProperty(), Boolean.toString( true ) );
}
// Batch mode
- final boolean batchMode = Environment.MAVEN_BATCH_MODE.hasCommandLineOption(args)
- || Environment.COMPLETION.hasCommandLineOption(args);
+ final boolean batchMode = Environment.MAVEN_BATCH_MODE.hasCommandLineOption( args )
+ || Environment.COMPLETION.hasCommandLineOption( args );
// Color
- Color styleColor = Color.of(Environment.MAVEN_COLOR.removeCommandLineOption(args)).orElse(Color.auto);
- if (styleColor == Color.auto) {
+ Color styleColor = Color.of( Environment.MAVEN_COLOR.removeCommandLineOption( args ) ).orElse( Color.auto );
+ if ( styleColor == Color.auto )
+ {
/* Translate from auto to either always or never */
/* stdout is not a terminal e.g. when stdout is redirected to a file */
- final boolean stdoutIsTerminal = CLibrary.isatty(1) != 0;
- styleColor = (batchMode || logFile != null || !stdoutIsTerminal) ? Color.never : Color.always;
+ final boolean stdoutIsTerminal = CLibrary.isatty( 1 ) != 0;
+ styleColor = ( batchMode || logFile != null || !stdoutIsTerminal ) ? Color.never : Color.always;
}
/* We cannot use Environment.addCommandLineOption() because that one would pass --color to the daemon
* and --color is not supported there yet. */
- args.add("-D" + Environment.MAVEN_COLOR.getProperty() + "=" + styleColor.name());
+ args.add( "-D" + Environment.MAVEN_COLOR.getProperty() + "=" + styleColor.name() );
- String userJdkJavaOpts = System.getenv(Environment.JDK_JAVA_OPTIONS.getEnvironmentVariable());
- if (userJdkJavaOpts != null) {
- Environment.JDK_JAVA_OPTIONS.addCommandLineOption(args, userJdkJavaOpts);
+ String userJdkJavaOpts = System.getenv( Environment.JDK_JAVA_OPTIONS.getEnvironmentVariable() );
+ if ( userJdkJavaOpts != null )
+ {
+ Environment.JDK_JAVA_OPTIONS.addCommandLineOption( args, userJdkJavaOpts );
}
// System properties
- setSystemPropertiesFromCommandLine(args);
+ setSystemPropertiesFromCommandLine( args );
DaemonParameters parameters = new DaemonParameters();
- if (parameters.serial()) {
- System.setProperty(Environment.MVND_THREADS.getProperty(), Integer.toString(1));
- System.setProperty(Environment.MVND_BUILDER.getProperty(), "singlethreaded");
- System.setProperty(Environment.MVND_NO_BUFERING.getProperty(), Boolean.toString(true));
+ if ( parameters.serial() )
+ {
+ System.setProperty( Environment.MVND_THREADS.getProperty(), Integer.toString( 1 ) );
+ System.setProperty( Environment.MVND_BUILDER.getProperty(), "singlethreaded" );
+ System.setProperty( Environment.MVND_NO_BUFERING.getProperty(), Boolean.toString( true ) );
}
- System.setProperty(Environment.MVND_HOME.getProperty(), parameters.mvndHome().toString());
+ System.setProperty( Environment.MVND_HOME.getProperty(), parameters.mvndHome().toString() );
// .mvn/jvm.config
- if (Files.isRegularFile(parameters.jvmConfigPath())) {
- try (Stream<String> jvmArgs = Files.lines(parameters.jvmConfigPath())) {
- String jvmArgsStr = jvmArgs.collect(Collectors.joining(" "));
- parameters = parameters.withJvmArgs(jvmArgsStr, false);
+ if ( Files.isRegularFile( parameters.jvmConfigPath() ) )
+ {
+ try ( Stream<String> jvmArgs = Files.lines( parameters.jvmConfigPath() ) )
+ {
+ String jvmArgsStr = jvmArgs.collect( Collectors.joining( " " ) );
+ parameters = parameters.withJvmArgs( jvmArgsStr, false );
}
}
int exitCode = 0;
boolean noBuffering = batchMode || parameters.noBuffering();
- try (TerminalOutput output = new TerminalOutput(noBuffering, parameters.rollingWindowSize(), logFile)) {
- try {
- final ExecutionResult result = new DefaultClient(parameters).execute(output, args);
+ try ( TerminalOutput output = new TerminalOutput( noBuffering, parameters.rollingWindowSize(), logFile ) )
+ {
+ try
+ {
+ final ExecutionResult result = new DefaultClient( parameters ).execute( output, args );
exitCode = result.getExitCode();
- } catch (DaemonException.InterruptedException e) {
- final AttributedStyle s = new AttributedStyle().bold().foreground(AttributedStyle.RED);
- String str = new AttributedString(System.lineSeparator() + "Canceled by user", s).toAnsi();
- output.accept(Message.display(str));
+ }
+ catch ( DaemonException.InterruptedException e )
+ {
+ final AttributedStyle s = new AttributedStyle().bold().foreground( AttributedStyle.RED );
+ String str = new AttributedString( System.lineSeparator() + "Canceled by user", s ).toAnsi();
+ output.accept( Message.display( str ) );
exitCode = 130;
}
}
- System.exit(exitCode);
+ System.exit( exitCode );
}
- public static void setSystemPropertiesFromCommandLine(List<String> args) {
- for (String arg : args) {
- String val = Environment.MAVEN_DEFINE.removeCommandLineOption(new ArrayList<>(Collections.singletonList(arg)));
- if (val != null) {
- if (val.isEmpty()) {
- throw new IllegalArgumentException("Missing argument for option " + arg);
+ public static void setSystemPropertiesFromCommandLine( List<String> args )
+ {
+ for ( String arg : args )
+ {
+ String val = Environment.MAVEN_DEFINE
+ .removeCommandLineOption( new ArrayList<>( Collections.singletonList( arg ) ) );
+ if ( val != null )
+ {
+ if ( val.isEmpty() )
+ {
+ throw new IllegalArgumentException( "Missing argument for option " + arg );
}
/* This needs to be done very early, otherwise various DaemonParameters do not work properly */
- final int eqPos = val.indexOf('=');
- if (eqPos >= 0) {
- System.setProperty(val.substring(0, eqPos), val.substring(eqPos + 1));
- } else {
- System.setProperty(val, "");
+ final int eqPos = val.indexOf( '=' );
+ if ( eqPos >= 0 )
+ {
+ System.setProperty( val.substring( 0, eqPos ), val.substring( eqPos + 1 ) );
+ }
+ else
+ {
+ System.setProperty( val, "" );
}
}
}
}
- public DefaultClient(DaemonParameters parameters) {
+ public DefaultClient( DaemonParameters parameters )
+ {
// Those options are needed in order to be able to set the environment correctly
this.parameters = parameters.withJdkJavaOpts(
"--add-opens java.base/java.io=ALL-UNNAMED "
@@ -165,40 +190,43 @@ public class DefaultClient implements Client {
+ "--add-opens java.base/java.util=ALL-UNNAMED "
+ "--add-opens java.base/sun.net.www.protocol.jar=ALL-UNNAMED "
+ "--add-opens java.base/sun.nio.fs=ALL-UNNAMED",
- true);
+ true );
}
@Override
- public ExecutionResult execute(ClientOutput output, List<String> argv) {
- LOGGER.debug("Starting client");
-
- final List<String> args = new ArrayList<>(argv);
- final String completionShell = Environment.COMPLETION.removeCommandLineOption(args);
- if (completionShell != null) {
- output.accept(Message.log(Completion.getCompletion(completionShell, parameters)));
- return DefaultResult.success(argv);
+ public ExecutionResult execute( ClientOutput output, List<String> argv )
+ {
+ LOGGER.debug( "Starting client" );
+
+ final List<String> args = new ArrayList<>( argv );
+ final String completionShell = Environment.COMPLETION.removeCommandLineOption( args );
+ if ( completionShell != null )
+ {
+ output.accept( Message.log( Completion.getCompletion( completionShell, parameters ) ) );
+ return DefaultResult.success( argv );
}
- boolean version = Environment.MAVEN_VERSION.hasCommandLineOption(args);
- boolean showVersion = Environment.MAVEN_SHOW_VERSION.hasCommandLineOption(args);
- boolean debug = Environment.MAVEN_DEBUG.hasCommandLineOption(args);
+ boolean version = Environment.MAVEN_VERSION.hasCommandLineOption( args );
+ boolean showVersion = Environment.MAVEN_SHOW_VERSION.hasCommandLineOption( args );
+ boolean debug = Environment.MAVEN_DEBUG.hasCommandLineOption( args );
// Print version if needed
- if (version || showVersion || debug) {
+ if ( version || showVersion || debug )
+ {
// Print mvnd version
BuildProperties buildProperties = BuildProperties.getInstance();
final String mvndVersionString = "mvnd "
- + (Environment.isNative() ? "native client " : "JVM client ")
+ + ( Environment.isNative() ? "native client " : "JVM client " )
+ buildProperties.getVersion()
+ "-" + buildProperties.getOsName()
+ "-" + buildProperties.getOsArch()
+ " (" + buildProperties.getRevision() + ")";
- boolean isColored = !"never".equals(Environment.MAVEN_COLOR.getCommandLineOption(args));
+ boolean isColored = !"never".equals( Environment.MAVEN_COLOR.getCommandLineOption( args ) );
final String v = isColored
? mvndVersionString
- : Ansi.ansi().bold().a(mvndVersionString).reset().toString();
- output.accept(Message.log(v));
+ : Ansi.ansi().bold().a( mvndVersionString ).reset().toString();
+ output.accept( Message.log( v ) );
// Print terminal information
output.describeTerminal();
/*
@@ -207,213 +235,276 @@ public class DefaultClient implements Client {
*/
}
- try (DaemonRegistry registry = new DaemonRegistry(parameters.registry())) {
- if (Environment.STATUS.removeCommandLineOption(args) != null) {
+ try ( DaemonRegistry registry = new DaemonRegistry( parameters.registry() ) )
+ {
+ if ( Environment.STATUS.removeCommandLineOption( args ) != null )
+ {
final String template = "%8s %7s %24s %7s %5s %23s %s";
- output.accept(Message.log(String.format(template,
- "ID", "PID", "Address", "Status", "RSS", "Last activity", "Java home")));
- for (DaemonInfo d : registry.getAll()) {
- if (ProcessHandle.of(d.getPid()).isEmpty()) {
+ output.accept( Message.log( String.format( template,
+ "ID", "PID", "Address", "Status", "RSS", "Last activity", "Java home" ) ) );
+ for ( DaemonInfo d : registry.getAll() )
+ {
+ if ( ProcessHandle.of( d.getPid() ).isEmpty() )
+ {
/* The process does not exist anymore - remove it from the registry */
- registry.remove(d.getId());
- } else {
- output.accept(Message.log(String.format(template,
+ registry.remove( d.getId() );
+ }
+ else
+ {
+ output.accept( Message.log( String.format( template,
d.getId(), d.getPid(), d.getAddress(), d.getState(),
- OsUtils.kbTohumanReadable(OsUtils.findProcessRssInKb(d.getPid())),
+ OsUtils.kbTohumanReadable( OsUtils.findProcessRssInKb( d.getPid() ) ),
LocalDateTime.ofInstant(
- Instant.ofEpochMilli(Math.max(d.getLastIdle(), d.getLastBusy())),
- ZoneId.systemDefault()),
- d.getJavaHome())));
+ Instant.ofEpochMilli( Math.max( d.getLastIdle(), d.getLastBusy() ) ),
+ ZoneId.systemDefault() ),
+ d.getJavaHome() ) ) );
}
}
- return DefaultResult.success(argv);
+ return DefaultResult.success( argv );
}
- if (Environment.STOP.removeCommandLineOption(args) != null) {
- DaemonInfo[] dis = registry.getAll().toArray(new DaemonInfo[0]);
- if (dis.length > 0) {
- output.accept(Message.display("Stopping " + dis.length + " running daemons"));
- for (DaemonInfo di : dis) {
- try {
- ProcessHandle.of(di.getPid()).ifPresent(ProcessHandle::destroyForcibly);
- } catch (Exception t) {
- System.out.println("Daemon " + di.getId() + ": " + t);
- } finally {
- registry.remove(di.getId());
+ if ( Environment.STOP.removeCommandLineOption( args ) != null )
+ {
+ DaemonInfo[] dis = registry.getAll().toArray( new DaemonInfo[0] );
+ if ( dis.length > 0 )
+ {
+ output.accept( Message.display( "Stopping " + dis.length + " running daemons" ) );
+ for ( DaemonInfo di : dis )
+ {
+ try
+ {
+ ProcessHandle.of( di.getPid() ).ifPresent( ProcessHandle::destroyForcibly );
+ }
+ catch ( Exception t )
+ {
+ System.out.println( "Daemon " + di.getId() + ": " + t );
+ }
+ finally
+ {
+ registry.remove( di.getId() );
}
}
}
- return DefaultResult.success(argv);
+ return DefaultResult.success( argv );
}
- if (Environment.PURGE.removeCommandLineOption(args) != null) {
+ if ( Environment.PURGE.removeCommandLineOption( args ) != null )
+ {
String result = purgeLogs();
- output.accept(Message.display(result != null ? result : "Nothing to purge"));
- return DefaultResult.success(argv);
+ output.accept( Message.display( result != null ? result : "Nothing to purge" ) );
+ return DefaultResult.success( argv );
}
- Optional<String> threads = Optional.ofNullable(Environment.MVND_THREADS.removeCommandLineOption(args));
- Environment.MVND_THREADS.addCommandLineOption(args, threads.orElseGet(parameters::threads));
+ Optional<String> threads = Optional.ofNullable( Environment.MVND_THREADS.removeCommandLineOption( args ) );
+ Environment.MVND_THREADS.addCommandLineOption( args, threads.orElseGet( parameters::threads ) );
- Optional<String> builder = Optional.ofNullable(Environment.MVND_BUILDER.removeCommandLineOption(args));
- Environment.MVND_BUILDER.addCommandLineOption(args, builder.orElseGet(parameters::builder));
+ Optional<String> builder = Optional.ofNullable( Environment.MVND_BUILDER.removeCommandLineOption( args ) );
+ Environment.MVND_BUILDER.addCommandLineOption( args, builder.orElseGet( parameters::builder ) );
- Optional<String> settings = Optional.ofNullable(Environment.MAVEN_SETTINGS.removeCommandLineOption(args))
- .or(() -> Optional.ofNullable(parameters.settings()).map(Path::toString));
- settings.ifPresent(s -> Environment.MAVEN_SETTINGS.addCommandLineOption(args, s));
+ Optional<String> settings = Optional
+ .ofNullable( Environment.MAVEN_SETTINGS.removeCommandLineOption( args ) )
+ .or( () -> Optional.ofNullable( parameters.settings() ).map( Path::toString ) );
+ settings.ifPresent( s -> Environment.MAVEN_SETTINGS.addCommandLineOption( args, s ) );
- Optional<String> repo = Optional.ofNullable(Environment.MAVEN_REPO_LOCAL.removeCommandLineOption(args))
- .or(() -> Optional.ofNullable(parameters.mavenRepoLocal()).map(Path::toString));
- repo.ifPresent(r -> Environment.MAVEN_REPO_LOCAL.addCommandLineOption(args, r));
+ Optional<String> repo = Optional.ofNullable( Environment.MAVEN_REPO_LOCAL.removeCommandLineOption( args ) )
+ .or( () -> Optional.ofNullable( parameters.mavenRepoLocal() ).map( Path::toString ) );
+ repo.ifPresent( r -> Environment.MAVEN_REPO_LOCAL.addCommandLineOption( args, r ) );
- String width = Optional.ofNullable(Environment.MVND_TERMINAL_WIDTH.removeCommandLineOption(args))
- .orElseGet(() -> {
+ String width = Optional.ofNullable( Environment.MVND_TERMINAL_WIDTH.removeCommandLineOption( args ) )
+ .orElseGet( () ->
+ {
int w = output.getTerminalWidth();
- return Integer.toString(w > 0 ? Math.max(w, 80) : 120);
- });
- Environment.MVND_TERMINAL_WIDTH.addCommandLineOption(args, width);
+ return Integer.toString( w > 0 ? Math.max( w, 80 ) : 120 );
+ } );
+ Environment.MVND_TERMINAL_WIDTH.addCommandLineOption( args, width );
Path dir;
- if (Environment.MAVEN_FILE.hasCommandLineOption(args)) {
- dir = parameters.userDir().resolve(Environment.MAVEN_FILE.getCommandLineOption(args));
- if (Files.isRegularFile(dir)) {
+ if ( Environment.MAVEN_FILE.hasCommandLineOption( args ) )
+ {
+ dir = parameters.userDir().resolve( Environment.MAVEN_FILE.getCommandLineOption( args ) );
+ if ( Files.isRegularFile( dir ) )
+ {
dir = dir.getParent();
}
dir = dir.normalize();
- } else {
+ }
+ else
+ {
dir = parameters.userDir();
}
- final DaemonConnector connector = new DaemonConnector(parameters, registry);
- try (DaemonClientConnection daemon = connector.connect(output)) {
- output.setDaemonId(daemon.getDaemon().getId());
- output.setDaemonDispatch(daemon::dispatch);
- output.setDaemonReceive(daemon::enqueue);
+ final DaemonConnector connector = new DaemonConnector( parameters, registry );
+ try ( DaemonClientConnection daemon = connector.connect( output ) )
+ {
+ output.setDaemonId( daemon.getDaemon().getId() );
+ output.setDaemonDispatch( daemon::dispatch );
+ output.setDaemonReceive( daemon::enqueue );
- daemon.dispatch(new Message.BuildRequest(
+ daemon.dispatch( new Message.BuildRequest(
args,
parameters.userDir().toString(),
- parameters.multiModuleProjectDirectory(dir).toString(),
- System.getenv()));
+ parameters.multiModuleProjectDirectory( dir ).toString(),
+ System.getenv() ) );
- output.accept(Message
- .buildStatus("Connected to daemon " + daemon.getDaemon().getId() + ", scanning for projects..."));
+ output.accept( Message
+ .buildStatus(
+ "Connected to daemon " + daemon.getDaemon().getId() + ", scanning for projects..." ) );
// We've sent the request, so it gives us a bit of time to purge the logs
AtomicReference<String> purgeMessage = new AtomicReference<>();
- Thread purgeLog = new Thread(() -> {
- purgeMessage.set(purgeLogs());
- }, "Log purge");
- purgeLog.setDaemon(true);
+ Thread purgeLog = new Thread( () ->
+ {
+ purgeMessage.set( purgeLogs() );
+ }, "Log purge" );
+ purgeLog.setDaemon( true );
purgeLog.start();
- try {
- while (true) {
+ try
+ {
+ while ( true )
+ {
final List<Message> messages = daemon.receive();
- output.accept(messages);
- for (Message m : messages) {
- switch (m.getType()) {
+ output.accept( messages );
+ for ( Message m : messages )
+ {
+ switch ( m.getType() )
+ {
case Message.CANCEL_BUILD:
- return new DefaultResult(argv,
- new InterruptedException("The build was canceled"), 130);
+ return new DefaultResult( argv,
+ new InterruptedException( "The build was canceled" ), 130 );
case Message.BUILD_EXCEPTION:
- final BuildException e = (BuildException) m;
- return new DefaultResult(argv,
- new Exception(e.getClassName() + ": " + e.getMessage() + "\n" + e.getStackTrace()),
- 1);
+ final BuildException e = ( BuildException ) m;
+ return new DefaultResult( argv,
+ new Exception(
+ e.getClassName() + ": " + e.getMessage() + "\n" + e.getStackTrace() ),
+ 1 );
case Message.BUILD_FINISHED:
- return new DefaultResult(argv, null, ((BuildFinished) m).getExitCode());
+ return new DefaultResult( argv, null, ( ( BuildFinished ) m ).getExitCode() );
}
}
}
- } finally {
+ }
+ finally
+ {
String msg = purgeMessage.get();
- if (msg != null) {
- output.accept(Message.display(msg));
+ if ( msg != null )
+ {
+ output.accept( Message.display( msg ) );
}
}
}
}
}
- private String purgeLogs() {
+ private String purgeLogs()
+ {
Path storage = parameters.daemonStorage();
Duration purgeLogPeriod = parameters.purgeLogPeriod();
- if (!Files.isDirectory(storage) || !TimeUtils.isPositive(purgeLogPeriod)) {
+ if ( !Files.isDirectory( storage ) || !TimeUtils.isPositive( purgeLogPeriod ) )
+ {
return null;
}
- String date = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault()).format(Instant.now());
- Path log = storage.resolve("purge-" + date + ".log");
+ String date = DateTimeFormatter.ofPattern( "yyyy-MM-dd" ).withZone( ZoneId.systemDefault() )
+ .format( Instant.now() );
+ Path log = storage.resolve( "purge-" + date + ".log" );
List<Path> deleted = new ArrayList<>();
List<Throwable> exceptions = new ArrayList<>();
- FileTime limit = FileTime.from(Instant.now().minus(purgeLogPeriod));
- try (Stream<Path> storagePath = Files.list(storage)) {
- storagePath.filter(p -> p.getFileName().toString().endsWith(LOG_EXTENSION))
- .filter(p -> !log.equals(p))
- .filter(p -> {
- try {
- FileTime lmt = Files.getLastModifiedTime(p);
- return lmt.compareTo(limit) < 0;
- } catch (IOException e) {
- exceptions.add(e);
+ FileTime limit = FileTime.from( Instant.now().minus( purgeLogPeriod ) );
+ try ( Stream<Path> storagePath = Files.list( storage ) )
+ {
+ storagePath.filter( p -> p.getFileName().toString().endsWith( LOG_EXTENSION ) )
+ .filter( p -> !log.equals( p ) )
+ .filter( p ->
+ {
+ try
+ {
+ FileTime lmt = Files.getLastModifiedTime( p );
+ return lmt.compareTo( limit ) < 0;
+ }
+ catch ( IOException e )
+ {
+ exceptions.add( e );
return false;
}
- })
- .forEach(p -> {
- try {
- Files.delete(p);
- deleted.add(p);
- } catch (IOException e) {
- exceptions.add(e);
+ } )
+ .forEach( p ->
+ {
+ try
+ {
+ Files.delete( p );
+ deleted.add( p );
+ }
+ catch ( IOException e )
+ {
+ exceptions.add( e );
}
- });
- } catch (Exception e) {
- exceptions.add(e);
+ } );
}
- if (exceptions.isEmpty() && deleted.isEmpty()) {
+ catch ( Exception e )
+ {
+ exceptions.add( e );
+ }
+ if ( exceptions.isEmpty() && deleted.isEmpty() )
+ {
return null;
}
String logMessage;
- try (PrintWriter w = new PrintWriter(Files.newBufferedWriter(log,
- StandardOpenOption.WRITE, StandardOpenOption.APPEND, StandardOpenOption.CREATE))) {
- w.printf("Purge executed at %s%n", Instant.now().toString());
- if (deleted.isEmpty()) {
- w.printf("No files deleted.%n");
- } else {
- w.printf("Deleted files:%n");
- for (Path p : deleted) {
- w.printf(" %s%n", p.toString());
+ try ( PrintWriter w = new PrintWriter( Files.newBufferedWriter( log,
+ StandardOpenOption.WRITE, StandardOpenOption.APPEND, StandardOpenOption.CREATE ) ) )
+ {
+ w.printf( "Purge executed at %s%n", Instant.now().toString() );
+ if ( deleted.isEmpty() )
+ {
+ w.printf( "No files deleted.%n" );
+ }
+ else
+ {
+ w.printf( "Deleted files:%n" );
+ for ( Path p : deleted )
+ {
+ w.printf( " %s%n", p.toString() );
}
}
- if (!exceptions.isEmpty()) {
- w.printf("%d exception(s) occurred during the purge", exceptions.size());
- for (Throwable t : exceptions) {
- t.printStackTrace(w);
+ if ( !exceptions.isEmpty() )
+ {
+ w.printf( "%d exception(s) occurred during the purge", exceptions.size() );
+ for ( Throwable t : exceptions )
+ {
+ t.printStackTrace( w );
}
}
char[] buf = new char[80];
- Arrays.fill(buf, '=');
- w.printf("%s%n", new String(buf));
+ Arrays.fill( buf, '=' );
+ w.printf( "%s%n", new String( buf ) );
logMessage = "log available in " + log.toString();
- } catch (IOException e) {
+ }
+ catch ( IOException e )
+ {
logMessage = "an exception occurred when writing log to " + log.toString() + ": " + e.toString();
}
- if (exceptions.isEmpty()) {
- return String.format("Purged %d log files (%s)", deleted.size(), logMessage);
- } else {
- return String.format("Purged %d log files with %d exceptions (%s)", deleted.size(), exceptions.size(), logMessage);
+ if ( exceptions.isEmpty() )
+ {
+ return String.format( "Purged %d log files (%s)", deleted.size(), logMessage );
+ }
+ else
+ {
+ return String.format( "Purged %d log files with %d exceptions (%s)", deleted.size(), exceptions.size(),
+ logMessage );
}
}
- private static class DefaultResult implements ExecutionResult {
+ private static class DefaultResult implements ExecutionResult
+ {
private final Exception exception;
private final List<String> args;
private final int exitCode;
- public static DefaultResult success(List<String> args) {
- return new DefaultResult(args, null, 0);
+ public static DefaultResult success( List<String> args )
+ {
+ return new DefaultResult( args, null, 0 );
}
- private DefaultResult(List<String> args, Exception exception, int exitCode) {
+ private DefaultResult( List<String> args, Exception exception, int exitCode )
+ {
super();
this.args = args;
this.exception = exception;
@@ -421,35 +512,45 @@ public class DefaultClient implements Client {
}
@Override
- public ExecutionResult assertSuccess() {
- if (exception != null) {
- throw new AssertionError(ExecutionResult.appendCommand(new StringBuilder("Build failed: "), args).toString(),
- exception);
+ public ExecutionResult assertSuccess()
+ {
+ if ( exception != null )
+ {
+ throw new AssertionError(
+ ExecutionResult.appendCommand( new StringBuilder( "Build failed: " ), args ).toString(),
+ exception );
}
- if (exitCode != 0) {
+ if ( exitCode != 0 )
+ {
throw new AssertionError(
ExecutionResult.appendCommand(
- new StringBuilder("Build exited with non-zero exit code " + exitCode + ": "), args).toString(),
- exception);
+ new StringBuilder( "Build exited with non-zero exit code " + exitCode + ": " ), args )
+ .toString(),
+ exception );
}
return this;
}
@Override
- public ExecutionResult assertFailure() {
- if (exception == null && exitCode == 0) {
- throw new AssertionError(ExecutionResult.appendCommand(new StringBuilder("Build did not fail: "), args));
+ public ExecutionResult assertFailure()
+ {
+ if ( exception == null && exitCode == 0 )
+ {
+ throw new AssertionError(
+ ExecutionResult.appendCommand( new StringBuilder( "Build did not fail: " ), args ) );
}
return this;
}
@Override
- public int getExitCode() {
+ public int getExitCode()
+ {
return exitCode;
}
@Override
- public boolean isSuccess() {
+ public boolean isSuccess()
+ {
return exception == null;
}
diff --git a/client/src/main/java/org/mvndaemon/mvnd/client/ExecutionResult.java b/client/src/main/java/org/mvndaemon/mvnd/client/ExecutionResult.java
index 0c87f01..1eb82e4 100644
--- a/client/src/main/java/org/mvndaemon/mvnd/client/ExecutionResult.java
+++ b/client/src/main/java/org/mvndaemon/mvnd/client/ExecutionResult.java
@@ -20,7 +20,8 @@ import java.util.List;
/**
* A result of a {@code mvnd} build.
*/
-public interface ExecutionResult {
+public interface ExecutionResult
+{
boolean isSuccess();
@@ -30,10 +31,12 @@ public interface ExecutionResult {
int getExitCode();
- public static StringBuilder appendCommand(StringBuilder sb, List<String> args) {
- sb.append("mvnd");
- for (String arg : args) {
- sb.append(" \"").append(arg).append('"');
+ public static StringBuilder appendCommand( StringBuilder sb, List<String> args )
+ {
+ sb.append( "mvnd" );
+ for ( String arg : args )
+ {
+ sb.append( " \"" ).append( arg ).append( '"' );
}
return sb;
}
diff --git a/client/src/main/java/org/mvndaemon/mvnd/client/svm/ReflectionRegistration.java b/client/src/main/java/org/mvndaemon/mvnd/client/svm/ReflectionRegistration.java
index 97c1b57..d4a2f37 100644
--- a/client/src/main/java/org/mvndaemon/mvnd/client/svm/ReflectionRegistration.java
+++ b/client/src/main/java/org/mvndaemon/mvnd/client/svm/ReflectionRegistration.java
@@ -19,8 +19,11 @@ import com.oracle.svm.core.annotate.AutomaticFeature;
import org.graalvm.nativeimage.hosted.Feature;
@AutomaticFeature
-public class ReflectionRegistration implements Feature {
- public void beforeAnalysis(BeforeAnalysisAccess access) {
+public class ReflectionRegistration implements Feature
+{
+
+ public void beforeAnalysis( BeforeAnalysisAccess access )
+ {
// try {
// RuntimeReflection.register(AsiExtraField.class.getConstructors());
// } catch (SecurityException e) {
diff --git a/client/src/main/java/org/mvndaemon/mvnd/client/svm/StaticMDCBinderSubstitution.java b/client/src/main/java/org/mvndaemon/mvnd/client/svm/StaticMDCBinderSubstitution.java
index 5a0fcd9..d99db47 100644
--- a/client/src/main/java/org/mvndaemon/mvnd/client/svm/StaticMDCBinderSubstitution.java
+++ b/client/src/main/java/org/mvndaemon/mvnd/client/svm/StaticMDCBinderSubstitution.java
@@ -21,11 +21,13 @@ import org.slf4j.MDC;
import org.slf4j.impl.StaticMDCBinder;
import org.slf4j.spi.MDCAdapter;
-@TargetClass(MDC.class)
-final class StaticMDCBinderSubstitution {
+@TargetClass( MDC.class )
+final class StaticMDCBinderSubstitution
+{
@Substitute
- private static MDCAdapter bwCompatibleGetMDCAdapterFromBinder() throws NoClassDefFoundError {
+ private static MDCAdapter bwCompatibleGetMDCAdapterFromBinder() throws NoClassDefFoundError
+ {
return StaticMDCBinder.SINGLETON.getMDCA();
}
diff --git a/client/src/test/java/org/mvndaemon/mvnd/client/CompletionGeneratorTest.java b/client/src/test/java/org/mvndaemon/mvnd/client/CompletionGeneratorTest.java
index 03a9036..ced6c02 100644
--- a/client/src/test/java/org/mvndaemon/mvnd/client/CompletionGeneratorTest.java
+++ b/client/src/test/java/org/mvndaemon/mvnd/client/CompletionGeneratorTest.java
@@ -29,48 +29,50 @@ import org.mvndaemon.mvnd.common.Environment;
import org.mvndaemon.mvnd.common.Environment.OptionOrigin;
import org.mvndaemon.mvnd.common.IoUtils;
-public class CompletionGeneratorTest {
+public class CompletionGeneratorTest
+{
@Test
- void generate() throws IOException {
+ void generate() throws IOException
+ {
- String template = IoUtils.readResource(Completion.class.getClassLoader(),
- "completion-templates/mvnd-bash-completion.bash");
+ String template = IoUtils.readResource( Completion.class.getClassLoader(),
+ "completion-templates/mvnd-bash-completion.bash" );
- final String shortOpts = Stream.of(Environment.values())
- .filter(env -> !env.isInternal())
- .flatMap(env -> env.getOptionMap().entrySet().stream())
- .filter(optEntry -> optEntry.getValue() == OptionOrigin.mvnd)
- .map(Map.Entry::getKey)
- .filter(opt -> !opt.startsWith("--"))
+ final String shortOpts = Stream.of( Environment.values() )
+ .filter( env -> !env.isInternal() )
+ .flatMap( env -> env.getOptionMap().entrySet().stream() )
+ .filter( optEntry -> optEntry.getValue() == OptionOrigin.mvnd )
+ .map( Map.Entry::getKey )
+ .filter( opt -> !opt.startsWith( "--" ) )
.sorted()
- .collect(Collectors.joining("|"));
+ .collect( Collectors.joining( "|" ) );
- final String longOpts = Stream.of(Environment.values())
- .filter(env -> !env.isInternal())
- .flatMap(env -> env.getOptionMap().entrySet().stream())
- .filter(optEntry -> optEntry.getValue() == OptionOrigin.mvnd)
- .map(Map.Entry::getKey)
- .filter(opt -> opt.startsWith("--"))
+ final String longOpts = Stream.of( Environment.values() )
+ .filter( env -> !env.isInternal() )
+ .flatMap( env -> env.getOptionMap().entrySet().stream() )
+ .filter( optEntry -> optEntry.getValue() == OptionOrigin.mvnd )
+ .map( Map.Entry::getKey )
+ .filter( opt -> opt.startsWith( "--" ) )
.sorted()
- .collect(Collectors.joining("|"));
+ .collect( Collectors.joining( "|" ) );
- final String props = Stream.of(Environment.values())
- .filter(env -> !env.isInternal())
- .map(Environment::getProperty)
- .filter(Objects::nonNull)
+ final String props = Stream.of( Environment.values() )
+ .filter( env -> !env.isInternal() )
+ .map( Environment::getProperty )
+ .filter( Objects::nonNull )
.sorted()
- .map(prop -> "-D" + prop)
- .collect(Collectors.joining("|"));
+ .map( prop -> "-D" + prop )
+ .collect( Collectors.joining( "|" ) );
- template = template.replace("%mvnd_opts%", shortOpts);
- template = template.replace("%mvnd_long_opts%", longOpts);
- template = template.replace("%mvnd_properties%", props);
+ template = template.replace( "%mvnd_opts%", shortOpts );
+ template = template.replace( "%mvnd_long_opts%", longOpts );
+ template = template.replace( "%mvnd_properties%", props );
- final Path baseDir = Paths.get(System.getProperty("project.basedir", "."));
+ final Path baseDir = Paths.get( System.getProperty( "project.basedir", "." ) );
- final byte[] bytes = template.getBytes(StandardCharsets.UTF_8);
- Files.write(baseDir.resolve("../dist/src/main/distro/bin/mvnd-bash-completion.bash"), bytes);
+ final byte[] bytes = template.getBytes( StandardCharsets.UTF_8 );
+ Files.write( baseDir.resolve( "../dist/src/main/distro/bin/mvnd-bash-completion.bash" ), bytes );
}
diff --git a/client/src/test/java/org/mvndaemon/mvnd/client/DaemonConnectorTest.java b/client/src/test/java/org/mvndaemon/mvnd/client/DaemonConnectorTest.java
index 11eaf55..6d2fe48 100644
--- a/client/src/test/java/org/mvndaemon/mvnd/client/DaemonConnectorTest.java
+++ b/client/src/test/java/org/mvndaemon/mvnd/client/DaemonConnectorTest.java
@@ -20,12 +20,14 @@ import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
-public class DaemonConnectorTest {
+public class DaemonConnectorTest
+{
@Test
- public void newId() {
+ public void newId()
+ {
String id = DaemonConnector.newId();
- assertNotNull(id);
- assertEquals(8, id.length());
+ assertNotNull( id );
+ assertEquals( 8, id.length() );
}
}
diff --git a/client/src/test/java/org/mvndaemon/mvnd/client/EnvironmentTest.java b/client/src/test/java/org/mvndaemon/mvnd/client/EnvironmentTest.java
index 5dca974..ab364bc 100644
--- a/client/src/test/java/org/mvndaemon/mvnd/client/EnvironmentTest.java
+++ b/client/src/test/java/org/mvndaemon/mvnd/client/EnvironmentTest.java
@@ -30,133 +30,158 @@ import org.mvndaemon.mvnd.common.Environment;
import static org.junit.jupiter.api.Assertions.assertEquals;
-public class EnvironmentTest {
+public class EnvironmentTest
+{
@Test
- void arguments() {
- assertEquals("foo=bar", Environment.MAVEN_DEFINE.removeCommandLineOption(list("-Dfoo=bar")));
- assertEquals("foo=bar", Environment.MAVEN_DEFINE.removeCommandLineOption(list("-D", "foo=bar")));
- assertEquals("foo=bar", Environment.MAVEN_DEFINE.removeCommandLineOption(list("--define", "foo=bar")));
- assertEquals("foo=bar", Environment.MAVEN_DEFINE.removeCommandLineOption(list("--define=foo=bar")));
+ void arguments()
+ {
+ assertEquals( "foo=bar", Environment.MAVEN_DEFINE.removeCommandLineOption( list( "-Dfoo=bar" ) ) );
+ assertEquals( "foo=bar", Environment.MAVEN_DEFINE.removeCommandLineOption( list( "-D", "foo=bar" ) ) );
+ assertEquals( "foo=bar", Environment.MAVEN_DEFINE.removeCommandLineOption( list( "--define", "foo=bar" ) ) );
+ assertEquals( "foo=bar", Environment.MAVEN_DEFINE.removeCommandLineOption( list( "--define=foo=bar" ) ) );
- assertEquals("foo", Environment.MAVEN_DEFINE.removeCommandLineOption(list("-D=foo")));
- assertEquals("foo", Environment.MAVEN_DEFINE.removeCommandLineOption(list("-Dfoo")));
- assertEquals("foo", Environment.MAVEN_DEFINE.removeCommandLineOption(list("-D", "foo")));
+ assertEquals( "foo", Environment.MAVEN_DEFINE.removeCommandLineOption( list( "-D=foo" ) ) );
+ assertEquals( "foo", Environment.MAVEN_DEFINE.removeCommandLineOption( list( "-Dfoo" ) ) );
+ assertEquals( "foo", Environment.MAVEN_DEFINE.removeCommandLineOption( list( "-D", "foo" ) ) );
- assertEquals("foo=", Environment.MAVEN_DEFINE.removeCommandLineOption(list("-Dfoo=")));
+ assertEquals( "foo=", Environment.MAVEN_DEFINE.removeCommandLineOption( list( "-Dfoo=" ) ) );
- assertEquals("", Environment.MAVEN_DEFINE.removeCommandLineOption(list("-D")));
- assertEquals("", Environment.MAVEN_DEFINE.removeCommandLineOption(list("--define")));
+ assertEquals( "", Environment.MAVEN_DEFINE.removeCommandLineOption( list( "-D" ) ) );
+ assertEquals( "", Environment.MAVEN_DEFINE.removeCommandLineOption( list( "--define" ) ) );
}
- private List<String> list(String... items) {
- return new ArrayList<>(Arrays.asList(items));
+ private List<String> list( String... items )
+ {
+ return new ArrayList<>( Arrays.asList( items ) );
}
@Test
- void prop() {
- try (EnvironmentResource env = new EnvironmentResource()) {
- env.props("mvnd.home", "/maven/home/prop");
- assertEquals("/maven/home/prop", DaemonParameters.systemProperty(Environment.MVND_HOME).asString());
+ void prop()
+ {
+ try ( EnvironmentResource env = new EnvironmentResource() )
+ {
+ env.props( "mvnd.home", "/maven/home/prop" );
+ assertEquals( "/maven/home/prop", DaemonParameters.systemProperty( Environment.MVND_HOME ).asString() );
}
}
@Test
- void env() {
- try (EnvironmentResource env = new EnvironmentResource()) {
- env.env("MVND_HOME", "/maven/home/env");
- assertEquals("/maven/home/env", DaemonParameters.environmentVariable(Environment.MVND_HOME).asString());
+ void env()
+ {
+ try ( EnvironmentResource env = new EnvironmentResource() )
+ {
+ env.env( "MVND_HOME", "/maven/home/env" );
+ assertEquals( "/maven/home/env", DaemonParameters.environmentVariable( Environment.MVND_HOME ).asString() );
}
}
@Test
- void localProps() {
- try (EnvironmentResource env = new EnvironmentResource()) {
+ void localProps()
+ {
+ try ( EnvironmentResource env = new EnvironmentResource() )
+ {
final Properties localProps = new Properties();
- localProps.put("mvnd.home", "/maven/home/local");
- assertEquals(Paths.get("/maven/home/local"),
+ localProps.put( "mvnd.home", "/maven/home/local" );
+ assertEquals( Paths.get( "/maven/home/local" ),
DaemonParameters
- .environmentVariable(Environment.MVND_HOME)
+ .environmentVariable( Environment.MVND_HOME )
.orSystemProperty()
- .orLocalProperty(path -> localProps, Paths.get("/local/properties"))
+ .orLocalProperty( path -> localProps, Paths.get( "/local/properties" ) )
.orFail()
- .asPath());
+ .asPath() );
}
}
@Test
- void envBeforeProp() {
- try (EnvironmentResource env = new EnvironmentResource()) {
- env.props("mvnd.home", "/maven/home/prop");
- env.env("MVND_HOME", "/maven/home/env");
- assertEquals("/maven/home/env",
+ void envBeforeProp()
+ {
+ try ( EnvironmentResource env = new EnvironmentResource() )
+ {
+ env.props( "mvnd.home", "/maven/home/prop" );
+ env.env( "MVND_HOME", "/maven/home/env" );
+ assertEquals( "/maven/home/env",
DaemonParameters
- .environmentVariable(Environment.MVND_HOME)
+ .environmentVariable( Environment.MVND_HOME )
.orSystemProperty()
- .asString());
+ .asString() );
}
}
@Test
- void fail() {
- try (EnvironmentResource env = new EnvironmentResource()) {
- try {
- assertEquals("/maven/home/env",
+ void fail()
+ {
+ try ( EnvironmentResource env = new EnvironmentResource() )
+ {
+ try
+ {
+ assertEquals( "/maven/home/env",
DaemonParameters
- .environmentVariable(Environment.MVND_HOME)
+ .environmentVariable( Environment.MVND_HOME )
.orSystemProperty()
.orFail()
- .asString());
- Assertions.fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
+ .asString() );
+ Assertions.fail( "IllegalStateException expected" );
+ }
+ catch ( IllegalStateException e )
+ {
assertEquals(
"Could not get value for Environment.MVND_HOME from any of the following sources: environment variable MVND_HOME, system property mvnd.home",
- e.getMessage());
+ e.getMessage() );
}
}
}
@Test
- void cygwin() {
- assertEquals("C:\\jdk-11.0.2\\", Environment.cygpath("/cygdrive/c/jdk-11.0.2/"));
+ void cygwin()
+ {
+ assertEquals( "C:\\jdk-11.0.2\\", Environment.cygpath( "/cygdrive/c/jdk-11.0.2/" ) );
}
@Test
- void emptyBooleanEnvValueIsTrue() {
+ void emptyBooleanEnvValueIsTrue()
+ {
final String EMPTY_STRING = "";
- final EnvValue envVal = new EnvValue(Environment.MVND_NO_BUFERING,
- new ValueSource(sb -> sb.append("envValueAsBoolean"), () -> EMPTY_STRING));
- assertEquals(true, envVal.asBoolean());
+ final EnvValue envVal = new EnvValue( Environment.MVND_NO_BUFERING,
+ new ValueSource( sb -> sb.append( "envValueAsBoolean" ), () -> EMPTY_STRING ) );
+ assertEquals( true, envVal.asBoolean() );
}
- static class EnvironmentResource implements AutoCloseable {
+ static class EnvironmentResource implements AutoCloseable
+ {
private final Properties props = new Properties();
private final Map<String, String> env = new HashMap<>();
- public EnvironmentResource() {
+ public EnvironmentResource()
+ {
DaemonParameters.EnvValue.env = env;
- Environment.setProperties(props);
+ Environment.setProperties( props );
}
- public void props(String... props) {
+ public void props( String... props )
+ {
int i = 0;
- while (i < props.length) {
- this.props.setProperty(props[i++], props[i++]);
+ while ( i < props.length )
+ {
+ this.props.setProperty( props[i++], props[i++] );
}
}
- public void env(String... env) {
+ public void env( String... env )
+ {
int i = 0;
- while (i < env.length) {
- this.env.put(env[i++], env[i++]);
+ while ( i < env.length )
+ {
+ this.env.put( env[i++], env[i++] );
}
}
@Override
- public void close() {
+ public void close()
+ {
DaemonParameters.EnvValue.env = System.getenv();
- Environment.setProperties(System.getProperties());
+ Environment.setProperties( System.getProperties() );
}
}
diff --git a/client/src/test/java/org/mvndaemon/mvnd/client/OsUtilsTest.java b/client/src/test/java/org/mvndaemon/mvnd/client/OsUtilsTest.java
index d32d630..97d66f3 100644
--- a/client/src/test/java/org/mvndaemon/mvnd/client/OsUtilsTest.java
+++ b/client/src/test/java/org/mvndaemon/mvnd/client/OsUtilsTest.java
@@ -19,14 +19,16 @@ import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mvndaemon.mvnd.common.OsUtils;
-public class OsUtilsTest {
+public class OsUtilsTest
+{
/**
* This test needs to be in the client module as long as the common module is on Java 8
*/
@Test
- void findProcessRssInKb() {
- long rss = OsUtils.findProcessRssInKb(ProcessHandle.current().pid());
- Assertions.assertThat(rss).isGreaterThan(0);
+ void findProcessRssInKb()
+ {
+ long rss = OsUtils.findProcessRssInKb( ProcessHandle.current().pid() );
+ Assertions.assertThat( rss ).isGreaterThan( 0 );
}
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/BufferCaster.java b/common/src/main/java/org/mvndaemon/mvnd/common/BufferCaster.java
index e0bc9a6..76d0f70 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/BufferCaster.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/BufferCaster.java
@@ -22,13 +22,16 @@ import java.nio.Buffer;
* File origin:
* https://github.com/gradle/gradle/blob/v5.6.2/subprojects/base-services/src/main/java/org/gradle/internal/io/BufferCaster.java
*/
-public class BufferCaster {
+public class BufferCaster
+{
+
/**
* Without this cast, when the code compiled by Java 9+ is executed on Java 8, it will throw
* java.lang.NoSuchMethodError: Method flip()Ljava/nio/ByteBuffer; does not exist in class java.nio.ByteBuffer
*/
- @SuppressWarnings("RedundantCast")
- public static <T extends Buffer> Buffer cast(T byteBuffer) {
- return (Buffer) byteBuffer;
+ @SuppressWarnings( "RedundantCast" )
+ public static <T extends Buffer> Buffer cast( T byteBuffer )
+ {
+ return ( Buffer ) byteBuffer;
}
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/BuildProperties.java b/common/src/main/java/org/mvndaemon/mvnd/common/BuildProperties.java
index 40b11a8..4d9c28e 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/BuildProperties.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/BuildProperties.java
@@ -19,26 +19,32 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
-public class BuildProperties {
+public class BuildProperties
+{
private static final BuildProperties INSTANCE = load();
- public static BuildProperties getInstance() {
+ public static BuildProperties getInstance()
+ {
return INSTANCE;
}
- public static BuildProperties load() {
+ public static BuildProperties load()
+ {
final Properties buildProperties = new Properties();
- try (InputStream is = BuildProperties.class.getResourceAsStream("build.properties")) {
- buildProperties.load(is);
- } catch (IOException e) {
- throw new RuntimeException("Could not read build.properties");
+ try ( InputStream is = BuildProperties.class.getResourceAsStream( "build.properties" ) )
+ {
+ buildProperties.load( is );
+ }
+ catch ( IOException e )
+ {
+ throw new RuntimeException( "Could not read build.properties" );
}
return new BuildProperties(
- buildProperties.getProperty("version"),
- buildProperties.getProperty("revision"),
- buildProperties.getProperty("os.detected.name"),
- buildProperties.getProperty("os.detected.arch"));
+ buildProperties.getProperty( "version" ),
+ buildProperties.getProperty( "revision" ),
+ buildProperties.getProperty( "os.detected.name" ),
+ buildProperties.getProperty( "os.detected.arch" ) );
}
private final String version;
@@ -46,26 +52,31 @@ public class BuildProperties {
private final String osArch;
private final String revision;
- public BuildProperties(String version, String revision, String os, String arch) {
+ public BuildProperties( String version, String revision, String os, String arch )
+ {
this.version = version;
this.revision = revision;
this.osName = os;
this.osArch = arch;
}
- public String getVersion() {
+ public String getVersion()
+ {
return version;
}
- public String getOsName() {
+ public String getOsName()
+ {
return osName;
}
- public String getOsArch() {
+ public String getOsArch()
+ {
return osArch;
}
- public String getRevision() {
+ public String getRevision()
+ {
return revision;
}
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/ByteChannelWrapper.java b/common/src/main/java/org/mvndaemon/mvnd/common/ByteChannelWrapper.java
index b299151..f0c99a6 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/ByteChannelWrapper.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/ByteChannelWrapper.java
@@ -23,31 +23,37 @@ import java.nio.channels.ByteChannel;
* Trivial ByteChannel wrapper to avoid the read/write synchronization which
* happens when the channel implements SelectableChannel.
*/
-public class ByteChannelWrapper implements ByteChannel {
+public class ByteChannelWrapper implements ByteChannel
+{
private final ByteChannel socket;
- public ByteChannelWrapper(ByteChannel socket) {
+ public ByteChannelWrapper( ByteChannel socket )
+ {
this.socket = socket;
}
@Override
- public int read(ByteBuffer dst) throws IOException {
- return socket.read(dst);
+ public int read( ByteBuffer dst ) throws IOException
+ {
+ return socket.read( dst );
}
@Override
- public int write(ByteBuffer src) throws IOException {
- return socket.write(src);
+ public int write( ByteBuffer src ) throws IOException
+ {
+ return socket.write( src );
}
@Override
- public boolean isOpen() {
+ public boolean isOpen()
+ {
return socket.isOpen();
}
@Override
- public void close() throws IOException {
+ public void close() throws IOException
+ {
socket.close();
}
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonCompatibilitySpec.java b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonCompatibilitySpec.java
index eae53be..0701299 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonCompatibilitySpec.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonCompatibilitySpec.java
@@ -25,7 +25,8 @@ import java.util.function.Supplier;
* File origin:
* https://github.com/gradle/gradle/blob/v5.6.2/subprojects/launcher/src/main/java/org/gradle/launcher/daemon/context/DaemonCompatibilitySpec.java
*/
-public class DaemonCompatibilitySpec {
+public class DaemonCompatibilitySpec
+{
private final Path javaHome;
private final List<String> options;
@@ -34,73 +35,90 @@ public class DaemonCompatibilitySpec {
* @param javaHome make sure the Path is a result of {@link Path#toRealPath(java.nio.file.LinkOption...)}
* @param options the options
*/
- public DaemonCompatibilitySpec(Path javaHome, List<String> options) {
- this.javaHome = Objects.requireNonNull(javaHome, "javaHome");
- this.options = Objects.requireNonNull(options, "options");
+ public DaemonCompatibilitySpec( Path javaHome, List<String> options )
+ {
+ this.javaHome = Objects.requireNonNull( javaHome, "javaHome" );
+ this.options = Objects.requireNonNull( options, "options" );
}
- public Path getJavaHome() {
+ public Path getJavaHome()
+ {
return javaHome;
}
- public List<String> getOptions() {
+ public List<String> getOptions()
+ {
return options;
}
- public Result isSatisfiedBy(DaemonInfo daemon) {
- if (!javaHomeMatches(daemon)) {
- return new Result(false, () -> "Java home is different.\n" + diff(daemon));
+ public Result isSatisfiedBy( DaemonInfo daemon )
+ {
+ if ( !javaHomeMatches( daemon ) )
+ {
+ return new Result( false, () -> "Java home is different.\n" + diff( daemon ) );
}
- if (!daemonOptsMatch(daemon)) {
- return new Result(false, () -> "At least one daemon option is different.\n" + diff(daemon));
+ if ( !daemonOptsMatch( daemon ) )
+ {
+ return new Result( false, () -> "At least one daemon option is different.\n" + diff( daemon ) );
}
- return new Result(true, () -> {
- throw new RuntimeException("No reason if DaemonCompatibilityResult.compatible == true");
- });
+ return new Result( true, () ->
+ {
+ throw new RuntimeException( "No reason if DaemonCompatibilityResult.compatible == true" );
+ } );
}
- private String diff(DaemonInfo context) {
- final StringBuilder sb = new StringBuilder("Wanted: ");
- appendFields(sb);
- sb.append("\nActual: ");
- context.appendNonKeyFields(sb).append("id=").append(context.getId()).append('\n');
+ private String diff( DaemonInfo context )
+ {
+ final StringBuilder sb = new StringBuilder( "Wanted: " );
+ appendFields( sb );
+ sb.append( "\nActual: " );
+ context.appendNonKeyFields( sb ).append( "id=" ).append( context.getId() ).append( '\n' );
return sb.toString();
}
- private boolean daemonOptsMatch(DaemonInfo daemon) {
- return daemon.getOptions().containsAll(options)
+ private boolean daemonOptsMatch( DaemonInfo daemon )
+ {
+ return daemon.getOptions().containsAll( options )
&& daemon.getOptions().size() == options.size();
}
- private boolean javaHomeMatches(DaemonInfo daemon) {
- return javaHome.equals(Paths.get(daemon.getJavaHome()));
+ private boolean javaHomeMatches( DaemonInfo daemon )
+ {
+ return javaHome.equals( Paths.get( daemon.getJavaHome() ) );
}
- StringBuilder appendFields(StringBuilder sb) {
- return sb.append("javaHome=").append(javaHome)
- .append(", options=").append(options);
+ StringBuilder appendFields( StringBuilder sb )
+ {
+ return sb.append( "javaHome=" ).append( javaHome )
+ .append( ", options=" ).append( options );
}
@Override
- public String toString() {
- return appendFields(new StringBuilder("DaemonCompatibilitySpec{")).append('}').toString();
+ public String toString()
+ {
+ return appendFields( new StringBuilder( "DaemonCompatibilitySpec{" ) ).append( '}' ).toString();
}
- public static class Result {
+ public static class Result
+ {
+
private final boolean compatible;
private final Supplier<String> why;
- Result(boolean compatible, Supplier<String> why) {
+ Result( boolean compatible, Supplier<String> why )
+ {
super();
this.compatible = compatible;
this.why = why;
}
- public boolean isCompatible() {
+ public boolean isCompatible()
+ {
return compatible;
}
- public String getWhy() {
+ public String getWhy()
+ {
return why.get();
}
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonConnection.java b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonConnection.java
index 66f1d3b..513a83c 100755
--- a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonConnection.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonConnection.java
@@ -40,9 +40,10 @@ import org.slf4j.LoggerFactory;
* https://github.com/gradle/gradle/blob/v5.6.2/subprojects/messaging/src/main/java/org/gradle/internal/remote/internal/inet/SocketConnection.java
*
*/
-public class DaemonConnection implements AutoCloseable {
+public class DaemonConnection implements AutoCloseable
+{
- private static final Logger LOGGER = LoggerFactory.getLogger(DaemonConnection.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger( DaemonConnection.class );
private final SocketChannel socket;
private final DataInputStream input;
@@ -50,232 +51,309 @@ public class DaemonConnection implements AutoCloseable {
private final SocketAddress localAddress;
private final SocketAddress remoteAddress;
- public DaemonConnection(SocketChannel socket) throws IOException {
+ public DaemonConnection( SocketChannel socket ) throws IOException
+ {
this.socket = socket;
- try {
+ try
+ {
// NOTE: we use non-blocking IO as there is no reliable way when using blocking IO to shutdown reads while
// keeping writes active. For example, Socket.shutdownInput() does not work on Windows.
- socket.configureBlocking(false);
- this.output = new DataOutputStream(new SocketOutputStream(socket));
- this.input = new DataInputStream(new SocketInputStream(socket));
- } catch (IOException e) {
- throw new DaemonException.InterruptedException(e);
+ socket.configureBlocking( false );
+ this.output = new DataOutputStream( new SocketOutputStream( socket ) );
+ this.input = new DataInputStream( new SocketInputStream( socket ) );
+ }
+ catch ( IOException e )
+ {
+ throw new DaemonException.InterruptedException( e );
}
localAddress = socket.getLocalAddress();
remoteAddress = socket.getRemoteAddress();
}
@Override
- public String toString() {
+ public String toString()
+ {
return "socket connection from " + localAddress + " to " + remoteAddress;
}
- public Message receive() throws DaemonException.MessageIOException {
- try {
- return Message.read(input);
- } catch (EOFException e) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Discarding EOFException: {}", e.toString(), e);
+ public Message receive() throws DaemonException.MessageIOException
+ {
+ try
+ {
+ return Message.read( input );
+ }
+ catch ( EOFException e )
+ {
+ if ( LOGGER.isDebugEnabled() )
+ {
+ LOGGER.debug( "Discarding EOFException: {}", e.toString(), e );
}
return null;
- } catch (IOException e) {
+ }
+ catch ( IOException e )
+ {
throw new DaemonException.RecoverableMessageIOException(
- String.format("Could not read message from '%s'.", remoteAddress), e);
- } catch (Throwable e) {
- throw new DaemonException.MessageIOException(String.format("Could not read message from '%s'.", remoteAddress), e);
+ String.format( "Could not read message from '%s'.", remoteAddress ), e );
+ }
+ catch ( Throwable e )
+ {
+ throw new DaemonException.MessageIOException(
+ String.format( "Could not read message from '%s'.", remoteAddress ), e );
}
}
- private static boolean isEndOfStream(Exception e) {
- if (e instanceof EOFException) {
+ private static boolean isEndOfStream( Exception e )
+ {
+ if ( e instanceof EOFException )
+ {
return true;
}
- if (e instanceof IOException) {
- if (Objects.equals(e.getMessage(), "An existing connection was forcibly closed by the remote host")) {
+ if ( e instanceof IOException )
+ {
+ if ( Objects.equals( e.getMessage(), "An existing connection was forcibly closed by the remote host" ) )
+ {
return true;
}
- if (Objects.equals(e.getMessage(), "An established connection was aborted by the software in your host machine")) {
+ if ( Objects.equals( e.getMessage(),
+ "An established connection was aborted by the software in your host machine" ) )
+ {
return true;
}
- if (Objects.equals(e.getMessage(), "Connection reset by peer")) {
+ if ( Objects.equals( e.getMessage(), "Connection reset by peer" ) )
+ {
return true;
}
- if (Objects.equals(e.getMessage(), "Connection reset")) {
+ if ( Objects.equals( e.getMessage(), "Connection reset" ) )
+ {
return true;
}
}
return false;
}
- public void dispatch(Message message) throws DaemonException.MessageIOException {
- try {
- message.write(output);
+ public void dispatch( Message message ) throws DaemonException.MessageIOException
+ {
+ try
+ {
+ message.write( output );
output.flush();
- } catch (IOException e) {
+ }
+ catch ( IOException e )
+ {
throw new DaemonException.RecoverableMessageIOException(
- String.format("Could not write message %s to '%s'.", message, remoteAddress), e);
- } catch (Throwable e) {
+ String.format( "Could not write message %s to '%s'.", message, remoteAddress ), e );
+ }
+ catch ( Throwable e )
+ {
throw new DaemonException.MessageIOException(
- String.format("Could not write message %s to '%s'.", message, remoteAddress), e);
+ String.format( "Could not write message %s to '%s'.", message, remoteAddress ), e );
}
}
- public void flush() throws DaemonException.MessageIOException {
- try {
+ public void flush() throws DaemonException.MessageIOException
+ {
+ try
+ {
output.flush();
- } catch (Throwable e) {
- throw new DaemonException.MessageIOException(String.format("Could not write '%s'.", remoteAddress), e);
+ }
+ catch ( Throwable e )
+ {
+ throw new DaemonException.MessageIOException( String.format( "Could not write '%s'.", remoteAddress ), e );
}
}
- public void close() {
+ public void close()
+ {
Throwable failure = null;
- List<Closeable> elements = Arrays.asList(this::flush, input, output, socket);
- for (Closeable element : elements) {
- try {
+ List<Closeable> elements = Arrays.asList( this::flush, input, output, socket );
+ for ( Closeable element : elements )
+ {
+ try
+ {
element.close();
- } catch (Throwable throwable) {
- if (failure == null) {
+ }
+ catch ( Throwable throwable )
+ {
+ if ( failure == null )
+ {
failure = throwable;
- } else if (!Thread.currentThread().isInterrupted()) {
- LOGGER.error(String.format("Could not stop %s.", element), throwable);
+ }
+ else if ( !Thread.currentThread().isInterrupted() )
+ {
+ LOGGER.error( String.format( "Could not stop %s.", element ), throwable );
}
}
}
- if (failure != null) {
- throw new DaemonException(failure);
+ if ( failure != null )
+ {
+ throw new DaemonException( failure );
}
}
- private static class SocketInputStream extends InputStream {
+ private static class SocketInputStream extends InputStream
+ {
+
private final Selector selector;
private final ByteBuffer buffer;
private final SocketChannel socket;
private final byte[] readBuffer = new byte[1];
- public SocketInputStream(SocketChannel socket) throws IOException {
+ public SocketInputStream( SocketChannel socket ) throws IOException
+ {
this.socket = socket;
selector = Selector.open();
- socket.register(selector, SelectionKey.OP_READ);
- buffer = ByteBuffer.allocateDirect(4096);
- BufferCaster.cast(buffer).limit(0);
+ socket.register( selector, SelectionKey.OP_READ );
+ buffer = ByteBuffer.allocateDirect( 4096 );
+ BufferCaster.cast( buffer ).limit( 0 );
}
@Override
- public int read() throws IOException {
- int nread = read(readBuffer, 0, 1);
- if (nread <= 0) {
+ public int read() throws IOException
+ {
+ int nread = read( readBuffer, 0, 1 );
+ if ( nread <= 0 )
+ {
return nread;
}
return readBuffer[0] & 0xFF;
}
@Override
- public int read(byte[] dest, int offset, int max) throws IOException {
- if (max == 0) {
+ public int read( byte[] dest, int offset, int max ) throws IOException
+ {
+ if ( max == 0 )
+ {
return 0;
}
- if (buffer.remaining() == 0) {
- try {
+ if ( buffer.remaining() == 0 )
+ {
+ try
+ {
selector.select();
- } catch (ClosedSelectorException e) {
+ }
+ catch ( ClosedSelectorException e )
+ {
return -1;
}
- if (!selector.isOpen()) {
+ if ( !selector.isOpen() )
+ {
return -1;
}
- BufferCaster.cast(buffer).clear();
+ BufferCaster.cast( buffer ).clear();
int nread;
- try {
- nread = socket.read(buffer);
- } catch (IOException e) {
- if (isEndOfStream(e)) {
- BufferCaster.cast(buffer).position(0);
- BufferCaster.cast(buffer).limit(0);
+ try
+ {
+ nread = socket.read( buffer );
+ }
+ catch ( IOException e )
+ {
+ if ( isEndOfStream( e ) )
+ {
+ BufferCaster.cast( buffer ).position( 0 );
+ BufferCaster.cast( buffer ).limit( 0 );
return -1;
}
throw e;
}
- BufferCaster.cast(buffer).flip();
+ BufferCaster.cast( buffer ).flip();
- if (nread < 0) {
+ if ( nread < 0 )
+ {
return -1;
}
}
- int count = Math.min(buffer.remaining(), max);
- buffer.get(dest, offset, count);
+ int count = Math.min( buffer.remaining(), max );
+ buffer.get( dest, offset, count );
return count;
}
@Override
- public void close() throws IOException {
+ public void close() throws IOException
+ {
selector.close();
}
}
- private static class SocketOutputStream extends OutputStream {
+ private static class SocketOutputStream extends OutputStream
+ {
+
private static final int RETRIES_WHEN_BUFFER_FULL = 2;
private Selector selector;
private final SocketChannel socket;
private final ByteBuffer buffer;
private final byte[] writeBuffer = new byte[1];
- public SocketOutputStream(SocketChannel socket) throws IOException {
+ public SocketOutputStream( SocketChannel socket ) throws IOException
+ {
this.socket = socket;
- buffer = ByteBuffer.allocateDirect(32 * 1024);
+ buffer = ByteBuffer.allocateDirect( 32 * 1024 );
}
@Override
- public void write(int b) throws IOException {
- writeBuffer[0] = (byte) b;
- write(writeBuffer);
+ public void write( int b ) throws IOException
+ {
+ writeBuffer[0] = ( byte ) b;
+ write( writeBuffer );
}
@Override
- public void write(byte[] src, int offset, int max) throws IOException {
+ public void write( byte[] src, int offset, int max ) throws IOException
+ {
int remaining = max;
int currentPos = offset;
- while (remaining > 0) {
- int count = Math.min(remaining, buffer.remaining());
- if (count > 0) {
- buffer.put(src, currentPos, count);
+ while ( remaining > 0 )
+ {
+ int count = Math.min( remaining, buffer.remaining() );
+ if ( count > 0 )
+ {
+ buffer.put( src, currentPos, count );
remaining -= count;
currentPos += count;
}
- while (buffer.remaining() == 0) {
+ while ( buffer.remaining() == 0 )
+ {
writeBufferToChannel();
}
}
}
@Override
- public void flush() throws IOException {
- while (buffer.position() > 0) {
+ public void flush() throws IOException
+ {
+ while ( buffer.position() > 0 )
+ {
writeBufferToChannel();
}
}
- private void writeBufferToChannel() throws IOException {
- BufferCaster.cast(buffer).flip();
+ private void writeBufferToChannel() throws IOException
+ {
+ BufferCaster.cast( buffer ).flip();
int count = writeWithNonBlockingRetry();
- if (count == 0) {
+ if ( count == 0 )
+ {
// buffer was still full after non-blocking retries, now block
waitForWriteBufferToDrain();
}
buffer.compact();
}
- private int writeWithNonBlockingRetry() throws IOException {
+ private int writeWithNonBlockingRetry() throws IOException
+ {
int count = 0;
int retryCount = 0;
- while (count == 0 && retryCount++ < RETRIES_WHEN_BUFFER_FULL) {
- count = socket.write(buffer);
- if (count < 0) {
+ while ( count == 0 && retryCount++ < RETRIES_WHEN_BUFFER_FULL )
+ {
+ count = socket.write( buffer );
+ if ( count < 0 )
+ {
throw new EOFException();
- } else if (count == 0) {
+ }
+ else if ( count == 0 )
+ {
// buffer was full, just call Thread.yield
Thread.yield();
}
@@ -283,11 +361,13 @@ public class DaemonConnection implements AutoCloseable {
return count;
}
- private void waitForWriteBufferToDrain() throws IOException {
- if (selector == null) {
+ private void waitForWriteBufferToDrain() throws IOException
+ {
+ if ( selector == null )
+ {
selector = Selector.open();
}
- SelectionKey key = socket.register(selector, SelectionKey.OP_WRITE);
+ SelectionKey key = socket.register( selector, SelectionKey.OP_WRITE );
// block until ready for write operations
selector.select();
// cancel OP_WRITE selection
@@ -297,8 +377,10 @@ public class DaemonConnection implements AutoCloseable {
}
@Override
- public void close() throws IOException {
- if (selector != null) {
+ public void close() throws IOException
+ {
+ if ( selector != null )
+ {
selector.close();
selector = null;
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonException.java b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonException.java
index adf90e1..81f280f 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonException.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonException.java
@@ -15,73 +15,100 @@
*/
package org.mvndaemon.mvnd.common;
-public class DaemonException extends RuntimeException {
+public class DaemonException extends RuntimeException
+{
- public DaemonException(String message) {
- super(message);
+ public DaemonException( String message )
+ {
+ super( message );
}
- public DaemonException(String message, Throwable cause) {
- super(message, cause);
+ public DaemonException( String message, Throwable cause )
+ {
+ super( message, cause );
}
- public DaemonException(Throwable cause) {
- super(cause);
+ public DaemonException( Throwable cause )
+ {
+ super( cause );
}
- public static class InterruptedException extends DaemonException {
- public InterruptedException(Throwable cause) {
- super(cause);
+ public static class InterruptedException extends DaemonException
+ {
+
+ public InterruptedException( Throwable cause )
+ {
+ super( cause );
}
}
- public static class ConnectException extends DaemonException {
- public ConnectException(String message) {
- super(message);
+ public static class ConnectException extends DaemonException
+ {
+
+ public ConnectException( String message )
+ {
+ super( message );
}
- public ConnectException(String message, Throwable cause) {
- super(message, cause);
+ public ConnectException( String message, Throwable cause )
+ {
+ super( message, cause );
}
}
- public static class StartException extends DaemonException {
- public StartException(String message) {
- super(message);
+ public static class StartException extends DaemonException
+ {
+
+ public StartException( String message )
+ {
+ super( message );
}
- public StartException(String message, Throwable cause) {
- super(message, cause);
+ public StartException( String message, Throwable cause )
+ {
+ super( message, cause );
}
}
- public static class MessageIOException extends DaemonException {
- public MessageIOException(String message) {
- super(message);
+ public static class MessageIOException extends DaemonException
+ {
+
+ public MessageIOException( String message )
+ {
+ super( message );
}
- public MessageIOException(String message, Throwable cause) {
- super(message, cause);
+ public MessageIOException( String message, Throwable cause )
+ {
+ super( message, cause );
}
}
- public static class RecoverableMessageIOException extends MessageIOException {
- public RecoverableMessageIOException(String message) {
- super(message);
+ public static class RecoverableMessageIOException extends MessageIOException
+ {
+
+ public RecoverableMessageIOException( String message )
+ {
+ super( message );
}
- public RecoverableMessageIOException(String message, Throwable cause) {
- super(message, cause);
+ public RecoverableMessageIOException( String message, Throwable cause )
+ {
+ super( message, cause );
}
}
- public static class StaleAddressException extends DaemonException {
- public StaleAddressException(String message) {
- super(message);
+ public static class StaleAddressException extends DaemonException
+ {
+
+ public StaleAddressException( String message )
+ {
+ super( message );
}
- public StaleAddressException(String message, Throwable cause) {
- super(message, cause);
+ public StaleAddressException( String message, Throwable cause )
+ {
+ super( message, cause );
}
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonExpirationStatus.java b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonExpirationStatus.java
index e844074..bc5feb3 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonExpirationStatus.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonExpirationStatus.java
@@ -24,7 +24,8 @@ package org.mvndaemon.mvnd.common;
* File origin:
* https://github.com/gradle/gradle/blob/v6.5.1/subprojects/launcher/src/main/java/org/gradle/launcher/daemon/server/expiry/DaemonExpirationStatus.java
*/
-public enum DaemonExpirationStatus {
+public enum DaemonExpirationStatus
+{
DO_NOT_EXPIRE,
QUIET_EXPIRE,
GRACEFUL_EXPIRE,
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonInfo.java b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonInfo.java
index c0f6907..42d509d 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonInfo.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonInfo.java
@@ -24,7 +24,8 @@ import static org.mvndaemon.mvnd.common.DaemonState.Idle;
* File origin:
* https://github.com/gradle/gradle/blob/v5.6.2/subprojects/launcher/src/main/java/org/gradle/launcher/daemon/registry/DaemonInfo.java
*/
-public class DaemonInfo {
+public class DaemonInfo
+{
public static final int TOKEN_SIZE = 16;
@@ -40,10 +41,11 @@ public class DaemonInfo {
private final long lastIdle;
private final long lastBusy;
- public DaemonInfo(String id, String javaHome, String mavenHome,
+ public DaemonInfo( String id, String javaHome, String mavenHome,
int pid, String address, byte[] token,
String locale, List<String> options,
- DaemonState state, long lastIdle, long lastBusy) {
+ DaemonState state, long lastIdle, long lastBusy )
+ {
this.id = id;
this.javaHome = javaHome;
this.mvndHome = mavenHome;
@@ -57,82 +59,101 @@ public class DaemonInfo {
this.lastBusy = lastBusy;
}
- public String getId() {
+ public String getId()
+ {
return id;
}
- public String getJavaHome() {
+ public String getJavaHome()
+ {
return javaHome;
}
- public String getMvndHome() {
+ public String getMvndHome()
+ {
return mvndHome;
}
- public int getPid() {
+ public int getPid()
+ {
return pid;
}
- public String getAddress() {
+ public String getAddress()
+ {
return address;
}
- public byte[] getToken() {
+ public byte[] getToken()
+ {
return token;
}
- public String getLocale() {
+ public String getLocale()
+ {
return locale;
}
- public List<String> getOptions() {
+ public List<String> getOptions()
+ {
return options;
}
- public DaemonState getState() {
+ public DaemonState getState()
+ {
return state;
}
- public long getLastIdle() {
+ public long getLastIdle()
+ {
return lastIdle;
}
- public long getLastBusy() {
+ public long getLastBusy()
+ {
return lastBusy;
}
- public DaemonInfo withState(DaemonState state) {
+ public DaemonInfo withState( DaemonState state )
+ {
long lb, li;
- if (this.state == Idle && state == Busy) {
+ if ( this.state == Idle && state == Busy )
+ {
li = lastIdle;
lb = System.currentTimeMillis();
- } else if (this.state == Busy && state == Idle) {
+ }
+ else if ( this.state == Busy && state == Idle )
+ {
li = System.currentTimeMillis();
lb = lastBusy;
- } else {
+ }
+ else
+ {
li = lastIdle;
lb = lastBusy;
}
- return new DaemonInfo(id, javaHome, mvndHome, pid, address,
- token, locale, options, state, li, lb);
+ return new DaemonInfo( id, javaHome, mvndHome, pid, address,
+ token, locale, options, state, li, lb );
}
@Override
- public String toString() {
- final StringBuilder sb = new StringBuilder("DaemonInfo{id=").append(id);
- appendNonKeyFields(sb);
- return sb.append('}').toString();
+ public String toString()
+ {
+ final StringBuilder sb = new StringBuilder( "DaemonInfo{id=" ).append( id );
+ appendNonKeyFields( sb );
+ return sb.append( '}' ).toString();
}
- public StringBuilder appendNonKeyFields(StringBuilder sb) {
- return sb.append("javaHome=").append(javaHome)
- .append(", options=").append(options)
- .append(", mavenHome=").append(mvndHome)
- .append(", pid=").append(pid)
- .append(", address=").append(address)
- .append(", locale=").append(locale)
- .append(", state=").append(state)
- .append(", lastIdle=").append(lastIdle)
- .append(", lastBusy=").append(lastBusy);
+ public StringBuilder appendNonKeyFields( StringBuilder sb )
+ {
+ return sb.append( "javaHome=" ).append( javaHome )
+ .append( ", options=" ).append( options )
+ .append( ", mavenHome=" ).append( mvndHome )
+ .append( ", pid=" ).append( pid )
+ .append( ", address=" ).append( address )
+ .append( ", locale=" ).append( locale )
+ .append( ", state=" ).append( state )
+ .append( ", lastIdle=" ).append( lastIdle )
+ .append( ", lastBusy=" ).append( lastBusy );
}
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonRegistry.java b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonRegistry.java
index ab414dc..4a25d32 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonRegistry.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonRegistry.java
@@ -48,9 +48,10 @@ import static org.mvndaemon.mvnd.common.DaemonState.Idle;
* https://github.com/gradle/gradle/blob/v5.6.2/subprojects/launcher/src/main/java/org/gradle/launcher/daemon/registry/DaemonRegistry.java
* https://github.com/OpenHFT/Java-Lang/blob/master/lang/src/main/java/net/openhft/lang/io/AbstractBytes.java
*/
-public class DaemonRegistry implements AutoCloseable {
+public class DaemonRegistry implements AutoCloseable
+{
- private static final Logger LOGGER = LoggerFactory.getLogger(DaemonRegistry.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger( DaemonRegistry.class );
private static final int MAX_LENGTH = 32768;
private static final long LOCK_TIMEOUT_MS = 1000 * 20;
@@ -63,124 +64,156 @@ public class DaemonRegistry implements AutoCloseable {
private final Map<String, DaemonInfo> infosMap = new HashMap<>();
private final List<DaemonStopEvent> stopEvents = new ArrayList<>();
- public DaemonRegistry(Path registryFile) {
+ public DaemonRegistry( Path registryFile )
+ {
final Path absPath = registryFile.toAbsolutePath().normalize();
- this.lck = locks.computeIfAbsent(absPath, p -> new Object());
+ this.lck = locks.computeIfAbsent( absPath, p -> new Object() );
this.registryFile = absPath;
- try {
- if (!Files.isRegularFile(absPath)) {
- if (!Files.isDirectory(absPath.getParent())) {
- Files.createDirectories(absPath.getParent());
+ try
+ {
+ if ( !Files.isRegularFile( absPath ) )
+ {
+ if ( !Files.isDirectory( absPath.getParent() ) )
+ {
+ Files.createDirectories( absPath.getParent() );
}
}
- channel = FileChannel.open(absPath,
- StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
- buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, MAX_LENGTH);
- } catch (IOException e) {
- throw new DaemonException(e);
+ channel = FileChannel.open( absPath,
+ StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE );
+ buffer = channel.map( FileChannel.MapMode.READ_WRITE, 0, MAX_LENGTH );
+ }
+ catch ( IOException e )
+ {
+ throw new DaemonException( e );
}
}
- public void close() {
- try {
+ public void close()
+ {
+ try
+ {
channel.close();
- } catch (IOException e) {
- throw new DaemonException("Error closing registry", e);
+ }
+ catch ( IOException e )
+ {
+ throw new DaemonException( "Error closing registry", e );
}
}
- public Path getRegistryFile() {
+ public Path getRegistryFile()
+ {
return registryFile;
}
- public DaemonInfo get(String daemonId) {
+ public DaemonInfo get( String daemonId )
+ {
read();
- return infosMap.get(daemonId);
+ return infosMap.get( daemonId );
}
- public List<DaemonInfo> getAll() {
+ public List<DaemonInfo> getAll()
+ {
read();
- return new ArrayList<>(infosMap.values());
+ return new ArrayList<>( infosMap.values() );
}
- public List<DaemonInfo> getIdle() {
+ public List<DaemonInfo> getIdle()
+ {
read();
return infosMap.values().stream()
- .filter(di -> di.getState() == Idle)
- .collect(Collectors.toList());
+ .filter( di -> di.getState() == Idle )
+ .collect( Collectors.toList() );
}
- public List<DaemonInfo> getNotIdle() {
+ public List<DaemonInfo> getNotIdle()
+ {
return infosMap.values().stream()
- .filter(di -> di.getState() != Idle)
- .collect(Collectors.toList());
+ .filter( di -> di.getState() != Idle )
+ .collect( Collectors.toList() );
}
- public List<DaemonInfo> getCanceled() {
+ public List<DaemonInfo> getCanceled()
+ {
read();
return infosMap.values().stream()
- .filter(di -> di.getState() == Canceled)
- .collect(Collectors.toList());
+ .filter( di -> di.getState() == Canceled )
+ .collect( Collectors.toList() );
}
- public void remove(final String daemonId) {
- update(() -> infosMap.remove(daemonId));
+ public void remove( final String daemonId )
+ {
+ update( () -> infosMap.remove( daemonId ) );
}
- public void markState(final String daemonId, final DaemonState state) {
- LOGGER.debug("Marking busy by id: {}", daemonId);
- update(() -> infosMap.computeIfPresent(daemonId, (id, di) -> di.withState(state)));
+ public void markState( final String daemonId, final DaemonState state )
+ {
+ LOGGER.debug( "Marking busy by id: {}", daemonId );
+ update( () -> infosMap.computeIfPresent( daemonId, ( id, di ) -> di.withState( state ) ) );
}
- public void storeStopEvent(final DaemonStopEvent stopEvent) {
- LOGGER.debug("Storing daemon stop event with timestamp {}", stopEvent.getTimestamp());
- update(() -> stopEvents.add(stopEvent));
+ public void storeStopEvent( final DaemonStopEvent stopEvent )
+ {
+ LOGGER.debug( "Storing daemon stop event with timestamp {}", stopEvent.getTimestamp() );
+ update( () -> stopEvents.add( stopEvent ) );
}
- public List<DaemonStopEvent> getStopEvents() {
+ public List<DaemonStopEvent> getStopEvents()
+ {
read();
return doGetDaemonStopEvents();
}
- protected List<DaemonStopEvent> doGetDaemonStopEvents() {
- return new ArrayList<>(stopEvents);
+ protected List<DaemonStopEvent> doGetDaemonStopEvents()
+ {
+ return new ArrayList<>( stopEvents );
}
- public void removeStopEvents(final Collection<DaemonStopEvent> events) {
- LOGGER.debug("Removing {} daemon stop events from registry", events.size());
- update(() -> stopEvents.removeAll(events));
+ public void removeStopEvents( final Collection<DaemonStopEvent> events )
+ {
+ LOGGER.debug( "Removing {} daemon stop events from registry", events.size() );
+ update( () -> stopEvents.removeAll( events ) );
}
- public void store(final DaemonInfo info) {
- LOGGER.debug("Storing daemon {}", info);
- update(() -> infosMap.put(info.getId(), info));
+ public void store( final DaemonInfo info )
+ {
+ LOGGER.debug( "Storing daemon {}", info );
+ update( () -> infosMap.put( info.getId(), info ) );
}
- public static int getProcessId() {
+ public static int getProcessId()
+ {
return PROCESS_ID;
}
- private void read() {
- doUpdate(null);
+ private void read()
+ {
+ doUpdate( null );
}
- private void update(Runnable updater) {
- doUpdate(updater);
+ private void update( Runnable updater )
+ {
+ doUpdate( updater );
}
- private void doUpdate(Runnable updater) {
- if (!Files.isReadable(registryFile)) {
- throw new DaemonException("Registry became unaccessible");
+ private void doUpdate( Runnable updater )
+ {
+ if ( !Files.isReadable( registryFile ) )
+ {
+ throw new DaemonException( "Registry became unaccessible" );
}
- synchronized (lck) {
+ synchronized ( lck )
+ {
final long deadline = System.currentTimeMillis() + LOCK_TIMEOUT_MS;
- while (System.currentTimeMillis() < deadline) {
- try (FileLock l = channel.tryLock(0, MAX_LENGTH, false)) {
- BufferCaster.cast(buffer).position(0);
+ while ( System.currentTimeMillis() < deadline )
+ {
+ try ( FileLock l = channel.tryLock( 0, MAX_LENGTH, false ) )
+ {
+ BufferCaster.cast( buffer ).position( 0 );
infosMap.clear();
int nb = buffer.getInt();
- for (int i = 0; i < nb; i++) {
+ for ( int i = 0; i < nb; i++ )
+ {
String daemonId = readString();
String javaHome = readString();
String mavenHome = readString();
@@ -188,145 +221,174 @@ public class DaemonRegistry implements AutoCloseable {
String address = readString();
byte[] token = new byte[DaemonInfo.TOKEN_SIZE];
- buffer.get(token);
+ buffer.get( token );
String locale = readString();
List<String> opts = new ArrayList<>();
int nbOpts = buffer.getInt();
- for (int j = 0; j < nbOpts; j++) {
- opts.add(readString());
+ for ( int j = 0; j < nbOpts; j++ )
+ {
+ opts.add( readString() );
}
DaemonState state = DaemonState.values()[buffer.get()];
long lastIdle = buffer.getLong();
long lastBusy = buffer.getLong();
- DaemonInfo di = new DaemonInfo(daemonId, javaHome, mavenHome, pid, address, token, locale,
- opts, state, lastIdle, lastBusy);
- infosMap.putIfAbsent(di.getId(), di);
+ DaemonInfo di = new DaemonInfo( daemonId, javaHome, mavenHome, pid, address, token, locale,
+ opts, state, lastIdle, lastBusy );
+ infosMap.putIfAbsent( di.getId(), di );
}
stopEvents.clear();
nb = buffer.getInt();
- for (int i = 0; i < nb; i++) {
+ for ( int i = 0; i < nb; i++ )
+ {
String daemonId = readString();
long date = buffer.getLong();
int ord = buffer.get();
DaemonExpirationStatus des = ord >= 0 ? DaemonExpirationStatus.values()[ord] : null;
String reason = readString();
- DaemonStopEvent se = new DaemonStopEvent(daemonId, date, des, reason);
- stopEvents.add(se);
+ DaemonStopEvent se = new DaemonStopEvent( daemonId, date, des, reason );
+ stopEvents.add( se );
}
- if (updater != null) {
+ if ( updater != null )
+ {
updater.run();
- BufferCaster.cast(buffer).position((int) 0);
- buffer.putInt(infosMap.size());
- for (DaemonInfo di : infosMap.values()) {
- writeString(di.getId());
- writeString(di.getJavaHome());
- writeString(di.getMvndHome());
- buffer.putInt(di.getPid());
- writeString(di.getAddress());
- buffer.put(di.getToken());
- writeString(di.getLocale());
- buffer.putInt(di.getOptions().size());
- for (String opt : di.getOptions()) {
- writeString(opt);
+ BufferCaster.cast( buffer ).position( ( int ) 0 );
+ buffer.putInt( infosMap.size() );
+ for ( DaemonInfo di : infosMap.values() )
+ {
+ writeString( di.getId() );
+ writeString( di.getJavaHome() );
+ writeString( di.getMvndHome() );
+ buffer.putInt( di.getPid() );
+ writeString( di.getAddress() );
+ buffer.put( di.getToken() );
+ writeString( di.getLocale() );
+ buffer.putInt( di.getOptions().size() );
+ for ( String opt : di.getOptions() )
+ {
+ writeString( opt );
}
- buffer.put((byte) di.getState().ordinal());
- buffer.putLong(di.getLastIdle());
- buffer.putLong(di.getLastBusy());
+ buffer.put( ( byte ) di.getState().ordinal() );
+ buffer.putLong( di.getLastIdle() );
+ buffer.putLong( di.getLastBusy() );
}
- buffer.putInt(stopEvents.size());
- for (DaemonStopEvent dse : stopEvents) {
- writeString(dse.getDaemonId());
- buffer.putLong(dse.getTimestamp());
- buffer.put((byte) (dse.getStatus() == null ? -1 : dse.getStatus().ordinal()));
- writeString(dse.getReason());
+ buffer.putInt( stopEvents.size() );
+ for ( DaemonStopEvent dse : stopEvents )
+ {
+ writeString( dse.getDaemonId() );
+ buffer.putLong( dse.getTimestamp() );
+ buffer.put( ( byte ) ( dse.getStatus() == null ? -1 : dse.getStatus().ordinal() ) );
+ writeString( dse.getReason() );
}
}
return;
- } catch (IOException e) {
- throw new RuntimeException("Could not lock offset 0 of " + registryFile);
- } catch (IllegalStateException | ArrayIndexOutOfBoundsException e) {
+ }
+ catch ( IOException e )
+ {
+ throw new RuntimeException( "Could not lock offset 0 of " + registryFile );
+ }
+ catch ( IllegalStateException | ArrayIndexOutOfBoundsException e )
+ {
String absPath = registryFile.toAbsolutePath().normalize().toString();
- LOGGER.warn("Invalid daemon registry info, " +
+ LOGGER.warn( "Invalid daemon registry info, " +
"trying to recover from this issue. " +
"If you keep getting this warning, " +
- "try deleting the `registry.bin` file at [" + absPath + "]", e);
+ "try deleting the `registry.bin` file at [" + absPath + "]", e );
this.reset();
return;
}
}
- throw new RuntimeException("Could not lock " + registryFile + " within " + LOCK_TIMEOUT_MS + " ms");
+ throw new RuntimeException( "Could not lock " + registryFile + " within " + LOCK_TIMEOUT_MS + " ms" );
}
}
- private void reset() {
+ private void reset()
+ {
infosMap.clear();
stopEvents.clear();
- BufferCaster.cast(buffer).clear();
- buffer.putInt(0); // reset daemon count
- buffer.putInt(0); // reset stop event count
+ BufferCaster.cast( buffer ).clear();
+ buffer.putInt( 0 ); // reset daemon count
+ buffer.putInt( 0 ); // reset stop event count
}
private static final int PROCESS_ID = getProcessId0();
- private static int getProcessId0() {
+ private static int getProcessId0()
+ {
String pid = null;
- try {
- final Path self = Paths.get("/proc/self");
- if (Files.exists(self)) {
+ try
+ {
+ final Path self = Paths.get( "/proc/self" );
+ if ( Files.exists( self ) )
+ {
pid = self.toRealPath().getFileName().toString();
}
- } catch (IOException ignored) {
}
- if (pid == null) {
- pid = ManagementFactory.getRuntimeMXBean().getName().split("@", 0)[0];
+ catch ( IOException ignored )
+ {
+ }
+ if ( pid == null )
+ {
+ pid = ManagementFactory.getRuntimeMXBean().getName().split( "@", 0 )[0];
}
- if (pid == null) {
- int rpid = new Random().nextInt(1 << 16);
- LOGGER.warn("Unable to determine PID, picked a random number=" + rpid);
+ if ( pid == null )
+ {
+ int rpid = new Random().nextInt( 1 << 16 );
+ LOGGER.warn( "Unable to determine PID, picked a random number=" + rpid );
return rpid;
- } else {
- return Integer.parseInt(pid);
+ }
+ else
+ {
+ return Integer.parseInt( pid );
}
}
- protected String readString() {
+ protected String readString()
+ {
int sz = buffer.getShort();
- if (sz == -1) {
+ if ( sz == -1 )
+ {
return null;
}
- if (sz < -1 || sz > 1024) {
- throw new IllegalStateException("Bad string size: " + sz);
+ if ( sz < -1 || sz > 1024 )
+ {
+ throw new IllegalStateException( "Bad string size: " + sz );
}
byte[] buf = new byte[sz];
- buffer.get(buf);
- return new String(buf, StandardCharsets.UTF_8);
+ buffer.get( buf );
+ return new String( buf, StandardCharsets.UTF_8 );
}
- protected void writeString(String str) {
- if (str == null) {
- buffer.putShort((short) -1);
+ protected void writeString( String str )
+ {
+ if ( str == null )
+ {
+ buffer.putShort( ( short ) -1 );
return;
}
- byte[] buf = str.getBytes(StandardCharsets.UTF_8);
- if (buf.length > 1024) {
- LOGGER.warn("Attempting to write string longer than 1024 bytes: '{}'. Please raise an issue.", str);
- str = str.substring(0, 1033);
- while (buf.length > 1024) {
- str = str.substring(0, str.length() - 12) + "…";
- buf = str.getBytes(StandardCharsets.UTF_8);
+ byte[] buf = str.getBytes( StandardCharsets.UTF_8 );
+ if ( buf.length > 1024 )
+ {
+ LOGGER.warn( "Attempting to write string longer than 1024 bytes: '{}'. Please raise an issue.", str );
+ str = str.substring( 0, 1033 );
+ while ( buf.length > 1024 )
+ {
+ str = str.substring( 0, str.length() - 12 ) + "…";
+ buf = str.getBytes( StandardCharsets.UTF_8 );
}
}
- buffer.putShort((short) buf.length);
- buffer.put(buf);
+ buffer.putShort( ( short ) buf.length );
+ buffer.put( buf );
}
- protected ByteBuffer buffer() {
+ protected ByteBuffer buffer()
+ {
return buffer;
}
- public String toString() {
- return String.format("DaemonRegistry[file=%s]", registryFile);
+ public String toString()
+ {
+ return String.format( "DaemonRegistry[file=%s]", registryFile );
}
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonState.java b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonState.java
index 808b498..d469844 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonState.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonState.java
@@ -19,7 +19,8 @@ package org.mvndaemon.mvnd.common;
* File origin
* https://github.com/gradle/gradle/blob/v5.6.2/subprojects/launcher/src/main/java/org/gradle/launcher/daemon/server/api/DaemonStateControl.java
*/
-public enum DaemonState {
+public enum DaemonState
+{
Idle,
Busy,
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonStopEvent.java b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonStopEvent.java
index 4520130..38621b3 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonStopEvent.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonStopEvent.java
@@ -27,59 +27,68 @@ import java.util.Objects;
* File origin:
* https://github.com/gradle/gradle/blob/v5.6.2/subprojects/launcher/src/main/java/org/gradle/launcher/daemon/registry/DaemonStopEvent.java
*/
-public class DaemonStopEvent implements Serializable {
+public class DaemonStopEvent implements Serializable
+{
private final String daemonId;
private final long timestamp;
private final DaemonExpirationStatus status;
private final String reason;
- public DaemonStopEvent(String daemonId, long timestamp, DaemonExpirationStatus status, String reason) {
+ public DaemonStopEvent( String daemonId, long timestamp, DaemonExpirationStatus status, String reason )
+ {
this.daemonId = daemonId;
this.timestamp = timestamp;
this.status = status;
this.reason = reason != null ? reason : "";
}
- public String getDaemonId() {
+ public String getDaemonId()
+ {
return daemonId;
}
- public long getTimestamp() {
+ public long getTimestamp()
+ {
return timestamp;
}
- public DaemonExpirationStatus getStatus() {
+ public DaemonExpirationStatus getStatus()
+ {
return status;
}
- public String getReason() {
+ public String getReason()
+ {
return reason;
}
@Override
- public boolean equals(Object o) {
- if (this == o)
+ public boolean equals( Object o )
+ {
+ if ( this == o )
return true;
- if (o == null || getClass() != o.getClass())
+ if ( o == null || getClass() != o.getClass() )
return false;
- DaemonStopEvent that = (DaemonStopEvent) o;
- return Objects.equals(daemonId, that.daemonId)
+ DaemonStopEvent that = ( DaemonStopEvent ) o;
+ return Objects.equals( daemonId, that.daemonId )
&& timestamp == that.timestamp
&& status == that.status
- && Objects.equals(reason, that.reason);
+ && Objects.equals( reason, that.reason );
}
@Override
- public int hashCode() {
- return Objects.hash(timestamp, daemonId, status, reason);
+ public int hashCode()
+ {
+ return Objects.hash( timestamp, daemonId, status, reason );
}
@Override
- public String toString() {
+ public String toString()
+ {
return "DaemonStopEvent{"
+ "daemonId=" + daemonId
- + ", timestamp=" + DateFormat.getDateTimeInstance().format(new Date(timestamp))
+ + ", timestamp=" + DateFormat.getDateTimeInstance().format( new Date( timestamp ) )
+ ", status=" + status
+ ", reason=" + reason
+ "}";
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/Environment.java b/common/src/main/java/org/mvndaemon/mvnd/common/Environment.java
index f7119c0..23402e1 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/Environment.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/Environment.java
@@ -42,22 +42,25 @@ import java.util.stream.Stream;
* The available units are <i>d/day/days</i>, <i>h/hour/hours</i>, <i>m/min/minute/minutes</i>,
* <i>s/sec/second/seconds</i> and <i>ms/millis/msec/milliseconds</i>.
*/
-public enum Environment {
+public enum Environment
+{
/**
- * Print the completion for the given shell to stdout. Only <code>--completion bash</code> is supported at this time.
+ * Print the completion for the given shell to stdout. Only <code>--completion bash</code> is supported at this
+ * time.
*/
- COMPLETION(null, null, null, OptionType.STRING, Flags.OPTIONAL, "mvnd:--completion"),
+ COMPLETION( null, null, null, OptionType.STRING, Flags.OPTIONAL, "mvnd:--completion" ),
/**
- * Delete log files under the <code>mvnd.registry</code> directory that are older than <code>mvnd.logPurgePeriod</code>
+ * Delete log files under the <code>mvnd.registry</code> directory that are older than
+ * <code>mvnd.logPurgePeriod</code>
*/
- PURGE(null, null, null, OptionType.VOID, Flags.OPTIONAL, "mvnd:--purge"),
+ PURGE( null, null, null, OptionType.VOID, Flags.OPTIONAL, "mvnd:--purge" ),
/** Prints the status of daemon instances registered in the registry specified by <code>mvnd.registry</code> */
- STATUS(null, null, null, OptionType.VOID, Flags.OPTIONAL, "mvnd:--status"),
+ STATUS( null, null, null, OptionType.VOID, Flags.OPTIONAL, "mvnd:--status" ),
/** Stop all daemon instances registered in the registry specified by <code>mvnd.registry</code> */
- STOP(null, null, null, OptionType.VOID, Flags.OPTIONAL, "mvnd:--stop"),
+ STOP( null, null, null, OptionType.VOID, Flags.OPTIONAL, "mvnd:--stop" ),
/** Use one thread, no log buffering and the default project builder to behave like a standard maven */
- SERIAL("mvnd.serial", null, Boolean.FALSE, OptionType.VOID, Flags.OPTIONAL, "mvnd:-1", "mvnd:--serial"),
+ SERIAL( "mvnd.serial", null, Boolean.FALSE, OptionType.VOID, Flags.OPTIONAL, "mvnd:-1", "mvnd:--serial" ),
//
// Log properties
@@ -66,52 +69,52 @@ public enum Environment {
/**
* The location of the Logback configuration file the daemon should use to configure its logging.
*/
- MVND_LOGBACK("mvnd.logback", null, null, OptionType.PATH, Flags.NONE),
+ MVND_LOGBACK( "mvnd.logback", null, null, OptionType.PATH, Flags.NONE ),
/** The system property expected by logback to set the configuration file */
- LOGBACK_CONFIGURATION_FILE("logback.configurationFile", null, null, OptionType.PATH, Flags.INTERNAL),
+ LOGBACK_CONFIGURATION_FILE( "logback.configurationFile", null, null, OptionType.PATH, Flags.INTERNAL ),
//
// System properties
//
/** Java home for starting the daemon */
- JAVA_HOME("java.home", "JAVA_HOME", null, OptionType.PATH, Flags.NONE),
+ JAVA_HOME( "java.home", "JAVA_HOME", null, OptionType.PATH, Flags.NONE ),
/**
* The daemon installation directory. The client normally sets this according to where its <code>mvnd</code>
* executable is located
*/
- MVND_HOME("mvnd.home", "MVND_HOME", null, OptionType.PATH, Flags.DISCRIMINATING),
+ MVND_HOME( "mvnd.home", "MVND_HOME", null, OptionType.PATH, Flags.DISCRIMINATING ),
/** The user home directory */
- USER_HOME("user.home", null, null, OptionType.PATH, Flags.NONE),
+ USER_HOME( "user.home", null, null, OptionType.PATH, Flags.NONE ),
/** The current working directory */
- USER_DIR("user.dir", null, null, OptionType.PATH, Flags.NONE),
+ USER_DIR( "user.dir", null, null, OptionType.PATH, Flags.NONE ),
/** The JDK_JAVA_OPTIONS option */
- JDK_JAVA_OPTIONS("jdk.java.options", "JDK_JAVA_OPTIONS", "", OptionType.STRING, Flags.DISCRIMINATING),
+ JDK_JAVA_OPTIONS( "jdk.java.options", "JDK_JAVA_OPTIONS", "", OptionType.STRING, Flags.DISCRIMINATING ),
//
// Maven properties
//
/** The path to the Maven local repository */
- MAVEN_REPO_LOCAL("maven.repo.local", null, null, OptionType.PATH, Flags.NONE),
+ MAVEN_REPO_LOCAL( "maven.repo.local", null, null, OptionType.PATH, Flags.NONE ),
/** The location of the maven settings file */
- MAVEN_SETTINGS("maven.settings", null, null, OptionType.PATH, Flags.NONE, "mvn:-s", "mvn:--settings"),
+ MAVEN_SETTINGS( "maven.settings", null, null, OptionType.PATH, Flags.NONE, "mvn:-s", "mvn:--settings" ),
/** The pom or directory to build */
- MAVEN_FILE(null, null, null, OptionType.PATH, Flags.NONE, "mvn:-f", "mvn:--file"),
+ MAVEN_FILE( null, null, null, OptionType.PATH, Flags.NONE, "mvn:-f", "mvn:--file" ),
/** The root directory of the current multi module Maven project */
- MAVEN_MULTIMODULE_PROJECT_DIRECTORY("maven.multiModuleProjectDirectory", null, null, OptionType.PATH, Flags.NONE),
+ MAVEN_MULTIMODULE_PROJECT_DIRECTORY( "maven.multiModuleProjectDirectory", null, null, OptionType.PATH, Flags.NONE ),
/** Log file */
- MAVEN_LOG_FILE(null, null, null, OptionType.PATH, Flags.INTERNAL, "mvn:-l", "mvn:--log-file"),
+ MAVEN_LOG_FILE( null, null, null, OptionType.PATH, Flags.INTERNAL, "mvn:-l", "mvn:--log-file" ),
/** Batch mode */
- MAVEN_BATCH_MODE(null, null, null, OptionType.BOOLEAN, Flags.INTERNAL, "mvn:-B", "mvn:--batch-mode"),
+ MAVEN_BATCH_MODE( null, null, null, OptionType.BOOLEAN, Flags.INTERNAL, "mvn:-B", "mvn:--batch-mode" ),
/** Debug */
- MAVEN_DEBUG(null, null, null, OptionType.BOOLEAN, Flags.INTERNAL, "mvn:-X", "mvn:--debug"),
+ MAVEN_DEBUG( null, null, null, OptionType.BOOLEAN, Flags.INTERNAL, "mvn:-X", "mvn:--debug" ),
/** Version */
- MAVEN_VERSION(null, null, null, OptionType.BOOLEAN, Flags.INTERNAL, "mvn:-v", "mvn:-version", "mvn:--version"),
+ MAVEN_VERSION( null, null, null, OptionType.BOOLEAN, Flags.INTERNAL, "mvn:-v", "mvn:-version", "mvn:--version" ),
/** Show version */
- MAVEN_SHOW_VERSION(null, null, null, OptionType.BOOLEAN, Flags.INTERNAL, "mvn:-V", "mvn:--show-version"),
+ MAVEN_SHOW_VERSION( null, null, null, OptionType.BOOLEAN, Flags.INTERNAL, "mvn:-V", "mvn:--show-version" ),
/** Define */
- MAVEN_DEFINE(null, null, null, OptionType.STRING, Flags.INTERNAL, "mvn:-D", "mvn:--define"),
+ MAVEN_DEFINE( null, null, null, OptionType.STRING, Flags.INTERNAL, "mvn:-D", "mvn:--define" ),
/** Whether the output should be styled using ANSI color codes; possible values: auto, always, never */
- MAVEN_COLOR("style.color", null, "auto", OptionType.STRING, Flags.OPTIONAL, "mvnd:--color"),
+ MAVEN_COLOR( "style.color", null, "auto", OptionType.STRING, Flags.OPTIONAL, "mvnd:--color" ),
//
// mvnd properties
@@ -120,140 +123,141 @@ public enum Environment {
/**
* The location of the user supplied <code>mvnd.properties</code> file.
*/
- MVND_PROPERTIES_PATH("mvnd.propertiesPath", "MVND_PROPERTIES_PATH", null, OptionType.PATH, Flags.NONE),
+ MVND_PROPERTIES_PATH( "mvnd.propertiesPath", "MVND_PROPERTIES_PATH", null, OptionType.PATH, Flags.NONE ),
/**
* The directory under which the daemon stores its registry, log files, etc.
* Default: <code>${user.home}/.m2/mvnd</code>
*/
- MVND_DAEMON_STORAGE("mvnd.daemonStorage", null, null, OptionType.PATH, Flags.NONE),
+ MVND_DAEMON_STORAGE( "mvnd.daemonStorage", null, null, OptionType.PATH, Flags.NONE ),
/**
* The path to the daemon registry.
* Default: <code>${mvnd.daemonStorage}/registry.bin</code>
*/
- MVND_REGISTRY("mvnd.registry", null, null, OptionType.PATH, Flags.NONE),
+ MVND_REGISTRY( "mvnd.registry", null, null, OptionType.PATH, Flags.NONE ),
/**
* If <code>true</code> the log messages are displayed continuously like with stock Maven; otherwise buffer the
* messages and output at the end of the build, grouped by module. Passing <code>-B</code> or
* <code>--batch-mode</code> on the command line enables this too for the given build.
*/
- MVND_NO_BUFERING("mvnd.noBuffering", null, Boolean.FALSE, OptionType.BOOLEAN, Flags.NONE),
+ MVND_NO_BUFERING( "mvnd.noBuffering", null, Boolean.FALSE, OptionType.BOOLEAN, Flags.NONE ),
/**
* The number of log lines to display for each Maven module that is built in parallel. The value can be increased
* or decreased by pressing + or - key during the build respectively. This option has no effect with
* <code>-Dmvnd.noBuffering=true</code>, <code>-B</code> or <code>--batch-mode</code>.
*/
- MVND_ROLLING_WINDOW_SIZE("mvnd.rollingWindowSize", null, "0", OptionType.INTEGER, Flags.NONE),
+ MVND_ROLLING_WINDOW_SIZE( "mvnd.rollingWindowSize", null, "0", OptionType.INTEGER, Flags.NONE ),
/**
* Daemon log files older than this value will be removed automatically.
*/
- MVND_LOG_PURGE_PERIOD("mvnd.logPurgePeriod", null, "7 days", OptionType.DURATION, Flags.NONE),
+ MVND_LOG_PURGE_PERIOD( "mvnd.logPurgePeriod", null, "7 days", OptionType.DURATION, Flags.NONE ),
/**
* If <code>true</code>, the client and daemon will run in the same JVM that exits when the build is finished;
* otherwise the client starts/connects to a long living daemon process. This option is only available with
* non-native clients and is useful mostly for debugging.
*/
- MVND_NO_DAEMON("mvnd.noDaemon", "MVND_NO_DAEMON", Boolean.FALSE, OptionType.BOOLEAN, Flags.DISCRIMINATING),
+ MVND_NO_DAEMON( "mvnd.noDaemon", "MVND_NO_DAEMON", Boolean.FALSE, OptionType.BOOLEAN, Flags.DISCRIMINATING ),
/**
* If <code>true</code>, the daemon will be launched in debug mode with the following JVM argument:
* <code>-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=8000</code>; otherwise the debug argument is
* not passed to the daemon.
*/
- MVND_DEBUG("mvnd.debug", null, Boolean.FALSE, OptionType.BOOLEAN, Flags.DISCRIMINATING),
+ MVND_DEBUG( "mvnd.debug", null, Boolean.FALSE, OptionType.BOOLEAN, Flags.DISCRIMINATING ),
/**
* A time period after which an unused daemon will terminate by itself.
*/
- MVND_IDLE_TIMEOUT("mvnd.idleTimeout", null, "3 hours", OptionType.DURATION, Flags.DISCRIMINATING),
+ MVND_IDLE_TIMEOUT( "mvnd.idleTimeout", null, "3 hours", OptionType.DURATION, Flags.DISCRIMINATING ),
/**
* If the daemon does not send any message to the client in this period of time, send a keep-alive message so that
* the client knows that the daemon is still alive.
*/
- MVND_KEEP_ALIVE("mvnd.keepAlive", null, "100 ms", OptionType.DURATION, Flags.DISCRIMINATING),
+ MVND_KEEP_ALIVE( "mvnd.keepAlive", null, "100 ms", OptionType.DURATION, Flags.DISCRIMINATING ),
/**
* The maximum number of keep alive messages that can be missed by the client before the client considers the daemon
* to be dead.
*/
- MVND_MAX_LOST_KEEP_ALIVE("mvnd.maxLostKeepAlive", null, 30, OptionType.INTEGER, Flags.NONE),
+ MVND_MAX_LOST_KEEP_ALIVE( "mvnd.maxLostKeepAlive", null, 30, OptionType.INTEGER, Flags.NONE ),
/**
* The minimum number of threads to use when constructing the default <code>-T</code> parameter for the daemon.
* This value is ignored if the user passes <code>-T</code>, <code>--threads</code> or <code>-Dmvnd.threads</code>
* on the command line or if he sets <code>mvnd.threads</code> in <code>~/.m2/mvnd.properties</code>.
*/
- MVND_MIN_THREADS("mvnd.minThreads", null, 1, OptionType.INTEGER, Flags.NONE),
+ MVND_MIN_THREADS( "mvnd.minThreads", null, 1, OptionType.INTEGER, Flags.NONE ),
/**
* The number of threads to pass to the daemon; same syntax as Maven's <code>-T</code>/<code>--threads</code>
* option.
*/
- MVND_THREADS("mvnd.threads", null, null, OptionType.STRING, Flags.NONE, "mvn:-T", "mvn:--threads"),
+ MVND_THREADS( "mvnd.threads", null, null, OptionType.STRING, Flags.NONE, "mvn:-T", "mvn:--threads" ),
/**
* The builder implementation the daemon should use.
*/
- MVND_BUILDER("mvnd.builder", null, "smart", OptionType.STRING, Flags.NONE, "mvn:-b", "mvn:--builder"),
+ MVND_BUILDER( "mvnd.builder", null, "smart", OptionType.STRING, Flags.NONE, "mvn:-b", "mvn:--builder" ),
/**
* An ID for a newly started daemon.
*/
- MVND_ID("mvnd.id", null, null, OptionType.STRING, Flags.INTERNAL),
+ MVND_ID( "mvnd.id", null, null, OptionType.STRING, Flags.INTERNAL ),
/**
* Internal option to specify the maven extension classpath.
*/
- MVND_EXT_CLASSPATH("mvnd.extClasspath", null, null, OptionType.STRING, Flags.DISCRIMINATING | Flags.INTERNAL),
+ MVND_EXT_CLASSPATH( "mvnd.extClasspath", null, null, OptionType.STRING, Flags.DISCRIMINATING | Flags.INTERNAL ),
/**
* Internal option to specify the list of maven extension to register.
*/
- MVND_CORE_EXTENSIONS("mvnd.coreExtensions", null, null, OptionType.STRING, Flags.DISCRIMINATING | Flags.INTERNAL),
+ MVND_CORE_EXTENSIONS( "mvnd.coreExtensions", null, null, OptionType.STRING, Flags.DISCRIMINATING | Flags.INTERNAL ),
/**
* The <code>-Xms</code> value to pass to the daemon.
* This option takes precedence over options specified in {@link #MVND_JVM_ARGS}.
*/
- MVND_MIN_HEAP_SIZE("mvnd.minHeapSize", null, "128M", OptionType.MEMORY_SIZE, Flags.DISCRIMINATING),
+ MVND_MIN_HEAP_SIZE( "mvnd.minHeapSize", null, "128M", OptionType.MEMORY_SIZE, Flags.DISCRIMINATING ),
/**
* The <code>-Xmx</code> value to pass to the daemon.
* This option takes precedence over options specified in {@link #MVND_JVM_ARGS}.
*/
- MVND_MAX_HEAP_SIZE("mvnd.maxHeapSize", null, "2G", OptionType.MEMORY_SIZE, Flags.DISCRIMINATING),
+ MVND_MAX_HEAP_SIZE( "mvnd.maxHeapSize", null, "2G", OptionType.MEMORY_SIZE, Flags.DISCRIMINATING ),
/**
* The <code>-Xss</code> value to pass to the daemon.
* This option takes precedence over options specified in {@link #MVND_JVM_ARGS}.
*/
- MVND_THREAD_STACK_SIZE("mvnd.threadStackSize", null, "1M", OptionType.MEMORY_SIZE, Flags.DISCRIMINATING),
+ MVND_THREAD_STACK_SIZE( "mvnd.threadStackSize", null, "1M", OptionType.MEMORY_SIZE, Flags.DISCRIMINATING ),
/**
* Additional JVM args to pass to the daemon.
* The content of the <code>.mvn/jvm.config</code> file will prepended (and thus with
* a lesser priority) to the user supplied value for this parameter before being used
* as startup options for the daemon JVM.
*/
- MVND_JVM_ARGS("mvnd.jvmArgs", null, null, OptionType.STRING, Flags.DISCRIMINATING | Flags.OPTIONAL),
+ MVND_JVM_ARGS( "mvnd.jvmArgs", null, null, OptionType.STRING, Flags.DISCRIMINATING | Flags.OPTIONAL ),
/**
* If <code>true</code>, the <code>-ea</code> option will be passed to the daemon; otherwise the <code>-ea</code>
* option is not passed to the daemon.
*/
- MVND_ENABLE_ASSERTIONS("mvnd.enableAssertions", null, Boolean.FALSE, OptionType.BOOLEAN, Flags.DISCRIMINATING),
+ MVND_ENABLE_ASSERTIONS( "mvnd.enableAssertions", null, Boolean.FALSE, OptionType.BOOLEAN, Flags.DISCRIMINATING ),
/**
* The daemon will check this often whether it should exit.
*/
- MVND_EXPIRATION_CHECK_DELAY("mvnd.expirationCheckDelay", null, "10 seconds", OptionType.DURATION, Flags.DISCRIMINATING),
+ MVND_EXPIRATION_CHECK_DELAY( "mvnd.expirationCheckDelay", null, "10 seconds", OptionType.DURATION,
+ Flags.DISCRIMINATING ),
/**
* Period after which idle duplicate daemons will be shut down. Duplicate daemons are daemons with the same set of
* discriminating start parameters.
*/
- MVND_DUPLICATE_DAEMON_GRACE_PERIOD("mvnd.duplicateDaemonGracePeriod", null, "10 seconds", OptionType.DURATION,
- Flags.DISCRIMINATING),
+ MVND_DUPLICATE_DAEMON_GRACE_PERIOD( "mvnd.duplicateDaemonGracePeriod", null, "10 seconds", OptionType.DURATION,
+ Flags.DISCRIMINATING ),
/**
* Internal property to tell the daemon the width of the terminal
*/
- MVND_TERMINAL_WIDTH("mvnd.terminalWidth", null, 0, OptionType.INTEGER, Flags.INTERNAL),
+ MVND_TERMINAL_WIDTH( "mvnd.terminalWidth", null, 0, OptionType.INTEGER, Flags.INTERNAL ),
/**
* Internal property to tell the daemon which JAVA_HOME was used to start it. It needs to be passed explicitly
* because the value may differ from what the daemon sees through <code>System.getProperty("java.home")</code>.
*/
- MVND_JAVA_HOME("mvnd.java.home", null, null, OptionType.PATH, Flags.INTERNAL),
+ MVND_JAVA_HOME( "mvnd.java.home", null, null, OptionType.PATH, Flags.INTERNAL ),
/**
* Log mojos execution time at the end of the build.
*/
- MVND_BUILD_TIME("mvnd.buildTime", null, null, OptionType.BOOLEAN, Flags.NONE),
+ MVND_BUILD_TIME( "mvnd.buildTime", null, null, OptionType.BOOLEAN, Flags.NONE ),
/**
* Socket family to use
*/
- MVND_SOCKET_FAMILY("mvnd.socketFamily", null, "inet", OptionType.STRING, Flags.DISCRIMINATING),
+ MVND_SOCKET_FAMILY( "mvnd.socketFamily", null, "inet", OptionType.STRING, Flags.DISCRIMINATING ),
/**
* Pattern that will force eviction of the plugin realms if one of its dependencies matches.
* The overall pattern is a comma separated list of either:
@@ -266,24 +270,27 @@ public enum Environment {
* This pattern will be evaluated against the full path of the dependencies, so it is usually desirable to
* start with <code>'glob:**/'</code> to support any location of the local repository.
*/
- MVND_PLUGIN_REALM_EVICT_PATTERN("mvnd.pluginRealmEvictPattern", null, "", OptionType.STRING, Flags.OPTIONAL),
+ MVND_PLUGIN_REALM_EVICT_PATTERN( "mvnd.pluginRealmEvictPattern", null, "", OptionType.STRING, Flags.OPTIONAL ),
/**
* The SyncContextFactory to use (can be either 'noop' or 'ipc' for a server-wide factory).
*/
- MVND_SYNC_CONTEXT_FACTORY("mvnd.syncContextFactory", null, "local", OptionType.BOOLEAN, Flags.OPTIONAL);
+ MVND_SYNC_CONTEXT_FACTORY( "mvnd.syncContextFactory", null, "local", OptionType.BOOLEAN, Flags.OPTIONAL );
static Properties properties;
- public static void setProperties(Properties properties) {
+ public static void setProperties( Properties properties )
+ {
Environment.properties = properties;
}
- public static String getProperty(String property) {
+ public static String getProperty( String property )
+ {
Properties props = Environment.properties;
- if (props == null) {
+ if ( props == null )
+ {
props = System.getProperties();
}
- return props.getProperty(property);
+ return props.getProperty( property );
}
private final String property;
@@ -293,164 +300,217 @@ public enum Environment {
private final OptionType type;
private final Map<String, OptionOrigin> options;
- Environment(String property, String environmentVariable, Object default_, OptionType type, int flags,
- String... options) {
- if (property == null && options.length == 0) {
+ Environment( String property, String environmentVariable, Object default_, OptionType type, int flags,
+ String... options )
+ {
+ if ( property == null && options.length == 0 )
+ {
throw new IllegalArgumentException(
- "An " + Environment.class.getSimpleName() + " entry must have property or options set");
+ "An " + Environment.class.getSimpleName() + " entry must have property or options set" );
}
this.property = property;
this.environmentVariable = environmentVariable;
this.default_ = default_ != null ? default_.toString() : null;
this.flags = flags;
this.type = type;
- if (options.length == 0) {
+ if ( options.length == 0 )
+ {
this.options = Collections.emptyMap();
- } else {
+ }
+ else
+ {
final Map<String, OptionOrigin> optMap = new LinkedHashMap<>();
- for (String opt : options) {
- OPTION_ORIGIN_SEARCH: {
- for (OptionOrigin oo : OptionOrigin.values()) {
- if (opt.startsWith(oo.prefix)) {
- optMap.put(opt.substring(oo.prefix.length()), oo);
+ for ( String opt : options )
+ {
+ OPTION_ORIGIN_SEARCH:
+ {
+ for ( OptionOrigin oo : OptionOrigin.values() )
+ {
+ if ( opt.startsWith( oo.prefix ) )
+ {
+ optMap.put( opt.substring( oo.prefix.length() ), oo );
break OPTION_ORIGIN_SEARCH;
}
}
throw new IllegalArgumentException(
"Unexpected option prefix: '" + opt + "'; Options should start with any of "
- + Stream.of(OptionOrigin.values()).map(oo -> oo.prefix).collect(Collectors.joining(",")));
+ + Stream.of( OptionOrigin.values() ).map( oo -> oo.prefix )
+ .collect( Collectors.joining( "," ) ) );
}
}
- this.options = Collections.unmodifiableMap(optMap);
+ this.options = Collections.unmodifiableMap( optMap );
}
}
- public String getProperty() {
+ public String getProperty()
+ {
return property;
}
- public String getEnvironmentVariable() {
+ public String getEnvironmentVariable()
+ {
return environmentVariable;
}
- public String getDefault() {
+ public String getDefault()
+ {
return default_;
}
- public Set<String> getOptions() {
+ public Set<String> getOptions()
+ {
return options.keySet();
}
- public Map<String, OptionOrigin> getOptionMap() {
+ public Map<String, OptionOrigin> getOptionMap()
+ {
return options;
}
- public OptionType getType() {
+ public OptionType getType()
+ {
return type;
}
- public boolean isDiscriminating() {
- return (flags & Flags.DISCRIMINATING) != 0;
+ public boolean isDiscriminating()
+ {
+ return ( flags & Flags.DISCRIMINATING ) != 0;
}
- public boolean isInternal() {
- return (flags & Flags.INTERNAL) != 0;
+ public boolean isInternal()
+ {
+ return ( flags & Flags.INTERNAL ) != 0;
}
- public boolean isOptional() {
- return (flags & Flags.OPTIONAL) != 0;
+ public boolean isOptional()
+ {
+ return ( flags & Flags.OPTIONAL ) != 0;
}
- public String asString() {
- String val = getProperty(property);
- if (val == null) {
- throw new IllegalStateException("The system property " + property + " is missing");
+ public String asString()
+ {
+ String val = getProperty( property );
+ if ( val == null )
+ {
+ throw new IllegalStateException( "The system property " + property + " is missing" );
}
return val;
}
- public Optional<String> asOptional() {
- String val = getProperty(property);
- if (val != null) {
- return Optional.of(val);
- } else if (isOptional()) {
+ public Optional<String> asOptional()
+ {
+ String val = getProperty( property );
+ if ( val != null )
+ {
+ return Optional.of( val );
+ }
+ else if ( isOptional() )
+ {
return Optional.empty();
- } else {
- throw new IllegalStateException("The system property " + property + " is missing");
+ }
+ else
+ {
+ throw new IllegalStateException( "The system property " + property + " is missing" );
}
}
- public int asInt() {
- return Integer.parseInt(asString());
+ public int asInt()
+ {
+ return Integer.parseInt( asString() );
}
- public boolean asBoolean() {
- return Boolean.parseBoolean(asString());
+ public boolean asBoolean()
+ {
+ return Boolean.parseBoolean( asString() );
}
- public Path asPath() {
+ public Path asPath()
+ {
String result = asString();
- if (Os.current().isCygwin()) {
- result = cygpath(result);
+ if ( Os.current().isCygwin() )
+ {
+ result = cygpath( result );
}
- return Paths.get(result);
+ return Paths.get( result );
}
- public Duration asDuration() {
- return TimeUtils.toDuration(asString());
+ public Duration asDuration()
+ {
+ return TimeUtils.toDuration( asString() );
}
- public String asDaemonOpt(String value) {
- return property + "=" + type.normalize(value);
+ public String asDaemonOpt( String value )
+ {
+ return property + "=" + type.normalize( value );
}
- public void addCommandLineOption(Collection<String> args, String value) {
- if (!options.isEmpty()) {
- args.add(options.keySet().iterator().next());
- args.add(type.normalize(value));
- } else {
- args.add("-D" + property + "=" + type.normalize(value));
+ public void addCommandLineOption( Collection<String> args, String value )
+ {
+ if ( !options.isEmpty() )
+ {
+ args.add( options.keySet().iterator().next() );
+ args.add( type.normalize( value ) );
+ }
+ else
+ {
+ args.add( "-D" + property + "=" + type.normalize( value ) );
}
}
- public boolean hasCommandLineOption(Collection<String> args) {
+ public boolean hasCommandLineOption( Collection<String> args )
+ {
final String[] prefixes = getPrefixes();
- return args.stream().anyMatch(arg -> Stream.of(prefixes).anyMatch(arg::startsWith));
+ return args.stream().anyMatch( arg -> Stream.of( prefixes ).anyMatch( arg::startsWith ) );
}
- public String getCommandLineOption(Collection<String> args) {
- return getCommandLineOption(args, false);
+ public String getCommandLineOption( Collection<String> args )
+ {
+ return getCommandLineOption( args, false );
}
- public String removeCommandLineOption(Collection<String> args) {
- return getCommandLineOption(args, true);
+ public String removeCommandLineOption( Collection<String> args )
+ {
+ return getCommandLineOption( args, true );
}
- String getCommandLineOption(Collection<String> args, boolean remove) {
+ String getCommandLineOption( Collection<String> args, boolean remove )
+ {
final String[] prefixes = getPrefixes();
String value = null;
- for (Iterator<String> it = args.iterator(); it.hasNext();) {
+ for ( Iterator<String> it = args.iterator(); it.hasNext(); )
+ {
String arg = it.next();
- if (Stream.of(prefixes).anyMatch(arg::startsWith)) {
- if (remove) {
+ if ( Stream.of( prefixes ).anyMatch( arg::startsWith ) )
+ {
+ if ( remove )
+ {
it.remove();
}
- if (type == OptionType.VOID) {
+ if ( type == OptionType.VOID )
+ {
value = "";
- } else {
- String opt = Stream.of(prefixes).filter(arg::startsWith)
- .max(Comparator.comparing(String::length)).get();
- value = arg.substring(opt.length());
- if (value.isEmpty()) {
- if (it.hasNext()) {
+ }
+ else
+ {
+ String opt = Stream.of( prefixes ).filter( arg::startsWith )
+ .max( Comparator.comparing( String::length ) ).get();
+ value = arg.substring( opt.length() );
+ if ( value.isEmpty() )
+ {
+ if ( it.hasNext() )
+ {
value = it.next();
- if (remove) {
+ if ( remove )
+ {
it.remove();
}
}
- } else {
- if (value.charAt(0) == '=') {
- value = value.substring(1);
+ }
+ else
+ {
+ if ( value.charAt( 0 ) == '=' )
+ {
+ value = value.substring( 1 );
}
}
}
@@ -459,55 +519,73 @@ public enum Environment {
return value;
}
- private String[] getPrefixes() {
+ private String[] getPrefixes()
+ {
final String[] prefixes;
- if (options.isEmpty()) {
- prefixes = new String[] { "-D" + property + "=" };
- } else if (property != null) {
+ if ( options.isEmpty() )
+ {
+ prefixes = new String[]
+ { "-D" + property + "="
+ };
+ }
+ else if ( property != null )
+ {
prefixes = new String[options.size() + 1];
- options.keySet().toArray(prefixes);
+ options.keySet().toArray( prefixes );
prefixes[options.size()] = "-D" + property + "=";
- } else {
- prefixes = options.keySet().toArray(new String[0]);
+ }
+ else
+ {
+ prefixes = options.keySet().toArray( new String[0] );
}
return prefixes;
}
- public static String cygpath(String result) {
- String path = result.replace('/', '\\');
- if (path.matches("\\\\cygdrive\\\\[a-z]\\\\.*")) {
- String s = path.substring("\\cygdrive\\".length());
- result = s.substring(0, 1).toUpperCase(Locale.ENGLISH) + ":" + s.substring(1);
+ public static String cygpath( String result )
+ {
+ String path = result.replace( '/', '\\' );
+ if ( path.matches( "\\\\cygdrive\\\\[a-z]\\\\.*" ) )
+ {
+ String s = path.substring( "\\cygdrive\\".length() );
+ result = s.substring( 0, 1 ).toUpperCase( Locale.ENGLISH ) + ":" + s.substring( 1 );
}
return result;
}
- public static boolean isNative() {
- return "executable".equals(System.getProperty("org.graalvm.nativeimage.kind"));
+ public static boolean isNative()
+ {
+ return "executable".equals( System.getProperty( "org.graalvm.nativeimage.kind" ) );
}
- public static Stream<DocumentedEnumEntry<Environment>> documentedEntries() {
+ public static Stream<DocumentedEnumEntry<Environment>> documentedEntries()
+ {
Properties props = new Properties();
Environment[] values = values();
final String cliOptionsPath = values[0].getClass().getSimpleName() + ".javadoc.properties";
- try (InputStream in = Environment.class.getResourceAsStream(cliOptionsPath)) {
- props.load(in);
- } catch (IOException e) {
- throw new RuntimeException("Could not read " + cliOptionsPath, e);
+ try ( InputStream in = Environment.class.getResourceAsStream( cliOptionsPath ) )
+ {
+ props.load( in );
+ }
+ catch ( IOException e )
+ {
+ throw new RuntimeException( "Could not read " + cliOptionsPath, e );
}
- return Stream.of(values)
- .filter(env -> !env.isInternal())
- .sorted(Comparator.<Environment, String> comparing(env -> env.property != null ? env.property : "")
- .thenComparing(env -> !env.options.isEmpty() ? env.options.keySet().iterator().next() : ""))
- .map(env -> new DocumentedEnumEntry<>(env, props.getProperty(env.name())));
+ return Stream.of( values )
+ .filter( env -> !env.isInternal() )
+ .sorted( Comparator.<Environment, String> comparing( env -> env.property != null ? env.property : "" )
+ .thenComparing( env -> !env.options.isEmpty() ? env.options.keySet().iterator().next() : "" ) )
+ .map( env -> new DocumentedEnumEntry<>( env, props.getProperty( env.name() ) ) );
}
- public enum OptionOrigin {
+ public enum OptionOrigin
+ {
+
mvn, mvnd;
private final String prefix;
- private OptionOrigin() {
+ private OptionOrigin()
+ {
this.prefix = name() + ":";
}
}
@@ -515,34 +593,43 @@ public enum Environment {
/**
* The values of {@link Environment#MAVEN_COLOR} option.
*/
- public enum Color {
+ public enum Color
+ {
+
always, never, auto;
- public static Optional<Color> of(String color) {
- return color == null ? Optional.empty() : Optional.of(Color.valueOf(color));
+ public static Optional<Color> of( String color )
+ {
+ return color == null ? Optional.empty() : Optional.of( Color.valueOf( color ) );
}
}
- public static class DocumentedEnumEntry<E> {
+ public static class DocumentedEnumEntry<E>
+ {
private final E entry;
private final String javaDoc;
- public DocumentedEnumEntry(E entry, String javaDoc) {
+ public DocumentedEnumEntry( E entry, String javaDoc )
+ {
this.entry = entry;
this.javaDoc = javaDoc;
}
- public E getEntry() {
+ public E getEntry()
+ {
return entry;
}
- public String getJavaDoc() {
+ public String getJavaDoc()
+ {
return javaDoc;
}
}
- static class Flags {
+ static class Flags
+ {
+
private static final int NONE = 0b0;
private static final int DISCRIMINATING = 0b1;
private static final int INTERNAL = 0b10;
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/IoUtils.java b/common/src/main/java/org/mvndaemon/mvnd/common/IoUtils.java
index 0d7f055..5500588 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/IoUtils.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/IoUtils.java
@@ -21,22 +21,29 @@ import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
-public class IoUtils {
- public static String readResource(ClassLoader cl, String resourcePath) {
+public class IoUtils
+{
+
+ public static String readResource( ClassLoader cl, String resourcePath )
+ {
final StringBuilder result = new StringBuilder();
final int bufSize = 1024;
- try (Reader in = new BufferedReader(
+ try ( Reader in = new BufferedReader(
new InputStreamReader(
- cl.getResourceAsStream(resourcePath),
- StandardCharsets.UTF_8),
- bufSize)) {
+ cl.getResourceAsStream( resourcePath ),
+ StandardCharsets.UTF_8 ),
+ bufSize ) )
+ {
int len = 0;
char[] buf = new char[bufSize];
- while ((len = in.read(buf)) >= 0) {
- result.append(buf, 0, len);
+ while ( ( len = in.read( buf ) ) >= 0 )
+ {
+ result.append( buf, 0, len );
}
- } catch (IOException e) {
- throw new RuntimeException("Could not read a class path resource: " + resourcePath, e);
+ }
+ catch ( IOException e )
+ {
+ throw new RuntimeException( "Could not read a class path resource: " + resourcePath, e );
}
return result.toString();
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/JavaVersion.java b/common/src/main/java/org/mvndaemon/mvnd/common/JavaVersion.java
index 1854d8b..9a90c8d 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/JavaVersion.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/JavaVersion.java
@@ -15,13 +15,16 @@
*/
package org.mvndaemon.mvnd.common;
-public class JavaVersion {
+public class JavaVersion
+{
private static float javaSpec = 0.0f;
- public static float getJavaSpec() {
- if (javaSpec <= 0.0f) {
- javaSpec = Float.parseFloat(System.getProperty("java.specification.version"));
+ public static float getJavaSpec()
+ {
+ if ( javaSpec <= 0.0f )
+ {
+ javaSpec = Float.parseFloat( System.getProperty( "java.specification.version" ) );
}
return javaSpec;
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/MavenDaemon.java b/common/src/main/java/org/mvndaemon/mvnd/common/MavenDaemon.java
index d94779f..4b2b9f6 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/MavenDaemon.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/MavenDaemon.java
@@ -22,62 +22,82 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
-public class MavenDaemon {
+public class MavenDaemon
+{
- public static void main(String[] args) throws Exception {
+ public static void main( String[] args ) throws Exception
+ {
final Path mvndHome = Environment.MVND_HOME.asPath();
URL[] classpath = Stream.concat(
/* jars */
- Stream.of("mvn/lib/ext", "mvn/lib", "mvn/boot")
- .map(mvndHome::resolve)
- .flatMap((Path p) -> {
- try {
- return Files.list(p);
- } catch (java.io.IOException e) {
- throw new RuntimeException("Could not list " + p, e);
+ Stream.of( "mvn/lib/ext", "mvn/lib", "mvn/boot" )
+ .map( mvndHome::resolve )
+ .flatMap( ( Path p ) ->
+ {
+ try
+ {
+ return Files.list( p );
}
- })
- .filter(p -> {
+ catch ( java.io.IOException e )
+ {
+ throw new RuntimeException( "Could not list " + p, e );
+ }
+ } )
+ .filter( p ->
+ {
final String fileName = p.getFileName().toString();
- return fileName.endsWith(".jar") && !fileName.startsWith("mvnd-client-");
- })
- .filter(Files::isRegularFile),
+ return fileName.endsWith( ".jar" ) && !fileName.startsWith( "mvnd-client-" );
+ } )
+ .filter( Files::isRegularFile ),
/* resources */
- Stream.of(mvndHome.resolve("mvn/conf"), mvndHome.resolve("mvn/conf/logging")))
+ Stream.of( mvndHome.resolve( "mvn/conf" ), mvndHome.resolve( "mvn/conf/logging" ) ) )
- .map(Path::normalize)
- .map(Path::toUri)
- .map(uri -> {
- try {
+ .map( Path::normalize )
+ .map( Path::toUri )
+ .map( uri ->
+ {
+ try
+ {
return uri.toURL();
- } catch (MalformedURLException e) {
- throw new RuntimeException(e);
}
- })
- .toArray(URL[]::new);
- ClassLoader loader = new URLClassLoader(classpath, null) {
+ catch ( MalformedURLException e )
+ {
+ throw new RuntimeException( e );
+ }
+ } )
+ .toArray( URL[]::new );
+ ClassLoader loader = new URLClassLoader( classpath, null )
+ {
+
@Override
- protected Class<?> findClass(String name) throws ClassNotFoundException {
- try {
- return super.findClass(name);
- } catch (ClassNotFoundException e) {
- return MavenDaemon.class.getClassLoader().loadClass(name);
+ protected Class<?> findClass( String name ) throws ClassNotFoundException
+ {
+ try
+ {
+ return super.findClass( name );
+ }
+ catch ( ClassNotFoundException e )
+ {
+ return MavenDaemon.class.getClassLoader().loadClass( name );
}
}
@Override
- public URL getResource(String name) {
- URL url = super.getResource(name);
- if (url == null) {
- url = MavenDaemon.class.getClassLoader().getResource(name);
+ public URL getResource( String name )
+ {
+ URL url = super.getResource( name );
+ if ( url == null )
+ {
+ url = MavenDaemon.class.getClassLoader().getResource( name );
}
return url;
}
};
- Thread.currentThread().setContextClassLoader(loader);
- Class<?> clazz = loader.loadClass("org.mvndaemon.mvnd.daemon.Server");
- try (AutoCloseable server = (AutoCloseable) clazz.getConstructor().newInstance()) {
- ((Runnable) server).run();
+ Thread.currentThread().setContextClassLoader( loader );
+ Class<?> clazz = loader.loadClass( "org.mvndaemon.mvnd.daemon.Server" );
+ try ( AutoCloseable server = ( AutoCloseable ) clazz.getConstructor().newInstance() )
+ {
+ ( ( Runnable ) server ).run();
}
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/Message.java b/common/src/main/java/org/mvndaemon/mvnd/common/Message.java
index c1ffa7d..41f2570 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/Message.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/Message.java
@@ -29,7 +29,9 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
-public abstract class Message {
+public abstract class Message
+{
+
public static final int BUILD_REQUEST = 1;
public static final int BUILD_STARTED = 2;
public static final int BUILD_FINISHED = 3;
@@ -61,42 +63,46 @@ public abstract class Message {
final int type;
- Message(int type) {
+ Message( int type )
+ {
this.type = type;
}
- public static Message read(DataInputStream input) throws IOException {
+ public static Message read( DataInputStream input ) throws IOException
+ {
int type = input.read();
- if (type < 0) {
+ if ( type < 0 )
+ {
return null;
}
- switch (type) {
+ switch ( type )
+ {
case BUILD_REQUEST:
- return BuildRequest.read(input);
+ return BuildRequest.read( input );
case BUILD_STARTED:
- return BuildStarted.read(input);
+ return BuildStarted.read( input );
case BUILD_FINISHED:
- return BuildFinished.read(input);
+ return BuildFinished.read( input );
case MOJO_STARTED:
- return MojoStartedEvent.read(input);
+ return MojoStartedEvent.read( input );
case PROJECT_LOG_MESSAGE:
case DISPLAY:
- return ProjectEvent.read(type, input);
+ return ProjectEvent.read( type, input );
case BUILD_EXCEPTION:
- return BuildException.read(input);
+ return BuildException.read( input );
case KEEP_ALIVE:
return BareMessage.KEEP_ALIVE_SINGLETON;
case STOP:
return BareMessage.STOP_SINGLETON;
case PROMPT:
- return Prompt.read(input);
+ return Prompt.read( input );
case PROMPT_RESPONSE:
- return PromptResponse.read(input);
+ return PromptResponse.read( input );
case PROJECT_STARTED:
case PROJECT_STOPPED:
case BUILD_STATUS:
case BUILD_LOG_MESSAGE:
- return StringMessage.read(type, input);
+ return StringMessage.read( type, input );
case CANCEL_BUILD:
return BareMessage.CANCEL_BUILD_SINGLETON;
case TRANSFER_INITIATED:
@@ -105,24 +111,27 @@ public abstract class Message {
case TRANSFER_CORRUPTED:
case TRANSFER_SUCCEEDED:
case TRANSFER_FAILED:
- return TransferEvent.read(type, input);
+ return TransferEvent.read( type, input );
case EXECUTION_FAILURE:
- return ExecutionFailureEvent.read(input);
+ return ExecutionFailureEvent.read( input );
case PRINT_OUT:
case PRINT_ERR:
- return StringMessage.read(type, input);
+ return StringMessage.read( type, input );
}
- throw new IllegalStateException("Unexpected message type: " + type);
+ throw new IllegalStateException( "Unexpected message type: " + type );
}
final long timestamp = System.nanoTime();
- public static Comparator<Message> getMessageComparator() {
- return Comparator.comparingInt(Message::getClassOrder).thenComparingLong(Message::timestamp);
+ public static Comparator<Message> getMessageComparator()
+ {
+ return Comparator.comparingInt( Message::getClassOrder ).thenComparingLong( Message::timestamp );
}
- public static int getClassOrder(Message m) {
- switch (m.getType()) {
+ public static int getClassOrder( Message m )
+ {
+ switch ( m.getType() )
+ {
case KEEP_ALIVE:
case BUILD_REQUEST:
return 0;
@@ -162,49 +171,59 @@ public abstract class Message {
case STOP:
return 99;
default:
- throw new IllegalStateException("Unexpected message type " + m.getType() + ": " + m);
+ throw new IllegalStateException( "Unexpected message type " + m.getType() + ": " + m );
}
}
- public long timestamp() {
+ public long timestamp()
+ {
return timestamp;
}
- public void write(DataOutputStream output) throws IOException {
- output.write(type);
+ public void write( DataOutputStream output ) throws IOException
+ {
+ output.write( type );
}
- static void writeStringList(DataOutputStream output, List<String> value) throws IOException {
- output.writeInt(value.size());
- for (String v : value) {
- writeUTF(output, v);
+ static void writeStringList( DataOutputStream output, List<String> value ) throws IOException
+ {
+ output.writeInt( value.size() );
+ for ( String v : value )
+ {
+ writeUTF( output, v );
}
}
- static void writeStringMap(DataOutputStream output, Map<String, String> value) throws IOException {
- output.writeInt(value.size());
- for (Map.Entry<String, String> e : value.entrySet()) {
- writeUTF(output, e.getKey());
- writeUTF(output, e.getValue());
+ static void writeStringMap( DataOutputStream output, Map<String, String> value ) throws IOException
+ {
+ output.writeInt( value.size() );
+ for ( Map.Entry<String, String> e : value.entrySet() )
+ {
+ writeUTF( output, e.getKey() );
+ writeUTF( output, e.getValue() );
}
}
- static List<String> readStringList(DataInputStream input) throws IOException {
+ static List<String> readStringList( DataInputStream input ) throws IOException
+ {
ArrayList<String> l = new ArrayList<>();
int nb = input.readInt();
- for (int i = 0; i < nb; i++) {
- l.add(readUTF(input));
+ for ( int i = 0; i < nb; i++ )
+ {
+ l.add( readUTF( input ) );
}
return l;
}
- static Map<String, String> readStringMap(DataInputStream input) throws IOException {
+ static Map<String, String> readStringMap( DataInputStream input ) throws IOException
+ {
LinkedHashMap<String, String> m = new LinkedHashMap<>();
int nb = input.readInt();
- for (int i = 0; i < nb; i++) {
- String k = readUTF(input);
- String v = readUTF(input);
- m.put(k, v);
+ for ( int i = 0; i < nb; i++ )
+ {
+ String k = readUTF( input );
+ String v = readUTF( input );
+ m.put( k, v );
}
return m;
}
@@ -212,146 +231,188 @@ public abstract class Message {
private static final String INVALID_BYTE = "Invalid byte";
private static final int UTF_BUFS_CHAR_CNT = 256;
private static final int UTF_BUFS_BYTE_CNT = UTF_BUFS_CHAR_CNT * 3;
- private static final ThreadLocal<byte[]> BUF_TLS = ThreadLocal.withInitial(() -> new byte[UTF_BUFS_BYTE_CNT]);
+ private static final ThreadLocal<byte[]> BUF_TLS = ThreadLocal.withInitial( () -> new byte[UTF_BUFS_BYTE_CNT] );
- static String readUTF(DataInputStream input) throws IOException {
+ static String readUTF( DataInputStream input ) throws IOException
+ {
byte[] byteBuf = BUF_TLS.get();
int len = input.readInt();
- if (len == -1) {
+ if ( len == -1 )
+ {
return null;
}
final char[] chars = new char[len];
int i = 0, cnt = 0, charIdx = 0;
- while (charIdx < len) {
- if (i == cnt) {
- cnt = input.read(byteBuf, 0, Math.min(UTF_BUFS_BYTE_CNT, len - charIdx));
- if (cnt < 0) {
+ while ( charIdx < len )
+ {
+ if ( i == cnt )
+ {
+ cnt = input.read( byteBuf, 0, Math.min( UTF_BUFS_BYTE_CNT, len - charIdx ) );
+ if ( cnt < 0 )
+ {
throw new EOFException();
}
i = 0;
}
final int a = byteBuf[i++] & 0xff;
- if (a < 0x80) {
+ if ( a < 0x80 )
+ {
// low bit clear
- chars[charIdx++] = (char) a;
- } else if (a < 0xc0) {
- throw new UTFDataFormatException(INVALID_BYTE);
- } else if (a < 0xe0) {
- if (i == cnt) {
- cnt = input.read(byteBuf, 0, Math.min(UTF_BUFS_BYTE_CNT, len - charIdx));
- if (cnt < 0) {
+ chars[charIdx++] = ( char ) a;
+ }
+ else if ( a < 0xc0 )
+ {
+ throw new UTFDataFormatException( INVALID_BYTE );
+ }
+ else if ( a < 0xe0 )
+ {
+ if ( i == cnt )
+ {
+ cnt = input.read( byteBuf, 0, Math.min( UTF_BUFS_BYTE_CNT, len - charIdx ) );
+ if ( cnt < 0 )
+ {
throw new EOFException();
}
i = 0;
}
final int b = byteBuf[i++] & 0xff;
- if ((b & 0xc0) != 0x80) {
- throw new UTFDataFormatException(INVALID_BYTE);
+ if ( ( b & 0xc0 ) != 0x80 )
+ {
+ throw new UTFDataFormatException( INVALID_BYTE );
}
- chars[charIdx++] = (char) ((a & 0x1f) << 6 | b & 0x3f);
- } else if (a < 0xf0) {
- if (i == cnt) {
- cnt = input.read(byteBuf, 0, Math.min(UTF_BUFS_BYTE_CNT, len - charIdx));
- if (cnt < 0) {
+ chars[charIdx++] = ( char ) ( ( a & 0x1f ) << 6 | b & 0x3f );
+ }
+ else if ( a < 0xf0 )
+ {
+ if ( i == cnt )
+ {
+ cnt = input.read( byteBuf, 0, Math.min( UTF_BUFS_BYTE_CNT, len - charIdx ) );
+ if ( cnt < 0 )
+ {
throw new EOFException();
}
i = 0;
}
final int b = byteBuf[i++] & 0xff;
- if ((b & 0xc0) != 0x80) {
- throw new UTFDataFormatException(INVALID_BYTE);
+ if ( ( b & 0xc0 ) != 0x80 )
+ {
+ throw new UTFDataFormatException( INVALID_BYTE );
}
- if (i == cnt) {
- cnt = input.read(byteBuf, 0, Math.min(UTF_BUFS_BYTE_CNT, len - charIdx));
- if (cnt < 0) {
+ if ( i == cnt )
+ {
+ cnt = input.read( byteBuf, 0, Math.min( UTF_BUFS_BYTE_CNT, len - charIdx ) );
+ if ( cnt < 0 )
+ {
throw new EOFException();
}
i = 0;
}
final int c = byteBuf[i++] & 0xff;
- if ((c & 0xc0) != 0x80) {
- throw new UTFDataFormatException(INVALID_BYTE);
+ if ( ( c & 0xc0 ) != 0x80 )
+ {
+ throw new UTFDataFormatException( INVALID_BYTE );
}
- chars[charIdx++] = (char) ((a & 0x0f) << 12 | (b & 0x3f) << 6 | c & 0x3f);
- } else {
- throw new UTFDataFormatException(INVALID_BYTE);
+ chars[charIdx++] = ( char ) ( ( a & 0x0f ) << 12 | ( b & 0x3f ) << 6 | c & 0x3f );
+ }
+ else
+ {
+ throw new UTFDataFormatException( INVALID_BYTE );
}
}
- return String.valueOf(chars);
+ return String.valueOf( chars );
}
- static void writeUTF(DataOutputStream output, String s) throws IOException {
+ static void writeUTF( DataOutputStream output, String s ) throws IOException
+ {
byte[] byteBuf = BUF_TLS.get();
- if (s == null) {
- output.writeInt(-1);
+ if ( s == null )
+ {
+ output.writeInt( -1 );
return;
}
final int length = s.length();
- output.writeInt(length);
+ output.writeInt( length );
int strIdx = 0;
int byteIdx = 0;
- while (strIdx < length) {
- final char c = s.charAt(strIdx++);
- if (c > 0 && c <= 0x7f) {
- byteBuf[byteIdx++] = (byte) c;
- } else if (c <= 0x07ff) {
- byteBuf[byteIdx++] = (byte) (0xc0 | 0x1f & c >> 6);
- byteBuf[byteIdx++] = (byte) (0x80 | 0x3f & c);
- } else {
- byteBuf[byteIdx++] = (byte) (0xe0 | 0x0f & c >> 12);
- byteBuf[byteIdx++] = (byte) (0x80 | 0x3f & c >> 6);
- byteBuf[byteIdx++] = (byte) (0x80 | 0x3f & c);
+ while ( strIdx < length )
+ {
+ final char c = s.charAt( strIdx++ );
+ if ( c > 0 && c <= 0x7f )
+ {
+ byteBuf[byteIdx++] = ( byte ) c;
+ }
+ else if ( c <= 0x07ff )
+ {
+ byteBuf[byteIdx++] = ( byte ) ( 0xc0 | 0x1f & c >> 6 );
+ byteBuf[byteIdx++] = ( byte ) ( 0x80 | 0x3f & c );
}
- if (byteIdx > UTF_BUFS_BYTE_CNT - 4) {
- output.write(byteBuf, 0, byteIdx);
+ else
+ {
+ byteBuf[byteIdx++] = ( byte ) ( 0xe0 | 0x0f & c >> 12 );
+ byteBuf[byteIdx++] = ( byte ) ( 0x80 | 0x3f & c >> 6 );
+ byteBuf[byteIdx++] = ( byte ) ( 0x80 | 0x3f & c );
+ }
+ if ( byteIdx > UTF_BUFS_BYTE_CNT - 4 )
+ {
+ output.write( byteBuf, 0, byteIdx );
byteIdx = 0;
}
}
- if (byteIdx > 0) {
- output.write(byteBuf, 0, byteIdx);
+ if ( byteIdx > 0 )
+ {
+ output.write( byteBuf, 0, byteIdx );
}
}
- public static class BuildRequest extends Message {
+ public static class BuildRequest extends Message
+ {
+
final List<String> args;
final String workingDir;
final String projectDir;
final Map<String, String> env;
- public static Message read(DataInputStream input) throws IOException {
- List<String> args = readStringList(input);
- String workingDir = readUTF(input);
- String projectDir = readUTF(input);
- Map<String, String> env = readStringMap(input);
- return new BuildRequest(args, workingDir, projectDir, env);
+ public static Message read( DataInputStream input ) throws IOException
+ {
+ List<String> args = readStringList( input );
+ String workingDir = readUTF( input );
+ String projectDir = readUTF( input );
+ Map<String, String> env = readStringMap( input );
+ return new BuildRequest( args, workingDir, projectDir, env );
}
- public BuildRequest(List<String> args, String workingDir, String projectDir, Map<String, String> env) {
- super(BUILD_REQUEST);
+ public BuildRequest( List<String> args, String workingDir, String projectDir, Map<String, String> env )
+ {
+ super( BUILD_REQUEST );
this.args = args;
this.workingDir = workingDir;
this.projectDir = projectDir;
this.env = env;
}
- public List<String> getArgs() {
+ public List<String> getArgs()
+ {
return args;
}
- public String getWorkingDir() {
+ public String getWorkingDir()
+ {
return workingDir;
}
- public String getProjectDir() {
+ public String getProjectDir()
+ {
return projectDir;
}
- public Map<String, String> getEnv() {
+ public Map<String, String> getEnv()
+ {
return env;
}
@Override
- public String toString() {
+ public String toString()
+ {
return "BuildRequest{" +
"args=" + args +
", workingDir='" + workingDir + '\'' +
@@ -361,87 +422,105 @@ public abstract class Message {
}
@Override
- public void write(DataOutputStream output) throws IOException {
- super.write(output);
- writeStringList(output, args);
- writeUTF(output, workingDir);
- writeUTF(output, projectDir);
- writeStringMap(output, env);
+ public void write( DataOutputStream output ) throws IOException
+ {
+ super.write( output );
+ writeStringList( output, args );
+ writeUTF( output, workingDir );
+ writeUTF( output, projectDir );
+ writeStringMap( output, env );
}
}
- public static class BuildFinished extends Message {
+ public static class BuildFinished extends Message
+ {
+
final int exitCode;
- public static Message read(DataInputStream input) throws IOException {
+ public static Message read( DataInputStream input ) throws IOException
+ {
int exitCode = input.readInt();
- return new BuildFinished(exitCode);
+ return new BuildFinished( exitCode );
}
- public BuildFinished(int exitCode) {
- super(BUILD_FINISHED);
+ public BuildFinished( int exitCode )
+ {
+ super( BUILD_FINISHED );
this.exitCode = exitCode;
}
@Override
- public String toString() {
+ public String toString()
+ {
return "BuildFinished{exitCode=" + exitCode + '}';
}
@Override
- public void write(DataOutputStream output) throws IOException {
- super.write(output);
- output.writeInt(exitCode);
+ public void write( DataOutputStream output ) throws IOException
+ {
+ super.write( output );
+ output.writeInt( exitCode );
}
- public int getExitCode() {
+ public int getExitCode()
+ {
return exitCode;
}
}
- public static class BuildException extends Message {
+ public static class BuildException extends Message
+ {
+
final String message;
final String className;
final String stackTrace;
- public static Message read(DataInputStream input) throws IOException {
- String message = readUTF(input);
- String className = readUTF(input);
- String stackTrace = readUTF(input);
- return new BuildException(message, className, stackTrace);
+ public static Message read( DataInputStream input ) throws IOException
+ {
+ String message = readUTF( input );
+ String className = readUTF( input );
+ String stackTrace = readUTF( input );
+ return new BuildException( message, className, stackTrace );
}
- public BuildException(Throwable t) {
- this(t.getMessage(), t.getClass().getName(), getStackTrace(t));
+ public BuildException( Throwable t )
+ {
+ this( t.getMessage(), t.getClass().getName(), getStackTrace( t ) );
}
- public static String getStackTrace(Throwable t) {
+ public static String getStackTrace( Throwable t )
+ {
StringWriter sw = new StringWriter();
- t.printStackTrace(new PrintWriter(sw, true));
+ t.printStackTrace( new PrintWriter( sw, true ) );
return sw.toString();
}
- public BuildException(String message, String className, String stackTrace) {
- super(BUILD_EXCEPTION);
+ public BuildException( String message, String className, String stackTrace )
+ {
+ super( BUILD_EXCEPTION );
this.message = message;
this.className = className;
this.stackTrace = stackTrace;
}
- public String getMessage() {
+ public String getMessage()
+ {
return message;
}
- public String getClassName() {
+ public String getClassName()
+ {
return className;
}
- public String getStackTrace() {
+ public String getStackTrace()
+ {
return stackTrace;
}
@Override
- public String toString() {
+ public String toString()
+ {
return "BuildException{" +
"message='" + message + '\'' +
", className='" + className + '\'' +
@@ -450,64 +529,77 @@ public abstract class Message {
}
@Override
- public void write(DataOutputStream output) throws IOException {
- super.write(output);
- writeUTF(output, message);
- writeUTF(output, className);
- writeUTF(output, stackTrace);
+ public void write( DataOutputStream output ) throws IOException
+ {
+ super.write( output );
+ writeUTF( output, message );
+ writeUTF( output, className );
+ writeUTF( output, stackTrace );
}
}
- public static class ProjectEvent extends Message {
+ public static class ProjectEvent extends Message
+ {
+
final String projectId;
final String message;
- public static Message read(int type, DataInputStream input) throws IOException {
- String projectId = readUTF(input);
- String message = readUTF(input);
- return new ProjectEvent(type, projectId, message);
+ public static Message read( int type, DataInputStream input ) throws IOException
+ {
+ String projectId = readUTF( input );
+ String message = readUTF( input );
+ return new ProjectEvent( type, projectId, message );
}
- private ProjectEvent(int type, String projectId, String message) {
- super(type);
- this.projectId = Objects.requireNonNull(projectId, "projectId cannot be null");
- this.message = Objects.requireNonNull(message, "message cannot be null");
+ private ProjectEvent( int type, String projectId, String message )
+ {
+ super( type );
+ this.projectId = Objects.requireNonNull( projectId, "projectId cannot be null" );
+ this.message = Objects.requireNonNull( message, "message cannot be null" );
}
- public String getProjectId() {
+ public String getProjectId()
+ {
return projectId;
}
- public String getMessage() {
+ public String getMessage()
+ {
return message;
}
@Override
- public String toString() {
+ public String toString()
+ {
return mnemonic() + "{" +
"projectId='" + projectId + '\'' +
", message='" + message + '\'' +
'}';
}
- private String mnemonic() {
- switch (type) {
+ private String mnemonic()
+ {
+ switch ( type )
+ {
case PROJECT_LOG_MESSAGE:
return "ProjectLogMessage";
default:
- throw new IllegalStateException("Unexpected type " + type);
+ throw new IllegalStateException( "Unexpected type " + type );
}
}
@Override
- public void write(DataOutputStream output) throws IOException {
- super.write(output);
- writeUTF(output, projectId);
- writeUTF(output, message);
+ public void write( DataOutputStream output ) throws IOException
+ {
+ super.write( output );
+ writeUTF( output, projectId );
+ writeUTF( output, message );
}
}
- public static class MojoStartedEvent extends Message {
+ public static class MojoStartedEvent extends Message
+ {
+
final String artifactId;
final String pluginGroupId;
final String pluginArtifactId;
@@ -515,53 +607,63 @@ public abstract class Message {
final String mojo;
final String executionId;
- public static MojoStartedEvent read(DataInputStream input) throws IOException {
- final String artifactId = readUTF(input);
- final String pluginGroupId = readUTF(input);
- final String pluginArtifactId = readUTF(input);
- final String pluginVersion = readUTF(input);
- final String mojo = readUTF(input);
- final String executionId = readUTF(input);
- return new MojoStartedEvent(artifactId, pluginGroupId, pluginArtifactId, pluginVersion, mojo, executionId);
- }
-
- public MojoStartedEvent(String artifactId, String pluginGroupId, String pluginArtifactId,
- String pluginVersion, String mojo, String executionId) {
- super(Message.MOJO_STARTED);
- this.artifactId = Objects.requireNonNull(artifactId, "artifactId cannot be null");
- this.pluginGroupId = Objects.requireNonNull(pluginGroupId, "pluginGroupId cannot be null");
- this.pluginArtifactId = Objects.requireNonNull(pluginArtifactId, "pluginArtifactId cannot be null");
- this.pluginVersion = Objects.requireNonNull(pluginVersion, "pluginVersion cannot be null");
- this.mojo = Objects.requireNonNull(mojo, "mojo cannot be null");
- this.executionId = Objects.requireNonNull(executionId, "executionId cannot be null");
- }
-
- public String getArtifactId() {
+ public static MojoStartedEvent read( DataInputStream input ) throws IOException
+ {
+ final String artifactId = readUTF( input );
+ final String pluginGroupId = readUTF( input );
+ final String pluginArtifactId = readUTF( input );
+ final String pluginVersion = readUTF( input );
+ final String mojo = readUTF( input );
+ final String executionId = readUTF( input );
+ return new MojoStartedEvent( artifactId, pluginGroupId, pluginArtifactId, pluginVersion, mojo,
+ executionId );
+ }
+
+ public MojoStartedEvent( String artifactId, String pluginGroupId, String pluginArtifactId,
+ String pluginVersion, String mojo, String executionId )
+ {
+ super( Message.MOJO_STARTED );
+ this.artifactId = Objects.requireNonNull( artifactId, "artifactId cannot be null" );
+ this.pluginGroupId = Objects.requireNonNull( pluginGroupId, "pluginGroupId cannot be null" );
+ this.pluginArtifactId = Objects.requireNonNull( pluginArtifactId, "pluginArtifactId cannot be null" );
+ this.pluginVersion = Objects.requireNonNull( pluginVersion, "pluginVersion cannot be null" );
+ this.mojo = Objects.requireNonNull( mojo, "mojo cannot be null" );
+ this.executionId = Objects.requireNonNull( executionId, "executionId cannot be null" );
+ }
+
+ public String getArtifactId()
+ {
return artifactId;
}
- public String getPluginGroupId() {
+ public String getPluginGroupId()
+ {
return pluginGroupId;
}
- public String getPluginArtifactId() {
+ public String getPluginArtifactId()
+ {
return pluginArtifactId;
}
- public String getPluginVersion() {
+ public String getPluginVersion()
+ {
return pluginVersion;
}
- public String getExecutionId() {
+ public String getExecutionId()
+ {
return executionId;
}
- public String getMojo() {
+ public String getMojo()
+ {
return mojo;
}
@Override
- public String toString() {
+ public String toString()
+ {
return "MojoStarted{" +
"artifactId='" + artifactId + '\'' +
", pluginGroupId='" + pluginGroupId + '\'' +
@@ -573,87 +675,101 @@ public abstract class Message {
}
@Override
- public void write(DataOutputStream output) throws IOException {
- super.write(output);
- writeUTF(output, artifactId);
- writeUTF(output, pluginGroupId);
- writeUTF(output, pluginArtifactId);
- writeUTF(output, pluginVersion);
- writeUTF(output, mojo);
- writeUTF(output, executionId);
+ public void write( DataOutputStream output ) throws IOException
+ {
+ super.write( output );
+ writeUTF( output, artifactId );
+ writeUTF( output, pluginGroupId );
+ writeUTF( output, pluginArtifactId );
+ writeUTF( output, pluginVersion );
+ writeUTF( output, mojo );
+ writeUTF( output, executionId );
}
}
- public static class BuildStarted extends Message {
+ public static class BuildStarted extends Message
+ {
final String projectId;
final int projectCount;
final int maxThreads;
final int artifactIdDisplayLength;
- public static BuildStarted read(DataInputStream input) throws IOException {
- final String projectId = readUTF(input);
+ public static BuildStarted read( DataInputStream input ) throws IOException
+ {
+ final String projectId = readUTF( input );
final int projectCount = input.readInt();
final int maxThreads = input.readInt();
final int artifactIdDisplayLength = input.readInt();
- return new BuildStarted(projectId, projectCount, maxThreads, artifactIdDisplayLength);
+ return new BuildStarted( projectId, projectCount, maxThreads, artifactIdDisplayLength );
}
- public BuildStarted(String projectId, int projectCount, int maxThreads, int artifactIdDisplayLength) {
- super(BUILD_STARTED);
+ public BuildStarted( String projectId, int projectCount, int maxThreads, int artifactIdDisplayLength )
+ {
+ super( BUILD_STARTED );
this.projectId = projectId;
this.projectCount = projectCount;
this.maxThreads = maxThreads;
this.artifactIdDisplayLength = artifactIdDisplayLength;
}
- public String getProjectId() {
+ public String getProjectId()
+ {
return projectId;
}
- public int getProjectCount() {
+ public int getProjectCount()
+ {
return projectCount;
}
- public int getMaxThreads() {
+ public int getMaxThreads()
+ {
return maxThreads;
}
- public int getArtifactIdDisplayLength() {
+ public int getArtifactIdDisplayLength()
+ {
return artifactIdDisplayLength;
}
@Override
- public String toString() {
+ public String toString()
+ {
return "BuildStarted{" +
"projectId='" + projectId + "', projectCount=" + projectCount +
", maxThreads=" + maxThreads + ", artifactIdDisplayLength=" + artifactIdDisplayLength + "}";
}
@Override
- public void write(DataOutputStream output) throws IOException {
- super.write(output);
- writeUTF(output, projectId);
- output.writeInt(projectCount);
- output.writeInt(maxThreads);
- output.writeInt(artifactIdDisplayLength);
+ public void write( DataOutputStream output ) throws IOException
+ {
+ super.write( output );
+ writeUTF( output, projectId );
+ output.writeInt( projectCount );
+ output.writeInt( maxThreads );
+ output.writeInt( artifactIdDisplayLength );
}
}
- public static class BareMessage extends Message {
+ public static class BareMessage extends Message
+ {
- public static final BareMessage KEEP_ALIVE_SINGLETON = new BareMessage(KEEP_ALIVE);
- public static final BareMessage STOP_SINGLETON = new BareMessage(STOP);
- public static final BareMessage CANCEL_BUILD_SINGLETON = new BareMessage(CANCEL_BUILD);
+ public static final BareMessage KEEP_ALIVE_SINGLETON = new BareMessage( KEEP_ALIVE );
+ public static final BareMessage STOP_SINGLETON = new BareMessage( STOP );
+ public static final BareMessage CANCEL_BUILD_SINGLETON = new BareMessage( CANCEL_BUILD );
- private BareMessage(int type) {
- super(type);
+ private BareMessage( int type )
+ {
+ super( type );
}
@Override
- public String toString() {
- switch (type) {
+ public String toString()
+ {
+ switch ( type )
+ {
case KEEP_ALIVE:
return "KeepAlive";
case BUILD_FINISHED:
@@ -663,43 +779,51 @@ public abstract class Message {
case CANCEL_BUILD:
return "BuildCanceled";
default:
- throw new IllegalStateException("Unexpected type " + type);
+ throw new IllegalStateException( "Unexpected type " + type );
}
}
}
- public static class StringMessage extends Message {
+ public static class StringMessage extends Message
+ {
final String message;
- public static StringMessage read(int type, DataInputStream input) throws IOException {
- String message = readUTF(input);
- return new StringMessage(type, message);
+ public static StringMessage read( int type, DataInputStream input ) throws IOException
+ {
+ String message = readUTF( input );
+ return new StringMessage( type, message );
}
- private StringMessage(int type, String message) {
- super(type);
+ private StringMessage( int type, String message )
+ {
+ super( type );
this.message = message;
}
- public String getMessage() {
+ public String getMessage()
+ {
return message;
}
@Override
- public void write(DataOutputStream output) throws IOException {
- super.write(output);
- writeUTF(output, message);
+ public void write( DataOutputStream output ) throws IOException
+ {
+ super.write( output );
+ writeUTF( output, message );
}
@Override
- public String toString() {
+ public String toString()
+ {
return mnemonic() + "{payload='" + message + "'}";
}
- private String mnemonic() {
- switch (type) {
+ private String mnemonic()
+ {
+ switch ( type )
+ {
case PROJECT_STARTED:
return "ProjectStarted";
case PROJECT_STOPPED:
@@ -717,53 +841,61 @@ public abstract class Message {
case PRINT_ERR:
return "PrintErr";
default:
- throw new IllegalStateException("Unexpected type " + type);
+ throw new IllegalStateException( "Unexpected type " + type );
}
}
}
- public static class Prompt extends Message {
+ public static class Prompt extends Message
+ {
final String projectId;
final String uid;
final String message;
final boolean password;
- public static Prompt read(DataInputStream input) throws IOException {
- String projectId = Message.readUTF(input);
- String uid = Message.readUTF(input);
- String message = Message.readUTF(input);
+ public static Prompt read( DataInputStream input ) throws IOException
+ {
+ String projectId = Message.readUTF( input );
+ String uid = Message.readUTF( input );
+ String message = Message.readUTF( input );
boolean password = input.readBoolean();
- return new Prompt(projectId, uid, message, password);
+ return new Prompt( projectId, uid, message, password );
}
- public Prompt(String projectId, String uid, String message, boolean password) {
- super(PROMPT);
+ public Prompt( String projectId, String uid, String message, boolean password )
+ {
+ super( PROMPT );
this.projectId = projectId;
this.uid = uid;
this.message = message;
this.password = password;
}
- public String getProjectId() {
+ public String getProjectId()
+ {
return projectId;
}
- public String getUid() {
+ public String getUid()
+ {
return uid;
}
- public String getMessage() {
+ public String getMessage()
+ {
return message;
}
- public boolean isPassword() {
+ public boolean isPassword()
+ {
return password;
}
@Override
- public String toString() {
+ public String toString()
+ {
return "Prompt{" +
"projectId='" + projectId + '\'' +
", uid='" + uid + '\'' +
@@ -773,54 +905,63 @@ public abstract class Message {
}
@Override
- public void write(DataOutputStream output) throws IOException {
- super.write(output);
- writeUTF(output, projectId);
- writeUTF(output, uid);
- writeUTF(output, message);
- output.writeBoolean(password);
+ public void write( DataOutputStream output ) throws IOException
+ {
+ super.write( output );
+ writeUTF( output, projectId );
+ writeUTF( output, uid );
+ writeUTF( output, message );
+ output.writeBoolean( password );
}
- public PromptResponse response(String message) {
- return new PromptResponse(projectId, uid, message);
+ public PromptResponse response( String message )
+ {
+ return new PromptResponse( projectId, uid, message );
}
}
- public static class PromptResponse extends Message {
+ public static class PromptResponse extends Message
+ {
final String projectId;
final String uid;
final String message;
- public static Message read(DataInputStream input) throws IOException {
- String projectId = Message.readUTF(input);
- String uid = Message.readUTF(input);
- String message = Message.readUTF(input);
- return new PromptResponse(projectId, uid, message);
+ public static Message read( DataInputStream input ) throws IOException
+ {
+ String projectId = Message.readUTF( input );
+ String uid = Message.readUTF( input );
+ String message = Message.readUTF( input );
+ return new PromptResponse( projectId, uid, message );
}
- private PromptResponse(String projectId, String uid, String message) {
- super(PROMPT_RESPONSE);
+ private PromptResponse( String projectId, String uid, String message )
+ {
+ super( PROMPT_RESPONSE );
this.projectId = projectId;
this.uid = uid;
this.message = message;
}
- public String getProjectId() {
+ public String getProjectId()
+ {
return projectId;
}
- public String getUid() {
+ public String getUid()
+ {
return uid;
}
- public String getMessage() {
+ public String getMessage()
+ {
return message;
}
@Override
- public String toString() {
+ public String toString()
+ {
return "PromptResponse{" +
"projectId='" + projectId + '\'' +
", uid='" + uid + '\'' +
@@ -829,41 +970,48 @@ public abstract class Message {
}
@Override
- public void write(DataOutputStream output) throws IOException {
- super.write(output);
- writeUTF(output, projectId);
- writeUTF(output, uid);
- writeUTF(output, message);
+ public void write( DataOutputStream output ) throws IOException
+ {
+ super.write( output );
+ writeUTF( output, projectId );
+ writeUTF( output, uid );
+ writeUTF( output, message );
}
}
- public static class ExecutionFailureEvent extends Message {
+ public static class ExecutionFailureEvent extends Message
+ {
final String projectId;
final boolean halted;
final String exception;
- private ExecutionFailureEvent(String projectId, boolean halted, String exception) {
- super(EXECUTION_FAILURE);
+ private ExecutionFailureEvent( String projectId, boolean halted, String exception )
+ {
+ super( EXECUTION_FAILURE );
this.projectId = projectId;
this.halted = halted;
this.exception = exception;
}
- public String getProjectId() {
+ public String getProjectId()
+ {
return projectId;
}
- public boolean isHalted() {
+ public boolean isHalted()
+ {
return halted;
}
- public String getException() {
+ public String getException()
+ {
return exception;
}
@Override
- public String toString() {
+ public String toString()
+ {
return "ExecutionFailure{" +
"projectId='" + projectId + '\'' +
", halted=" + halted +
@@ -872,22 +1020,25 @@ public abstract class Message {
}
@Override
- public void write(DataOutputStream output) throws IOException {
- super.write(output);
- writeUTF(output, projectId);
- output.writeBoolean(halted);
- writeUTF(output, exception);
+ public void write( DataOutputStream output ) throws IOException
+ {
+ super.write( output );
+ writeUTF( output, projectId );
+ output.writeBoolean( halted );
+ writeUTF( output, exception );
}
- public static ExecutionFailureEvent read(DataInputStream input) throws IOException {
- String projectId = readUTF(input);
+ public static ExecutionFailureEvent read( DataInputStream input ) throws IOException
+ {
+ String projectId = readUTF( input );
boolean halted = input.readBoolean();
- String exception = readUTF(input);
- return new ExecutionFailureEvent(projectId, halted, exception);
+ String exception = readUTF( input );
+ return new ExecutionFailureEvent( projectId, halted, exception );
}
}
- public static class TransferEvent extends Message {
+ public static class TransferEvent extends Message
+ {
public static final int INITIATED = 0;
public static final int STARTED = 1;
@@ -909,11 +1060,12 @@ public abstract class Message {
final long transferredBytes;
final String exception;
- private TransferEvent(int type, String projectId, int requestType,
+ private TransferEvent( int type, String projectId, int requestType,
String repositoryId, String repositoryUrl,
String resourceName, long contentLength, long transferredBytes,
- String exception) {
- super(type);
+ String exception )
+ {
+ super( type );
this.projectId = projectId;
this.requestType = requestType;
this.repositoryId = repositoryId;
@@ -924,40 +1076,49 @@ public abstract class Message {
this.exception = exception;
}
- public String getProjectId() {
+ public String getProjectId()
+ {
return projectId;
}
- public int getRequestType() {
+ public int getRequestType()
+ {
return requestType;
}
- public String getRepositoryId() {
+ public String getRepositoryId()
+ {
return repositoryId;
}
- public String getRepositoryUrl() {
+ public String getRepositoryUrl()
+ {
return repositoryUrl;
}
- public String getResourceName() {
+ public String getResourceName()
+ {
return resourceName;
}
- public long getContentLength() {
+ public long getContentLength()
+ {
return contentLength;
}
- public long getTransferredBytes() {
+ public long getTransferredBytes()
+ {
return transferredBytes;
}
- public String getException() {
+ public String getException()
+ {
return exception;
}
@Override
- public String toString() {
+ public String toString()
+ {
return mnemonic() + "{" +
"projectId=" + projectId +
", requestType=" + requestType +
@@ -970,8 +1131,10 @@ public abstract class Message {
'}';
}
- private String mnemonic() {
- switch (type) {
+ private String mnemonic()
+ {
+ switch ( type )
+ {
case TRANSFER_INITIATED:
return "TransferInitiated";
case TRANSFER_STARTED:
@@ -985,96 +1148,112 @@ public abstract class Message {
case TRANSFER_FAILED:
return "TransferFailed";
default:
- throw new IllegalStateException("Unexpected type " + type);
+ throw new IllegalStateException( "Unexpected type " + type );
}
}
@Override
- public void write(DataOutputStream output) throws IOException {
- super.write(output);
- writeUTF(output, projectId);
- output.writeByte(requestType);
- writeUTF(output, repositoryId);
- writeUTF(output, repositoryUrl);
- writeUTF(output, resourceName);
- output.writeLong(contentLength);
- output.writeLong(transferredBytes);
- writeUTF(output, exception);
- }
-
- public static TransferEvent read(int type, DataInputStream input) throws IOException {
- String projectId = readUTF(input);
+ public void write( DataOutputStream output ) throws IOException
+ {
+ super.write( output );
+ writeUTF( output, projectId );
+ output.writeByte( requestType );
+ writeUTF( output, repositoryId );
+ writeUTF( output, repositoryUrl );
+ writeUTF( output, resourceName );
+ output.writeLong( contentLength );
+ output.writeLong( transferredBytes );
+ writeUTF( output, exception );
+ }
+
+ public static TransferEvent read( int type, DataInputStream input ) throws IOException
+ {
+ String projectId = readUTF( input );
int request = input.readByte();
- String repositoryId = readUTF(input);
- String repositoryUrl = readUTF(input);
- String resourceName = readUTF(input);
+ String repositoryId = readUTF( input );
+ String repositoryUrl = readUTF( input );
+ String resourceName = readUTF( input );
long contentLength = input.readLong();
long transferredBytes = input.readLong();
- String exception = readUTF(input);
- return new TransferEvent(type, projectId, request, repositoryId, repositoryUrl, resourceName,
- contentLength, transferredBytes, exception);
+ String exception = readUTF( input );
+ return new TransferEvent( type, projectId, request, repositoryId, repositoryUrl, resourceName,
+ contentLength, transferredBytes, exception );
}
}
- public int getType() {
+ public int getType()
+ {
return type;
}
- public static StringMessage buildStatus(String payload) {
- return new StringMessage(BUILD_STATUS, payload);
+ public static StringMessage buildStatus( String payload )
+ {
+ return new StringMessage( BUILD_STATUS, payload );
}
- public static StringMessage display(String message) {
- return new StringMessage(DISPLAY, message);
+ public static StringMessage display( String message )
+ {
+ return new StringMessage( DISPLAY, message );
}
- public static StringMessage out(String message) {
- return new StringMessage(PRINT_OUT, message);
+ public static StringMessage out( String message )
+ {
+ return new StringMessage( PRINT_OUT, message );
}
- public static StringMessage err(String message) {
- return new StringMessage(PRINT_ERR, message);
+ public static StringMessage err( String message )
+ {
+ return new StringMessage( PRINT_ERR, message );
}
- public static StringMessage log(String message) {
- return new StringMessage(BUILD_LOG_MESSAGE, message);
+ public static StringMessage log( String message )
+ {
+ return new StringMessage( BUILD_LOG_MESSAGE, message );
}
- public static ProjectEvent log(String projectId, String message) {
- return new ProjectEvent(PROJECT_LOG_MESSAGE, projectId, message);
+ public static ProjectEvent log( String projectId, String message )
+ {
+ return new ProjectEvent( PROJECT_LOG_MESSAGE, projectId, message );
}
- public static StringMessage keyboardInput(char keyStroke) {
- return new StringMessage(KEYBOARD_INPUT, String.valueOf(keyStroke));
+ public static StringMessage keyboardInput( char keyStroke )
+ {
+ return new StringMessage( KEYBOARD_INPUT, String.valueOf( keyStroke ) );
}
- public static StringMessage projectStarted(String projectId) {
- return new StringMessage(PROJECT_STARTED, projectId);
+ public static StringMessage projectStarted( String projectId )
+ {
+ return new StringMessage( PROJECT_STARTED, projectId );
}
- public static StringMessage projectStopped(String projectId) {
- return new StringMessage(PROJECT_STOPPED, projectId);
+ public static StringMessage projectStopped( String projectId )
+ {
+ return new StringMessage( PROJECT_STOPPED, projectId );
}
- public static ExecutionFailureEvent executionFailure(String projectId, boolean halted, String exception) {
- return new ExecutionFailureEvent(projectId, halted, exception);
+ public static ExecutionFailureEvent executionFailure( String projectId, boolean halted, String exception )
+ {
+ return new ExecutionFailureEvent( projectId, halted, exception );
}
- public static Message mojoStarted(String artifactId, String pluginGroupId, String pluginArtifactId,
- String pluginVersion, String mojo, String executionId) {
- return new MojoStartedEvent(artifactId, pluginGroupId, pluginArtifactId, pluginVersion, mojo, executionId);
+ public static Message mojoStarted( String artifactId, String pluginGroupId, String pluginArtifactId,
+ String pluginVersion, String mojo, String executionId )
+ {
+ return new MojoStartedEvent( artifactId, pluginGroupId, pluginArtifactId, pluginVersion, mojo, executionId );
}
- public static ProjectEvent display(String projectId, String message) {
- return new ProjectEvent(Message.DISPLAY, projectId, message);
+ public static ProjectEvent display( String projectId, String message )
+ {
+ return new ProjectEvent( Message.DISPLAY, projectId, message );
}
- public static TransferEvent transfer(String projectId, int transferEventType, int requestType,
+ public static TransferEvent transfer( String projectId, int transferEventType, int requestType,
String repositoryId, String repositoryUrl,
String resourceName, long contentLength, long transferredBytes,
- String exception) {
- return new TransferEvent(transferEventType, projectId, requestType,
- repositoryId, repositoryUrl, resourceName, contentLength, transferredBytes, exception);
+ String exception )
+ {
+ return new TransferEvent( transferEventType, projectId, requestType,
+ repositoryId, repositoryUrl, resourceName, contentLength, transferredBytes, exception );
}
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/OptionType.java b/common/src/main/java/org/mvndaemon/mvnd/common/OptionType.java
index cbf49ec..a033da5 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/OptionType.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/OptionType.java
@@ -22,7 +22,9 @@ import java.util.Properties;
import java.util.stream.Stream;
import org.mvndaemon.mvnd.common.Environment.DocumentedEnumEntry;
-public enum OptionType {
+public enum OptionType
+{
+
/**
* <code>true</code> or <code>false</code>; empty string is also interpreted as <code>true</code> - so
* <code>-Dmvnd.noBuffering</code> is equivalent to <code>-Dmvnd.noBuffering=true</code>
@@ -36,10 +38,13 @@ public enum OptionType {
* Examples: <code>7 days</code>, <code>7days</code>, <code>7d</code>, <code>100 milliseconds</code>,
* <code>100 millis</code>, <code>100ms</code>, <code>100</code>
*/
- DURATION {
+ DURATION
+ {
+
@Override
- public String normalize(String value) {
- return TimeUtils.printDuration(TimeUtils.toMilliSeconds(value));
+ public String normalize( String value )
+ {
+ return TimeUtils.printDuration( TimeUtils.toMilliSeconds( value ) );
}
},
/** A whole number */
@@ -56,22 +61,27 @@ public enum OptionType {
/** No value */
VOID;
- public String normalize(String value) {
+ public String normalize( String value )
+ {
return value;
}
- public static Stream<DocumentedEnumEntry<OptionType>> documentedEntries() {
+ public static Stream<DocumentedEnumEntry<OptionType>> documentedEntries()
+ {
Properties props = new Properties();
OptionType[] values = values();
final String cliOptionsPath = values[0].getClass().getSimpleName() + ".javadoc.properties";
- try (InputStream in = Environment.class.getResourceAsStream(cliOptionsPath)) {
- props.load(in);
- } catch (IOException e) {
- throw new RuntimeException("Could not read " + cliOptionsPath, e);
+ try ( InputStream in = Environment.class.getResourceAsStream( cliOptionsPath ) )
+ {
+ props.load( in );
+ }
+ catch ( IOException e )
+ {
+ throw new RuntimeException( "Could not read " + cliOptionsPath, e );
}
- return Stream.of(values)
- .filter(opt -> opt != VOID)
- .sorted(Comparator.comparing(OptionType::name))
- .map(env -> new DocumentedEnumEntry<>(env, props.getProperty(env.name())));
+ return Stream.of( values )
+ .filter( opt -> opt != VOID )
+ .sorted( Comparator.comparing( OptionType::name ) )
+ .map( env -> new DocumentedEnumEntry<>( env, props.getProperty( env.name() ) ) );
}
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/Os.java b/common/src/main/java/org/mvndaemon/mvnd/common/Os.java
index 6870163..b614371 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/Os.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/Os.java
@@ -17,59 +17,78 @@ package org.mvndaemon.mvnd.common;
import java.util.Locale;
-public enum Os {
- LINUX(true),
- MAC(true),
- WINDOWS(false) {
+public enum Os
+{
+
+ LINUX( true ),
+ MAC( true ),
+ WINDOWS( false )
+ {
+
private boolean cygwin;
{
- String pwd = System.getenv("PWD");
- cygwin = pwd != null && pwd.startsWith("/");
+ String pwd = System.getenv( "PWD" );
+ cygwin = pwd != null && pwd.startsWith( "/" );
}
@Override
- public boolean isCygwin() {
+ public boolean isCygwin()
+ {
return cygwin;
}
},
- UNKNOWN(false) {
+ UNKNOWN( false )
+ {
@Override
- public boolean isUnixLike() {
- throw new UnsupportedOperationException("Cannot tell isUnixLike() for an " + UNKNOWN.name() + " OS");
+ public boolean isUnixLike()
+ {
+ throw new UnsupportedOperationException( "Cannot tell isUnixLike() for an " + UNKNOWN.name() + " OS" );
}
};
private static final Os CURRENT;
- static {
- final String osName = System.getProperty("os.name").toLowerCase(Locale.ROOT);
- if (osName.startsWith("osx") || osName.startsWith("mac os x")) {
+ static
+ {
+ final String osName = System.getProperty( "os.name" ).toLowerCase( Locale.ROOT );
+ if ( osName.startsWith( "osx" ) || osName.startsWith( "mac os x" ) )
+ {
CURRENT = MAC;
- } else if (osName.contains("win")) {
+ }
+ else if ( osName.contains( "win" ) )
+ {
CURRENT = WINDOWS;
- } else if (osName.contains("linux")) {
+ }
+ else if ( osName.contains( "linux" ) )
+ {
CURRENT = LINUX;
- } else {
+ }
+ else
+ {
CURRENT = UNKNOWN;
}
}
private final boolean unixLike;
- public static Os current() {
+ public static Os current()
+ {
return CURRENT;
}
- Os(boolean unixLike) {
+ Os( boolean unixLike )
+ {
this.unixLike = unixLike;
}
- public boolean isUnixLike() {
+ public boolean isUnixLike()
+ {
return unixLike;
}
- public boolean isCygwin() {
+ public boolean isCygwin()
+ {
return false;
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/OsUtils.java b/common/src/main/java/org/mvndaemon/mvnd/common/OsUtils.java
index 369ba90..01e3688 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/OsUtils.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/OsUtils.java
@@ -29,89 +29,127 @@ import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class OsUtils {
+public class OsUtils
+{
- private static final Logger LOGGER = LoggerFactory.getLogger(OsUtils.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger( OsUtils.class );
private static final long KB = 1024;
private static final String UNITS = "Bkmgt";
- private OsUtils() {
+ private OsUtils()
+ {
}
- public static String bytesTohumanReadable(long bytes) {
+ public static String bytesTohumanReadable( long bytes )
+ {
int unit = 0;
- while (bytes >= KB && unit < UNITS.length() - 1) {
+ while ( bytes >= KB && unit < UNITS.length() - 1 )
+ {
bytes /= KB;
unit++;
}
- String kbString = String.valueOf(bytes);
- return new StringBuilder(kbString.length() + 1).append(kbString).append(UNITS.charAt(unit)).toString();
+ String kbString = String.valueOf( bytes );
+ return new StringBuilder( kbString.length() + 1 ).append( kbString ).append( UNITS.charAt( unit ) ).toString();
}
- public static String kbTohumanReadable(long kb) {
+ public static String kbTohumanReadable( long kb )
+ {
int unit = 1;
- while (kb >= KB && unit < UNITS.length() - 1) {
+ while ( kb >= KB && unit < UNITS.length() - 1 )
+ {
kb /= KB;
unit++;
}
- String kbString = String.valueOf(kb);
- return new StringBuilder(kbString.length() + 1).append(kbString).append(UNITS.charAt(unit)).toString();
+ String kbString = String.valueOf( kb );
+ return new StringBuilder( kbString.length() + 1 ).append( kbString ).append( UNITS.charAt( unit ) ).toString();
}
- public static long findProcessRssInKb(long pid) {
+ public static long findProcessRssInKb( long pid )
+ {
final Os os = Os.current();
- if (os.isUnixLike()) {
- String[] cmd = { "ps", "-o", "rss=", "-p", String.valueOf(pid) };
- final List<String> output = new ArrayList<String>(1);
- exec(cmd, output);
- if (output.size() == 1) {
- try {
- return Long.parseLong(output.get(0).trim());
- } catch (NumberFormatException e) {
- LOGGER.warn("Could not parse the output of " + Stream.of(cmd).collect(Collectors.joining(" "))
- + " as a long:\n"
- + output.stream().collect(Collectors.joining("\n")));
+ if ( os.isUnixLike() )
+ {
+ String[] cmd =
+ { "ps", "-o", "rss=", "-p", String.valueOf( pid )
+ };
+ final List<String> output = new ArrayList<String>( 1 );
+ exec( cmd, output );
+ if ( output.size() == 1 )
+ {
+ try
+ {
+ return Long.parseLong( output.get( 0 ).trim() );
}
- } else {
- LOGGER.warn("Unexpected output of " + Stream.of(cmd).collect(Collectors.joining(" ")) + ":\n"
- + output.stream().collect(Collectors.joining("\n")));
+ catch ( NumberFormatException e )
+ {
+ LOGGER.warn(
+ "Could not parse the output of " + Stream.of( cmd ).collect( Collectors.joining( " " ) )
+ + " as a long:\n"
+ + output.stream().collect( Collectors.joining( "\n" ) ) );
+ }
+ }
+ else
+ {
+ LOGGER.warn( "Unexpected output of " + Stream.of( cmd ).collect( Collectors.joining( " " ) ) + ":\n"
+ + output.stream().collect( Collectors.joining( "\n" ) ) );
}
return -1;
- } else if (os == Os.WINDOWS) {
- String[] cmd = { "wmic", "process", "where", "processid=" + pid, "get", "WorkingSetSize" };
- final List<String> output = new ArrayList<String>(1);
- exec(cmd, output);
- final List<String> nonEmptyLines = output.stream().filter(l -> !l.isEmpty()).collect(Collectors.toList());
- if (nonEmptyLines.size() >= 2) {
- try {
- return Long.parseLong(nonEmptyLines.get(1).trim()) / KB;
- } catch (NumberFormatException e) {
- LOGGER.warn("Could not parse the second line of " + Stream.of(cmd).collect(Collectors.joining(" "))
+ }
+ else if ( os == Os.WINDOWS )
+ {
+ String[] cmd =
+ { "wmic", "process", "where", "processid=" + pid, "get", "WorkingSetSize"
+ };
+ final List<String> output = new ArrayList<String>( 1 );
+ exec( cmd, output );
+ final List<String> nonEmptyLines = output.stream().filter( l -> !l.isEmpty() )
+ .collect( Collectors.toList() );
+ if ( nonEmptyLines.size() >= 2 )
+ {
+ try
+ {
+ return Long.parseLong( nonEmptyLines.get( 1 ).trim() ) / KB;
+ }
+ catch ( NumberFormatException e )
+ {
+ LOGGER.warn( "Could not parse the second line of "
+ + Stream.of( cmd ).collect( Collectors.joining( " " ) )
+ " output as a long:\n"
- + nonEmptyLines.stream().collect(Collectors.joining("\n")));
+ + nonEmptyLines.stream().collect( Collectors.joining( "\n" ) ) );
}
- } else {
- LOGGER.warn("Unexpected output of " + Stream.of(cmd).collect(Collectors.joining(" ")) + ":\n"
- + output.stream().collect(Collectors.joining("\n")));
+ }
+ else
+ {
+ LOGGER.warn( "Unexpected output of " + Stream.of( cmd ).collect( Collectors.joining( " " ) ) + ":\n"
+ + output.stream().collect( Collectors.joining( "\n" ) ) );
}
return -1;
- } else {
+ }
+ else
+ {
return -1;
}
}
- private static void exec(String[] cmd, final List<String> output) {
- final ProcessBuilder builder = new ProcessBuilder(cmd).redirectErrorStream(true);
- try (CommandProcess ps = new CommandProcess(builder.start(), output::add)) {
- final int exitCode = ps.waitFor(1000);
- if (exitCode != 0) {
- LOGGER.warn(Stream.of(cmd).collect(Collectors.joining(" ")) + " exited with " + exitCode + ":\n"
- + output.stream().collect(Collectors.joining("\n")));
+ private static void exec( String[] cmd, final List<String> output )
+ {
+ final ProcessBuilder builder = new ProcessBuilder( cmd ).redirectErrorStream( true );
+ try ( CommandProcess ps = new CommandProcess( builder.start(), output::add ) )
+ {
+ final int exitCode = ps.waitFor( 1000 );
+ if ( exitCode != 0 )
+ {
+ LOGGER.warn( Stream.of( cmd ).collect( Collectors.joining( " " ) ) + " exited with " + exitCode + ":\n"
+ + output.stream().collect( Collectors.joining( "\n" ) ) );
}
- } catch (IOException e) {
- LOGGER.warn("Could not execute " + Stream.of(cmd).collect(Collectors.joining(" ")));
- } catch (InterruptedException e) {
+ }
+ catch ( IOException e )
+ {
+ LOGGER.warn( "Could not execute " + Stream.of( cmd ).collect( Collectors.joining( " " ) ) );
+ }
+ catch ( InterruptedException e )
+ {
Thread.currentThread().interrupt();
}
}
@@ -120,41 +158,54 @@ public class OsUtils {
* A simple wrapper over {@link Process} that manages its destroying and offers Java 8-like
* {@link #waitFor(long, TimeUnit, String[])} with timeout.
*/
- public static class CommandProcess implements AutoCloseable {
+ public static class CommandProcess implements AutoCloseable
+ {
+
public static final int TIMEOUT_EXIT_CODE = Integer.MIN_VALUE + 42;
/**
* The usual friend of {@link Process#getInputStream()} / {@link Process#getErrorStream()}.
*/
- static class StreamGobbler extends Thread {
+ static class StreamGobbler extends Thread
+ {
+
private volatile boolean cancelled;
private IOException exception;
private final InputStream in;
private final Consumer<String> out;
- private StreamGobbler(InputStream in, Consumer<String> out) {
+ private StreamGobbler( InputStream in, Consumer<String> out )
+ {
this.in = in;
this.out = out;
}
- public void assertSuccess() throws IOException {
- if (exception != null) {
+ public void assertSuccess() throws IOException
+ {
+ if ( exception != null )
+ {
throw exception;
}
}
- public void cancel() {
+ public void cancel()
+ {
this.cancelled = true;
}
@Override
- public void run() {
- try (BufferedReader r = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
+ public void run()
+ {
+ try ( BufferedReader r = new BufferedReader( new InputStreamReader( in, StandardCharsets.UTF_8 ) ) )
+ {
String line;
- while (!cancelled && (line = r.readLine()) != null) {
- out.accept(line);
+ while ( !cancelled && ( line = r.readLine() ) != null )
+ {
+ out.accept( line );
}
- } catch (IOException e) {
+ }
+ catch ( IOException e )
+ {
exception = e;
}
}
@@ -164,36 +215,45 @@ public class OsUtils {
private final Thread shutDownHook;
private final StreamGobbler stdOut;
- public CommandProcess(Process process, Consumer<String> outputConsumer) {
+ public CommandProcess( Process process, Consumer<String> outputConsumer )
+ {
super();
this.process = process;
- this.stdOut = new StreamGobbler(process.getInputStream(), outputConsumer);
+ this.stdOut = new StreamGobbler( process.getInputStream(), outputConsumer );
stdOut.start();
- this.shutDownHook = new Thread(new Runnable() {
+ this.shutDownHook = new Thread( new Runnable()
+ {
+
@Override
- public void run() {
+ public void run()
+ {
stdOut.cancel();
CommandProcess.this.process.destroy();
}
- });
- Runtime.getRuntime().addShutdownHook(shutDownHook);
+ } );
+ Runtime.getRuntime().addShutdownHook( shutDownHook );
}
@Override
- public void close() {
+ public void close()
+ {
process.destroy();
}
- public int waitFor(long timeoutMs) throws InterruptedException, IOException {
+ public int waitFor( long timeoutMs ) throws InterruptedException, IOException
+ {
final long deadline = System.currentTimeMillis() + timeoutMs;
- final boolean timeouted = !process.waitFor(timeoutMs, TimeUnit.MILLISECONDS);
- timeoutMs = Math.max(0, deadline - System.currentTimeMillis());
- stdOut.join(timeoutMs);
+ final boolean timeouted = !process.waitFor( timeoutMs, TimeUnit.MILLISECONDS );
+ timeoutMs = Math.max( 0, deadline - System.currentTimeMillis() );
+ stdOut.join( timeoutMs );
stdOut.assertSuccess();
- try {
- Runtime.getRuntime().removeShutdownHook(shutDownHook);
- } catch (Exception ignored) {
+ try
+ {
+ Runtime.getRuntime().removeShutdownHook( shutDownHook );
+ }
+ catch ( Exception ignored )
+ {
}
final int exitCode = timeouted ? TIMEOUT_EXIT_CODE : process.exitValue();
return exitCode;
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/ProcessHelper.java b/common/src/main/java/org/mvndaemon/mvnd/common/ProcessHelper.java
index 17acbdb..05614e2 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/ProcessHelper.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/ProcessHelper.java
@@ -15,9 +15,11 @@
*/
package org.mvndaemon.mvnd.common;
-public class ProcessHelper {
+public class ProcessHelper
+{
- public static void killChildrenProcesses() {
+ public static void killChildrenProcesses()
+ {
}
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/SocketFamily.java b/common/src/main/java/org/mvndaemon/mvnd/common/SocketFamily.java
index 1a8cb9e..c016a89 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/SocketFamily.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/SocketFamily.java
@@ -26,12 +26,16 @@ import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Locale;
-public enum SocketFamily {
+public enum SocketFamily
+{
+
inet,
unix;
- public SocketChannel openSocket() throws IOException {
- switch (this) {
+ public SocketChannel openSocket() throws IOException
+ {
+ switch ( this )
+ {
case inet:
return SocketChannel.open();
case unix:
@@ -41,10 +45,12 @@ public enum SocketFamily {
}
}
- public ServerSocketChannel openServerSocket() throws IOException {
- switch (this) {
+ public ServerSocketChannel openServerSocket() throws IOException
+ {
+ switch ( this )
+ {
case inet:
- return ServerSocketChannel.open().bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
+ return ServerSocketChannel.open().bind( new InetSocketAddress( InetAddress.getLoopbackAddress(), 0 ), 0 );
case unix:
return SocketHelper.openUnixServerSocket();
default:
@@ -52,89 +58,123 @@ public enum SocketFamily {
}
}
- private StandardProtocolFamily getStandardProtocolFamily() {
- return StandardProtocolFamily.valueOf(name().toUpperCase(Locale.ROOT));
+ private StandardProtocolFamily getStandardProtocolFamily()
+ {
+ return StandardProtocolFamily.valueOf( name().toUpperCase( Locale.ROOT ) );
}
- private SocketAddress getLoopbackAddress() {
- if (this == inet) {
- return new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
- } else {
+ private SocketAddress getLoopbackAddress()
+ {
+ if ( this == inet )
+ {
+ return new InetSocketAddress( InetAddress.getLoopbackAddress(), 0 );
+ }
+ else
+ {
return null;
}
}
- public static SocketAddress fromString(String str) {
- if (str.startsWith("inet:")) {
- String s = str.substring("inet:".length());
- int ic = s.lastIndexOf(':');
- String ia = s.substring(0, ic);
- int is = ia.indexOf('/');
- String h = ia.substring(0, is);
- String a = ia.substring(is + 1);
- String p = s.substring(ic + 1);
+ public static SocketAddress fromString( String str )
+ {
+ if ( str.startsWith( "inet:" ) )
+ {
+ String s = str.substring( "inet:".length() );
+ int ic = s.lastIndexOf( ':' );
+ String ia = s.substring( 0, ic );
+ int is = ia.indexOf( '/' );
+ String h = ia.substring( 0, is );
+ String a = ia.substring( is + 1 );
+ String p = s.substring( ic + 1 );
InetAddress addr;
- if ("<unresolved>".equals(a)) {
- return InetSocketAddress.createUnresolved(h, Integer.parseInt(p));
- } else {
- if (a.indexOf('.') > 0) {
- String[] as = a.split("\\.");
- if (as.length != 4) {
- throw new IllegalArgumentException("Unsupported socket address: '" + str + "'");
+ if ( "<unresolved>".equals( a ) )
+ {
+ return InetSocketAddress.createUnresolved( h, Integer.parseInt( p ) );
+ }
+ else
+ {
+ if ( a.indexOf( '.' ) > 0 )
+ {
+ String[] as = a.split( "\\." );
+ if ( as.length != 4 )
+ {
+ throw new IllegalArgumentException( "Unsupported socket address: '" + str + "'" );
}
byte[] ab = new byte[4];
- for (int i = 0; i < 4; i++) {
- ab[i] = (byte) Integer.parseInt(as[i]);
+ for ( int i = 0; i < 4; i++ )
+ {
+ ab[i] = ( byte ) Integer.parseInt( as[i] );
}
- try {
- addr = InetAddress.getByAddress(h.isEmpty() ? null : h, ab);
- } catch (UnknownHostException e) {
- throw new IllegalArgumentException("Unsupported address: " + str, e);
+ try
+ {
+ addr = InetAddress.getByAddress( h.isEmpty() ? null : h, ab );
}
- } else {
- throw new IllegalArgumentException("Unsupported address: " + str);
+ catch ( UnknownHostException e )
+ {
+ throw new IllegalArgumentException( "Unsupported address: " + str, e );
+ }
+ }
+ else
+ {
+ throw new IllegalArgumentException( "Unsupported address: " + str );
}
- return new InetSocketAddress(addr, Integer.parseInt(p));
+ return new InetSocketAddress( addr, Integer.parseInt( p ) );
}
- } else if (str.startsWith("unix:")) {
- return SocketHelper.unixSocketAddressOf(str.substring("unix:".length()));
- } else {
- throw new IllegalArgumentException("Unsupported socket address: '" + str + "'");
+ }
+ else if ( str.startsWith( "unix:" ) )
+ {
+ return SocketHelper.unixSocketAddressOf( str.substring( "unix:".length() ) );
+ }
+ else
+ {
+ throw new IllegalArgumentException( "Unsupported socket address: '" + str + "'" );
}
}
- public static String toString(SocketAddress address) {
- switch (familyOf(address)) {
+ public static String toString( SocketAddress address )
+ {
+ switch ( familyOf( address ) )
+ {
case inet:
- InetSocketAddress isa = (InetSocketAddress) address;
+ InetSocketAddress isa = ( InetSocketAddress ) address;
String host = isa.getHostString();
InetAddress addr = isa.getAddress();
int port = isa.getPort();
String formatted;
- if (addr == null) {
+ if ( addr == null )
+ {
formatted = host + "/<unresolved>";
- } else {
+ }
+ else
+ {
formatted = addr.toString();
- if (addr instanceof Inet6Address) {
- int i = formatted.lastIndexOf("/");
- formatted = formatted.substring(0, i + 1) + "[" + formatted.substring(i + 1) + "]";
+ if ( addr instanceof Inet6Address )
+ {
+ int i = formatted.lastIndexOf( "/" );
+ formatted = formatted.substring( 0, i + 1 ) + "[" + formatted.substring( i + 1 ) + "]";
}
}
return "inet:" + formatted + ":" + port;
case unix:
return "unix:" + address;
default:
- throw new IllegalArgumentException("Unsupported socket address: '" + address + "'");
+ throw new IllegalArgumentException( "Unsupported socket address: '" + address + "'" );
}
}
- public static SocketFamily familyOf(SocketAddress address) {
- if (address instanceof InetSocketAddress) {
+ public static SocketFamily familyOf( SocketAddress address )
+ {
+ if ( address instanceof InetSocketAddress )
+ {
return SocketFamily.inet;
- } else if ("java.net.UnixDomainSocketAddress".equals(address.getClass().getName())) {
+ }
+ else if ( "java.net.UnixDomainSocketAddress".equals( address.getClass().getName() ) )
+ {
return SocketFamily.unix;
- } else {
- throw new IllegalArgumentException("Unsupported socket address '" + address + "'");
+ }
+ else
+ {
+ throw new IllegalArgumentException( "Unsupported socket address '" + address + "'" );
}
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/SocketHelper.java b/common/src/main/java/org/mvndaemon/mvnd/common/SocketHelper.java
index 765777b..22d2d48 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/SocketHelper.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/SocketHelper.java
@@ -20,17 +20,21 @@ import java.net.SocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
-public class SocketHelper {
+public class SocketHelper
+{
- public static SocketChannel openUnixSocket() throws IOException {
- throw new UnsupportedOperationException("Unix sockets are supported only on JDK >= 16");
+ public static SocketChannel openUnixSocket() throws IOException
+ {
+ throw new UnsupportedOperationException( "Unix sockets are supported only on JDK >= 16" );
}
- public static ServerSocketChannel openUnixServerSocket() throws IOException {
- throw new UnsupportedOperationException("Unix sockets are supported only on JDK >= 16");
+ public static ServerSocketChannel openUnixServerSocket() throws IOException
+ {
+ throw new UnsupportedOperationException( "Unix sockets are supported only on JDK >= 16" );
}
- public static SocketAddress unixSocketAddressOf(String s) {
- throw new UnsupportedOperationException("Unix sockets are supported only on JDK >= 16");
+ public static SocketAddress unixSocketAddressOf( String s )
+ {
+ throw new UnsupportedOperationException( "Unix sockets are supported only on JDK >= 16" );
}
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/TimeUtils.java b/common/src/main/java/org/mvndaemon/mvnd/common/TimeUtils.java
index d5abefd..bef531c 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/TimeUtils.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/TimeUtils.java
@@ -23,13 +23,14 @@ import java.util.regex.Pattern;
/**
* Time utils.
*/
-public final class TimeUtils {
+public final class TimeUtils
+{
private static final int ONE_UNIT = 1;
- public static final long DAYS_MILLIS = TimeUnit.DAYS.toMillis(ONE_UNIT);
- public static final long HOURS_MILLIS = TimeUnit.HOURS.toMillis(ONE_UNIT);
- public static final long MINUTES_MILLIS = TimeUnit.MINUTES.toMillis(ONE_UNIT);
- public static final long SECONDS_MILLIS = TimeUnit.SECONDS.toMillis(ONE_UNIT);
+ public static final long DAYS_MILLIS = TimeUnit.DAYS.toMillis( ONE_UNIT );
+ public static final long HOURS_MILLIS = TimeUnit.HOURS.toMillis( ONE_UNIT );
+ public static final long MINUTES_MILLIS = TimeUnit.MINUTES.toMillis( ONE_UNIT );
+ public static final long SECONDS_MILLIS = TimeUnit.SECONDS.toMillis( ONE_UNIT );
private static final Pattern DURATION_PATTERN = Pattern.compile(
"(?<n>-?\\d+)" +
@@ -41,17 +42,20 @@ public final class TimeUtils {
"((?<s>\\d+(\\.\\d+)?)\\s*s(ec(ond(s)?)?)?)?" + "\\s*" +
"((?<l>\\d+(\\.\\d+)?)\\s*m(illi)?s(ec(ond)?(s)?)?)?" +
")",
- Pattern.CASE_INSENSITIVE);
+ Pattern.CASE_INSENSITIVE );
- private TimeUtils() {
+ private TimeUtils()
+ {
}
- public static boolean isPositive(Duration dur) {
+ public static boolean isPositive( Duration dur )
+ {
return dur.getSeconds() > 0 || dur.getNano() != 0;
}
- public static String printDuration(Duration uptime) {
- return printDuration(uptime.toMillis());
+ public static String printDuration( Duration uptime )
+ {
+ return printDuration( uptime.toMillis() );
}
/**
@@ -65,56 +69,69 @@ public final class TimeUtils {
* @param millis time in milliseconds
* @return time in string
*/
- public static String printDuration(long millis) {
- if (millis < 0) {
- return Long.toString(millis);
+ public static String printDuration( long millis )
+ {
+ if ( millis < 0 )
+ {
+ return Long.toString( millis );
}
final StringBuilder sb = new StringBuilder();
- if (millis >= DAYS_MILLIS) {
- sb.append(millis / DAYS_MILLIS).append("d");
+ if ( millis >= DAYS_MILLIS )
+ {
+ sb.append( millis / DAYS_MILLIS ).append( "d" );
millis %= DAYS_MILLIS;
}
- if (millis >= HOURS_MILLIS) {
- sb.append(millis / HOURS_MILLIS).append("h");
+ if ( millis >= HOURS_MILLIS )
+ {
+ sb.append( millis / HOURS_MILLIS ).append( "h" );
millis %= HOURS_MILLIS;
}
- if (millis >= MINUTES_MILLIS) {
- sb.append(millis / MINUTES_MILLIS).append("m");
+ if ( millis >= MINUTES_MILLIS )
+ {
+ sb.append( millis / MINUTES_MILLIS ).append( "m" );
millis %= MINUTES_MILLIS;
}
- if (millis >= SECONDS_MILLIS) {
- sb.append(millis / SECONDS_MILLIS).append("s");
+ if ( millis >= SECONDS_MILLIS )
+ {
+ sb.append( millis / SECONDS_MILLIS ).append( "s" );
millis %= SECONDS_MILLIS;
}
- if (millis >= ONE_UNIT || sb.length() == 0) {
- sb.append(millis / ONE_UNIT).append("ms");
+ if ( millis >= ONE_UNIT || sb.length() == 0 )
+ {
+ sb.append( millis / ONE_UNIT ).append( "ms" );
}
return sb.toString();
}
- public static Duration toDuration(String source) throws IllegalArgumentException {
- return Duration.ofMillis(toMilliSeconds(source));
+ public static Duration toDuration( String source ) throws IllegalArgumentException
+ {
+ return Duration.ofMillis( toMilliSeconds( source ) );
}
- public static long toMilliSeconds(String source) throws IllegalArgumentException {
- Matcher matcher = DURATION_PATTERN.matcher(source);
- if (!matcher.matches()) {
- throw new IllegalArgumentException("Unable to parse duration: '" + source + "'");
+ public static long toMilliSeconds( String source ) throws IllegalArgumentException
+ {
+ Matcher matcher = DURATION_PATTERN.matcher( source );
+ if ( !matcher.matches() )
+ {
+ throw new IllegalArgumentException( "Unable to parse duration: '" + source + "'" );
}
- String n = matcher.group("n");
- if (n != null) {
- return Long.parseLong(n);
- } else {
- String d = matcher.group("d");
- String h = matcher.group("h");
- String m = matcher.group("m");
- String s = matcher.group("s");
- String l = matcher.group("l");
- return (d != null ? TimeUnit.DAYS.toMillis(Long.parseLong(d)) : 0)
- + (h != null ? TimeUnit.HOURS.toMillis(Long.parseLong(h)) : 0)
- + (m != null ? TimeUnit.MINUTES.toMillis(Long.parseLong(m)) : 0)
- + (s != null ? TimeUnit.SECONDS.toMillis(Long.parseLong(s)) : 0)
- + (l != null ? TimeUnit.MILLISECONDS.toMillis(Long.parseLong(l)) : 0);
+ String n = matcher.group( "n" );
+ if ( n != null )
+ {
+ return Long.parseLong( n );
+ }
+ else
+ {
+ String d = matcher.group( "d" );
+ String h = matcher.group( "h" );
+ String m = matcher.group( "m" );
+ String s = matcher.group( "s" );
+ String l = matcher.group( "l" );
+ return ( d != null ? TimeUnit.DAYS.toMillis( Long.parseLong( d ) ) : 0 )
+ + ( h != null ? TimeUnit.HOURS.toMillis( Long.parseLong( h ) ) : 0 )
+ + ( m != null ? TimeUnit.MINUTES.toMillis( Long.parseLong( m ) ) : 0 )
+ + ( s != null ? TimeUnit.SECONDS.toMillis( Long.parseLong( s ) ) : 0 )
+ + ( l != null ? TimeUnit.MILLISECONDS.toMillis( Long.parseLong( l ) ) : 0 );
}
}
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/logging/ClientOutput.java b/common/src/main/java/org/mvndaemon/mvnd/common/logging/ClientOutput.java
index 9d55552..4382dd2 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/logging/ClientOutput.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/logging/ClientOutput.java
@@ -22,17 +22,18 @@ import org.mvndaemon.mvnd.common.Message;
/**
* A sink for various kinds of events sent by the daemon.
*/
-public interface ClientOutput extends AutoCloseable {
+public interface ClientOutput extends AutoCloseable
+{
- void setDaemonId(String daemonId);
+ void setDaemonId( String daemonId );
- void setDaemonDispatch(Consumer<Message> sink);
+ void setDaemonDispatch( Consumer<Message> sink );
- void setDaemonReceive(Consumer<Message> sink);
+ void setDaemonReceive( Consumer<Message> sink );
- void accept(Message message);
+ void accept( Message message );
- void accept(List<Message> messages);
+ void accept( List<Message> messages );
void describeTerminal();
diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/logging/TerminalOutput.java b/common/src/main/java/org/mvndaemon/mvnd/common/logging/TerminalOutput.java
index 1f842e6..b8e9188 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/logging/TerminalOutput.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/logging/TerminalOutput.java
@@ -57,7 +57,8 @@ import org.mvndaemon.mvnd.common.OsUtils;
/**
* A terminal {@link ClientOutput} based on JLine.
*/
-public class TerminalOutput implements ClientOutput {
+public class TerminalOutput implements ClientOutput
+{
/**
* The '+' key is used to increase the number of lines displayed per project.
@@ -88,8 +89,8 @@ public class TerminalOutput implements ClientOutput {
*/
public static final int KEY_CTRL_M = 'M' & 0x1f;
- private static final AttributedStyle GREEN_FOREGROUND = new AttributedStyle().foreground(AttributedStyle.GREEN);
- private static final AttributedStyle CYAN_FOREGROUND = new AttributedStyle().foreground(AttributedStyle.CYAN);
+ private static final AttributedStyle GREEN_FOREGROUND = new AttributedStyle().foreground( AttributedStyle.GREEN );
+ private static final AttributedStyle CYAN_FOREGROUND = new AttributedStyle().foreground( AttributedStyle.CYAN );
private final Terminal terminal;
private final Terminal.SignalHandler previousIntHandler;
@@ -136,270 +137,349 @@ public class TerminalOutput implements ClientOutput {
* {@link Project} is owned by the display loop thread and is accessed only from there. Therefore it does not need
* to be immutable.
*/
- static class Project {
+ static class Project
+ {
+
final String id;
MojoStartedEvent runningExecution;
final List<String> log = new ArrayList<>();
- public Project(String id) {
+ public Project( String id )
+ {
this.id = id;
}
}
- public TerminalOutput(boolean noBuffering, int rollingWindowSize, Path logFile) throws IOException {
+ public TerminalOutput( boolean noBuffering, int rollingWindowSize, Path logFile ) throws IOException
+ {
this.start = System.currentTimeMillis();
TerminalBuilder builder = TerminalBuilder.builder();
- boolean outRedirected = CLibrary.isatty(1) == 0;
- if (outRedirected) {
- builder.dumb(true);
+ boolean outRedirected = CLibrary.isatty( 1 ) == 0;
+ if ( outRedirected )
+ {
+ builder.dumb( true );
}
this.terminal = builder.build();
- this.dumb = terminal.getType().startsWith("dumb");
+ this.dumb = terminal.getType().startsWith( "dumb" );
this.noBuffering = noBuffering;
this.linesPerProject = rollingWindowSize;
terminal.enterRawMode();
Thread mainThread = Thread.currentThread();
- daemonDispatch = m -> {
- if (m == Message.BareMessage.CANCEL_BUILD_SINGLETON) {
+ daemonDispatch = m ->
+ {
+ if ( m == Message.BareMessage.CANCEL_BUILD_SINGLETON )
+ {
mainThread.interrupt();
}
};
- this.previousIntHandler = terminal.handle(Terminal.Signal.INT,
- sig -> daemonDispatch.accept(Message.BareMessage.CANCEL_BUILD_SINGLETON));
- this.display = new Display(terminal, false);
- this.log = logFile == null ? new MessageCollector() : new FileLog(logFile);
- if (!dumb) {
- final Thread r = new Thread(this::readInputLoop);
- r.setDaemon(true);
+ this.previousIntHandler = terminal.handle( Terminal.Signal.INT,
+ sig -> daemonDispatch.accept( Message.BareMessage.CANCEL_BUILD_SINGLETON ) );
+ this.display = new Display( terminal, false );
+ this.log = logFile == null ? new MessageCollector() : new FileLog( logFile );
+ if ( !dumb )
+ {
+ final Thread r = new Thread( this::readInputLoop );
+ r.setDaemon( true );
r.start();
this.reader = r;
- } else {
+ }
+ else
+ {
this.reader = null;
}
}
@Override
- public void setDaemonId(String daemonId) {
+ public void setDaemonId( String daemonId )
+ {
this.daemonId = daemonId;
}
@Override
- public void setDaemonDispatch(Consumer<Message> daemonDispatch) {
+ public void setDaemonDispatch( Consumer<Message> daemonDispatch )
+ {
this.daemonDispatch = daemonDispatch;
}
@Override
- public void setDaemonReceive(Consumer<Message> daemonReceive) {
+ public void setDaemonReceive( Consumer<Message> daemonReceive )
+ {
this.daemonReceive = daemonReceive;
}
@Override
- public void accept(Message entry) {
- assert "main".equals(Thread.currentThread().getName());
- if (doAccept(entry)) {
+ public void accept( Message entry )
+ {
+ assert "main".equals( Thread.currentThread().getName() );
+ if ( doAccept( entry ) )
+ {
update();
}
}
@Override
- public void accept(List<Message> entries) {
- assert "main".equals(Thread.currentThread().getName());
- for (Message entry : entries) {
- if (!doAccept(entry)) {
+ public void accept( List<Message> entries )
+ {
+ assert "main".equals( Thread.currentThread().getName() );
+ for ( Message entry : entries )
+ {
+ if ( !doAccept( entry ) )
+ {
return;
}
}
update();
}
- private boolean doAccept(Message entry) {
- switch (entry.getType()) {
- case Message.BUILD_STARTED: {
- BuildStarted bs = (BuildStarted) entry;
+ private boolean doAccept( Message entry )
+ {
+ switch ( entry.getType() )
+ {
+ case Message.BUILD_STARTED:
+ {
+ BuildStarted bs = ( BuildStarted ) entry;
this.name = bs.getProjectId();
this.totalProjects = bs.getProjectCount();
- final int totalProjectsDigits = (int) (Math.log10(totalProjects) + 1);
+ final int totalProjectsDigits = ( int ) ( Math.log10( totalProjects ) + 1 );
this.projectsDoneFomat = "%" + totalProjectsDigits + "d";
this.maxThreads = bs.getMaxThreads();
this.artifactIdFormat = "%-" + bs.getArtifactIdDisplayLength() + "s ";
- final int maxThreadsDigits = (int) (Math.log10(maxThreads) + 1);
- this.threadsFormat = "%" + (maxThreadsDigits * 3 + 2) + "s";
- if (maxThreads <= 1 || totalProjects <= 1) {
+ final int maxThreadsDigits = ( int ) ( Math.log10( maxThreads ) + 1 );
+ this.threadsFormat = "%" + ( maxThreadsDigits * 3 + 2 ) + "s";
+ if ( maxThreads <= 1 || totalProjects <= 1 )
+ {
this.noBuffering = true;
- display.update(Collections.emptyList(), 0);
+ display.update( Collections.emptyList(), 0 );
applyNoBuffering();
}
break;
}
- case Message.CANCEL_BUILD: {
- projects.values().stream().flatMap(p -> p.log.stream()).forEach(log);
+ case Message.CANCEL_BUILD:
+ {
+ projects.values().stream().flatMap( p -> p.log.stream() ).forEach( log );
clearDisplay();
- try {
+ try
+ {
log.close();
- } catch (IOException e1) {
- throw new RuntimeException(e1);
}
- final AttributedStyle s = new AttributedStyle().bold().foreground(AttributedStyle.RED);
- new AttributedString("The build was canceled", s).println(terminal);
+ catch ( IOException e1 )
+ {
+ throw new RuntimeException( e1 );
+ }
+ final AttributedStyle s = new AttributedStyle().bold().foreground( AttributedStyle.RED );
+ new AttributedString( "The build was canceled", s ).println( terminal );
terminal.flush();
return false;
}
- case Message.BUILD_EXCEPTION: {
- final BuildException e = (BuildException) entry;
+ case Message.BUILD_EXCEPTION:
+ {
+ final BuildException e = ( BuildException ) entry;
final String msg;
- if ("org.apache.commons.cli.UnrecognizedOptionException".equals(e.getClassName())) {
+ if ( "org.apache.commons.cli.UnrecognizedOptionException".equals( e.getClassName() ) )
+ {
msg = "Unable to parse command line options: " + e.getMessage();
- } else {
+ }
+ else
+ {
msg = e.getClassName() + ": " + e.getMessage();
}
- projects.values().stream().flatMap(p -> p.log.stream()).forEach(log);
+ projects.values().stream().flatMap( p -> p.log.stream() ).forEach( log );
clearDisplay();
- try {
+ try
+ {
log.close();
- } catch (IOException e1) {
- throw new RuntimeException(e1);
}
- final AttributedStyle s = new AttributedStyle().bold().foreground(AttributedStyle.RED);
- new AttributedString(msg, s).println(terminal);
+ catch ( IOException e1 )
+ {
+ throw new RuntimeException( e1 );
+ }
+ final AttributedStyle s = new AttributedStyle().bold().foreground( AttributedStyle.RED );
+ new AttributedString( msg, s ).println( terminal );
terminal.flush();
return false;
}
- case Message.PROJECT_STARTED: {
- StringMessage be = (StringMessage) entry;
+ case Message.PROJECT_STARTED:
+ {
+ StringMessage be = ( StringMessage ) entry;
final String artifactId = be.getMessage();
- projects.put(artifactId, new Project(artifactId));
+ projects.put( artifactId, new Project( artifactId ) );
break;
}
- case Message.MOJO_STARTED: {
- final MojoStartedEvent execution = (MojoStartedEvent) entry;
- final Project prj = projects.computeIfAbsent(execution.getArtifactId(), Project::new);
+ case Message.MOJO_STARTED:
+ {
+ final MojoStartedEvent execution = ( MojoStartedEvent ) entry;
+ final Project prj = projects.computeIfAbsent( execution.getArtifactId(), Project::new );
prj.runningExecution = execution;
break;
}
- case Message.PROJECT_STOPPED: {
- StringMessage be = (StringMessage) entry;
+ case Message.PROJECT_STOPPED:
+ {
+ StringMessage be = ( StringMessage ) entry;
final String artifactId = be.getMessage();
- Project prj = projects.remove(artifactId);
- if (prj != null) {
- prj.log.forEach(log);
+ Project prj = projects.remove( artifactId );
+ if ( prj != null )
+ {
+ prj.log.forEach( log );
}
doneProjects++;
displayDone();
break;
}
- case Message.BUILD_STATUS: {
- this.buildStatus = ((StringMessage) entry).getMessage();
+ case Message.BUILD_STATUS:
+ {
+ this.buildStatus = ( ( StringMessage ) entry ).getMessage();
break;
}
- case Message.BUILD_FINISHED: {
- projects.values().stream().flatMap(p -> p.log.stream()).forEach(log);
+ case Message.BUILD_FINISHED:
+ {
+ projects.values().stream().flatMap( p -> p.log.stream() ).forEach( log );
clearDisplay();
- try {
+ try
+ {
log.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- } finally {
+ }
+ catch ( IOException e )
+ {
+ throw new RuntimeException( e );
+ }
+ finally
+ {
terminal.flush();
}
return false;
}
- case Message.KEEP_ALIVE: {
+ case Message.KEEP_ALIVE:
+ {
break;
}
- case Message.DISPLAY: {
- Message.StringMessage d = (Message.StringMessage) entry;
+ case Message.DISPLAY:
+ {
+ Message.StringMessage d = ( Message.StringMessage ) entry;
clearDisplay();
- terminal.writer().printf("%s%n", d.getMessage());
+ terminal.writer().printf( "%s%n", d.getMessage() );
break;
}
- case Message.PRINT_OUT: {
- Message.StringMessage d = (Message.StringMessage) entry;
+ case Message.PRINT_OUT:
+ {
+ Message.StringMessage d = ( Message.StringMessage ) entry;
clearDisplay();
- System.out.printf("%s%n", d.getMessage());
+ System.out.printf( "%s%n", d.getMessage() );
break;
}
- case Message.PRINT_ERR: {
- Message.StringMessage d = (Message.StringMessage) entry;
+ case Message.PRINT_ERR:
+ {
+ Message.StringMessage d = ( Message.StringMessage ) entry;
clearDisplay();
- System.err.printf("%s%n", d.getMessage());
+ System.err.printf( "%s%n", d.getMessage() );
break;
}
- case Message.PROMPT: {
- Message.Prompt prompt = (Message.Prompt) entry;
- if (dumb) {
- terminal.writer().println("");
+ case Message.PROMPT:
+ {
+ Message.Prompt prompt = ( Message.Prompt ) entry;
+ if ( dumb )
+ {
+ terminal.writer().println( "" );
break;
}
readInput.writeLock().lock();
- try {
+ try
+ {
clearDisplay();
- terminal.writer().printf("[%s] %s", prompt.getProjectId(), prompt.getMessage());
+ terminal.writer().printf( "[%s] %s", prompt.getProjectId(), prompt.getMessage() );
terminal.flush();
StringBuilder sb = new StringBuilder();
- while (true) {
+ while ( true )
+ {
int c = terminal.reader().read();
- if (c < 0) {
+ if ( c < 0 )
+ {
break;
- } else if (c == '\n' || c == '\r') {
+ }
+ else if ( c == '\n' || c == '\r' )
+ {
terminal.writer().println();
- daemonDispatch.accept(prompt.response(sb.toString()));
+ daemonDispatch.accept( prompt.response( sb.toString() ) );
break;
- } else if (c == 127) {
- if (sb.length() > 0) {
- sb.setLength(sb.length() - 1);
- terminal.writer().write("\b \b");
+ }
+ else if ( c == 127 )
+ {
+ if ( sb.length() > 0 )
+ {
+ sb.setLength( sb.length() - 1 );
+ terminal.writer().write( "\b \b" );
terminal.writer().flush();
}
- } else {
- terminal.writer().print((char) c);
+ }
+ else
+ {
+ terminal.writer().print( ( char ) c );
terminal.writer().flush();
- sb.append((char) c);
+ sb.append( ( char ) c );
}
}
- } catch (IOException e) {
- throw new RuntimeException(e);
- } finally {
+ }
+ catch ( IOException e )
+ {
+ throw new RuntimeException( e );
+ }
+ finally
+ {
readInput.writeLock().unlock();
}
break;
}
- case Message.BUILD_LOG_MESSAGE: {
- StringMessage sm = (StringMessage) entry;
- log.accept(sm.getMessage());
+ case Message.BUILD_LOG_MESSAGE:
+ {
+ StringMessage sm = ( StringMessage ) entry;
+ log.accept( sm.getMessage() );
break;
}
- case Message.PROJECT_LOG_MESSAGE: {
- final ProjectEvent bm = (ProjectEvent) entry;
- final Project prj = projects.get(bm.getProjectId());
- if (prj == null) {
- log.accept(bm.getMessage());
- } else if (noBuffering || dumb) {
+ case Message.PROJECT_LOG_MESSAGE:
+ {
+ final ProjectEvent bm = ( ProjectEvent ) entry;
+ final Project prj = projects.get( bm.getProjectId() );
+ if ( prj == null )
+ {
+ log.accept( bm.getMessage() );
+ }
+ else if ( noBuffering || dumb )
+ {
String msg;
- if (maxThreads > 1) {
- msg = String.format("[%s] %s", bm.getProjectId(), bm.getMessage());
- } else {
+ if ( maxThreads > 1 )
+ {
+ msg = String.format( "[%s] %s", bm.getProjectId(), bm.getMessage() );
+ }
+ else
+ {
msg = bm.getMessage();
}
- log.accept(msg);
- } else {
- prj.log.add(bm.getMessage());
+ log.accept( msg );
+ }
+ else
+ {
+ prj.log.add( bm.getMessage() );
}
break;
}
- case Message.KEYBOARD_INPUT: {
- char keyStroke = ((StringMessage) entry).getMessage().charAt(0);
- switch (keyStroke) {
+ case Message.KEYBOARD_INPUT:
+ {
+ char keyStroke = ( ( StringMessage ) entry ).getMessage().charAt( 0 );
+ switch ( keyStroke )
+ {
case KEY_PLUS:
- linesPerProject = Math.min(10, linesPerProject + 1);
+ linesPerProject = Math.min( 10, linesPerProject + 1 );
break;
case KEY_MINUS:
- linesPerProject = Math.max(0, linesPerProject - 1);
+ linesPerProject = Math.max( 0, linesPerProject - 1 );
break;
case KEY_CTRL_B:
noBuffering = !noBuffering;
- if (noBuffering) {
+ if ( noBuffering )
+ {
applyNoBuffering();
- } else {
+ }
+ else
+ {
clearDisplay();
}
break;
@@ -415,115 +495,150 @@ public class TerminalOutput implements ClientOutput {
}
case Message.TRANSFER_INITIATED:
case Message.TRANSFER_STARTED:
- case Message.TRANSFER_PROGRESSED: {
- final TransferEvent te = (TransferEvent) entry;
- transfers.computeIfAbsent(orEmpty(te.getProjectId()), p -> new LinkedHashMap<>())
- .put(te.getResourceName(), te);
+ case Message.TRANSFER_PROGRESSED:
+ {
+ final TransferEvent te = ( TransferEvent ) entry;
+ transfers.computeIfAbsent( orEmpty( te.getProjectId() ), p -> new LinkedHashMap<>() )
+ .put( te.getResourceName(), te );
break;
}
case Message.TRANSFER_CORRUPTED:
case Message.TRANSFER_SUCCEEDED:
- case Message.TRANSFER_FAILED: {
- final TransferEvent te = (TransferEvent) entry;
- transfers.computeIfAbsent(orEmpty(te.getProjectId()), p -> new LinkedHashMap<>())
- .remove(te.getResourceName());
+ case Message.TRANSFER_FAILED:
+ {
+ final TransferEvent te = ( TransferEvent ) entry;
+ transfers.computeIfAbsent( orEmpty( te.getProjectId() ), p -> new LinkedHashMap<>() )
+ .remove( te.getResourceName() );
break;
}
- case Message.EXECUTION_FAILURE: {
- final ExecutionFailureEvent efe = (ExecutionFailureEvent) entry;
- failures.add(efe);
+ case Message.EXECUTION_FAILURE:
+ {
+ final ExecutionFailureEvent efe = ( ExecutionFailureEvent ) entry;
+ failures.add( efe );
break;
}
default:
- throw new IllegalStateException("Unexpected message " + entry);
+ throw new IllegalStateException( "Unexpected message " + entry );
}
return true;
}
- private String orEmpty(String s) {
+ private String orEmpty( String s )
+ {
return s != null ? s : "";
}
- private void applyNoBuffering() {
- projects.values().stream().flatMap(p -> p.log.stream()).forEach(log);
+ private void applyNoBuffering()
+ {
+ projects.values().stream().flatMap( p -> p.log.stream() ).forEach( log );
projects.clear();
}
@Override
- public void describeTerminal() {
+ public void describeTerminal()
+ {
StringBuilder sb = new StringBuilder();
- sb.append("Terminal: ").append(terminal != null ? terminal.getClass().getName() : null);
- if (terminal instanceof AbstractPosixTerminal) {
- sb.append(" with pty ").append(((AbstractPosixTerminal) terminal).getPty().getClass().getName());
+ sb.append( "Terminal: " ).append( terminal != null ? terminal.getClass().getName() : null );
+ if ( terminal instanceof AbstractPosixTerminal )
+ {
+ sb.append( " with pty " ).append( ( ( AbstractPosixTerminal ) terminal ).getPty().getClass().getName() );
}
- this.accept(Message.log(sb.toString()));
+ this.accept( Message.log( sb.toString() ) );
}
@Override
- public int getTerminalWidth() {
+ public int getTerminalWidth()
+ {
return terminal.getWidth();
}
- void readInputLoop() {
- try {
- while (!closing) {
- if (readInput.readLock().tryLock(10, TimeUnit.MILLISECONDS)) {
- int c = terminal.reader().read(10);
- if (c == -1) {
+ void readInputLoop()
+ {
+ try
+ {
+ while ( !closing )
+ {
+ if ( readInput.readLock().tryLock( 10, TimeUnit.MILLISECONDS ) )
+ {
+ int c = terminal.reader().read( 10 );
+ if ( c == -1 )
+ {
break;
}
- if (c == KEY_PLUS || c == KEY_MINUS || c == KEY_CTRL_L || c == KEY_CTRL_M || c == KEY_CTRL_B) {
- daemonReceive.accept(Message.keyboardInput((char) c));
+ if ( c == KEY_PLUS || c == KEY_MINUS || c == KEY_CTRL_L || c == KEY_CTRL_M || c == KEY_CTRL_B )
+ {
+ daemonReceive.accept( Message.keyboardInput( ( char ) c ) );
}
readInput.readLock().unlock();
}
}
- } catch (InterruptedException e) {
+ }
+ catch ( InterruptedException e )
+ {
Thread.currentThread().interrupt();
- } catch (InterruptedIOException e) {
+ }
+ catch ( InterruptedIOException e )
+ {
Thread.currentThread().interrupt();
- } catch (IOException e) {
+ }
+ catch ( IOException e )
+ {
this.exception = e;
}
}
- private void clearDisplay() {
- if (!noBuffering && !dumb) {
- display.update(Collections.emptyList(), 0);
+ private void clearDisplay()
+ {
+ if ( !noBuffering && !dumb )
+ {
+ display.update( Collections.emptyList(), 0 );
}
}
- private void displayDone() {
- if (displayDone) {
- try {
+ private void displayDone()
+ {
+ if ( displayDone )
+ {
+ try
+ {
log.flush();
- } catch (IOException e) {
- throw new RuntimeException(e);
+ }
+ catch ( IOException e )
+ {
+ throw new RuntimeException( e );
}
}
}
@Override
- public void close() throws Exception {
+ public void close() throws Exception
+ {
closing = true;
- if (reader != null) {
+ if ( reader != null )
+ {
reader.interrupt();
}
log.close();
- terminal.handle(Terminal.Signal.INT, previousIntHandler);
+ terminal.handle( Terminal.Signal.INT, previousIntHandler );
terminal.close();
- if (exception != null) {
+ if ( exception != null )
+ {
throw exception;
}
}
- private void update() {
- if (noBuffering || dumb) {
- try {
+ private void update()
+ {
+ if ( noBuffering || dumb )
+ {
+ try
+ {
log.flush();
- } catch (IOException e) {
- throw new RuntimeException(e);
+ }
+ catch ( IOException e )
+ {
+ throw new RuntimeException( e );
}
return;
}
@@ -531,12 +646,13 @@ public class TerminalOutput implements ClientOutput {
final Size size = terminal.getSize();
final int rows = size.getRows();
final int cols = size.getColumns();
- display.resize(rows, size.getColumns());
- if (rows <= 0) {
+ display.resize( rows, size.getColumns() );
+ if ( rows <= 0 )
+ {
clearDisplay();
return;
}
- final List<AttributedString> lines = new ArrayList<>(rows);
+ final List<AttributedString> lines = new ArrayList<>( rows );
final int projectsCount = projects.size();
int dispLines = rows;
@@ -546,151 +662,189 @@ public class TerminalOutput implements ClientOutput {
// so keep one more line empty at the end
dispLines--;
- addStatusLine(lines, dispLines, projectsCount);
+ addStatusLine( lines, dispLines, projectsCount );
AttributedString globalFailure = formatFailures();
- if (globalFailure != null) {
- lines.add(globalFailure);
+ if ( globalFailure != null )
+ {
+ lines.add( globalFailure );
dispLines--;
}
- AttributedString globalTransfer = formatTransfers("");
- if (globalTransfer != null) {
- lines.add(globalTransfer);
+ AttributedString globalTransfer = formatTransfers( "" );
+ if ( globalTransfer != null )
+ {
+ lines.add( globalTransfer );
dispLines--;
}
- if (projectsCount <= dispLines) {
+ if ( projectsCount <= dispLines )
+ {
int remLogLines = dispLines - projectsCount;
- for (Project prj : projects.values()) {
- addProjectLine(lines, prj);
+ for ( Project prj : projects.values() )
+ {
+ addProjectLine( lines, prj );
// get the last lines of the project log, taking multi-line logs into account
- int nb = Math.min(remLogLines, linesPerProject);
- List<AttributedString> logs = lastN(prj.log, nb).stream()
- .flatMap(s -> AttributedString.fromAnsi(s).columnSplitLength(Integer.MAX_VALUE).stream())
- .map(s -> concat(" ", s))
- .collect(lastN(nb));
- lines.addAll(logs);
+ int nb = Math.min( remLogLines, linesPerProject );
+ List<AttributedString> logs = lastN( prj.log, nb ).stream()
+ .flatMap( s -> AttributedString.fromAnsi( s ).columnSplitLength( Integer.MAX_VALUE ).stream() )
+ .map( s -> concat( " ", s ) )
+ .collect( lastN( nb ) );
+ lines.addAll( logs );
remLogLines -= logs.size();
}
- while (remLogLines-- > 0 && lines.size() <= maxThreads + 1) {
- lines.add(AttributedString.EMPTY);
+ while ( remLogLines-- > 0 && lines.size() <= maxThreads + 1 )
+ {
+ lines.add( AttributedString.EMPTY );
... 21607 lines suppressed ...