diff --git a/.config/mill-version b/.config/mill-version index 34a83616bb5..bbf7dd65555 100644 --- a/.config/mill-version +++ b/.config/mill-version @@ -1 +1 @@ -0.12.1 +0.12.1-59-9f7450 \ No newline at end of file diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 7541421ec64..e0555cf08a6 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -169,10 +169,10 @@ jobs: env-bridge-versions: 'essential' # Scalafmt, Mima, and Scalafix job runs last because it's the least important: - # usually just a automated or mechanical manual fix to do before merging + # usually just an automated or mechanical manual fix to do before merging lint-autofix: needs: build-linux uses: ./.github/workflows/run-mill-action.yml with: - java-version: '11' - buildcmd: ./mill -i mill.scalalib.scalafmt.ScalafmtModule/checkFormatAll __.sources; ./mill -i __.mimaReportBinaryIssues; ./mill -i __.fix --check + java-version: '17' + buildcmd: ./mill -i mill.scalalib.scalafmt.ScalafmtModule/checkFormatAll __.sources && ./mill -i __.mimaReportBinaryIssues && ./mill -i __.fix --check && ./mill -i mill.javalib.palantirformat.PalantirFormatModule/ --check diff --git a/contrib/playlib/api/src/mill/playlib/api/RouteCompilerType.java b/contrib/playlib/api/src/mill/playlib/api/RouteCompilerType.java index 35b98e46f62..8249f9ead73 100644 --- a/contrib/playlib/api/src/mill/playlib/api/RouteCompilerType.java +++ b/contrib/playlib/api/src/mill/playlib/api/RouteCompilerType.java @@ -1,6 +1,6 @@ package mill.playlib.api; public enum RouteCompilerType { - InjectedGenerator, - StaticGenerator + InjectedGenerator, + StaticGenerator } diff --git a/contrib/playlib/api/src/mill/playlib/api/RouteCompilerWorkerApi.java b/contrib/playlib/api/src/mill/playlib/api/RouteCompilerWorkerApi.java index 24a071e7f80..2fbc3a07b1f 100644 --- a/contrib/playlib/api/src/mill/playlib/api/RouteCompilerWorkerApi.java +++ b/contrib/playlib/api/src/mill/playlib/api/RouteCompilerWorkerApi.java @@ -1,13 +1,12 @@ package mill.playlib.api; public interface RouteCompilerWorkerApi { - String compile(java.io.File[] files, - String[] additionalImports, - boolean forwardsRouter, - boolean reverseRouter, - boolean namespaceReverseRouter, - RouteCompilerType generatorType, - java.io.File dest); - - + String compile( + java.io.File[] files, + String[] additionalImports, + boolean forwardsRouter, + boolean reverseRouter, + boolean namespaceReverseRouter, + RouteCompilerType generatorType, + java.io.File dest); } diff --git a/contrib/playlib/api/src/mill/playlib/api/Versions.java b/contrib/playlib/api/src/mill/playlib/api/Versions.java index 9c31b143eba..5b48972ec01 100644 --- a/contrib/playlib/api/src/mill/playlib/api/Versions.java +++ b/contrib/playlib/api/src/mill/playlib/api/Versions.java @@ -1,9 +1,9 @@ package mill.playlib.api; public class Versions { - public static final String PLAY_2_6 = "2.6"; - public static final String PLAY_2_7 = "2.7"; - public static final String PLAY_2_8 = "2.8"; - public static final String PLAY_2_9 = "2.9"; - public static final String PLAY_3_0 = "3.0"; + public static final String PLAY_2_6 = "2.6"; + public static final String PLAY_2_7 = "2.7"; + public static final String PLAY_2_8 = "2.8"; + public static final String PLAY_2_9 = "2.9"; + public static final String PLAY_3_0 = "3.0"; } diff --git a/contrib/scoverage/api/src/mill/contrib/scoverage/api/ScoverageReportWorkerApi2.java b/contrib/scoverage/api/src/mill/contrib/scoverage/api/ScoverageReportWorkerApi2.java index 09868af8b3e..14dc82d6dd1 100644 --- a/contrib/scoverage/api/src/mill/contrib/scoverage/api/ScoverageReportWorkerApi2.java +++ b/contrib/scoverage/api/src/mill/contrib/scoverage/api/ScoverageReportWorkerApi2.java @@ -1,24 +1,27 @@ package mill.contrib.scoverage.api; -import java.nio.file.Path; -import java.nio.file.Files; import java.io.IOException; import java.io.Serializable; +import java.nio.file.Files; +import java.nio.file.Path; public interface ScoverageReportWorkerApi2 { interface Logger { void info(String msg); + void error(String msg); + void debug(String msg); } interface Ctx { Logger log(); + Path dest(); } - public static abstract class ReportType implements Serializable { + public abstract static class ReportType implements Serializable { private String name; /*private[api]*/ @@ -35,7 +38,8 @@ static final class ConsoleModule extends ReportType implements Serializable { ConsoleModule() { super("Console"); } - }; + } + ; /* private[api]*/ static final class HtmlModule extends FileReportType implements Serializable { @@ -43,7 +47,8 @@ static final class HtmlModule extends FileReportType implements Serializable { HtmlModule() { super("Html", "htmlReport"); } - }; + } + ; /* private[api]*/ static final class XmlModule extends FileReportType implements Serializable { @@ -67,7 +72,7 @@ public String toString() { } } - public static abstract class FileReportType extends ReportType implements Serializable { + public abstract static class FileReportType extends ReportType implements Serializable { private final String folderName; /*private[api]*/ @@ -91,5 +96,4 @@ static void makeAllDirs(Path path) throws IOException { Files.createDirectories(path); } } - } diff --git a/contrib/testng/src/mill/testng/ResultEvent.java b/contrib/testng/src/mill/testng/ResultEvent.java index 6e2a50d6954..46be47a63b2 100644 --- a/contrib/testng/src/mill/testng/ResultEvent.java +++ b/contrib/testng/src/mill/testng/ResultEvent.java @@ -1,45 +1,55 @@ - package mill.testng; -import sbt.testing.*; import org.testng.ITestResult; +import sbt.testing.*; public class ResultEvent { - static Event failure(ITestResult result){ return event(Status.Failure, result); } - static Event skipped(ITestResult result){ return event(Status.Skipped, result); } - static Event success(ITestResult result){ return event(Status.Success, result); } - - static Event event(Status result, ITestResult testNGResult) { - return new Event() { - public String fullyQualifiedName() { - return testNGResult.getTestClass().getName(); - } - - public Fingerprint fingerprint() { - return TestNGFingerprint.instance; - } - - public Selector selector() { - return new SuiteSelector(); - } - - public Status status() { - return result; - } - - public OptionalThrowable throwable() { - if (result != Status.Success){ - return new OptionalThrowable(testNGResult.getThrowable()); - }else { - return new OptionalThrowable(); - } - } - - @Override - public long duration() { - return testNGResult.getEndMillis() - testNGResult.getStartMillis(); - } - }; - } - static String classNameOf(ITestResult result){ return result.getTestClass().getName(); } -} \ No newline at end of file + static Event failure(ITestResult result) { + return event(Status.Failure, result); + } + + static Event skipped(ITestResult result) { + return event(Status.Skipped, result); + } + + static Event success(ITestResult result) { + return event(Status.Success, result); + } + + static Event event(Status result, ITestResult testNGResult) { + return new Event() { + public String fullyQualifiedName() { + return testNGResult.getTestClass().getName(); + } + + public Fingerprint fingerprint() { + return TestNGFingerprint.instance; + } + + public Selector selector() { + return new SuiteSelector(); + } + + public Status status() { + return result; + } + + public OptionalThrowable throwable() { + if (result != Status.Success) { + return new OptionalThrowable(testNGResult.getThrowable()); + } else { + return new OptionalThrowable(); + } + } + + @Override + public long duration() { + return testNGResult.getEndMillis() - testNGResult.getStartMillis(); + } + }; + } + + static String classNameOf(ITestResult result) { + return result.getTestClass().getName(); + } +} diff --git a/contrib/testng/src/mill/testng/TestNGFramework.java b/contrib/testng/src/mill/testng/TestNGFramework.java index a5aeb286164..d388e78315f 100644 --- a/contrib/testng/src/mill/testng/TestNGFramework.java +++ b/contrib/testng/src/mill/testng/TestNGFramework.java @@ -7,23 +7,29 @@ public class TestNGFramework implements Framework { - public String name(){ return "TestNG"; } - - public Fingerprint[] fingerprints() { - return new Fingerprint[]{TestNGFingerprint.instance}; - } - - @Override - public Runner runner(String[] args, String[] remoteArgs, ClassLoader classLoader) { - return new TestNGRunner(args, remoteArgs, classLoader); - } + public String name() { + return "TestNG"; + } + + public Fingerprint[] fingerprints() { + return new Fingerprint[] {TestNGFingerprint.instance}; + } + + @Override + public Runner runner(String[] args, String[] remoteArgs, ClassLoader classLoader) { + return new TestNGRunner(args, remoteArgs, classLoader); + } } -class TestNGFingerprint implements AnnotatedFingerprint{ +class TestNGFingerprint implements AnnotatedFingerprint { - public static final TestNGFingerprint instance = new TestNGFingerprint(); + public static final TestNGFingerprint instance = new TestNGFingerprint(); - public String annotationName(){return "org.testng.annotations.Test";} + public String annotationName() { + return "org.testng.annotations.Test"; + } - public boolean isModule(){return false;} + public boolean isModule() { + return false; + } } diff --git a/contrib/testng/src/mill/testng/TestNGInstance.java b/contrib/testng/src/mill/testng/TestNGInstance.java index 709ad4281ed..48832dc675e 100644 --- a/contrib/testng/src/mill/testng/TestNGInstance.java +++ b/contrib/testng/src/mill/testng/TestNGInstance.java @@ -1,8 +1,6 @@ package mill.testng; - import java.util.Arrays; - import org.testng.CommandLineArgs; import org.testng.ITestContext; import org.testng.ITestListener; @@ -11,71 +9,70 @@ import sbt.testing.EventHandler; import sbt.testing.Logger; -class TestNGListener implements ITestListener{ +class TestNGListener implements ITestListener { - private final EventHandler basket; - private final boolean printEnabled; + private final EventHandler basket; + private final boolean printEnabled; - private String lastName = ""; + private String lastName = ""; - public TestNGListener(EventHandler basket){ - this.basket = basket; - String prop = System.getProperty("mill.testng.printProgress", "1"); - this.printEnabled = Arrays.asList("1", "y", "yes", "true").contains(prop); - } + public TestNGListener(EventHandler basket) { + this.basket = basket; + String prop = System.getProperty("mill.testng.printProgress", "1"); + this.printEnabled = Arrays.asList("1", "y", "yes", "true").contains(prop); + } - public void onTestStart(ITestResult iTestResult) { - String newName = iTestResult.getTestClass().getName() + " " + iTestResult.getName() + " "; - if(!newName.equals(lastName)){ - if (!lastName.equals("")){ - System.out.println(); - } - lastName = newName; - System.out.print(lastName); - } + public void onTestStart(ITestResult iTestResult) { + String newName = iTestResult.getTestClass().getName() + " " + iTestResult.getName() + " "; + if (!newName.equals(lastName)) { + if (!lastName.equals("")) { + System.out.println(); + } + lastName = newName; + System.out.print(lastName); } + } - public void onTestSuccess(ITestResult iTestResult) { - printProgress('+'); - basket.handle(ResultEvent.success(iTestResult)); - } + public void onTestSuccess(ITestResult iTestResult) { + printProgress('+'); + basket.handle(ResultEvent.success(iTestResult)); + } - public void onTestFailure(ITestResult iTestResult) { - printProgress('X'); - basket.handle(ResultEvent.failure(iTestResult)); - } + public void onTestFailure(ITestResult iTestResult) { + printProgress('X'); + basket.handle(ResultEvent.failure(iTestResult)); + } - public void onTestSkipped(ITestResult iTestResult) { - printProgress('-'); - basket.handle(ResultEvent.skipped(iTestResult)); - } + public void onTestSkipped(ITestResult iTestResult) { + printProgress('-'); + basket.handle(ResultEvent.skipped(iTestResult)); + } - public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) { - basket.handle(ResultEvent.failure(iTestResult)); - } + public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) { + basket.handle(ResultEvent.failure(iTestResult)); + } + + public void onStart(ITestContext iTestContext) {} - public void onStart(ITestContext iTestContext) {} + public void onFinish(ITestContext iTestContext) {} - public void onFinish(ITestContext iTestContext) {} - - protected void printProgress(char progress) { - if(printEnabled) { - System.out.print(progress); - } + protected void printProgress(char progress) { + if (printEnabled) { + System.out.print(progress); } + } } -public class TestNGInstance extends TestNG{ - public TestNGInstance(Logger[] loggers, - ClassLoader testClassLoader, - CommandLineArgs args, - EventHandler eventHandler) { - addClassLoader(testClassLoader); +public class TestNGInstance extends TestNG { + public TestNGInstance( + Logger[] loggers, + ClassLoader testClassLoader, + CommandLineArgs args, + EventHandler eventHandler) { + addClassLoader(testClassLoader); - this.addListener(new TestNGListener(eventHandler)); + this.addListener(new TestNGListener(eventHandler)); - configure(args); - } + configure(args); + } } - - diff --git a/contrib/testng/src/mill/testng/TestNGRunner.java b/contrib/testng/src/mill/testng/TestNGRunner.java index 6a725cd84e2..bd757ca4674 100644 --- a/contrib/testng/src/mill/testng/TestNGRunner.java +++ b/contrib/testng/src/mill/testng/TestNGRunner.java @@ -10,66 +10,65 @@ class TestNGTask implements Task { - private final TaskDef taskDef; - private final ClassLoader testClassLoader; - private final CommandLineArgs cliArgs; + private final TaskDef taskDef; + private final ClassLoader testClassLoader; + private final CommandLineArgs cliArgs; - public TestNGTask(TaskDef taskDef, - ClassLoader testClassLoader, - CommandLineArgs cliArgs){ - this.taskDef = taskDef; - this.testClassLoader = testClassLoader; - this.cliArgs = cliArgs; - } + public TestNGTask(TaskDef taskDef, ClassLoader testClassLoader, CommandLineArgs cliArgs) { + this.taskDef = taskDef; + this.testClassLoader = testClassLoader; + this.cliArgs = cliArgs; + } - @Override - public String[] tags() { - return new String[0]; - } + @Override + public String[] tags() { + return new String[0]; + } - @Override - public Task[] execute(EventHandler eventHandler, Logger[] loggers) { - new TestNGInstance( - loggers, - testClassLoader, - cliArgs, - eventHandler - ).run(); - return new Task[0]; - } + @Override + public Task[] execute(EventHandler eventHandler, Logger[] loggers) { + new TestNGInstance(loggers, testClassLoader, cliArgs, eventHandler).run(); + return new Task[0]; + } - @Override - public TaskDef taskDef() { - return taskDef; - } + @Override + public TaskDef taskDef() { + return taskDef; + } } public class TestNGRunner implements Runner { - private final ClassLoader testClassLoader; - private final String[] args; - private final String[] remoteArgs; + private final ClassLoader testClassLoader; + private final String[] args; + private final String[] remoteArgs; - public TestNGRunner(String[] args, String[] remoteArgs, ClassLoader testClassLoader) { - this.testClassLoader = testClassLoader; - this.args = args; - this.remoteArgs = remoteArgs; - } + public TestNGRunner(String[] args, String[] remoteArgs, ClassLoader testClassLoader) { + this.testClassLoader = testClassLoader; + this.args = args; + this.remoteArgs = remoteArgs; + } - public Task[] tasks(TaskDef[] taskDefs) { - Task[] returnTasks = new Task[taskDefs.length]; - for(int i = 0; i < taskDefs.length; i += 1){ - CommandLineArgs cliArgs = new CommandLineArgs(); - new JCommander(cliArgs).parse(args); // args is an output parameter of the constructor! - cliArgs.testClass = taskDefs[i].fullyQualifiedName(); - returnTasks[i] = new TestNGTask(taskDefs[i], testClassLoader, cliArgs); - } - return returnTasks; + public Task[] tasks(TaskDef[] taskDefs) { + Task[] returnTasks = new Task[taskDefs.length]; + for (int i = 0; i < taskDefs.length; i += 1) { + CommandLineArgs cliArgs = new CommandLineArgs(); + new JCommander(cliArgs).parse(args); // args is an output parameter of the constructor! + cliArgs.testClass = taskDefs[i].fullyQualifiedName(); + returnTasks[i] = new TestNGTask(taskDefs[i], testClassLoader, cliArgs); } + return returnTasks; + } - public String done() { return null; } + public String done() { + return null; + } - public String[] remoteArgs() { return remoteArgs; } + public String[] remoteArgs() { + return remoteArgs; + } - public String[] args() { return args; } + public String[] args() { + return args; + } } diff --git a/docs/modules/ROOT/pages/comparisons/why-mill.adoc b/docs/modules/ROOT/pages/comparisons/why-mill.adoc index d2ec5d4ae07..5339233399b 100644 --- a/docs/modules/ROOT/pages/comparisons/why-mill.adoc +++ b/docs/modules/ROOT/pages/comparisons/why-mill.adoc @@ -426,7 +426,7 @@ the application code to use e.g. below, where we just print it out: ```bash > mill foo.run -Line Count: 17 +Line Count: 18 ``` Most developers do not need to embed the line-count of their codebase in a resource diff --git a/example/depth/sandbox/2-test/bar/src/bar/Bar.java b/example/depth/sandbox/2-test/bar/src/bar/Bar.java index 291650df9bf..64675cb7d88 100644 --- a/example/depth/sandbox/2-test/bar/src/bar/Bar.java +++ b/example/depth/sandbox/2-test/bar/src/bar/Bar.java @@ -1,7 +1,7 @@ package bar; public class Bar { - public static String generateHtml(String text) { - return "

" + text + "

"; - } -} \ No newline at end of file + public static String generateHtml(String text) { + return "

" + text + "

"; + } +} diff --git a/example/depth/sandbox/2-test/bar/test/src/bar/BarTests.java b/example/depth/sandbox/2-test/bar/test/src/bar/BarTests.java index 0b44619b8cf..59259dd0931 100644 --- a/example/depth/sandbox/2-test/bar/test/src/bar/BarTests.java +++ b/example/depth/sandbox/2-test/bar/test/src/bar/BarTests.java @@ -1,15 +1,16 @@ package bar; import static org.junit.Assert.assertEquals; -import org.junit.Test; + import java.nio.file.*; +import org.junit.Test; public class BarTests { - @Test - public void simple() throws Exception { - String result = Bar.generateHtml("world"); - Path path = Paths.get("generated.html"); - Files.write(path, result.getBytes()); - assertEquals("

world

", Files.readString(path)); - } + @Test + public void simple() throws Exception { + String result = Bar.generateHtml("world"); + Path path = Paths.get("generated.html"); + Files.write(path, result.getBytes()); + assertEquals("

world

", Files.readString(path)); + } } diff --git a/example/depth/sandbox/2-test/foo/src/foo/Foo.java b/example/depth/sandbox/2-test/foo/src/foo/Foo.java index 809cfde1092..54002a90031 100644 --- a/example/depth/sandbox/2-test/foo/src/foo/Foo.java +++ b/example/depth/sandbox/2-test/foo/src/foo/Foo.java @@ -1,8 +1,7 @@ package foo; public class Foo { - public static String generateHtml(String text) { - return "

" + text + "

"; - } + public static String generateHtml(String text) { + return "

" + text + "

"; + } } - diff --git a/example/depth/sandbox/2-test/foo/test/src/foo/FooTests.java b/example/depth/sandbox/2-test/foo/test/src/foo/FooTests.java index fa3c336b827..5d883056567 100644 --- a/example/depth/sandbox/2-test/foo/test/src/foo/FooTests.java +++ b/example/depth/sandbox/2-test/foo/test/src/foo/FooTests.java @@ -1,15 +1,16 @@ package foo; import static org.junit.Assert.assertEquals; -import org.junit.Test; + import java.nio.file.*; +import org.junit.Test; public class FooTests { - @Test - public void simple() throws Exception { - String result = Foo.generateHtml("hello"); - Path path = Paths.get("generated.html"); - Files.write(path, result.getBytes()); - assertEquals("

hello

", Files.readString(path)); - } + @Test + public void simple() throws Exception { + String result = Foo.generateHtml("hello"); + Path path = Paths.get("generated.html"); + Files.write(path, result.getBytes()); + assertEquals("

hello

", Files.readString(path)); + } } diff --git a/example/depth/sandbox/3-breaking/foo/src/foo/Foo.java b/example/depth/sandbox/3-breaking/foo/src/foo/Foo.java index 809cfde1092..54002a90031 100644 --- a/example/depth/sandbox/3-breaking/foo/src/foo/Foo.java +++ b/example/depth/sandbox/3-breaking/foo/src/foo/Foo.java @@ -1,8 +1,7 @@ package foo; public class Foo { - public static String generateHtml(String text) { - return "

" + text + "

"; - } + public static String generateHtml(String text) { + return "

" + text + "

"; + } } - diff --git a/example/depth/sandbox/3-breaking/foo/test/src/foo/FooTests.java b/example/depth/sandbox/3-breaking/foo/test/src/foo/FooTests.java index e74d87ad719..09e07863ef1 100644 --- a/example/depth/sandbox/3-breaking/foo/test/src/foo/FooTests.java +++ b/example/depth/sandbox/3-breaking/foo/test/src/foo/FooTests.java @@ -1,23 +1,21 @@ package foo; -import java.util.stream.Collectors; -import java.nio.file.*; import static org.junit.Assert.assertEquals; + +import java.nio.file.*; +import java.util.stream.Collectors; import org.junit.Test; public class FooTests { - @Test - public void simple() throws Exception { - String workspaceRoot = System.getenv("MILL_WORKSPACE_ROOT"); + @Test + public void simple() throws Exception { + String workspaceRoot = System.getenv("MILL_WORKSPACE_ROOT"); - for(Path subpath: Files.list(Paths.get(workspaceRoot)).collect(Collectors.toList())){ - String result = Foo.generateHtml(subpath.getFileName().toString()); - Path tmppath = Paths.get(subpath.getFileName() + ".html"); - Files.write(tmppath, result.getBytes()); - assertEquals( - "

" + subpath.getFileName() + "

", - Files.readString(tmppath) - ); - } + for (Path subpath : Files.list(Paths.get(workspaceRoot)).collect(Collectors.toList())) { + String result = Foo.generateHtml(subpath.getFileName().toString()); + Path tmppath = Paths.get(subpath.getFileName() + ".html"); + Files.write(tmppath, result.getBytes()); + assertEquals("

" + subpath.getFileName() + "

", Files.readString(tmppath)); } + } } diff --git a/example/extending/imports/1-import-ivy/foo/src/Foo.java b/example/extending/imports/1-import-ivy/foo/src/Foo.java index 1cec754f604..eaf98130fe1 100644 --- a/example/extending/imports/1-import-ivy/foo/src/Foo.java +++ b/example/extending/imports/1-import-ivy/foo/src/Foo.java @@ -1,12 +1,13 @@ package foo; + import java.io.*; -public class Foo{ - public static void main(String[] args) throws IOException{ - InputStream res = Foo.class.getResourceAsStream("/snippet.txt"); +public class Foo { + public static void main(String[] args) throws IOException { + InputStream res = Foo.class.getResourceAsStream("/snippet.txt"); - try (BufferedReader br = new BufferedReader(new InputStreamReader(res))) { - System.out.println("generated snippet.txt resource: " + br.readLine()); - } + try (BufferedReader br = new BufferedReader(new InputStreamReader(res))) { + System.out.println("generated snippet.txt resource: " + br.readLine()); } + } } diff --git a/example/extending/jvmcode/1-subprocess/foo/src/Foo.java b/example/extending/jvmcode/1-subprocess/foo/src/Foo.java index 91a18ebb3b9..89625933c75 100644 --- a/example/extending/jvmcode/1-subprocess/foo/src/Foo.java +++ b/example/extending/jvmcode/1-subprocess/foo/src/Foo.java @@ -8,13 +8,14 @@ public class Foo { // Read `file.txt` from classpath public static String groovyGeneratedHtml() throws IOException { // Get the resource as an InputStream - try (InputStream inputStream = Foo.class.getClassLoader().getResourceAsStream("groovy-generated.html")) { + try (InputStream inputStream = + Foo.class.getClassLoader().getResourceAsStream("groovy-generated.html")) { return new String(inputStream.readAllBytes()); } } - public static void main(String[] args) throws IOException{ - String appClasspathResourceText = Foo.groovyGeneratedHtml(); - System.out.println("Contents of groovy-generated.html is " + appClasspathResourceText); + public static void main(String[] args) throws IOException { + String appClasspathResourceText = Foo.groovyGeneratedHtml(); + System.out.println("Contents of groovy-generated.html is " + appClasspathResourceText); } } diff --git a/example/extending/jvmcode/2-classloader/foo/src/Foo.java b/example/extending/jvmcode/2-classloader/foo/src/Foo.java index 91a18ebb3b9..89625933c75 100644 --- a/example/extending/jvmcode/2-classloader/foo/src/Foo.java +++ b/example/extending/jvmcode/2-classloader/foo/src/Foo.java @@ -8,13 +8,14 @@ public class Foo { // Read `file.txt` from classpath public static String groovyGeneratedHtml() throws IOException { // Get the resource as an InputStream - try (InputStream inputStream = Foo.class.getClassLoader().getResourceAsStream("groovy-generated.html")) { + try (InputStream inputStream = + Foo.class.getClassLoader().getResourceAsStream("groovy-generated.html")) { return new String(inputStream.readAllBytes()); } } - public static void main(String[] args) throws IOException{ - String appClasspathResourceText = Foo.groovyGeneratedHtml(); - System.out.println("Contents of groovy-generated.html is " + appClasspathResourceText); + public static void main(String[] args) throws IOException { + String appClasspathResourceText = Foo.groovyGeneratedHtml(); + System.out.println("Contents of groovy-generated.html is " + appClasspathResourceText); } } diff --git a/example/extending/jvmcode/3-worker/bar/src/Bar.java b/example/extending/jvmcode/3-worker/bar/src/Bar.java index 008500d6cd2..41070d93471 100644 --- a/example/extending/jvmcode/3-worker/bar/src/Bar.java +++ b/example/extending/jvmcode/3-worker/bar/src/Bar.java @@ -8,13 +8,14 @@ public class Bar { // Read `file.txt` from classpath public static String groovyGeneratedHtml() throws IOException { // Get the resource as an InputStream - try (InputStream inputStream = Bar.class.getClassLoader().getResourceAsStream("groovy-generated.html")) { + try (InputStream inputStream = + Bar.class.getClassLoader().getResourceAsStream("groovy-generated.html")) { return new String(inputStream.readAllBytes()); } } - public static void main(String[] args) throws IOException{ - String appClasspathResourceText = Bar.groovyGeneratedHtml(); - System.out.println("Contents of groovy-generated.html is " + appClasspathResourceText); + public static void main(String[] args) throws IOException { + String appClasspathResourceText = Bar.groovyGeneratedHtml(); + System.out.println("Contents of groovy-generated.html is " + appClasspathResourceText); } } diff --git a/example/extending/jvmcode/3-worker/foo/src/Foo.java b/example/extending/jvmcode/3-worker/foo/src/Foo.java index 91a18ebb3b9..89625933c75 100644 --- a/example/extending/jvmcode/3-worker/foo/src/Foo.java +++ b/example/extending/jvmcode/3-worker/foo/src/Foo.java @@ -8,13 +8,14 @@ public class Foo { // Read `file.txt` from classpath public static String groovyGeneratedHtml() throws IOException { // Get the resource as an InputStream - try (InputStream inputStream = Foo.class.getClassLoader().getResourceAsStream("groovy-generated.html")) { + try (InputStream inputStream = + Foo.class.getClassLoader().getResourceAsStream("groovy-generated.html")) { return new String(inputStream.readAllBytes()); } } - public static void main(String[] args) throws IOException{ - String appClasspathResourceText = Foo.groovyGeneratedHtml(); - System.out.println("Contents of groovy-generated.html is " + appClasspathResourceText); + public static void main(String[] args) throws IOException { + String appClasspathResourceText = Foo.groovyGeneratedHtml(); + System.out.println("Contents of groovy-generated.html is " + appClasspathResourceText); } } diff --git a/example/extending/jvmcode/5-module-classloader/bar/src/Bar.java b/example/extending/jvmcode/5-module-classloader/bar/src/Bar.java index 883ca8675f0..3af63004b46 100644 --- a/example/extending/jvmcode/5-module-classloader/bar/src/Bar.java +++ b/example/extending/jvmcode/5-module-classloader/bar/src/Bar.java @@ -2,26 +2,25 @@ import java.io.IOException; import java.nio.file.*; -import java.util.List; import java.util.Arrays; import java.util.stream.Collectors; import java.util.stream.Stream; public class Bar { - public static void main(String[] args) throws IOException { - Path dest = Paths.get(args[0]); - String[] sources = Arrays.copyOfRange(args, 1, args.length); - for (String sourceStr : sources) { - Path sourcePath = Paths.get(sourceStr).toAbsolutePath(); - try (Stream paths = Files.walk(sourcePath)) { - for (Path p : paths.collect(Collectors.toList())) { - if (p.toString().endsWith(".java")) { - String mangledText = Files.readString(p).replace("hello", "HELLO"); - Path fileDest = dest.resolve(sourcePath.relativize(p)); - Files.write(fileDest, mangledText.getBytes()); - } - } - } + public static void main(String[] args) throws IOException { + Path dest = Paths.get(args[0]); + String[] sources = Arrays.copyOfRange(args, 1, args.length); + for (String sourceStr : sources) { + Path sourcePath = Paths.get(sourceStr).toAbsolutePath(); + try (Stream paths = Files.walk(sourcePath)) { + for (Path p : paths.collect(Collectors.toList())) { + if (p.toString().endsWith(".java")) { + String mangledText = Files.readString(p).replace("hello", "HELLO"); + Path fileDest = dest.resolve(sourcePath.relativize(p)); + Files.write(fileDest, mangledText.getBytes()); + } } + } } + } } diff --git a/example/extending/jvmcode/5-module-classloader/foo/src/Foo.java b/example/extending/jvmcode/5-module-classloader/foo/src/Foo.java index db78094dae5..ce4e4d88128 100644 --- a/example/extending/jvmcode/5-module-classloader/foo/src/Foo.java +++ b/example/extending/jvmcode/5-module-classloader/foo/src/Foo.java @@ -1,9 +1,9 @@ package foo; public class Foo { - public static final String value = "hello"; // Equivalent to val in Scala + public static final String value = "hello"; // Equivalent to val in Scala - public static void main(String[] args) { - System.out.println("Foo.value: " + Foo.value); - } + public static void main(String[] args) { + System.out.println("Foo.value: " + Foo.value); + } } diff --git a/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/example-test-project/build.mill b/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/example-test-project/build.mill index 03147287731..7d4295fc6c0 100644 --- a/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/example-test-project/build.mill +++ b/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/example-test-project/build.mill @@ -9,13 +9,13 @@ object `package` extends RootModule with LineCountJavaModule { /** Usage > ./mill run -Line Count: 17 +Line Count: 18 ... > printf "\n" >> src/foo/Foo.java > ./mill run -Line Count: 18 +Line Count: 19 ... */ diff --git a/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/example-test-project/src/foo/Foo.java b/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/example-test-project/src/foo/Foo.java index 12dcba2b7ab..467b53614de 100644 --- a/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/example-test-project/src/foo/Foo.java +++ b/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/example-test-project/src/foo/Foo.java @@ -1,12 +1,13 @@ package foo; public class Foo { - public static String getLineCount(){ - try{ + public static String getLineCount() { + try { return new String( - Foo.class.getClassLoader().getResourceAsStream("line-count.txt").readAllBytes() - ); - }catch(java.io.IOException e){ return null; } + Foo.class.getClassLoader().getResourceAsStream("line-count.txt").readAllBytes()); + } catch (java.io.IOException e) { + return null; + } } static String lineCount = getLineCount(); diff --git a/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/integration-test-project/src/foo/Foo.java b/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/integration-test-project/src/foo/Foo.java index 12dcba2b7ab..467b53614de 100644 --- a/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/integration-test-project/src/foo/Foo.java +++ b/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/integration-test-project/src/foo/Foo.java @@ -1,12 +1,13 @@ package foo; public class Foo { - public static String getLineCount(){ - try{ + public static String getLineCount() { + try { return new String( - Foo.class.getClassLoader().getResourceAsStream("line-count.txt").readAllBytes() - ); - }catch(java.io.IOException e){ return null; } + Foo.class.getClassLoader().getResourceAsStream("line-count.txt").readAllBytes()); + } catch (java.io.IOException e) { + return null; + } } static String lineCount = getLineCount(); diff --git a/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/unit-test-project/src/foo/Foo.java b/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/unit-test-project/src/foo/Foo.java index 12dcba2b7ab..467b53614de 100644 --- a/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/unit-test-project/src/foo/Foo.java +++ b/example/extending/plugins/7-writing-mill-plugins/myplugin/test/resources/unit-test-project/src/foo/Foo.java @@ -1,12 +1,13 @@ package foo; public class Foo { - public static String getLineCount(){ - try{ + public static String getLineCount() { + try { return new String( - Foo.class.getClassLoader().getResourceAsStream("line-count.txt").readAllBytes() - ); - }catch(java.io.IOException e){ return null; } + Foo.class.getClassLoader().getResourceAsStream("line-count.txt").readAllBytes()); + } catch (java.io.IOException e) { + return null; + } } static String lineCount = getLineCount(); diff --git a/example/extending/plugins/7-writing-mill-plugins/myplugin/test/src/mill/testkit/IntegrationTests.scala b/example/extending/plugins/7-writing-mill-plugins/myplugin/test/src/mill/testkit/IntegrationTests.scala index d957f1a1e87..924c8966bb8 100644 --- a/example/extending/plugins/7-writing-mill-plugins/myplugin/test/src/mill/testkit/IntegrationTests.scala +++ b/example/extending/plugins/7-writing-mill-plugins/myplugin/test/src/mill/testkit/IntegrationTests.scala @@ -20,20 +20,20 @@ object IntegrationTests extends TestSuite { val res1 = tester.eval("run") assert(res1.isSuccess) assert(res1.err.contains("compiling 1 Java source")) // compiling the `build.mill` - assert(res1.out.contains("Line Count: 17")) - assert(tester.out("lineCount").value[Int] == 17) + assert(res1.out.contains("Line Count: 18")) + assert(tester.out("lineCount").value[Int] == 18) val res2 = tester.eval("run") // No need to recompile when nothing changed assert(!res2.err.contains("compiling 1 Java source")) - assert(res2.out.contains("Line Count: 17")) - assert(tester.out("lineCount").value[Int] == 17) + assert(res2.out.contains("Line Count: 18")) + assert(tester.out("lineCount").value[Int] == 18) tester.modifyFile(tester.workspacePath / "src/foo/Foo.java", _ + "\n") val res3 = tester.eval("run") // Additional newline forces recompile and increases line count assert(res3.err.contains("compiling 1 Java source")) - assert(res3.out.contains("Line Count: 18")) - assert(tester.out("lineCount").value[Int] == 18) + assert(res3.out.contains("Line Count: 19")) + assert(tester.out("lineCount").value[Int] == 19) } } } diff --git a/example/extending/plugins/7-writing-mill-plugins/myplugin/test/src/mill/testkit/UnitTests.scala b/example/extending/plugins/7-writing-mill-plugins/myplugin/test/src/mill/testkit/UnitTests.scala index ee81ba3d432..4397fcfe51d 100644 --- a/example/extending/plugins/7-writing-mill-plugins/myplugin/test/src/mill/testkit/UnitTests.scala +++ b/example/extending/plugins/7-writing-mill-plugins/myplugin/test/src/mill/testkit/UnitTests.scala @@ -17,7 +17,7 @@ object UnitTests extends TestSuite { assert( result.value.exists(pathref => os.exists(pathref.path / "line-count.txt") && - os.read(pathref.path / "line-count.txt") == "17" + os.read(pathref.path / "line-count.txt") == "18" ) ) @@ -27,7 +27,7 @@ object UnitTests extends TestSuite { assert( pathrefs.exists(pathref => os.exists(pathref.path / "line-count.txt") && - os.read(pathref.path / "line-count.txt") == "17" + os.read(pathref.path / "line-count.txt") == "18" ) ) } diff --git a/example/fundamentals/modules/10-external-module-aliases/foo/src/foo/Foo.java b/example/fundamentals/modules/10-external-module-aliases/foo/src/foo/Foo.java index 5172b788bea..d52a3367948 100644 --- a/example/fundamentals/modules/10-external-module-aliases/foo/src/foo/Foo.java +++ b/example/fundamentals/modules/10-external-module-aliases/foo/src/foo/Foo.java @@ -1 +1,7 @@ -package foo;public class Foo{ public static void main(String[] args) {System.out.println("Hello World!");}} +package foo; + +public class Foo { + public static void main(String[] args) { + System.out.println("Hello World!"); + } +} diff --git a/example/fundamentals/modules/11-abstract-module-ref/bar/src/bar/Bar.java b/example/fundamentals/modules/11-abstract-module-ref/bar/src/bar/Bar.java index 7bec32e40d0..e283e6decd6 100644 --- a/example/fundamentals/modules/11-abstract-module-ref/bar/src/bar/Bar.java +++ b/example/fundamentals/modules/11-abstract-module-ref/bar/src/bar/Bar.java @@ -1,11 +1,8 @@ package bar; - public class Bar { - public static String generateHtml(String text) { - String value = "

" + text + "

"; - return value; - } - - + public static String generateHtml(String text) { + String value = "

" + text + "

"; + return value; + } } diff --git a/example/fundamentals/modules/11-abstract-module-ref/bartest/src/bar/BarTests.java b/example/fundamentals/modules/11-abstract-module-ref/bartest/src/bar/BarTests.java index 486c311554f..787d7931110 100644 --- a/example/fundamentals/modules/11-abstract-module-ref/bartest/src/bar/BarTests.java +++ b/example/fundamentals/modules/11-abstract-module-ref/bartest/src/bar/BarTests.java @@ -1,13 +1,14 @@ package bar; import static org.junit.Assert.assertEquals; + import org.junit.Test; public class BarTests { - @Test - public void simple() { - String result = Bar.generateHtml("hello"); - assertEquals("

hello

", result); - } + @Test + public void simple() { + String result = Bar.generateHtml("hello"); + assertEquals("

hello

", result); + } } diff --git a/example/fundamentals/modules/11-abstract-module-ref/foo/src/foo/Foo.java b/example/fundamentals/modules/11-abstract-module-ref/foo/src/foo/Foo.java index ede476c2074..cfa20cd9ef3 100644 --- a/example/fundamentals/modules/11-abstract-module-ref/foo/src/foo/Foo.java +++ b/example/fundamentals/modules/11-abstract-module-ref/foo/src/foo/Foo.java @@ -1,8 +1,6 @@ package foo; - public class Foo { - public static final String VALUE = "hello"; + public static final String VALUE = "hello"; } - diff --git a/example/fundamentals/modules/11-abstract-module-ref/footest/src/bar/FooTests.java b/example/fundamentals/modules/11-abstract-module-ref/footest/src/bar/FooTests.java index adbccf3a864..46832c96b3d 100644 --- a/example/fundamentals/modules/11-abstract-module-ref/footest/src/bar/FooTests.java +++ b/example/fundamentals/modules/11-abstract-module-ref/footest/src/bar/FooTests.java @@ -1,12 +1,13 @@ package foo; import static org.junit.Assert.assertEquals; + import org.junit.Test; public class FooTests { - @Test - public void simple() { - assertEquals("hello", Foo.VALUE); - } + @Test + public void simple() { + assertEquals("hello", Foo.VALUE); + } } diff --git a/example/fundamentals/modules/7-root-module/src/foo/Foo.java b/example/fundamentals/modules/7-root-module/src/foo/Foo.java index f18ca73bf8b..26a6c1174e4 100644 --- a/example/fundamentals/modules/7-root-module/src/foo/Foo.java +++ b/example/fundamentals/modules/7-root-module/src/foo/Foo.java @@ -2,34 +2,33 @@ import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; -import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; -public class Foo{ - public static String generateHtml(String text){ - Context context = new Context(); - context.setVariable("text", text); - return new TemplateEngine().process("

", context); - } - public static void main(String[] args) { - ArgumentParser parser = ArgumentParsers.newFor("template").build() - .defaultHelp(true) - .description("Inserts text into a HTML template"); +public class Foo { + public static String generateHtml(String text) { + Context context = new Context(); + context.setVariable("text", text); + return new TemplateEngine().process("

", context); + } - parser.addArgument("-t", "--text") - .required(true) - .help("text to insert"); + public static void main(String[] args) { + ArgumentParser parser = ArgumentParsers.newFor("template") + .build() + .defaultHelp(true) + .description("Inserts text into a HTML template"); - Namespace ns = null; - try { - ns = parser.parseArgs(args); - }catch(Exception e){ - System.out.println(e.getMessage()); - System.exit(1); - } + parser.addArgument("-t", "--text").required(true).help("text to insert"); - System.out.println(generateHtml(ns.getString("text"))); + Namespace ns = null; + try { + ns = parser.parseArgs(args); + } catch (Exception e) { + System.out.println(e.getMessage()); + System.exit(1); } + + System.out.println(generateHtml(ns.getString("text"))); + } } diff --git a/example/fundamentals/modules/7-root-module/test/src/foo/FooTest.java b/example/fundamentals/modules/7-root-module/test/src/foo/FooTest.java index 80f730a8735..93ec5f03e61 100644 --- a/example/fundamentals/modules/7-root-module/test/src/foo/FooTest.java +++ b/example/fundamentals/modules/7-root-module/test/src/foo/FooTest.java @@ -1,16 +1,18 @@ package foo; -import static org.junit.Assert.assertEquals; + import static com.google.common.html.HtmlEscapers.htmlEscaper; +import static org.junit.Assert.assertEquals; + import org.junit.Test; public class FooTest { - @Test - public void testSimple() { - assertEquals(Foo.generateHtml("hello"), "

hello

"); - } + @Test + public void testSimple() { + assertEquals(Foo.generateHtml("hello"), "

hello

"); + } - @Test - public void testEscaping() { - assertEquals(Foo.generateHtml(""), "

" + htmlEscaper().escape("") + "

"); - } + @Test + public void testEscaping() { + assertEquals(Foo.generateHtml(""), "

" + htmlEscaper().escape("") + "

"); + } } diff --git a/example/fundamentals/modules/8-diy-java-modules/foo/bar/src/Bar.java b/example/fundamentals/modules/8-diy-java-modules/foo/bar/src/Bar.java index ca35a232ed2..309ca9569c7 100644 --- a/example/fundamentals/modules/8-diy-java-modules/foo/bar/src/Bar.java +++ b/example/fundamentals/modules/8-diy-java-modules/foo/bar/src/Bar.java @@ -1,4 +1,5 @@ package foo.bar; -public class Bar{ - public static final int value = 271828; + +public class Bar { + public static final int value = 271828; } diff --git a/example/fundamentals/modules/8-diy-java-modules/foo/src/Foo.java b/example/fundamentals/modules/8-diy-java-modules/foo/src/Foo.java index db25a197534..80da56c6059 100644 --- a/example/fundamentals/modules/8-diy-java-modules/foo/src/Foo.java +++ b/example/fundamentals/modules/8-diy-java-modules/foo/src/Foo.java @@ -1,8 +1,10 @@ package foo; -public class Foo{ - public static final int value = 31337; - public static void main(String[] args){ - System.out.println("Foo.value: " + foo.Foo.value); - System.out.println("Bar.value: " + foo.bar.Bar.value); - } + +public class Foo { + public static final int value = 31337; + + public static void main(String[] args) { + System.out.println("Foo.value: " + foo.Foo.value); + System.out.println("Bar.value: " + foo.bar.Bar.value); + } } diff --git a/example/fundamentals/modules/8-diy-java-modules/qux/src/Qux.java b/example/fundamentals/modules/8-diy-java-modules/qux/src/Qux.java index b5e730656d9..d57a2f00db2 100644 --- a/example/fundamentals/modules/8-diy-java-modules/qux/src/Qux.java +++ b/example/fundamentals/modules/8-diy-java-modules/qux/src/Qux.java @@ -1,9 +1,11 @@ package qux; -public class Qux{ - public static final int value = 9000; - public static void main(String[] args){ - System.out.println("Foo.value: " + foo.Foo.value); - System.out.println("Bar.value: " + foo.bar.Bar.value); - System.out.println("Qux.value: " + value); - } + +public class Qux { + public static final int value = 9000; + + public static void main(String[] args) { + System.out.println("Foo.value: " + foo.Foo.value); + System.out.println("Bar.value: " + foo.bar.Bar.value); + System.out.println("Qux.value: " + value); + } } diff --git a/example/fundamentals/tasks/1-task-graph/src/Foo.java b/example/fundamentals/tasks/1-task-graph/src/Foo.java index 7f6eaa4135a..3db1642557e 100644 --- a/example/fundamentals/tasks/1-task-graph/src/Foo.java +++ b/example/fundamentals/tasks/1-task-graph/src/Foo.java @@ -1,16 +1,18 @@ package foo; + import java.io.*; -public class Foo{ - public static final int value = 31337; - public static void main(String[] args) throws IOException{ - System.out.println("Foo.value: " + value ); - System.out.println("args: " + String.join(" ", args) ); +public class Foo { + public static final int value = 31337; + + public static void main(String[] args) throws IOException { + System.out.println("Foo.value: " + value); + System.out.println("args: " + String.join(" ", args)); - InputStream res = Foo.class.getResourceAsStream("/foo.txt"); + InputStream res = Foo.class.getResourceAsStream("/foo.txt"); - try (BufferedReader br = new BufferedReader(new InputStreamReader(res))) { - System.out.println("foo.txt resource: " + br.readLine()); - } + try (BufferedReader br = new BufferedReader(new InputStreamReader(res))) { + System.out.println("foo.txt resource: " + br.readLine()); } + } } diff --git a/example/fundamentals/tasks/2-primary-tasks/src/foo/Foo.java b/example/fundamentals/tasks/2-primary-tasks/src/foo/Foo.java index 7f6eaa4135a..3db1642557e 100644 --- a/example/fundamentals/tasks/2-primary-tasks/src/foo/Foo.java +++ b/example/fundamentals/tasks/2-primary-tasks/src/foo/Foo.java @@ -1,16 +1,18 @@ package foo; + import java.io.*; -public class Foo{ - public static final int value = 31337; - public static void main(String[] args) throws IOException{ - System.out.println("Foo.value: " + value ); - System.out.println("args: " + String.join(" ", args) ); +public class Foo { + public static final int value = 31337; + + public static void main(String[] args) throws IOException { + System.out.println("Foo.value: " + value); + System.out.println("args: " + String.join(" ", args)); - InputStream res = Foo.class.getResourceAsStream("/foo.txt"); + InputStream res = Foo.class.getResourceAsStream("/foo.txt"); - try (BufferedReader br = new BufferedReader(new InputStreamReader(res))) { - System.out.println("foo.txt resource: " + br.readLine()); - } + try (BufferedReader br = new BufferedReader(new InputStreamReader(res))) { + System.out.println("foo.txt resource: " + br.readLine()); } + } } diff --git a/example/javalib/android/1-hello-world/app/src/main/java/com/helloworld/app/MainActivity.java b/example/javalib/android/1-hello-world/app/src/main/java/com/helloworld/app/MainActivity.java index 1883d567555..2c0cf8ad67f 100644 --- a/example/javalib/android/1-hello-world/app/src/main/java/com/helloworld/app/MainActivity.java +++ b/example/javalib/android/1-hello-world/app/src/main/java/com/helloworld/app/MainActivity.java @@ -2,35 +2,32 @@ import android.app.Activity; import android.os.Bundle; -import android.view.View; -import android.widget.TextView; -import android.view.ViewGroup.LayoutParams; import android.view.Gravity; - +import android.view.ViewGroup.LayoutParams; +import android.widget.TextView; public class MainActivity extends Activity { - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - // Create a new TextView - TextView textView = new TextView(this); + // Create a new TextView + TextView textView = new TextView(this); - // Set the text to "Hello, World!" - textView.setText("Hello, World!"); + // Set the text to "Hello, World!" + textView.setText("Hello, World!"); - // Set text size - textView.setTextSize(32); + // Set text size + textView.setTextSize(32); - // Center the text within the view - textView.setGravity(Gravity.CENTER); + // Center the text within the view + textView.setGravity(Gravity.CENTER); - // Set layout parameters (width and height) - textView.setLayoutParams(new LayoutParams( - LayoutParams.MATCH_PARENT, - LayoutParams.MATCH_PARENT)); + // Set layout parameters (width and height) + textView.setLayoutParams( + new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); - // Set the content view to display the TextView - setContentView(textView); - } + // Set the content view to display the TextView + setContentView(textView); + } } diff --git a/example/javalib/android/1-hello-world/build.mill b/example/javalib/android/1-hello-world/build.mill index bbe1fb59931..d0e2bceb1fd 100644 --- a/example/javalib/android/1-hello-world/build.mill +++ b/example/javalib/android/1-hello-world/build.mill @@ -1,9 +1,9 @@ -// This section sets up a basic Android project using Mill. -// We utilize `AndroidAppModule` and `AndroidSdkModule` to streamline the process of +// This section sets up a basic Android project using Mill. +// We utilize `AndroidAppModule` and `AndroidSdkModule` to streamline the process of // building an Android application with minimal configuration. // -// By extending `AndroidAppModule`, we inherit all Android-related tasks such as -// resource generation, APK building, DEX conversion, and APK signing. +// By extending `AndroidAppModule`, we inherit all Android-related tasks such as +// resource generation, APK building, DEX conversion, and APK signing. // Additionally, `AndroidSdkModule` is embedded, making SDK management seamless. //// SNIPPET:BUILD @@ -13,7 +13,7 @@ import mill._ import mill.javalib.android.{AndroidAppModule, AndroidSdkModule} // Create and configure an Android SDK module to manage Android SDK paths and tools. -object androidSdkModule0 extends AndroidSdkModule{ +object androidSdkModule0 extends AndroidSdkModule { def buildToolsVersion = "35.0.0" } @@ -24,7 +24,6 @@ object app extends AndroidAppModule { ////SNIPPET:END - /** Usage > ./mill show app.androidApk @@ -32,14 +31,14 @@ object app extends AndroidAppModule { */ -// This command triggers the build process, which installs the Android Setup, compiles the Java -// code, generates Android resources, converts Java bytecode to DEX format, packages everything +// This command triggers the build process, which installs the Android Setup, compiles the Java +// code, generates Android resources, converts Java bytecode to DEX format, packages everything // into an APK, optimizes the APK using `zipalign`, and finally signs it. // -// This Mill build configuration is designed to build a simple "Hello World" Android application. -// By extending `AndroidAppModule`, we leverage its predefined Android build tasks, ensuring that +// This Mill build configuration is designed to build a simple "Hello World" Android application. +// By extending `AndroidAppModule`, we leverage its predefined Android build tasks, ensuring that // all necessary steps (resource generation, APK creation, and signing) are executed automatically. -// +// // ### Project Structure: // The project follows the standard Android app layout. Below is a typical project folder structure: // diff --git a/example/javalib/basic/1-simple/build.mill b/example/javalib/basic/1-simple/build.mill index cc0ebc6fc43..67abcd1e759 100644 --- a/example/javalib/basic/1-simple/build.mill +++ b/example/javalib/basic/1-simple/build.mill @@ -8,7 +8,7 @@ object foo extends JavaModule { ivy"org.thymeleaf:thymeleaf:3.1.1.RELEASE" ) - object test extends JavaTests with TestModule.Junit4{ + object test extends JavaTests with TestModule.Junit4 { def ivyDeps = super.ivyDeps() ++ Agg( ivy"com.google.guava:guava:33.3.0-jre" ) diff --git a/example/javalib/basic/1-simple/foo/src/foo/Foo.java b/example/javalib/basic/1-simple/foo/src/foo/Foo.java index f18ca73bf8b..26a6c1174e4 100644 --- a/example/javalib/basic/1-simple/foo/src/foo/Foo.java +++ b/example/javalib/basic/1-simple/foo/src/foo/Foo.java @@ -2,34 +2,33 @@ import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; -import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; -public class Foo{ - public static String generateHtml(String text){ - Context context = new Context(); - context.setVariable("text", text); - return new TemplateEngine().process("

", context); - } - public static void main(String[] args) { - ArgumentParser parser = ArgumentParsers.newFor("template").build() - .defaultHelp(true) - .description("Inserts text into a HTML template"); +public class Foo { + public static String generateHtml(String text) { + Context context = new Context(); + context.setVariable("text", text); + return new TemplateEngine().process("

", context); + } - parser.addArgument("-t", "--text") - .required(true) - .help("text to insert"); + public static void main(String[] args) { + ArgumentParser parser = ArgumentParsers.newFor("template") + .build() + .defaultHelp(true) + .description("Inserts text into a HTML template"); - Namespace ns = null; - try { - ns = parser.parseArgs(args); - }catch(Exception e){ - System.out.println(e.getMessage()); - System.exit(1); - } + parser.addArgument("-t", "--text").required(true).help("text to insert"); - System.out.println(generateHtml(ns.getString("text"))); + Namespace ns = null; + try { + ns = parser.parseArgs(args); + } catch (Exception e) { + System.out.println(e.getMessage()); + System.exit(1); } + + System.out.println(generateHtml(ns.getString("text"))); + } } diff --git a/example/javalib/basic/1-simple/foo/test/src/foo/FooTest.java b/example/javalib/basic/1-simple/foo/test/src/foo/FooTest.java index 80f730a8735..93ec5f03e61 100644 --- a/example/javalib/basic/1-simple/foo/test/src/foo/FooTest.java +++ b/example/javalib/basic/1-simple/foo/test/src/foo/FooTest.java @@ -1,16 +1,18 @@ package foo; -import static org.junit.Assert.assertEquals; + import static com.google.common.html.HtmlEscapers.htmlEscaper; +import static org.junit.Assert.assertEquals; + import org.junit.Test; public class FooTest { - @Test - public void testSimple() { - assertEquals(Foo.generateHtml("hello"), "

hello

"); - } + @Test + public void testSimple() { + assertEquals(Foo.generateHtml("hello"), "

hello

"); + } - @Test - public void testEscaping() { - assertEquals(Foo.generateHtml(""), "

" + htmlEscaper().escape("") + "

"); - } + @Test + public void testEscaping() { + assertEquals(Foo.generateHtml(""), "

" + htmlEscaper().escape("") + "

"); + } } diff --git a/example/javalib/basic/2-custom-build-logic/build.mill b/example/javalib/basic/2-custom-build-logic/build.mill index 5b62f57e913..8866a6ce867 100644 --- a/example/javalib/basic/2-custom-build-logic/build.mill +++ b/example/javalib/basic/2-custom-build-logic/build.mill @@ -3,6 +3,7 @@ package build import mill._, javalib._ object foo extends JavaModule { + /** Total number of lines in module source files */ def lineCount = Task { allSourceFiles().map(f => os.read.lines(f.path).size).sum diff --git a/example/javalib/basic/2-custom-build-logic/foo/src/foo/Foo.java b/example/javalib/basic/2-custom-build-logic/foo/src/foo/Foo.java index 12dcba2b7ab..0e5ce273d12 100644 --- a/example/javalib/basic/2-custom-build-logic/foo/src/foo/Foo.java +++ b/example/javalib/basic/2-custom-build-logic/foo/src/foo/Foo.java @@ -1,17 +1,17 @@ package foo; public class Foo { - public static String getLineCount(){ - try{ + public static String getLineCount() { + try { return new String( - Foo.class.getClassLoader().getResourceAsStream("line-count.txt").readAllBytes() - ); - }catch(java.io.IOException e){ return null; } + Foo.class.getClassLoader().getResourceAsStream("line-count.txt").readAllBytes()); + } catch (java.io.IOException e) { + return null; + } } - static String lineCount = getLineCount(); - public static void main(String[] args) throws Exception { + String lineCount = getLineCount(); System.out.println("Line Count: " + lineCount); } } diff --git a/example/javalib/basic/2-custom-build-logic/foo/test/src/foo/FooTests.java b/example/javalib/basic/2-custom-build-logic/foo/test/src/foo/FooTests.java index a94710a2367..e38513adddd 100644 --- a/example/javalib/basic/2-custom-build-logic/foo/test/src/foo/FooTests.java +++ b/example/javalib/basic/2-custom-build-logic/foo/test/src/foo/FooTests.java @@ -1,6 +1,7 @@ package foo; import static org.junit.Assert.assertEquals; + import org.junit.Test; public class FooTests { @@ -8,7 +9,7 @@ public class FooTests { @Test public void testSimple() { int expectedLineCount = 12; - int actualLineCount = Integer.parseInt(Foo.lineCount.trim()); + int actualLineCount = Integer.parseInt(Foo.getLineCount().trim()); assertEquals(expectedLineCount, actualLineCount); } -} \ No newline at end of file +} diff --git a/example/javalib/basic/3-multi-module/bar/src/bar/Bar.java b/example/javalib/basic/3-multi-module/bar/src/bar/Bar.java index 5a3b7ea0805..75b569dc909 100644 --- a/example/javalib/basic/3-multi-module/bar/src/bar/Bar.java +++ b/example/javalib/basic/3-multi-module/bar/src/bar/Bar.java @@ -1,19 +1,16 @@ package bar; -import net.sourceforge.argparse4j.ArgumentParsers; -import net.sourceforge.argparse4j.inf.ArgumentParser; -import net.sourceforge.argparse4j.inf.Namespace; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; public class Bar { - public static String generateHtml(String text){ - Context context = new Context(); - context.setVariable("text", text); - return new TemplateEngine().process("

", context); - } + public static String generateHtml(String text) { + Context context = new Context(); + context.setVariable("text", text); + return new TemplateEngine().process("

", context); + } - public static void main(String[] args) { - System.out.println("Bar.value: " + generateHtml(args[0])); - } + public static void main(String[] args) { + System.out.println("Bar.value: " + generateHtml(args[0])); + } } diff --git a/example/javalib/basic/3-multi-module/bar/test/src/bar/BarTests.java b/example/javalib/basic/3-multi-module/bar/test/src/bar/BarTests.java index c50bcd9e1c6..6ba4530d2f4 100644 --- a/example/javalib/basic/3-multi-module/bar/test/src/bar/BarTests.java +++ b/example/javalib/basic/3-multi-module/bar/test/src/bar/BarTests.java @@ -1,19 +1,20 @@ package bar; import static org.junit.Assert.assertEquals; + import org.junit.Test; public class BarTests { - @Test - public void simple() { - String result = Bar.generateHtml("hello"); - assertEquals("

hello

", result); - } + @Test + public void simple() { + String result = Bar.generateHtml("hello"); + assertEquals("

hello

", result); + } - @Test - public void escaping() { - String result = Bar.generateHtml(""); - assertEquals("

<hello>

", result); - } -} \ No newline at end of file + @Test + public void escaping() { + String result = Bar.generateHtml(""); + assertEquals("

<hello>

", result); + } +} diff --git a/example/javalib/basic/3-multi-module/build.mill b/example/javalib/basic/3-multi-module/build.mill index 1d744cf2351..3cec1059de1 100644 --- a/example/javalib/basic/3-multi-module/build.mill +++ b/example/javalib/basic/3-multi-module/build.mill @@ -2,18 +2,18 @@ package build import mill._, javalib._ -trait MyModule extends JavaModule{ +trait MyModule extends JavaModule { object test extends JavaTests with TestModule.Junit4 } -object foo extends MyModule{ +object foo extends MyModule { def moduleDeps = Seq(bar) def ivyDeps = Agg( - ivy"net.sourceforge.argparse4j:argparse4j:0.9.0", + ivy"net.sourceforge.argparse4j:argparse4j:0.9.0" ) } -object bar extends MyModule{ +object bar extends MyModule { def ivyDeps = Agg( ivy"net.sourceforge.argparse4j:argparse4j:0.9.0", ivy"org.thymeleaf:thymeleaf:3.1.1.RELEASE" diff --git a/example/javalib/basic/3-multi-module/foo/src/foo/Foo.java b/example/javalib/basic/3-multi-module/foo/src/foo/Foo.java index a57f5f830fd..89d0317a0d7 100644 --- a/example/javalib/basic/3-multi-module/foo/src/foo/Foo.java +++ b/example/javalib/basic/3-multi-module/foo/src/foo/Foo.java @@ -6,24 +6,23 @@ public class Foo { - public static final String VALUE = "hello"; + public static final String VALUE = "hello"; - public static void mainFunction(String fooText, String barText) { - System.out.println("Foo.value: " + Foo.VALUE); - System.out.println("Bar.value: " + bar.Bar.generateHtml(barText)); - } + public static void mainFunction(String fooText, String barText) { + System.out.println("Foo.value: " + Foo.VALUE); + System.out.println("Bar.value: " + bar.Bar.generateHtml(barText)); + } - public static void main(String[] args) throws Exception { - ArgumentParser parser = ArgumentParsers.newFor("Foo").build(); - parser.addArgument("--foo-text").required(true); - parser.addArgument("--bar-text").required(true); + public static void main(String[] args) throws Exception { + ArgumentParser parser = ArgumentParsers.newFor("Foo").build(); + parser.addArgument("--foo-text").required(true); + parser.addArgument("--bar-text").required(true); - Namespace res = parser.parseArgs(args); + Namespace res = parser.parseArgs(args); - String fooText = res.getString("foo_text"); - String barText = res.getString("bar_text"); + String fooText = res.getString("foo_text"); + String barText = res.getString("bar_text"); - mainFunction(fooText, barText); - } + mainFunction(fooText, barText); + } } - diff --git a/example/javalib/basic/4-compat-modules/bar/src/main/java/bar/Bar.java b/example/javalib/basic/4-compat-modules/bar/src/main/java/bar/Bar.java index c309ec7b2b1..d7a1769aebb 100644 --- a/example/javalib/basic/4-compat-modules/bar/src/main/java/bar/Bar.java +++ b/example/javalib/basic/4-compat-modules/bar/src/main/java/bar/Bar.java @@ -4,4 +4,4 @@ public class Bar { public static void main(String[] args) { System.out.println("Bar.value: " + Bar.value); } -} \ No newline at end of file +} diff --git a/example/javalib/basic/4-compat-modules/build.mill b/example/javalib/basic/4-compat-modules/build.mill index 49624650348..6a469b3b6c2 100644 --- a/example/javalib/basic/4-compat-modules/build.mill +++ b/example/javalib/basic/4-compat-modules/build.mill @@ -12,7 +12,6 @@ object foo extends MavenModule { object test extends MavenTests with TestModule.Junit4 } - // `MavenModule` is a variant of `JavaModule` // that uses the more verbose folder layout of Maven, SBT, and other tools: // @@ -42,4 +41,4 @@ compiling 1 Java source... > mill foo.test ...foo.FooTests.hello ... -*/ \ No newline at end of file +*/ diff --git a/example/javalib/basic/4-compat-modules/foo/src/main/java/foo/Foo.java b/example/javalib/basic/4-compat-modules/foo/src/main/java/foo/Foo.java index 2a23172eb1d..b695cd0836b 100644 --- a/example/javalib/basic/4-compat-modules/foo/src/main/java/foo/Foo.java +++ b/example/javalib/basic/4-compat-modules/foo/src/main/java/foo/Foo.java @@ -8,4 +8,4 @@ public static void main(String[] args) { public static String hello() { return "Hello World"; } -} \ No newline at end of file +} diff --git a/example/javalib/basic/4-compat-modules/foo/src/test/java/foo/FooTests.java b/example/javalib/basic/4-compat-modules/foo/src/test/java/foo/FooTests.java index fde78a85abf..567e06f8c3c 100644 --- a/example/javalib/basic/4-compat-modules/foo/src/test/java/foo/FooTests.java +++ b/example/javalib/basic/4-compat-modules/foo/src/test/java/foo/FooTests.java @@ -11,4 +11,4 @@ public void hello() { String result = Foo.hello(); assertEquals("Hello World", result); } -} \ No newline at end of file +} diff --git a/example/javalib/basic/5-builtin-commands/bar/src/bar/Bar.java b/example/javalib/basic/5-builtin-commands/bar/src/bar/Bar.java index e51f1e6519e..75b569dc909 100644 --- a/example/javalib/basic/5-builtin-commands/bar/src/bar/Bar.java +++ b/example/javalib/basic/5-builtin-commands/bar/src/bar/Bar.java @@ -2,18 +2,15 @@ import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; -import net.sourceforge.argparse4j.ArgumentParsers; -import net.sourceforge.argparse4j.inf.ArgumentParser; -import net.sourceforge.argparse4j.inf.Namespace; public class Bar { - public static String generateHtml(String text){ - Context context = new Context(); - context.setVariable("text", text); - return new TemplateEngine().process("

", context); - } + public static String generateHtml(String text) { + Context context = new Context(); + context.setVariable("text", text); + return new TemplateEngine().process("

", context); + } - public static void main(String[] args) { - System.out.println("Bar.value: " + generateHtml(args[0])); - } + public static void main(String[] args) { + System.out.println("Bar.value: " + generateHtml(args[0])); + } } diff --git a/example/javalib/basic/5-builtin-commands/bar/test/src/bar/BarTest.java b/example/javalib/basic/5-builtin-commands/bar/test/src/bar/BarTest.java index d790eb94f27..b3426bd59f1 100644 --- a/example/javalib/basic/5-builtin-commands/bar/test/src/bar/BarTest.java +++ b/example/javalib/basic/5-builtin-commands/bar/test/src/bar/BarTest.java @@ -1,19 +1,20 @@ package bar; import static org.junit.Assert.assertEquals; + import org.junit.Test; public class BarTests { - @Test - public void testSimple() { - String result = Bar.generateHtml("hello"); - assertEquals("

hello

", result); - } + @Test + public void testSimple() { + String result = Bar.generateHtml("hello"); + assertEquals("

hello

", result); + } - @Test - public void testEscaping() { - String result = Bar.generateHtml(""); - assertEquals("

<hello>

", result); - } -} \ No newline at end of file + @Test + public void testEscaping() { + String result = Bar.generateHtml(""); + assertEquals("

<hello>

", result); + } +} diff --git a/example/javalib/basic/5-builtin-commands/build.mill b/example/javalib/basic/5-builtin-commands/build.mill index 51c535243d3..47886619c3c 100644 --- a/example/javalib/basic/5-builtin-commands/build.mill +++ b/example/javalib/basic/5-builtin-commands/build.mill @@ -2,21 +2,20 @@ package build import mill._, javalib._ -trait MyModule extends JavaModule{ +trait MyModule extends JavaModule { object test extends JavaTests with TestModule.Junit4 } -object foo extends MyModule{ +object foo extends MyModule { def moduleDeps = Seq(bar) def ivyDeps = Agg( - ivy"net.sourceforge.argparse4j:argparse4j:0.9.0", + ivy"net.sourceforge.argparse4j:argparse4j:0.9.0" ) } -object bar extends MyModule{ +object bar extends MyModule { def ivyDeps = Agg( ivy"net.sourceforge.argparse4j:argparse4j:0.9.0", ivy"org.thymeleaf:thymeleaf:3.1.1.RELEASE" ) } - diff --git a/example/javalib/basic/5-builtin-commands/foo/src/foo/Foo.java b/example/javalib/basic/5-builtin-commands/foo/src/foo/Foo.java index a57f5f830fd..89d0317a0d7 100644 --- a/example/javalib/basic/5-builtin-commands/foo/src/foo/Foo.java +++ b/example/javalib/basic/5-builtin-commands/foo/src/foo/Foo.java @@ -6,24 +6,23 @@ public class Foo { - public static final String VALUE = "hello"; + public static final String VALUE = "hello"; - public static void mainFunction(String fooText, String barText) { - System.out.println("Foo.value: " + Foo.VALUE); - System.out.println("Bar.value: " + bar.Bar.generateHtml(barText)); - } + public static void mainFunction(String fooText, String barText) { + System.out.println("Foo.value: " + Foo.VALUE); + System.out.println("Bar.value: " + bar.Bar.generateHtml(barText)); + } - public static void main(String[] args) throws Exception { - ArgumentParser parser = ArgumentParsers.newFor("Foo").build(); - parser.addArgument("--foo-text").required(true); - parser.addArgument("--bar-text").required(true); + public static void main(String[] args) throws Exception { + ArgumentParser parser = ArgumentParsers.newFor("Foo").build(); + parser.addArgument("--foo-text").required(true); + parser.addArgument("--bar-text").required(true); - Namespace res = parser.parseArgs(args); + Namespace res = parser.parseArgs(args); - String fooText = res.getString("foo_text"); - String barText = res.getString("bar_text"); + String fooText = res.getString("foo_text"); + String barText = res.getString("bar_text"); - mainFunction(fooText, barText); - } + mainFunction(fooText, barText); + } } - diff --git a/example/javalib/basic/6-realistic/bar/src/bar/Bar.java b/example/javalib/basic/6-realistic/bar/src/bar/Bar.java index 3186c7c824b..f6dab346622 100644 --- a/example/javalib/basic/6-realistic/bar/src/bar/Bar.java +++ b/example/javalib/basic/6-realistic/bar/src/bar/Bar.java @@ -4,7 +4,7 @@ import org.thymeleaf.context.Context; public class Bar { - public static String value() { + public static String value() { Context context = new Context(); context.setVariable("text", "world"); return new TemplateEngine().process("

", context); diff --git a/example/javalib/basic/6-realistic/bar/test/src/bar/BarTests.java b/example/javalib/basic/6-realistic/bar/test/src/bar/BarTests.java index 3ce9410123a..74759a8b076 100644 --- a/example/javalib/basic/6-realistic/bar/test/src/bar/BarTests.java +++ b/example/javalib/basic/6-realistic/bar/test/src/bar/BarTests.java @@ -1,12 +1,13 @@ package bar; -import org.junit.Test; import static org.junit.Assert.assertEquals; +import org.junit.Test; + public class BarTests { @Test public void test() { assertEquals(Bar.value(), "

world

"); } -} \ No newline at end of file +} diff --git a/example/javalib/basic/6-realistic/foo/src/foo/Foo.java b/example/javalib/basic/6-realistic/foo/src/foo/Foo.java index 9ae1b46164a..bae2c0b2960 100644 --- a/example/javalib/basic/6-realistic/foo/src/foo/Foo.java +++ b/example/javalib/basic/6-realistic/foo/src/foo/Foo.java @@ -9,4 +9,4 @@ public static void main(String[] args) { System.out.println("Bar.value: " + bar.Bar.value()); System.out.println("Qux.value: " + qux.Qux.value); } -} \ No newline at end of file +} diff --git a/example/javalib/basic/6-realistic/foo/test/src/foo/FooTests.java b/example/javalib/basic/6-realistic/foo/test/src/foo/FooTests.java index a568625f695..288d12e7cb9 100644 --- a/example/javalib/basic/6-realistic/foo/test/src/foo/FooTests.java +++ b/example/javalib/basic/6-realistic/foo/test/src/foo/FooTests.java @@ -1,12 +1,13 @@ package foo; -import org.junit.Test; import static org.junit.Assert.assertEquals; +import org.junit.Test; + public class FooTests { @Test public void test() { assertEquals(Foo.value, "

hello

"); } -} \ No newline at end of file +} diff --git a/example/javalib/basic/6-realistic/qux/src/qux/Qux.java b/example/javalib/basic/6-realistic/qux/src/qux/Qux.java index bf88526d57c..9fc071c04ee 100644 --- a/example/javalib/basic/6-realistic/qux/src/qux/Qux.java +++ b/example/javalib/basic/6-realistic/qux/src/qux/Qux.java @@ -1,7 +1,9 @@ package qux; -public class Qux{ - public static final int value = 31337; - public static void main(String[] args){ - System.out.println("Qux.value: " + Qux.value); - } + +public class Qux { + public static final int value = 31337; + + public static void main(String[] args) { + System.out.println("Qux.value: " + Qux.value); + } } diff --git a/example/javalib/dependencies/1-ivy-deps/build.mill b/example/javalib/dependencies/1-ivy-deps/build.mill index e92c33c1fc6..d611fdffa6e 100644 --- a/example/javalib/dependencies/1-ivy-deps/build.mill +++ b/example/javalib/dependencies/1-ivy-deps/build.mill @@ -4,7 +4,7 @@ import mill._, javalib._ object `package` extends RootModule with JavaModule { def ivyDeps = Agg( - ivy"com.fasterxml.jackson.core:jackson-databind:2.13.4", + ivy"com.fasterxml.jackson.core:jackson-databind:2.13.4" ) } diff --git a/example/javalib/dependencies/1-ivy-deps/src/foo/Foo.java b/example/javalib/dependencies/1-ivy-deps/src/foo/Foo.java index 033f55cd3ca..52ccbe2b325 100644 --- a/example/javalib/dependencies/1-ivy-deps/src/foo/Foo.java +++ b/example/javalib/dependencies/1-ivy-deps/src/foo/Foo.java @@ -1,10 +1,9 @@ package foo; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; public class Foo { - public static void main(String[] args) throws Exception{ + public static void main(String[] args) throws Exception { System.out.println("JSONified using Jackson: " + new ObjectMapper().writeValueAsString(args)); } -} \ No newline at end of file +} diff --git a/example/javalib/dependencies/2-run-compile-deps/bar/src/bar/Bar.java b/example/javalib/dependencies/2-run-compile-deps/bar/src/bar/Bar.java index 6cd8c366bc7..38751f60787 100644 --- a/example/javalib/dependencies/2-run-compile-deps/bar/src/bar/Bar.java +++ b/example/javalib/dependencies/2-run-compile-deps/bar/src/bar/Bar.java @@ -1,17 +1,18 @@ package bar; +import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; class BarServlet extends HttpServlet { @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("Hello World!"); @@ -28,4 +29,4 @@ public static void main(String[] args) throws Exception { server.start(); server.join(); } -} \ No newline at end of file +} diff --git a/example/javalib/dependencies/2-run-compile-deps/build.mill b/example/javalib/dependencies/2-run-compile-deps/build.mill index aba7f71d1b2..25ff49a6c52 100644 --- a/example/javalib/dependencies/2-run-compile-deps/build.mill +++ b/example/javalib/dependencies/2-run-compile-deps/build.mill @@ -23,4 +23,3 @@ object bar extends JavaModule { } //// SNIPPET:SCALASTEWARD - diff --git a/example/javalib/dependencies/2-run-compile-deps/foo/src/foo/Foo.java b/example/javalib/dependencies/2-run-compile-deps/foo/src/foo/Foo.java index 8a80fa42a25..6bfe37e30c1 100644 --- a/example/javalib/dependencies/2-run-compile-deps/foo/src/foo/Foo.java +++ b/example/javalib/dependencies/2-run-compile-deps/foo/src/foo/Foo.java @@ -4,4 +4,4 @@ public class Foo { public static void main(String[] args) { System.out.println("Hello World"); } -} \ No newline at end of file +} diff --git a/example/javalib/dependencies/3-unmanaged-jars/src/foo/Foo.java b/example/javalib/dependencies/3-unmanaged-jars/src/foo/Foo.java index 85cea22a4b7..238ebcbed04 100644 --- a/example/javalib/dependencies/3-unmanaged-jars/src/foo/Foo.java +++ b/example/javalib/dependencies/3-unmanaged-jars/src/foo/Foo.java @@ -1,12 +1,12 @@ package foo; -import com.grack.nanojson.JsonParser; import com.grack.nanojson.JsonObject; +import com.grack.nanojson.JsonParser; import java.util.Map; public class Foo { - public static void main(String[] args) throws Exception{ + public static void main(String[] args) throws Exception { String jsonString = args[0]; JsonObject jsonObj = JsonParser.object().from(jsonString); @@ -14,4 +14,4 @@ public static void main(String[] args) throws Exception{ System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()); } } -} \ No newline at end of file +} diff --git a/example/javalib/dependencies/4-downloading-unmanaged-jars/build.mill b/example/javalib/dependencies/4-downloading-unmanaged-jars/build.mill index e6d97d04f76..e8c9341ba95 100644 --- a/example/javalib/dependencies/4-downloading-unmanaged-jars/build.mill +++ b/example/javalib/dependencies/4-downloading-unmanaged-jars/build.mill @@ -13,4 +13,3 @@ object `package` extends RootModule with JavaModule { Agg(PathRef(Task.dest / "fastjavaio.jar")) } } - diff --git a/example/javalib/dependencies/4-downloading-unmanaged-jars/src/foo/Foo.java b/example/javalib/dependencies/4-downloading-unmanaged-jars/src/foo/Foo.java index b81404077c5..ca16cb44ac6 100644 --- a/example/javalib/dependencies/4-downloading-unmanaged-jars/src/foo/Foo.java +++ b/example/javalib/dependencies/4-downloading-unmanaged-jars/src/foo/Foo.java @@ -1,31 +1,30 @@ package foo; import com.williamfiset.fastjavaio.InputReader; - import java.io.FileInputStream; import java.io.IOException; public class Foo { - public static void main(String[] args) { - String filePath = args[0]; - InputReader fi = null; + public static void main(String[] args) { + String filePath = args[0]; + InputReader fi = null; + try { + fi = new InputReader(new FileInputStream(filePath)); + String line; + while ((line = fi.nextLine()) != null) { + System.out.println(line); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (fi != null) { try { - fi = new InputReader(new FileInputStream(filePath)); - String line; - while ((line = fi.nextLine()) != null) { - System.out.println(line); - } + fi.close(); } catch (IOException e) { - e.printStackTrace(); - } finally { - if (fi != null) { - try { - fi.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } + e.printStackTrace(); } + } } -} \ No newline at end of file + } +} diff --git a/example/javalib/dependencies/5-repository-config/foo/src/foo/Foo.java b/example/javalib/dependencies/5-repository-config/foo/src/foo/Foo.java index a758c57d8b9..3785a77b602 100644 --- a/example/javalib/dependencies/5-repository-config/foo/src/foo/Foo.java +++ b/example/javalib/dependencies/5-repository-config/foo/src/foo/Foo.java @@ -8,9 +8,8 @@ public class Foo { - public static void main(String[] args) throws Exception{ - ArgumentParser parser = ArgumentParsers.newFor("Foo").build() - .defaultHelp(true); + public static void main(String[] args) throws Exception { + ArgumentParser parser = ArgumentParsers.newFor("Foo").build().defaultHelp(true); parser.addArgument("--text"); diff --git a/example/javalib/linting/1-error-prone/build.mill b/example/javalib/linting/1-error-prone/build.mill index 645feb1883a..542b3030959 100644 --- a/example/javalib/linting/1-error-prone/build.mill +++ b/example/javalib/linting/1-error-prone/build.mill @@ -3,8 +3,6 @@ // `ErrorProneModule`: mix `ErrorProneModule` into your `JavaModule` and it will // automatically run with every compilation. - - package build import mill._, javalib._, errorprone._ @@ -59,4 +57,4 @@ object `package` extends RootModule with JavaModule with ErrorProneModule { // `def errorProneOptions: T[Seq[String]]`:: // Options directly given to the `error-prone` processor. // Those are documented as "flags" at https://errorprone.info/docs/flags -// \ No newline at end of file +// diff --git a/example/javalib/linting/1-error-prone/src/example/ShortSet.java b/example/javalib/linting/1-error-prone/src/example/ShortSet.java index deb61d116ee..d2343ee3783 100644 --- a/example/javalib/linting/1-error-prone/src/example/ShortSet.java +++ b/example/javalib/linting/1-error-prone/src/example/ShortSet.java @@ -4,7 +4,7 @@ import java.util.Set; public class ShortSet { - public static void main (String[] args) { + public static void main(String[] args) { Set s = new HashSet<>(); for (short i = 0; i < 100; i++) { s.add(i); @@ -13,4 +13,3 @@ public static void main (String[] args) { System.out.println(s.size()); } } - diff --git a/example/javalib/linting/2-checkstyle/build.mill b/example/javalib/linting/2-checkstyle/build.mill index 8901e719660..07791bd0ac5 100644 --- a/example/javalib/linting/2-checkstyle/build.mill +++ b/example/javalib/linting/2-checkstyle/build.mill @@ -8,7 +8,6 @@ object `package` extends RootModule with CheckstyleModule { def checkstyleVersion = "9.3" } - // To use this plugin in a Java/Scala module, // // 1. Extend `mill.contrib.checkstyle.CheckstyleModule`. @@ -157,4 +156,4 @@ Audit done. // } // } // ---- -// \ No newline at end of file +// diff --git a/example/javalib/linting/3-palantirformat/build.mill b/example/javalib/linting/3-palantirformat/build.mill index 6bd6ae0117c..fc795c11f9e 100644 --- a/example/javalib/linting/3-palantirformat/build.mill +++ b/example/javalib/linting/3-palantirformat/build.mill @@ -14,7 +14,6 @@ object `package` extends RootModule with PalantirFormatModule // You can also use `--check` if you wish to error if the code is not formatted, // which is useful in CI validation jobs to ensure code is formatted before merging. - /** Usage > ./mill palantirformat --check # check should fail initially @@ -39,4 +38,4 @@ error: ...palantirformat aborted due to format error(s) (or invalid plugin setti // If entering the long fully-qualified module name // `mill.javalib.palantirformat.PalantirFormatModule/` is tedious, you can add // an xref:fundamentals/modules.adoc#_aliasing_external_modules[External Module Alias] -// to give it a shorter name that's easier to type \ No newline at end of file +// to give it a shorter name that's easier to type diff --git a/example/javalib/module/1-common-config/build.mill b/example/javalib/module/1-common-config/build.mill index 7313a4a954a..08c86f7be89 100644 --- a/example/javalib/module/1-common-config/build.mill +++ b/example/javalib/module/1-common-config/build.mill @@ -12,18 +12,18 @@ object `package` extends RootModule with JavaModule { def mainClass: T[Option[String]] = Some("foo.Foo2") // Add (or replace) source folders for the module to use - def sources = Task.Sources{ + def sources = Task.Sources { super.sources() ++ Seq(PathRef(millSourcePath / "custom-src")) } // Add (or replace) resource folders for the module to use - def resources = Task.Sources{ + def resources = Task.Sources { super.resources() ++ Seq(PathRef(millSourcePath / "custom-resources")) } // Generate sources at build time def generatedSources: T[Seq[PathRef]] = Task { - for(name <- Seq("A", "B", "C")) os.write( + for (name <- Seq("A", "B", "C")) os.write( Task.dest / s"Foo$name.java", s""" |package foo; @@ -55,4 +55,4 @@ object `package` extends RootModule with JavaModule { // (right-click open in new tab to see full sized) // //// SNIPPET:FATAL_WARNINGS -// \ No newline at end of file +// diff --git a/example/javalib/module/1-common-config/custom-src/Foo2.java b/example/javalib/module/1-common-config/custom-src/Foo2.java index 889afc5e443..d71e1f80f18 100644 --- a/example/javalib/module/1-common-config/custom-src/Foo2.java +++ b/example/javalib/module/1-common-config/custom-src/Foo2.java @@ -1,18 +1,15 @@ package foo; -import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; import java.util.Properties; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; public class Foo2 { - public static final String value(){ - Context context = new Context(); - context.setVariable("text", "hello2"); - return new TemplateEngine().process("

", context); + public static final String value() { + Context context = new Context(); + context.setVariable("text", "hello2"); + return new TemplateEngine().process("

", context); } public static void main(String[] args) { @@ -38,8 +35,9 @@ public static void main(String[] args) { private static String readResource(String resourceName) { try { return new String( - Foo2.class.getClassLoader().getResourceAsStream(resourceName).readAllBytes() - ); - }catch (IOException e) { return null; } + Foo2.class.getClassLoader().getResourceAsStream(resourceName).readAllBytes()); + } catch (IOException e) { + return null; + } } } diff --git a/example/javalib/module/1-common-config/src/foo/Foo.java b/example/javalib/module/1-common-config/src/foo/Foo.java index 105392db3fd..79a25e5a861 100644 --- a/example/javalib/module/1-common-config/src/foo/Foo.java +++ b/example/javalib/module/1-common-config/src/foo/Foo.java @@ -1,13 +1,14 @@ package foo; + import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; public class Foo { - public static String value(){ - Context context = new Context(); - context.setVariable("text", "hello"); - return new TemplateEngine().process("

", context); - } + public static String value() { + Context context = new Context(); + context.setVariable("text", "hello"); + return new TemplateEngine().process("

", context); + } public static void main(String[] args) { System.out.println("Foo.value: " + Foo.value()); diff --git a/example/javalib/module/11-main-class/src/foo/Bar.java b/example/javalib/module/11-main-class/src/foo/Bar.java index 956ad303180..82b8d1030e7 100644 --- a/example/javalib/module/11-main-class/src/foo/Bar.java +++ b/example/javalib/module/11-main-class/src/foo/Bar.java @@ -5,4 +5,4 @@ public class Bar { public static void main(String[] args) { System.out.println("Hello Bar"); } -} \ No newline at end of file +} diff --git a/example/javalib/module/11-main-class/src/foo/Foo.java b/example/javalib/module/11-main-class/src/foo/Foo.java index b3203a05717..2b19bc0e42c 100644 --- a/example/javalib/module/11-main-class/src/foo/Foo.java +++ b/example/javalib/module/11-main-class/src/foo/Foo.java @@ -5,4 +5,4 @@ public class Foo { public static void main(String[] args) { System.out.println("Hello Foo"); } -} \ No newline at end of file +} diff --git a/example/javalib/module/11-main-class/src/foo/Qux.java b/example/javalib/module/11-main-class/src/foo/Qux.java index 29d510b9c6f..b59aeb07908 100644 --- a/example/javalib/module/11-main-class/src/foo/Qux.java +++ b/example/javalib/module/11-main-class/src/foo/Qux.java @@ -5,4 +5,4 @@ public class Qux { public static void main(String[] args) { System.out.println("Hello Qux"); } -} \ No newline at end of file +} diff --git a/example/javalib/module/13-assembly-config/build.mill b/example/javalib/module/13-assembly-config/build.mill index 1e9c8e1d8a8..fa4b2e4f7a0 100644 --- a/example/javalib/module/13-assembly-config/build.mill +++ b/example/javalib/module/13-assembly-config/build.mill @@ -17,5 +17,4 @@ object foo extends JavaModule { ) } -object bar extends JavaModule { -} +object bar extends JavaModule {} diff --git a/example/javalib/module/13-assembly-config/foo/src/foo/Foo.java b/example/javalib/module/13-assembly-config/foo/src/foo/Foo.java index 26874749137..87af722ed02 100644 --- a/example/javalib/module/13-assembly-config/foo/src/foo/Foo.java +++ b/example/javalib/module/13-assembly-config/foo/src/foo/Foo.java @@ -4,9 +4,9 @@ import java.io.InputStream; public class Foo { - public static void main(String[] args) throws IOException{ + public static void main(String[] args) throws IOException { InputStream inputStream = Foo.class.getClassLoader().getResourceAsStream("application.conf"); String conf = new String(inputStream.readAllBytes()); System.out.println("Loaded application.conf from resources: " + conf); } -} \ No newline at end of file +} diff --git a/example/javalib/module/15-jni/build.mill b/example/javalib/module/15-jni/build.mill index 711f343affa..f9fb34a1028 100644 --- a/example/javalib/module/15-jni/build.mill +++ b/example/javalib/module/15-jni/build.mill @@ -10,7 +10,14 @@ object `package` extends RootModule with JavaModule { // Auto-generate JNI `.h` files from Java classes using Javac def nativeHeaders = Task { - os.proc(Jvm.jdkTool("javac"), "-h", Task.dest, "-d", Task.dest.toString, allSourceFiles().map(_.path)).call() + os.proc( + Jvm.jdkTool("javac"), + "-h", + Task.dest, + "-d", + Task.dest.toString, + allSourceFiles().map(_.path) + ).call() PathRef(Task.dest) } @@ -19,14 +26,17 @@ object `package` extends RootModule with JavaModule { val cSourceFiles = nativeSources().map(_.path).flatMap(os.walk(_)).filter(_.ext == "c") val output = "libhelloworld.so" os.proc( - "clang", "-shared", "-fPIC", - "-I" + nativeHeaders().path, // - "-I" + sys.props("java.home") + "/include/", // global JVM header files - "-I" + sys.props("java.home") + "/include/darwin", - "-I" + sys.props("java.home") + "/include/linux", - "-o", Task.dest / output, - cSourceFiles - ) + "clang", + "-shared", + "-fPIC", + "-I" + nativeHeaders().path, // + "-I" + sys.props("java.home") + "/include/", // global JVM header files + "-I" + sys.props("java.home") + "/include/darwin", + "-I" + sys.props("java.home") + "/include/linux", + "-o", + Task.dest / output, + cSourceFiles + ) .call(stdout = os.Inherit) PathRef(Task.dest / output) @@ -34,7 +44,7 @@ object `package` extends RootModule with JavaModule { def forkEnv = Map("HELLO_WORLD_BINARY" -> nativeCompiled().path.toString) - object test extends JavaTests with TestModule.Junit4{ + object test extends JavaTests with TestModule.Junit4 { def forkEnv = Map("HELLO_WORLD_BINARY" -> nativeCompiled().path.toString) } } diff --git a/example/javalib/module/15-jni/src/foo/HelloWorld.java b/example/javalib/module/15-jni/src/foo/HelloWorld.java index c8d3b0ce933..83d91e6ca3b 100644 --- a/example/javalib/module/15-jni/src/foo/HelloWorld.java +++ b/example/javalib/module/15-jni/src/foo/HelloWorld.java @@ -1,16 +1,16 @@ package foo; public class HelloWorld { - // Declare a native method - public native String sayHello(); + // Declare a native method + public native String sayHello(); - // Load the native library - static { - System.load(System.getenv("HELLO_WORLD_BINARY")); - } + // Load the native library + static { + System.load(System.getenv("HELLO_WORLD_BINARY")); + } - public static void main(String[] args) { - HelloWorld helloWorld = new HelloWorld(); - System.out.println(helloWorld.sayHello()); - } -} \ No newline at end of file + public static void main(String[] args) { + HelloWorld helloWorld = new HelloWorld(); + System.out.println(helloWorld.sayHello()); + } +} diff --git a/example/javalib/module/15-jni/test/src/foo/HelloWorldTest.java b/example/javalib/module/15-jni/test/src/foo/HelloWorldTest.java index 46c5528656b..d0eff2b5abd 100644 --- a/example/javalib/module/15-jni/test/src/foo/HelloWorldTest.java +++ b/example/javalib/module/15-jni/test/src/foo/HelloWorldTest.java @@ -1,10 +1,12 @@ package foo; + import static org.junit.Assert.assertEquals; + import org.junit.Test; public class HelloWorldTest { - @Test - public void testSimple() { - assertEquals(new HelloWorld().sayHello(), "Hello, World!"); - } + @Test + public void testSimple() { + assertEquals(new HelloWorld().sayHello(), "Hello, World!"); + } } diff --git a/example/javalib/module/2-custom-tasks/build.mill b/example/javalib/module/2-custom-tasks/build.mill index 35bb7e1b588..ff530dc1b50 100644 --- a/example/javalib/module/2-custom-tasks/build.mill +++ b/example/javalib/module/2-custom-tasks/build.mill @@ -6,7 +6,7 @@ object `package` extends RootModule with JavaModule { def ivyDeps = Agg(ivy"net.sourceforge.argparse4j:argparse4j:0.9.0") def generatedSources: T[Seq[PathRef]] = Task { - val prettyIvyDeps = for(ivyDep <- ivyDeps()) yield { + val prettyIvyDeps = for (ivyDep <- ivyDeps()) yield { val org = ivyDep.dep.module.organization.value val name = ivyDep.dep.module.name.value val version = ivyDep.dep.version @@ -47,11 +47,11 @@ object `package` extends RootModule with JavaModule { > mill run --text hello text: hello MyDeps.value: net.sourceforge.argparse4j:argparse4j:0.9.0 -my.line.count: 24 +my.line.count: 22 > mill show lineCount -24 +22 > mill printLineCount -24 -*/ \ No newline at end of file +22 +*/ diff --git a/example/javalib/module/2-custom-tasks/src/foo/Foo.java b/example/javalib/module/2-custom-tasks/src/foo/Foo.java index 532f98b1536..a83e3959aad 100644 --- a/example/javalib/module/2-custom-tasks/src/foo/Foo.java +++ b/example/javalib/module/2-custom-tasks/src/foo/Foo.java @@ -2,17 +2,15 @@ import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; -import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; public class Foo { public static void main(String[] args) throws Exception { - ArgumentParser parser = ArgumentParsers.newFor("Foo").build() - .defaultHelp(true) - .description("Process some integers."); - parser.addArgument("-t", "--text") - .required(true) - .help("input text"); + ArgumentParser parser = ArgumentParsers.newFor("Foo") + .build() + .defaultHelp(true) + .description("Process some integers."); + parser.addArgument("-t", "--text").required(true).help("input text"); Namespace res = parser.parseArgs(args); String text = res.getString("text"); diff --git a/example/javalib/module/4-compilation-execution-flags/build.mill b/example/javalib/module/4-compilation-execution-flags/build.mill index 1703912a7a5..4bf522efd5a 100644 --- a/example/javalib/module/4-compilation-execution-flags/build.mill +++ b/example/javalib/module/4-compilation-execution-flags/build.mill @@ -2,7 +2,7 @@ package build import mill._, javalib._ -object `package` extends RootModule with JavaModule{ +object `package` extends RootModule with JavaModule { def forkArgs = Seq("-Xmx4g", "-Dmy.jvm.property=hello") def forkEnv = Map("MY_ENV_VAR" -> "WORLD") def javacOptions = Seq("-deprecation") @@ -20,4 +20,4 @@ hello WORLD */ -//// SNIPPET:END \ No newline at end of file +//// SNIPPET:END diff --git a/example/javalib/module/7-resources/foo/src/Foo.java b/example/javalib/module/7-resources/foo/src/Foo.java index a57cab9c41d..deb5b9fa442 100644 --- a/example/javalib/module/7-resources/foo/src/Foo.java +++ b/example/javalib/module/7-resources/foo/src/Foo.java @@ -12,4 +12,4 @@ public static String classpathResourceText() throws IOException { return new String(inputStream.readAllBytes()); } } -} \ No newline at end of file +} diff --git a/example/javalib/module/7-resources/foo/test/src/FooTests.java b/example/javalib/module/7-resources/foo/test/src/FooTests.java index fcf3f5773eb..3ab0b55561c 100644 --- a/example/javalib/module/7-resources/foo/test/src/FooTests.java +++ b/example/javalib/module/7-resources/foo/test/src/FooTests.java @@ -1,15 +1,15 @@ package foo; -import org.junit.Test; import static org.junit.Assert.*; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; import java.nio.file.Files; -import java.nio.file.Paths; import java.nio.file.Path; -import java.util.List; +import java.nio.file.Paths; import java.util.ArrayList; +import java.util.List; +import org.junit.Test; public class FooTests { @@ -21,32 +21,29 @@ public void simple() throws IOException { // Read `test-file-a.txt` from classpath String testClasspathResourceText; - try (InputStream inputStream = Foo.class.getClassLoader().getResourceAsStream("test-file-a.txt")) { + try (InputStream inputStream = + Foo.class.getClassLoader().getResourceAsStream("test-file-a.txt")) { testClasspathResourceText = new String(inputStream.readAllBytes()); } assertEquals("Test Hello World Resource File A", testClasspathResourceText); // Use `MILL_TEST_RESOURCE_DIR` to read `test-file-b.txt` from filesystem Path testFileResourceDir = Paths.get(System.getenv("MILL_TEST_RESOURCE_DIR")); - String testFileResourceText = Files.readString( - testFileResourceDir.resolve("test-file-b.txt") - ); + String testFileResourceText = Files.readString(testFileResourceDir.resolve("test-file-b.txt")); assertEquals("Test Hello World Resource File B", testFileResourceText); // Use `MILL_TEST_RESOURCE_DIR` to list files available in resource folder List actualFiles = new ArrayList<>(Files.list(testFileResourceDir).toList()); actualFiles.sort(Path::compareTo); List expectedFiles = List.of( - testFileResourceDir.resolve("test-file-a.txt"), - testFileResourceDir.resolve("test-file-b.txt") - ); + testFileResourceDir.resolve("test-file-a.txt"), + testFileResourceDir.resolve("test-file-b.txt")); assertEquals(expectedFiles, actualFiles); // Use the `OTHER_FILES_DIR` configured in your build to access the // files in `foo/test/other-files/`. - String otherFileText = Files.readString( - Paths.get(System.getenv("OTHER_FILES_DIR"), "other-file.txt") - ); + String otherFileText = + Files.readString(Paths.get(System.getenv("OTHER_FILES_DIR"), "other-file.txt")); assertEquals("Other Hello World File", otherFileText); } } diff --git a/example/javalib/module/8-annotation-processors/bar/src/bar/GetterSetterExample.java b/example/javalib/module/8-annotation-processors/bar/src/bar/GetterSetterExample.java index b4345030525..091280b45e1 100644 --- a/example/javalib/module/8-annotation-processors/bar/src/bar/GetterSetterExample.java +++ b/example/javalib/module/8-annotation-processors/bar/src/bar/GetterSetterExample.java @@ -1,4 +1,5 @@ package bar; + import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @@ -6,22 +7,26 @@ public class GetterSetterExample { /** * Age of the person. Water is wet. - * + * * @param age New value for this person's age. Sky is blue. * @return The current value of this person's age. Circles are round. */ - @Getter @Setter private int age = 10; - + @Getter + @Setter + private int age = 10; + /** * Name of the person. * -- SETTER -- * Changes the name of this person. - * + * * @param name The new value. */ - @Setter(AccessLevel.PROTECTED) private String name; - - @Override public String toString() { + @Setter(AccessLevel.PROTECTED) + private String name; + + @Override + public String toString() { return String.format("%s (age: %d)", name, age); } -} \ No newline at end of file +} diff --git a/example/javalib/module/8-annotation-processors/bar/test/src/bar/HelloWorldTest.java b/example/javalib/module/8-annotation-processors/bar/test/src/bar/HelloWorldTest.java index 9fa7223e308..4ee201bdcf5 100644 --- a/example/javalib/module/8-annotation-processors/bar/test/src/bar/HelloWorldTest.java +++ b/example/javalib/module/8-annotation-processors/bar/test/src/bar/HelloWorldTest.java @@ -1,13 +1,15 @@ package bar; + import static org.junit.Assert.assertEquals; + import org.junit.Test; public class HelloWorldTest { - @Test - public void testSimple() { - GetterSetterExample exampleValue = new GetterSetterExample(); - assertEquals(exampleValue.getAge(), 10); - exampleValue.setAge(20); - assertEquals(exampleValue.getAge(), 20); - } + @Test + public void testSimple() { + GetterSetterExample exampleValue = new GetterSetterExample(); + assertEquals(exampleValue.getAge(), 10); + exampleValue.setAge(20); + assertEquals(exampleValue.getAge(), 20); + } } diff --git a/example/javalib/module/8-annotation-processors/build.mill b/example/javalib/module/8-annotation-processors/build.mill index edda35f7c64..05779cc3d60 100644 --- a/example/javalib/module/8-annotation-processors/build.mill +++ b/example/javalib/module/8-annotation-processors/build.mill @@ -42,7 +42,7 @@ object bar extends JavaModule { def javacOptions = Seq( "-processorpath", - processors().map(_.path).mkString(File.pathSeparator), + processors().map(_.path).mkString(File.pathSeparator) ) object test extends JavaTests with TestModule.Junit4 diff --git a/example/javalib/module/8-annotation-processors/foo/src/foo/GetterSetterExample.java b/example/javalib/module/8-annotation-processors/foo/src/foo/GetterSetterExample.java index 7266a36e5d7..79113c988cc 100644 --- a/example/javalib/module/8-annotation-processors/foo/src/foo/GetterSetterExample.java +++ b/example/javalib/module/8-annotation-processors/foo/src/foo/GetterSetterExample.java @@ -1,4 +1,5 @@ package foo; + import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @@ -6,22 +7,26 @@ public class GetterSetterExample { /** * Age of the person. Water is wet. - * + * * @param age New value for this person's age. Sky is blue. * @return The current value of this person's age. Circles are round. */ - @Getter @Setter private int age = 10; - + @Getter + @Setter + private int age = 10; + /** * Name of the person. * -- SETTER -- * Changes the name of this person. - * + * * @param name The new value. */ - @Setter(AccessLevel.PROTECTED) private String name; - - @Override public String toString() { + @Setter(AccessLevel.PROTECTED) + private String name; + + @Override + public String toString() { return String.format("%s (age: %d)", name, age); } -} \ No newline at end of file +} diff --git a/example/javalib/module/8-annotation-processors/foo/test/src/foo/HelloWorldTest.java b/example/javalib/module/8-annotation-processors/foo/test/src/foo/HelloWorldTest.java index 544d1d7581d..853e050b419 100644 --- a/example/javalib/module/8-annotation-processors/foo/test/src/foo/HelloWorldTest.java +++ b/example/javalib/module/8-annotation-processors/foo/test/src/foo/HelloWorldTest.java @@ -1,13 +1,15 @@ package foo; + import static org.junit.Assert.assertEquals; + import org.junit.Test; public class HelloWorldTest { - @Test - public void testSimple() { - GetterSetterExample exampleValue = new GetterSetterExample(); - assertEquals(exampleValue.getAge(), 10); - exampleValue.setAge(20); - assertEquals(exampleValue.getAge(), 20); - } + @Test + public void testSimple() { + GetterSetterExample exampleValue = new GetterSetterExample(); + assertEquals(exampleValue.getAge(), 10); + exampleValue.setAge(20); + assertEquals(exampleValue.getAge(), 20); + } } diff --git a/example/javalib/module/9-docjar/build.mill b/example/javalib/module/9-docjar/build.mill index ebc6d1c6029..e8af95360ed 100644 --- a/example/javalib/module/9-docjar/build.mill +++ b/example/javalib/module/9-docjar/build.mill @@ -6,7 +6,6 @@ object foo extends JavaModule { def javadocOptions = Seq("-quiet") } - /** Usage > ./mill show foo.docJar @@ -18,4 +17,3 @@ object foo extends JavaModule { */ //// SNIPPET:SCALA3 - diff --git a/example/javalib/module/9-docjar/foo/src/foo/Foo.java b/example/javalib/module/9-docjar/foo/src/foo/Foo.java index f06f5982322..585ac18916a 100644 --- a/example/javalib/module/9-docjar/foo/src/foo/Foo.java +++ b/example/javalib/module/9-docjar/foo/src/foo/Foo.java @@ -7,4 +7,4 @@ public class Foo { public void run() { System.out.println("running Foo"); } -} \ No newline at end of file +} diff --git a/example/javalib/publishing/2-publish-module/foo/src/foo/Foo.java b/example/javalib/publishing/2-publish-module/foo/src/foo/Foo.java index 8a80fa42a25..6bfe37e30c1 100644 --- a/example/javalib/publishing/2-publish-module/foo/src/foo/Foo.java +++ b/example/javalib/publishing/2-publish-module/foo/src/foo/Foo.java @@ -4,4 +4,4 @@ public class Foo { public static void main(String[] args) { System.out.println("Hello World"); } -} \ No newline at end of file +} diff --git a/example/javalib/testing/1-test-suite/bar/src/bar/Bar.java b/example/javalib/testing/1-test-suite/bar/src/bar/Bar.java index 45d4791612f..b4392f7cb89 100644 --- a/example/javalib/testing/1-test-suite/bar/src/bar/Bar.java +++ b/example/javalib/testing/1-test-suite/bar/src/bar/Bar.java @@ -8,4 +8,4 @@ public static void main(String[] args) { public String hello() { return "Hello World"; } -} \ No newline at end of file +} diff --git a/example/javalib/testing/1-test-suite/bar/test/src/bar/BarTests.java b/example/javalib/testing/1-test-suite/bar/test/src/bar/BarTests.java index 7b0d7d358ba..51988209426 100644 --- a/example/javalib/testing/1-test-suite/bar/test/src/bar/BarTests.java +++ b/example/javalib/testing/1-test-suite/bar/test/src/bar/BarTests.java @@ -2,6 +2,7 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; + import org.junit.Test; public class BarTests { @@ -29,4 +30,4 @@ public void testMockito() { assertTrue(result.equals("Hello Mockito World")); verify(mockBar).hello(); } -} \ No newline at end of file +} diff --git a/example/javalib/testing/1-test-suite/build.mill b/example/javalib/testing/1-test-suite/build.mill index 19f0f6fc653..e197f3955be 100644 --- a/example/javalib/testing/1-test-suite/build.mill +++ b/example/javalib/testing/1-test-suite/build.mill @@ -17,10 +17,9 @@ object foo extends JavaModule { //// SNIPPET:BUILD2 object bar extends JavaModule { - object test extends JavaTests with TestModule.Junit4{ + object test extends JavaTests with TestModule.Junit4 { def ivyDeps = super.ivyDeps() ++ Agg( ivy"org.mockito:mockito-core:4.6.1" ) } } - diff --git a/example/javalib/testing/1-test-suite/foo/src/foo/Foo.java b/example/javalib/testing/1-test-suite/foo/src/foo/Foo.java index 6495735bf03..ba912ebcce9 100644 --- a/example/javalib/testing/1-test-suite/foo/src/foo/Foo.java +++ b/example/javalib/testing/1-test-suite/foo/src/foo/Foo.java @@ -8,4 +8,4 @@ public static void main(String[] args) { public String hello() { return "Hello World"; } -} \ No newline at end of file +} diff --git a/example/javalib/testing/1-test-suite/foo/test/src/foo/FooTests.java b/example/javalib/testing/1-test-suite/foo/test/src/foo/FooTests.java index ec2c09987e7..4f71ead8435 100644 --- a/example/javalib/testing/1-test-suite/foo/test/src/foo/FooTests.java +++ b/example/javalib/testing/1-test-suite/foo/test/src/foo/FooTests.java @@ -2,6 +2,7 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; + import org.junit.Test; public class FooTests { @@ -29,4 +30,4 @@ public void testMockito() { assertTrue(result.equals("Hello Mockito World")); verify(mockFoo).hello(); } -} \ No newline at end of file +} diff --git a/example/javalib/testing/2-test-deps/baz/src/baz/Baz.java b/example/javalib/testing/2-test-deps/baz/src/baz/Baz.java index 67a1378168e..a863babe4bb 100644 --- a/example/javalib/testing/2-test-deps/baz/src/baz/Baz.java +++ b/example/javalib/testing/2-test-deps/baz/src/baz/Baz.java @@ -4,4 +4,4 @@ public class Baz { public static int getValue() { return 123; } -} \ No newline at end of file +} diff --git a/example/javalib/testing/2-test-deps/baz/test/src/baz/BazTestUtils.java b/example/javalib/testing/2-test-deps/baz/test/src/baz/BazTestUtils.java index 81caf360735..7dfcb001045 100644 --- a/example/javalib/testing/2-test-deps/baz/test/src/baz/BazTestUtils.java +++ b/example/javalib/testing/2-test-deps/baz/test/src/baz/BazTestUtils.java @@ -8,4 +8,4 @@ public static void bazAssertEquals(Object x, Object y) { throw new AssertionError("Expected " + y + " but got " + x); } } -} \ No newline at end of file +} diff --git a/example/javalib/testing/2-test-deps/baz/test/src/baz/BazTests.java b/example/javalib/testing/2-test-deps/baz/test/src/baz/BazTests.java index 68760f3ca86..ae26287bac3 100644 --- a/example/javalib/testing/2-test-deps/baz/test/src/baz/BazTests.java +++ b/example/javalib/testing/2-test-deps/baz/test/src/baz/BazTests.java @@ -1,14 +1,14 @@ package baz; -import org.junit.Test; -import com.google.common.math.IntMath; - import static org.junit.Assert.*; +import com.google.common.math.IntMath; +import org.junit.Test; + public class BazTests { @Test public void simple() { BazTestUtils.bazAssertEquals(Baz.getValue(), IntMath.mean(122, 124)); } -} \ No newline at end of file +} diff --git a/example/javalib/testing/2-test-deps/qux/src/qux/Qux.java b/example/javalib/testing/2-test-deps/qux/src/qux/Qux.java index 0fd963e6e88..495352285b3 100644 --- a/example/javalib/testing/2-test-deps/qux/src/qux/Qux.java +++ b/example/javalib/testing/2-test-deps/qux/src/qux/Qux.java @@ -4,4 +4,4 @@ public class Qux { public static String getValue() { return "xyz"; } -} \ No newline at end of file +} diff --git a/example/javalib/testing/2-test-deps/qux/test/src/qux/QuxTests.java b/example/javalib/testing/2-test-deps/qux/test/src/qux/QuxTests.java index 3aecbb5ec48..0e910b8c536 100644 --- a/example/javalib/testing/2-test-deps/qux/test/src/qux/QuxTests.java +++ b/example/javalib/testing/2-test-deps/qux/test/src/qux/QuxTests.java @@ -1,7 +1,7 @@ package qux; -import org.junit.Test; import com.google.common.base.Ascii; +import org.junit.Test; public class QuxTests { @@ -9,4 +9,4 @@ public class QuxTests { public void simple() { baz.BazTestUtils.bazAssertEquals(Ascii.toLowerCase("XYZ"), Qux.getValue()); } -} \ No newline at end of file +} diff --git a/example/javalib/testing/3-integration-suite/qux/integration/src/qux/QuxIntegrationTests.java b/example/javalib/testing/3-integration-suite/qux/integration/src/qux/QuxIntegrationTests.java index a3d3cbc0798..78fe34090c3 100644 --- a/example/javalib/testing/3-integration-suite/qux/integration/src/qux/QuxIntegrationTests.java +++ b/example/javalib/testing/3-integration-suite/qux/integration/src/qux/QuxIntegrationTests.java @@ -1,6 +1,7 @@ package qux; import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.Test; public class QuxIntegrationTests { @@ -10,4 +11,4 @@ public void helloworld() { String result = Qux.hello(); assertEquals("Hello World", result); } -} \ No newline at end of file +} diff --git a/example/javalib/testing/3-integration-suite/qux/src/qux/Qux.java b/example/javalib/testing/3-integration-suite/qux/src/qux/Qux.java index 54c78cdb82e..96b501976a7 100644 --- a/example/javalib/testing/3-integration-suite/qux/src/qux/Qux.java +++ b/example/javalib/testing/3-integration-suite/qux/src/qux/Qux.java @@ -8,4 +8,4 @@ public static void main(String[] args) { public static String hello() { return "Hello World"; } -} \ No newline at end of file +} diff --git a/example/javalib/testing/3-integration-suite/qux/test/src/qux/QuxTests.java b/example/javalib/testing/3-integration-suite/qux/test/src/qux/QuxTests.java index 579a2eb55ab..d07d2aded86 100644 --- a/example/javalib/testing/3-integration-suite/qux/test/src/qux/QuxTests.java +++ b/example/javalib/testing/3-integration-suite/qux/test/src/qux/QuxTests.java @@ -1,6 +1,7 @@ package qux; import static org.junit.jupiter.api.Assertions.assertTrue; + import org.junit.jupiter.api.Test; public class QuxTests { @@ -16,4 +17,4 @@ public void world() { String result = Qux.hello(); assertTrue(result.endsWith("World")); } -} \ No newline at end of file +} diff --git a/example/javalib/testing/4-test-grouping/build.mill b/example/javalib/testing/4-test-grouping/build.mill index 8d1634a8849..31b672dbe0c 100644 --- a/example/javalib/testing/4-test-grouping/build.mill +++ b/example/javalib/testing/4-test-grouping/build.mill @@ -1,4 +1,3 @@ - //// SNIPPET:BUILD1 package build import mill._, javalib._ diff --git a/example/javalib/testing/4-test-grouping/foo/src/foo/Foo.java b/example/javalib/testing/4-test-grouping/foo/src/foo/Foo.java index 6495735bf03..ba912ebcce9 100644 --- a/example/javalib/testing/4-test-grouping/foo/src/foo/Foo.java +++ b/example/javalib/testing/4-test-grouping/foo/src/foo/Foo.java @@ -8,4 +8,4 @@ public static void main(String[] args) { public String hello() { return "Hello World"; } -} \ No newline at end of file +} diff --git a/example/javalib/testing/4-test-grouping/foo/test/src/foo/HelloTests.java b/example/javalib/testing/4-test-grouping/foo/test/src/foo/HelloTests.java index aad0156520a..9700f72de6e 100644 --- a/example/javalib/testing/4-test-grouping/foo/test/src/foo/HelloTests.java +++ b/example/javalib/testing/4-test-grouping/foo/test/src/foo/HelloTests.java @@ -1,6 +1,7 @@ package foo; import static org.junit.Assert.assertTrue; + import org.junit.Test; public class HelloTests { diff --git a/example/javalib/testing/4-test-grouping/foo/test/src/foo/WorldTests.java b/example/javalib/testing/4-test-grouping/foo/test/src/foo/WorldTests.java index d69bfa74e5e..4c27fd1f083 100644 --- a/example/javalib/testing/4-test-grouping/foo/test/src/foo/WorldTests.java +++ b/example/javalib/testing/4-test-grouping/foo/test/src/foo/WorldTests.java @@ -1,6 +1,7 @@ package foo; import static org.junit.Assert.assertTrue; + import org.junit.Test; public class WorldTests { diff --git a/example/javalib/web/1-hello-jetty/src/com/example/HelloJetty.java b/example/javalib/web/1-hello-jetty/src/com/example/HelloJetty.java index 84b093762b7..a1f9a1bde7f 100644 --- a/example/javalib/web/1-hello-jetty/src/com/example/HelloJetty.java +++ b/example/javalib/web/1-hello-jetty/src/com/example/HelloJetty.java @@ -1,15 +1,17 @@ package com.example; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.handler.AbstractHandler; +import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.handler.AbstractHandler; public class HelloJetty extends AbstractHandler { - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { + public void handle( + String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException { response.setContentType("text/html; charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); @@ -22,4 +24,4 @@ public static void main(String[] args) throws Exception { server.start(); server.join(); } -} \ No newline at end of file +} diff --git a/example/javalib/web/1-hello-jetty/test/src/com/example/HelloJettyTest.java b/example/javalib/web/1-hello-jetty/test/src/com/example/HelloJettyTest.java index 31a19c23100..05121fc3eae 100644 --- a/example/javalib/web/1-hello-jetty/test/src/com/example/HelloJettyTest.java +++ b/example/javalib/web/1-hello-jetty/test/src/com/example/HelloJettyTest.java @@ -1,18 +1,17 @@ package com.example; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.HandlerList; -import org.eclipse.jetty.server.handler.HandlerWrapper; import org.junit.After; import org.junit.Before; import org.junit.Test; -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; - -import static org.junit.Assert.assertEquals; - public class HelloJettyTest { private Server server; private int port; @@ -43,11 +42,11 @@ public void tearDown() throws Exception { public void testHelloJetty() throws IOException { URL url = new URL("http://localhost:" + port + "/"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - + connection.setRequestMethod("GET"); connection.connect(); int responseCode = connection.getResponseCode(); assertEquals(HttpURLConnection.HTTP_OK, responseCode); } -} \ No newline at end of file +} diff --git a/example/javalib/web/2-hello-spring-boot/src/com/example/HelloSpringBoot.java b/example/javalib/web/2-hello-spring-boot/src/com/example/HelloSpringBoot.java index c17ed70013c..d0a765ca207 100644 --- a/example/javalib/web/2-hello-spring-boot/src/com/example/HelloSpringBoot.java +++ b/example/javalib/web/2-hello-spring-boot/src/com/example/HelloSpringBoot.java @@ -19,4 +19,4 @@ public String hello() { return "

Hello, World!

"; } } -} \ No newline at end of file +} diff --git a/example/javalib/web/2-hello-spring-boot/test/src/com/example/HelloSpringBootTest.java b/example/javalib/web/2-hello-spring-boot/test/src/com/example/HelloSpringBootTest.java index 81ef5ed0291..9e3c5cc0093 100644 --- a/example/javalib/web/2-hello-spring-boot/test/src/com/example/HelloSpringBootTest.java +++ b/example/javalib/web/2-hello-spring-boot/test/src/com/example/HelloSpringBootTest.java @@ -1,11 +1,12 @@ package com.example; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; -import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class HelloSpringBootTest { @@ -21,4 +22,4 @@ public void shouldReturnDefaultMessage() { String response = restTemplate.getForObject("http://localhost:" + port + "/", String.class); assertEquals("

Hello, World!

", response); } -} \ No newline at end of file +} diff --git a/example/javalib/web/3-todo-spring-boot/integration/src/com/example/TodomvcIntegrationTests.java b/example/javalib/web/3-todo-spring-boot/integration/src/com/example/TodomvcIntegrationTests.java index d9ff593454e..caec71b3ad9 100644 --- a/example/javalib/web/3-todo-spring-boot/integration/src/com/example/TodomvcIntegrationTests.java +++ b/example/javalib/web/3-todo-spring-boot/integration/src/com/example/TodomvcIntegrationTests.java @@ -1,6 +1,7 @@ package com.example; -import org.junit.jupiter.api.BeforeAll; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -17,53 +18,55 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import static org.assertj.core.api.Assertions.assertThat; - @Testcontainers @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class TodomvcIntegrationTests { - @Container - public static PostgreSQLContainer postgresContainer = new PostgreSQLContainer<>("postgres:latest") - .withDatabaseName("test") - .withUsername("test") - .withPassword("test"); + @Container + public static PostgreSQLContainer postgresContainer = new PostgreSQLContainer<>( + "postgres:latest") + .withDatabaseName("test") + .withUsername("test") + .withPassword("test"); - @LocalServerPort - private int port; + @LocalServerPort + private int port; - @Autowired - private TestRestTemplate restTemplate; + @Autowired + private TestRestTemplate restTemplate; - @DynamicPropertySource - static void postgresProperties(DynamicPropertyRegistry registry) { - registry.add("spring.datasource.url", postgresContainer::getJdbcUrl); - registry.add("spring.datasource.username", postgresContainer::getUsername); - registry.add("spring.datasource.password", postgresContainer::getPassword); - } + @DynamicPropertySource + static void postgresProperties(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", postgresContainer::getJdbcUrl); + registry.add("spring.datasource.username", postgresContainer::getUsername); + registry.add("spring.datasource.password", postgresContainer::getPassword); + } - @Test - void homePageLoads() { - ResponseEntity response = this.restTemplate.getForEntity("http://localhost:" + port + "/", String.class); - assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); - assertThat(response.getBody()).contains("

todos

"); - } + @Test + void homePageLoads() { + ResponseEntity response = + this.restTemplate.getForEntity("http://localhost:" + port + "/", String.class); + assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); + assertThat(response.getBody()).contains("

todos

"); + } - @Test - void addNewTodoItem() { - // Set up headers and form data for the POST request - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - String newTodo = "title=Test+Todo"; - HttpEntity entity = new HttpEntity<>(newTodo, headers); + @Test + void addNewTodoItem() { + // Set up headers and form data for the POST request + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + String newTodo = "title=Test+Todo"; + HttpEntity entity = new HttpEntity<>(newTodo, headers); - // Send the POST request to add a new todo item - ResponseEntity postResponse = this.restTemplate.exchange("http://localhost:" + port + "/", HttpMethod.POST, entity, String.class); - assertThat(postResponse.getStatusCode().is3xxRedirection()).isTrue(); + // Send the POST request to add a new todo item + ResponseEntity postResponse = this.restTemplate.exchange( + "http://localhost:" + port + "/", HttpMethod.POST, entity, String.class); + assertThat(postResponse.getStatusCode().is3xxRedirection()).isTrue(); - // Send a GET request to verify the new todo item was added - ResponseEntity getResponse = this.restTemplate.getForEntity("http://localhost:" + port + "/", String.class); - assertThat(getResponse.getStatusCode().is2xxSuccessful()).isTrue(); - assertThat(getResponse.getBody()).contains("Test Todo"); - } + // Send a GET request to verify the new todo item was added + ResponseEntity getResponse = + this.restTemplate.getForEntity("http://localhost:" + port + "/", String.class); + assertThat(getResponse.getStatusCode().is2xxSuccessful()).isTrue(); + assertThat(getResponse.getBody()).contains("Test Todo"); + } } diff --git a/example/javalib/web/3-todo-spring-boot/src/com/example/TodomvcApplication.java b/example/javalib/web/3-todo-spring-boot/src/com/example/TodomvcApplication.java index 692e0795e78..435a4b4b980 100644 --- a/example/javalib/web/3-todo-spring-boot/src/com/example/TodomvcApplication.java +++ b/example/javalib/web/3-todo-spring-boot/src/com/example/TodomvcApplication.java @@ -5,7 +5,7 @@ @SpringBootApplication public class TodomvcApplication { - public static void main(String[] args) { - SpringApplication.run(TodomvcApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(TodomvcApplication.class, args); + } } diff --git a/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/TodoItem.java b/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/TodoItem.java index 85060635639..b365ab3ccf7 100644 --- a/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/TodoItem.java +++ b/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/TodoItem.java @@ -7,27 +7,39 @@ @Entity public class TodoItem { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @NotBlank - private String title; + @NotBlank + private String title; - private boolean completed; + private boolean completed; - protected TodoItem() {} + protected TodoItem() {} - public TodoItem(String title, boolean completed) { - this.title = title; - this.completed = completed; - } + public TodoItem(String title, boolean completed) { + this.title = title; + this.completed = completed; + } - public Long getId() { return id; } + public Long getId() { + return id; + } - public String getTitle() { return title; } - public void setTitle(String title) { this.title = title; } + public String getTitle() { + return title; + } - public boolean isCompleted() { return completed; } - public void setCompleted(boolean completed) { this.completed = completed; } + public void setTitle(String title) { + this.title = title; + } + + public boolean isCompleted() { + return completed; + } + + public void setCompleted(boolean completed) { + this.completed = completed; + } } diff --git a/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/TodoItemNotFoundException.java b/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/TodoItemNotFoundException.java index 06065a92b03..8bb4c66c361 100644 --- a/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/TodoItemNotFoundException.java +++ b/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/TodoItemNotFoundException.java @@ -5,7 +5,7 @@ @ResponseStatus(HttpStatus.NOT_FOUND) public class TodoItemNotFoundException extends RuntimeException { - public TodoItemNotFoundException(Long itemId) { - super(String.format("TodoItem itemId=%s not found", itemId)); - } + public TodoItemNotFoundException(Long itemId) { + super(String.format("TodoItem itemId=%s not found", itemId)); + } } diff --git a/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/TodoItemRepository.java b/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/TodoItemRepository.java index a4f6d6a30aa..83b4f7ca27c 100644 --- a/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/TodoItemRepository.java +++ b/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/TodoItemRepository.java @@ -1,11 +1,10 @@ package com.example.todoitem; -import org.springframework.data.jpa.repository.JpaRepository; - import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; public interface TodoItemRepository extends JpaRepository { - int countAllByCompleted(boolean completed); + int countAllByCompleted(boolean completed); - List findAllByCompleted(boolean completed); + List findAllByCompleted(boolean completed); } diff --git a/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/web/TodoItemController.java b/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/web/TodoItemController.java index 6e443e5d5d8..b35aca7da52 100644 --- a/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/web/TodoItemController.java +++ b/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/web/TodoItemController.java @@ -3,119 +3,121 @@ import com.example.todoitem.TodoItem; import com.example.todoitem.TodoItemNotFoundException; import com.example.todoitem.TodoItemRepository; +import java.util.List; +import java.util.stream.Collectors; +import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; -import javax.validation.Valid; -import java.util.List; -import java.util.stream.Collectors; - @Controller @RequestMapping("/") public class TodoItemController { - private final TodoItemRepository repository; - - public TodoItemController(TodoItemRepository repository) { this.repository = repository; } - - @GetMapping - public String index(Model model) { - addAttributesForIndex(model, ListFilter.ALL); - return "index"; + private final TodoItemRepository repository; + + public TodoItemController(TodoItemRepository repository) { + this.repository = repository; + } + + @GetMapping + public String index(Model model) { + addAttributesForIndex(model, ListFilter.ALL); + return "index"; + } + + @GetMapping("/active") + public String indexActive(Model model) { + addAttributesForIndex(model, ListFilter.ACTIVE); + return "index"; + } + + @GetMapping("/completed") + public String indexCompleted(Model model) { + addAttributesForIndex(model, ListFilter.COMPLETED); + return "index"; + } + + private void addAttributesForIndex(Model model, ListFilter listFilter) { + model.addAttribute("item", new TodoItemFormData()); + model.addAttribute("todoFilter", listFilter); + model.addAttribute("todoItems", getTodoItems(listFilter)); + model.addAttribute("totalItemCount", repository.count()); + model.addAttribute("activeItemCount", getactiveItemCount()); + model.addAttribute("completedItemCount", getcompletedItemCount()); + } + + @PostMapping + public String addNewTodoItem(@Valid @ModelAttribute("item") TodoItemFormData formData) { + repository.save(new TodoItem(formData.getTitle(), false)); + + return "redirect:/"; + } + + @PutMapping("/{id}/toggle") + public String toggleSelection(@PathVariable("id") Long id) { + TodoItem todoItem = + repository.findById(id).orElseThrow(() -> new TodoItemNotFoundException(id)); + + todoItem.setCompleted(!todoItem.isCompleted()); + repository.save(todoItem); + return "redirect:/"; + } + + @PutMapping("/toggle-all") + public String toggleAll() { + List todoItems = repository.findAll(); + for (TodoItem todoItem : todoItems) { + todoItem.setCompleted(!todoItem.isCompleted()); + repository.save(todoItem); } + return "redirect:/"; + } - @GetMapping("/active") - public String indexActive(Model model) { - addAttributesForIndex(model, ListFilter.ACTIVE); - return "index"; - } - - @GetMapping("/completed") - public String indexCompleted(Model model) { - addAttributesForIndex(model, ListFilter.COMPLETED); - return "index"; - } - - private void addAttributesForIndex(Model model, - ListFilter listFilter) { - model.addAttribute("item", new TodoItemFormData()); - model.addAttribute("todoFilter", listFilter); - model.addAttribute("todoItems", getTodoItems(listFilter)); - model.addAttribute("totalItemCount", repository.count()); - model.addAttribute("activeItemCount", getactiveItemCount()); - model.addAttribute("completedItemCount", getcompletedItemCount()); - } - - @PostMapping - public String addNewTodoItem(@Valid @ModelAttribute("item") TodoItemFormData formData) { - repository.save(new TodoItem(formData.getTitle(), false)); - - return "redirect:/"; - } - - @PutMapping("/{id}/toggle") - public String toggleSelection(@PathVariable("id") Long id) { - TodoItem todoItem = repository.findById(id) - .orElseThrow(() -> new TodoItemNotFoundException(id)); - - todoItem.setCompleted(!todoItem.isCompleted()); - repository.save(todoItem); - return "redirect:/"; - } - - @PutMapping("/toggle-all") - public String toggleAll() { - List todoItems = repository.findAll(); - for (TodoItem todoItem : todoItems) { - todoItem.setCompleted(!todoItem.isCompleted()); - repository.save(todoItem); - } - return "redirect:/"; - } - - @DeleteMapping("/{id}") - public String deleteTodoItem(@PathVariable("id") Long id) { - repository.deleteById(id); - - return "redirect:/"; - } - - @DeleteMapping("/completed") - public String deleteCompletedItems() { - List items = repository.findAllByCompleted(true); - for (TodoItem item : items) { - repository.deleteById(item.getId()); - } - return "redirect:/"; - } - - private List getTodoItems(ListFilter filter) { - return switch (filter) { - case ALL -> convertToDto(repository.findAll()); - case ACTIVE -> convertToDto(repository.findAllByCompleted(false)); - case COMPLETED -> convertToDto(repository.findAllByCompleted(true)); - }; - } - - private List convertToDto(List todoItems) { - return todoItems - .stream() - .map(todoItem -> new TodoItemDto(todoItem.getId(), - todoItem.getTitle(), - todoItem.isCompleted())) - .collect(Collectors.toList()); - } - - private int getactiveItemCount() { return repository.countAllByCompleted(false); } - - private int getcompletedItemCount() { return repository.countAllByCompleted(true); } + @DeleteMapping("/{id}") + public String deleteTodoItem(@PathVariable("id") Long id) { + repository.deleteById(id); - public static record TodoItemDto(long id, String title, boolean completed) { } + return "redirect:/"; + } - public enum ListFilter { - ALL, - ACTIVE, - COMPLETED + @DeleteMapping("/completed") + public String deleteCompletedItems() { + List items = repository.findAllByCompleted(true); + for (TodoItem item : items) { + repository.deleteById(item.getId()); } + return "redirect:/"; + } + + private List getTodoItems(ListFilter filter) { + return switch (filter) { + case ALL -> convertToDto(repository.findAll()); + case ACTIVE -> convertToDto(repository.findAllByCompleted(false)); + case COMPLETED -> convertToDto(repository.findAllByCompleted(true)); + }; + } + + private List convertToDto(List todoItems) { + return todoItems.stream() + .map(todoItem -> + new TodoItemDto(todoItem.getId(), todoItem.getTitle(), todoItem.isCompleted())) + .collect(Collectors.toList()); + } + + private int getactiveItemCount() { + return repository.countAllByCompleted(false); + } + + private int getcompletedItemCount() { + return repository.countAllByCompleted(true); + } + + public static record TodoItemDto(long id, String title, boolean completed) {} + + public enum ListFilter { + ALL, + ACTIVE, + COMPLETED + } } diff --git a/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/web/TodoItemFormData.java b/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/web/TodoItemFormData.java index 10edb2e5729..1b9763cea2a 100644 --- a/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/web/TodoItemFormData.java +++ b/example/javalib/web/3-todo-spring-boot/src/com/example/todoitem/web/TodoItemFormData.java @@ -3,8 +3,14 @@ import javax.validation.constraints.NotBlank; public class TodoItemFormData { - @NotBlank - private String title; - public String getTitle() { return title; } - public void setTitle(String title) { this.title = title; } + @NotBlank + private String title; + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } } diff --git a/example/javalib/web/3-todo-spring-boot/test/src/com/example/TodomvcTests.java b/example/javalib/web/3-todo-spring-boot/test/src/com/example/TodomvcTests.java index dfaa678cf04..289a337af9a 100644 --- a/example/javalib/web/3-todo-spring-boot/test/src/com/example/TodomvcTests.java +++ b/example/javalib/web/3-todo-spring-boot/test/src/com/example/TodomvcTests.java @@ -1,5 +1,7 @@ package com.example; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -11,39 +13,40 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import static org.assertj.core.api.Assertions.assertThat; - @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class TodomvcTests { - @LocalServerPort - private int port; - - @Autowired - private TestRestTemplate restTemplate; - - @Test - void homePageLoads() { - ResponseEntity response = this.restTemplate.getForEntity("http://localhost:" + port + "/", String.class); - assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); - assertThat(response.getBody()).contains("

todos

"); - } - - @Test - void addNewTodoItem() { - // Set up headers and form data for the POST request - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - String newTodo = "title=Test+Todo"; - HttpEntity entity = new HttpEntity<>(newTodo, headers); - - // Send the POST request to add a new todo item - ResponseEntity postResponse = this.restTemplate.exchange("http://localhost:" + port + "/", HttpMethod.POST, entity, String.class); - assertThat(postResponse.getStatusCode().is3xxRedirection()).isTrue(); - - // Send a GET request to verify the new todo item was added - ResponseEntity getResponse = this.restTemplate.getForEntity("http://localhost:" + port + "/", String.class); - assertThat(getResponse.getStatusCode().is2xxSuccessful()).isTrue(); - assertThat(getResponse.getBody()).contains("Test Todo"); - } + @LocalServerPort + private int port; + + @Autowired + private TestRestTemplate restTemplate; + + @Test + void homePageLoads() { + ResponseEntity response = + this.restTemplate.getForEntity("http://localhost:" + port + "/", String.class); + assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); + assertThat(response.getBody()).contains("

todos

"); + } + + @Test + void addNewTodoItem() { + // Set up headers and form data for the POST request + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + String newTodo = "title=Test+Todo"; + HttpEntity entity = new HttpEntity<>(newTodo, headers); + + // Send the POST request to add a new todo item + ResponseEntity postResponse = this.restTemplate.exchange( + "http://localhost:" + port + "/", HttpMethod.POST, entity, String.class); + assertThat(postResponse.getStatusCode().is3xxRedirection()).isTrue(); + + // Send a GET request to verify the new todo item was added + ResponseEntity getResponse = + this.restTemplate.getForEntity("http://localhost:" + port + "/", String.class); + assertThat(getResponse.getStatusCode().is2xxSuccessful()).isTrue(); + assertThat(getResponse.getBody()).contains("Test Todo"); + } } diff --git a/example/javalib/web/4-hello-micronaut/src/main/java/example/micronaut/Application.java b/example/javalib/web/4-hello-micronaut/src/main/java/example/micronaut/Application.java index 6df394c533b..e1280f0b8a4 100644 --- a/example/javalib/web/4-hello-micronaut/src/main/java/example/micronaut/Application.java +++ b/example/javalib/web/4-hello-micronaut/src/main/java/example/micronaut/Application.java @@ -19,7 +19,7 @@ public class Application { - public static void main(String[] args) { - Micronaut.run(Application.class, args); - } -} \ No newline at end of file + public static void main(String[] args) { + Micronaut.run(Application.class, args); + } +} diff --git a/example/javalib/web/4-hello-micronaut/src/main/java/example/micronaut/HelloController.java b/example/javalib/web/4-hello-micronaut/src/main/java/example/micronaut/HelloController.java index c6a5d8cb824..0b054b51965 100644 --- a/example/javalib/web/4-hello-micronaut/src/main/java/example/micronaut/HelloController.java +++ b/example/javalib/web/4-hello-micronaut/src/main/java/example/micronaut/HelloController.java @@ -22,9 +22,9 @@ @Controller("/hello") // <1> public class HelloController { - @Get // <2> - @Produces(MediaType.TEXT_PLAIN) // <3> - public String index() { - return "Hello World"; // <4> - } + @Get // <2> + @Produces(MediaType.TEXT_PLAIN) // <3> + public String index() { + return "Hello World"; // <4> + } } diff --git a/example/javalib/web/4-hello-micronaut/src/test/java/example/micronaut/DefaultTest.java b/example/javalib/web/4-hello-micronaut/src/test/java/example/micronaut/DefaultTest.java index daac65cc276..659430f4c8d 100644 --- a/example/javalib/web/4-hello-micronaut/src/test/java/example/micronaut/DefaultTest.java +++ b/example/javalib/web/4-hello-micronaut/src/test/java/example/micronaut/DefaultTest.java @@ -17,20 +17,18 @@ import io.micronaut.runtime.EmbeddedApplication; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Assertions; - import jakarta.inject.Inject; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; @MicronautTest class DefaultTest { - @Inject - EmbeddedApplication application; - - @Test - void testItWorks() { - Assertions.assertTrue(application.isRunning()); - } + @Inject + EmbeddedApplication application; + @Test + void testItWorks() { + Assertions.assertTrue(application.isRunning()); + } } diff --git a/example/javalib/web/4-hello-micronaut/src/test/java/example/micronaut/HelloControllerTest.java b/example/javalib/web/4-hello-micronaut/src/test/java/example/micronaut/HelloControllerTest.java index 486c8406edf..5a135d9e420 100644 --- a/example/javalib/web/4-hello-micronaut/src/test/java/example/micronaut/HelloControllerTest.java +++ b/example/javalib/web/4-hello-micronaut/src/test/java/example/micronaut/HelloControllerTest.java @@ -23,23 +23,22 @@ import io.micronaut.http.client.HttpClient; import io.micronaut.http.client.annotation.Client; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; -import org.junit.jupiter.api.Test; - import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; @MicronautTest // <1> public class HelloControllerTest { - @Inject - @Client("/") // <2> - HttpClient client; + @Inject + @Client("/") // <2> + HttpClient client; - @Test - public void testHello() { - HttpRequest request = HttpRequest.GET("/hello").accept(MediaType.TEXT_PLAIN); // <3> - String body = client.toBlocking().retrieve(request); + @Test + public void testHello() { + HttpRequest request = HttpRequest.GET("/hello").accept(MediaType.TEXT_PLAIN); // <3> + String body = client.toBlocking().retrieve(request); - assertNotNull(body); - assertEquals("Hello World", body); - } + assertNotNull(body); + assertEquals("Hello World", body); + } } diff --git a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/Application.java b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/Application.java index 1cd68874b69..d9eb7e631cf 100644 --- a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/Application.java +++ b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/Application.java @@ -4,7 +4,7 @@ public class Application { - public static void main(String[] args) { - Micronaut.run(Application.class, args); - } -} \ No newline at end of file + public static void main(String[] args) { + Micronaut.run(Application.class, args); + } +} diff --git a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/LoggingHeadersFilter.java b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/LoggingHeadersFilter.java index 7417d65a5af..49886cfb349 100644 --- a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/LoggingHeadersFilter.java +++ b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/LoggingHeadersFilter.java @@ -1,28 +1,29 @@ package example.micronaut; +import static io.micronaut.http.annotation.Filter.MATCH_ALL_PATTERN; + import io.micronaut.core.order.Ordered; import io.micronaut.http.HttpRequest; import io.micronaut.http.annotation.RequestFilter; import io.micronaut.http.annotation.ServerFilter; import io.micronaut.http.filter.ServerFilterPhase; +import io.micronaut.http.util.HttpHeadersUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.micronaut.http.util.HttpHeadersUtil; -import static io.micronaut.http.annotation.Filter.MATCH_ALL_PATTERN; @ServerFilter(MATCH_ALL_PATTERN) class LoggingHeadersFilter implements Ordered { - private static final Logger LOG = LoggerFactory.getLogger(LoggingHeadersFilter.class); + private static final Logger LOG = LoggerFactory.getLogger(LoggingHeadersFilter.class); - @RequestFilter - void filterRequest(HttpRequest request) { - LOG.trace("Request {} {}", request.getMethod(), request.getPath()); - HttpHeadersUtil.trace(LOG, request.getHeaders()); - } + @RequestFilter + void filterRequest(HttpRequest request) { + LOG.trace("Request {} {}", request.getMethod(), request.getPath()); + HttpHeadersUtil.trace(LOG, request.getHeaders()); + } - @Override - public int getOrder() { - return ServerFilterPhase.FIRST.order(); - } -} \ No newline at end of file + @Override + public int getOrder() { + return ServerFilterPhase.FIRST.order(); + } +} diff --git a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItem.java b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItem.java index e5f36fffd2e..09b4097f852 100644 --- a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItem.java +++ b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItem.java @@ -6,7 +6,4 @@ import io.micronaut.data.annotation.MappedEntity; @MappedEntity -public record TodoItem(@Nullable @Id @GeneratedValue Long id, - String title, - boolean completed) { -} +public record TodoItem(@Nullable @Id @GeneratedValue Long id, String title, boolean completed) {} diff --git a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemController.java b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemController.java index 415c97793e8..7ecc4d2130b 100644 --- a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemController.java +++ b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemController.java @@ -9,7 +9,6 @@ import io.micronaut.views.View; import io.micronaut.views.htmx.http.HtmxRequestHeaders; import io.micronaut.views.htmx.http.HtmxResponseHeaders; - import java.net.URI; import java.util.Collections; import java.util.List; @@ -17,143 +16,148 @@ @Controller class TodoItemController { - private static final String MODEL_ITEM = "item"; - private static final String MODEL_FILTER = "filter"; - private static final String MODEL_TODOS = "todos"; - private static final String MODEL_TOTAL_NUMBER_OF_ITEMS = "totalNumberOfItems"; - private static final String MODEL_NUMBER_OF_ACTIVE_ITEMS = "numberOfActiveItems"; - private static final String MODEL_NUMBER_OF_COMPLETED_ITEMS = "numberOfCompletedItems"; - private static final URI ROOT = URI.create("/"); - - private final TodoItemRepository repository; - private final TodoItemMapper todoItemMapper; - - TodoItemController(TodoItemRepository repository, - TodoItemMapper todoItemMapper) { - this.repository = repository; - this.todoItemMapper = todoItemMapper; - } - - @View("index") - @Get - Map index() { - return createModel(ListFilter.ALL); - } - - @View("index") - @Get("/active") - Map indexActive() { - return createModel(ListFilter.ACTIVE); - } - - - @Get("/completed") - @View("index") - Map indexCompleted() { - return createModel(ListFilter.COMPLETED); - } - - @Consumes(MediaType.APPLICATION_FORM_URLENCODED) - @Post("/save") - HttpResponse addNewTodoItem(@Body TodoItemFormData formData, @Nullable HtmxRequestHeaders htmxRequestHeaders) { - TodoItem item = repository.save(todoItemMapper.toEntity(formData)); - if (htmxRequestHeaders != null) { - return HttpResponse.ok(new ModelAndView<>("fragments :: todoItem", Collections.singletonMap(MODEL_ITEM, item))) - .header(HtmxResponseHeaders.HX_TRIGGER, "itemAdded"); - } - return HttpResponse.seeOther(ROOT); - } - - @Get("/active-items-count") - @View("fragments :: active-items-count") - Map htmxActiveItemsAcount(@NonNull HtmxRequestHeaders htmxRequestHeaders) { - return Collections.singletonMap("numberOfActiveItems", getNumberOfActiveItems()); - } - - @Consumes(MediaType.APPLICATION_FORM_URLENCODED) - @Post("/{id}/toggle") - HttpResponse toggleSelection(@PathVariable Long id) { - TodoItem todoItem = repository.findById(id) - .orElseThrow(() -> new TodoItemNotFoundException(id)); - repository.updateCompletedById(!todoItem.completed(), id); - return HttpResponse.seeOther(ROOT); - } - - @Consumes(MediaType.APPLICATION_FORM_URLENCODED) - @Put("/{id}/toggle") - HttpResponse htmxToggleTodoItem(@PathVariable Long id, @NonNull HtmxRequestHeaders htmxRequestHeaders) { - TodoItem todoItem = repository.findById(id) - .orElseThrow(() -> new TodoItemNotFoundException(id)); - TodoItem updated = new TodoItem(todoItem.id(), - todoItem.title(), - !todoItem.completed()); - repository.updateCompletedById(updated.completed(), id); - return HttpResponse.ok(new ModelAndView<>("fragments :: todoItem", - Collections.singletonMap(MODEL_ITEM, updated))) - .header(HtmxResponseHeaders.HX_TRIGGER, "itemCompletionToggled"); - } - - @Consumes(MediaType.APPLICATION_FORM_URLENCODED) - @Post("/toggle-all") - HttpResponse toggleAll() { - repository.updateCompleted(true); - return HttpResponse.seeOther(ROOT); - } - - @Consumes(MediaType.APPLICATION_FORM_URLENCODED) - @Post("/{id}/delete") - HttpResponse deleteTodoItem(@PathVariable Long id) { - repository.deleteById(id); - return HttpResponse.seeOther(ROOT); - } - - @Consumes(MediaType.APPLICATION_FORM_URLENCODED) - @Delete("/{id}") - HttpResponse deleteTodoItem(@PathVariable Long id, - @NonNull HtmxRequestHeaders htmxRequestHeaders) { - repository.deleteById(id); - return HttpResponse.ok().body("").header(HtmxResponseHeaders.HX_TRIGGER, "itemDeleted"); - } - - @Consumes(MediaType.APPLICATION_FORM_URLENCODED) - @Post("/completed/delete") - HttpResponse deleteCompletedItems() { - List items = repository.findAllByCompleted(true); - for (TodoItem item : items) { - repository.deleteById(item.id()); - } - return HttpResponse.seeOther(ROOT); - } - - private Map createModel(ListFilter listFilter) { - return Map.of( - MODEL_ITEM, new TodoItemFormData(), - MODEL_TODOS, getTodoItems(listFilter), - MODEL_TOTAL_NUMBER_OF_ITEMS, repository.count(), - MODEL_NUMBER_OF_ACTIVE_ITEMS, getNumberOfActiveItems(), - MODEL_NUMBER_OF_COMPLETED_ITEMS, getNumberOfCompletedItems(), - MODEL_FILTER, listFilter); - } - - private int getNumberOfActiveItems() { - return repository.countByCompleted(false); - } - - private int getNumberOfCompletedItems() { - return repository.countByCompleted(true); - } - - private List getTodoItems(ListFilter filter) { - return switch (filter) { - case ALL -> repository.findAll(); - case ACTIVE -> repository.findAllByCompleted(false); - case COMPLETED -> repository.findAllByCompleted(true); - }; - } - - public enum ListFilter { - ALL, - ACTIVE, - COMPLETED - } + private static final String MODEL_ITEM = "item"; + private static final String MODEL_FILTER = "filter"; + private static final String MODEL_TODOS = "todos"; + private static final String MODEL_TOTAL_NUMBER_OF_ITEMS = "totalNumberOfItems"; + private static final String MODEL_NUMBER_OF_ACTIVE_ITEMS = "numberOfActiveItems"; + private static final String MODEL_NUMBER_OF_COMPLETED_ITEMS = "numberOfCompletedItems"; + private static final URI ROOT = URI.create("/"); + + private final TodoItemRepository repository; + private final TodoItemMapper todoItemMapper; + + TodoItemController(TodoItemRepository repository, TodoItemMapper todoItemMapper) { + this.repository = repository; + this.todoItemMapper = todoItemMapper; + } + + @View("index") + @Get + Map index() { + return createModel(ListFilter.ALL); + } + + @View("index") + @Get("/active") + Map indexActive() { + return createModel(ListFilter.ACTIVE); + } + + @Get("/completed") + @View("index") + Map indexCompleted() { + return createModel(ListFilter.COMPLETED); + } + + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + @Post("/save") + HttpResponse addNewTodoItem( + @Body TodoItemFormData formData, @Nullable HtmxRequestHeaders htmxRequestHeaders) { + TodoItem item = repository.save(todoItemMapper.toEntity(formData)); + if (htmxRequestHeaders != null) { + return HttpResponse.ok(new ModelAndView<>( + "fragments :: todoItem", Collections.singletonMap(MODEL_ITEM, item))) + .header(HtmxResponseHeaders.HX_TRIGGER, "itemAdded"); + } + return HttpResponse.seeOther(ROOT); + } + + @Get("/active-items-count") + @View("fragments :: active-items-count") + Map htmxActiveItemsAcount(@NonNull HtmxRequestHeaders htmxRequestHeaders) { + return Collections.singletonMap("numberOfActiveItems", getNumberOfActiveItems()); + } + + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + @Post("/{id}/toggle") + HttpResponse toggleSelection(@PathVariable Long id) { + TodoItem todoItem = + repository.findById(id).orElseThrow(() -> new TodoItemNotFoundException(id)); + repository.updateCompletedById(!todoItem.completed(), id); + return HttpResponse.seeOther(ROOT); + } + + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + @Put("/{id}/toggle") + HttpResponse htmxToggleTodoItem( + @PathVariable Long id, @NonNull HtmxRequestHeaders htmxRequestHeaders) { + TodoItem todoItem = + repository.findById(id).orElseThrow(() -> new TodoItemNotFoundException(id)); + TodoItem updated = new TodoItem(todoItem.id(), todoItem.title(), !todoItem.completed()); + repository.updateCompletedById(updated.completed(), id); + return HttpResponse.ok(new ModelAndView<>( + "fragments :: todoItem", Collections.singletonMap(MODEL_ITEM, updated))) + .header(HtmxResponseHeaders.HX_TRIGGER, "itemCompletionToggled"); + } + + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + @Post("/toggle-all") + HttpResponse toggleAll() { + repository.updateCompleted(true); + return HttpResponse.seeOther(ROOT); + } + + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + @Post("/{id}/delete") + HttpResponse deleteTodoItem(@PathVariable Long id) { + repository.deleteById(id); + return HttpResponse.seeOther(ROOT); + } + + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + @Delete("/{id}") + HttpResponse deleteTodoItem( + @PathVariable Long id, @NonNull HtmxRequestHeaders htmxRequestHeaders) { + repository.deleteById(id); + return HttpResponse.ok().body("").header(HtmxResponseHeaders.HX_TRIGGER, "itemDeleted"); + } + + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + @Post("/completed/delete") + HttpResponse deleteCompletedItems() { + List items = repository.findAllByCompleted(true); + for (TodoItem item : items) { + repository.deleteById(item.id()); + } + return HttpResponse.seeOther(ROOT); + } + + private Map createModel(ListFilter listFilter) { + return Map.of( + MODEL_ITEM, + new TodoItemFormData(), + MODEL_TODOS, + getTodoItems(listFilter), + MODEL_TOTAL_NUMBER_OF_ITEMS, + repository.count(), + MODEL_NUMBER_OF_ACTIVE_ITEMS, + getNumberOfActiveItems(), + MODEL_NUMBER_OF_COMPLETED_ITEMS, + getNumberOfCompletedItems(), + MODEL_FILTER, + listFilter); + } + + private int getNumberOfActiveItems() { + return repository.countByCompleted(false); + } + + private int getNumberOfCompletedItems() { + return repository.countByCompleted(true); + } + + private List getTodoItems(ListFilter filter) { + return switch (filter) { + case ALL -> repository.findAll(); + case ACTIVE -> repository.findAllByCompleted(false); + case COMPLETED -> repository.findAllByCompleted(true); + }; + } + + public enum ListFilter { + ALL, + ACTIVE, + COMPLETED + } } diff --git a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemFormData.java b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemFormData.java index 01a3e968f11..89a9102970c 100644 --- a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemFormData.java +++ b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemFormData.java @@ -5,14 +5,14 @@ @Serdeable public class TodoItemFormData { - @NotBlank - private String title; + @NotBlank + private String title; - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public void setTitle(String title) { - this.title = title; - } + public void setTitle(String title) { + this.title = title; + } } diff --git a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemMapper.java b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemMapper.java index fbb3d163cf3..99411303488 100644 --- a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemMapper.java +++ b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemMapper.java @@ -5,6 +5,6 @@ @Singleton public interface TodoItemMapper { - @Mapper.Mapping(to = "completed", from = "#{false}") - TodoItem toEntity(TodoItemFormData form); + @Mapper.Mapping(to = "completed", from = "#{false}") + TodoItem toEntity(TodoItemFormData form); } diff --git a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemNotFoundException.java b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemNotFoundException.java index d0616175f9a..1eb8b20a20e 100644 --- a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemNotFoundException.java +++ b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemNotFoundException.java @@ -1,7 +1,7 @@ package example.micronaut; public class TodoItemNotFoundException extends RuntimeException { - public TodoItemNotFoundException(Long id) { - super(String.format("TodoItem with id %s not found", id)); - } + public TodoItemNotFoundException(Long id) { + super(String.format("TodoItem with id %s not found", id)); + } } diff --git a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemNotFoundExceptionHandler.java b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemNotFoundExceptionHandler.java index 5ecd9230afa..15b00b6e0ba 100644 --- a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemNotFoundExceptionHandler.java +++ b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemNotFoundExceptionHandler.java @@ -12,19 +12,19 @@ @Produces @Singleton @Requires(classes = {TodoItemNotFoundException.class, ExceptionHandler.class}) -class TodoItemNotFoundExceptionHandler implements ExceptionHandler { +class TodoItemNotFoundExceptionHandler + implements ExceptionHandler { - private final ErrorResponseProcessor errorResponseProcessor; + private final ErrorResponseProcessor errorResponseProcessor; - public TodoItemNotFoundExceptionHandler(ErrorResponseProcessor errorResponseProcessor) { - this.errorResponseProcessor = errorResponseProcessor; - } + public TodoItemNotFoundExceptionHandler(ErrorResponseProcessor errorResponseProcessor) { + this.errorResponseProcessor = errorResponseProcessor; + } - @Override - public HttpResponse handle(HttpRequest request, TodoItemNotFoundException e) { - return errorResponseProcessor.processResponse(ErrorContext.builder(request) - .cause(e) - .errorMessage(e.getMessage()) - .build(), HttpResponse.notFound()); - } -} \ No newline at end of file + @Override + public HttpResponse handle(HttpRequest request, TodoItemNotFoundException e) { + return errorResponseProcessor.processResponse( + ErrorContext.builder(request).cause(e).errorMessage(e.getMessage()).build(), + HttpResponse.notFound()); + } +} diff --git a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemRepository.java b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemRepository.java index 0e581709aab..f3ba6ee06c3 100644 --- a/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemRepository.java +++ b/example/javalib/web/5-todo-micronaut/src/main/java/example/micronaut/TodoItemRepository.java @@ -5,18 +5,18 @@ import io.micronaut.data.jdbc.annotation.JdbcRepository; import io.micronaut.data.model.query.builder.sql.Dialect; import io.micronaut.data.repository.CrudRepository; - import java.util.List; @JdbcRepository(dialect = Dialect.H2) -public interface TodoItemRepository extends CrudRepository{ - int countByCompleted(boolean completed); +public interface TodoItemRepository extends CrudRepository { + int countByCompleted(boolean completed); + + @NonNull + List findAllByCompleted(boolean completed); - @NonNull - List findAllByCompleted(boolean completed); - @Query("UPDATE todo_item SET completed = :completed") - void updateCompleted(boolean completed); + @Query("UPDATE todo_item SET completed = :completed") + void updateCompleted(boolean completed); - @Query("UPDATE todo_item SET completed = :completed WHERE id = :id") - void updateCompletedById(boolean completed, Long id); + @Query("UPDATE todo_item SET completed = :completed WHERE id = :id") + void updateCompletedById(boolean completed, Long id); } diff --git a/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/HtmxWebJarsTest.java b/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/HtmxWebJarsTest.java index 210190dc793..170675d7afc 100644 --- a/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/HtmxWebJarsTest.java +++ b/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/HtmxWebJarsTest.java @@ -1,18 +1,19 @@ package example.micronaut; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import io.micronaut.http.client.BlockingHttpClient; import io.micronaut.http.client.HttpClient; import io.micronaut.http.client.annotation.Client; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - @MicronautTest class HtmxWebJarsTest { - @Test - void htmxViaWebJarsAvailable(@Client("/") HttpClient httpClient) { - BlockingHttpClient client = httpClient.toBlocking(); - assertDoesNotThrow(() -> client.exchange("/webjars/github-com-bigskysoftware-htmx/1.9.10/htmx.js")); - } + @Test + void htmxViaWebJarsAvailable(@Client("/") HttpClient httpClient) { + BlockingHttpClient client = httpClient.toBlocking(); + assertDoesNotThrow( + () -> client.exchange("/webjars/github-com-bigskysoftware-htmx/1.9.10/htmx.js")); + } } diff --git a/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/LearnJsonTest.java b/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/LearnJsonTest.java index 944bfd18ea8..0ce215a57c5 100644 --- a/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/LearnJsonTest.java +++ b/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/LearnJsonTest.java @@ -1,19 +1,19 @@ package example.micronaut; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import io.micronaut.http.client.BlockingHttpClient; import io.micronaut.http.client.HttpClient; import io.micronaut.http.client.annotation.Client; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - @MicronautTest class LearnJsonTest { - @Test - void learnJsonAvailable(@Client("/") HttpClient httpClient) { - BlockingHttpClient client = httpClient.toBlocking(); - assertDoesNotThrow(() -> client.exchange("/learn.json")); - } + @Test + void learnJsonAvailable(@Client("/") HttpClient httpClient) { + BlockingHttpClient client = httpClient.toBlocking(); + assertDoesNotThrow(() -> client.exchange("/learn.json")); + } } diff --git a/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/TodoItemControllerTest.java b/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/TodoItemControllerTest.java index 47a3d5e8052..e93bd185075 100644 --- a/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/TodoItemControllerTest.java +++ b/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/TodoItemControllerTest.java @@ -1,5 +1,7 @@ package example.micronaut; +import static org.junit.jupiter.api.Assertions.assertEquals; + import io.micronaut.http.HttpRequest; import io.micronaut.http.MediaType; import io.micronaut.http.client.BlockingHttpClient; @@ -8,20 +10,18 @@ import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - @MicronautTest class TodoItemControllerTest { - @Test - void crud(@Client("/") HttpClient httpClient, TodoItemRepository repository) { - BlockingHttpClient client = httpClient.toBlocking(); - // create - long count = repository.count(); - TodoItemFormData data = new TodoItemFormData(); - data.setTitle("Micronaut"); - client.exchange(HttpRequest.POST("/save", data).contentType(MediaType.APPLICATION_FORM_URLENCODED)); - assertEquals(count + 1, repository.count()); - - } -} \ No newline at end of file + @Test + void crud(@Client("/") HttpClient httpClient, TodoItemRepository repository) { + BlockingHttpClient client = httpClient.toBlocking(); + // create + long count = repository.count(); + TodoItemFormData data = new TodoItemFormData(); + data.setTitle("Micronaut"); + client.exchange( + HttpRequest.POST("/save", data).contentType(MediaType.APPLICATION_FORM_URLENCODED)); + assertEquals(count + 1, repository.count()); + } +} diff --git a/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/TodoItemMapperTest.java b/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/TodoItemMapperTest.java index 06637ca08fc..330d40e7988 100644 --- a/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/TodoItemMapperTest.java +++ b/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/TodoItemMapperTest.java @@ -1,22 +1,23 @@ package example.micronaut; +import static org.junit.jupiter.api.Assertions.*; + import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - @MicronautTest(startApplication = false) class TodoItemMapperTest { - @Test - void mapper(TodoItemMapper mapper) { - TodoItem todoItem = mapper.toEntity(new TodoItemFormData() {{ - setTitle("Micronaut"); - }}); - assertNotNull(todoItem); - assertNull(todoItem.id()); - assertEquals("Micronaut", todoItem.title()); - assertFalse(todoItem.completed()); - } - -} \ No newline at end of file + @Test + void mapper(TodoItemMapper mapper) { + TodoItem todoItem = mapper.toEntity(new TodoItemFormData() { + { + setTitle("Micronaut"); + } + }); + assertNotNull(todoItem); + assertNull(todoItem.id()); + assertEquals("Micronaut", todoItem.title()); + assertFalse(todoItem.completed()); + } +} diff --git a/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/TodoTest.java b/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/TodoTest.java index 0d8d896543a..52b166c1d55 100644 --- a/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/TodoTest.java +++ b/example/javalib/web/5-todo-micronaut/src/test/java/example/micronaut/TodoTest.java @@ -2,20 +2,18 @@ import io.micronaut.runtime.EmbeddedApplication; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Assertions; - import jakarta.inject.Inject; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; @MicronautTest class TodoTest { - @Inject - EmbeddedApplication application; - - @Test - void testItWorks() { - Assertions.assertTrue(application.isRunning()); - } + @Inject + EmbeddedApplication application; + @Test + void testItWorks() { + Assertions.assertTrue(application.isRunning()); + } } diff --git a/example/kotlinlib/android/1-hello-world/build.mill b/example/kotlinlib/android/1-hello-world/build.mill index 49df51f1e50..28ffa2b5ab5 100644 --- a/example/kotlinlib/android/1-hello-world/build.mill +++ b/example/kotlinlib/android/1-hello-world/build.mill @@ -1,9 +1,9 @@ -// This section sets up a basic Android project using Mill. -// We utilize `AndroidAppKotlinModule` and `AndroidSdkModule` to streamline the process of +// This section sets up a basic Android project using Mill. +// We utilize `AndroidAppKotlinModule` and `AndroidSdkModule` to streamline the process of // building an Android application with minimal configuration. // -// By extending `AndroidAppKotlinModule`, we inherit all Android-related tasks such as -// resource generation, APK building, DEX conversion, and APK signing. +// By extending `AndroidAppKotlinModule`, we inherit all Android-related tasks such as +// resource generation, APK building, DEX conversion, and APK signing. // Additionally, `AndroidSdkModule` is embedded, making SDK management seamless. //// SNIPPET:BUILD @@ -15,20 +15,19 @@ import mill.kotlinlib.android.AndroidAppKotlinModule import mill.javalib.android.AndroidSdkModule // Create and configure an Android SDK module to manage Android SDK paths and tools. -object androidSdkModule0 extends AndroidSdkModule{ +object androidSdkModule0 extends AndroidSdkModule { def buildToolsVersion = "35.0.0" } // Actual android application object app extends AndroidAppKotlinModule { - + def kotlinVersion = "2.0.0" def androidSdkModule = mill.define.ModuleRef(androidSdkModule0) } ////SNIPPET:END - /** Usage > ./mill show app.androidApk @@ -36,14 +35,14 @@ object app extends AndroidAppKotlinModule { */ -// This command triggers the build process, which installs the Android Setup, compiles the kotlin -// code, generates Android resources, converts kotlin bytecode to DEX format, packages everything +// This command triggers the build process, which installs the Android Setup, compiles the kotlin +// code, generates Android resources, converts kotlin bytecode to DEX format, packages everything // into an APK, optimizes the APK using `zipalign`, and finally signs it. // -// This Mill build configuration is designed to build a simple "Hello World" Android application. -// By extending `AndroidAppKotlinModule`, we leverage its predefined Android build tasks, ensuring that +// This Mill build configuration is designed to build a simple "Hello World" Android application. +// By extending `AndroidAppKotlinModule`, we leverage its predefined Android build tasks, ensuring that // all necessary steps (resource generation, APK creation, and signing) are executed automatically. -// +// // ### Project Structure: // The project follows the standard Android app layout. Below is a typical project folder structure: // diff --git a/example/kotlinlib/basic/4-compat-modules/build.mill b/example/kotlinlib/basic/4-compat-modules/build.mill index 8f0d51188d6..7f69476af1f 100644 --- a/example/kotlinlib/basic/4-compat-modules/build.mill +++ b/example/kotlinlib/basic/4-compat-modules/build.mill @@ -19,7 +19,6 @@ object foo extends KotlinModule with KotlinMavenModule { } } - // `KotlinMavenModule` is a variant of `KotlinModule` // that uses the more verbose folder layout of Maven, SBT, and other tools: // diff --git a/example/kotlinlib/basic/4-compat-modules/foo/src/main/java/foo/Foo2.java b/example/kotlinlib/basic/4-compat-modules/foo/src/main/java/foo/Foo2.java index 070c0ccf9ec..47684927c22 100644 --- a/example/kotlinlib/basic/4-compat-modules/foo/src/main/java/foo/Foo2.java +++ b/example/kotlinlib/basic/4-compat-modules/foo/src/main/java/foo/Foo2.java @@ -1,5 +1,5 @@ package foo; public class Foo2 { - public static final String VALUE = "Earth"; + public static final String VALUE = "Earth"; } diff --git a/example/kotlinlib/dependencies/1-ivy-deps/build.mill b/example/kotlinlib/dependencies/1-ivy-deps/build.mill index 12adaa68bd3..6d95273180e 100644 --- a/example/kotlinlib/dependencies/1-ivy-deps/build.mill +++ b/example/kotlinlib/dependencies/1-ivy-deps/build.mill @@ -9,7 +9,7 @@ object `package` extends RootModule with KotlinModule { def mainClass = Some("foo.FooKt") def ivyDeps = Agg( - ivy"com.fasterxml.jackson.core:jackson-databind:2.13.4", + ivy"com.fasterxml.jackson.core:jackson-databind:2.13.4" ) } diff --git a/example/kotlinlib/linting/1-detekt/build.mill b/example/kotlinlib/linting/1-detekt/build.mill index 55a2427821e..4a90e495482 100644 --- a/example/kotlinlib/linting/1-detekt/build.mill +++ b/example/kotlinlib/linting/1-detekt/build.mill @@ -8,7 +8,6 @@ object `package` extends RootModule with KotlinModule with DetektModule { def kotlinVersion = "1.9.24" } - // This example shows how to use the https://github.com/detekt/detekt[Detekt] // static code analyzer for linting a `KotlinModule`, by mixing in the trait // `DetektModule` and calling the `detekt` task: diff --git a/example/kotlinlib/linting/2-ktlint/build.mill b/example/kotlinlib/linting/2-ktlint/build.mill index 762c902c4eb..b77476af730 100644 --- a/example/kotlinlib/linting/2-ktlint/build.mill +++ b/example/kotlinlib/linting/2-ktlint/build.mill @@ -28,4 +28,3 @@ error: ...src/example/FooWrong.kt:6:28: Missing newline before ")" (standard:par > ./mill ktlint # after fixing the violations, ktlint no longer errors */ - diff --git a/example/kotlinlib/module/1-common-config/build.mill b/example/kotlinlib/module/1-common-config/build.mill index d4249bf847e..b7a39e857f8 100644 --- a/example/kotlinlib/module/1-common-config/build.mill +++ b/example/kotlinlib/module/1-common-config/build.mill @@ -14,18 +14,18 @@ object `package` extends RootModule with KotlinModule { def mainClass = Some("foo.Foo2Kt") // Add (or replace) source folders for the module to use - def sources = T.sources{ + def sources = T.sources { super.sources() ++ Seq(PathRef(millSourcePath / "custom-src")) } // Add (or replace) resource folders for the module to use - def resources = T.sources{ + def resources = T.sources { super.resources() ++ Seq(PathRef(millSourcePath / "custom-resources")) } // Generate sources at build time def generatedSources: T[Seq[PathRef]] = Task { - for(name <- Seq("A", "B", "C")) os.write( + for (name <- Seq("A", "B", "C")) os.write( T.dest / s"Foo$name.kt", s""" |package foo diff --git a/example/kotlinlib/module/15-jni/build.mill b/example/kotlinlib/module/15-jni/build.mill index d5f64563716..d9deeccc4f0 100644 --- a/example/kotlinlib/module/15-jni/build.mill +++ b/example/kotlinlib/module/15-jni/build.mill @@ -15,13 +15,16 @@ object `package` extends RootModule with KotlinModule { val cSourceFiles = nativeSources().map(_.path).flatMap(os.walk(_)).filter(_.ext == "c") val output = "libhelloworld.so" os.proc( - "clang", "-shared", "-fPIC", - "-I" + sys.props("java.home") + "/include/", // global JVM header files - "-I" + sys.props("java.home") + "/include/darwin", - "-I" + sys.props("java.home") + "/include/linux", - "-o", T.dest / output, - cSourceFiles - ) + "clang", + "-shared", + "-fPIC", + "-I" + sys.props("java.home") + "/include/", // global JVM header files + "-I" + sys.props("java.home") + "/include/darwin", + "-I" + sys.props("java.home") + "/include/linux", + "-o", + T.dest / output, + cSourceFiles + ) .call(stdout = os.Inherit) PathRef(T.dest / output) diff --git a/example/kotlinlib/module/2-custom-tasks/build.mill b/example/kotlinlib/module/2-custom-tasks/build.mill index 4dbd7bda99c..e5a2bf6170f 100644 --- a/example/kotlinlib/module/2-custom-tasks/build.mill +++ b/example/kotlinlib/module/2-custom-tasks/build.mill @@ -11,7 +11,7 @@ object `package` extends RootModule with KotlinModule { def ivyDeps = Agg(ivy"com.github.ajalt.clikt:clikt-jvm:4.4.0") def generatedSources: T[Seq[PathRef]] = Task { - val prettyIvyDeps = for(ivyDep <- ivyDeps()) yield { + val prettyIvyDeps = for (ivyDep <- ivyDeps()) yield { val org = ivyDep.dep.module.organization.value val name = ivyDep.dep.module.name.value val version = ivyDep.dep.version diff --git a/example/kotlinlib/module/4-compilation-execution-flags/build.mill b/example/kotlinlib/module/4-compilation-execution-flags/build.mill index 0536411e396..8ad70cc8d0b 100644 --- a/example/kotlinlib/module/4-compilation-execution-flags/build.mill +++ b/example/kotlinlib/module/4-compilation-execution-flags/build.mill @@ -28,4 +28,4 @@ error: .../src/foo/Foo.kt... warning: 'stop(): Unit' is deprecated. Deprecated i */ -//// SNIPPET:END \ No newline at end of file +//// SNIPPET:END diff --git a/example/kotlinlib/module/9-docjar/build.mill b/example/kotlinlib/module/9-docjar/build.mill index 3efe7dd7b5b..a2bb950b0a7 100644 --- a/example/kotlinlib/module/9-docjar/build.mill +++ b/example/kotlinlib/module/9-docjar/build.mill @@ -11,7 +11,6 @@ object foo extends KotlinModule { } - /** Usage > ./mill show foo.docJar @@ -28,4 +27,4 @@ object foo extends KotlinModule { //// SNIPPET:END -//// SNIPPET:SCALA3 \ No newline at end of file +//// SNIPPET:SCALA3 diff --git a/example/kotlinlib/module/9-docjar/foo/src/foo/Bar.java b/example/kotlinlib/module/9-docjar/foo/src/foo/Bar.java index 533f9855344..b80ded1114d 100644 --- a/example/kotlinlib/module/9-docjar/foo/src/foo/Bar.java +++ b/example/kotlinlib/module/9-docjar/foo/src/foo/Bar.java @@ -4,7 +4,7 @@ * My Awesome Docs for class Bar */ public class Bar { - public void run() { - System.out.println(); - } + public void run() { + System.out.println(); + } } diff --git a/example/kotlinlib/testing/1-test-suite/build.mill b/example/kotlinlib/testing/1-test-suite/build.mill index d7183aecf81..c2bc445eeef 100644 --- a/example/kotlinlib/testing/1-test-suite/build.mill +++ b/example/kotlinlib/testing/1-test-suite/build.mill @@ -41,4 +41,3 @@ object bar extends KotlinModule { def kotlincOptions = super.kotlincOptions() ++ Seq("-jvm-target", "11") } } - diff --git a/example/kotlinlib/testing/4-test-grouping/build.mill b/example/kotlinlib/testing/4-test-grouping/build.mill index 350aad90db3..fda8ef631eb 100644 --- a/example/kotlinlib/testing/4-test-grouping/build.mill +++ b/example/kotlinlib/testing/4-test-grouping/build.mill @@ -23,4 +23,4 @@ object foo extends KotlinModule { /** See Also: foo/test/src/foo/HelloTests.kt */ /** See Also: foo/test/src/foo/WorldTests.kt */ -//// SNIPPET:END \ No newline at end of file +//// SNIPPET:END diff --git a/example/kotlinlib/web/1-hello-ktor/build.mill b/example/kotlinlib/web/1-hello-ktor/build.mill index 858c85eb6ba..2c5433ac14d 100644 --- a/example/kotlinlib/web/1-hello-ktor/build.mill +++ b/example/kotlinlib/web/1-hello-ktor/build.mill @@ -15,7 +15,7 @@ object `package` extends RootModule with KotlinModule { object test extends KotlinTests with TestModule.Junit5 { def ivyDeps = super.ivyDeps() ++ Agg( - ivy"io.kotest:kotest-runner-junit5-jvm:5.9.1", + ivy"io.kotest:kotest-runner-junit5-jvm:5.9.1", ivy"io.ktor:ktor-server-test-host-jvm:2.3.12" ) } @@ -24,7 +24,7 @@ object `package` extends RootModule with KotlinModule { /** See Also: src/com/example/HelloKtor.kt */ /** See Also: test/src/com/example/HelloKtorTest.kt */ -// This example demonstrates how to set up a simple webserver +// This example demonstrates how to set up a simple webserver // serving a single "

Hello, World!

" web page using Kotlin and Ktor. // It includes one module which is the Ktor webserver/app, and one test module // using kotest @@ -41,4 +41,4 @@ Test com.example.HelloKtorTest finished, took... > mill clean runBackground -*/ \ No newline at end of file +*/ diff --git a/example/kotlinlib/web/2-todo-ktor/build.mill b/example/kotlinlib/web/2-todo-ktor/build.mill index 5e7dfef5270..39ecd190549 100644 --- a/example/kotlinlib/web/2-todo-ktor/build.mill +++ b/example/kotlinlib/web/2-todo-ktor/build.mill @@ -14,18 +14,18 @@ object `package` extends RootModule with KotlinModule { val exposedVersion = "0.53.0" def ivyDeps = Agg( - ivy"io.ktor:ktor-server-core-jvm:$ktorVersion", - ivy"io.ktor:ktor-server-netty-jvm:$ktorVersion", - ivy"org.jetbrains.exposed:exposed-core:$exposedVersion", - ivy"org.jetbrains.exposed:exposed-jdbc:$exposedVersion", - ivy"com.h2database:h2:2.2.224", - ivy"io.ktor:ktor-server-webjars-jvm:$ktorVersion", - ivy"org.webjars:jquery:3.2.1", - ivy"io.ktor:ktor-server-thymeleaf-jvm:$ktorVersion", - ivy"org.webjars:webjars-locator:0.41", - ivy"org.webjars.npm:todomvc-common:1.0.5", - ivy"org.webjars.npm:todomvc-app-css:2.4.1", - ivy"ch.qos.logback:logback-classic:1.4.14" + ivy"io.ktor:ktor-server-core-jvm:$ktorVersion", + ivy"io.ktor:ktor-server-netty-jvm:$ktorVersion", + ivy"org.jetbrains.exposed:exposed-core:$exposedVersion", + ivy"org.jetbrains.exposed:exposed-jdbc:$exposedVersion", + ivy"com.h2database:h2:2.2.224", + ivy"io.ktor:ktor-server-webjars-jvm:$ktorVersion", + ivy"org.webjars:jquery:3.2.1", + ivy"io.ktor:ktor-server-thymeleaf-jvm:$ktorVersion", + ivy"org.webjars:webjars-locator:0.41", + ivy"org.webjars.npm:todomvc-common:1.0.5", + ivy"org.webjars.npm:todomvc-app-css:2.4.1", + ivy"ch.qos.logback:logback-classic:1.4.14" ) object test extends KotlinTests with TestModule.Junit5 { @@ -36,7 +36,6 @@ object `package` extends RootModule with KotlinModule { } } - // Apart from running a webserver, this example also demonstrates: // * Serving HTML templates using Thymeleaf diff --git a/example/kotlinlib/web/3-hello-kotlinjs/build.mill b/example/kotlinlib/web/3-hello-kotlinjs/build.mill index 6f18db8c741..6fdae02fe83 100644 --- a/example/kotlinlib/web/3-hello-kotlinjs/build.mill +++ b/example/kotlinlib/web/3-hello-kotlinjs/build.mill @@ -15,12 +15,11 @@ object `package` extends RootModule with KotlinJsModule { def kotlinVersion = "1.9.25" def kotlinJsRunTarget = Some(RunTarget.Node) def ivyDeps = Agg( - ivy"org.jetbrains.kotlinx:kotlinx-html-js:0.11.0", + ivy"org.jetbrains.kotlinx:kotlinx-html-js:0.11.0" ) object test extends KotlinJsModule with KotestTests } - /** Usage > mill run diff --git a/example/kotlinlib/web/4-webapp-kotlinjs/build.mill b/example/kotlinlib/web/4-webapp-kotlinjs/build.mill index 9f363193177..33e65f24726 100644 --- a/example/kotlinlib/web/4-webapp-kotlinjs/build.mill +++ b/example/kotlinlib/web/4-webapp-kotlinjs/build.mill @@ -18,7 +18,7 @@ object `package` extends RootModule with KotlinModule { def ivyDeps = Agg( ivy"io.ktor:ktor-server-core-jvm:$ktorVersion", ivy"io.ktor:ktor-server-netty-jvm:$ktorVersion", - ivy"io.ktor:ktor-server-html-builder-jvm:$ktorVersion", + ivy"io.ktor:ktor-server-html-builder-jvm:$ktorVersion" ) def resources = Task { @@ -44,7 +44,7 @@ object `package` extends RootModule with KotlinModule { override def splitPerModule = false def ivyDeps = Agg( - ivy"org.jetbrains.kotlinx:kotlinx-html-js:$kotlinHtmlVersion", + ivy"org.jetbrains.kotlinx:kotlinx-html-js:$kotlinHtmlVersion" ) } } diff --git a/example/kotlinlib/web/5-webapp-kotlinjs-shared/build.mill b/example/kotlinlib/web/5-webapp-kotlinjs-shared/build.mill index 3db344050e1..1da1dfae335 100644 --- a/example/kotlinlib/web/5-webapp-kotlinjs-shared/build.mill +++ b/example/kotlinlib/web/5-webapp-kotlinjs-shared/build.mill @@ -29,7 +29,7 @@ object `package` extends RootModule with AppKotlinModule { ivy"io.ktor:ktor-server-html-builder-jvm:$ktorVersion", ivy"io.ktor:ktor-server-content-negotiation-jvm:$ktorVersion", ivy"io.ktor:ktor-serialization-kotlinx-json-jvm:$ktorVersion", - ivy"ch.qos.logback:logback-classic:1.5.8", + ivy"ch.qos.logback:logback-classic:1.5.8" ) def resources = Task { @@ -66,13 +66,13 @@ object `package` extends RootModule with AppKotlinModule { object jvm extends SharedModule { def ivyDeps = super.ivyDeps() ++ Agg( ivy"org.jetbrains.kotlinx:kotlinx-html-jvm:$kotlinHtmlVersion", - ivy"org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:$kotlinxSerializationVersion", + ivy"org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:$kotlinxSerializationVersion" ) } object js extends SharedModule with AppKotlinJsModule { def ivyDeps = super.ivyDeps() ++ Agg( ivy"org.jetbrains.kotlinx:kotlinx-html-js:$kotlinHtmlVersion", - ivy"org.jetbrains.kotlinx:kotlinx-serialization-json-js:$kotlinxSerializationVersion", + ivy"org.jetbrains.kotlinx:kotlinx-serialization-json-js:$kotlinxSerializationVersion" ) } } @@ -82,12 +82,11 @@ object `package` extends RootModule with AppKotlinModule { def moduleDeps = Seq(shared.js) def ivyDeps = Agg( ivy"org.jetbrains.kotlinx:kotlinx-html-js:$kotlinHtmlVersion", - ivy"org.jetbrains.kotlinx:kotlinx-serialization-json-js:$kotlinxSerializationVersion", + ivy"org.jetbrains.kotlinx:kotlinx-serialization-json-js:$kotlinxSerializationVersion" ) } } - // The JSON serialization logic and HTML generation logic in the `shared` module // is shared between client and server, and uses libraries like `kotlinx-serialization` and // `kotlinx-html` which work on both Kotlin/JVM and Kotlin/JS. This allows us to freely diff --git a/example/package.mill b/example/package.mill index fedb790a290..e43806af832 100644 --- a/example/package.mill +++ b/example/package.mill @@ -105,6 +105,15 @@ object `package` extends RootModule with Module { val upstreamOpt = upstreamCross(this.millModuleSegments.parts.dropRight(1).last) .flatMap(_.valuesToModules.get(List(crossValue))) + + def sources = Task{ + super.sources() + .flatMap(pathRef => os.walk(pathRef.path)) + .filter(os.isFile) + .filterNot(p => p.ext == "java" && p.segments.contains("linting")) + .map(PathRef(_)) + } + def testRepoRoot = Task { os.copy(super.testRepoRoot().path, T.dest, mergeFolders = true) for(suffix <- Seq("build.sc", "build.mill", "build.mill.scala")){ @@ -169,9 +178,9 @@ object `package` extends RootModule with Module { trait ExampleCrossModule extends build.integration.IntegrationTestModule { // disable scalafix because these example modules don't have sources causing it to misbehave def fix(args: String*): Command[Unit] = T.command {} - def testRepoRoot: T[PathRef] = T.source(millSourcePath) + def testRepoRoot: T[PathRef] = Task.Source(millSourcePath) - def sources = Task.Sources { testRepoRoot().path } + def sources = Task.Sources(millSourcePath) def resources = Seq(testRepoRoot()) def runClasspath = build.main.test.runClasspath() def localRunClasspath = build.testkit.localRunClasspath() diff --git a/example/scalalib/basic/6-realistic/qux/src/Qux.java b/example/scalalib/basic/6-realistic/qux/src/Qux.java index bf88526d57c..9fc071c04ee 100644 --- a/example/scalalib/basic/6-realistic/qux/src/Qux.java +++ b/example/scalalib/basic/6-realistic/qux/src/Qux.java @@ -1,7 +1,9 @@ package qux; -public class Qux{ - public static final int value = 31337; - public static void main(String[] args){ - System.out.println("Qux.value: " + Qux.value); - } + +public class Qux { + public static final int value = 31337; + + public static void main(String[] args) { + System.out.println("Qux.value: " + Qux.value); + } } diff --git a/example/thirdparty/acyclic/build.mill b/example/thirdparty/acyclic/build.mill index f36a0656c5d..5b73eb200e0 100644 --- a/example/thirdparty/acyclic/build.mill +++ b/example/thirdparty/acyclic/build.mill @@ -18,8 +18,8 @@ object Deps { val crosses = Seq("2.11.12") ++ - Range.inclusive(8, 17).map("2.12." + _) ++ - Range.inclusive(0, 10).map("2.13." + _) + Range.inclusive(8, 17).map("2.12." + _) ++ + Range.inclusive(0, 10).map("2.13." + _) object acyclic extends Cross[AcyclicModule](crosses) trait AcyclicModule extends CrossScalaModule with PublishModule { @@ -82,4 +82,4 @@ compiling 6 Scala sources... -------------------------------- Running Tests -------------------------------- ... -*/ \ No newline at end of file +*/ diff --git a/example/thirdparty/arrow/build.mill b/example/thirdparty/arrow/build.mill index cf6800e619b..9dce0cbeaa8 100644 --- a/example/thirdparty/arrow/build.mill +++ b/example/thirdparty/arrow/build.mill @@ -102,7 +102,6 @@ object `package` extends RootModule { // `arrow-libs`.optics.`arrow-optics-ksp-plugin`, `arrow-libs`.optics.`arrow-optics-reflect`, `arrow-libs`.optics.`arrow-optics`, - `arrow-libs`.resilience.`arrow-resilience` ) @@ -127,7 +126,7 @@ object `package` extends RootModule { s"-Xcommon-sources=${files.mkString(",")}" } - trait ArrowPlatformModule extends KotlinMavenModule with PlatformKotlinModule { outer => + trait ArrowPlatformModule extends KotlinMavenModule with PlatformKotlinModule { outer => def kotlinVersion = libraries.versions.kotlin def kotlinLanguageVersion = majorVersion(kotlinVersion()) def kotlinApiVersion = majorVersion(kotlinVersion()) @@ -149,9 +148,9 @@ object `package` extends RootModule { override def kotlincOptions = super.kotlincOptions() ++ - Seq("-Xexpect-actual-classes", commonSourcesArg(sources(), "commonMain")) + Seq("-Xexpect-actual-classes", commonSourcesArg(sources(), "commonMain")) - trait ArrowPlatformTests extends KotlinMavenTests{ + trait ArrowPlatformTests extends KotlinMavenTests { override def compile: T[CompilationResult] = if (modulesWithTestingEnabled(multiplatformRoot)) super.compile @@ -174,8 +173,8 @@ object `package` extends RootModule { trait ArrowPlatformJvmModule extends ArrowPlatformModule with KoverModule { def test: ArrowPlatformJvmTests - trait ArrowPlatformJvmTests extends KotlinMavenTests with KoverTests with TestModule.Junit5 with ArrowPlatformTests{ - } + trait ArrowPlatformJvmTests extends KotlinMavenTests with KoverTests with TestModule.Junit5 + with ArrowPlatformTests {} } def js: ArrowPlatformJsModule @@ -184,7 +183,8 @@ object `package` extends RootModule { def kotlinJsRunTarget = Some(RunTarget.Node) def test: ArrowPlatformJsTests - trait ArrowPlatformJsTests extends KotlinMavenTests with KotlinTestPackageTests with ArrowPlatformTests{ + trait ArrowPlatformJsTests extends KotlinMavenTests with KotlinTestPackageTests + with ArrowPlatformTests { def testTimeout = 30_000L } } @@ -211,17 +211,17 @@ object `package` extends RootModule { object `arrow-libs` extends Module { object core extends Module { - object `arrow-annotations` extends ArrowMultiplatformModule{ - object jvm extends ArrowPlatformJvmModule{ + object `arrow-annotations` extends ArrowMultiplatformModule { + object jvm extends ArrowPlatformJvmModule { object test extends ArrowPlatformJvmTests } - object js extends ArrowPlatformJsModule{ + object js extends ArrowPlatformJsModule { object test extends ArrowPlatformJsTests } } object `arrow-atomic` extends ArrowMultiplatformModule { - object jvm extends ArrowPlatformJvmModule{ - object test extends ArrowPlatformJvmTests{ + object jvm extends ArrowPlatformJvmModule { + object test extends ArrowPlatformJvmTests { def moduleDeps = super.moduleDeps ++ Seq(fx.`arrow-fx-coroutines`.jvm) def ivyDeps = super.ivyDeps() ++ Agg( libraries.kotlinTestJunit5, @@ -231,8 +231,8 @@ object `package` extends RootModule { ) } } - object js extends ArrowPlatformJsModule{ - object test extends ArrowPlatformJsTests{ + object js extends ArrowPlatformJsModule { + object test extends ArrowPlatformJsTests { def moduleDeps = super.moduleDeps ++ Seq(fx.`arrow-fx-coroutines`.js) def ivyDeps = super.ivyDeps() ++ Agg( libraries.coroutinesTestJs, @@ -242,13 +242,11 @@ object `package` extends RootModule { } } - - } object `arrow-autoclose` extends ArrowMultiplatformModule { - object jvm extends ArrowPlatformJvmModule{ + object jvm extends ArrowPlatformJvmModule { def moduleDeps = super.moduleDeps ++ Seq(`arrow-atomic`.jvm) - object test extends ArrowPlatformJvmTests{ + object test extends ArrowPlatformJvmTests { def moduleDeps = super.moduleDeps ++ Seq(fx.`arrow-fx-coroutines`.jvm) def ivyDeps = super.ivyDeps() ++ Agg( libraries.kotlinTestJunit5, @@ -258,9 +256,9 @@ object `package` extends RootModule { def kotlincOptions = super.kotlincOptions() ++ Seq("-Xcontext-receivers") } } - object js extends ArrowPlatformJsModule{ + object js extends ArrowPlatformJsModule { def moduleDeps = super.moduleDeps ++ Seq(`arrow-atomic`.js) - object test extends ArrowPlatformJsTests{ + object test extends ArrowPlatformJsTests { def moduleDeps = super.moduleDeps ++ Seq(fx.`arrow-fx-coroutines`.js) def ivyDeps = super.ivyDeps() ++ Agg( libraries.coroutinesTestJs, @@ -271,12 +269,12 @@ object `package` extends RootModule { } object `arrow-cache4k` extends ArrowMultiplatformModule { - object jvm extends ArrowPlatformJvmModule{ + object jvm extends ArrowPlatformJvmModule { def moduleDeps = super.moduleDeps ++ Seq(`arrow-core`.jvm) def ivyDeps = super.ivyDeps() ++ Agg(libraries.cache4kJvm) object test extends ArrowPlatformJvmTests } - object js extends ArrowPlatformJsModule{ + object js extends ArrowPlatformJsModule { def moduleDeps = super.moduleDeps ++ Seq(`arrow-core`.js) def ivyDeps = super.ivyDeps() ++ Agg(libraries.cache4kJs) object test extends ArrowPlatformJsTests @@ -284,11 +282,11 @@ object `package` extends RootModule { } object `arrow-core-high-arity` extends ArrowMultiplatformModule { - object jvm extends ArrowPlatformJvmModule{ + object jvm extends ArrowPlatformJvmModule { def moduleDeps = super.moduleDeps ++ Seq(`arrow-core`.jvm) object test extends ArrowPlatformJvmTests } - object js extends ArrowPlatformJsModule{ + object js extends ArrowPlatformJsModule { def moduleDeps = super.moduleDeps ++ Seq(`arrow-core`.js) object test extends ArrowPlatformJsTests } @@ -301,7 +299,7 @@ object `package` extends RootModule { defaultResolver().resolveDeps(Agg(libraries.kotlinxSerializationPlugin)) } - object test extends ArrowJvmTests{ + object test extends ArrowJvmTests { def kotlincOptions = super.kotlincOptions() ++ Seq(s"-Xplugin=${processors().head.path}") def moduleDeps = super.moduleDeps ++ Seq(`arrow-core`.jvm) def ivyDeps = super.ivyDeps() ++ Agg( @@ -319,10 +317,10 @@ object `package` extends RootModule { } } object `arrow-core-serialization` extends ArrowMultiplatformModule { - object jvm extends ArrowPlatformJvmModule{ + object jvm extends ArrowPlatformJvmModule { def moduleDeps = super.moduleDeps ++ Seq(`arrow-core`.jvm) def ivyDeps = super.ivyDeps() ++ Agg(libraries.kotlinxSerializationCoreJvm) - object test extends ArrowPlatformJvmTests{ + object test extends ArrowPlatformJvmTests { def ivyDeps = super.ivyDeps() ++ Agg( libraries.kotlinTestJunit5, libraries.kotlinxSerializationJson, @@ -330,20 +328,22 @@ object `package` extends RootModule { libraries.kotestAssertionsCoreJvm, libraries.kotestPropertyJvm ) - def kotlincOptions = super.kotlincOptions() ++ Seq(s"-Xplugin=${processors().head.path}") + def kotlincOptions = + super.kotlincOptions() ++ Seq(s"-Xplugin=${processors().head.path}") } } - object js extends ArrowPlatformJsModule{ + object js extends ArrowPlatformJsModule { def moduleDeps = super.moduleDeps ++ Seq(`arrow-core`.js) def ivyDeps = super.ivyDeps() ++ Agg(libraries.kotlinxSerializationCoreJs) - object test extends ArrowPlatformJsTests{ + object test extends ArrowPlatformJsTests { def ivyDeps = super.ivyDeps() ++ Agg( libraries.kotlinxSerializationJsonJs, libraries.coroutinesTestJs, libraries.kotestAssertionsCoreJs, libraries.kotestPropertyJs ) - def kotlincOptions = super.kotlincOptions() ++ Seq(s"-Xplugin=${processors().head.path}") + def kotlincOptions = + super.kotlincOptions() ++ Seq(s"-Xplugin=${processors().head.path}") def testTimeout = 60_000L } } @@ -354,11 +354,11 @@ object `package` extends RootModule { } object `arrow-core` extends ArrowMultiplatformModule { - object jvm extends ArrowPlatformJvmModule{ + object jvm extends ArrowPlatformJvmModule { def moduleDeps = super.moduleDeps ++ Seq(`arrow-atomic`.jvm, `arrow-annotations`.jvm) def ivyDeps = super.ivyDeps() ++ Agg(libraries.kotlinxSerializationCoreJvm) def kotlincOptions = super.kotlincOptions() ++ Seq("-Xcontext-receivers") - object test extends ArrowPlatformJvmTests{ + object test extends ArrowPlatformJvmTests { def moduleDeps = super.moduleDeps ++ Seq(fx.`arrow-fx-coroutines`.jvm) def ivyDeps = super.ivyDeps() ++ Agg( @@ -369,7 +369,7 @@ object `package` extends RootModule { ) } } - object js extends ArrowPlatformJsModule{ + object js extends ArrowPlatformJsModule { def moduleDeps = super.moduleDeps ++ Seq(`arrow-atomic`.js, `arrow-annotations`.js) def ivyDeps = super.ivyDeps() ++ Agg(libraries.kotlinxSerializationCoreJs) object test extends ArrowPlatformJsTests { @@ -385,9 +385,9 @@ object `package` extends RootModule { } object `arrow-eval` extends ArrowMultiplatformModule { - object jvm extends ArrowPlatformJvmModule{ + object jvm extends ArrowPlatformJvmModule { def moduleDeps = super.moduleDeps ++ Seq(`arrow-core`.jvm) - object test extends ArrowPlatformJvmTests{ + object test extends ArrowPlatformJvmTests { def ivyDeps = super.ivyDeps() ++ Agg( libraries.kotlinTestJunit5, libraries.kotestAssertionsCoreJvm, @@ -395,9 +395,9 @@ object `package` extends RootModule { ) } } - object js extends ArrowPlatformJsModule{ + object js extends ArrowPlatformJsModule { def moduleDeps = super.moduleDeps ++ Seq(`arrow-core`.js) - object test extends ArrowPlatformJsTests{ + object test extends ArrowPlatformJsTests { def ivyDeps = super.ivyDeps() ++ Agg( libraries.kotestAssertionsCoreJs, libraries.kotestPropertyJs @@ -407,9 +407,9 @@ object `package` extends RootModule { } object `arrow-functions` extends ArrowMultiplatformModule { - object jvm extends ArrowPlatformJvmModule{ + object jvm extends ArrowPlatformJvmModule { def moduleDeps = super.moduleDeps ++ Seq(`arrow-atomic`.jvm, `arrow-annotations`.jvm) - object test extends ArrowPlatformJvmTests{ + object test extends ArrowPlatformJvmTests { def moduleDeps = super.moduleDeps ++ Seq(fx.`arrow-fx-coroutines`.jvm) def ivyDeps = super.ivyDeps() ++ Agg( @@ -420,9 +420,9 @@ object `package` extends RootModule { ) } } - object js extends ArrowPlatformJsModule{ + object js extends ArrowPlatformJsModule { def moduleDeps = super.moduleDeps ++ Seq(`arrow-atomic`.js, `arrow-annotations`.js) - object test extends ArrowPlatformJsTests{ + object test extends ArrowPlatformJsTests { def moduleDeps = super.moduleDeps ++ Seq(fx.`arrow-fx-coroutines`.js) def ivyDeps = super.ivyDeps() ++ Agg( libraries.coroutinesTestJs, @@ -436,10 +436,11 @@ object `package` extends RootModule { object fx extends Module { object `arrow-collectors` extends ArrowMultiplatformModule { - object jvm extends ArrowPlatformJvmModule{ - def moduleDeps = super.moduleDeps ++ Seq(core.`arrow-atomic`.jvm, `arrow-fx-coroutines`.jvm) + object jvm extends ArrowPlatformJvmModule { + def moduleDeps = + super.moduleDeps ++ Seq(core.`arrow-atomic`.jvm, `arrow-fx-coroutines`.jvm) def ivyDeps = super.ivyDeps() ++ Agg(libraries.coroutinesCoreJvm) - object test extends ArrowPlatformJvmTests{ + object test extends ArrowPlatformJvmTests { def ivyDeps = super.ivyDeps() ++ Agg( libraries.kotlinTestJunit5, libraries.coroutinesTestJvm, @@ -448,10 +449,10 @@ object `package` extends RootModule { ) } } - object js extends ArrowPlatformJsModule{ + object js extends ArrowPlatformJsModule { def moduleDeps = super.moduleDeps ++ Seq(core.`arrow-atomic`.js, `arrow-fx-coroutines`.js) def ivyDeps = super.ivyDeps() ++ Agg(libraries.coroutinesCoreJs) - object test extends ArrowPlatformJsTests{ + object test extends ArrowPlatformJsTests { def ivyDeps = super.ivyDeps() ++ Agg( libraries.coroutinesTestJs, libraries.kotestAssertionsCoreJs, @@ -461,16 +462,15 @@ object `package` extends RootModule { } } - } object `arrow-fx-coroutines` extends ArrowMultiplatformModule { - object jvm extends ArrowPlatformJvmModule{ - def moduleDeps = super.moduleDeps ++ Seq(core.`arrow-core`.jvm, core.`arrow-autoclose`.jvm) + object jvm extends ArrowPlatformJvmModule { + def moduleDeps = + super.moduleDeps ++ Seq(core.`arrow-core`.jvm, core.`arrow-autoclose`.jvm) def ivyDeps = super.ivyDeps() ++ Agg(libraries.coroutinesCoreJvm) - object test extends ArrowPlatformJvmTests{ + object test extends ArrowPlatformJvmTests { def moduleDeps = super.moduleDeps ++ Seq(core.`arrow-core`.jvm, core.`arrow-atomic`.jvm) - def ivyDeps = super.ivyDeps() ++ Agg( libraries.kotlinTestJunit5, libraries.coroutinesTestJvm, @@ -479,10 +479,10 @@ object `package` extends RootModule { ) } } - object js extends ArrowPlatformJsModule{ + object js extends ArrowPlatformJsModule { def moduleDeps = super.moduleDeps ++ Seq(core.`arrow-core`.js, core.`arrow-autoclose`.js) def ivyDeps = super.ivyDeps() ++ Agg(libraries.coroutinesCoreJs) - object test extends ArrowPlatformJsTests{ + object test extends ArrowPlatformJsTests { def moduleDeps = super.moduleDeps ++ Seq(core.`arrow-core`.js, core.`arrow-atomic`.js) def ivyDeps = super.ivyDeps() ++ Agg( libraries.coroutinesTestJs, @@ -493,16 +493,13 @@ object `package` extends RootModule { } } - - - } object `arrow-fx-stm` extends ArrowMultiplatformModule { - object jvm extends ArrowPlatformJvmModule{ + object jvm extends ArrowPlatformJvmModule { def moduleDeps = super.moduleDeps ++ Seq(core.`arrow-core`.jvm) def ivyDeps = super.ivyDeps() ++ Agg(libraries.coroutinesCoreJvm) def kotlincOptions = super.kotlincOptions() ++ additionalKotlincOptions - object test extends ArrowPlatformJvmTests{ + object test extends ArrowPlatformJvmTests { def moduleDeps = super.moduleDeps ++ Seq(`arrow-fx-coroutines`.jvm) def ivyDeps = super.ivyDeps() ++ Agg( libraries.kotlinTestJunit5, @@ -512,15 +509,13 @@ object `package` extends RootModule { ) } } - object js extends ArrowPlatformJsModule{ + object js extends ArrowPlatformJsModule { def moduleDeps = super.moduleDeps ++ Seq(core.`arrow-core`.js) def ivyDeps = super.ivyDeps() ++ Agg(libraries.coroutinesCoreJs) def kotlincOptions = super.kotlincOptions() ++ additionalKotlincOptions - object test extends ArrowPlatformJsTests{ + object test extends ArrowPlatformJsTests { def moduleDeps = super.moduleDeps ++ Seq(`arrow-fx-coroutines`.js) - - def ivyDeps = super.ivyDeps() ++ Agg( libraries.coroutinesTestJs, libraries.kotestAssertionsCoreJs, @@ -531,7 +526,6 @@ object `package` extends RootModule { } val additionalKotlincOptions = Seq("-Xconsistent-data-class-copy-visibility") - } } @@ -542,7 +536,7 @@ object `package` extends RootModule { def kotlinExplicitApi = false def ivyDeps = Agg(libraries.ksp) - object test extends ArrowJvmTests{ + object test extends ArrowJvmTests { def ivyDeps = super.ivyDeps() ++ Agg( libraries.kotlinTestJunit5, libraries.coroutinesTestJvm, @@ -564,7 +558,7 @@ object `package` extends RootModule { def moduleDeps = Seq(core.`arrow-core`.jvm, `arrow-optics`.jvm) def ivyDeps = Agg(libraries.kotlinReflect) - object test extends ArrowJvmTests{ + object test extends ArrowJvmTests { def ivyDeps = super.ivyDeps() ++ Agg( libraries.kotlinTestJunit5, libraries.coroutinesTestJvm, @@ -574,10 +568,11 @@ object `package` extends RootModule { } } object `arrow-optics` extends ArrowMultiplatformModule { - object jvm extends ArrowPlatformJvmModule{ + object jvm extends ArrowPlatformJvmModule { def moduleDeps = super.moduleDeps ++ Seq(core.`arrow-core`.jvm) - object test extends ArrowPlatformJvmTests{ - def kotlincOptions = super.kotlincOptions() ++ Seq(commonSourcesArg(jvm.test.sources(), "commonTest")) + object test extends ArrowPlatformJvmTests { + def kotlincOptions = + super.kotlincOptions() ++ Seq(commonSourcesArg(jvm.test.sources(), "commonTest")) def ivyDeps = super.ivyDeps() ++ Agg( libraries.kotlinTestJunit5, libraries.coroutinesTestJvm, @@ -586,10 +581,11 @@ object `package` extends RootModule { ) } } - object js extends ArrowPlatformJsModule{ + object js extends ArrowPlatformJsModule { def moduleDeps = super.moduleDeps ++ Seq(core.`arrow-core`.js) - object test extends ArrowPlatformJsTests{ - def kotlincOptions = super.kotlincOptions() ++ Seq(commonSourcesArg(js.test.sources(), "commonTest")) + object test extends ArrowPlatformJsTests { + def kotlincOptions = + super.kotlincOptions() ++ Seq(commonSourcesArg(js.test.sources(), "commonTest")) def ivyDeps = super.ivyDeps() ++ Agg( libraries.coroutinesTestJs, libraries.kotestAssertionsCoreJs, @@ -602,10 +598,10 @@ object `package` extends RootModule { object resilience extends Module { object `arrow-resilience` extends ArrowMultiplatformModule { - object jvm extends ArrowPlatformJvmModule{ + object jvm extends ArrowPlatformJvmModule { def moduleDeps = super.moduleDeps ++ Seq(core.`arrow-core`.jvm) def ivyDeps = super.ivyDeps() ++ Agg(libraries.coroutinesCoreJvm) - object test extends ArrowPlatformJvmTests{ + object test extends ArrowPlatformJvmTests { def moduleDeps = super.moduleDeps ++ Seq(fx.`arrow-fx-coroutines`.jvm) def ivyDeps = super.ivyDeps() ++ Agg( @@ -614,11 +610,11 @@ object `package` extends RootModule { ) } } - object js extends ArrowPlatformJsModule{ + object js extends ArrowPlatformJsModule { def moduleDeps = super.moduleDeps ++ Seq(core.`arrow-core`.js) def ivyDeps = super.ivyDeps() ++ Agg(libraries.coroutinesCoreJs) - object test extends ArrowPlatformJsTests{ - def moduleDeps = super.moduleDeps ++Seq(fx.`arrow-fx-coroutines`.js) + object test extends ArrowPlatformJsTests { + def moduleDeps = super.moduleDeps ++ Seq(fx.`arrow-fx-coroutines`.js) def ivyDeps = super.ivyDeps() ++ Agg( libraries.coroutinesTestJs diff --git a/example/thirdparty/commons-io/build.mill b/example/thirdparty/commons-io/build.mill index 31f552368bf..91b6d73f31f 100644 --- a/example/thirdparty/commons-io/build.mill +++ b/example/thirdparty/commons-io/build.mill @@ -15,7 +15,7 @@ object `package` extends RootModule with PublishModule with MavenModule { developers = Nil ) - object test extends MavenTests with TestModule.Junit5 with JmhModule{ + object test extends MavenTests with TestModule.Junit5 with JmhModule { def testSandboxWorkingDir = false def jmhCoreVersion = "1.37" def ivyDeps = super.ivyDeps() ++ Agg( @@ -28,7 +28,7 @@ object `package` extends RootModule with PublishModule with MavenModule { ivy"org.apache.commons:commons-lang3:3.14.0", ivy"commons-codec:commons-codec:1.17.1", ivy"org.openjdk.jmh:jmh-core:1.37", - ivy"org.openjdk.jmh:jmh-generator-annprocess:1.37", + ivy"org.openjdk.jmh:jmh-generator-annprocess:1.37" ) } } @@ -69,4 +69,4 @@ PathUtilsContentEqualsBenchmark.testCurrent_fileContentEquals_Blackhole ss PathUtilsContentEqualsBenchmark.testProposal_contentEquals ss 5 ... PathUtilsContentEqualsBenchmark.testProposal_contentEquals_Blackhole ss 5 ... -*/ \ No newline at end of file +*/ diff --git a/example/thirdparty/fansi/build.mill b/example/thirdparty/fansi/build.mill index c88e50cb216..5786f09a4f6 100644 --- a/example/thirdparty/fansi/build.mill +++ b/example/thirdparty/fansi/build.mill @@ -92,4 +92,4 @@ Starting process: node Publishing Artifact(com.lihaoyi,fansi_native0.4_3,1.3.3.7) to ivy repo... ... -*/ \ No newline at end of file +*/ diff --git a/example/thirdparty/gatling/build.mill b/example/thirdparty/gatling/build.mill index c976ceeba25..ef6d6b4a929 100644 --- a/example/thirdparty/gatling/build.mill +++ b/example/thirdparty/gatling/build.mill @@ -1,7 +1,6 @@ package build import mill._, scalalib._ - object Dependencies { // Compile dependencies @@ -198,7 +197,8 @@ object Dependencies { val benchmarkDependencies = Seq(jmh) - val recorderDependencies = Seq(gatlingSharedCli, scalaSwing, jackson, bouncyCastle, netty) ++ testDeps + val recorderDependencies = + Seq(gatlingSharedCli, scalaSwing, jackson, bouncyCastle, netty) ++ testDeps val testFrameworkDependencies = Seq(gatlingSharedCli, testInterface) @@ -215,17 +215,17 @@ object Dependencies { ) } -trait GatlingModule extends SbtModule{ +trait GatlingModule extends SbtModule { def scalaVersion = "2.13.14" def testModuleDeps: Seq[JavaModule] = Nil - object test extends SbtTests with TestModule.ScalaTest{ + object test extends SbtTests with TestModule.ScalaTest { def moduleDeps = super.moduleDeps ++ testModuleDeps def ivyDeps = Agg.from(Dependencies.testDeps) } } -object `gatling-app` extends GatlingModule{ +object `gatling-app` extends GatlingModule { def moduleDeps = Seq( `gatling-core`, `gatling-core-java`, @@ -241,20 +241,20 @@ object `gatling-app` extends GatlingModule{ ) def ivyDeps = Agg[Dep]() } -object `gatling-benchmarks` extends GatlingModule{ +object `gatling-benchmarks` extends GatlingModule { def moduleDeps = Seq(`gatling-core`, `gatling-http`) def ivyDeps = Agg.from(Dependencies.benchmarkDependencies) } -object `gatling-charts` extends GatlingModule{ +object `gatling-charts` extends GatlingModule { def moduleDeps = Seq(`gatling-core`) def testModuleDeps = Seq(`gatling-core`.test) def ivyDeps = Agg.from(Dependencies.chartsDependencies) } -object `gatling-commons` extends GatlingModule{ +object `gatling-commons` extends GatlingModule { def moduleDeps = Seq() def ivyDeps = Agg.from(Dependencies.commonsDependencies) } -object `gatling-core` extends GatlingModule{ +object `gatling-core` extends GatlingModule { def moduleDeps = Seq( `gatling-netty-util`, `gatling-quicklens`, @@ -267,78 +267,78 @@ object `gatling-core` extends GatlingModule{ ) def ivyDeps = Agg.from(Dependencies.coreDependencies) } -object `gatling-core-java` extends GatlingModule{ +object `gatling-core-java` extends GatlingModule { def moduleDeps = Seq(`gatling-core`) def testModuleDeps = Seq(`gatling-core`.test) def ivyDeps = Agg.from(Dependencies.coreJavaDependencies) } -object `gatling-http` extends GatlingModule{ +object `gatling-http` extends GatlingModule { def moduleDeps = Seq(`gatling-core`, `gatling-http-client`) def testModuleDeps = Seq(`gatling-core`.test, `gatling-http-client`.test) def ivyDeps = Agg.from(Dependencies.httpDependencies) } -object `gatling-http-client` extends GatlingModule{ +object `gatling-http-client` extends GatlingModule { def moduleDeps = Seq(`gatling-netty-util`) def testModuleDeps = Seq(`gatling-netty-util`.test) def ivyDeps = Agg.from(Dependencies.httpClientDependencies) } -object `gatling-http-java` extends GatlingModule{ +object `gatling-http-java` extends GatlingModule { def moduleDeps = Seq(`gatling-core-java`, `gatling-http`) def testModuleDeps = Seq(`gatling-http`.test) def ivyDeps = Agg.from(Dependencies.defaultJavaDependencies) } -object `gatling-jdbc` extends GatlingModule{ +object `gatling-jdbc` extends GatlingModule { def moduleDeps = Seq(`gatling-core`) def testModuleDeps = Seq(`gatling-core`.test) def ivyDeps = Agg.from(Dependencies.jdbcDependencies) } -object `gatling-jdbc-java` extends GatlingModule{ +object `gatling-jdbc-java` extends GatlingModule { def moduleDeps = Seq(`gatling-core-java`, `gatling-jdbc`) def testModuleDeps = Seq(`gatling-jdbc`.test) def ivyDeps = Agg.from(Dependencies.defaultJavaDependencies) } -object `gatling-jms` extends GatlingModule{ +object `gatling-jms` extends GatlingModule { def moduleDeps = Seq(`gatling-core`) def testModuleDeps = Seq(`gatling-core`.test) def ivyDeps = Agg.from(Dependencies.jmsDependencies) } -object `gatling-jms-java` extends GatlingModule{ +object `gatling-jms-java` extends GatlingModule { def moduleDeps = Seq(`gatling-core-java`, `gatling-jms`) def testModuleDeps = Seq(`gatling-jms`.test) def ivyDeps = Agg.from(Dependencies.defaultJavaDependencies) } -object `gatling-jsonpath` extends GatlingModule{ +object `gatling-jsonpath` extends GatlingModule { def moduleDeps = Seq() def ivyDeps = Agg.from(Dependencies.jsonpathDependencies) } -object `gatling-netty-util` extends GatlingModule{ +object `gatling-netty-util` extends GatlingModule { def moduleDeps = Seq() def ivyDeps = Agg.from(Dependencies.nettyUtilDependencies) } -object `gatling-quicklens` extends GatlingModule{ +object `gatling-quicklens` extends GatlingModule { def moduleDeps = Seq() def ivyDeps = Agg.from(Dependencies.quicklensDependencies(scalaVersion())) } -object `gatling-recorder` extends GatlingModule{ +object `gatling-recorder` extends GatlingModule { def moduleDeps = Seq(`gatling-core`, `gatling-http`) def testModuleDeps = Seq(`gatling-core`.test) def ivyDeps = Agg.from(Dependencies.recorderDependencies) } -object `gatling-redis` extends GatlingModule{ +object `gatling-redis` extends GatlingModule { def moduleDeps = Seq(`gatling-core`) def testModuleDeps = Seq(`gatling-core`.test) def ivyDeps = Agg.from(Dependencies.redisDependencies) } -object `gatling-redis-java` extends GatlingModule{ +object `gatling-redis-java` extends GatlingModule { def moduleDeps = Seq(`gatling-core-java`, `gatling-redis`) def testModuleDeps = Seq(`gatling-redis`.test) def ivyDeps = Agg.from(Dependencies.defaultJavaDependencies) } -object `gatling-samples` extends GatlingModule{ +object `gatling-samples` extends GatlingModule { def moduleDeps = Seq(`gatling-app`) def ivyDeps = Agg[Dep]() } -object `gatling-test-framework` extends GatlingModule{ +object `gatling-test-framework` extends GatlingModule { def moduleDeps = Seq(`gatling-app`) def ivyDeps = Agg.from(Dependencies.testFrameworkDependencies) } @@ -385,4 +385,4 @@ jsonPath.find.exists for TextMessage - should not fail on empty array ... -*/ \ No newline at end of file +*/ diff --git a/example/thirdparty/jimfs/build.mill b/example/thirdparty/jimfs/build.mill index b7ecf4ff87d..d967d889d00 100644 --- a/example/thirdparty/jimfs/build.mill +++ b/example/thirdparty/jimfs/build.mill @@ -6,11 +6,10 @@ def sharedCompileIvyDeps = Task { ivy"com.google.auto.service:auto-service:1.0.1", ivy"com.google.code.findbugs:jsr305:3.0.2", ivy"org.checkerframework:checker-compat-qual:2.5.5", - ivy"com.ibm.icu:icu4j:73.1", + ivy"com.ibm.icu:icu4j:73.1" ) } - object jimfs extends PublishModule with MavenModule { def publishVersion = "1.3.3.7" @@ -24,7 +23,7 @@ object jimfs extends PublishModule with MavenModule { ) def ivyDeps = sharedCompileIvyDeps() ++ Agg( - ivy"com.google.guava:guava:31.1-android", + ivy"com.google.guava:guava:31.1-android" ) def javacOptions = Seq("-processor", "com.google.auto.service.processor.AutoServiceProcessor") @@ -35,7 +34,7 @@ object jimfs extends PublishModule with MavenModule { ivy"com.google.guava:guava-testlib:31.1-android", ivy"com.google.truth:truth:1.1.3", ivy"com.github.sbt:junit-interface:0.13.2", - ivy"com.ibm.icu:icu4j:73.1", + ivy"com.ibm.icu:icu4j:73.1" ) def testFramework = "com.novocode.junit.JUnitFramework" @@ -61,4 +60,4 @@ Test run com.google.common.jimfs.FileTest started Test run com.google.common.jimfs.FileTest finished: 0 failed, 0 ignored, 7 total... ... -*/ \ No newline at end of file +*/ diff --git a/example/thirdparty/mockito/build.mill b/example/thirdparty/mockito/build.mill index ad0fbf5e3b1..2952aa906e1 100644 --- a/example/thirdparty/mockito/build.mill +++ b/example/thirdparty/mockito/build.mill @@ -1,7 +1,7 @@ package build import mill._, javalib._ -object libraries{ +object libraries { object versions { val bytebuddy = "1.14.18" @@ -31,12 +31,12 @@ object libraries{ val osgi = ivy"org.osgi:osgi.core:8.0.0" val equinox = ivy"org.eclipse.platform:org.eclipse.osgi:3.20.0" - val bndGradle = "biz.aQute.bnd:biz.aQute.bnd.gradle:6.4.0" + val bndGradle = "biz.aQute.bnd:biz.aQute.bnd.gradle:6.4.0" val groovy = ivy"org.codehaus.groovy:groovy:3.0.22" } -trait MockitoModule extends MavenModule{ +trait MockitoModule extends MavenModule { def testModuleDeps: Seq[JavaModule] = Nil def testIvyDeps: T[Agg[Dep]] = Agg.empty[Dep] def testRuntimeIvyDeps: T[Agg[Dep]] = Agg.empty[Dep] @@ -45,7 +45,7 @@ trait MockitoModule extends MavenModule{ def testFilteredSources: T[Seq[PathRef]] = Task { Seq.empty[PathRef] } - object test extends MavenTests{ + object test extends MavenTests { def moduleDeps = super.moduleDeps ++ MockitoModule.this.testModuleDeps def testFramework = MockitoModule.this.testFramework def runIvyDeps = testRuntimeIvyDeps() @@ -58,18 +58,20 @@ trait MockitoModule extends MavenModule{ } def ivyDeps = testIvyDeps() ++ - Agg( - libraries.hamcrest, - libraries.junit4, - libraries.bytebuddyagent, - ivy"com.github.sbt:junit-interface:0.13.2" - ) + Agg( + libraries.hamcrest, + libraries.junit4, + libraries.bytebuddyagent, + ivy"com.github.sbt:junit-interface:0.13.2" + ) } } -object `package` extends RootModule with MockitoModule{ +object `package` extends RootModule with MockitoModule { def compileIvyDeps = Agg( - libraries.hamcrest, libraries.junit4, libraries.bytebuddyagent, + libraries.hamcrest, + libraries.junit4, + libraries.bytebuddyagent, libraries.bytebuddy, libraries.opentest4j ) @@ -96,7 +98,9 @@ object `package` extends RootModule with MockitoModule{ def testFilteredSources: T[Seq[PathRef]] = Task { // test `add_listeners_concurrently_sanity_check` is flaky - Seq(PathRef(millSourcePath / "src/test/java/org/mockitousage/debugging/StubbingLookupListenerCallbackTest.java")) + Seq(PathRef( + millSourcePath / "src/test/java/org/mockitousage/debugging/StubbingLookupListenerCallbackTest.java" + )) } object subprojects extends Module { @@ -121,7 +125,7 @@ object `package` extends RootModule with MockitoModule{ "--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED", "--add-exports=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED", "--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED", - "--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED", + "--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED" ) def javacOptions = Seq( @@ -130,13 +134,13 @@ object `package` extends RootModule with MockitoModule{ "--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED" ) } - object extTest extends MockitoModule{ + object extTest extends MockitoModule { def moduleDeps = Seq(build, `junit-jupiter`) def testModuleDeps = Seq(build.test) def testIvyDeps = Agg( libraries.junit4, libraries.assertj, - libraries.junitJupiterApi, + libraries.junitJupiterApi ) def testRuntimeIvyDeps = Agg( @@ -146,7 +150,7 @@ object `package` extends RootModule with MockitoModule{ ) } - object inlineTest extends MockitoModule{ + object inlineTest extends MockitoModule { def testModuleDeps = Seq(build) def testIvyDeps = Agg(libraries.junit4, libraries.assertj) } @@ -156,8 +160,7 @@ object `package` extends RootModule with MockitoModule{ // def testIvyDeps = Agg(libraries.junit4, libraries.assertj) // } - - object `junit-jupiter` extends MockitoModule{ + object `junit-jupiter` extends MockitoModule { def moduleDeps = Seq(build) def ivyDeps = Agg(libraries.junitJupiterApi) @@ -169,39 +172,42 @@ object `package` extends RootModule with MockitoModule{ ) def testRuntimeIvyDeps = Agg( - libraries.junitJupiterEngine, + libraries.junitJupiterEngine ) } - object junitJupiterExtensionTest extends MockitoModule{ + object junitJupiterExtensionTest extends MockitoModule { def testFramework = "com.github.sbt.junit.jupiter.api.JupiterFramework" def testModuleDeps = Seq(`junit-jupiter`) def testIvyDeps = Agg(libraries.assertj, libraries.junitJupiterApi) def testRuntimeIvyDeps = Agg( - libraries.junitJupiterEngine, libraries.junitPlatformLauncher, + libraries.junitJupiterEngine, + libraries.junitPlatformLauncher, ivy"com.github.sbt.junit:jupiter-interface:0.11.4" ) } - object junitJupiterInlineMockMakerExtensionTest extends MockitoModule{ + object junitJupiterInlineMockMakerExtensionTest extends MockitoModule { def testFramework = "com.github.sbt.junit.jupiter.api.JupiterFramework" def testModuleDeps = Seq(`junit-jupiter`) def testIvyDeps = Agg(libraries.assertj, libraries.junitJupiterApi) def testRuntimeIvyDeps = Agg( - libraries.junitJupiterEngine, libraries.junitPlatformLauncher, + libraries.junitJupiterEngine, + libraries.junitPlatformLauncher, ivy"com.github.sbt.junit:jupiter-interface:0.11.4" ) } - object junitJupiterParallelTest extends MockitoModule{ + object junitJupiterParallelTest extends MockitoModule { def testFramework = "com.github.sbt.junit.jupiter.api.JupiterFramework" def testModuleDeps = Seq(`junit-jupiter`) def testIvyDeps = Agg(libraries.junitJupiterApi) def testRuntimeIvyDeps = Agg( - libraries.junitJupiterEngine, libraries.junitPlatformLauncher, + libraries.junitJupiterEngine, + libraries.junitPlatformLauncher, ivy"com.github.sbt.junit:jupiter-interface:0.11.4", libraries.bytebuddy ) } - object `memory-test` extends MockitoModule{ + object `memory-test` extends MockitoModule { def testModuleDeps = Seq(build) def testIvyDeps = Agg(libraries.assertj) def testForkArgs = Seq("-Xmx128m") @@ -258,22 +264,21 @@ object `package` extends RootModule with MockitoModule{ // s"-DtestRuntimeBundles=${testRuntimeBundles.runClasspath().map(_.path).distinct.filter(os.exists(_)).mkString(java.io.File.pathSeparator)}" // ) // } - object `programmatic-test` extends MockitoModule{ + object `programmatic-test` extends MockitoModule { def testModuleDeps = Seq(build) def testIvyDeps = Agg(libraries.junit4, libraries.assertj) } - object proxy extends MockitoModule{ + object proxy extends MockitoModule { def testModuleDeps = Seq(build) def testIvyDeps = Agg(libraries.junit4, libraries.assertj) } - object subclass extends MockitoModule{ + object subclass extends MockitoModule { def testModuleDeps = Seq(build) def testIvyDeps = Agg(libraries.junit4, libraries.assertj) } } } - // Run a few smoketests on the mockito repo, compiling everything (including tests) // but only running the subset of tests that run quickly /** Usage diff --git a/example/thirdparty/netty/build.mill b/example/thirdparty/netty/build.mill index b9a1a7f3099..582bf65ca57 100644 --- a/example/thirdparty/netty/build.mill +++ b/example/thirdparty/netty/build.mill @@ -10,10 +10,10 @@ import $ivy.`ant:ant-optional:1.5.3-1` def isOSX = System.getProperty("os.name").toLowerCase.contains("mac") -trait NettyBaseModule extends MavenModule{ +trait NettyBaseModule extends MavenModule { def javacOptions = Seq("-source", "1.8", "-target", "1.8") } -trait NettyBaseTestSuiteModule extends NettyBaseModule with TestModule.Junit5{ +trait NettyBaseTestSuiteModule extends NettyBaseModule with TestModule.Junit5 { def testSandboxWorkingDir = false def testFramework = "com.github.sbt.junit.jupiter.api.JupiterFramework" def ivyDeps = Agg( @@ -47,14 +47,15 @@ trait NettyBaseTestSuiteModule extends NettyBaseModule with TestModule.Junit5{ ivy"ch.qos.logback:logback-classic:1.1.7", ivy"org.eclipse.jetty.npn:npn-api:1.1.1.v20141010", ivy"org.bouncycastle:bcpkix-jdk15on:1.69", - ivy"org.bouncycastle:bctls-jdk15on:1.69", + ivy"org.bouncycastle:bctls-jdk15on:1.69" ) def forkArgs = Seq( "-DnativeImage.handlerMetadataGroupId=io.netty", "-Dio.netty.bootstrap.extensions=serviceload", "-XX:+AllowRedefinitionToAddDeleteMethods", - "--add-exports", "java.base/sun.security.x509=ALL-UNNAMED", + "--add-exports", + "java.base/sun.security.x509=ALL-UNNAMED", "-enableassertions" ) @@ -66,19 +67,17 @@ trait NettyBaseTestSuiteModule extends NettyBaseModule with TestModule.Junit5{ sup.copy(classes = PathRef(testClasses)) } } -trait NettyTestSuiteModule extends NettyBaseTestSuiteModule{ - -} -trait NettyModule extends NettyBaseModule{ +trait NettyTestSuiteModule extends NettyBaseTestSuiteModule {} +trait NettyModule extends NettyBaseModule { def testModuleDeps: Seq[MavenModule] = Nil def testIvyDeps: T[Agg[mill.scalalib.Dep]] = Task { Agg() } - object test extends NettyBaseTestSuiteModule with MavenTests{ + object test extends NettyBaseTestSuiteModule with MavenTests { def moduleDeps = super.moduleDeps ++ testModuleDeps def ivyDeps = super.ivyDeps() ++ testIvyDeps() def forkWorkingDir = NettyModule.this.millSourcePath def forkArgs = super.forkArgs() ++ Seq( - "-Dnativeimage.handlerMetadataArtifactId=netty-" + NettyModule.this.millModuleSegments.parts.last, + "-Dnativeimage.handlerMetadataArtifactId=netty-" + NettyModule.this.millModuleSegments.parts.last ) } @@ -99,14 +98,17 @@ trait NettyJniModule extends NettyModule { ) .toSeq - os.makeDir.all(Task.dest / "src/main/c") - os.proc("jar", "xf", sourceJar.path).call(cwd = Task.dest / "src/main/c") + os.makeDir.all(Task.dest / "src/main/c") + os.proc("jar", "xf", sourceJar.path).call(cwd = Task.dest / "src/main/c") os.proc( "clang", // CFLAGS - "-O3", "-Werror", "-fno-omit-frame-pointer", - "-Wunused-variable", "-fvisibility=hidden", + "-O3", + "-Werror", + "-fno-omit-frame-pointer", + "-Wunused-variable", + "-fvisibility=hidden", "-I" + (Task.dest / "src/main/c"), "-I" + `transport-native-unix-common`.cHeaders().path, "-I" + sys.props("java.home") + "/include/", @@ -128,16 +130,11 @@ trait NettyJniModule extends NettyModule { } } +object all extends NettyModule {} -object all extends NettyModule{ - -} +object bom extends NettyModule {} -object bom extends NettyModule{ - -} - -object buffer extends NettyModule{ +object buffer extends NettyModule { def moduleDeps = Seq(common) def testIvyDeps = Agg(ivy"org.jctools:jctools-core:4.0.5") } @@ -146,7 +143,7 @@ object codec extends NettyModule { def moduleDeps = Seq(common, buffer, transport) def testModuleDeps = Seq(transport.test) def ivyDeps = Agg( - ivy"com.google.protobuf:protobuf-java:2.6.1", + ivy"com.google.protobuf:protobuf-java:2.6.1" ) def compileIvyDeps = Agg( ivy"org.jboss.marshalling:jboss-marshalling:2.0.5.Final", @@ -156,71 +153,71 @@ object codec extends NettyModule { ivy"com.ning:compress-lzf:1.0.3", ivy"com.github.jponge:lzma-java:1.3", ivy"com.github.luben:zstd-jni:1.5.5-11", - ivy"com.google.protobuf.nano:protobuf-javanano:3.0.0-alpha-5", + ivy"com.google.protobuf.nano:protobuf-javanano:3.0.0-alpha-5" ) } -object `codec-dns` extends NettyModule{ +object `codec-dns` extends NettyModule { def moduleDeps = Seq(common, buffer, transport, codec) def testModuleDeps = Seq(transport.test) } -object `codec-haproxy` extends NettyModule{ +object `codec-haproxy` extends NettyModule { def moduleDeps = Seq(buffer, transport, codec) def testModuleDeps = Seq(transport.test) } -object `codec-http` extends NettyModule{ +object `codec-http` extends NettyModule { def moduleDeps = Seq(common, buffer, transport, codec, handler) def testModuleDeps = Seq(transport.test) def compileIvyDeps = Agg( ivy"com.jcraft:jzlib:1.1.3", - ivy"com.aayushatharva.brotli4j:brotli4j:1.16.0", + ivy"com.aayushatharva.brotli4j:brotli4j:1.16.0" ) def testIvyDeps = Agg( - ivy"com.aayushatharva.brotli4j:brotli4j:1.16.0", + ivy"com.aayushatharva.brotli4j:brotli4j:1.16.0" ) } -object `codec-http2` extends NettyModule{ +object `codec-http2` extends NettyModule { def moduleDeps = Seq(common, buffer, transport, codec, handler, `codec-http`) def testModuleDeps = Seq(transport.test) def compileIvyDeps = Agg( - ivy"com.aayushatharva.brotli4j:brotli4j:1.16.0", + ivy"com.aayushatharva.brotli4j:brotli4j:1.16.0" ) } -object `codec-memcache` extends NettyModule{ +object `codec-memcache` extends NettyModule { def moduleDeps = Seq(common, buffer, transport, codec) def testModuleDeps = Seq(transport.test) } -object `codec-mqtt` extends NettyModule{ +object `codec-mqtt` extends NettyModule { def moduleDeps = Seq(common, buffer, transport, codec) def testModuleDeps = Seq(transport.test) } -object `codec-redis` extends NettyModule{ +object `codec-redis` extends NettyModule { def moduleDeps = Seq(common, buffer, transport, codec) def testModuleDeps = Seq(transport.test) } -object `codec-smtp` extends NettyModule{ +object `codec-smtp` extends NettyModule { def moduleDeps = Seq(common, buffer, transport, codec) def testModuleDeps = Seq(transport.test) } -object `codec-socks` extends NettyModule{ +object `codec-socks` extends NettyModule { def moduleDeps = Seq(common, buffer, transport, codec) def testModuleDeps = Seq(transport.test) } -object `codec-stomp` extends NettyModule{ +object `codec-stomp` extends NettyModule { def moduleDeps = Seq(common, buffer, transport, codec) def testModuleDeps = Seq(transport.test) } -object `codec-xml` extends NettyModule{ +object `codec-xml` extends NettyModule { def moduleDeps = Seq(buffer, transport, codec) def testModuleDeps = Seq(transport.test) def ivyDeps = Agg( @@ -228,7 +225,7 @@ object `codec-xml` extends NettyModule{ ) } -object common extends NettyModule{ +object common extends NettyModule { def compileIvyDeps = Agg( ivy"org.jctools:jctools-core:4.0.5", ivy"org.graalvm.nativeimage:svm:19.3.6", @@ -237,7 +234,7 @@ object common extends NettyModule{ ivy"commons-logging:commons-logging:1.2", ivy"org.apache.logging.log4j:log4j-api:2.17.2", ivy"org.apache.logging.log4j:log4j-1.2-api:2.17.2", - ivy"org.slf4j:slf4j-api:1.7.30", + ivy"org.slf4j:slf4j-api:1.7.30" ) def testIvyDeps = Agg( ivy"org.jetbrains:annotations-java5:23.0.0", @@ -245,7 +242,7 @@ object common extends NettyModule{ ivy"org.apache.logging.log4j:log4j-api:2.17.2", ivy"org.apache.logging.log4j:log4j-core:2.17.2", ivy"org.apache.logging.log4j:log4j-1.2-api:2.17.2", - ivy"org.jctools:jctools-core:4.0.5", + ivy"org.jctools:jctools-core:4.0.5" ) def script = Task.Source(millSourcePath / "src/main/script") @@ -263,19 +260,16 @@ object common extends NettyModule{ (PathRef(Task.dest / "src"), PathRef(Task.dest / "testsrc")) } - def generatedSources = Task { Seq(generatedSources0()._1)} + def generatedSources = Task { Seq(generatedSources0()._1) } } -object `dev-tools` extends NettyModule{ +object `dev-tools` extends NettyModule {} -} - -object example extends NettyModule{ +object example extends NettyModule { def ivyDeps = Agg( ivy"org.bouncycastle:bcpkix-jdk15on:1.69", ivy"org.bouncycastle:bctls-jdk15on:1.69", ivy"com.sun.activation:javax.activation:1.2.0" - ) def moduleDeps = Seq( common, @@ -283,13 +277,23 @@ object example extends NettyModule{ transport, codec, handler, - `transport-sctp`, `transport-rxtx`, `transport-udt`, - `handler-proxy`, `codec-http`, `codec-memcache`, - `codec-http2`, `codec-redis`, `codec-socks`, `codec-stomp`, `codec-mqtt`, `codec-haproxy`, `codec-dns` + `transport-sctp`, + `transport-rxtx`, + `transport-udt`, + `handler-proxy`, + `codec-http`, + `codec-memcache`, + `codec-http2`, + `codec-redis`, + `codec-socks`, + `codec-stomp`, + `codec-mqtt`, + `codec-haproxy`, + `codec-dns` ) } -object handler extends NettyModule{ +object handler extends NettyModule { def moduleDeps = Seq(common, resolver, buffer, transport, `transport-native-unix-common`, codec) def testModuleDeps = Seq(transport.test) def compileIvyDeps = Agg( @@ -298,36 +302,41 @@ object handler extends NettyModule{ ivy"org.conscrypt:conscrypt-openjdk-uber:2.5.2", ivy"io.netty:netty-tcnative-classes:2.0.65.Final", ivy"org.eclipse.jetty.alpn:alpn-api:1.1.2.v20150522", - ivy"org.eclipse.jetty.npn:npn-api:1.1.1.v20141010", + ivy"org.eclipse.jetty.npn:npn-api:1.1.1.v20141010" ) def testIvyDeps = Agg( ivy"org.bouncycastle:bcpkix-jdk15on:1.69", ivy"org.bouncycastle:bctls-jdk15on:1.69", ivy"software.amazon.cryptools:AmazonCorrettoCryptoProvider:1.1.0;classifier=linux-x86_64", - ivy"org.conscrypt:conscrypt-openjdk-uber:2.5.2", - + ivy"org.conscrypt:conscrypt-openjdk-uber:2.5.2" ) } -object `handler-proxy` extends NettyModule{ +object `handler-proxy` extends NettyModule { def moduleDeps = Seq(common, buffer, transport, codec, `codec-socks`, `codec-http`, handler) def testModuleDeps = Seq(transport.test) } -object `handler-ssl-ocsp` extends NettyModule{ +object `handler-ssl-ocsp` extends NettyModule { def moduleDeps = Seq(`codec-http`, transport, `resolver-dns`) def ivyDeps = Agg( ivy"org.bouncycastle:bcpkix-jdk15on:1.69", - ivy"org.bouncycastle:bctls-jdk15on:1.69", + ivy"org.bouncycastle:bctls-jdk15on:1.69" ) } -object microbench extends NettyModule{ +object microbench extends NettyModule { def moduleDeps = Seq( - handler, `codec-http`, `codec-http2`, `codec-redis`, `codec-mqtt`, `codec-stomp`, - `transport-native-epoll`, `transport-native-kqueue` + handler, + `codec-http`, + `codec-http2`, + `codec-redis`, + `codec-mqtt`, + `codec-stomp`, + `transport-native-epoll`, + `transport-native-kqueue` ) def ivyDeps = Agg( @@ -339,11 +348,11 @@ object microbench extends NettyModule{ ) } -object resolver extends NettyModule{ +object resolver extends NettyModule { def moduleDeps = Seq(common) } -object `resolver-dns` extends NettyModule{ +object `resolver-dns` extends NettyModule { def moduleDeps = Seq(common, buffer, resolver, transport, codec, `codec-dns`, handler) def testModuleDeps = Seq(transport.test) def testIvyDeps = Agg( @@ -351,11 +360,10 @@ object `resolver-dns` extends NettyModule{ ) } -object `resolver-dns-classes-macos` extends NettyModule{ +object `resolver-dns-classes-macos` extends NettyModule { def moduleDeps = Seq(common, resolver, `transport-native-unix-common`, `resolver-dns`) } - object `resolver-dns-native-macos` extends NettyJniModule { def jniLibraryName = "libnetty_resolver_dns_native_macos_aarch_64.jnilib" def moduleDeps = Seq(resolver) @@ -364,19 +372,18 @@ object `resolver-dns-native-macos` extends NettyJniModule { ivy"org.apache.directory.server:apacheds-protocol-dns:1.5.7" ) - } -object testsuite extends NettyTestSuiteModule{ - def moduleDeps = Seq(common, resolver, transport, `transport-sctp`, handler, `codec-http`, `transport-udt`) +object testsuite extends NettyTestSuiteModule { + def moduleDeps = + Seq(common, resolver, transport, `transport-sctp`, handler, `codec-http`, `transport-udt`) def ivyDeps = super.ivyDeps() ++ Agg( ivy"org.slf4j:slf4j-api:1.7.30", - ivy"org.tukaani:xz:1.5", + ivy"org.tukaani:xz:1.5" ) } - -object `testsuite-autobahn` extends NettyTestSuiteModule{ +object `testsuite-autobahn` extends NettyTestSuiteModule { def moduleDeps = Seq(common, buffer, transport, `codec-http`) // override def test(args: String*) = { // val server = os.proc(assembly().path).spawn() @@ -392,8 +399,7 @@ object `testsuite-autobahn` extends NettyTestSuiteModule{ // } } - -object `testsuite-http2` extends NettyTestSuiteModule{ +object `testsuite-http2` extends NettyTestSuiteModule { def moduleDeps = Seq(common, buffer, transport, handler, `codec-http`, `codec-http2`) def h2Spec = Task { @@ -405,7 +411,7 @@ object `testsuite-http2` extends NettyTestSuiteModule{ os.proc("tar", "xzf", Task.dest / "h2spec.tar.gz").call(cwd = Task.dest) PathRef(Task.dest / "h2spec") } - override def test(args: String*) = Task.Command{ + override def test(args: String*) = Task.Command { val server = os.proc(assembly().path).spawn(stdout = os.Inherit) try { Thread.sleep(1000) // let the server start up @@ -434,7 +440,7 @@ object `testsuite-http2` extends NettyTestSuiteModule{ ("http2/5.1.1", "Sends stream identifier that is numerically smaller than previous"), ("http2/8.1.2.3", "Sends a HEADERS frame that omits \":method\" pseudo-header field"), ("http2/8.1.2.3", "Sends a HEADERS frame that omits \":scheme\" pseudo-header field"), - ("http2/8.1.2.3", "Sends a HEADERS frame that omits \":path\" pseudo-header field"), + ("http2/8.1.2.3", "Sends a HEADERS frame that omits \":path\" pseudo-header field") ) assert(errorDetails.toSet.subsetOf(expectedFailures)) } finally server.destroyForcibly() @@ -442,73 +448,90 @@ object `testsuite-http2` extends NettyTestSuiteModule{ } } -object `testsuite-native` extends NettyTestSuiteModule{ - def moduleDeps = Seq(`transport-native-kqueue`, `resolver-dns-native-macos`, `resolver-dns-classes-macos`, `transport-native-epoll`) +object `testsuite-native` extends NettyTestSuiteModule { + def moduleDeps = Seq( + `transport-native-kqueue`, + `resolver-dns-native-macos`, + `resolver-dns-classes-macos`, + `transport-native-epoll` + ) def testModuleDeps = Seq(`resolver-dns-classes-macos`) - override def sources = Task.Sources( millSourcePath / "src/test/java" ) + override def sources = Task.Sources(millSourcePath / "src/test/java") } -object `testsuite-native-image` extends NettyTestSuiteModule{ +object `testsuite-native-image` extends NettyTestSuiteModule { def moduleDeps = Seq(common, buffer, transport, handler, `codec-http`) } -object `testsuite-native-image-client` extends NettyTestSuiteModule{ +object `testsuite-native-image-client` extends NettyTestSuiteModule { def moduleDeps = Seq(transport, `resolver-dns`) } -object `testsuite-native-image-client-runtime-init` extends NettyTestSuiteModule{ +object `testsuite-native-image-client-runtime-init` extends NettyTestSuiteModule { def moduleDeps = Seq(common) } - -object `testsuite-osgi` extends NettyTestSuiteModule{ +object `testsuite-osgi` extends NettyTestSuiteModule { def moduleDeps = Seq( buffer, - codec, `codec-dns`, `codec-haproxy`, `codec-http`, `codec-http2`, `codec-memcache`, `codec-mqtt`, `codec-socks`, `codec-stomp`, + codec, + `codec-dns`, + `codec-haproxy`, + `codec-http`, + `codec-http2`, + `codec-memcache`, + `codec-mqtt`, + `codec-socks`, + `codec-stomp`, common, - handler, `handler-proxy`, - resolver, `resolver-dns`, - transport, `transport-sctp`, `transport-udt` + handler, + `handler-proxy`, + resolver, + `resolver-dns`, + transport, + `transport-sctp`, + `transport-udt` ) - override def sources = Task.Sources( millSourcePath / "src/test/java" ) + override def sources = Task.Sources(millSourcePath / "src/test/java") def ivyDeps = super.ivyDeps() ++ Agg( ivy"org.apache.felix:org.apache.felix.configadmin:1.9.14", ivy"org.ops4j.pax.exam:pax-exam-junit4:4.13.0", ivy"org.ops4j.pax.exam:pax-exam-container-native:4.13.0", ivy"org.ops4j.pax.exam:pax-exam-link-assembly:4.13.0", - ivy"org.apache.felix:org.apache.felix.framework:6.0.2", + ivy"org.apache.felix:org.apache.felix.framework:6.0.2" ) } -object `testsuite-shading` extends NettyTestSuiteModule{ +object `testsuite-shading` extends NettyTestSuiteModule { def moduleDeps = Seq(common) - override def sources = Task.Sources( millSourcePath / "src/test/java" ) + override def sources = Task.Sources(millSourcePath / "src/test/java") } -object transport extends NettyModule{ +object transport extends NettyModule { def moduleDeps = Seq(common, buffer, resolver) } -object `transport-blockhound-tests` extends NettyTestSuiteModule{ +object `transport-blockhound-tests` extends NettyTestSuiteModule { def moduleDeps = Seq(transport, handler, `resolver-dns`) def ivyDeps = super.ivyDeps() ++ Agg( ivy"io.projectreactor.tools:blockhound:1.0.6.RELEASE" ) } -object `transport-classes-epoll` extends NettyModule{ +object `transport-classes-epoll` extends NettyModule { def moduleDeps = Seq(common, buffer, transport, `transport-native-unix-common`) } -object `transport-classes-kqueue` extends NettyModule{ +object `transport-classes-kqueue` extends NettyModule { def moduleDeps = Seq(common, buffer, transport, `transport-native-unix-common`) } -object `transport-native-epoll` extends NettyJniModule{ +object `transport-native-epoll` extends NettyJniModule { def jniLibraryName = "libnetty_transport_native_epoll_aarch_64.jnilib" - def moduleDeps = Seq(common, buffer, transport, `transport-native-unix-common`, `transport-classes-epoll`) + def moduleDeps = + Seq(common, buffer, transport, `transport-native-unix-common`, `transport-classes-epoll`) def testModuleDeps = Seq(testsuite, `transport-native-unix-common-tests`) def testIvyDeps = Agg( @@ -516,26 +539,29 @@ object `transport-native-epoll` extends NettyJniModule{ ) // Stub this out on OS-X - def clang = if (!isOSX) T{ super.clang() } else T{ PathRef(os.temp())} + def clang = if (!isOSX) T { super.clang() } + else T { PathRef(os.temp()) } } -object `transport-native-kqueue` extends NettyJniModule{ +object `transport-native-kqueue` extends NettyJniModule { def jniLibraryName = "libnetty_transport_native_kqueue_aarch_64.jnilib" - def moduleDeps = Seq(common, buffer, transport, `transport-native-unix-common`, `transport-classes-kqueue`) + def moduleDeps = + Seq(common, buffer, transport, `transport-native-unix-common`, `transport-classes-kqueue`) def testModuleDeps = Seq(testsuite, `transport-native-unix-common-tests`) // Stub this out on linux - def clang = if (isOSX) T{ super.clang() } else T{ PathRef(os.temp())} + def clang = if (isOSX) T { super.clang() } + else T { PathRef(os.temp()) } } -object `transport-native-unix-common` extends NettyModule{ +object `transport-native-unix-common` extends NettyModule { def moduleDeps = Seq(common, buffer, transport) def ivyDeps = Agg(ivy"org.junit.jupiter:junit-jupiter-api:5.9.0") def makefile = Task.Source(millSourcePath / "Makefile") def cSources = Task.Source(millSourcePath / "src/main/c") def cHeaders = Task { - for(p <- os.walk(cSources().path) if p.ext == "h"){ + for (p <- os.walk(cSources().path) if p.ext == "h") { os.copy(p, Task.dest / p.relativeTo(cSources().path), createFolders = true) } PathRef(Task.dest) @@ -549,7 +575,7 @@ object `transport-native-unix-common` extends NettyModule{ os.copy(makefile().path, Task.dest / "Makefile") os.copy(cSources().path, Task.dest / "src/main/c", createFolders = true) - os.proc("jar", "xf", sourceJar.path).call(cwd = Task.dest / "src/main/c") + os.proc("jar", "xf", sourceJar.path).call(cwd = Task.dest / "src/main/c") os.proc("make").call( cwd = Task.dest, @@ -570,34 +596,33 @@ object `transport-native-unix-common` extends NettyModule{ "-fvisibility=hidden", "-I" + sys.props("java.home") + "/include/", "-I" + sys.props("java.home") + "/include/darwin", - "-I" + sys.props("java.home") + "/include/linux", + "-I" + sys.props("java.home") + "/include/linux" ).mkString(" "), "LD_FLAGS" -> "-Wl,--no-as-needed -lrt -Wl,-platform_version,macos,10.9,10.9", "LIB_NAME" -> "libnetty-unix-common" ) ) - (PathRef(Task.dest / "lib-out"), PathRef(Task.dest / "obj-out")) } } -object `transport-native-unix-common-tests` extends NettyTestSuiteModule{ +object `transport-native-unix-common-tests` extends NettyTestSuiteModule { def moduleDeps = Seq(transport, `transport-native-unix-common`) } -object `transport-rxtx` extends NettyModule{ +object `transport-rxtx` extends NettyModule { def moduleDeps = Seq(buffer, transport) def ivyDeps = Agg( ivy"org.rxtx:rxtx:2.1.7" ) } -object `transport-sctp` extends NettyModule{ +object `transport-sctp` extends NettyModule { def moduleDeps = Seq(common, buffer, transport, codec) def testModuleDeps = Seq(transport.test) } -object `transport-udt` extends NettyModule{ +object `transport-udt` extends NettyModule { def moduleDeps = Seq(common, buffer, transport) def ivyDeps = Agg( ivy"com.barchart.udt:barchart-udt-bundle:2.3.0", @@ -606,7 +631,6 @@ object `transport-udt` extends NettyModule{ ) } - // Run a few smoketests on the netty repo, compiling everything (including tests) // but only running the subset of tests that run quickly (otherwise this would // take over an hour) diff --git a/main/api/src/mill/java9rtexport/Copy.java b/main/api/src/mill/java9rtexport/Copy.java index d5a5ceb23e6..2cd981c836e 100644 --- a/main/api/src/mill/java9rtexport/Copy.java +++ b/main/api/src/mill/java9rtexport/Copy.java @@ -26,49 +26,51 @@ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING */ package mill.java9rtexport; +import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES; +import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; + import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.EnumSet; -import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES; -import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; - class Copy { - public static void copyDirectory(final Path source, final Path target) - throws IOException { - Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), - Integer.MAX_VALUE, new FileVisitor() { - - @Override - public FileVisitResult preVisitDirectory(Path dir, - BasicFileAttributes sourceBasic) throws IOException { + public static void copyDirectory(final Path source, final Path target) throws IOException { + Files.walkFileTree( + source, + EnumSet.of(FileVisitOption.FOLLOW_LINKS), + Integer.MAX_VALUE, + new FileVisitor() { - String relative = source.relativize(dir).toString(); - if (!Files.exists(target.getFileSystem().getPath(relative))) - Files.createDirectory(target.getFileSystem().getPath(relative)); - return FileVisitResult.CONTINUE; - } + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes sourceBasic) + throws IOException { - @Override - public FileVisitResult visitFile(Path file, - BasicFileAttributes attrs) throws IOException { - String relative = source.relativize(file).toString(); - Files.copy(file, target.getFileSystem().getPath(relative), COPY_ATTRIBUTES, REPLACE_EXISTING); - return FileVisitResult.CONTINUE; - } + String relative = source.relativize(dir).toString(); + if (!Files.exists(target.getFileSystem().getPath(relative))) + Files.createDirectory(target.getFileSystem().getPath(relative)); + return FileVisitResult.CONTINUE; + } - @Override - public FileVisitResult visitFileFailed(Path file, IOException e) throws IOException { - throw e; - } + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) + throws IOException { + String relative = source.relativize(file).toString(); + Files.copy( + file, target.getFileSystem().getPath(relative), COPY_ATTRIBUTES, REPLACE_EXISTING); + return FileVisitResult.CONTINUE; + } - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { - if (e != null) throw e; - return FileVisitResult.CONTINUE; - } - }); - } + @Override + public FileVisitResult visitFileFailed(Path file, IOException e) throws IOException { + throw e; + } + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { + if (e != null) throw e; + return FileVisitResult.CONTINUE; + } + }); + } } diff --git a/main/api/src/mill/java9rtexport/Export.java b/main/api/src/mill/java9rtexport/Export.java index 2c75413fa0a..71e439bf831 100644 --- a/main/api/src/mill/java9rtexport/Export.java +++ b/main/api/src/mill/java9rtexport/Export.java @@ -38,69 +38,68 @@ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING import java.util.Map; class Export0 { - private final static Object lock = new Object(); - private static File tempFile = null; + private static final Object lock = new Object(); + private static File tempFile = null; - public static String rtJarName = "rt-" + System.getProperty("java.version") + ".jar"; + public static String rtJarName = "rt-" + System.getProperty("java.version") + ".jar"; - public static File rt() { - try { - synchronized (lock) { - if (tempFile == null) { - Path tempPath = Files.createTempFile("rt", ".jar"); - tempFile = tempPath.toFile(); - tempFile.deleteOnExit(); - tempFile.delete(); - FileSystem fileSystem = FileSystems.getFileSystem(URI.create("jrt:/")); - Path path = fileSystem.getPath("/modules"); - URI uri = URI.create("jar:" + tempPath.toUri()); - Map env = new HashMap<>(); - env.put("create", "true"); - try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) { - Iterator iterator = Files.list(path).iterator(); - while (iterator.hasNext()) { - Path next = iterator.next(); - Copy.copyDirectory(next, zipfs.getPath("/")); - } - } - } + public static File rt() { + try { + synchronized (lock) { + if (tempFile == null) { + Path tempPath = Files.createTempFile("rt", ".jar"); + tempFile = tempPath.toFile(); + tempFile.deleteOnExit(); + tempFile.delete(); + FileSystem fileSystem = FileSystems.getFileSystem(URI.create("jrt:/")); + Path path = fileSystem.getPath("/modules"); + URI uri = URI.create("jar:" + tempPath.toUri()); + Map env = new HashMap<>(); + env.put("create", "true"); + try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) { + Iterator iterator = Files.list(path).iterator(); + while (iterator.hasNext()) { + Path next = iterator.next(); + Copy.copyDirectory(next, zipfs.getPath("/")); } - } catch (IOException e) { - e.printStackTrace(); - System.exit(-1); + } } - return tempFile; + } + } catch (IOException e) { + e.printStackTrace(); + System.exit(-1); } + return tempFile; + } - public static boolean rtTo(File dest, boolean verbose) { - try { - if (!dest.exists()) { - if (verbose) { - System.out.println("Copying Java " + - System.getProperty("java.version") + - " runtime jar to " + - dest.getParentFile() + - " ..."); - System.out.flush(); - } - dest.getParentFile().mkdirs(); - Files.copy(rt().toPath(), dest.toPath()); - return true; - } - } catch (IOException e) { - e.printStackTrace(); - System.exit(-1); + public static boolean rtTo(File dest, boolean verbose) { + try { + if (!dest.exists()) { + if (verbose) { + System.out.println("Copying Java " + System.getProperty("java.version") + + " runtime jar to " + + dest.getParentFile() + + " ..."); + System.out.flush(); } - return false; + dest.getParentFile().mkdirs(); + Files.copy(rt().toPath(), dest.toPath()); + return true; + } + } catch (IOException e) { + e.printStackTrace(); + System.exit(-1); } + return false; + } - public static File rtAt(File dir, boolean verbose) { - File f = new File(dir, rtJarName); - rtTo(f, verbose); - return f; - } + public static File rtAt(File dir, boolean verbose) { + File f = new File(dir, rtJarName); + rtTo(f, verbose); + return f; + } - public static File rtAt(File dir) { - return rtAt(dir, false); - } + public static File rtAt(File dir) { + return rtAt(dir, false); + } } diff --git a/main/client/src/mill/main/client/CodeGenConstants.java b/main/client/src/mill/main/client/CodeGenConstants.java index 5a5f1b55733..a8c99aa5033 100644 --- a/main/client/src/mill/main/client/CodeGenConstants.java +++ b/main/client/src/mill/main/client/CodeGenConstants.java @@ -1,40 +1,41 @@ package mill.main.client; - public class CodeGenConstants { - /** - * Global package prefix for Mill builds. Cannot be `build` because - * it would conflict with the name of the `lazy val build ` object - * we import to work around the need for the `.package` suffix, so - * we add an `_` and call it `build_` - */ - final public static String globalPackagePrefix = "build_"; + /** + * Global package prefix for Mill builds. Cannot be `build` because + * it would conflict with the name of the `lazy val build ` object + * we import to work around the need for the `.package` suffix, so + * we add an `_` and call it `build_` + */ + public static final String globalPackagePrefix = "build_"; - /** - * What the wrapper objects are called. Not `package` because we don't - * want them to be `package objects` due to weird edge case behavior, - * even though we want them to look like package objects to users and IDEs, - * so we add an `_` and call it `package_` - */ - final public static String wrapperObjectName = "package_"; + /** + * What the wrapper objects are called. Not `package` because we don't + * want them to be `package objects` due to weird edge case behavior, + * even though we want them to look like package objects to users and IDEs, + * so we add an `_` and call it `package_` + */ + public static final String wrapperObjectName = "package_"; - /** - * The name of the root build file - */ - final public static String[] rootBuildFileNames = {"build.mill", "build.mill.scala", "build.sc"}; + /** + * The name of the root build file + */ + public static final String[] rootBuildFileNames = {"build.mill", "build.mill.scala", "build.sc"}; - /** - * The name of any sub-folder build files - */ - final public static String[] nestedBuildFileNames = {"package.mill", "package.mill.scala", "package.sc"}; + /** + * The name of any sub-folder build files + */ + public static final String[] nestedBuildFileNames = { + "package.mill", "package.mill.scala", "package.sc" + }; - /** - * The extensions used by build files - */ - final public static String[] buildFileExtensions = {"mill", "mill.scala", "sc"}; + /** + * The extensions used by build files + */ + public static final String[] buildFileExtensions = {"mill", "mill.scala", "sc"}; - /** - * The user-facing name for the root of the module tree. - */ - final public static String rootModuleAlias = "build"; + /** + * The user-facing name for the root of the module tree. + */ + public static final String rootModuleAlias = "build"; } diff --git a/main/client/src/mill/main/client/DebugLog.java b/main/client/src/mill/main/client/DebugLog.java index f2c842a57da..bb4631f9e61 100644 --- a/main/client/src/mill/main/client/DebugLog.java +++ b/main/client/src/mill/main/client/DebugLog.java @@ -1,4 +1,5 @@ package mill.main.client; + import java.io.IOException; import java.nio.file.*; @@ -7,14 +8,14 @@ * your stdout/stderr/logs are going, and so we just dump them in a file in your * home folder so you can find them */ -public class DebugLog{ - synchronized public static void println(String s){ - Path path = Paths.get(System.getProperty("user.home"), "mill-debug-log.txt"); - try { - if (!Files.exists(path)) Files.createFile(path); - Files.writeString(path, s + "\n", StandardOpenOption.APPEND); - }catch (IOException e){ - throw new RuntimeException(e); - } +public class DebugLog { + public static synchronized void println(String s) { + Path path = Paths.get(System.getProperty("user.home"), "mill-debug-log.txt"); + try { + if (!Files.exists(path)) Files.createFile(path); + Files.writeString(path, s + "\n", StandardOpenOption.APPEND); + } catch (IOException e) { + throw new RuntimeException(e); } + } } diff --git a/main/client/src/mill/main/client/EnvVars.java b/main/client/src/mill/main/client/EnvVars.java index 8ac1aa905c3..6ea62d17756 100644 --- a/main/client/src/mill/main/client/EnvVars.java +++ b/main/client/src/mill/main/client/EnvVars.java @@ -4,52 +4,48 @@ * Central place containing all the environment variables that Mill uses */ public class EnvVars { - // USER FACING ENVIRONMENT VARIABLES - - /** - * Available in test modules for users to find the test resource folder on disk - * in a convenient fashion. If multiple resource folders are provided on the classpath, - * they are provided as a comma-separated list - */ - public static final String MILL_TEST_RESOURCE_DIR = "MILL_TEST_RESOURCE_DIR"; - - - /** - * How long the Mill background server should run before timing out from inactivity - */ - public static final String MILL_SERVER_TIMEOUT_MILLIS = "MILL_SERVER_TIMEOUT_MILLIS"; - - - public static final String MILL_JVM_OPTS_PATH = "MILL_JVM_OPTS_PATH"; - public static final String MILL_OPTS_PATH = "MILL_OPTS_PATH"; - - - /** - * Output directory where Mill workers' state and Mill tasks output should be - * written to - */ - public static final String MILL_OUTPUT_DIR = "MILL_OUTPUT_DIR"; - - // INTERNAL ENVIRONMENT VARIABLES - /** - * Used to pass the Mill workspace root from the client to the server, so - * the server code can access it despite it not being os.pwd. - * - * Also, available in test modules for users to find the root folder of the - * mill project on disk. Not intended for common usage, but sometimes necessary. - */ - public static final String MILL_WORKSPACE_ROOT = "MILL_WORKSPACE_ROOT"; - - /** - * Used to indicate to Mill that it is running as part of the Mill test suite, - * e.g. to turn on additional testing/debug/log-related code - */ - public static final String MILL_TEST_SUITE = "MILL_TEST_SUITE"; - - /** - * Used to indicate to the Mill test suite which libraries should be resolved from - * the local disk and not from Maven Central - */ - public static final String MILL_BUILD_LIBRARIES = "MILL_BUILD_LIBRARIES"; - + // USER FACING ENVIRONMENT VARIABLES + + /** + * Available in test modules for users to find the test resource folder on disk + * in a convenient fashion. If multiple resource folders are provided on the classpath, + * they are provided as a comma-separated list + */ + public static final String MILL_TEST_RESOURCE_DIR = "MILL_TEST_RESOURCE_DIR"; + + /** + * How long the Mill background server should run before timing out from inactivity + */ + public static final String MILL_SERVER_TIMEOUT_MILLIS = "MILL_SERVER_TIMEOUT_MILLIS"; + + public static final String MILL_JVM_OPTS_PATH = "MILL_JVM_OPTS_PATH"; + public static final String MILL_OPTS_PATH = "MILL_OPTS_PATH"; + + /** + * Output directory where Mill workers' state and Mill tasks output should be + * written to + */ + public static final String MILL_OUTPUT_DIR = "MILL_OUTPUT_DIR"; + + // INTERNAL ENVIRONMENT VARIABLES + /** + * Used to pass the Mill workspace root from the client to the server, so + * the server code can access it despite it not being os.pwd. + * + * Also, available in test modules for users to find the root folder of the + * mill project on disk. Not intended for common usage, but sometimes necessary. + */ + public static final String MILL_WORKSPACE_ROOT = "MILL_WORKSPACE_ROOT"; + + /** + * Used to indicate to Mill that it is running as part of the Mill test suite, + * e.g. to turn on additional testing/debug/log-related code + */ + public static final String MILL_TEST_SUITE = "MILL_TEST_SUITE"; + + /** + * Used to indicate to the Mill test suite which libraries should be resolved from + * the local disk and not from Maven Central + */ + public static final String MILL_BUILD_LIBRARIES = "MILL_BUILD_LIBRARIES"; } diff --git a/main/client/src/mill/main/client/FileToStreamTailer.java b/main/client/src/mill/main/client/FileToStreamTailer.java index 9847f5db6d0..5976a9aee29 100644 --- a/main/client/src/mill/main/client/FileToStreamTailer.java +++ b/main/client/src/mill/main/client/FileToStreamTailer.java @@ -10,96 +10,96 @@ public class FileToStreamTailer extends Thread implements AutoCloseable { - private final File file; - private final PrintStream stream; - private final int intervalMsec; + private final File file; + private final PrintStream stream; + private final int intervalMsec; - // if true, we won't read the whole file, but only new lines - private boolean ignoreHead = true; + // if true, we won't read the whole file, but only new lines + private boolean ignoreHead = true; - private volatile boolean keepReading = true; - private volatile boolean flush = false; + private volatile boolean keepReading = true; + private volatile boolean flush = false; - public FileToStreamTailer(File file, PrintStream stream, int intervalMsec) { - super("Tail"); - this.intervalMsec = intervalMsec; - setDaemon(true); - this.file = file; - this.stream = stream; - } + public FileToStreamTailer(File file, PrintStream stream, int intervalMsec) { + super("Tail"); + this.intervalMsec = intervalMsec; + setDaemon(true); + this.file = file; + this.stream = stream; + } - @Override - public void run() { - if (isInterrupted()) { - keepReading = false; - } - Optional reader = Optional.empty(); + @Override + public void run() { + if (isInterrupted()) { + keepReading = false; + } + Optional reader = Optional.empty(); + try { + while (keepReading || flush) { + flush = false; try { - while (keepReading || flush) { - flush = false; - try { - // Init reader, if not already done - if (!reader.isPresent()) { - try { - reader = Optional.of(new BufferedReader(new FileReader(file))); - } catch (FileNotFoundException e) { - // nothing to ignore if file is initially missing - ignoreHead = false; - } - } - reader.ifPresent(r -> { - // read lines - try { - String line; - while ((line = r.readLine()) != null) { - if (!ignoreHead) { - stream.println(line); - } - } - // we ignored once - this.ignoreHead = false; - } catch (IOException e) { - // could not read line or file vanished - } - }); - } finally { - if (keepReading) { - // wait - try { - Thread.sleep(intervalMsec); - } catch (InterruptedException e) { - // can't handle anyway - } - } + // Init reader, if not already done + if (!reader.isPresent()) { + try { + reader = Optional.of(new BufferedReader(new FileReader(file))); + } catch (FileNotFoundException e) { + // nothing to ignore if file is initially missing + ignoreHead = false; + } + } + reader.ifPresent(r -> { + // read lines + try { + String line; + while ((line = r.readLine()) != null) { + if (!ignoreHead) { + stream.println(line); } + } + // we ignored once + this.ignoreHead = false; + } catch (IOException e) { + // could not read line or file vanished } + }); } finally { - reader.ifPresent(r -> { - try { - r.close(); - } catch (IOException e) { - // could not close but also can't do anything about it - } - }); + if (keepReading) { + // wait + try { + Thread.sleep(intervalMsec); + } catch (InterruptedException e) { + // can't handle anyway + } + } } + } + } finally { + reader.ifPresent(r -> { + try { + r.close(); + } catch (IOException e) { + // could not close but also can't do anything about it + } + }); } + } - @Override - public void interrupt() { - this.keepReading = false; - super.interrupt(); - } + @Override + public void interrupt() { + this.keepReading = false; + super.interrupt(); + } - /** - * Force a next read, even if we interrupt the thread. - */ - public void flush() { - this.flush = true; - } + /** + * Force a next read, even if we interrupt the thread. + */ + public void flush() { + this.flush = true; + } - @Override - public void close() throws Exception { - flush(); - interrupt(); - } + @Override + public void close() throws Exception { + flush(); + interrupt(); + } } diff --git a/main/client/src/mill/main/client/InputPumper.java b/main/client/src/mill/main/client/InputPumper.java index 1bddc0bc656..3cf432a65b3 100644 --- a/main/client/src/mill/main/client/InputPumper.java +++ b/main/client/src/mill/main/client/InputPumper.java @@ -4,61 +4,62 @@ import java.io.OutputStream; import java.util.function.Supplier; -public class InputPumper implements Runnable{ - private Supplier src0; - private Supplier dest0; +public class InputPumper implements Runnable { + private Supplier src0; + private Supplier dest0; - private Boolean checkAvailable; - private java.util.function.BooleanSupplier runningCheck; - public InputPumper(Supplier src, - Supplier dest, - Boolean checkAvailable){ - this(src, dest, checkAvailable, () -> true); - } - public InputPumper(Supplier src, - Supplier dest, - Boolean checkAvailable, - java.util.function.BooleanSupplier runningCheck){ - this.src0 = src; - this.dest0 = dest; - this.checkAvailable = checkAvailable; - this.runningCheck = runningCheck; - } + private Boolean checkAvailable; + private java.util.function.BooleanSupplier runningCheck; + + public InputPumper( + Supplier src, Supplier dest, Boolean checkAvailable) { + this(src, dest, checkAvailable, () -> true); + } + + public InputPumper( + Supplier src, + Supplier dest, + Boolean checkAvailable, + java.util.function.BooleanSupplier runningCheck) { + this.src0 = src; + this.dest0 = dest; + this.checkAvailable = checkAvailable; + this.runningCheck = runningCheck; + } + + boolean running = true; - boolean running = true; - public void run() { - InputStream src = src0.get(); - OutputStream dest = dest0.get(); + public void run() { + InputStream src = src0.get(); + OutputStream dest = dest0.get(); - byte[] buffer = new byte[1024]; - try{ - while(running){ - if (!runningCheck.getAsBoolean()) { - running = false; - } - else if (checkAvailable && src.available() == 0) Thread.sleep(2); - else { - int n; - try{ - n = src.read(buffer); - } catch (Exception e){ - n = -1; - } - if (n == -1) { - running = false; - } - else { - try { - dest.write(buffer, 0, n); - dest.flush(); - }catch(java.io.IOException e){ - running = false; - } - } - } + byte[] buffer = new byte[1024]; + try { + while (running) { + if (!runningCheck.getAsBoolean()) { + running = false; + } else if (checkAvailable && src.available() == 0) Thread.sleep(2); + else { + int n; + try { + n = src.read(buffer); + } catch (Exception e) { + n = -1; + } + if (n == -1) { + running = false; + } else { + try { + dest.write(buffer, 0, n); + dest.flush(); + } catch (java.io.IOException e) { + running = false; } - }catch(Exception e){ - throw new RuntimeException(e); + } } + } + } catch (Exception e) { + throw new RuntimeException(e); } + } } diff --git a/main/client/src/mill/main/client/OutFiles.java b/main/client/src/mill/main/client/OutFiles.java index c502b982609..e30f06b392f 100644 --- a/main/client/src/mill/main/client/OutFiles.java +++ b/main/client/src/mill/main/client/OutFiles.java @@ -6,65 +6,64 @@ */ public class OutFiles { - final private static String envOutOrNull = System.getenv(EnvVars.MILL_OUTPUT_DIR); + private static final String envOutOrNull = System.getenv(EnvVars.MILL_OUTPUT_DIR); - /** - * Default hard-coded value for the Mill `out/` folder path. Unless you know - * what you are doing, you should favor using [[out]] instead. - */ - final public static String defaultOut = "out"; + /** + * Default hard-coded value for the Mill `out/` folder path. Unless you know + * what you are doing, you should favor using [[out]] instead. + */ + public static final String defaultOut = "out"; - /** - * Path of the Mill `out/` folder - */ - final public static String out = envOutOrNull == null ? defaultOut : envOutOrNull; + /** + * Path of the Mill `out/` folder + */ + public static final String out = envOutOrNull == null ? defaultOut : envOutOrNull; - /** - * Path of the Mill "meta-build", used to compile the `build.sc` file so we can - * run the primary Mill build. Can be nested for multiple stages of bootstrapping - */ - final public static String millBuild = "mill-build"; + /** + * Path of the Mill "meta-build", used to compile the `build.sc` file so we can + * run the primary Mill build. Can be nested for multiple stages of bootstrapping + */ + public static final String millBuild = "mill-build"; - /** - * A parallel performance and timing profile generated for every Mill execution. - * Can be loaded into the Chrome browser chrome://tracing page to visualize where - * time in a build is being spent - */ - final public static String millChromeProfile = "mill-chrome-profile.json"; + /** + * A parallel performance and timing profile generated for every Mill execution. + * Can be loaded into the Chrome browser chrome://tracing page to visualize where + * time in a build is being spent + */ + public static final String millChromeProfile = "mill-chrome-profile.json"; - /** - * A sequential profile containing rich information about the tasks that were run - * as part of a build: name, duration, cached, dependencies, etc. Useful to help - * understand what tasks are taking time in a build run and why those tasks are - * being executed - */ - final public static String millProfile = "mill-profile.json"; + /** + * A sequential profile containing rich information about the tasks that were run + * as part of a build: name, duration, cached, dependencies, etc. Useful to help + * understand what tasks are taking time in a build run and why those tasks are + * being executed + */ + public static final String millProfile = "mill-profile.json"; - /** - * Long-lived metadata about the Mill bootstrap process that persists between runs: - * workers, watched files, classpaths, etc. - */ - final public static String millRunnerState = "mill-runner-state.json"; + /** + * Long-lived metadata about the Mill bootstrap process that persists between runs: + * workers, watched files, classpaths, etc. + */ + public static final String millRunnerState = "mill-runner-state.json"; - /** - * Subfolder of `out/` that contains the machinery necessary for a single Mill background - * server: metadata files, pipes, logs, etc. - */ - final public static String millServer = "mill-server"; + /** + * Subfolder of `out/` that contains the machinery necessary for a single Mill background + * server: metadata files, pipes, logs, etc. + */ + public static final String millServer = "mill-server"; - /** - * Subfolder of `out/` used to contain the Mill subprocess when run in no-server mode - */ - final public static String millNoServer = "mill-no-server"; + /** + * Subfolder of `out/` used to contain the Mill subprocess when run in no-server mode + */ + public static final String millNoServer = "mill-no-server"; - /** - * Lock file used for exclusive access to the Mill output directory - */ - final public static String millLock = "mill-lock"; - - /** - * Any active Mill command that is currently run, for debugging purposes - */ - final public static String millActiveCommand = "mill-active-command"; + /** + * Lock file used for exclusive access to the Mill output directory + */ + public static final String millLock = "mill-lock"; + /** + * Any active Mill command that is currently run, for debugging purposes + */ + public static final String millActiveCommand = "mill-active-command"; } diff --git a/main/client/src/mill/main/client/ProxyStream.java b/main/client/src/mill/main/client/ProxyStream.java index 55b1ffda65f..eed2c632c35 100644 --- a/main/client/src/mill/main/client/ProxyStream.java +++ b/main/client/src/mill/main/client/ProxyStream.java @@ -1,11 +1,8 @@ package mill.main.client; - import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.util.function.BiConsumer; -import java.util.function.Consumer; /** * Logic to capture a pair of streams (typically stdout and stderr), combining @@ -33,150 +30,163 @@ * stream, forwards each packet to its respective destination stream, or terminates * when it hits a packet with `header == 0` */ -public class ProxyStream{ +public class ProxyStream { - public static final int OUT = 1; - public static final int ERR = -1; - public static final int END = 0; + public static final int OUT = 1; + public static final int ERR = -1; + public static final int END = 0; - public static void sendEnd(OutputStream out) throws IOException { - synchronized(out){ - out.write(ProxyStream.END); - out.flush(); - } + public static void sendEnd(OutputStream out) throws IOException { + synchronized (out) { + out.write(ProxyStream.END); + out.flush(); } + } - public static class Output extends java.io.OutputStream { - private java.io.OutputStream destination; - private int key; + public static class Output extends java.io.OutputStream { + private java.io.OutputStream destination; + private int key; - public Output(java.io.OutputStream out, int key){ - this.destination = out; - this.key = key; - } + public Output(java.io.OutputStream out, int key) { + this.destination = out; + this.key = key; + } - @Override public void write(int b) throws IOException { - synchronized (destination){ - destination.write(key); - destination.write(b); - } - } + @Override + public void write(int b) throws IOException { + synchronized (destination) { + destination.write(key); + destination.write(b); + } + } - @Override public void write(byte[] b) throws IOException { - if (b.length > 0) { - synchronized (destination) { - write(b, 0, b.length); - } - } + @Override + public void write(byte[] b) throws IOException { + if (b.length > 0) { + synchronized (destination) { + write(b, 0, b.length); } + } + } - @Override public void write(byte[] b, int off, int len) throws IOException { - - synchronized (destination) { - int i = 0; - while (i < len && i + off < b.length) { - int chunkLength = Math.min(len - i, 127); - if (chunkLength > 0) { - destination.write(chunkLength * key); - destination.write(b, off + i, Math.min(b.length - off - i, chunkLength)); - i += chunkLength; - } - } - } + @Override + public void write(byte[] b, int off, int len) throws IOException { + + synchronized (destination) { + int i = 0; + while (i < len && i + off < b.length) { + int chunkLength = Math.min(len - i, 127); + if (chunkLength > 0) { + destination.write(chunkLength * key); + destination.write(b, off + i, Math.min(b.length - off - i, chunkLength)); + i += chunkLength; + } } + } + } - @Override public void flush() throws IOException { - synchronized (destination) { - destination.flush(); - } - } + @Override + public void flush() throws IOException { + synchronized (destination) { + destination.flush(); + } + } - @Override public void close() throws IOException { - synchronized (destination) { - destination.close(); - } - } + @Override + public void close() throws IOException { + synchronized (destination) { + destination.close(); + } + } + } + + public static class Pumper implements Runnable { + private InputStream src; + private OutputStream destOut; + private OutputStream destErr; + private Object synchronizer; + + public Pumper( + InputStream src, OutputStream destOut, OutputStream destErr, Object synchronizer) { + this.src = src; + this.destOut = destOut; + this.destErr = destErr; + this.synchronizer = synchronizer; } - public static class Pumper implements Runnable{ - private InputStream src; - private OutputStream destOut; - private OutputStream destErr; - private Object synchronizer; - public Pumper(InputStream src, OutputStream destOut, OutputStream destErr, Object synchronizer){ - this.src = src; - this.destOut = destOut; - this.destErr = destErr; - this.synchronizer = synchronizer; - } - public Pumper(InputStream src, OutputStream destOut, OutputStream destErr){ - this(src, destOut, destErr, new Object()); - } + public Pumper(InputStream src, OutputStream destOut, OutputStream destErr) { + this(src, destOut, destErr, new Object()); + } - public void preRead(InputStream src){} - - public void preWrite(byte[] buffer, int length){} - - public void run() { - - byte[] buffer = new byte[1024]; - while (true) { - try { - this.preRead(src); - int header = src.read(); - // -1 means socket was closed, 0 means a ProxyStream.END was sent. Note - // that only header values > 0 represent actual data to read: - // - sign((byte)header) represents which stream the data should be sent to - // - abs((byte)header) represents the length of the data to read and send - if (header == -1 || header == 0) break; - else { - int stream = (byte) header > 0 ? 1 : -1; - int quantity0 = (byte) header; - int quantity = Math.abs(quantity0); - int offset = 0; - int delta = -1; - while (offset < quantity) { - this.preRead(src); - delta = src.read(buffer, offset, quantity - offset); - if (delta == -1) { - break; - } else { - offset += delta; - } - } - - if (delta != -1) { - synchronized (synchronizer) { - this.preWrite(buffer, offset); - switch(stream){ - case ProxyStream.OUT: destOut.write(buffer, 0, offset); break; - case ProxyStream.ERR: destErr.write(buffer, 0, offset); break; - } - } - } - } - } catch (org.newsclub.net.unix.ConnectionResetSocketException e) { - // This happens when you run mill shutdown and the server exits gracefully + public void preRead(InputStream src) {} + + public void preWrite(byte[] buffer, int length) {} + + public void run() { + + byte[] buffer = new byte[1024]; + while (true) { + try { + this.preRead(src); + int header = src.read(); + // -1 means socket was closed, 0 means a ProxyStream.END was sent. Note + // that only header values > 0 represent actual data to read: + // - sign((byte)header) represents which stream the data should be sent to + // - abs((byte)header) represents the length of the data to read and send + if (header == -1 || header == 0) break; + else { + int stream = (byte) header > 0 ? 1 : -1; + int quantity0 = (byte) header; + int quantity = Math.abs(quantity0); + int offset = 0; + int delta = -1; + while (offset < quantity) { + this.preRead(src); + delta = src.read(buffer, offset, quantity - offset); + if (delta == -1) { + break; + } else { + offset += delta; + } + } + + if (delta != -1) { + synchronized (synchronizer) { + this.preWrite(buffer, offset); + switch (stream) { + case ProxyStream.OUT: + destOut.write(buffer, 0, offset); break; - } catch (IOException e) { - // This happens when the upstream pipe was closed + case ProxyStream.ERR: + destErr.write(buffer, 0, offset); break; } + } } - - try { - synchronized (synchronizer) { - destOut.flush(); - destErr.flush(); - } - } catch(IOException e) {} + } + } catch (org.newsclub.net.unix.ConnectionResetSocketException e) { + // This happens when you run mill shutdown and the server exits gracefully + break; + } catch (IOException e) { + // This happens when the upstream pipe was closed + break; } + } - public void flush() throws IOException { - synchronized (synchronizer) { - destOut.flush(); - destErr.flush(); - } + try { + synchronized (synchronizer) { + destOut.flush(); + destErr.flush(); } + } catch (IOException e) { + } + } + + public void flush() throws IOException { + synchronized (synchronizer) { + destOut.flush(); + destErr.flush(); + } } + } } diff --git a/main/client/src/mill/main/client/ServerCouldNotBeStarted.java b/main/client/src/mill/main/client/ServerCouldNotBeStarted.java index 908dbce62f3..0576332c941 100644 --- a/main/client/src/mill/main/client/ServerCouldNotBeStarted.java +++ b/main/client/src/mill/main/client/ServerCouldNotBeStarted.java @@ -1,7 +1,7 @@ package mill.main.client; public class ServerCouldNotBeStarted extends Exception { - public ServerCouldNotBeStarted(String msg) { - super(msg); - } + public ServerCouldNotBeStarted(String msg) { + super(msg); + } } diff --git a/main/client/src/mill/main/client/ServerFiles.java b/main/client/src/mill/main/client/ServerFiles.java index bd7ac1a289c..e06e3715c95 100644 --- a/main/client/src/mill/main/client/ServerFiles.java +++ b/main/client/src/mill/main/client/ServerFiles.java @@ -5,71 +5,68 @@ * and documentation about what they do */ public class ServerFiles { - final public static String serverId = "serverId"; - final public static String sandbox = "sandbox"; + public static final String serverId = "serverId"; + public static final String sandbox = "sandbox"; - /** - * Ensures only a single client is manipulating each mill-server folder at - * a time, either spawning the server or submitting a command. Also used by - * the server to detect when a client disconnects, so it can terminate execution - */ - final public static String clientLock = "clientLock"; + /** + * Ensures only a single client is manipulating each mill-server folder at + * a time, either spawning the server or submitting a command. Also used by + * the server to detect when a client disconnects, so it can terminate execution + */ + public static final String clientLock = "clientLock"; - /** - * Lock file ensuring a single server is running in a particular mill-server - * folder. If multiple servers are spawned in the same folder, only one takes - * the lock and the others fail to do so and terminate immediately. - */ - final public static String processLock = "processLock"; + /** + * Lock file ensuring a single server is running in a particular mill-server + * folder. If multiple servers are spawned in the same folder, only one takes + * the lock and the others fail to do so and terminate immediately. + */ + public static final String processLock = "processLock"; - /** - * The pipe by which the client snd server exchange IO - * - * Use uniquely-named pipes based on the fully qualified path of the project folder - * because on Windows the un-qualified name of the pipe must be globally unique - * across the whole filesystem - */ - public static String pipe(String base) { - try { - return base + "/mill-" + Util.md5hex(new java.io.File(base).getCanonicalPath()).substring(0, 8) + "-io"; - }catch (Exception e){ - throw new RuntimeException(e); - } + /** + * The pipe by which the client snd server exchange IO + * + * Use uniquely-named pipes based on the fully qualified path of the project folder + * because on Windows the un-qualified name of the pipe must be globally unique + * across the whole filesystem + */ + public static String pipe(String base) { + try { + return base + "/mill-" + + Util.md5hex(new java.io.File(base).getCanonicalPath()).substring(0, 8) + "-io"; + } catch (Exception e) { + throw new RuntimeException(e); } + } - /** - * Log file containing server housekeeping information - */ - final public static String serverLog = "server.log"; + /** + * Log file containing server housekeeping information + */ + public static final String serverLog = "server.log"; + /** + * File that the client writes to pass the arguments, environment variables, + * and other necessary metadata to the Mill server to kick off a run + */ + public static final String runArgs = "runArgs"; - /** - * File that the client writes to pass the arguments, environment variables, - * and other necessary metadata to the Mill server to kick off a run - */ - final public static String runArgs = "runArgs"; + /** + * File the server writes to pass the exit code of a completed run back to the + * client + */ + public static final String exitCode = "exitCode"; + /** + * Where the server's stdout is piped to + */ + public static final String stdout = "stdout"; - /** - * File the server writes to pass the exit code of a completed run back to the - * client - */ - final public static String exitCode = "exitCode"; + /** + * Where the server's stderr is piped to + */ + public static final String stderr = "stderr"; - - /** - * Where the server's stdout is piped to - */ - final public static String stdout = "stdout"; - - - /** - * Where the server's stderr is piped to - */ - final public static String stderr = "stderr"; - - /** - * Terminal information that we need to propagate from client to server - */ - final public static String terminfo = "terminfo"; + /** + * Terminal information that we need to propagate from client to server + */ + public static final String terminfo = "terminfo"; } diff --git a/main/client/src/mill/main/client/ServerLauncher.java b/main/client/src/mill/main/client/ServerLauncher.java index ec4cd320ee6..3ce9a3c23a3 100644 --- a/main/client/src/mill/main/client/ServerLauncher.java +++ b/main/client/src/mill/main/client/ServerLauncher.java @@ -1,12 +1,7 @@ package mill.main.client; -import mill.main.client.lock.Locks; -import mill.main.client.lock.TryLocked; import static mill.main.client.OutFiles.*; -import org.newsclub.net.unix.AFUNIXSocket; -import org.newsclub.net.unix.AFUNIXSocketAddress; - import java.io.File; import java.io.InputStream; import java.io.OutputStream; @@ -16,7 +11,10 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.Map; -import java.util.function.BiConsumer; +import mill.main.client.lock.Locks; +import mill.main.client.lock.TryLocked; +import org.newsclub.net.unix.AFUNIXSocket; +import org.newsclub.net.unix.AFUNIXSocketAddress; /** * Client side code that interacts with `Server.scala` in order to launch a generic @@ -44,148 +42,153 @@ * indicating server has finished execution and all data has been received */ public abstract class ServerLauncher { - public static class Result{ - public int exitCode; - public Path serverDir; - } - final static int tailerRefreshIntervalMillis = 2; - final int serverProcessesLimit = 5; - final int serverInitWaitMillis = 10000; - public abstract void initServer(Path serverDir, boolean b, Locks locks) throws Exception; - public abstract void preRun(Path serverDir) throws Exception; - InputStream stdin; - PrintStream stdout; - PrintStream stderr; - Map env; - String[] args; - Locks[] memoryLocks; - int forceFailureForTestingMillisDelay; - public ServerLauncher(InputStream stdin, - PrintStream stdout, - PrintStream stderr, - Map env, - String[] args, - Locks[] memoryLocks, - int forceFailureForTestingMillisDelay){ - this.stdin = stdin; - this.stdout = stdout; - this.stderr = stderr; - this.env = env; - this.args = args; - - // For testing in memory, we need to pass in the locks separately, so that the - // locks can be shared between the different instances of `ServerLauncher` the - // same way file locks are shared between different Mill client/server processes - this.memoryLocks = memoryLocks; - - this.forceFailureForTestingMillisDelay = forceFailureForTestingMillisDelay; + public static class Result { + public int exitCode; + public Path serverDir; + } + + static final int tailerRefreshIntervalMillis = 2; + final int serverProcessesLimit = 5; + final int serverInitWaitMillis = 10000; + + public abstract void initServer(Path serverDir, boolean b, Locks locks) throws Exception; + + public abstract void preRun(Path serverDir) throws Exception; + + InputStream stdin; + PrintStream stdout; + PrintStream stderr; + Map env; + String[] args; + Locks[] memoryLocks; + int forceFailureForTestingMillisDelay; + + public ServerLauncher( + InputStream stdin, + PrintStream stdout, + PrintStream stderr, + Map env, + String[] args, + Locks[] memoryLocks, + int forceFailureForTestingMillisDelay) { + this.stdin = stdin; + this.stdout = stdout; + this.stderr = stderr; + this.env = env; + this.args = args; + + // For testing in memory, we need to pass in the locks separately, so that the + // locks can be shared between the different instances of `ServerLauncher` the + // same way file locks are shared between different Mill client/server processes + this.memoryLocks = memoryLocks; + + this.forceFailureForTestingMillisDelay = forceFailureForTestingMillisDelay; + } + + public Result acquireLocksAndRun(String outDir) throws Exception { + + final boolean setJnaNoSys = System.getProperty("jna.nosys") == null; + if (setJnaNoSys) { + System.setProperty("jna.nosys", "true"); } - public Result acquireLocksAndRun(String outDir) throws Exception { - - final boolean setJnaNoSys = System.getProperty("jna.nosys") == null; - if (setJnaNoSys) { - System.setProperty("jna.nosys", "true"); - } - final String versionAndJvmHomeEncoding = Util.sha1Hash(BuildInfo.millVersion + System.getProperty("java.home")); - - - int serverIndex = 0; - while (serverIndex < serverProcessesLimit) { // Try each possible server process (-1 to -5) - serverIndex++; - final Path serverDir = Paths.get(outDir, millServer, versionAndJvmHomeEncoding + "-" + serverIndex); - Files.createDirectories(serverDir); - - try ( - Locks locks = memoryLocks != null ? memoryLocks[serverIndex-1] : Locks.files(serverDir.toString()); - TryLocked clientLocked = locks.clientLock.tryLock() - ) { - if (clientLocked.isLocked()) { - Result result = new Result(); - preRun(serverDir); - result.exitCode = run(serverDir, setJnaNoSys, locks); - result.serverDir = serverDir; - return result; - } - } + final String versionAndJvmHomeEncoding = + Util.sha1Hash(BuildInfo.millVersion + System.getProperty("java.home")); + + int serverIndex = 0; + while (serverIndex < serverProcessesLimit) { // Try each possible server process (-1 to -5) + serverIndex++; + final Path serverDir = + Paths.get(outDir, millServer, versionAndJvmHomeEncoding + "-" + serverIndex); + Files.createDirectories(serverDir); + + try (Locks locks = memoryLocks != null + ? memoryLocks[serverIndex - 1] + : Locks.files(serverDir.toString()); + TryLocked clientLocked = locks.clientLock.tryLock()) { + if (clientLocked.isLocked()) { + Result result = new Result(); + preRun(serverDir); + result.exitCode = run(serverDir, setJnaNoSys, locks); + result.serverDir = serverDir; + return result; } - throw new ServerCouldNotBeStarted("Reached max server processes limit: " + serverProcessesLimit); + } } - - int run(Path serverDir, boolean setJnaNoSys, Locks locks) throws Exception { - try( - final FileToStreamTailer stdoutTailer = new FileToStreamTailer( - new java.io.File(serverDir + "/" + ServerFiles.stdout), - stdout, - tailerRefreshIntervalMillis - ); - final FileToStreamTailer stderrTailer = new FileToStreamTailer( - new java.io.File(serverDir + "/" + ServerFiles.stderr), - stderr, - tailerRefreshIntervalMillis - ); - ) { - stdoutTailer.start(); - stderrTailer.start(); - String serverPath = serverDir + "/" + ServerFiles.runArgs; - try (OutputStream f = Files.newOutputStream(Paths.get(serverPath))) { - f.write(System.console() != null ? 1 : 0); - Util.writeString(f, BuildInfo.millVersion); - Util.writeArgs(args, f); - Util.writeMap(env, f); - } - - if (locks.processLock.probe()) { - initServer(serverDir, setJnaNoSys, locks); - } - - while (locks.processLock.probe()) Thread.sleep(3); - - String socketName = ServerFiles.pipe(serverDir.toString()); - AFUNIXSocketAddress addr = AFUNIXSocketAddress.of(new File(socketName)); - - long retryStart = System.currentTimeMillis(); - Socket ioSocket = null; - Throwable socketThrowable = null; - while (ioSocket == null && System.currentTimeMillis() - retryStart < serverInitWaitMillis) { - try { - ioSocket = AFUNIXSocket.connectTo(addr); - } catch (Throwable e) { - socketThrowable = e; - Thread.sleep(10); - } - } - - if (ioSocket == null) { - throw new Exception("Failed to connect to server", socketThrowable); - } - - InputStream outErr = ioSocket.getInputStream(); - OutputStream in = ioSocket.getOutputStream(); - ProxyStream.Pumper outPumper = new ProxyStream.Pumper(outErr, stdout, stderr); - InputPumper inPump = new InputPumper(() -> stdin, () -> in, true); - Thread outPumperThread = new Thread(outPumper, "outPump"); - outPumperThread.setDaemon(true); - Thread inThread = new Thread(inPump, "inPump"); - inThread.setDaemon(true); - outPumperThread.start(); - inThread.start(); - - if (forceFailureForTestingMillisDelay > 0){ - Thread.sleep(forceFailureForTestingMillisDelay); - throw new Exception("Force failure for testing: " + serverDir); - } - outPumperThread.join(); - - try { - return Integer.parseInt(Files.readAllLines(Paths.get(serverDir + "/" + ServerFiles.exitCode)).get(0)); - } catch (Throwable e) { - return Util.ExitClientCodeCannotReadFromExitCodeFile(); - } finally { - ioSocket.close(); - } + throw new ServerCouldNotBeStarted( + "Reached max server processes limit: " + serverProcessesLimit); + } + + int run(Path serverDir, boolean setJnaNoSys, Locks locks) throws Exception { + try (final FileToStreamTailer stdoutTailer = new FileToStreamTailer( + new java.io.File(serverDir + "/" + ServerFiles.stdout), + stdout, + tailerRefreshIntervalMillis); + final FileToStreamTailer stderrTailer = new FileToStreamTailer( + new java.io.File(serverDir + "/" + ServerFiles.stderr), + stderr, + tailerRefreshIntervalMillis); ) { + stdoutTailer.start(); + stderrTailer.start(); + String serverPath = serverDir + "/" + ServerFiles.runArgs; + try (OutputStream f = Files.newOutputStream(Paths.get(serverPath))) { + f.write(System.console() != null ? 1 : 0); + Util.writeString(f, BuildInfo.millVersion); + Util.writeArgs(args, f); + Util.writeMap(env, f); + } + + if (locks.processLock.probe()) { + initServer(serverDir, setJnaNoSys, locks); + } + + while (locks.processLock.probe()) Thread.sleep(3); + + String socketName = ServerFiles.pipe(serverDir.toString()); + AFUNIXSocketAddress addr = AFUNIXSocketAddress.of(new File(socketName)); + + long retryStart = System.currentTimeMillis(); + Socket ioSocket = null; + Throwable socketThrowable = null; + while (ioSocket == null && System.currentTimeMillis() - retryStart < serverInitWaitMillis) { + try { + ioSocket = AFUNIXSocket.connectTo(addr); + } catch (Throwable e) { + socketThrowable = e; + Thread.sleep(10); } - + } + + if (ioSocket == null) { + throw new Exception("Failed to connect to server", socketThrowable); + } + + InputStream outErr = ioSocket.getInputStream(); + OutputStream in = ioSocket.getOutputStream(); + ProxyStream.Pumper outPumper = new ProxyStream.Pumper(outErr, stdout, stderr); + InputPumper inPump = new InputPumper(() -> stdin, () -> in, true); + Thread outPumperThread = new Thread(outPumper, "outPump"); + outPumperThread.setDaemon(true); + Thread inThread = new Thread(inPump, "inPump"); + inThread.setDaemon(true); + outPumperThread.start(); + inThread.start(); + + if (forceFailureForTestingMillisDelay > 0) { + Thread.sleep(forceFailureForTestingMillisDelay); + throw new Exception("Force failure for testing: " + serverDir); + } + outPumperThread.join(); + + try { + return Integer.parseInt( + Files.readAllLines(Paths.get(serverDir + "/" + ServerFiles.exitCode)) + .get(0)); + } catch (Throwable e) { + return Util.ExitClientCodeCannotReadFromExitCodeFile(); + } finally { + ioSocket.close(); + } } - + } } diff --git a/main/client/src/mill/main/client/Util.java b/main/client/src/mill/main/client/Util.java index c611d2bbc45..d6e88c6ad8e 100644 --- a/main/client/src/mill/main/client/Util.java +++ b/main/client/src/mill/main/client/Util.java @@ -1,10 +1,10 @@ package mill.main.client; +import java.io.File; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.File; -import java.io.FileNotFoundException; import java.math.BigInteger; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; @@ -12,173 +12,173 @@ import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.HashMap; -import java.util.Map; -import java.util.List; import java.util.LinkedList; +import java.util.List; +import java.util.Map; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Util { - // use methods instead of constants to avoid inlining by compiler - public static final int ExitClientCodeCannotReadFromExitCodeFile() { - return 1; - } - - public static final int ExitServerCodeWhenIdle() { - return 0; - } - - public static final int ExitServerCodeWhenVersionMismatch() { - return 101; - } - - - public static boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows"); - public static boolean isJava9OrAbove = !System.getProperty("java.specification.version").startsWith("1."); - private static Charset utf8 = Charset.forName("UTF-8"); - - public static String[] parseArgs(InputStream argStream) throws IOException { - int argsLength = readInt(argStream); - String[] args = new String[argsLength]; - for (int i = 0; i < args.length; i++) { - args[i] = readString(argStream); - } - return args; - } - - public static void writeArgs(String[] args, - OutputStream argStream) throws IOException { - writeInt(argStream, args.length); - for (String arg : args) { - writeString(argStream, arg); - } - } - - /** - * This allows the mill client to pass the environment as it sees it to the - * server (as the server remains alive over the course of several runs and - * does not see the environment changes the client would) - */ - public static void writeMap(Map map, OutputStream argStream) throws IOException { - writeInt(argStream, map.size()); - for (Map.Entry kv : map.entrySet()) { - writeString(argStream, kv.getKey()); - writeString(argStream, kv.getValue()); - } - } - - public static Map parseMap(InputStream argStream) throws IOException { - Map env = new HashMap<>(); - int mapLength = readInt(argStream); - for (int i = 0; i < mapLength; i++) { - String key = readString(argStream); - String value = readString(argStream); - env.put(key, value); + // use methods instead of constants to avoid inlining by compiler + public static final int ExitClientCodeCannotReadFromExitCodeFile() { + return 1; + } + + public static final int ExitServerCodeWhenIdle() { + return 0; + } + + public static final int ExitServerCodeWhenVersionMismatch() { + return 101; + } + + public static boolean isWindows = + System.getProperty("os.name").toLowerCase().startsWith("windows"); + public static boolean isJava9OrAbove = + !System.getProperty("java.specification.version").startsWith("1."); + private static Charset utf8 = Charset.forName("UTF-8"); + + public static String[] parseArgs(InputStream argStream) throws IOException { + int argsLength = readInt(argStream); + String[] args = new String[argsLength]; + for (int i = 0; i < args.length; i++) { + args[i] = readString(argStream); + } + return args; + } + + public static void writeArgs(String[] args, OutputStream argStream) throws IOException { + writeInt(argStream, args.length); + for (String arg : args) { + writeString(argStream, arg); + } + } + + /** + * This allows the mill client to pass the environment as it sees it to the + * server (as the server remains alive over the course of several runs and + * does not see the environment changes the client would) + */ + public static void writeMap(Map map, OutputStream argStream) throws IOException { + writeInt(argStream, map.size()); + for (Map.Entry kv : map.entrySet()) { + writeString(argStream, kv.getKey()); + writeString(argStream, kv.getValue()); + } + } + + public static Map parseMap(InputStream argStream) throws IOException { + Map env = new HashMap<>(); + int mapLength = readInt(argStream); + for (int i = 0; i < mapLength; i++) { + String key = readString(argStream); + String value = readString(argStream); + env.put(key, value); + } + return env; + } + + public static String readString(InputStream inputStream) throws IOException { + // Result is between 0 and 255, hence the loop. + final int length = readInt(inputStream); + final byte[] arr = new byte[length]; + int total = 0; + while (total < length) { + int res = inputStream.read(arr, total, length - total); + if (res == -1) throw new IOException("Incomplete String"); + else { + total += res; + } + } + return new String(arr, utf8); + } + + public static void writeString(OutputStream outputStream, String string) throws IOException { + final byte[] bytes = string.getBytes(utf8); + writeInt(outputStream, bytes.length); + outputStream.write(bytes); + } + + public static void writeInt(OutputStream out, int i) throws IOException { + out.write((byte) (i >>> 24)); + out.write((byte) (i >>> 16)); + out.write((byte) (i >>> 8)); + out.write((byte) i); + } + + public static int readInt(InputStream in) throws IOException { + return ((in.read() & 0xFF) << 24) + + ((in.read() & 0xFF) << 16) + + ((in.read() & 0xFF) << 8) + + (in.read() & 0xFF); + } + + /** + * @return Hex encoded MD5 hash of input string. + */ + public static String md5hex(String str) throws NoSuchAlgorithmException { + return hexArray(MessageDigest.getInstance("md5").digest(str.getBytes(StandardCharsets.UTF_8))); + } + + private static String hexArray(byte[] arr) { + return String.format("%0" + (arr.length << 1) + "x", new BigInteger(1, arr)); + } + + static String sha1Hash(String path) throws NoSuchAlgorithmException { + MessageDigest md = MessageDigest.getInstance("SHA1"); + md.reset(); + byte[] pathBytes = path.getBytes(StandardCharsets.UTF_8); + md.update(pathBytes); + byte[] digest = md.digest(); + return Base64.getEncoder().encodeToString(digest); + } + + /** + * Reads a file, ignoring empty or comment lines, interpolating env variables. + * + * @return The non-empty lines of the files or an empty list, if the file does not exist + */ + public static List readOptsFileLines(final File file) { + final List vmOptions = new LinkedList<>(); + try (final Scanner sc = new Scanner(file)) { + final Map env = System.getenv(); + while (sc.hasNextLine()) { + String arg = sc.nextLine(); + String trimmed = arg.trim(); + if (!trimmed.isEmpty() && !trimmed.startsWith("#")) { + vmOptions.add(interpolateEnvVars(arg, env)); } - return env; - } - - public static String readString(InputStream inputStream) throws IOException { - // Result is between 0 and 255, hence the loop. - final int length = readInt(inputStream); - final byte[] arr = new byte[length]; - int total = 0; - while (total < length) { - int res = inputStream.read(arr, total, length - total); - if (res == -1) throw new IOException("Incomplete String"); - else { - total += res; - } - } - return new String(arr, utf8); - } - - public static void writeString(OutputStream outputStream, String string) throws IOException { - final byte[] bytes = string.getBytes(utf8); - writeInt(outputStream, bytes.length); - outputStream.write(bytes); - } - - public static void writeInt(OutputStream out, int i) throws IOException { - out.write((byte) (i >>> 24)); - out.write((byte) (i >>> 16)); - out.write((byte) (i >>> 8)); - out.write((byte) i); - } - - public static int readInt(InputStream in) throws IOException { - return ((in.read() & 0xFF) << 24) + - ((in.read() & 0xFF) << 16) + - ((in.read() & 0xFF) << 8) + - (in.read() & 0xFF); - } - - /** - * @return Hex encoded MD5 hash of input string. - */ - public static String md5hex(String str) throws NoSuchAlgorithmException { - return hexArray(MessageDigest.getInstance("md5").digest(str.getBytes(StandardCharsets.UTF_8))); - } - - private static String hexArray(byte[] arr) { - return String.format("%0" + (arr.length << 1) + "x", new BigInteger(1, arr)); - } - - static String sha1Hash(String path) throws NoSuchAlgorithmException { - MessageDigest md = MessageDigest.getInstance("SHA1"); - md.reset(); - byte[] pathBytes = path.getBytes(StandardCharsets.UTF_8); - md.update(pathBytes); - byte[] digest = md.digest(); - return Base64.getEncoder().encodeToString(digest); - } - - /** - * Reads a file, ignoring empty or comment lines, interpolating env variables. - * - * @return The non-empty lines of the files or an empty list, if the file does not exist - */ - public static List readOptsFileLines(final File file) { - final List vmOptions = new LinkedList<>(); - try (final Scanner sc = new Scanner(file)) { - final Map env = System.getenv(); - while (sc.hasNextLine()) { - String arg = sc.nextLine(); - String trimmed = arg.trim(); - if (!trimmed.isEmpty() && !trimmed.startsWith("#")) { - vmOptions.add(interpolateEnvVars(arg, env)); - } - } - } catch (FileNotFoundException e) { - // ignored - } - return vmOptions; - } - - /** - * Interpolate variables in the form of ${VARIABLE} based on the given Map env. - * Missing vars will be replaced by the empty string. - */ - public static String interpolateEnvVars(String input, Map env) { - Matcher matcher = envInterpolatorPattern.matcher(input); - // StringBuilder to store the result after replacing - StringBuffer result = new StringBuffer(); - - while (matcher.find()) { - String match = matcher.group(1); - if (match.equals("$")) { - matcher.appendReplacement(result, "\\$"); - } else { - String envVarValue = env.containsKey(match) ? env.get(match) : ""; - matcher.appendReplacement(result, envVarValue); - } - } - - matcher.appendTail(result); // Append the remaining part of the string - return result.toString(); - } - - private static Pattern envInterpolatorPattern = Pattern.compile("\\$\\{(\\$|[A-Z_][A-Z0-9_]*)\\}"); - + } + } catch (FileNotFoundException e) { + // ignored + } + return vmOptions; + } + + /** + * Interpolate variables in the form of ${VARIABLE} based on the given Map env. + * Missing vars will be replaced by the empty string. + */ + public static String interpolateEnvVars(String input, Map env) { + Matcher matcher = envInterpolatorPattern.matcher(input); + // StringBuilder to store the result after replacing + StringBuffer result = new StringBuffer(); + + while (matcher.find()) { + String match = matcher.group(1); + if (match.equals("$")) { + matcher.appendReplacement(result, "\\$"); + } else { + String envVarValue = env.containsKey(match) ? env.get(match) : ""; + matcher.appendReplacement(result, envVarValue); + } + } + + matcher.appendTail(result); // Append the remaining part of the string + return result.toString(); + } + + private static Pattern envInterpolatorPattern = + Pattern.compile("\\$\\{(\\$|[A-Z_][A-Z0-9_]*)\\}"); } diff --git a/main/client/src/mill/main/client/lock/FileLock.java b/main/client/src/mill/main/client/lock/FileLock.java index 454b8794bd7..c19916a146f 100644 --- a/main/client/src/mill/main/client/lock/FileLock.java +++ b/main/client/src/mill/main/client/lock/FileLock.java @@ -5,36 +5,38 @@ class FileLock extends Lock { - final private RandomAccessFile raf; - final private FileChannel chan; - - public FileLock(String path) throws Exception { - raf = new RandomAccessFile(path, "rw"); - chan = raf.getChannel(); - } - - public Locked lock() throws Exception { - return new FileLocked(chan.lock()); - } - - public TryLocked tryLock() throws Exception { - return new FileTryLocked(chan.tryLock()); - } - - public boolean probe() throws Exception { - java.nio.channels.FileLock l = chan.tryLock(); - if (l == null) return false; - else { - l.release(); - return true; - } + private final RandomAccessFile raf; + private final FileChannel chan; + + public FileLock(String path) throws Exception { + raf = new RandomAccessFile(path, "rw"); + chan = raf.getChannel(); + } + + public Locked lock() throws Exception { + return new FileLocked(chan.lock()); + } + + public TryLocked tryLock() throws Exception { + return new FileTryLocked(chan.tryLock()); + } + + public boolean probe() throws Exception { + java.nio.channels.FileLock l = chan.tryLock(); + if (l == null) return false; + else { + l.release(); + return true; } + } - @Override - public void close() throws Exception { - chan.close(); - raf.close(); - } + @Override + public void close() throws Exception { + chan.close(); + raf.close(); + } - public void delete() throws Exception { close(); } + public void delete() throws Exception { + close(); + } } diff --git a/main/client/src/mill/main/client/lock/FileLocked.java b/main/client/src/mill/main/client/lock/FileLocked.java index ae31613278b..3c27c66abe3 100644 --- a/main/client/src/mill/main/client/lock/FileLocked.java +++ b/main/client/src/mill/main/client/lock/FileLocked.java @@ -2,13 +2,13 @@ class FileLocked implements Locked { - final protected java.nio.channels.FileLock lock; + protected final java.nio.channels.FileLock lock; - public FileLocked(java.nio.channels.FileLock lock) { - this.lock = lock; - } + public FileLocked(java.nio.channels.FileLock lock) { + this.lock = lock; + } - public void release() throws Exception { - this.lock.release(); - } + public void release() throws Exception { + this.lock.release(); + } } diff --git a/main/client/src/mill/main/client/lock/FileTryLocked.java b/main/client/src/mill/main/client/lock/FileTryLocked.java index 42e632f94a0..a4a29bc0f55 100644 --- a/main/client/src/mill/main/client/lock/FileTryLocked.java +++ b/main/client/src/mill/main/client/lock/FileTryLocked.java @@ -1,13 +1,15 @@ package mill.main.client.lock; -class FileTryLocked extends FileLocked implements TryLocked{ - public FileTryLocked(java.nio.channels.FileLock lock) { - super(lock); - } +class FileTryLocked extends FileLocked implements TryLocked { + public FileTryLocked(java.nio.channels.FileLock lock) { + super(lock); + } - public boolean isLocked(){ return lock != null; } + public boolean isLocked() { + return lock != null; + } - public void release() throws Exception { - if (isLocked()) super.release(); - } + public void release() throws Exception { + if (isLocked()) super.release(); + } } diff --git a/main/client/src/mill/main/client/lock/Lock.java b/main/client/src/mill/main/client/lock/Lock.java index d7f65ee2b85..f91f4885fd4 100644 --- a/main/client/src/mill/main/client/lock/Lock.java +++ b/main/client/src/mill/main/client/lock/Lock.java @@ -2,25 +2,26 @@ public abstract class Lock implements AutoCloseable { - public abstract Locked lock() throws Exception; + public abstract Locked lock() throws Exception; - public abstract TryLocked tryLock() throws Exception; + public abstract TryLocked tryLock() throws Exception; - public void await() throws Exception { - lock().release(); - } + public void await() throws Exception { + lock().release(); + } - /** - * Returns `true` if the lock is *available for taking* - */ - public abstract boolean probe() throws Exception; - public void delete() throws Exception {} + /** + * Returns `true` if the lock is *available for taking* + */ + public abstract boolean probe() throws Exception; - public static Lock file(String path) throws Exception { - return new FileLock(path); - } + public void delete() throws Exception {} - public static Lock memory() { - return new MemoryLock(); - } + public static Lock file(String path) throws Exception { + return new FileLock(path); + } + + public static Lock memory() { + return new MemoryLock(); + } } diff --git a/main/client/src/mill/main/client/lock/Locked.java b/main/client/src/mill/main/client/lock/Locked.java index 7e527c5fa31..48338c56693 100644 --- a/main/client/src/mill/main/client/lock/Locked.java +++ b/main/client/src/mill/main/client/lock/Locked.java @@ -2,8 +2,9 @@ public interface Locked extends AutoCloseable { - void release() throws Exception; - default void close() throws Exception { - release(); - } + void release() throws Exception; + + default void close() throws Exception { + release(); + } } diff --git a/main/client/src/mill/main/client/lock/Locks.java b/main/client/src/mill/main/client/lock/Locks.java index b026fc17393..6e25ee8504b 100644 --- a/main/client/src/mill/main/client/lock/Locks.java +++ b/main/client/src/mill/main/client/lock/Locks.java @@ -2,34 +2,29 @@ import mill.main.client.ServerFiles; - -final public class Locks implements AutoCloseable { - - final public Lock clientLock; - final public Lock processLock; - - public Locks(Lock clientLock, Lock processLock){ - this.clientLock = clientLock; - this.processLock = processLock; - } - - public static Locks files(String serverDir) throws Exception { - return new Locks( - new FileLock(serverDir + "/" + ServerFiles.clientLock), - new FileLock(serverDir + "/" + ServerFiles.processLock) - ); - } - - public static Locks memory() { - return new Locks( - new MemoryLock(), - new MemoryLock() - ); - } - - @Override - public void close() throws Exception { - clientLock.delete(); - processLock.delete(); - } +public final class Locks implements AutoCloseable { + + public final Lock clientLock; + public final Lock processLock; + + public Locks(Lock clientLock, Lock processLock) { + this.clientLock = clientLock; + this.processLock = processLock; + } + + public static Locks files(String serverDir) throws Exception { + return new Locks( + new FileLock(serverDir + "/" + ServerFiles.clientLock), + new FileLock(serverDir + "/" + ServerFiles.processLock)); + } + + public static Locks memory() { + return new Locks(new MemoryLock(), new MemoryLock()); + } + + @Override + public void close() throws Exception { + clientLock.delete(); + processLock.delete(); + } } diff --git a/main/client/src/mill/main/client/lock/MemoryLock.java b/main/client/src/mill/main/client/lock/MemoryLock.java index 0e523c34898..a8bdfcc4c6e 100644 --- a/main/client/src/mill/main/client/lock/MemoryLock.java +++ b/main/client/src/mill/main/client/lock/MemoryLock.java @@ -4,24 +4,24 @@ class MemoryLock extends Lock { - final private ReentrantLock innerLock = new ReentrantLock(); + private final ReentrantLock innerLock = new ReentrantLock(); - public boolean probe() { - return !innerLock.isLocked(); - } + public boolean probe() { + return !innerLock.isLocked(); + } - public Locked lock() { - innerLock.lock(); - return new MemoryLocked(innerLock); - } + public Locked lock() { + innerLock.lock(); + return new MemoryLocked(innerLock); + } - public MemoryTryLocked tryLock() { - if (innerLock.tryLock()) return new MemoryTryLocked(innerLock); - else return new MemoryTryLocked(null); - } + public MemoryTryLocked tryLock() { + if (innerLock.tryLock()) return new MemoryTryLocked(innerLock); + else return new MemoryTryLocked(null); + } - @Override - public void close() throws Exception { - innerLock.unlock(); - } + @Override + public void close() throws Exception { + innerLock.unlock(); + } } diff --git a/main/client/src/mill/main/client/lock/MemoryLocked.java b/main/client/src/mill/main/client/lock/MemoryLocked.java index 37bdc3cb625..b2e7efdc974 100644 --- a/main/client/src/mill/main/client/lock/MemoryLocked.java +++ b/main/client/src/mill/main/client/lock/MemoryLocked.java @@ -2,13 +2,13 @@ class MemoryLocked implements Locked { - final protected java.util.concurrent.locks.Lock lock; + protected final java.util.concurrent.locks.Lock lock; - public MemoryLocked(java.util.concurrent.locks.Lock lock) { - this.lock = lock; - } + public MemoryLocked(java.util.concurrent.locks.Lock lock) { + this.lock = lock; + } - public void release() throws Exception { - lock.unlock(); - } + public void release() throws Exception { + lock.unlock(); + } } diff --git a/main/client/src/mill/main/client/lock/MemoryTryLocked.java b/main/client/src/mill/main/client/lock/MemoryTryLocked.java index 4a0ec840dee..0f5c3f20b5e 100644 --- a/main/client/src/mill/main/client/lock/MemoryTryLocked.java +++ b/main/client/src/mill/main/client/lock/MemoryTryLocked.java @@ -1,13 +1,15 @@ package mill.main.client.lock; class MemoryTryLocked extends MemoryLocked implements TryLocked { - public MemoryTryLocked(java.util.concurrent.locks.Lock lock) { - super(lock); - } + public MemoryTryLocked(java.util.concurrent.locks.Lock lock) { + super(lock); + } - public boolean isLocked(){ return lock != null; } + public boolean isLocked() { + return lock != null; + } - public void release() throws Exception { - if (isLocked()) super.release(); - } + public void release() throws Exception { + if (isLocked()) super.release(); + } } diff --git a/main/client/src/mill/main/client/lock/TryLocked.java b/main/client/src/mill/main/client/lock/TryLocked.java index 14491a96c71..e8e6cb4725e 100644 --- a/main/client/src/mill/main/client/lock/TryLocked.java +++ b/main/client/src/mill/main/client/lock/TryLocked.java @@ -1,5 +1,5 @@ package mill.main.client.lock; public interface TryLocked extends Locked { - boolean isLocked(); + boolean isLocked(); } diff --git a/main/client/test/src/mill/main/client/ClientTests.java b/main/client/test/src/mill/main/client/ClientTests.java index 0466db7e2ec..588a99bf310 100644 --- a/main/client/test/src/mill/main/client/ClientTests.java +++ b/main/client/test/src/mill/main/client/ClientTests.java @@ -3,153 +3,152 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import org.junit.Test; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.util.*; +import org.junit.Test; public class ClientTests { - @org.junit.Rule - public RetryRule retryRule = new RetryRule(3); - - @Test - public void readWriteInt() throws Exception{ - int[] examples = { - 0, 1, 126, 127, 128, 254, 255, 256, 1024, 99999, 1234567, - Integer.MAX_VALUE, Integer.MAX_VALUE / 2, Integer.MIN_VALUE - }; - for(int example0: examples){ - for(int example: new int[]{-example0, example0}){ - ByteArrayOutputStream o = new ByteArrayOutputStream(); - Util.writeInt(o, example); - ByteArrayInputStream i = new ByteArrayInputStream(o.toByteArray()); - int s = Util.readInt(i); - assertEquals(example, s); - assertEquals(i.available(), 0); - } - } - } - @Test - public void readWriteString() throws Exception{ - String[] examples = { - "", - "hello", - "i am cow", - "i am cow\nhear me moo\ni weight twice as much as you", - "我是一个叉烧包", - }; - for(String example: examples){ - checkStringRoundTrip(example); - } - } - - @Test - public void readWriteBigString() throws Exception{ - int[] lengths = {0, 1, 126, 127, 128, 254, 255, 256, 1024, 99999, 1234567}; - for(int i = 0; i < lengths.length; i++){ - final char[] bigChars = new char[lengths[i]]; - java.util.Arrays.fill(bigChars, 'X'); - checkStringRoundTrip(new String(bigChars)); - } - } - - public void checkStringRoundTrip(String example) throws Exception{ + @org.junit.Rule + public RetryRule retryRule = new RetryRule(3); + + @Test + public void readWriteInt() throws Exception { + int[] examples = { + 0, + 1, + 126, + 127, + 128, + 254, + 255, + 256, + 1024, + 99999, + 1234567, + Integer.MAX_VALUE, + Integer.MAX_VALUE / 2, + Integer.MIN_VALUE + }; + for (int example0 : examples) { + for (int example : new int[] {-example0, example0}) { ByteArrayOutputStream o = new ByteArrayOutputStream(); - Util.writeString(o, example); + Util.writeInt(o, example); ByteArrayInputStream i = new ByteArrayInputStream(o.toByteArray()); - String s = Util.readString(i); + int s = Util.readInt(i); assertEquals(example, s); assertEquals(i.available(), 0); + } } - - public byte[] readSamples(String ...samples) throws Exception{ - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for(String sample: samples) { - byte[] bytes = java.nio.file.Files.readAllBytes( - java.nio.file.Paths.get(getClass().getResource(sample).toURI()) - ); - out.write(bytes); - } - return out.toByteArray(); + } + + @Test + public void readWriteString() throws Exception { + String[] examples = { + "", "hello", "i am cow", "i am cow\nhear me moo\ni weight twice as much as you", "我是一个叉烧包", + }; + for (String example : examples) { + checkStringRoundTrip(example); } - @Test - public void tinyProxyInputOutputStream() throws Exception{ - proxyInputOutputStreams( - Arrays.copyOf(readSamples("/bandung.jpg"), 30), - readSamples(), - 10 - ); + } + + @Test + public void readWriteBigString() throws Exception { + int[] lengths = {0, 1, 126, 127, 128, 254, 255, 256, 1024, 99999, 1234567}; + for (int i = 0; i < lengths.length; i++) { + final char[] bigChars = new char[lengths[i]]; + java.util.Arrays.fill(bigChars, 'X'); + checkStringRoundTrip(new String(bigChars)); } - @Test - public void leftProxyInputOutputStream() throws Exception{ - proxyInputOutputStreams( - readSamples("/bandung.jpg", "/akanon.mid", "/gettysburg.txt", "/pip.tar.gz"), - readSamples(), - 2950 - ); + } + + public void checkStringRoundTrip(String example) throws Exception { + ByteArrayOutputStream o = new ByteArrayOutputStream(); + Util.writeString(o, example); + ByteArrayInputStream i = new ByteArrayInputStream(o.toByteArray()); + String s = Util.readString(i); + assertEquals(example, s); + assertEquals(i.available(), 0); + } + + public byte[] readSamples(String... samples) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (String sample : samples) { + byte[] bytes = java.nio.file.Files.readAllBytes( + java.nio.file.Paths.get(getClass().getResource(sample).toURI())); + out.write(bytes); } - @Test - public void rightProxyInputOutputStream() throws Exception{ - proxyInputOutputStreams( - readSamples(), - readSamples("/bandung.jpg", "/akanon.mid", "/gettysburg.txt", "/pip.tar.gz"), - 3000 - ); - } - @Test - public void mixedProxyInputOutputStream() throws Exception{ - proxyInputOutputStreams( - readSamples("/bandung.jpg", "/gettysburg.txt"), - readSamples("/akanon.mid", "/pip.tar.gz"), - 3050 - ); + return out.toByteArray(); + } + + @Test + public void tinyProxyInputOutputStream() throws Exception { + proxyInputOutputStreams(Arrays.copyOf(readSamples("/bandung.jpg"), 30), readSamples(), 10); + } + + @Test + public void leftProxyInputOutputStream() throws Exception { + proxyInputOutputStreams( + readSamples("/bandung.jpg", "/akanon.mid", "/gettysburg.txt", "/pip.tar.gz"), + readSamples(), + 2950); + } + + @Test + public void rightProxyInputOutputStream() throws Exception { + proxyInputOutputStreams( + readSamples(), + readSamples("/bandung.jpg", "/akanon.mid", "/gettysburg.txt", "/pip.tar.gz"), + 3000); + } + + @Test + public void mixedProxyInputOutputStream() throws Exception { + proxyInputOutputStreams( + readSamples("/bandung.jpg", "/gettysburg.txt"), + readSamples("/akanon.mid", "/pip.tar.gz"), + 3050); + } + + /** + * Make sure that when we shove data through both ProxyOutputStreams in + * variously sized chunks, we get the exact same bytes back out from the + * ProxyStreamPumper. + */ + public void proxyInputOutputStreams(byte[] samples1, byte[] samples2, int chunkMax) + throws Exception { + + ByteArrayOutputStream pipe = new ByteArrayOutputStream(); + OutputStream src1 = new ProxyStream.Output(pipe, ProxyStream.OUT); + OutputStream src2 = new ProxyStream.Output(pipe, ProxyStream.ERR); + + Random random = new Random(31337); + + int i1 = 0; + int i2 = 0; + while (i1 < samples1.length || i2 < samples2.length) { + int chunk = random.nextInt(chunkMax); + if (random.nextBoolean() && i1 < samples1.length) { + src1.write(samples1, i1, Math.min(samples1.length - i1, chunk)); + src1.flush(); + i1 += chunk; + } else if (i2 < samples2.length) { + src2.write(samples2, i2, Math.min(samples2.length - i2, chunk)); + src2.flush(); + i2 += chunk; + } } - /** - * Make sure that when we shove data through both ProxyOutputStreams in - * variously sized chunks, we get the exact same bytes back out from the - * ProxyStreamPumper. - */ - public void proxyInputOutputStreams(byte[] samples1, - byte[] samples2, - int chunkMax) throws Exception{ - - ByteArrayOutputStream pipe = new ByteArrayOutputStream(); - OutputStream src1 = new ProxyStream.Output(pipe, ProxyStream.OUT); - OutputStream src2 = new ProxyStream.Output(pipe, ProxyStream.ERR); - - Random random = new Random(31337); - - int i1 = 0; - int i2 = 0; - while(i1 < samples1.length || i2 < samples2.length){ - int chunk = random.nextInt(chunkMax); - if (random.nextBoolean() && i1 < samples1.length){ - src1.write(samples1, i1, Math.min(samples1.length-i1, chunk)); - src1.flush(); - i1 += chunk; - }else if (i2 < samples2.length){ - src2.write(samples2, i2, Math.min(samples2.length-i2, chunk)); - src2.flush(); - i2 += chunk; - } - } - - byte[] bytes = pipe.toByteArray(); - - - ByteArrayOutputStream dest1 = new ByteArrayOutputStream(); - ByteArrayOutputStream dest2 = new ByteArrayOutputStream(); - ProxyStream.Pumper pumper = new ProxyStream.Pumper( - new ByteArrayInputStream(bytes), - dest1, dest2 - ); - pumper.run(); - assertTrue(Arrays.equals(samples1, dest1.toByteArray())); - assertTrue(Arrays.equals(samples2, dest2.toByteArray())); - } + byte[] bytes = pipe.toByteArray(); + ByteArrayOutputStream dest1 = new ByteArrayOutputStream(); + ByteArrayOutputStream dest2 = new ByteArrayOutputStream(); + ProxyStream.Pumper pumper = + new ProxyStream.Pumper(new ByteArrayInputStream(bytes), dest1, dest2); + pumper.run(); + assertTrue(Arrays.equals(samples1, dest1.toByteArray())); + assertTrue(Arrays.equals(samples2, dest2.toByteArray())); + } } diff --git a/main/client/test/src/mill/main/client/FileToStreamTailerTest.java b/main/client/test/src/mill/main/client/FileToStreamTailerTest.java index 5fc22d7641e..5a175600524 100644 --- a/main/client/test/src/mill/main/client/FileToStreamTailerTest.java +++ b/main/client/test/src/mill/main/client/FileToStreamTailerTest.java @@ -1,5 +1,6 @@ package mill.main.client; +import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.io.File; @@ -8,155 +9,134 @@ import org.junit.Ignore; import org.junit.Test; - -import static org.junit.Assert.*; - public class FileToStreamTailerTest { - @org.junit.Rule - public RetryRule retryRule = new RetryRule(3); + @org.junit.Rule + public RetryRule retryRule = new RetryRule(3); - @Test - public void handleNonExistingFile() throws Exception{ - ByteArrayOutputStream bas = new ByteArrayOutputStream(); - final PrintStream ps = new PrintStream(bas); + @Test + public void handleNonExistingFile() throws Exception { + ByteArrayOutputStream bas = new ByteArrayOutputStream(); + final PrintStream ps = new PrintStream(bas); - final File file = File.createTempFile("tailer", ""); - assertTrue(file.delete()); + final File file = File.createTempFile("tailer", ""); + assertTrue(file.delete()); - try ( - final FileToStreamTailer tailer = new FileToStreamTailer(file, ps, 10); - ) { - tailer.start(); - Thread.sleep(200); - assertEquals(bas.toString(), ""); - } - } - @Test - public void handleNoExistingFileThatAppearsLater() throws Exception { - ByteArrayOutputStream bas = new ByteArrayOutputStream(); - final PrintStream ps = new PrintStream(bas); - - final File file = File.createTempFile("tailer", ""); - assertTrue(file.delete()); - - try ( - final FileToStreamTailer tailer = new FileToStreamTailer(file, ps, 10); - ) { - tailer.start(); - Thread.sleep(100); - assertEquals(bas.toString(), ""); - - try ( - PrintStream out = new PrintStream(Files.newOutputStream(file.toPath())); - ) { - out.println("log line"); - assertTrue(file.exists()); - Thread.sleep(100); - assertEquals(bas.toString(), "log line" + System.lineSeparator()); - } - } + try (final FileToStreamTailer tailer = new FileToStreamTailer(file, ps, 10); ) { + tailer.start(); + Thread.sleep(200); + assertEquals(bas.toString(), ""); } + } - @Test - public void handleExistingInitiallyEmptyFile() throws Exception{ - ByteArrayOutputStream bas = new ByteArrayOutputStream(); - final PrintStream ps = new PrintStream(bas); + @Test + public void handleNoExistingFileThatAppearsLater() throws Exception { + ByteArrayOutputStream bas = new ByteArrayOutputStream(); + final PrintStream ps = new PrintStream(bas); - final File file = File.createTempFile("tailer", ""); - assertTrue(file.exists()); + final File file = File.createTempFile("tailer", ""); + assertTrue(file.delete()); + + try (final FileToStreamTailer tailer = new FileToStreamTailer(file, ps, 10); ) { + tailer.start(); + Thread.sleep(100); + assertEquals(bas.toString(), ""); - try ( - final FileToStreamTailer tailer = new FileToStreamTailer(file, ps, 10); - ) { - tailer.start(); - Thread.sleep(100); - - assertEquals(bas.toString(), ""); - - try ( - PrintStream out = new PrintStream(Files.newOutputStream(file.toPath())); - ) { - out.println("log line"); - assertTrue(file.exists()); - Thread.sleep(100); - assertEquals(bas.toString(), "log line" + System.lineSeparator()); - } - } + try (PrintStream out = new PrintStream(Files.newOutputStream(file.toPath())); ) { + out.println("log line"); + assertTrue(file.exists()); + Thread.sleep(100); + assertEquals(bas.toString(), "log line" + System.lineSeparator()); + } } + } - @Test - public void handleExistingFileWithOldContent() throws Exception{ - ByteArrayOutputStream bas = new ByteArrayOutputStream(); - final PrintStream ps = new PrintStream(bas); + @Test + public void handleExistingInitiallyEmptyFile() throws Exception { + ByteArrayOutputStream bas = new ByteArrayOutputStream(); + final PrintStream ps = new PrintStream(bas); - final File file = File.createTempFile("tailer", ""); - assertTrue(file.exists()); + final File file = File.createTempFile("tailer", ""); + assertTrue(file.exists()); + + try (final FileToStreamTailer tailer = new FileToStreamTailer(file, ps, 10); ) { + tailer.start(); + Thread.sleep(100); - try ( - PrintStream out = new PrintStream(Files.newOutputStream(file.toPath())); - ) { - out.println("old line 1"); - out.println("old line 2"); - try ( - final FileToStreamTailer tailer = new FileToStreamTailer(file, ps, 10); - ) { - tailer.start(); - Thread.sleep(500); - assertEquals(bas.toString(), ""); - out.println("log line"); - assertTrue(file.exists()); - Thread.sleep(500); - assertEquals(bas.toString().trim(), "log line"); - } - } + assertEquals(bas.toString(), ""); + + try (PrintStream out = new PrintStream(Files.newOutputStream(file.toPath())); ) { + out.println("log line"); + assertTrue(file.exists()); + Thread.sleep(100); + assertEquals(bas.toString(), "log line" + System.lineSeparator()); + } } - @Ignore - @Test - public void handleExistingEmptyFileWhichDisappearsAndComesBack() throws Exception{ - ByteArrayOutputStream bas = new ByteArrayOutputStream(); - final PrintStream ps = new PrintStream(bas); + } + + @Test + public void handleExistingFileWithOldContent() throws Exception { + ByteArrayOutputStream bas = new ByteArrayOutputStream(); + final PrintStream ps = new PrintStream(bas); + + final File file = File.createTempFile("tailer", ""); + assertTrue(file.exists()); + + try (PrintStream out = new PrintStream(Files.newOutputStream(file.toPath())); ) { + out.println("old line 1"); + out.println("old line 2"); + try (final FileToStreamTailer tailer = new FileToStreamTailer(file, ps, 10); ) { + tailer.start(); + Thread.sleep(500); + assertEquals(bas.toString(), ""); + out.println("log line"); + assertTrue(file.exists()); + Thread.sleep(500); + assertEquals(bas.toString().trim(), "log line"); + } + } + } + + @Ignore + @Test + public void handleExistingEmptyFileWhichDisappearsAndComesBack() throws Exception { + ByteArrayOutputStream bas = new ByteArrayOutputStream(); + final PrintStream ps = new PrintStream(bas); - final File file = File.createTempFile("tailer", ""); + final File file = File.createTempFile("tailer", ""); + assertTrue(file.exists()); + + try (final FileToStreamTailer tailer = new FileToStreamTailer(file, ps, 10); ) { + tailer.start(); + Thread.sleep(100); + + assertEquals(bas.toString(), ""); + + try (PrintStream out = new PrintStream(Files.newOutputStream(file.toPath())); ) { + out.println("log line 1"); + out.println("log line 2"); assertTrue(file.exists()); + Thread.sleep(100); + assertEquals( + bas.toString(), + "log line 1" + System.lineSeparator() + "log line 2" + System.lineSeparator()); + } - try ( - final FileToStreamTailer tailer = new FileToStreamTailer(file, ps, 10); - ) { - tailer.start(); - Thread.sleep(100); - - assertEquals(bas.toString(), ""); - - try ( - PrintStream out = new PrintStream(Files.newOutputStream(file.toPath())); - ) { - out.println("log line 1"); - out.println("log line 2"); - assertTrue(file.exists()); - Thread.sleep(100); - assertEquals(bas.toString(), - "log line 1" + System.lineSeparator() + "log line 2" + System.lineSeparator()); - } - - // Now delete file and give some time, then append new lines - - assertTrue(file.delete()); - Thread.sleep(100); - - try ( - PrintStream out = new PrintStream(Files.newOutputStream(file.toPath())); - ) { - out.println("new line"); - assertTrue(file.exists()); - Thread.sleep(100); - assertEquals(bas.toString(), - "log line 1" + System.lineSeparator() + - "log line 2" + System.lineSeparator() + - "new line" + System.lineSeparator()); - } - - } + // Now delete file and give some time, then append new lines + assertTrue(file.delete()); + Thread.sleep(100); + + try (PrintStream out = new PrintStream(Files.newOutputStream(file.toPath())); ) { + out.println("new line"); + assertTrue(file.exists()); + Thread.sleep(100); + assertEquals( + bas.toString(), + "log line 1" + System.lineSeparator() + "log line 2" + + System.lineSeparator() + "new line" + + System.lineSeparator()); + } } + } } diff --git a/main/client/test/src/mill/main/client/MillEnvTests.java b/main/client/test/src/mill/main/client/MillEnvTests.java index a744a7e8f92..b979253e58f 100644 --- a/main/client/test/src/mill/main/client/MillEnvTests.java +++ b/main/client/test/src/mill/main/client/MillEnvTests.java @@ -1,30 +1,20 @@ package mill.main.client; - -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import java.util.List; - -import static org.junit.Assert.assertEquals; - +import org.junit.Test; public class MillEnvTests { - @Test - public void readOptsFileLinesWithoutFInalNewline() throws Exception { - File file = new File( - getClass().getClassLoader().getResource("file-wo-final-newline.txt").toURI() - ); - List lines = Util.readOptsFileLines(file); - assertEquals( - lines, - Arrays.asList( - "-DPROPERTY_PROPERLY_SET_VIA_JVM_OPTS=value-from-file", - "-Xss120m" - )); - } + @Test + public void readOptsFileLinesWithoutFInalNewline() throws Exception { + File file = new File( + getClass().getClassLoader().getResource("file-wo-final-newline.txt").toURI()); + List lines = Util.readOptsFileLines(file); + assertEquals( + lines, Arrays.asList("-DPROPERTY_PROPERLY_SET_VIA_JVM_OPTS=value-from-file", "-Xss120m")); + } } - - diff --git a/main/client/test/src/mill/main/client/ProxyStreamTests.java b/main/client/test/src/mill/main/client/ProxyStreamTests.java index 3af807c7a3e..02487f9580c 100644 --- a/main/client/test/src/mill/main/client/ProxyStreamTests.java +++ b/main/client/test/src/mill/main/client/ProxyStreamTests.java @@ -1,121 +1,117 @@ package mill.main.client; -import org.junit.Test; +import static org.junit.Assert.assertArrayEquals; import java.io.*; -import static org.junit.Assert.assertArrayEquals; import org.apache.commons.io.output.TeeOutputStream; +import org.junit.Test; + public class ProxyStreamTests { - /** - * Ad-hoc fuzz tests to try and make sure the stuff we write into the - * `ProxyStreams.Output` and read out of the `ProxyStreams.Pumper` ends up - * being the same - */ - @Test - public void test() throws Exception{ - // Test writes of sizes around 1, around 127, around 255, and much larger. These - // are likely sizes to have bugs since we write data in chunks of size 127 - int[] interestingLengths = { - 1, 2, 3, 4, 5, 6, 7, 8, 9, - 10, 20, 30, 40, 50, 100, - 126, 127, 128, 129, 130, - 253, 254, 255, 256, 257, - 1000, 2000, 4000, 8000 - }; - byte[] interestingBytes = { - -1, -127, -126, - -120, -100, -80, -60, -40, -20, -10, - -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, - 10, 20, 40, 60, 80, 100, 120, - 125, 126, 127 - }; - - for (int n: interestingLengths){ - - System.out.println("ProxyStreamTests fuzzing length " + n); - for (int r = 1; r < interestingBytes.length + 1; r += 1) { - byte[] outData = new byte[n]; - byte[] errData = new byte[n]; - for(int j = 0; j < n; j++) { - // fill test data blobs with arbitrary bytes from `interestingBytes`, negating - // the bytes we use for `errData` so we can distinguish it from `outData` - // - // offset the start byte we use by `r`, so we exercise writing blobs - // that start with every value listed in `interestingBytes` - outData[j] = interestingBytes[(j + r) % interestingBytes.length]; - errData[j] = (byte)-interestingBytes[(j + r) % interestingBytes.length]; - } - - // Run all tests both with the format `ProxyStream.END` packet - // being sent as well as when the stream is unceremoniously closed - test0(outData, errData, r, false); - test0(outData, errData, r, true); - } + /** + * Ad-hoc fuzz tests to try and make sure the stuff we write into the + * `ProxyStreams.Output` and read out of the `ProxyStreams.Pumper` ends up + * being the same + */ + @Test + public void test() throws Exception { + // Test writes of sizes around 1, around 127, around 255, and much larger. These + // are likely sizes to have bugs since we write data in chunks of size 127 + int[] interestingLengths = { + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 100, 126, 127, 128, 129, 130, 253, 254, 255, + 256, 257, 1000, 2000, 4000, 8000 + }; + byte[] interestingBytes = { + -1, -127, -126, -120, -100, -80, -60, -40, -20, -10, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 10, + 20, 40, 60, 80, 100, 120, 125, 126, 127 + }; + + for (int n : interestingLengths) { + + System.out.println("ProxyStreamTests fuzzing length " + n); + for (int r = 1; r < interestingBytes.length + 1; r += 1) { + byte[] outData = new byte[n]; + byte[] errData = new byte[n]; + for (int j = 0; j < n; j++) { + // fill test data blobs with arbitrary bytes from `interestingBytes`, negating + // the bytes we use for `errData` so we can distinguish it from `outData` + // + // offset the start byte we use by `r`, so we exercise writing blobs + // that start with every value listed in `interestingBytes` + outData[j] = interestingBytes[(j + r) % interestingBytes.length]; + errData[j] = (byte) -interestingBytes[(j + r) % interestingBytes.length]; } - } - - public void test0(byte[] outData, byte[] errData, int repeats, boolean gracefulEnd) throws Exception{ - PipedOutputStream pipedOutputStream = new PipedOutputStream(); - PipedInputStream pipedInputStream = new PipedInputStream(1000000); - - pipedInputStream.connect(pipedOutputStream); - ProxyStream.Output srcOut = new ProxyStream.Output(pipedOutputStream, ProxyStream.OUT); - ProxyStream.Output srcErr = new ProxyStream.Output(pipedOutputStream, ProxyStream.ERR); - - // Capture both the destOut/destErr from the pumper, as well as the destCombined - // to ensure the individual streams contain the right data and combined stream - // is in the right order - ByteArrayOutputStream destOut = new ByteArrayOutputStream(); - ByteArrayOutputStream destErr = new ByteArrayOutputStream(); - ByteArrayOutputStream destCombined = new ByteArrayOutputStream(); - ProxyStream.Pumper pumper = new ProxyStream.Pumper( - pipedInputStream, - new TeeOutputStream(destOut, destCombined), - new TeeOutputStream(destErr, destCombined) - ); - - - new Thread(() -> { - try { - for (int i = 0; i < repeats; i++) { - srcOut.write(outData); - srcErr.write(errData); - } - - if (gracefulEnd) ProxyStream.sendEnd(pipedOutputStream); - else { - pipedOutputStream.close(); - } - }catch(Exception e){ e.printStackTrace();} - }).start(); + // Run all tests both with the format `ProxyStream.END` packet + // being sent as well as when the stream is unceremoniously closed + test0(outData, errData, r, false); + test0(outData, errData, r, true); + } + } + } + + public void test0(byte[] outData, byte[] errData, int repeats, boolean gracefulEnd) + throws Exception { + PipedOutputStream pipedOutputStream = new PipedOutputStream(); + PipedInputStream pipedInputStream = new PipedInputStream(1000000); + + pipedInputStream.connect(pipedOutputStream); + + ProxyStream.Output srcOut = new ProxyStream.Output(pipedOutputStream, ProxyStream.OUT); + ProxyStream.Output srcErr = new ProxyStream.Output(pipedOutputStream, ProxyStream.ERR); + + // Capture both the destOut/destErr from the pumper, as well as the destCombined + // to ensure the individual streams contain the right data and combined stream + // is in the right order + ByteArrayOutputStream destOut = new ByteArrayOutputStream(); + ByteArrayOutputStream destErr = new ByteArrayOutputStream(); + ByteArrayOutputStream destCombined = new ByteArrayOutputStream(); + ProxyStream.Pumper pumper = new ProxyStream.Pumper( + pipedInputStream, + new TeeOutputStream(destOut, destCombined), + new TeeOutputStream(destErr, destCombined)); + + new Thread(() -> { + try { + for (int i = 0; i < repeats; i++) { + srcOut.write(outData); + srcErr.write(errData); + } - Thread pumperThread = new Thread(pumper); + if (gracefulEnd) ProxyStream.sendEnd(pipedOutputStream); + else { + pipedOutputStream.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + }) + .start(); - pumperThread.start(); - pumperThread.join(); + Thread pumperThread = new Thread(pumper); - // Check that the individual `destOut` and `destErr` contain the correct bytes - assertArrayEquals(repeatArray(outData, repeats), destOut.toByteArray()); - assertArrayEquals(repeatArray(errData, repeats), destErr.toByteArray()); + pumperThread.start(); + pumperThread.join(); - // Check that the combined `destCombined` contains the correct bytes in the correct order - byte[] combinedData = new byte[outData.length + errData.length]; + // Check that the individual `destOut` and `destErr` contain the correct bytes + assertArrayEquals(repeatArray(outData, repeats), destOut.toByteArray()); + assertArrayEquals(repeatArray(errData, repeats), destErr.toByteArray()); - System.arraycopy(outData, 0, combinedData, 0, outData.length); - System.arraycopy(errData, 0, combinedData, outData.length, errData.length); + // Check that the combined `destCombined` contains the correct bytes in the correct order + byte[] combinedData = new byte[outData.length + errData.length]; - assertArrayEquals(repeatArray(combinedData, repeats), destCombined.toByteArray()); - } + System.arraycopy(outData, 0, combinedData, 0, outData.length); + System.arraycopy(errData, 0, combinedData, outData.length, errData.length); - private static byte[] repeatArray(byte[] original, int n) { - byte[] result = new byte[original.length * n]; + assertArrayEquals(repeatArray(combinedData, repeats), destCombined.toByteArray()); + } - for (int i = 0; i < n; i++) { - System.arraycopy(original, 0, result, i * original.length, original.length); - } + private static byte[] repeatArray(byte[] original, int n) { + byte[] result = new byte[original.length * n]; - return result; + for (int i = 0; i < n; i++) { + System.arraycopy(original, 0, result, i * original.length, original.length); } + return result; + } } diff --git a/main/client/test/src/mill/main/client/RetryRule.java b/main/client/test/src/mill/main/client/RetryRule.java index c53dd332ad3..8abfa049288 100644 --- a/main/client/test/src/mill/main/client/RetryRule.java +++ b/main/client/test/src/mill/main/client/RetryRule.java @@ -1,36 +1,41 @@ // Taken from https://www.swtestacademy.com/rerun-failed-test-junit/ package mill.main.client; + import java.util.Objects; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; + public class RetryRule implements TestRule { - private int retryCount; - public RetryRule(int retryCount) { - this.retryCount = retryCount; - } - public Statement apply(Statement base, Description description) { - return statement(base, description); - } - private Statement statement(final Statement base, final Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - Throwable caughtThrowable = null; - // implement retry logic here - for (int i = 0; i < retryCount; i++) { - try { - base.evaluate(); - return; - } - catch (Throwable t) { - caughtThrowable = t; - System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed."); - } - } - System.err.println(description.getDisplayName() + ": Giving up after " + retryCount + " failures."); - throw Objects.requireNonNull(caughtThrowable); - } - }; - } -} \ No newline at end of file + private int retryCount; + + public RetryRule(int retryCount) { + this.retryCount = retryCount; + } + + public Statement apply(Statement base, Description description) { + return statement(base, description); + } + + private Statement statement(final Statement base, final Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + Throwable caughtThrowable = null; + // implement retry logic here + for (int i = 0; i < retryCount; i++) { + try { + base.evaluate(); + return; + } catch (Throwable t) { + caughtThrowable = t; + System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed."); + } + } + System.err.println( + description.getDisplayName() + ": Giving up after " + retryCount + " failures."); + throw Objects.requireNonNull(caughtThrowable); + } + }; + } +} diff --git a/main/codesig/test/cases/callgraph/basic/1-static-method/src/Hello.java b/main/codesig/test/cases/callgraph/basic/1-static-method/src/Hello.java index ab7ba498a82..26a7e798121 100644 --- a/main/codesig/test/cases/callgraph/basic/1-static-method/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/1-static-method/src/Hello.java @@ -1,9 +1,17 @@ package hello; -public class Hello{ - public static int main(){ return used(); } - public static int used(){ return 2; } - public static int unused(){ return 1; } +public class Hello { + public static int main() { + return used(); + } + + public static int used() { + return 2; + } + + public static int unused() { + return 1; + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/basic/10-overriden-static-method/src/Hello.java b/main/codesig/test/cases/callgraph/basic/10-overriden-static-method/src/Hello.java index d53bf75ed0b..08ea86c33ce 100644 --- a/main/codesig/test/cases/callgraph/basic/10-overriden-static-method/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/10-overriden-static-method/src/Hello.java @@ -1,17 +1,33 @@ package hello; -class GrandParent{ - public static int foo(){ return 1; } - public static int bar(){ return 2; } +class GrandParent { + public static int foo() { + return 1; + } + + public static int bar() { + return 2; + } } -class Parent extends GrandParent{ - public static int foo(){ return 3; } - public static int bar(){ return 4; } + +class Parent extends GrandParent { + public static int foo() { + return 3; + } + + public static int bar() { + return 4; + } } -public class Hello extends Parent{ - public static int main(){ return foo() + bar(); } - public static int foo(){ return 5; } +public class Hello extends Parent { + public static int main() { + return foo() + bar(); + } + + public static int foo() { + return 5; + } } /* expected-direct-call-graph { diff --git a/main/codesig/test/cases/callgraph/basic/11-peer-inherited-method/src/Hello.java b/main/codesig/test/cases/callgraph/basic/11-peer-inherited-method/src/Hello.java index 274f4a6d564..0a957c11c36 100644 --- a/main/codesig/test/cases/callgraph/basic/11-peer-inherited-method/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/11-peer-inherited-method/src/Hello.java @@ -1,22 +1,28 @@ package hello; -interface Foo{ - public int used(); - public int other(); +interface Foo { + public int used(); + + public int other(); } -class Bar{ - public int used(){ return 2; } - public int other(){ return 1; } +class Bar { + public int used() { + return 2; + } + + public int other() { + return 1; + } } -class Qux extends Bar implements Foo{} +class Qux extends Bar implements Foo {} public class Hello { - public static int main(){ - Foo foo = new Qux(); - return foo.used(); - } + public static int main() { + Foo foo = new Qux(); + return foo.used(); + } } /* expected-direct-call-graph { diff --git a/main/codesig/test/cases/callgraph/basic/12-java-lambda/src/Hello.java b/main/codesig/test/cases/callgraph/basic/12-java-lambda/src/Hello.java index b40b63a1a6a..beab61cbf49 100644 --- a/main/codesig/test/cases/callgraph/basic/12-java-lambda/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/12-java-lambda/src/Hello.java @@ -1,12 +1,18 @@ package hello; -public class Hello{ - public static int main(){ - java.util.function.IntSupplier foo = () -> used(); - return foo.getAsInt(); - } - public static int used(){ return 2; } - public static int unused(){ return 1; } +public class Hello { + public static int main() { + java.util.function.IntSupplier foo = () -> used(); + return foo.getAsInt(); + } + + public static int used() { + return 2; + } + + public static int unused() { + return 1; + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/basic/13-java-anon-class-lambda/src/Hello.java b/main/codesig/test/cases/callgraph/basic/13-java-anon-class-lambda/src/Hello.java index 9113e1c2252..788654805aa 100644 --- a/main/codesig/test/cases/callgraph/basic/13-java-anon-class-lambda/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/13-java-anon-class-lambda/src/Hello.java @@ -1,14 +1,22 @@ package hello; -public class Hello{ - public static int main(){ - java.util.function.IntSupplier foo = new java.util.function.IntSupplier(){ - public int getAsInt(){ return used(); } - }; - return foo.getAsInt(); - } - public static int used(){ return 2; } - public static int unused(){ return 1; } +public class Hello { + public static int main() { + java.util.function.IntSupplier foo = new java.util.function.IntSupplier() { + public int getAsInt() { + return used(); + } + }; + return foo.getAsInt(); + } + + public static int used() { + return 2; + } + + public static int unused() { + return 1; + } } // We treat single-abstract-method classes similarly to InvokeDynamic lambdas: diff --git a/main/codesig/test/cases/callgraph/basic/14-clinit/src/Hello.java b/main/codesig/test/cases/callgraph/basic/14-clinit/src/Hello.java index 1678a7e83f4..79c1e021154 100644 --- a/main/codesig/test/cases/callgraph/basic/14-clinit/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/14-clinit/src/Hello.java @@ -1,33 +1,47 @@ package hello; -class Foo{ - static { - initFoo(); - } +class Foo { + static { + initFoo(); + } - static void initFoo(){ System.out.println("Initializing class Foo"); } - public static int foo(){ return 1; } + static void initFoo() { + System.out.println("Initializing class Foo"); + } + + public static int foo() { + return 1; + } } -class Bar{ - static { - initBar(); - } - static void initBar(){ System.out.println("Initializing class Bar"); } - public int x = 1; +class Bar { + static { + initBar(); + } + + static void initBar() { + System.out.println("Initializing class Bar"); + } + + public int x = 1; } -class Qux{ - static { - initQux(); - } - static void initQux(){ System.out.println("Initializing class Qux"); } - public static int x = 1; +class Qux { + static { + initQux(); + } + + static void initQux() { + System.out.println("Initializing class Qux"); + } + + public static int x = 1; } -public class Hello{ - public static int main(){ - return Foo.foo() + new Bar().x + Qux.x; - } + +public class Hello { + public static int main() { + return Foo.foo() + new Bar().x + Qux.x; + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/basic/15-private-method-not-inherited/src/Hello.java b/main/codesig/test/cases/callgraph/basic/15-private-method-not-inherited/src/Hello.java index 020cc2c76e2..c121a4a4f32 100644 --- a/main/codesig/test/cases/callgraph/basic/15-private-method-not-inherited/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/15-private-method-not-inherited/src/Hello.java @@ -4,17 +4,30 @@ // `Hello#bar` -> `Parent#foo`, we can be confident we are calling `Parent#foo` // specifically and not calling `Hello#foo` or `Grandparent#foo` -class Grandparent{ - private int foo(){ return 2; } +class Grandparent { + private int foo() { + return 2; + } } -class Parent extends Grandparent{ - private int foo(){ return 2; } - int bar(){ return foo(); } + +class Parent extends Grandparent { + private int foo() { + return 2; + } + + int bar() { + return foo(); + } } -public class Hello extends Parent{ - public static int main(){ return new Hello().bar(); } - private int foo(){ return 3; } +public class Hello extends Parent { + public static int main() { + return new Hello().bar(); + } + + private int foo() { + return 3; + } } /* expected-direct-call-graph { diff --git a/main/codesig/test/cases/callgraph/basic/2-instance-method/src/Hello.java b/main/codesig/test/cases/callgraph/basic/2-instance-method/src/Hello.java index a34e9e9ac2d..3f301063697 100644 --- a/main/codesig/test/cases/callgraph/basic/2-instance-method/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/2-instance-method/src/Hello.java @@ -1,9 +1,17 @@ package hello; -public class Hello{ - public static int main(){ return new Hello().used(); } - public int used(){ return 2; } - public int unused(){ return 1; } +public class Hello { + public static int main() { + return new Hello().used(); + } + + public int used() { + return 2; + } + + public int unused() { + return 1; + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/basic/20-array-method/src/Hello.java b/main/codesig/test/cases/callgraph/basic/20-array-method/src/Hello.java index 2666559e40f..7a1bccb1be8 100644 --- a/main/codesig/test/cases/callgraph/basic/20-array-method/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/20-array-method/src/Hello.java @@ -1,9 +1,17 @@ package hello; -public class Hello{ - public static int main(){ return used() + new Hello[10].clone().length + new Hello[10].hashCode(); } - public static int used(){ return 2; } - public static int unused(){ return 1; } +public class Hello { + public static int main() { + return used() + new Hello[10].clone().length + new Hello[10].hashCode(); + } + + public static int used() { + return 2; + } + + public static int unused() { + return 1; + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/basic/3-sam-interface-method/src/Hello.java b/main/codesig/test/cases/callgraph/basic/3-sam-interface-method/src/Hello.java index 915c8b51e89..78d1741bae4 100644 --- a/main/codesig/test/cases/callgraph/basic/3-sam-interface-method/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/3-sam-interface-method/src/Hello.java @@ -1,23 +1,35 @@ package hello; -interface Foo{ - public int used(); +interface Foo { + public int used(); } -class Bar implements Foo{ - public int used() { return 1; } - public int unused1() { return 3; } +class Bar implements Foo { + public int used() { + return 1; + } + + public int unused1() { + return 3; + } } -class Qux implements Foo{ - public int used() { return 2; } - public int unused2() { return 4; } + +class Qux implements Foo { + public int used() { + return 2; + } + + public int unused2() { + return 4; + } } -public class Hello{ - public static int main(){ - Foo bar = new Bar(); - Foo qux = new Qux(); - return bar.used() + qux.used(); - } + +public class Hello { + public static int main() { + Foo bar = new Bar(); + Foo qux = new Qux(); + return bar.used() + qux.used(); + } } // Single-abstract method "SAM" interfaces and their implementing classes are diff --git a/main/codesig/test/cases/callgraph/basic/4-multi-interface-method/src/Hello.java b/main/codesig/test/cases/callgraph/basic/4-multi-interface-method/src/Hello.java index 97dbcb40c8a..af183279b73 100644 --- a/main/codesig/test/cases/callgraph/basic/4-multi-interface-method/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/4-multi-interface-method/src/Hello.java @@ -1,26 +1,45 @@ package hello; -interface Foo{ - public int used(); - public int otherUnused(); +interface Foo { + public int used(); + + public int otherUnused(); } -class Bar implements Foo{ - public int used() { return 1; } - public int otherUnused() { return 1; } - public int unused1() { return 3; } +class Bar implements Foo { + public int used() { + return 1; + } + + public int otherUnused() { + return 1; + } + + public int unused1() { + return 3; + } } -class Qux implements Foo{ - public int used() { return 2; } - public int otherUnused() { return 2; } - public int unused2() { return 4; } + +class Qux implements Foo { + public int used() { + return 2; + } + + public int otherUnused() { + return 2; + } + + public int unused2() { + return 4; + } } -public class Hello{ - public static int main(){ - Foo bar = new Bar(); - Foo qux = new Qux(); - return bar.used() + qux.used(); - } + +public class Hello { + public static int main() { + Foo bar = new Bar(); + Foo qux = new Qux(); + return bar.used() + qux.used(); + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/basic/5-inherited-method/src/Hello.java b/main/codesig/test/cases/callgraph/basic/5-inherited-method/src/Hello.java index cbb71cb89c2..49942cf612b 100644 --- a/main/codesig/test/cases/callgraph/basic/5-inherited-method/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/5-inherited-method/src/Hello.java @@ -1,12 +1,19 @@ package hello; -class Parent{ - public int used(){ return 2; } +class Parent { + public int used() { + return 2; + } } -public class Hello extends Parent{ - public static int main(){ return new Hello().used(); } - public int unused(){return 1;} +public class Hello extends Parent { + public static int main() { + return new Hello().used(); + } + + public int unused() { + return 1; + } } /* expected-direct-call-graph { diff --git a/main/codesig/test/cases/callgraph/basic/6-inherited-interface-method/src/Hello.java b/main/codesig/test/cases/callgraph/basic/6-inherited-interface-method/src/Hello.java index 22de97dcb86..4f643674571 100644 --- a/main/codesig/test/cases/callgraph/basic/6-inherited-interface-method/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/6-inherited-interface-method/src/Hello.java @@ -1,12 +1,19 @@ package hello; -interface Parent{ - default int used(){ return 2; } +interface Parent { + default int used() { + return 2; + } } -public class Hello implements Parent{ - public static int main(){ return new Hello().used(); } - public int unused(){return 1;} +public class Hello implements Parent { + public static int main() { + return new Hello().used(); + } + + public int unused() { + return 1; + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/basic/7-transitive-static-methods/src/Hello.java b/main/codesig/test/cases/callgraph/basic/7-transitive-static-methods/src/Hello.java index 8355963d3cd..3d21a1c16ea 100644 --- a/main/codesig/test/cases/callgraph/basic/7-transitive-static-methods/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/7-transitive-static-methods/src/Hello.java @@ -1,17 +1,25 @@ package hello; -public class Hello{ - public static int main(){ - return usedStatic(); - } +public class Hello { + public static int main() { + return usedStatic(); + } - public static int unusedStatic(){ return usedTransitiveStatic(); } + public static int unusedStatic() { + return usedTransitiveStatic(); + } - public static int usedStatic(){ return usedTransitiveStatic(); } + public static int usedStatic() { + return usedTransitiveStatic(); + } - public static int usedTransitiveStatic(){ return 2 + Hello.usedDeepestStatic(); } + public static int usedTransitiveStatic() { + return 2 + Hello.usedDeepestStatic(); + } - public static int usedDeepestStatic(){ return 3; } + public static int usedDeepestStatic() { + return 3; + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/basic/8-transitive-virtual-methods/src/Hello.java b/main/codesig/test/cases/callgraph/basic/8-transitive-virtual-methods/src/Hello.java index 3251fae1754..9d37287a1f1 100644 --- a/main/codesig/test/cases/callgraph/basic/8-transitive-virtual-methods/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/8-transitive-virtual-methods/src/Hello.java @@ -1,17 +1,25 @@ package hello; -public class Hello{ - public static int main(){ - return new Hello().used(); - } +public class Hello { + public static int main() { + return new Hello().used(); + } - public int unused(){ return usedTransitive(); } + public int unused() { + return usedTransitive(); + } - public int used(){ return usedTransitive(); } + public int used() { + return usedTransitive(); + } - public int usedTransitive(){ return 2 + Hello.usedDeepestStatic(); } + public int usedTransitive() { + return 2 + Hello.usedDeepestStatic(); + } - public static int usedDeepestStatic(){ return 3; } + public static int usedDeepestStatic() { + return 3; + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/basic/9-overriden-virtual-method/src/Hello.java b/main/codesig/test/cases/callgraph/basic/9-overriden-virtual-method/src/Hello.java index 1aad08734de..4035d06140e 100644 --- a/main/codesig/test/cases/callgraph/basic/9-overriden-virtual-method/src/Hello.java +++ b/main/codesig/test/cases/callgraph/basic/9-overriden-virtual-method/src/Hello.java @@ -1,17 +1,33 @@ package hello; -abstract class GrandParent{ - public int foo(){ return 1; } - public int bar(){ return 2; } +abstract class GrandParent { + public int foo() { + return 1; + } + + public int bar() { + return 2; + } } -abstract class Parent extends GrandParent{ - public int foo(){ return 3; } - public int bar(){ return 4; } + +abstract class Parent extends GrandParent { + public int foo() { + return 3; + } + + public int bar() { + return 4; + } } -public class Hello extends Parent{ - public static int main(){ return new Hello().foo() + new Hello().bar(); } - public int foo(){ return 5; } +public class Hello extends Parent { + public static int main() { + return new Hello().foo() + new Hello().bar(); + } + + public int foo() { + return 5; + } } /* expected-direct-call-graph { diff --git a/main/codesig/test/cases/callgraph/complicated/1-statics/src/Hello.java b/main/codesig/test/cases/callgraph/complicated/1-statics/src/Hello.java index a9c3579a0bb..65bd994621f 100644 --- a/main/codesig/test/cases/callgraph/complicated/1-statics/src/Hello.java +++ b/main/codesig/test/cases/callgraph/complicated/1-statics/src/Hello.java @@ -1,57 +1,61 @@ package hello; -// Taken from https://github.com/lihaoyi/Metascala/blob/76dfbfa18484b9ee39bd09453328ea1081fcab6b/src/test/java/metascala/features/methods/Statics.java +// Taken from +// https://github.com/lihaoyi/Metascala/blob/76dfbfa18484b9ee39bd09453328ea1081fcab6b/src/test/java/metascala/features/methods/Statics.java public class Hello { - public static int helloWorld(int n){ - return timesTwo(n); - } + public static int helloWorld(int n) { + return timesTwo(n); + } - public static int timesTwo(int n){ - return n * 2; - } + public static int timesTwo(int n) { + return n * 2; + } - public static int helloWorld2(int a, int b){ - return timesTwo2(a, b); - } + public static int helloWorld2(int a, int b) { + return timesTwo2(a, b); + } - public static int timesTwo2(int a, int b){ - return (a - b) * 2; - } + public static int timesTwo2(int a, int b) { + return (a - b) * 2; + } - public static int tailFactorial(int n){ - if (n == 1){ - return 1; - }else{ - return n * tailFactorial(n-1); - } - } - public static int fibonacci(int n){ - if (n == 1 || n == 0){ - return 1; - }else{ - return fibonacci(n-1) + fibonacci(n-2); - } - } - public static int indirectFibonacciA(int n){ - if (n == 1 || n == 0){ - return 1; - }else{ - return indirectFibonacciB(n-1) + indirectFibonacciB(n-2); - } + public static int tailFactorial(int n) { + if (n == 1) { + return 1; + } else { + return n * tailFactorial(n - 1); } + } - public static int indirectFibonacciB(int n){ - return indirectFibonacciA(n); + public static int fibonacci(int n) { + if (n == 1 || n == 0) { + return 1; + } else { + return fibonacci(n - 1) + fibonacci(n - 2); } + } - public static int call(int x) { - return x+1; + public static int indirectFibonacciA(int n) { + if (n == 1 || n == 0) { + return 1; + } else { + return indirectFibonacciB(n - 1) + indirectFibonacciB(n - 2); } - public static int callAtPhiBoundary(int i){ + } - int size = (i < 0) ? 1 : call(i); - return size; - } + public static int indirectFibonacciB(int n) { + return indirectFibonacciA(n); + } + + public static int call(int x) { + return x + 1; + } + + public static int callAtPhiBoundary(int i) { + + int size = (i < 0) ? 1 : call(i); + return size; + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/complicated/2-sudoku/src/Hello.java b/main/codesig/test/cases/callgraph/complicated/2-sudoku/src/Hello.java index 9f574d7b048..ccec1fa810e 100644 --- a/main/codesig/test/cases/callgraph/complicated/2-sudoku/src/Hello.java +++ b/main/codesig/test/cases/callgraph/complicated/2-sudoku/src/Hello.java @@ -1,89 +1,77 @@ package hello; -// Taken from https://github.com/lihaoyi/Metascala/blob/76dfbfa18484b9ee39bd09453328ea1081fcab6b/src/test/java/metascala/full/Sudoku.java +// Taken from +// https://github.com/lihaoyi/Metascala/blob/76dfbfa18484b9ee39bd09453328ea1081fcab6b/src/test/java/metascala/full/Sudoku.java import java.util.*; -import java.math.BigInteger; import java.util.concurrent.atomic.*; import java.util.regex.*; -import java.lang.reflect.Array; public class Hello { - public static String run(){ - int[][] grid = { - {5, 3, 0, 0, 7, 0, 0, 0, 0}, - {6, 0, 0, 1, 9, 5, 0, 0, 0}, - {0, 9, 8, 0, 0, 0, 0, 6, 0}, - {8, 0, 0, 0, 6, 0, 0, 0, 3}, - {4, 0, 0, 8, 0, 3, 0, 0, 1}, - {7, 0, 0, 0, 2, 0, 0, 0, 6}, - {0, 6, 0, 0, 0, 0, 2, 8, 0}, - {0, 0, 0, 4, 1, 9, 0, 0, 5}, - {0, 0, 0, 0, 8, 0, 0, 7, 9}, - }; - Hello.solve(0, 0, grid); - return Hello.writeMatrix(grid); + public static String run() { + int[][] grid = { + {5, 3, 0, 0, 7, 0, 0, 0, 0}, + {6, 0, 0, 1, 9, 5, 0, 0, 0}, + {0, 9, 8, 0, 0, 0, 0, 6, 0}, + {8, 0, 0, 0, 6, 0, 0, 0, 3}, + {4, 0, 0, 8, 0, 3, 0, 0, 1}, + {7, 0, 0, 0, 2, 0, 0, 0, 6}, + {0, 6, 0, 0, 0, 0, 2, 8, 0}, + {0, 0, 0, 4, 1, 9, 0, 0, 5}, + {0, 0, 0, 0, 8, 0, 0, 7, 9}, + }; + Hello.solve(0, 0, grid); + return Hello.writeMatrix(grid); + } + + static boolean solve(int i, int j, int[][] cells) { + if (i == 9) { + i = 0; + if (++j == 9) return true; } - static boolean solve(int i, int j, int[][] cells) { - if (i == 9) { - i = 0; - if (++j == 9) - return true; - } - if (cells[i][j] != 0) // skip filled cells - return solve(i+1,j,cells); + if (cells[i][j] != 0) // skip filled cells + return solve(i + 1, j, cells); - for (int val = 1; val <= 9; ++val) { - if (legal(i,j,val,cells)) { - cells[i][j] = val; - if (solve(i+1,j,cells)) - return true; - } - } - cells[i][j] = 0; // reset on backtrack - return false; + for (int val = 1; val <= 9; ++val) { + if (legal(i, j, val, cells)) { + cells[i][j] = val; + if (solve(i + 1, j, cells)) return true; + } } + cells[i][j] = 0; // reset on backtrack + return false; + } - static boolean legal(int i, int j, int val, int[][] cells) { - for (int k = 0; k < 9; ++k) // row - if (val == cells[k][j]) - return false; + static boolean legal(int i, int j, int val, int[][] cells) { + for (int k = 0; k < 9; ++k) // row + if (val == cells[k][j]) return false; - for (int k = 0; k < 9; ++k) // col - if (val == cells[i][k]) - return false; + for (int k = 0; k < 9; ++k) // col + if (val == cells[i][k]) return false; - int boxRowOffset = (i / 3)*3; - int boxColOffset = (j / 3)*3; - for (int k = 0; k < 3; ++k) // box - for (int m = 0; m < 3; ++m) - if (val == cells[boxRowOffset+k][boxColOffset+m]) - return false; + int boxRowOffset = (i / 3) * 3; + int boxColOffset = (j / 3) * 3; + for (int k = 0; k < 3; ++k) // box + for (int m = 0; m < 3; ++m) if (val == cells[boxRowOffset + k][boxColOffset + m]) return false; - return true; // no violations, so it's legal - } + return true; // no violations, so it's legal + } - static String writeMatrix(int[][] solution) { + static String writeMatrix(int[][] solution) { - StringBuilder s = new StringBuilder("\n"); - for (int i = 0; i < 9; ++i) { - if (i % 3 == 0) - s.append(" -----------------------\n"); - for (int j = 0; j < 9; ++j) { - if (j % 3 == 0) s.append("| "); - s.append( - solution[i][j] == 0 - ? " " - : Integer.toString(solution[i][j]) - ); + StringBuilder s = new StringBuilder("\n"); + for (int i = 0; i < 9; ++i) { + if (i % 3 == 0) s.append(" -----------------------\n"); + for (int j = 0; j < 9; ++j) { + if (j % 3 == 0) s.append("| "); + s.append(solution[i][j] == 0 ? " " : Integer.toString(solution[i][j])); - s.append(' '); - } - s.append("|\n"); - } - s.append(" ----------------------- "); - return s.toString(); + s.append(' '); + } + s.append("|\n"); } - + s.append(" ----------------------- "); + return s.toString(); + } } /* expected-direct-call-graph { diff --git a/main/codesig/test/cases/callgraph/complicated/3-classes-cars/src/Hello.java b/main/codesig/test/cases/callgraph/complicated/3-classes-cars/src/Hello.java index 853eabb0d26..1b3c0122452 100644 --- a/main/codesig/test/cases/callgraph/complicated/3-classes-cars/src/Hello.java +++ b/main/codesig/test/cases/callgraph/complicated/3-classes-cars/src/Hello.java @@ -1,71 +1,73 @@ package hello; -// Taken from https://github.com/lihaoyi/Metascala/blob/76dfbfa18484b9ee39bd09453328ea1081fcab6b/src/test/java/metascala/features/classes/Inheritance.java - - -import java.util.HashMap; -import java.util.Map; -import java.util.Vector; +// Taken from +// https://github.com/lihaoyi/Metascala/blob/76dfbfa18484b9ee39bd09453328ea1081fcab6b/src/test/java/metascala/features/classes/Inheritance.java public class Hello { - public static String abstractClass(){ - Car toyota = new Toyota(); - return toyota.vroom(); - } + public static String abstractClass() { + Car toyota = new Toyota(); + return toyota.vroom(); + } - public static String shadowedInheritedGet(){ - Car honda = new Honda(); - return honda.vroom(); - } + public static String shadowedInheritedGet() { + Car honda = new Honda(); + return honda.vroom(); + } - public static String shadowedInheritedSet(){ - Car honda = new Honda(); - honda.rev(); - honda.cc++; - ((Honda)honda).cc++; - return honda.vroom(); - } + public static String shadowedInheritedSet() { + Car honda = new Honda(); + honda.rev(); + honda.cc++; + ((Honda) honda).cc++; + return honda.vroom(); + } - public static String superMethod(){ - return new Toyota().superVStart(); - } + public static String superMethod() { + return new Toyota().superVStart(); + } } -class Toyota extends Car{ - public Toyota(){ - this.cc = 10; - } +class Toyota extends Car { + public Toyota() { + this.cc = 10; + } - public String vStart(){ - return "vr"; - } - public String superVStart(){ - return super.vStart(); - } + public String vStart() { + return "vr"; + } + + public String superVStart() { + return super.vStart(); + } } -class Honda extends Car{ - public int cc = 5; - public String vStart(){ - return "v" + cc + "r" + ((Car)this).cc + "r" + super.cc; - } + +class Honda extends Car { + public int cc = 5; + + public String vStart() { + return "v" + cc + "r" + ((Car) this).cc + "r" + super.cc; + } } -class Car{ - public int cc; - public String vStart(){ - return ""; - } - public void rev(){ - this.cc = this.cc + 1; - } - public String vroom(){ - String s = vStart(); - for(int i = 0; i < cc; i++){ - s = s + "o"; - } - return s + "m"; +class Car { + public int cc; + + public String vStart() { + return ""; + } + + public void rev() { + this.cc = this.cc + 1; + } + + public String vroom() { + String s = vStart(); + for (int i = 0; i < cc; i++) { + s = s + "o"; } + return s + "m"; + } } /* expected-direct-call-graph { diff --git a/main/codesig/test/cases/callgraph/complicated/4-classes-parent/src/Hello.java b/main/codesig/test/cases/callgraph/complicated/4-classes-parent/src/Hello.java index 8256edda5cf..6b746637636 100644 --- a/main/codesig/test/cases/callgraph/complicated/4-classes-parent/src/Hello.java +++ b/main/codesig/test/cases/callgraph/complicated/4-classes-parent/src/Hello.java @@ -1,36 +1,37 @@ package hello; -// Taken from https://github.com/lihaoyi/Metascala/blob/76dfbfa18484b9ee39bd09453328ea1081fcab6b/src/test/java/metascala/features/classes/Inheritance.java - - -import java.util.HashMap; -import java.util.Map; -import java.util.Vector; +// Taken from +// https://github.com/lihaoyi/Metascala/blob/76dfbfa18484b9ee39bd09453328ea1081fcab6b/src/test/java/metascala/features/classes/Inheritance.java public class Hello { - public static int staticInheritance(){ - int a = Parent.x; - Child1.x = 100; - return a + Child1.x + Child2.x; - } + public static int staticInheritance() { + int a = Parent.x; + Child1.x = 100; + return a + Child1.x + Child2.x; + } } -interface ParentInterface{ - public static int x = 30; + +interface ParentInterface { + public static int x = 30; } -class Parent{ - public static int x = 10; + +class Parent { + public static int x = 10; } -class Child1 extends Parent{ - public static int get(){ - return x; - } + +class Child1 extends Parent { + public static int get() { + return x; + } } -class Cowc{} -class Child2 extends Cowc implements ParentInterface{ - public static int get(){ - return x; - } + +class Cowc {} + +class Child2 extends Cowc implements ParentInterface { + public static int get() { + return x; + } } /* expected-direct-call-graph { diff --git a/main/codesig/test/cases/callgraph/complicated/5-classes-sheep/src/Hello.java b/main/codesig/test/cases/callgraph/complicated/5-classes-sheep/src/Hello.java index ae3044585aa..286d75fcf92 100644 --- a/main/codesig/test/cases/callgraph/complicated/5-classes-sheep/src/Hello.java +++ b/main/codesig/test/cases/callgraph/complicated/5-classes-sheep/src/Hello.java @@ -1,23 +1,25 @@ package hello; -// Taken from https://github.com/lihaoyi/Metascala/blob/76dfbfa18484b9ee39bd09453328ea1081fcab6b/src/test/java/metascala/features/classes/Inheritance.java +// Taken from +// https://github.com/lihaoyi/Metascala/blob/76dfbfa18484b9ee39bd09453328ea1081fcab6b/src/test/java/metascala/features/classes/Inheritance.java public class Hello { - public static String implement(int n){ - Baas b = new Sheep(); - return b.baa(n); - } + public static String implement(int n) { + Baas b = new Sheep(); + return b.baa(n); + } } -class Sheep implements Baas{ - public String baa(int n){ - String s = "b"; - for(int i = 0; i < n; i++) s = s + "a"; - return s; - } +class Sheep implements Baas { + public String baa(int n) { + String s = "b"; + for (int i = 0; i < n; i++) s = s + "a"; + return s; + } } -interface Baas{ - public String baa(int n); + +interface Baas { + public String baa(int n); } // Baas a single-abstract-method interface and so is approximated as diff --git a/main/codesig/test/cases/callgraph/external/1-sam-interface-method/src/Hello.java b/main/codesig/test/cases/callgraph/external/1-sam-interface-method/src/Hello.java index 55778d222d8..4c779e7e611 100644 --- a/main/codesig/test/cases/callgraph/external/1-sam-interface-method/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/1-sam-interface-method/src/Hello.java @@ -1,21 +1,26 @@ package hello; import java.util.function.IntSupplier; -import java.util.function.DoubleSupplier; -class Foo implements IntSupplier{ - public int getAsInt(){ return 1; } - public int uncalled(){ return 2; } +class Foo implements IntSupplier { + public int getAsInt() { + return 1; + } + + public int uncalled() { + return 2; + } } -public class Hello{ - public static int main(){ - IntSupplier is = new Foo(); - return bar(is); - } - public static int bar(IntSupplier is) { - return is.getAsInt(); - } +public class Hello { + public static int main() { + IntSupplier is = new Foo(); + return bar(is); + } + + public static int bar(IntSupplier is) { + return is.getAsInt(); + } } // Since `Foo` is a SAM implementation, we treat its SAM method `getAsInt` @@ -45,4 +50,3 @@ public static int bar(IntSupplier is) { ] } */ - diff --git a/main/codesig/test/cases/callgraph/external/10-abstract-class-indirect-inheritance-not-called/src/Hello.java b/main/codesig/test/cases/callgraph/external/10-abstract-class-indirect-inheritance-not-called/src/Hello.java index 122c5cd0496..e04a1e3c93b 100644 --- a/main/codesig/test/cases/callgraph/external/10-abstract-class-indirect-inheritance-not-called/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/10-abstract-class-indirect-inheritance-not-called/src/Hello.java @@ -9,28 +9,30 @@ // defined on `Object`. That means we can be confident that `toString` does not // call our own implementation `Foo#read` // -class Foo extends java.io.ByteArrayInputStream{ - public Foo() throws java.io.IOException{ - super(new byte[]{}); - } +class Foo extends java.io.ByteArrayInputStream { + public Foo() throws java.io.IOException { + super(new byte[] {}); + } - public int read(){ - return readSpecial(); - } - public int readSpecial(){ - return 1337; - } -} -public class Hello{ - public static int main() throws java.io.IOException{ - java.io.InputStream is = new Foo(); - return bar(is); - } - public static int bar(java.io.InputStream is){ - return is.toString().length(); - } + public int read() { + return readSpecial(); + } + + public int readSpecial() { + return 1337; + } } +public class Hello { + public static int main() throws java.io.IOException { + java.io.InputStream is = new Foo(); + return bar(is); + } + + public static int bar(java.io.InputStream is) { + return is.toString().length(); + } +} /* expected-direct-call-graph { diff --git a/main/codesig/test/cases/callgraph/external/11-abstract-class-indirect-delegation-called/src/Hello.java b/main/codesig/test/cases/callgraph/external/11-abstract-class-indirect-delegation-called/src/Hello.java index b772b5b225d..03c94ea3704 100644 --- a/main/codesig/test/cases/callgraph/external/11-abstract-class-indirect-delegation-called/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/11-abstract-class-indirect-delegation-called/src/Hello.java @@ -6,30 +6,31 @@ // // Make sure we treat this conservatively and mark all methods that are present // on the type of the third-party code parameter as called -class Foo extends java.io.ByteArrayInputStream{ - public Foo() throws java.io.IOException{ - super(new byte[]{}); - } +class Foo extends java.io.ByteArrayInputStream { + public Foo() throws java.io.IOException { + super(new byte[] {}); + } - public int read(){ - return readSpecial(); - } - public int readSpecial(){ - return 1337; - } + public int read() { + return readSpecial(); + } - public int uncalled(){ - return 1337; - } + public int readSpecial() { + return 1337; + } + + public int uncalled() { + return 1337; + } } -public class Hello{ - public static int main() throws java.io.IOException{ - java.io.BufferedReader is = - new java.io.BufferedReader(new java.io.InputStreamReader(new Foo())); +public class Hello { + public static int main() throws java.io.IOException { + java.io.BufferedReader is = + new java.io.BufferedReader(new java.io.InputStreamReader(new Foo())); - return is.readLine().length(); - } + return is.readLine().length(); + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/external/12-abstract-class-indirect-delegation-uncalled/src/Hello.java b/main/codesig/test/cases/callgraph/external/12-abstract-class-indirect-delegation-uncalled/src/Hello.java index 1e2ae6fa502..05344040fac 100644 --- a/main/codesig/test/cases/callgraph/external/12-abstract-class-indirect-delegation-uncalled/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/12-abstract-class-indirect-delegation-uncalled/src/Hello.java @@ -9,22 +9,22 @@ // analyze the call-graph of external code so we have to assume every method // that is present on the type of the parameter we pass to the // `java.io.OutputStreamWriter` constructor may get called -class Bar extends java.io.ByteArrayOutputStream{ - public synchronized void write(byte b[], int off, int len) { - // do nothing - } +class Bar extends java.io.ByteArrayOutputStream { + public synchronized void write(byte b[], int off, int len) { + // do nothing + } - public int uncalled(){ - return 1337; - } + public int uncalled() { + return 1337; + } } -public class Hello{ - public static int main() throws java.io.IOException{ - java.io.OutputStreamWriter os = new java.io.OutputStreamWriter(new Bar()); +public class Hello { + public static int main() throws java.io.IOException { + java.io.OutputStreamWriter os = new java.io.OutputStreamWriter(new Bar()); - return 1234; - } + return 1234; + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/external/13-interface-two-implementations-interface-call/src/Hello.java b/main/codesig/test/cases/callgraph/external/13-interface-two-implementations-interface-call/src/Hello.java index d7ec222484c..fa3d1c6b14d 100644 --- a/main/codesig/test/cases/callgraph/external/13-interface-two-implementations-interface-call/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/13-interface-two-implementations-interface-call/src/Hello.java @@ -1,30 +1,39 @@ package hello; - - // When an external interface is implemented multiple times, only instantiated // once, but we only make the virtual call through the interface. We cannot be // sure we are only calling that specific implementation and not any of the // other implementations, since we do not do dataflow analysis -class Foo implements java.util.Enumeration{ - public boolean hasMoreElements() {return false;} - public Integer nextElement() {return null;} +class Foo implements java.util.Enumeration { + public boolean hasMoreElements() { + return false; + } + + public Integer nextElement() { + return null; + } } -class Bar implements java.util.Enumeration{ - public boolean hasMoreElements() {return true;} - public Integer nextElement() {return 123;} +class Bar implements java.util.Enumeration { + public boolean hasMoreElements() { + return true; + } + + public Integer nextElement() { + return 123; + } } -public class Hello{ - public static int main(){ - java.util.Enumeration is = new Foo(); - return bar(is); - } - public static int bar(java.util.Enumeration is) { - return is.nextElement(); - } +public class Hello { + public static int main() { + java.util.Enumeration is = new Foo(); + return bar(is); + } + + public static int bar(java.util.Enumeration is) { + return is.nextElement(); + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/external/14-interface-two-implementations-direct-call/src/Hello.java b/main/codesig/test/cases/callgraph/external/14-interface-two-implementations-direct-call/src/Hello.java index 4c0fb27daf1..9407946ed84 100644 --- a/main/codesig/test/cases/callgraph/external/14-interface-two-implementations-direct-call/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/14-interface-two-implementations-direct-call/src/Hello.java @@ -1,32 +1,39 @@ package hello; -import java.util.function.IntSupplier; -import java.util.function.DoubleSupplier; - // When an external interface is implemented multiple times, but when we call // its method we call it on a specific subclass, we can be sure we are only // calling that specific implementation and not any of the other // implementations for the interface -class Foo implements java.util.Enumeration{ - public boolean hasMoreElements() {return false;} - public Integer nextElement() {return null;} +class Foo implements java.util.Enumeration { + public boolean hasMoreElements() { + return false; + } + + public Integer nextElement() { + return null; + } } -class Bar implements java.util.Enumeration{ - public boolean hasMoreElements() {return true;} - public Integer nextElement() {return 123;} +class Bar implements java.util.Enumeration { + public boolean hasMoreElements() { + return true; + } + + public Integer nextElement() { + return 123; + } } +public class Hello { + public static int main() { + Foo is = new Foo(); + return bar(is); + } -public class Hello{ - public static int main(){ - Foo is = new Foo(); - return bar(is); - } - public static int bar(Foo is) { - return is.nextElement(); - } + public static int bar(Foo is) { + return is.nextElement(); + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/external/15-static-method/src/Hello.java b/main/codesig/test/cases/callgraph/external/15-static-method/src/Hello.java index c0ef66ffb77..222ae232a48 100644 --- a/main/codesig/test/cases/callgraph/external/15-static-method/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/15-static-method/src/Hello.java @@ -3,17 +3,20 @@ // Make sure that we create external call graph edges when calling external // static methods too. class Foo { - public String toString() { return "Foo"; } + public String toString() { + return "Foo"; + } } -public class Hello{ - public static void main(){ - Foo foo = new Foo(); - bar(foo); - } - public static void bar(Foo foo) { - System.identityHashCode(foo); - } +public class Hello { + public static void main() { + Foo foo = new Foo(); + bar(foo); + } + + public static void bar(Foo foo) { + System.identityHashCode(foo); + } } // In this case, `bar` calling `System.identityHashCode(Object)` should be diff --git a/main/codesig/test/cases/callgraph/external/16-external-method-edge-to-inherited-method-override/external/src/External.java b/main/codesig/test/cases/callgraph/external/16-external-method-edge-to-inherited-method-override/external/src/External.java index d4c0cbeb2f8..84c7d362040 100644 --- a/main/codesig/test/cases/callgraph/external/16-external-method-edge-to-inherited-method-override/external/src/External.java +++ b/main/codesig/test/cases/callgraph/external/16-external-method-edge-to-inherited-method-override/external/src/External.java @@ -1,16 +1,21 @@ package hello; -interface Grandparent{ - default void doGrandThingConcrete(){ - System.out.println("Running doGrandThingConcrete"); - } - void doGrandThing(); - void otherNonSamMethod(); +interface Grandparent { + default void doGrandThingConcrete() { + System.out.println("Running doGrandThingConcrete"); + } + + void doGrandThing(); + + void otherNonSamMethod(); } -interface Parent extends Grandparent{ - default void doParentThingConcrete(){ - System.out.println("Running doGrandThingConcrete"); - } - void doParentThing(); - void otherNonSamMethod(); + +interface Parent extends Grandparent { + default void doParentThingConcrete() { + System.out.println("Running doGrandThingConcrete"); + } + + void doParentThing(); + + void otherNonSamMethod(); } diff --git a/main/codesig/test/cases/callgraph/external/16-external-method-edge-to-inherited-method-override/src/Hello.java b/main/codesig/test/cases/callgraph/external/16-external-method-edge-to-inherited-method-override/src/Hello.java index 97bc3d1f79a..b74d771630f 100644 --- a/main/codesig/test/cases/callgraph/external/16-external-method-edge-to-inherited-method-override/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/16-external-method-edge-to-inherited-method-override/src/Hello.java @@ -4,25 +4,38 @@ // call graph edges to local methods that are defined on the external class // that we called the external method on. -class Foo implements Parent{ - public void doParentThing() { System.out.println("Running doThing"); } - public void doGrandThing() { System.out.println("Running doGrandThing"); } - public void otherNonSamMethod() { System.out.println("Running otherNonSamMethod"); } - public void notDoneThing() { System.out.println("Running notDoneThing"); } +class Foo implements Parent { + public void doParentThing() { + System.out.println("Running doThing"); + } + + public void doGrandThing() { + System.out.println("Running doGrandThing"); + } + + public void otherNonSamMethod() { + System.out.println("Running otherNonSamMethod"); + } + + public void notDoneThing() { + System.out.println("Running notDoneThing"); + } } -public class Hello{ - public static void main(){ - Foo foo = new Foo(); - bar(foo); - qux(foo); - } - public static void bar(Foo foo) { - foo.doGrandThingConcrete(); - } - public static void qux(Foo foo) { - foo.doParentThingConcrete(); - } +public class Hello { + public static void main() { + Foo foo = new Foo(); + bar(foo); + qux(foo); + } + + public static void bar(Foo foo) { + foo.doGrandThingConcrete(); + } + + public static void qux(Foo foo) { + foo.doParentThingConcrete(); + } } // In this case, `bar` calls `doGrandThingConcrete` which is defined externally diff --git a/main/codesig/test/cases/callgraph/external/17-jcanvas/src/Hello.java b/main/codesig/test/cases/callgraph/external/17-jcanvas/src/Hello.java index ff35b6c4435..453e9b3341a 100644 --- a/main/codesig/test/cases/callgraph/external/17-jcanvas/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/17-jcanvas/src/Hello.java @@ -1,29 +1,28 @@ package hello; import java.awt.*; -import javax.swing.*; import java.awt.image.*; +import javax.swing.*; -class JCanvas extends JPanel{ - private BufferedImage Picture; - Graphics2D Painter; - private Graphics Paint; - - public JCanvas(){ - Picture = new BufferedImage(800, 600, BufferedImage.TYPE_BYTE_INDEXED); - Painter = Picture.createGraphics(); - } +class JCanvas extends JPanel { + private BufferedImage Picture; + Graphics2D Painter; + private Graphics Paint; + public JCanvas() { + Picture = new BufferedImage(800, 600, BufferedImage.TYPE_BYTE_INDEXED); + Painter = Picture.createGraphics(); + } - public void paintComponent(Graphics g){ - try{ + public void paintComponent(Graphics g) { + try { - Paint = this.getGraphics(); - g.drawImage(Picture, 0, 0, null); + Paint = this.getGraphics(); + g.drawImage(Picture, 0, 0, null); - }catch(NullPointerException e){ - } + } catch (NullPointerException e) { } + } } // Note that `JCanvas#` has an edge to `JCanvas#paintComponent` because diff --git a/main/codesig/test/cases/callgraph/external/18-external-method-calls-parent-method/external/src/External.java b/main/codesig/test/cases/callgraph/external/18-external-method-calls-parent-method/external/src/External.java index 15e44de0415..6e1455b8456 100644 --- a/main/codesig/test/cases/callgraph/external/18-external-method-calls-parent-method/external/src/External.java +++ b/main/codesig/test/cases/callgraph/external/18-external-method-calls-parent-method/external/src/External.java @@ -1,14 +1,15 @@ package hello; -abstract class Grandparent{ - public void doGrandThingConcrete(){ - doGrandThingAbstract(); - } - abstract public void doGrandThingAbstract(); +abstract class Grandparent { + public void doGrandThingConcrete() { + doGrandThingAbstract(); + } + + public abstract void doGrandThingAbstract(); } -abstract class Parent extends Grandparent{ - public void doParentThing(){ - doGrandThingConcrete(); - } +abstract class Parent extends Grandparent { + public void doParentThing() { + doGrandThingConcrete(); + } } diff --git a/main/codesig/test/cases/callgraph/external/18-external-method-calls-parent-method/src/Hello.java b/main/codesig/test/cases/callgraph/external/18-external-method-calls-parent-method/src/Hello.java index e7dc4027c8d..c9343034db5 100644 --- a/main/codesig/test/cases/callgraph/external/18-external-method-calls-parent-method/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/18-external-method-calls-parent-method/src/Hello.java @@ -1,16 +1,19 @@ package hello; -class Foo extends Parent{ - void called(){ System.out.println("called"); } - public void doGrandThingAbstract() { - called(); - } +class Foo extends Parent { + void called() { + System.out.println("called"); + } + + public void doGrandThingAbstract() { + called(); + } } -public class Hello{ - public static void main(){ - new Foo().doParentThing(); - } +public class Hello { + public static void main() { + new Foo().doParentThing(); + } } // that it could call either of `doGrandThing` or `doParentThing` diff --git a/main/codesig/test/cases/callgraph/external/2-multi-interface-method/src/Hello.java b/main/codesig/test/cases/callgraph/external/2-multi-interface-method/src/Hello.java index 7e014511c37..77d432d7cbe 100644 --- a/main/codesig/test/cases/callgraph/external/2-multi-interface-method/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/2-multi-interface-method/src/Hello.java @@ -1,22 +1,30 @@ package hello; - // We instantiate this and call its method, so we record that in // the call graph. -class Foo implements java.util.Enumeration{ - public int uncalled(){ return 2; } - public boolean hasMoreElements() {return false;} - public Integer nextElement() {return null;} +class Foo implements java.util.Enumeration { + public int uncalled() { + return 2; + } + + public boolean hasMoreElements() { + return false; + } + + public Integer nextElement() { + return null; + } } -public class Hello{ - public static int main(){ - java.util.Enumeration is = new Foo(); - return bar(is); - } - public static int bar(java.util.Enumeration is) { - return is.nextElement(); - } +public class Hello { + public static int main() { + java.util.Enumeration is = new Foo(); + return bar(is); + } + + public static int bar(java.util.Enumeration is) { + return is.nextElement(); + } } // `Foo#` does not end up calling `IntSupplier#` to diff --git a/main/codesig/test/cases/callgraph/external/3-sam-interface-never-instantiated/src/Hello.java b/main/codesig/test/cases/callgraph/external/3-sam-interface-never-instantiated/src/Hello.java index cd124da0e73..4a95b98a6f5 100644 --- a/main/codesig/test/cases/callgraph/external/3-sam-interface-never-instantiated/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/3-sam-interface-never-instantiated/src/Hello.java @@ -1,22 +1,24 @@ package hello; import java.util.function.IntSupplier; -import java.util.function.DoubleSupplier; -class Foo implements IntSupplier{ - public int getAsInt(){ return 1; } +class Foo implements IntSupplier { + public int getAsInt() { + return 1; + } } -class Bar implements IntSupplier{ - public int getAsInt(){ return 1; } +class Bar implements IntSupplier { + public int getAsInt() { + return 1; + } } - -public class Hello{ - public static int main(){ - IntSupplier is = new Foo(); - return is.getAsInt(); - } +public class Hello { + public static int main() { + IntSupplier is = new Foo(); + return is.getAsInt(); + } } // Because `Foo` and `Bar` are SAM implementations, we treat them as being diff --git a/main/codesig/test/cases/callgraph/external/4-multi-interface-never-instantiated/src/Hello.java b/main/codesig/test/cases/callgraph/external/4-multi-interface-never-instantiated/src/Hello.java index 6dfd3ae64ee..3a20a13493f 100644 --- a/main/codesig/test/cases/callgraph/external/4-multi-interface-never-instantiated/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/4-multi-interface-never-instantiated/src/Hello.java @@ -1,13 +1,15 @@ package hello; -import java.util.function.IntSupplier; -import java.util.function.DoubleSupplier; - // Simple case: we instantiate this and call its method, so we record that in // the call graph. -class Foo implements java.util.Enumeration{ - public boolean hasMoreElements() { return false; } - public Integer nextElement() { return null; } +class Foo implements java.util.Enumeration { + public boolean hasMoreElements() { + return false; + } + + public Integer nextElement() { + return null; + } } // We do not instantiate this, but it's a type we do call the method @@ -17,16 +19,20 @@ class Foo implements java.util.Enumeration{ // a possible dispatch target for `IntSupplier#getAsInt` and also record it in // the call graph class Bar extends Foo { - public boolean hasMoreElements() { return true; } - public Integer nextElement() { return 1; } -} + public boolean hasMoreElements() { + return true; + } + public Integer nextElement() { + return 1; + } +} -public class Hello{ - public static int main(){ - java.util.Enumeration is = new Foo(); - return is.nextElement(); - } +public class Hello { + public static int main() { + java.util.Enumeration is = new Foo(); + return is.nextElement(); + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/external/5-sam-interface-never-called/src/Hello.java b/main/codesig/test/cases/callgraph/external/5-sam-interface-never-called/src/Hello.java index 2d614c1a4b5..a66f643ccfa 100644 --- a/main/codesig/test/cases/callgraph/external/5-sam-interface-never-called/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/5-sam-interface-never-called/src/Hello.java @@ -1,19 +1,20 @@ package hello; -import java.util.function.IntSupplier; import java.util.function.DoubleSupplier; // We implement a method for an external interface we do not call anywhere. // // It should still appear as getting called by its method since it's a SAM -class Unused implements DoubleSupplier{ - public double getAsDouble(){ return 1.0; } +class Unused implements DoubleSupplier { + public double getAsDouble() { + return 1.0; + } } -public class Hello{ - public static int main(){ - return 123; - } +public class Hello { + public static int main() { + return 123; + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/external/6-multi-interface-never-called/src/Hello.java b/main/codesig/test/cases/callgraph/external/6-multi-interface-never-called/src/Hello.java index f072cf9a948..dfa126aa673 100644 --- a/main/codesig/test/cases/callgraph/external/6-multi-interface-never-called/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/6-multi-interface-never-called/src/Hello.java @@ -1,20 +1,22 @@ package hello; -import java.util.function.IntSupplier; -import java.util.function.DoubleSupplier; - // We implement a method for an external interface we do not call anywhere. // // This should not appear in the call graph -class Unused implements java.util.Enumeration{ - public boolean hasMoreElements() {return false;} - public Integer nextElement() {return null;} +class Unused implements java.util.Enumeration { + public boolean hasMoreElements() { + return false; + } + + public Integer nextElement() { + return null; + } } -public class Hello{ - public static int main(){ - return 123; - } +public class Hello { + public static int main() { + return 123; + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/external/7-sam-abstract-class-maybe-called/src/Hello.java b/main/codesig/test/cases/callgraph/external/7-sam-abstract-class-maybe-called/src/Hello.java index ea093491479..2224f6582fb 100644 --- a/main/codesig/test/cases/callgraph/external/7-sam-abstract-class-maybe-called/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/7-sam-abstract-class-maybe-called/src/Hello.java @@ -5,29 +5,30 @@ // implemented, but because this is a SAM method we instead consider it called // at `` time and not during the unknown external call. -class Bar extends java.io.InputStream{ - public synchronized int read() { - return called(); - } +class Bar extends java.io.InputStream { + public synchronized int read() { + return called(); + } - public int called(){ - return 1337; - } + public int called() { + return 1337; + } - public int uncalled(){ - return 1337; - } + public int uncalled() { + return 1337; + } } -public class Hello{ - public static int main() throws java.io.IOException{ - java.io.InputStream is = new Bar(); - return bar(is); - } - public static int bar(java.io.InputStream is) throws java.io.IOException{ - is.read(new byte[10], 0, 10); - return 1234; - } +public class Hello { + public static int main() throws java.io.IOException { + java.io.InputStream is = new Bar(); + return bar(is); + } + + public static int bar(java.io.InputStream is) throws java.io.IOException { + is.read(new byte[10], 0, 10); + return 1234; + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/external/8-multi-abstract-class-maybe-called/src/Hello.java b/main/codesig/test/cases/callgraph/external/8-multi-abstract-class-maybe-called/src/Hello.java index 99d4afb03ca..68552cf41b5 100644 --- a/main/codesig/test/cases/callgraph/external/8-multi-abstract-class-maybe-called/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/8-multi-abstract-class-maybe-called/src/Hello.java @@ -7,31 +7,32 @@ // have called any other method defined on the interface type, and so assume // that our implementation gets called indirectly -class Bar extends java.io.Reader{ - public synchronized int read(char[] cbuf, int off, int len) { - return called(); - } +class Bar extends java.io.Reader { + public synchronized int read(char[] cbuf, int off, int len) { + return called(); + } - public void close(){} + public void close() {} - public int called(){ - return 1337; - } + public int called() { + return 1337; + } - public int uncalled(){ - return 1337; - } + public int uncalled() { + return 1337; + } } -public class Hello{ - public static int main() throws java.io.IOException{ - java.io.Reader is = new Bar(); - return bar(is); - } - public static int bar(java.io.Reader is) throws java.io.IOException{ - is.read(new char[10], 0, 10); - return 1234; - } +public class Hello { + public static int main() throws java.io.IOException { + java.io.Reader is = new Bar(); + return bar(is); + } + + public static int bar(java.io.Reader is) throws java.io.IOException { + is.read(new char[10], 0, 10); + return 1234; + } } // Note that we mark `Bar#read` as called from `Bar#`. This is because diff --git a/main/codesig/test/cases/callgraph/external/9-abstract-class-indirect-inheritance-called/src/Hello.java b/main/codesig/test/cases/callgraph/external/9-abstract-class-indirect-inheritance-called/src/Hello.java index 39ccf89a190..d9a14c4098c 100644 --- a/main/codesig/test/cases/callgraph/external/9-abstract-class-indirect-inheritance-called/src/Hello.java +++ b/main/codesig/test/cases/callgraph/external/9-abstract-class-indirect-inheritance-called/src/Hello.java @@ -5,26 +5,29 @@ // // Make sure we can resolve that and still record in the call graph that the // method is called -class Foo extends java.io.ByteArrayInputStream{ - public Foo() throws java.io.IOException{ - super(new byte[]{}); - } +class Foo extends java.io.ByteArrayInputStream { + public Foo() throws java.io.IOException { + super(new byte[] {}); + } - public int read(){ - return readSpecial(); - } - public int readSpecial(){ - return 1337; - } + public int read() { + return readSpecial(); + } + + public int readSpecial() { + return 1337; + } } -public class Hello{ - public static int main() throws java.io.IOException{ - java.io.InputStream is = new Foo(); - return bar(is); - } - public static int bar(java.io.InputStream is) throws java.io.IOException{ - return is.read(); - } + +public class Hello { + public static int main() throws java.io.IOException { + java.io.InputStream is = new Foo(); + return bar(is); + } + + public static int bar(java.io.InputStream is) throws java.io.IOException { + return is.read(); + } } /* expected-direct-call-graph diff --git a/main/codesig/test/cases/callgraph/realistic/1-tetris/src/Tetris.java b/main/codesig/test/cases/callgraph/realistic/1-tetris/src/Tetris.java index 996671a3861..84c08fb072d 100644 --- a/main/codesig/test/cases/callgraph/realistic/1-tetris/src/Tetris.java +++ b/main/codesig/test/cases/callgraph/realistic/1-tetris/src/Tetris.java @@ -1,485 +1,541 @@ -import javax.swing.*; +import java.awt.*; import java.awt.event.*; -import java.awt.image.*; import java.awt.geom.*; -import java.awt.*; -import java.util.Vector; - -class GUI{ - static int X = 100; - static int Y = 100; - static int Speed = 100; - static int randomInt(int x, int y){ - return x + y; - } - static void close(String s, String s2){ - throw new RuntimeException(s); - } +import java.awt.image.*; +import javax.swing.*; + +class GUI { + static int X = 100; + static int Y = 100; + static int Speed = 100; + + static int randomInt(int x, int y) { + return x + y; + } + + static void close(String s, String s2) { + throw new RuntimeException(s); + } } -class Tetris extends JFrame implements KeyListener, ActionListener{ - - final int X = GUI.X; - final int Y = GUI.Y; - final int BlockWidth = 20; - final int Width = 13; - final int Height = Y / BlockWidth; - final int LeftBorder = (X - BlockWidth * Width) / 2; - final int ShapeSize = 7; - int SoundCounter = 0; - Position[][] Map = new Position[Width][Height]; - Timer Stopwatch = new Timer((int)(GUI.Speed * 15), this); - Background Area; - int Counter = 0; - int LinesCleared = 0; -// LoopingMidi Music = new LoopingMidi("Tetris.mid", 0); - Timer MoveTimer = new Timer((int)(GUI.Speed * 60), new ActionListener(){ - public void actionPerformed(ActionEvent evt) { - try{ - if(Left == true){ - MovingBlock.move(-1, 0, true); - } - if(Right == true){ - MovingBlock.move(1, 0, true); - } - if(Down == true){ - MovingBlock.move(0, 1, true); - } - }catch(NullPointerException e){} +class Tetris extends JFrame implements KeyListener, ActionListener { + + final int X = GUI.X; + final int Y = GUI.Y; + final int BlockWidth = 20; + final int Width = 13; + final int Height = Y / BlockWidth; + final int LeftBorder = (X - BlockWidth * Width) / 2; + final int ShapeSize = 7; + int SoundCounter = 0; + Position[][] Map = new Position[Width][Height]; + Timer Stopwatch = new Timer((int) (GUI.Speed * 15), this); + Background Area; + int Counter = 0; + int LinesCleared = 0; + // LoopingMidi Music = new LoopingMidi("Tetris.mid", 0); + Timer MoveTimer = new Timer((int) (GUI.Speed * 60), new ActionListener() { + public void actionPerformed(ActionEvent evt) { + try { + if (Left == true) { + MovingBlock.move(-1, 0, true); + } + if (Right == true) { + MovingBlock.move(1, 0, true); } - }); - public void moveSound(){ - if(SoundCounter == 0){ -// GUI.playSound(true, "MOVPIECE.wav", 0, 2); -// GUI.playSound(true, "MOVPIECE.wav", 0, 2); - SoundCounter = 3; + if (Down == true) { + MovingBlock.move(0, 1, true); } + } catch (NullPointerException e) { + } } - public void printSquare(int POSX, int POSY, Color Tint){ - int INTX = LeftBorder + POSX * BlockWidth; - int INTY = POSY * BlockWidth; - Area.Painter.setColor(new Color(Tint.getRed() / 2, Tint.getGreen() / 2, Tint.getBlue() / 2)); - Area.Painter.fillRect(INTX, INTY, BlockWidth, BlockWidth); - Area.Painter.setColor(Tint); - Area.Painter.drawRect(INTX + 1, INTY + 1, BlockWidth - 2, BlockWidth - 2); + }); + + public void moveSound() { + if (SoundCounter == 0) { + // GUI.playSound(true, "MOVPIECE.wav", 0, 2); + // GUI.playSound(true, "MOVPIECE.wav", 0, 2); + SoundCounter = 3; } - class Position{ - Color Tint; - boolean Filled; - boolean Final; - public Position(){ - Tint = Color.black; - Filled = false; - Final = false; - } - public void setPosition(Color tTint, boolean tFilled, boolean tFinal){ - Tint = tTint; - Filled = tFilled; - Final = tFinal; - } + } + + public void printSquare(int POSX, int POSY, Color Tint) { + int INTX = LeftBorder + POSX * BlockWidth; + int INTY = POSY * BlockWidth; + Area.Painter.setColor(new Color(Tint.getRed() / 2, Tint.getGreen() / 2, Tint.getBlue() / 2)); + Area.Painter.fillRect(INTX, INTY, BlockWidth, BlockWidth); + Area.Painter.setColor(Tint); + Area.Painter.drawRect(INTX + 1, INTY + 1, BlockWidth - 2, BlockWidth - 2); + } + + class Position { + Color Tint; + boolean Filled; + boolean Final; + + public Position() { + Tint = Color.black; + Filled = false; + Final = false; } - class Block{ - int[][] Shape; - int Rotation; - int POSY; - int POSX; - int INTX = 0; - int INTY = 0; - int Direction = 2; - boolean Rotateable; - Color Tint = new Color(0); - public void imprint(){ - for(int i = 0; i < ShapeSize; i++){ - for(int j = 0; j < ShapeSize; j++){ - if(Shape[i][j] == 1 || Shape[i][j] == 2){ - if(j - INTY + POSY < 1){ - Stopwatch.stop(); - GUI.close("You lose", ""); - return; - } - Map[i - INTX + POSX][j - INTY + POSY].setPosition(Tint, true, true); - - } - } - } - checkLines(); - } - public void rotate(int Rotation, boolean Primary){ - if(Primary == true){ - this.print(Color.black); - } - moveSound(); - int[][] Temp = new int[ShapeSize][ShapeSize]; - for(int i = 0; i < ShapeSize; i++){ - for(int j = 0; j < ShapeSize; j++){ - if(Shape[i][j] == 1 || Shape[i][j] == 2){ - int TEMPX = i - INTX; - int TEMPY = j - INTY; - if(Rotation == 1){ - Temp[-TEMPY + INTX][TEMPX + INTY] = Shape[i][j]; - }else{ - Temp[TEMPY + INTX][-TEMPX + INTY] = Shape[i][j]; - } - } - } - } - Shape = Temp; - if(checkOverlap() && (Primary == true)){ - rotate(-Rotation, false); - } - if(Primary == true){ - this.print(Tint); + public void setPosition(Color tTint, boolean tFilled, boolean tFinal) { + Tint = tTint; + Filled = tFilled; + Final = tFinal; + } + } + + class Block { + int[][] Shape; + int Rotation; + int POSY; + int POSX; + int INTX = 0; + int INTY = 0; + int Direction = 2; + boolean Rotateable; + Color Tint = new Color(0); + + public void imprint() { + for (int i = 0; i < ShapeSize; i++) { + for (int j = 0; j < ShapeSize; j++) { + if (Shape[i][j] == 1 || Shape[i][j] == 2) { + if (j - INTY + POSY < 1) { + Stopwatch.stop(); + GUI.close("You lose", ""); + return; } + Map[i - INTX + POSX][j - INTY + POSY].setPosition(Tint, true, true); + } } - public boolean checkOverlap(){ - for(int i = 0; i < ShapeSize; i++){ - for(int j = 0; j < ShapeSize; j++){ - if(Shape[i][j] == 1 || Shape[i][j] == 2){ - try{ - if(Map[i - INTX + POSX][j - INTY + POSY].Filled == true){ - return true; - } - }catch(ArrayIndexOutOfBoundsException e){return true;} - } - } + } + + checkLines(); + } + + public void rotate(int Rotation, boolean Primary) { + if (Primary == true) { + this.print(Color.black); + } + moveSound(); + int[][] Temp = new int[ShapeSize][ShapeSize]; + for (int i = 0; i < ShapeSize; i++) { + for (int j = 0; j < ShapeSize; j++) { + if (Shape[i][j] == 1 || Shape[i][j] == 2) { + int TEMPX = i - INTX; + int TEMPY = j - INTY; + if (Rotation == 1) { + Temp[-TEMPY + INTX][TEMPX + INTY] = Shape[i][j]; + } else { + Temp[TEMPY + INTX][-TEMPX + INTY] = Shape[i][j]; } - return false; + } } - public Block(int tShape){ - POSX = Map.length / 2; - POSY = 1; - - switch(tShape){ - case 1:{int[][] Temp = {{0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 1, 0, 0, 0}, - {0, 0, 1, 2, 1, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}}; - Shape = Temp; - Rotateable = true; - Tint = Color.red; - break;} - case 2:{int[][] Temp = {{0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 1, 1, 0, 0}, - {0, 0, 0, 2, 0, 0, 0}, - {0, 0, 0, 1, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}}; - Shape = Temp; - Rotateable = true; - Tint = Color.blue; - break;} - case 3:{int[][] Temp = {{0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 1, 1, 0, 0, 0}, - {0, 0, 0, 2, 0, 0, 0}, - {0, 0, 0, 1, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}}; - Shape = Temp; - Rotateable = true; - Tint = Color.green; - break;} - case 4:{int[][] Temp = {{0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 1, 0, 0, 0}, - {0, 0, 0, 2, 0, 0, 0}, - {0, 0, 0, 1, 0, 0, 0}, - {0, 0, 0, 1, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}}; - Shape = Temp; - Rotateable = true; - Tint = Color.yellow; - break;} - case 5:{int[][] Temp = {{0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 1, 1, 0, 0, 0}, - {0, 0, 1, 2, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}}; - Shape = Temp; - Rotateable = false; - Tint = Color.white; - break;} - case 6:{int[][] Temp = {{0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 1, 1, 0, 0, 0}, - {0, 0, 0, 2, 1, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}}; - Shape = Temp; - Rotateable = true; - Tint = Color.magenta; - break;} - case 7:{int[][] Temp = {{0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 1, 1, 0, 0}, - {0, 0, 1, 2, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}}; - Shape = Temp; - Rotateable = true; - Tint = Color.cyan; - break;} - } - for(int i = 0; i < ShapeSize; i++){ - for(int j = 0; j < ShapeSize; j++){ - if(Shape[i][j] == 2){ - INTX = i; - INTY = j; - } - } + } + Shape = Temp; + if (checkOverlap() && (Primary == true)) { + rotate(-Rotation, false); + } + if (Primary == true) { + this.print(Tint); + } + } + + public boolean checkOverlap() { + for (int i = 0; i < ShapeSize; i++) { + for (int j = 0; j < ShapeSize; j++) { + if (Shape[i][j] == 1 || Shape[i][j] == 2) { + try { + if (Map[i - INTX + POSX][j - INTY + POSY].Filled == true) { + return true; + } + } catch (ArrayIndexOutOfBoundsException e) { + return true; } + } } - public void print(Color Tint){ - - for(int i = 0; i < ShapeSize; i++){ - for(int j = 0; j < ShapeSize; j++){ - if(Shape[i][j] == 1 || Shape[i][j] == 2){ - printSquare(i - INTX + POSX, j - INTY + POSY, Tint); - } - } - } + } + return false; + } + public Block(int tShape) { + POSX = Map.length / 2; + POSY = 1; + + switch (tShape) { + case 1: { + int[][] Temp = { + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 1, 0, 0, 0}, + {0, 0, 1, 2, 1, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0} + }; + Shape = Temp; + Rotateable = true; + Tint = Color.red; + break; } - public void move(int MoveX, int MoveY, boolean Manuel){ - boolean BOOLA = false; - print(Color.black); - POSY = POSY + MoveY; - POSX = POSX + MoveX; - if(Manuel == true){ - moveSound(); - } - if(checkOverlap() == true){ - POSY = POSY - MoveY; - POSX = POSX - MoveX; - } - - print(Tint); + case 2: { + int[][] Temp = { + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 1, 1, 0, 0}, + {0, 0, 0, 2, 0, 0, 0}, + {0, 0, 0, 1, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0} + }; + Shape = Temp; + Rotateable = true; + Tint = Color.blue; + break; } - public boolean checkCollision(){ - for(int i = 0; i < ShapeSize; i++){ - for(int j = 0; j < ShapeSize; j++){ - if(Shape[i][j] == 1 || Shape[i][j] == 2){ - try{ - if((Shape[i][j + 1] != 1) && (Map[i - INTX + POSX][j - INTY + POSY + 1].Filled == true)){ - return true; - } - }catch(ArrayIndexOutOfBoundsException e){return true; - }//catch(NullPointerException f){} - } - } - } - return false; + case 3: { + int[][] Temp = { + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 1, 1, 0, 0, 0}, + {0, 0, 0, 2, 0, 0, 0}, + {0, 0, 0, 1, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0} + }; + Shape = Temp; + Rotateable = true; + Tint = Color.green; + break; } - - } - Block MovingBlock; - Block NextBlock; - int Speed = 0; - boolean Left; - boolean Right; - boolean Down; - public void initMap(){ - for(int i = 0; i < Map.length; i++){ - for(int j = 0; j < Map[i].length; j++){ - Map[i][j] = new Position(); - } + case 4: { + int[][] Temp = { + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 1, 0, 0, 0}, + {0, 0, 0, 2, 0, 0, 0}, + {0, 0, 0, 1, 0, 0, 0}, + {0, 0, 0, 1, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0} + }; + Shape = Temp; + Rotateable = true; + Tint = Color.yellow; + break; } - } - public boolean checkLine(int Line){ - for(int j = 0; j < Width; j++){ - if(Map[j][Line].Filled == false){ - return false; - } + case 5: { + int[][] Temp = { + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 1, 1, 0, 0, 0}, + {0, 0, 1, 2, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0} + }; + Shape = Temp; + Rotateable = false; + Tint = Color.white; + break; } - return true; - } - public void clearLine(int Line){ - for(int i = 0; i < Width; i++){ - Map[i][Line] = new Position(); + case 6: { + int[][] Temp = { + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 1, 1, 0, 0, 0}, + {0, 0, 0, 2, 1, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0} + }; + Shape = Temp; + Rotateable = true; + Tint = Color.magenta; + break; } - - LinesCleared = LinesCleared + 1; - - } - public void checkLines(){ - for(int i = 0; i < Height; i++){ - - - if(checkLine(i) == true){ - clearLine(i); - moveDown(i); - } + case 7: { + int[][] Temp = { + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 1, 1, 0, 0}, + {0, 0, 1, 2, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0} + }; + Shape = Temp; + Rotateable = true; + Tint = Color.cyan; + break; } - } - public void moveLine(int Line){ - for(int i = 0; i < Width; i++){ - try{ - Map[i][Line].setPosition(Map[i][Line - 1].Tint, Map[i][Line - 1].Filled, Map[i][Line - 1].Final); - Map[i][Line - 1] = new Position(); - printLine(Line - 1); - printLine(Line); - }catch(ArrayIndexOutOfBoundsException e){} + } + for (int i = 0; i < ShapeSize; i++) { + for (int j = 0; j < ShapeSize; j++) { + if (Shape[i][j] == 2) { + INTX = i; + INTY = j; + } } + } } - public void printLine(int Line){ - for(int i = 0; i < Width; i++){ - printSquare(i, Line, Map[i][Line].Tint); + + public void print(Color Tint) { + + for (int i = 0; i < ShapeSize; i++) { + for (int j = 0; j < ShapeSize; j++) { + if (Shape[i][j] == 1 || Shape[i][j] == 2) { + printSquare(i - INTX + POSX, j - INTY + POSY, Tint); + } } + } } - public void moveDown(int Level){ - for(int j = Level; j >= 0; j--){ - moveLine(j); - } + + public void move(int MoveX, int MoveY, boolean Manuel) { + boolean BOOLA = false; + print(Color.black); + POSY = POSY + MoveY; + POSX = POSX + MoveX; + if (Manuel == true) { + moveSound(); + } + if (checkOverlap() == true) { + POSY = POSY - MoveY; + POSX = POSX - MoveX; + } + + print(Tint); } - public void drawBorders(){ - Area.Painter.setColor(Color.white); - Area.Painter.drawRect(0, 0, LeftBorder - 1, Y); - Area.Painter.drawRect(X - LeftBorder + 1, 0, LeftBorder - 1, Y); - Area.Painter.drawRect(LeftBorder, Height * BlockWidth, X - 2 * LeftBorder, Y - Height * BlockWidth); + public boolean checkCollision() { + for (int i = 0; i < ShapeSize; i++) { + for (int j = 0; j < ShapeSize; j++) { + if (Shape[i][j] == 1 || Shape[i][j] == 2) { + try { + if ((Shape[i][j + 1] != 1) + && (Map[i - INTX + POSX][j - INTY + POSY + 1].Filled == true)) { + return true; + } + } catch (ArrayIndexOutOfBoundsException e) { + return true; + } // catch(NullPointerException f){} + } + } + } + return false; } - public void initSounds(){ -// GUI.playSound(false, "MOVPIECE.wav", 0, 2); + } + + Block MovingBlock; + Block NextBlock; + int Speed = 0; + boolean Left; + boolean Right; + boolean Down; + + public void initMap() { + for (int i = 0; i < Map.length; i++) { + for (int j = 0; j < Map[i].length; j++) { + Map[i][j] = new Position(); + } } + } - public Tetris(){ - - //BASIC INITIALIZATION - super("Window"); - this.setSize(X, Y); - this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - this.setResizable(false); - - //SET CONTENT PANE - Container contentArea = getContentPane(); - - //LAYOUT MANAGER - //ADD ITEMS TO CONTENT PANE - Area = new Background(); - initMap(); - drawBorders(); - initSounds(); -// Music.play('s'); - contentArea.add(Area); - MoveTimer.start(); - Stopwatch.start(); - this.addKeyListener(this); - - - //ADD CONTENT PANE AND PACK - this.setContentPane(contentArea); - this.show(); - //this.pack(); + public boolean checkLine(int Line) { + for (int j = 0; j < Width; j++) { + if (Map[j][Line].Filled == false) { + return false; + } } + return true; + } - //EVENT TRIGGERS - public void keyPressed(KeyEvent e){ - try{ - switch(e.getKeyCode()){ - case 32: if(MovingBlock.Rotateable)MovingBlock.rotate(1, true); ; break; - case 39: Right = true;/* MovingBlock.move(1, 0);*/ break; - case 37: Left = true;/* MovingBlock.move(-1, 0);*/ break; - case 40: Down = true;/* MovingBlock.move(0, 1);*/ break; - - } - }catch(NullPointerException u){} + public void clearLine(int Line) { + for (int i = 0; i < Width; i++) { + Map[i][Line] = new Position(); } - public void keyReleased(KeyEvent e){ - try{ - switch(e.getKeyCode()){ - case 39: Right = false; break; - case 37: Left = false; break; - case 40: Down = false; break; + LinesCleared = LinesCleared + 1; + } - } - }catch(NullPointerException u){} + public void checkLines() { + for (int i = 0; i < Height; i++) { + if (checkLine(i) == true) { + clearLine(i); + moveDown(i); + } } - - - public void keyTyped(KeyEvent e){ - - + } + + public void moveLine(int Line) { + for (int i = 0; i < Width; i++) { + try { + Map[i][Line].setPosition( + Map[i][Line - 1].Tint, Map[i][Line - 1].Filled, Map[i][Line - 1].Final); + Map[i][Line - 1] = new Position(); + printLine(Line - 1); + printLine(Line); + } catch (ArrayIndexOutOfBoundsException e) { + } } + } + public void printLine(int Line) { + for (int i = 0; i < Width; i++) { + printSquare(i, Line, Map[i][Line].Tint); + } + } + public void moveDown(int Level) { + for (int j = Level; j >= 0; j--) { + moveLine(j); + } + } + + public void drawBorders() { + + Area.Painter.setColor(Color.white); + Area.Painter.drawRect(0, 0, LeftBorder - 1, Y); + Area.Painter.drawRect(X - LeftBorder + 1, 0, LeftBorder - 1, Y); + Area.Painter.drawRect( + LeftBorder, Height * BlockWidth, X - 2 * LeftBorder, Y - Height * BlockWidth); + } + + public void initSounds() { + // GUI.playSound(false, "MOVPIECE.wav", 0, 2); + } + + public Tetris() { + + // BASIC INITIALIZATION + super("Window"); + this.setSize(X, Y); + this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + this.setResizable(false); + + // SET CONTENT PANE + Container contentArea = getContentPane(); + + // LAYOUT MANAGER + // ADD ITEMS TO CONTENT PANE + Area = new Background(); + initMap(); + drawBorders(); + initSounds(); + // Music.play('s'); + contentArea.add(Area); + MoveTimer.start(); + Stopwatch.start(); + this.addKeyListener(this); + + // ADD CONTENT PANE AND PACK + this.setContentPane(contentArea); + this.show(); + // this.pack(); + } + + // EVENT TRIGGERS + public void keyPressed(KeyEvent e) { + try { + switch (e.getKeyCode()) { + case 32: + if (MovingBlock.Rotateable) MovingBlock.rotate(1, true); + ; + break; + case 39: + Right = true; /* MovingBlock.move(1, 0);*/ + break; + case 37: + Left = true; /* MovingBlock.move(-1, 0);*/ + break; + case 40: + Down = true; /* MovingBlock.move(0, 1);*/ + break; + } + } catch (NullPointerException u) { + } + } + + public void keyReleased(KeyEvent e) { + try { + switch (e.getKeyCode()) { + case 39: + Right = false; + break; + case 37: + Left = false; + break; + case 40: + Down = false; + break; + } + } catch (NullPointerException u) { + } + } - public void actionPerformed(ActionEvent e){ - /* - try{ - if(loop.sequencer.isRunning() == false){ - loop.sequencer.start(); - } - }catch(Exception f){} - */ - SoundCounter = Math.max(SoundCounter - 1, 0); - if(NextBlock == null){ - NextBlock = new Block(GUI.randomInt(1, 7)); - } - if(MovingBlock == null){ - NextBlock.print(Color.black); - MovingBlock = NextBlock; - MovingBlock.POSX = Map.length / 2; - MovingBlock.POSY = 0; - NextBlock = new Block(GUI.randomInt(1, 7)); - NextBlock.POSY = 10; - NextBlock.POSX = 19; - NextBlock.print(NextBlock.Tint); - } - - - + public void keyTyped(KeyEvent e) {} - Counter = Counter + 1; - if(Counter % (20 - LinesCleared / 10) == 0){ - if(MovingBlock.checkCollision() == true){ - MovingBlock.imprint(); - MovingBlock = null; - }else{ - MovingBlock.move(0, 1, false); - } - - Counter = 0; + public void actionPerformed(ActionEvent e) { + /* + try{ + if(loop.sequencer.isRunning() == false){ + loop.sequencer.start(); } - - Area.paintComponent(this.getGraphics()); + }catch(Exception f){} + */ + SoundCounter = Math.max(SoundCounter - 1, 0); + if (NextBlock == null) { + NextBlock = new Block(GUI.randomInt(1, 7)); + } + if (MovingBlock == null) { + NextBlock.print(Color.black); + MovingBlock = NextBlock; + MovingBlock.POSX = Map.length / 2; + MovingBlock.POSY = 0; + NextBlock = new Block(GUI.randomInt(1, 7)); + NextBlock.POSY = 10; + NextBlock.POSX = 19; + NextBlock.print(NextBlock.Tint); } + Counter = Counter + 1; + if (Counter % (20 - LinesCleared / 10) == 0) { + if (MovingBlock.checkCollision() == true) { + MovingBlock.imprint(); + MovingBlock = null; + } else { + MovingBlock.move(0, 1, false); + } - - public void paint(){ - ((Graphics2D)this.getGraphics()).drawImage(Area.Picture, null, 0, 0); - + Counter = 0; } - class Background extends JPanel{ + Area.paintComponent(this.getGraphics()); + } - BufferedImage Picture = new BufferedImage(X, Y, BufferedImage.TYPE_USHORT_555_RGB); - Graphics Painter = Picture.getGraphics(); + public void paint() { + ((Graphics2D) this.getGraphics()).drawImage(Area.Picture, null, 0, 0); + } + class Background extends JPanel { - public void paintComponent(Graphics paint){ - try{ - Graphics2D Painter = Picture.createGraphics(); - Graphics2D Paint = (Graphics2D)(paint); - Area.Painter.setColor(Color.black); - Area.Painter.fillRect((int)(LeftBorder * 1.3 + BlockWidth * Width), 90, 125, 15); - Area.Painter.setColor(Color.white); - Area.Painter.drawString("Lines Cleared: " + LinesCleared, (int)(LeftBorder * 1.3 + BlockWidth * Width), 100); - Area.Painter.drawString("Next Block:", (int)(LeftBorder * 1.35 + BlockWidth * Width), 150); - Paint.drawImage(Picture, null, 0, 0); - }catch(NullPointerException e){} - } - } + BufferedImage Picture = new BufferedImage(X, Y, BufferedImage.TYPE_USHORT_555_RGB); + Graphics Painter = Picture.getGraphics(); + public void paintComponent(Graphics paint) { + try { + Graphics2D Painter = Picture.createGraphics(); + Graphics2D Paint = (Graphics2D) (paint); + Area.Painter.setColor(Color.black); + Area.Painter.fillRect((int) (LeftBorder * 1.3 + BlockWidth * Width), 90, 125, 15); + Area.Painter.setColor(Color.white); + Area.Painter.drawString( + "Lines Cleared: " + LinesCleared, (int) (LeftBorder * 1.3 + BlockWidth * Width), 100); + Area.Painter.drawString("Next Block:", (int) (LeftBorder * 1.35 + BlockWidth * Width), 150); + Paint.drawImage(Picture, null, 0, 0); + } catch (NullPointerException e) { + } + } + } } diff --git a/main/codesig/test/cases/callgraph/realistic/2-ribbon/src/JCanvas.java b/main/codesig/test/cases/callgraph/realistic/2-ribbon/src/JCanvas.java index 5d56cf2c6ec..85a7d2d7863 100644 --- a/main/codesig/test/cases/callgraph/realistic/2-ribbon/src/JCanvas.java +++ b/main/codesig/test/cases/callgraph/realistic/2-ribbon/src/JCanvas.java @@ -1,28 +1,28 @@ -import java.io.*; -import java.util.*; import java.awt.*; -import javax.swing.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.image.*; -class JCanvas extends JPanel{ - private BufferedImage Picture; - Graphics2D Painter; - private Graphics Paint; +import java.io.*; +import java.util.*; +import javax.swing.*; - public JCanvas(){ - Picture = new BufferedImage(800, 600, BufferedImage.TYPE_BYTE_INDEXED); - Painter = Picture.createGraphics(); - } +class JCanvas extends JPanel { + private BufferedImage Picture; + Graphics2D Painter; + private Graphics Paint; + public JCanvas() { + Picture = new BufferedImage(800, 600, BufferedImage.TYPE_BYTE_INDEXED); + Painter = Picture.createGraphics(); + } - public void paintComponent(Graphics g){ - try{ + public void paintComponent(Graphics g) { + try { - Paint = this.getGraphics(); - g.drawImage(Picture, 0, 0, null); + Paint = this.getGraphics(); + g.drawImage(Picture, 0, 0, null); - }catch(NullPointerException e){ - } + } catch (NullPointerException e) { } + } } diff --git a/main/codesig/test/cases/callgraph/realistic/2-ribbon/src/Ribbon.java b/main/codesig/test/cases/callgraph/realistic/2-ribbon/src/Ribbon.java index 25577b1bbae..0740b7310b4 100644 --- a/main/codesig/test/cases/callgraph/realistic/2-ribbon/src/Ribbon.java +++ b/main/codesig/test/cases/callgraph/realistic/2-ribbon/src/Ribbon.java @@ -1,495 +1,549 @@ -// Taken from https://github.com/lihaoyi/Java-Games/blob/f5a47a07993ea6a6504c071792ec37b9e62a49f8/Ribbon4K/Ribbon.java +// Taken from +// https://github.com/lihaoyi/Java-Games/blob/f5a47a07993ea6a6504c071792ec37b9e62a49f8/Ribbon4K/Ribbon.java import java.awt.*; -import java.util.*; import java.awt.event.*; import java.awt.geom.*; +import java.util.*; import javax.swing.*; import javax.swing.Timer; -public class Ribbon{ - public static void main(String[] args){ - new RibbonGame(); +public class Ribbon { + public static void main(String[] args) { + new RibbonGame(); + } - } - public static double square(double INPUT){ - return INPUT * INPUT; - } - public static double length(Line2D L){ - return Math.sqrt(square(L.getX1() - L.getX2()) + square(L.getY1() - L.getY2())); - } - public static int randomInt(int INTA, int INTB){ - return ((int)Math.ceil(Math.random() * (Math.max(INTA, INTB) - Math.min(INTA, INTB) + 1) + Math.min(INTA, INTB) - 1)); - } - public static double cap(double Min, double Current, double Max){ - if(Current < Min){ - return Min; - } + public static double square(double INPUT) { + return INPUT * INPUT; + } - if(Current > Max){ - return Max; - } - return Current; - } -} -class SnakeVector extends Vector{ - public Point2D.Float point(int A){ - return (Point2D.Float)elementAt(A); - } - public Snake snake(int A){ - return (Snake)elementAt(A); + public static double length(Line2D L) { + return Math.sqrt(square(L.getX1() - L.getX2()) + square(L.getY1() - L.getY2())); + } + + public static int randomInt(int INTA, int INTB) { + return ((int) Math.ceil(Math.random() * (Math.max(INTA, INTB) - Math.min(INTA, INTB) + 1) + + Math.min(INTA, INTB) + - 1)); + } + + public static double cap(double Min, double Current, double Max) { + if (Current < Min) { + return Min; } - public Apple apple(int A){ - return (Apple)elementAt(A); + + if (Current > Max) { + return Max; } + return Current; + } } -class Snake{ - final SnakeVector Points = new SnakeVector(); - final Point[] LeftPoints = new Point[1024]; - final Point[] RightPoints = new Point[1024]; - - final float Width = 5; - - final float PointStep = 4; - - float Length; - float Speed; - - float ActualLength; - float Theta; - - int N; - int WaveCounter = 0; - boolean Left; - boolean Right; - float TurboCounter = 5; - boolean TurboOn = false; - - boolean Dead = false; - final float TurnSpeed = (float)Math.PI / 1.5f; - - final SnakeVector Home; - final Color Tint; - - public Snake(SnakeVector home, float theta, Point2D.Float Position, Color tint){ - Home = home; - Length = 150; - Speed = 50; - Theta = theta; - Tint = tint; - Points.add(Position); - Points.add(Position.clone()); - // Points.point(0).x += 0.1 * Math.cos(Theta); - // Points.point(0).y += 0.1 * Math.sin(Theta); - for(int i = 0; i < LeftPoints.length; i++){ - LeftPoints[i] = new Point(); - RightPoints[i] = new Point(); - } - N = Points.size() - 1; - } - public void move(double FramesPerSecond){ +class SnakeVector extends Vector { + public Point2D.Float point(int A) { + return (Point2D.Float) elementAt(A); + } - Theta += TurnSpeed / FramesPerSecond * ((Left ? -1 : 0) + (Right ? 1 : 0)); - - if(TurboOn == false){ - TurboCounter += 1.0 / FramesPerSecond; - }else{ - TurboCounter -= 1.0 / FramesPerSecond; - } - TurboCounter = (float)Ribbon.cap(0, TurboCounter, 5); - float DS = (float)((TurboOn == true && TurboCounter >= 0 ? (Speed * 1.75) : (Speed)) / FramesPerSecond); - - Points.point(0).x += (float)(DS * Math.cos(Theta)); - Points.point(0).y += (float)(DS * Math.sin(Theta)); - ; - WaveCounter += DS; + public Snake snake(int A) { + return (Snake) elementAt(A); + } + public Apple apple(int A) { + return (Apple) elementAt(A); + } +} - if(Points.point(0).distance(Points.point(1)) >= PointStep){ - Points.insertElementAt(Points.point(0).clone(), 0); - Points.point(0).x += 0.1 * Math.cos(Theta); - Points.point(0).y += 0.1 * Math.sin(Theta); - } +class Snake { + final SnakeVector Points = new SnakeVector(); + final Point[] LeftPoints = new Point[1024]; + final Point[] RightPoints = new Point[1024]; + + final float Width = 5; + + final float PointStep = 4; + + float Length; + float Speed; + + float ActualLength; + float Theta; + + int N; + int WaveCounter = 0; + boolean Left; + boolean Right; + float TurboCounter = 5; + boolean TurboOn = false; + + boolean Dead = false; + final float TurnSpeed = (float) Math.PI / 1.5f; + + final SnakeVector Home; + final Color Tint; + + public Snake(SnakeVector home, float theta, Point2D.Float Position, Color tint) { + Home = home; + Length = 150; + Speed = 50; + Theta = theta; + Tint = tint; + Points.add(Position); + Points.add(Position.clone()); + // Points.point(0).x += 0.1 * Math.cos(Theta); + // Points.point(0).y += 0.1 * Math.sin(Theta); + for (int i = 0; i < LeftPoints.length; i++) { + LeftPoints[i] = new Point(); + RightPoints[i] = new Point(); + } + N = Points.size() - 1; + } + public void move(double FramesPerSecond) { - if(Dead){ - Length -= 8; - } - shorten(); - N = Points.size() - 1; - calcLength(); + Theta += TurnSpeed / FramesPerSecond * ((Left ? -1 : 0) + (Right ? 1 : 0)); - if(Length <= 0){ - Home.remove(this); - } - // printPoints(); - } - final public void thicken(){ - - for(int i = 1; i < Points.size(); i++){ - float DX = Points.point(i).x - Points.point(i - 1).x; - float DY = Points.point(i).y - Points.point(i - 1).y; - float FX = DY / (float)Math.sqrt(DX * DX + DY * DY) * Width * (float)Math.sin((PointStep * i + WaveCounter) / Math.PI / 8); - float FY = -DX / (float)Math.sqrt(DX * DX + DY * DY) * Width * (float)Math.sin((PointStep * i + WaveCounter) / Math.PI / 8); - - LeftPoints[i].x = (int)(Points.point(i).x + FX); - LeftPoints[i].y = (int)(Points.point(i).y + FY); - RightPoints[i].x = (int)(Points.point(i).x - FX); - RightPoints[i].y = (int)(Points.point(i).y - FY); - if(i == 1){ - i--; - LeftPoints[i].x = (int)(Points.point(i).x + FX); - LeftPoints[i].y = (int)(Points.point(i).y + FY); - RightPoints[i].x = (int)(Points.point(i).x - FX); - RightPoints[i].y = (int)(Points.point(i).y - FY); - i++; - } - } + if (TurboOn == false) { + TurboCounter += 1.0 / FramesPerSecond; + } else { + TurboCounter -= 1.0 / FramesPerSecond; } - final private void calcLength(){ - ActualLength = 0; - for(int i = 1; i < Points.size(); i++){ - ActualLength += Points.point(i).distance(Points.point(i - 1)); - } + TurboCounter = (float) Ribbon.cap(0, TurboCounter, 5); + float DS = (float) + ((TurboOn == true && TurboCounter >= 0 ? (Speed * 1.75) : (Speed)) / FramesPerSecond); + + Points.point(0).x += (float) (DS * Math.cos(Theta)); + Points.point(0).y += (float) (DS * Math.sin(Theta)); + ; + WaveCounter += DS; + + if (Points.point(0).distance(Points.point(1)) >= PointStep) { + Points.insertElementAt(Points.point(0).clone(), 0); + Points.point(0).x += 0.1 * Math.cos(Theta); + Points.point(0).y += 0.1 * Math.sin(Theta); } - final public void shorten(){ - calcLength(); - float LengthDefect = ActualLength - Length; - if(LengthDefect > 0){ - if(Points.size() > 2 && LengthDefect > Points.point(Points.size() - 2).distance(Points.point(Points.size() - 1))){ - Points.removeElementAt(Points.size() - 1); - shorten(); - }else{ - - float DX = Points.point(Points.size() - 2).x - Points.point(Points.size() - 1).x; - float DY = Points.point(Points.size() - 2).y - Points.point(Points.size() - 1).y; - - float Multiplier = (float)(LengthDefect / Math.sqrt(DX * DX + DY * DY)); - Points.point(Points.size() - 1).x += DX * Multiplier; - Points.point(Points.size() - 1).y += DY * Multiplier; - } - } - return; + if (Dead) { + Length -= 8; } - final public boolean checkCollision(Rectangle Target){ + shorten(); + N = Points.size() - 1; + calcLength(); + if (Length <= 0) { + Home.remove(this); + } + // printPoints(); + } + + public final void thicken() { + + for (int i = 1; i < Points.size(); i++) { + float DX = Points.point(i).x - Points.point(i - 1).x; + float DY = Points.point(i).y - Points.point(i - 1).y; + float FX = DY + / (float) Math.sqrt(DX * DX + DY * DY) + * Width + * (float) Math.sin((PointStep * i + WaveCounter) / Math.PI / 8); + float FY = -DX + / (float) Math.sqrt(DX * DX + DY * DY) + * Width + * (float) Math.sin((PointStep * i + WaveCounter) / Math.PI / 8); + + LeftPoints[i].x = (int) (Points.point(i).x + FX); + LeftPoints[i].y = (int) (Points.point(i).y + FY); + RightPoints[i].x = (int) (Points.point(i).x - FX); + RightPoints[i].y = (int) (Points.point(i).y - FY); + if (i == 1) { + i--; + LeftPoints[i].x = (int) (Points.point(i).x + FX); + LeftPoints[i].y = (int) (Points.point(i).y + FY); + RightPoints[i].x = (int) (Points.point(i).x - FX); + RightPoints[i].y = (int) (Points.point(i).y - FY); + i++; + } + } + } - if(!Target.contains(LeftPoints[0]) || !Target.contains(RightPoints[0])){ - return true; - }else{ - return false; - } + private final void calcLength() { + ActualLength = 0; + for (int i = 1; i < Points.size(); i++) { + ActualLength += Points.point(i).distance(Points.point(i - 1)); } + } + + public final void shorten() { + calcLength(); + float LengthDefect = ActualLength - Length; + if (LengthDefect > 0) { + if (Points.size() > 2 + && LengthDefect + > Points.point(Points.size() - 2).distance(Points.point(Points.size() - 1))) { + Points.removeElementAt(Points.size() - 1); + shorten(); + } else { - final public boolean checkCollision(Snake Target){ + float DX = Points.point(Points.size() - 2).x - Points.point(Points.size() - 1).x; + float DY = Points.point(Points.size() - 2).y - Points.point(Points.size() - 1).y; - Line2D.Float LineA = new Line2D.Float(); - Line2D.Float LineB = new Line2D.Float(); - LineA.setLine(LeftPoints[0], RightPoints[0]); - for(int i = 1; i <= Target.N; i++){ - if(Target == this && (i == 1 || i == 2)){ - continue; - } - LineB.setLine(Target.RightPoints[i], Target.RightPoints[i - 1]); - if(LineB.intersectsLine(LineA) && Ribbon.length(LineA) > 0 && Ribbon.length(LineB) > 0){ - System.out.println("DAI1"); - return true; + float Multiplier = (float) (LengthDefect / Math.sqrt(DX * DX + DY * DY)); + Points.point(Points.size() - 1).x += DX * Multiplier; + Points.point(Points.size() - 1).y += DY * Multiplier; + } + } + return; + } - } - LineB.setLine(Target.LeftPoints[i], Target.LeftPoints[i - 1]); - if(LineB.intersectsLine(LineA) && Ribbon.length(LineA) > 0 && Ribbon.length(LineB) > 0){ - System.out.println("DAI2"); - return true; - } + public final boolean checkCollision(Rectangle Target) { - } - LineB.setLine(Target.LeftPoints[N], Target.RightPoints[N]); - if(LineB.intersectsLine(LineA) && Ribbon.length(LineA) > 0 && Ribbon.length(LineB) > 0 && ActualLength > 2){ - System.out.println("DAI3"); - return true; - } - LineB.setLine(Target.LeftPoints[0], Target.RightPoints[0]); - if(Target != this && LineB.intersectsLine(LineA) && Ribbon.length(LineA) > 0 && Ribbon.length(LineB) > 0){ - System.out.println("DAI4"); - return true; - } - return false; - } - public void print(Graphics2D Painter){ - Painter.setColor(Tint); - Painter.drawLine(LeftPoints[0].x, LeftPoints[0].y, RightPoints[0].x, RightPoints[0].y); - Painter.drawLine(LeftPoints[N].x, LeftPoints[N].y, RightPoints[N].x, RightPoints[N].y); - for(int i = 1; i <= N; i++){ - Painter.drawLine((int)LeftPoints[i].x, (int)LeftPoints[i].y, (int)LeftPoints[i - 1].x, (int)LeftPoints[i - 1].y); - Painter.drawLine((int)RightPoints[i].x, (int)RightPoints[i].y, (int)RightPoints[i - 1].x, (int)RightPoints[i - 1].y); - //Painter.drawLine((int)Points.point(i).x, (int)Points.point(i).y, (int)Points.point(i - 1).x, (int)Points.point(i - 1).y); - } + if (!Target.contains(LeftPoints[0]) || !Target.contains(RightPoints[0])) { + return true; + } else { + return false; } -} -class Apple{ - final Point2D.Float Position; - final Point2D.Float Velocity; - final Color Tint; - final int Points; - final int Radius = 4; - final SnakeVector Home; - public Apple(SnakeVector home, int Level, Rectangle Boundary){ - Home = home; - int V = 0; - switch(Level){ - case 1: - Tint = Color.red; - Points = 15; - V = 0; - break; - case 2: - Tint = Color.blue; - Points = 45; - V = 50; - break; - case 3: - Tint = Color.cyan; - Points = 75; - V = 100; - break; - default: - Tint = Color.white; - Points = 1; - } - - Velocity = new Point2D.Float((Ribbon.randomInt(0, 1) * 2 - 1) * V, (Ribbon.randomInt(0, 1) * 2 - 1) * V); - Position = new Point2D.Float(Ribbon.randomInt(Radius + Boundary.x, Boundary.width + Boundary.x - Radius), Ribbon.randomInt(Radius + Boundary.y, Boundary.height + Boundary.y - Radius)); + } + + public final boolean checkCollision(Snake Target) { + + Line2D.Float LineA = new Line2D.Float(); + Line2D.Float LineB = new Line2D.Float(); + LineA.setLine(LeftPoints[0], RightPoints[0]); + for (int i = 1; i <= Target.N; i++) { + if (Target == this && (i == 1 || i == 2)) { + continue; + } + LineB.setLine(Target.RightPoints[i], Target.RightPoints[i - 1]); + if (LineB.intersectsLine(LineA) && Ribbon.length(LineA) > 0 && Ribbon.length(LineB) > 0) { + System.out.println("DAI1"); + return true; + } + LineB.setLine(Target.LeftPoints[i], Target.LeftPoints[i - 1]); + if (LineB.intersectsLine(LineA) && Ribbon.length(LineA) > 0 && Ribbon.length(LineB) > 0) { + System.out.println("DAI2"); + return true; + } } - final public void move(double FramesPerSecond){ - Position.x += Velocity.x / FramesPerSecond; - Position.y += Velocity.y / FramesPerSecond; + LineB.setLine(Target.LeftPoints[N], Target.RightPoints[N]); + if (LineB.intersectsLine(LineA) + && Ribbon.length(LineA) > 0 + && Ribbon.length(LineB) > 0 + && ActualLength > 2) { + System.out.println("DAI3"); + return true; } - - final public void tryBoundaries(Rectangle Boundary){ - if(Position.x - Radius < Boundary.x){ - Velocity.x = Math.abs(Velocity.x); - } - if(Position.y - Radius < Boundary.y){ - Velocity.y = Math.abs(Velocity.y); - } - if(Position.x + Radius > Boundary.width + Boundary.x){ - Velocity.x = -Math.abs(Velocity.x); - } - if(Position.y + Radius > Boundary.height + Boundary.y){ - Velocity.y = -Math.abs(Velocity.y); - } + LineB.setLine(Target.LeftPoints[0], Target.RightPoints[0]); + if (Target != this + && LineB.intersectsLine(LineA) + && Ribbon.length(LineA) > 0 + && Ribbon.length(LineB) > 0) { + System.out.println("DAI4"); + return true; } - final public void tryEat(Snake Target){ - if(Line2D.Float.ptSegDist(Target.LeftPoints[0].x, Target.LeftPoints[0].y, Target.RightPoints[0].x, Target.RightPoints[0].y, Position.x, Position.y) < Radius){ - Home.remove(this); - Target.Length += Points; - } + return false; + } + + public void print(Graphics2D Painter) { + Painter.setColor(Tint); + Painter.drawLine(LeftPoints[0].x, LeftPoints[0].y, RightPoints[0].x, RightPoints[0].y); + Painter.drawLine(LeftPoints[N].x, LeftPoints[N].y, RightPoints[N].x, RightPoints[N].y); + for (int i = 1; i <= N; i++) { + Painter.drawLine( + (int) LeftPoints[i].x, (int) LeftPoints[i].y, (int) LeftPoints[i - 1].x, (int) + LeftPoints[i - 1].y); + Painter.drawLine( + (int) RightPoints[i].x, (int) RightPoints[i].y, (int) RightPoints[i - 1].x, (int) + RightPoints[i - 1].y); + // Painter.drawLine((int)Points.point(i).x, (int)Points.point(i).y, (int)Points.point(i - + // 1).x, (int)Points.point(i - 1).y); } + } +} - final public void tryCollision(Snake Target){ - - Line2D.Float TargetLine = new Line2D.Float(); - float Distance = -1; - int Index = -1; - for(int i = 1; i < Target.Points.size(); i++){ - TargetLine.setLine(Target.LeftPoints[i - 1], Target.LeftPoints[i]); - double D = TargetLine.ptSegDist(Position); - if(D < Radius && (D < Distance || Index == -1)){ - Index = i; - Distance = (float)D; - } - } - for(int i = 1; i < Target.Points.size(); i++){ - TargetLine.setLine(Target.RightPoints[i - 1], Target.RightPoints[i]); - double D = TargetLine.ptSegDist(Position); - if(D < Radius && (D < Distance || Index == -1)){ - Index = i; - Distance = (float)D; - } - } - TargetLine.setLine(Target.RightPoints[Target.N], Target.LeftPoints[Target.N]); - double D = TargetLine.ptSegDist(Position); - if(D < Radius && (D < Distance || Index == -1)){ - Index = -2; - Distance = (float)D; - } - if(Index != -1){ - if(Index == -2){ - TargetLine.setLine(Target.Points.point(Target.N), Target.Points.point(Target.N)); - }else{ - TargetLine.setLine(Target.Points.point(Index - 1), Target.Points.point(Index)); - } - Point2D.Float Average = new Point2D.Float((float)(TargetLine.getX1() + TargetLine.getX2()), (float)(TargetLine.getY1() + TargetLine.getY2())); - Average.x /= 2; Average.y /= 2; - Average.x = Position.x - Average.x; - Average.y = Position.y - Average.y; - float L = (float)Math.sqrt(Average.x * Average.x + Average.y * Average.y); - Average.x /= L; Average.y /= L; - float Dot = Average.x * Velocity.x + Average.y * Velocity.y; - Dot = (float)Ribbon.cap(-Math.sqrt(Velocity.x * Velocity.x + Velocity.y * Velocity.y), Dot, 0); - Velocity.x -= 2 * Average.x * Dot; Velocity.y -= 2 * Average.y * Dot; - +class Apple { + final Point2D.Float Position; + final Point2D.Float Velocity; + final Color Tint; + final int Points; + final int Radius = 4; + final SnakeVector Home; + + public Apple(SnakeVector home, int Level, Rectangle Boundary) { + Home = home; + int V = 0; + switch (Level) { + case 1: + Tint = Color.red; + Points = 15; + V = 0; + break; + case 2: + Tint = Color.blue; + Points = 45; + V = 50; + break; + case 3: + Tint = Color.cyan; + Points = 75; + V = 100; + break; + default: + Tint = Color.white; + Points = 1; + } - } + Velocity = new Point2D.Float( + (Ribbon.randomInt(0, 1) * 2 - 1) * V, (Ribbon.randomInt(0, 1) * 2 - 1) * V); + Position = new Point2D.Float( + Ribbon.randomInt(Radius + Boundary.x, Boundary.width + Boundary.x - Radius), + Ribbon.randomInt(Radius + Boundary.y, Boundary.height + Boundary.y - Radius)); + } + + public final void move(double FramesPerSecond) { + Position.x += Velocity.x / FramesPerSecond; + Position.y += Velocity.y / FramesPerSecond; + } + + public final void tryBoundaries(Rectangle Boundary) { + if (Position.x - Radius < Boundary.x) { + Velocity.x = Math.abs(Velocity.x); } - final public void print(Graphics2D Painter){ - Painter.setColor(Tint); - Painter.drawLine((int)Position.x - Radius, (int)Position.y - Radius, (int)Position.x + Radius, (int)Position.y + Radius); - Painter.drawLine((int)Position.x + Radius, (int)Position.y - Radius, (int)Position.x - Radius, (int)Position.y + Radius); + if (Position.y - Radius < Boundary.y) { + Velocity.y = Math.abs(Velocity.y); } - + if (Position.x + Radius > Boundary.width + Boundary.x) { + Velocity.x = -Math.abs(Velocity.x); + } + if (Position.y + Radius > Boundary.height + Boundary.y) { + Velocity.y = -Math.abs(Velocity.y); + } + } + + public final void tryEat(Snake Target) { + if (Line2D.Float.ptSegDist( + Target.LeftPoints[0].x, + Target.LeftPoints[0].y, + Target.RightPoints[0].x, + Target.RightPoints[0].y, + Position.x, + Position.y) + < Radius) { + Home.remove(this); + Target.Length += Points; + } + } + + public final void tryCollision(Snake Target) { + + Line2D.Float TargetLine = new Line2D.Float(); + float Distance = -1; + int Index = -1; + for (int i = 1; i < Target.Points.size(); i++) { + TargetLine.setLine(Target.LeftPoints[i - 1], Target.LeftPoints[i]); + double D = TargetLine.ptSegDist(Position); + if (D < Radius && (D < Distance || Index == -1)) { + Index = i; + Distance = (float) D; + } + } + for (int i = 1; i < Target.Points.size(); i++) { + TargetLine.setLine(Target.RightPoints[i - 1], Target.RightPoints[i]); + double D = TargetLine.ptSegDist(Position); + if (D < Radius && (D < Distance || Index == -1)) { + Index = i; + Distance = (float) D; + } + } + TargetLine.setLine(Target.RightPoints[Target.N], Target.LeftPoints[Target.N]); + double D = TargetLine.ptSegDist(Position); + if (D < Radius && (D < Distance || Index == -1)) { + Index = -2; + Distance = (float) D; + } + if (Index != -1) { + if (Index == -2) { + TargetLine.setLine(Target.Points.point(Target.N), Target.Points.point(Target.N)); + } else { + TargetLine.setLine(Target.Points.point(Index - 1), Target.Points.point(Index)); + } + Point2D.Float Average = + new Point2D.Float((float) (TargetLine.getX1() + TargetLine.getX2()), (float) + (TargetLine.getY1() + TargetLine.getY2())); + Average.x /= 2; + Average.y /= 2; + Average.x = Position.x - Average.x; + Average.y = Position.y - Average.y; + float L = (float) Math.sqrt(Average.x * Average.x + Average.y * Average.y); + Average.x /= L; + Average.y /= L; + float Dot = Average.x * Velocity.x + Average.y * Velocity.y; + Dot = + (float) Ribbon.cap(-Math.sqrt(Velocity.x * Velocity.x + Velocity.y * Velocity.y), Dot, 0); + Velocity.x -= 2 * Average.x * Dot; + Velocity.y -= 2 * Average.y * Dot; + } + } + + public final void print(Graphics2D Painter) { + Painter.setColor(Tint); + Painter.drawLine( + (int) Position.x - Radius, + (int) Position.y - Radius, + (int) Position.x + Radius, + (int) Position.y + Radius); + Painter.drawLine( + (int) Position.x + Radius, + (int) Position.y - Radius, + (int) Position.x - Radius, + (int) Position.y + Radius); + } } -class RibbonGame extends JFrame implements KeyListener, ActionListener{ - - final int X = 800; - final int Y = 600; - - - - Timer Stopwatch = new Timer(20, this); - float FramesPerSecond = 50; - - JCanvas Area; - - Rectangle Boundary = new Rectangle(0, 0, X, Y); - SnakeVector Snakes = new SnakeVector(); - SnakeVector Apples = new SnakeVector(); - Snake Player; - - - public void init(){ - Snake S = new Snake(Snakes, 0, new Point2D.Float(X / 2, Y / 2), Color.red); - Snakes.add(S); - Player = S; +class RibbonGame extends JFrame implements KeyListener, ActionListener { + + final int X = 800; + final int Y = 600; + + Timer Stopwatch = new Timer(20, this); + float FramesPerSecond = 50; + + JCanvas Area; + + Rectangle Boundary = new Rectangle(0, 0, X, Y); + SnakeVector Snakes = new SnakeVector(); + SnakeVector Apples = new SnakeVector(); + Snake Player; + + public void init() { + Snake S = new Snake(Snakes, 0, new Point2D.Float(X / 2, Y / 2), Color.red); + Snakes.add(S); + Player = S; + } + + public RibbonGame() { + // BASIC INITIALIZATION + super("Window"); + this.setSize(X, Y); + this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + this.setResizable(false); + // SET CONTENT PANE + Container contentArea = getContentPane(); + contentArea.setLayout(null); + // LAYOUT MANAGER + // ADD ITEMS TO CONTENT PANE + Area = new JCanvas(); + + contentArea.add(Area); + + Boundary.setBounds(0 + 4, 0 + 4, X - 8, Y - 8); + + this.addKeyListener(this); + + // initSockets(); + init(); + Stopwatch.start(); + + // ADD CONTENT PANE AND PACK + this.setUndecorated(true); + this.setContentPane(contentArea); + this.show(); + // this.pack(); + } + + // EVENT TRIGGERS + public void keyPressed(KeyEvent e) { + // System.out.println(e.getKeyChar() + "\t" + LEFT + "\t" + RIGHT + "\t" + FORWARD + "\t" + + // BACK); + System.out.println(e.getKeyCode()); + switch (e.getKeyCode()) { + case 38: + Player.TurboOn = true; + break; + case 40: + Apple B = new Apple(Apples, Ribbon.randomInt(1, 3), Boundary); + Apples.add(B); + ; + break; + case 37: + Player.Left = true; + break; + case 39: + Player.Right = true; + break; } + } + public void keyReleased(KeyEvent e) { + switch (e.getKeyCode()) { + case 38: + Player.TurboOn = false; + ; + break; + case 40: + ; + break; + case 37: + Player.Left = !true; + break; + case 39: + Player.Right = !true; + break; + } + } + public void keyTyped(KeyEvent e) {} - public RibbonGame(){ - //BASIC INITIALIZATION - super("Window"); - this.setSize(X, Y); - this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - this.setResizable(false); - //SET CONTENT PANE - Container contentArea = getContentPane(); - contentArea.setLayout(null); - //LAYOUT MANAGER - //ADD ITEMS TO CONTENT PANE - Area = new JCanvas(); - - contentArea.add(Area); - - Boundary.setBounds(0 + 4, 0 + 4, X - 8, Y - 8); - - this.addKeyListener(this); + public void actionPerformed(ActionEvent e) { - // initSockets(); - init(); - Stopwatch.start(); + Area.Painter.setColor(Color.black); + Area.Painter.fillRect(0, 0, X, Y); + System.out.println("GO"); - //ADD CONTENT PANE AND PACK - this.setUndecorated(true); - this.setContentPane(contentArea); - this.show(); - //this.pack(); + for (int i = 0; i < Snakes.size(); i++) { + Snakes.snake(i).move(FramesPerSecond); } - - //EVENT TRIGGERS - public void keyPressed(KeyEvent e){ - // System.out.println(e.getKeyChar() + "\t" + LEFT + "\t" + RIGHT + "\t" + FORWARD + "\t" + BACK); - System.out.println(e.getKeyCode()); - switch(e.getKeyCode()){ - case 38: - Player.TurboOn = true; - break; - case 40: - Apple B = new Apple(Apples, Ribbon.randomInt(1, 3), Boundary); - Apples.add(B); - ; break; - case 37: Player.Left = true; break; - case 39: Player.Right = true; break; - - } - + for (int i = 0; i < Snakes.size(); i++) { + Snakes.snake(i).thicken(); } - public void keyReleased(KeyEvent e){ - switch(e.getKeyCode()){ - case 38: Player.TurboOn = false; - ; break; - case 40: ; break; - case 37: Player.Left = !true; break; - case 39: Player.Right = !true; break; - } + for (int i = 0; i < Apples.size(); i++) { + Apples.apple(i).move(FramesPerSecond); + Apples.apple(i).tryBoundaries(Boundary); + for (int j = 0; j < Snakes.size(); j++) { + Apples.apple(i).tryCollision(Snakes.snake(j)); + } } - - - public void keyTyped(KeyEvent e){ - + for (int i = 0; i < Apples.size(); i++) { + ; + for (int j = 0; j < Snakes.size(); j++) { + Apples.apple(i).tryEat(Snakes.snake(j)); + } } + for (int i = 0; i < Snakes.size(); i++) { + if (Snakes.snake(i).checkCollision(Boundary)) { + Snakes.snake(i).Dead = true; + Snakes.snake(i).Speed = 0; + } + } + for (int i = 0; i < Snakes.size(); i++) { + for (int j = 0; j < Snakes.size(); j++) { + Point CollisionData = null; - - public void actionPerformed(ActionEvent e){ - - Area.Painter.setColor(Color.black); - Area.Painter.fillRect(0, 0, X, Y); - System.out.println("GO"); - - for(int i = 0; i < Snakes.size(); i++){ - Snakes.snake(i).move(FramesPerSecond); - - - } - for(int i = 0; i < Snakes.size(); i++){ - Snakes.snake(i).thicken(); - } - for(int i = 0; i < Apples.size(); i++){ - Apples.apple(i).move(FramesPerSecond); - Apples.apple(i).tryBoundaries(Boundary); - for(int j = 0; j < Snakes.size(); j++){ - Apples.apple(i).tryCollision(Snakes.snake(j)); - } - } - for(int i = 0; i < Apples.size(); i++){; - for(int j = 0; j < Snakes.size(); j++){ - Apples.apple(i).tryEat(Snakes.snake(j)); - } - } - for(int i = 0; i < Snakes.size(); i++){ - if(Snakes.snake(i).checkCollision(Boundary)){ - Snakes.snake(i).Dead = true; - Snakes.snake(i).Speed = 0; - - } - } - for(int i = 0; i < Snakes.size(); i++){ - for(int j = 0; j < Snakes.size(); j++){ - Point CollisionData = null; - - if(Snakes.snake(i).checkCollision(Snakes.snake(j))){ - Snakes.snake(i).Dead = true; - Snakes.snake(i).Speed = 0; - - } - - } - } - for(int i = 0; i < Snakes.size(); i++){ - - Snakes.snake(i).print(Area.Painter); - } - for(int j = 0; j < Apples.size(); j++){ - Apples.apple(j).print(Area.Painter); + if (Snakes.snake(i).checkCollision(Snakes.snake(j))) { + Snakes.snake(i).Dead = true; + Snakes.snake(i).Speed = 0; } + } + } + for (int i = 0; i < Snakes.size(); i++) { - Area.Painter.setColor(Color.white); - Area.Painter.drawRect(2, 2, X - 4, Y - 4); - Area.Painter.drawRect(4, 4, X - 8, Y - 8); - Area.paintComponent(this.getGraphics()); - + Snakes.snake(i).print(Area.Painter); + } + for (int j = 0; j < Apples.size(); j++) { + Apples.apple(j).print(Area.Painter); } - //Time Considerations + + Area.Painter.setColor(Color.white); + Area.Painter.drawRect(2, 2, X - 4, Y - 4); + Area.Painter.drawRect(4, 4, X - 8, Y - 8); + Area.paintComponent(this.getGraphics()); + } + // Time Considerations } diff --git a/main/codesig/test/cases/methodhash/changed/basic/src/Hello.java b/main/codesig/test/cases/methodhash/changed/basic/src/Hello.java index 1fe3dd04941..aa7c43b8353 100644 --- a/main/codesig/test/cases/methodhash/changed/basic/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/basic/src/Hello.java @@ -1,7 +1,7 @@ package hello; -public class Hello{ - public static void main(String[] args){ - System.out.println(1); - } +public class Hello { + public static void main(String[] args) { + System.out.println(1); + } } diff --git a/main/codesig/test/cases/methodhash/changed/constant-large/src/Hello.java b/main/codesig/test/cases/methodhash/changed/constant-large/src/Hello.java index 41a5c8efb4e..8eed0ea0f94 100644 --- a/main/codesig/test/cases/methodhash/changed/constant-large/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/constant-large/src/Hello.java @@ -1,7 +1,7 @@ package hello; -public class Hello{ - public static void main(String[] args){ - System.out.println(31337); - } +public class Hello { + public static void main(String[] args) { + System.out.println(31337); + } } diff --git a/main/codesig/test/cases/methodhash/changed/constant-small/src/Hello.java b/main/codesig/test/cases/methodhash/changed/constant-small/src/Hello.java index 424578980d6..979690813f3 100644 --- a/main/codesig/test/cases/methodhash/changed/constant-small/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/constant-small/src/Hello.java @@ -1,7 +1,7 @@ package hello; -public class Hello{ - public static void main(String[] args){ - System.out.println(2); - } +public class Hello { + public static void main(String[] args) { + System.out.println(2); + } } diff --git a/main/codesig/test/cases/methodhash/changed/constant-string/src/Hello.java b/main/codesig/test/cases/methodhash/changed/constant-string/src/Hello.java index e690a7ef786..3ba74d1df8e 100644 --- a/main/codesig/test/cases/methodhash/changed/constant-string/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/constant-string/src/Hello.java @@ -1,7 +1,7 @@ package hello; -public class Hello{ - public static void main(String[] args){ - System.out.println("2"); - } +public class Hello { + public static void main(String[] args) { + System.out.println("2"); + } } diff --git a/main/codesig/test/cases/methodhash/changed/different-field-read/src/Hello.java b/main/codesig/test/cases/methodhash/changed/different-field-read/src/Hello.java index 708f684975a..17682144874 100644 --- a/main/codesig/test/cases/methodhash/changed/different-field-read/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/different-field-read/src/Hello.java @@ -1,7 +1,7 @@ package hello; -public class Hello{ - public static void main(String[] args){ - System.err.println(2); - } +public class Hello { + public static void main(String[] args) { + System.err.println(2); + } } diff --git a/main/codesig/test/cases/methodhash/changed/if-else-biased/src/Hello.java b/main/codesig/test/cases/methodhash/changed/if-else-biased/src/Hello.java index d8ceaf4c4c3..96e15ff185d 100644 --- a/main/codesig/test/cases/methodhash/changed/if-else-biased/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/if-else-biased/src/Hello.java @@ -1,11 +1,11 @@ package hello; -public class Hello{ - public static void main(String[] args){ - if (args.length == 0) {} - else { - System.out.println(1); - System.out.println(2); - } +public class Hello { + public static void main(String[] args) { + if (args.length == 0) { + } else { + System.out.println(1); + System.out.println(2); } + } } diff --git a/main/codesig/test/cases/methodhash/changed/if-else-reverse-conditional/src/Hello.java b/main/codesig/test/cases/methodhash/changed/if-else-reverse-conditional/src/Hello.java index ed7a686d3ab..10d4df9ea91 100644 --- a/main/codesig/test/cases/methodhash/changed/if-else-reverse-conditional/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/if-else-reverse-conditional/src/Hello.java @@ -1,8 +1,8 @@ package hello; -public class Hello{ - public static void main(String[] args){ - if (args.length != 0) System.out.println(1); - else System.out.println(2); - } +public class Hello { + public static void main(String[] args) { + if (args.length != 0) System.out.println(1); + else System.out.println(2); + } } diff --git a/main/codesig/test/cases/methodhash/changed/if-else/src/Hello.java b/main/codesig/test/cases/methodhash/changed/if-else/src/Hello.java index 3f064264b77..02c0da37f2d 100644 --- a/main/codesig/test/cases/methodhash/changed/if-else/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/if-else/src/Hello.java @@ -1,8 +1,8 @@ package hello; -public class Hello{ - public static void main(String[] args){ - if (args.length == 0) System.out.println(1); - else System.out.println(2); - } +public class Hello { + public static void main(String[] args) { + if (args.length == 0) System.out.println(1); + else System.out.println(2); + } } diff --git a/main/codesig/test/cases/methodhash/changed/if/src/Hello.java b/main/codesig/test/cases/methodhash/changed/if/src/Hello.java index 52c62571319..ffa656d1c78 100644 --- a/main/codesig/test/cases/methodhash/changed/if/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/if/src/Hello.java @@ -1,7 +1,7 @@ package hello; -public class Hello{ - public static void main(String[] args){ - if (args.length == 0) System.out.println(1); - } +public class Hello { + public static void main(String[] args) { + if (args.length == 0) System.out.println(1); + } } diff --git a/main/codesig/test/cases/methodhash/changed/local-call-instance/src/Hello.java b/main/codesig/test/cases/methodhash/changed/local-call-instance/src/Hello.java index 83b5ce32ac7..03d29d3b9d5 100644 --- a/main/codesig/test/cases/methodhash/changed/local-call-instance/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/local-call-instance/src/Hello.java @@ -1,11 +1,12 @@ package hello; -public class Hello{ - public static void main(String[] args){ - System.out.println(1); - new Hello().doThing(); - } - public void doThing(){ - System.out.println(2); - } +public class Hello { + public static void main(String[] args) { + System.out.println(1); + new Hello().doThing(); + } + + public void doThing() { + System.out.println(2); + } } diff --git a/main/codesig/test/cases/methodhash/changed/local-call-parameter/src/Hello.java b/main/codesig/test/cases/methodhash/changed/local-call-parameter/src/Hello.java index 08d8975b3e8..a8aba68e03f 100644 --- a/main/codesig/test/cases/methodhash/changed/local-call-parameter/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/local-call-parameter/src/Hello.java @@ -1,11 +1,12 @@ package hello; -public class Hello{ - public static void main(String[] args){ - System.out.println(1); - doThing(); - } - public static void doThing(){ - System.out.println(2); - } +public class Hello { + public static void main(String[] args) { + System.out.println(1); + doThing(); + } + + public static void doThing() { + System.out.println(2); + } } diff --git a/main/codesig/test/cases/methodhash/changed/local-call-renamed/src/Hello.java b/main/codesig/test/cases/methodhash/changed/local-call-renamed/src/Hello.java index 796800ec945..076a769f949 100644 --- a/main/codesig/test/cases/methodhash/changed/local-call-renamed/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/local-call-renamed/src/Hello.java @@ -1,11 +1,12 @@ package hello; -public class Hello{ - public static void main(String[] args){ - System.out.println(1); - doThing2(); - } - public static void doThing2(){ - System.out.println(2); - } +public class Hello { + public static void main(String[] args) { + System.out.println(1); + doThing2(); + } + + public static void doThing2() { + System.out.println(2); + } } diff --git a/main/codesig/test/cases/methodhash/changed/local-call-transitive-change/src/Hello.java b/main/codesig/test/cases/methodhash/changed/local-call-transitive-change/src/Hello.java index c89d8a749c2..4ff90789664 100644 --- a/main/codesig/test/cases/methodhash/changed/local-call-transitive-change/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/local-call-transitive-change/src/Hello.java @@ -1,11 +1,12 @@ package hello; -public class Hello{ - public static void main(String[] args){ - System.out.println(1); - doThing(2); - } - public static void doThing(int i){ - System.out.println(i); - } +public class Hello { + public static void main(String[] args) { + System.out.println(1); + doThing(2); + } + + public static void doThing(int i) { + System.out.println(i); + } } diff --git a/main/codesig/test/cases/methodhash/changed/local-call/src/Hello.java b/main/codesig/test/cases/methodhash/changed/local-call/src/Hello.java index a7c19812abc..8d5275576df 100644 --- a/main/codesig/test/cases/methodhash/changed/local-call/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/local-call/src/Hello.java @@ -1,11 +1,12 @@ package hello; -public class Hello{ - public static void main(String[] args){ - System.out.println(1); - doThing(2); - } - public static void doThing(int i){ - System.out.println(i + i); - } +public class Hello { + public static void main(String[] args) { + System.out.println(1); + doThing(2); + } + + public static void doThing(int i) { + System.out.println(i + i); + } } diff --git a/main/codesig/test/cases/methodhash/changed/switch-keys/src/Hello.java b/main/codesig/test/cases/methodhash/changed/switch-keys/src/Hello.java index 921b208693a..51e0f6bc502 100644 --- a/main/codesig/test/cases/methodhash/changed/switch-keys/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/switch-keys/src/Hello.java @@ -1,11 +1,17 @@ package hello; -public class Hello{ - public static void main(String[] args){ - switch(args.length){ - case 0: System.out.println(0); break; - case 1: System.out.println(1); break; - case 3: System.out.println(2); break; - } +public class Hello { + public static void main(String[] args) { + switch (args.length) { + case 0: + System.out.println(0); + break; + case 1: + System.out.println(1); + break; + case 3: + System.out.println(2); + break; } + } } diff --git a/main/codesig/test/cases/methodhash/changed/switch-remove-break/src/Hello.java b/main/codesig/test/cases/methodhash/changed/switch-remove-break/src/Hello.java index e76f0390abe..d30ba1978b3 100644 --- a/main/codesig/test/cases/methodhash/changed/switch-remove-break/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/switch-remove-break/src/Hello.java @@ -1,11 +1,16 @@ package hello; -public class Hello{ - public static void main(String[] args){ - switch(args.length){ - case 0: System.out.println(0); break; - case 1: System.out.println(1); - case 5: System.out.println(2); break; - } +public class Hello { + public static void main(String[] args) { + switch (args.length) { + case 0: + System.out.println(0); + break; + case 1: + System.out.println(1); + case 5: + System.out.println(2); + break; } + } } diff --git a/main/codesig/test/cases/methodhash/changed/switch/src/Hello.java b/main/codesig/test/cases/methodhash/changed/switch/src/Hello.java index 345c128caac..7447a9ee32b 100644 --- a/main/codesig/test/cases/methodhash/changed/switch/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/switch/src/Hello.java @@ -1,11 +1,17 @@ package hello; -public class Hello{ - public static void main(String[] args){ - switch(args.length){ - case 0: System.out.println(0); break; - case 1: System.out.println(1); break; - case 2: System.out.println(2); break; - } +public class Hello { + public static void main(String[] args) { + switch (args.length) { + case 0: + System.out.println(0); + break; + case 1: + System.out.println(1); + break; + case 2: + System.out.println(2); + break; } + } } diff --git a/main/codesig/test/cases/methodhash/changed/two-calls/src/Hello.java b/main/codesig/test/cases/methodhash/changed/two-calls/src/Hello.java index 41b88574238..37fd0b5e84b 100644 --- a/main/codesig/test/cases/methodhash/changed/two-calls/src/Hello.java +++ b/main/codesig/test/cases/methodhash/changed/two-calls/src/Hello.java @@ -1,8 +1,8 @@ package hello; -public class Hello{ - public static void main(String[] args){ - System.out.println(1); - System.out.println(2); - } +public class Hello { + public static void main(String[] args) { + System.out.println(1); + System.out.println(2); + } } diff --git a/main/codesig/test/cases/methodhash/unchanged/simple-java-2/src/Hello.java b/main/codesig/test/cases/methodhash/unchanged/simple-java-2/src/Hello.java index c0602eb82c5..188d74249ad 100644 --- a/main/codesig/test/cases/methodhash/unchanged/simple-java-2/src/Hello.java +++ b/main/codesig/test/cases/methodhash/unchanged/simple-java-2/src/Hello.java @@ -3,24 +3,21 @@ /** * Very verbose Javadoc comment on top of class */ -public class Hello{ - /** - * less verbose Javadoc comment for single method - */ - public static int main(){ - System.out.println(1); - return used(); - } +public class Hello { + /** + * less verbose Javadoc comment for single method + */ + public static int main() { + System.out.println(1); + return used(); + } + public static int used() { + // Random line-comment inside + return 2; + } - - public static int used(){ - // Random line-comment inside - return 2; - } - - - public static int unused(){ - return 1; - } + public static int unused() { + return 1; + } } diff --git a/main/codesig/test/cases/methodhash/unchanged/simple-java/src/Hello.java b/main/codesig/test/cases/methodhash/unchanged/simple-java/src/Hello.java index c29534eb651..7332bb48c66 100644 --- a/main/codesig/test/cases/methodhash/unchanged/simple-java/src/Hello.java +++ b/main/codesig/test/cases/methodhash/unchanged/simple-java/src/Hello.java @@ -1,7 +1,16 @@ package hello; -public class Hello{ - public static int main(){System.out.println(1); return used();} - public static int used(){ return 2; } - public static int unused(){ return 1; } +public class Hello { + public static int main() { + System.out.println(1); + return used(); + } + + public static int used() { + return 2; + } + + public static int unused() { + return 1; + } } diff --git a/main/util/test/src/mill/util/PromptLoggerTests.scala b/main/util/test/src/mill/util/PromptLoggerTests.scala index 0f487a4e640..77dfd59c05b 100644 --- a/main/util/test/src/mill/util/PromptLoggerTests.scala +++ b/main/util/test/src/mill/util/PromptLoggerTests.scala @@ -52,7 +52,7 @@ object PromptLoggerTests extends TestSuite { } val tests = Tests { - test("nonInteractive") { + test("nonInteractive") - retry(3) { // These tests seem flaky on windows but not sure why if (!Util.windowsPlatform) { var now = 0L @@ -105,7 +105,7 @@ object PromptLoggerTests extends TestSuite { } } - test("interactive") { + test("interactive") - retry(3) { if (!Util.windowsPlatform) { var now = 0L val (baos, promptLogger, prefixLogger) = setup(() => now, os.temp("80 40")) @@ -281,57 +281,6 @@ object PromptLoggerTests extends TestSuite { } } - test("sequentialShortLived") { - if (!Util.windowsPlatform) { - // Make sure that when we have multiple sequential tasks being run on different threads, - // we still end up showing some kind of task in progress in the ticker, even though the - // tasks on each thread are short-lived enough they would not normally get shown if run - // alone. - @volatile var now = 0L - val (baos, promptLogger, prefixLogger) = setup(() => now, os.temp("80 40")) - - promptLogger.setPromptHeaderPrefix("123/456") - promptLogger.refreshPrompt() - check(promptLogger, baos)( - " [123/456] ========================== TITLE ==================================" - ) - promptLogger.setPromptLine(Seq("1"), "/456", "my-task") - - now += 100 - - promptLogger.refreshPrompt() - check(promptLogger, baos)( - " [123/456] ========================== TITLE ==================================" - ) - - promptLogger.removePromptLine(Seq("1")) - - val newTaskThread = new Thread(() => { - promptLogger.setPromptLine(Seq("2"), "/456", "my-task-new") - now += 100 - promptLogger.removePromptLine(Seq("2")) - }) - newTaskThread.start() - newTaskThread.join() - - promptLogger.refreshPrompt() - check(promptLogger, baos)( - " [123/456] ========================== TITLE ==================================" - ) - - val newTaskThread2 = new Thread(() => { - promptLogger.setPromptLine(Seq("2"), "/456", "my-task-new") - now += 100 - }) - newTaskThread2.start() - newTaskThread2.join() - promptLogger.refreshPrompt() - check(promptLogger, baos)( - " [123/456] ========================== TITLE ==================================", - "[2] my-task-new" - ) - } - } test("detail") { if (!Util.windowsPlatform) { // Make sure that when we have multiple sequential tasks being run on different threads, diff --git a/runner/client/src/mill/runner/client/MillClientMain.java b/runner/client/src/mill/runner/client/MillClientMain.java index e6ce1c37ca1..471b74713f2 100644 --- a/runner/client/src/mill/runner/client/MillClientMain.java +++ b/runner/client/src/mill/runner/client/MillClientMain.java @@ -1,79 +1,84 @@ package mill.runner.client; +import static mill.runner.client.MillProcessLauncher.millOptsFile; + import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; - +import mill.main.client.OutFiles; +import mill.main.client.ServerCouldNotBeStarted; import mill.main.client.ServerLauncher; import mill.main.client.Util; import mill.main.client.lock.Locks; -import mill.main.client.OutFiles; -import mill.main.client.ServerCouldNotBeStarted; - -import static mill.runner.client.MillProcessLauncher.millOptsFile; /** * This is a Java implementation to speed up repetitive starts. * A Scala implementation would result in the JVM loading much more classes almost doubling the start-up times. */ public class MillClientMain { - public static void main(String[] args) throws Exception { - boolean runNoServer = false; - if (args.length > 0) { - String firstArg = args[0]; - runNoServer = - Arrays.asList("--interactive", "--no-server", "--repl", "--bsp", "--help") - .contains(firstArg) || firstArg.startsWith("-i"); - } - if (!runNoServer) { - // WSL2 has the directory /run/WSL/ and WSL1 not. - String osVersion = System.getProperty("os.version"); - if(osVersion != null && (osVersion.contains("icrosoft") || osVersion.contains("WSL"))) { - // Server-Mode not supported under WSL1 - runNoServer = true; - } - } + public static void main(String[] args) throws Exception { + boolean runNoServer = false; + if (args.length > 0) { + String firstArg = args[0]; + runNoServer = Arrays.asList("--interactive", "--no-server", "--repl", "--bsp", "--help") + .contains(firstArg) + || firstArg.startsWith("-i"); + } + if (!runNoServer) { + // WSL2 has the directory /run/WSL/ and WSL1 not. + String osVersion = System.getProperty("os.version"); + if (osVersion != null && (osVersion.contains("icrosoft") || osVersion.contains("WSL"))) { + // Server-Mode not supported under WSL1 + runNoServer = true; + } + } - if (runNoServer) { - // start in no-server mode - MillNoServerLauncher.runMain(args); - } else try { - // start in client-server mode - java.util.List optsArgs = Util.readOptsFileLines(millOptsFile()); - Collections.addAll(optsArgs, args); + if (runNoServer) { + // start in no-server mode + MillNoServerLauncher.runMain(args); + } else + try { + // start in client-server mode + java.util.List optsArgs = Util.readOptsFileLines(millOptsFile()); + Collections.addAll(optsArgs, args); - ServerLauncher launcher = new ServerLauncher( - System.in, System.out, System.err, - System.getenv(), optsArgs.toArray(new String[0]), - null, -1 - ){ - public void initServer(Path serverDir, boolean setJnaNoSys, Locks locks) throws Exception{ - MillProcessLauncher.launchMillServer(serverDir, setJnaNoSys); - } - public void preRun(Path serverDir) throws Exception { - MillProcessLauncher.runTermInfoThread(serverDir); - } + ServerLauncher launcher = + new ServerLauncher( + System.in, + System.out, + System.err, + System.getenv(), + optsArgs.toArray(new String[0]), + null, + -1) { + public void initServer(Path serverDir, boolean setJnaNoSys, Locks locks) + throws Exception { + MillProcessLauncher.launchMillServer(serverDir, setJnaNoSys); + } + + public void preRun(Path serverDir) throws Exception { + MillProcessLauncher.runTermInfoThread(serverDir); + } }; - int exitCode = launcher.acquireLocksAndRun(OutFiles.out).exitCode; - if (exitCode == Util.ExitServerCodeWhenVersionMismatch()) { - exitCode = launcher.acquireLocksAndRun(OutFiles.out).exitCode; - } - System.exit(exitCode); - } catch (ServerCouldNotBeStarted e) { - // TODO: try to run in-process - System.err.println("Could not start a Mill server process.\n" + - "This could be caused by too many already running Mill instances " + - "or by an unsupported platform.\n" + e.getMessage() + "\n"); - if (MillNoServerLauncher.load().canLoad) { - System.err.println("Trying to run Mill in-process ..."); - MillNoServerLauncher.runMain(args); - } else { - System.err.println("Loading Mill in-process isn't possible.\n" + - "Please check your Mill installation!"); - throw e; - } + int exitCode = launcher.acquireLocksAndRun(OutFiles.out).exitCode; + if (exitCode == Util.ExitServerCodeWhenVersionMismatch()) { + exitCode = launcher.acquireLocksAndRun(OutFiles.out).exitCode; } - } - + System.exit(exitCode); + } catch (ServerCouldNotBeStarted e) { + // TODO: try to run in-process + System.err.println("Could not start a Mill server process.\n" + + "This could be caused by too many already running Mill instances " + + "or by an unsupported platform.\n" + + e.getMessage() + "\n"); + if (MillNoServerLauncher.load().canLoad) { + System.err.println("Trying to run Mill in-process ..."); + MillNoServerLauncher.runMain(args); + } else { + System.err.println( + "Loading Mill in-process isn't possible.\n" + "Please check your Mill installation!"); + throw e; + } + } + } } diff --git a/runner/client/src/mill/runner/client/MillNoServerLauncher.java b/runner/client/src/mill/runner/client/MillNoServerLauncher.java index b07655b8873..5fb56186258 100644 --- a/runner/client/src/mill/runner/client/MillNoServerLauncher.java +++ b/runner/client/src/mill/runner/client/MillNoServerLauncher.java @@ -5,51 +5,50 @@ class MillNoServerLauncher { - public static class LoadResult { + public static class LoadResult { - public final Optional millMainMethod; - public final boolean canLoad; - public final long loadTime; + public final Optional millMainMethod; + public final boolean canLoad; + public final long loadTime; - public LoadResult(Optional millMainMethod, final long loadTime) { - this.millMainMethod = millMainMethod; - this.canLoad = millMainMethod.isPresent(); - this.loadTime = loadTime; - } + public LoadResult(Optional millMainMethod, final long loadTime) { + this.millMainMethod = millMainMethod; + this.canLoad = millMainMethod.isPresent(); + this.loadTime = loadTime; } - - private static Optional canLoad = Optional.empty(); - - public static LoadResult load() { - if (canLoad.isPresent()) { - return canLoad.get(); - } else { - long startTime = System.currentTimeMillis(); - Optional millMainMethod = Optional.empty(); - try { - Class millMainClass = MillNoServerLauncher.class.getClassLoader().loadClass("mill.runner.MillMain"); - Method mainMethod = millMainClass.getMethod("main", String[].class); - millMainMethod = Optional.of(mainMethod); - } catch (ClassNotFoundException | NoSuchMethodException e) { - millMainMethod = Optional.empty(); - } - - long loadTime = System.currentTimeMillis() - startTime; - LoadResult result = new LoadResult(millMainMethod, loadTime); - canLoad = Optional.of(result); - return result; - } + } + + private static Optional canLoad = Optional.empty(); + + public static LoadResult load() { + if (canLoad.isPresent()) { + return canLoad.get(); + } else { + long startTime = System.currentTimeMillis(); + Optional millMainMethod = Optional.empty(); + try { + Class millMainClass = + MillNoServerLauncher.class.getClassLoader().loadClass("mill.runner.MillMain"); + Method mainMethod = millMainClass.getMethod("main", String[].class); + millMainMethod = Optional.of(mainMethod); + } catch (ClassNotFoundException | NoSuchMethodException e) { + millMainMethod = Optional.empty(); + } + + long loadTime = System.currentTimeMillis() - startTime; + LoadResult result = new LoadResult(millMainMethod, loadTime); + canLoad = Optional.of(result); + return result; } - - public static void runMain(String[] args) throws Exception { - LoadResult loadResult = load(); - if (loadResult.millMainMethod.isPresent()) { - int exitVal = MillProcessLauncher.launchMillNoServer(args); - System.exit(exitVal); - } else { - throw new RuntimeException("Cannot load mill.runner.MillMain class"); - } + } + + public static void runMain(String[] args) throws Exception { + LoadResult loadResult = load(); + if (loadResult.millMainMethod.isPresent()) { + int exitVal = MillProcessLauncher.launchMillNoServer(args); + System.exit(exitVal); + } else { + throw new RuntimeException("Cannot load mill.runner.MillMain class"); } - - + } } diff --git a/runner/client/src/mill/runner/client/MillProcessLauncher.java b/runner/client/src/mill/runner/client/MillProcessLauncher.java index d83e16b8fb2..c27d7bf3bdf 100644 --- a/runner/client/src/mill/runner/client/MillProcessLauncher.java +++ b/runner/client/src/mill/runner/client/MillProcessLauncher.java @@ -3,226 +3,214 @@ import static mill.main.client.OutFiles.*; import java.io.File; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; - -import mill.main.client.DebugLog; -import org.jline.terminal.TerminalBuilder; -import org.jline.terminal.Terminal; - -import mill.main.client.Util; -import mill.main.client.ServerFiles; import mill.main.client.EnvVars; +import mill.main.client.ServerFiles; +import mill.main.client.Util; +import org.jline.terminal.Terminal; +import org.jline.terminal.TerminalBuilder; public class MillProcessLauncher { - static int launchMillNoServer(String[] args) throws Exception { - final boolean setJnaNoSys = System.getProperty("jna.nosys") == null; - final String sig = String.format("%08x", UUID.randomUUID().hashCode()); - final Path processDir = Paths.get(".").resolve(out).resolve(millNoServer).resolve(sig); - - final List l = new ArrayList<>(); - l.addAll(millLaunchJvmCommand(setJnaNoSys)); - l.add("mill.runner.MillMain"); - l.add(processDir.toAbsolutePath().toString()); - l.addAll(Util.readOptsFileLines(millOptsFile())); - l.addAll(Arrays.asList(args)); - - final ProcessBuilder builder = new ProcessBuilder() - .command(l) - .inheritIO(); - - boolean interrupted = false; - - try { - Process p = configureRunMillProcess(builder, processDir); - MillProcessLauncher.runTermInfoThread(processDir); - return p.waitFor(); - - } catch (InterruptedException e) { - interrupted = true; - throw e; - } finally { - if (!interrupted) { - // cleanup if process terminated for sure - Files.walk(processDir) - // depth-first - .sorted(Comparator.reverseOrder()) - .forEach(p -> p.toFile().delete()); - } - } + static int launchMillNoServer(String[] args) throws Exception { + final boolean setJnaNoSys = System.getProperty("jna.nosys") == null; + final String sig = String.format("%08x", UUID.randomUUID().hashCode()); + final Path processDir = Paths.get(".").resolve(out).resolve(millNoServer).resolve(sig); + + final List l = new ArrayList<>(); + l.addAll(millLaunchJvmCommand(setJnaNoSys)); + l.add("mill.runner.MillMain"); + l.add(processDir.toAbsolutePath().toString()); + l.addAll(Util.readOptsFileLines(millOptsFile())); + l.addAll(Arrays.asList(args)); + + final ProcessBuilder builder = new ProcessBuilder().command(l).inheritIO(); + + boolean interrupted = false; + + try { + Process p = configureRunMillProcess(builder, processDir); + MillProcessLauncher.runTermInfoThread(processDir); + return p.waitFor(); + + } catch (InterruptedException e) { + interrupted = true; + throw e; + } finally { + if (!interrupted) { + // cleanup if process terminated for sure + Files.walk(processDir) + // depth-first + .sorted(Comparator.reverseOrder()) + .forEach(p -> p.toFile().delete()); + } } + } - static void launchMillServer(Path serverDir, boolean setJnaNoSys) throws Exception { - List l = new ArrayList<>(); - l.addAll(millLaunchJvmCommand(setJnaNoSys)); - l.add("mill.runner.MillServerMain"); - l.add(serverDir.toFile().getCanonicalPath()); + static void launchMillServer(Path serverDir, boolean setJnaNoSys) throws Exception { + List l = new ArrayList<>(); + l.addAll(millLaunchJvmCommand(setJnaNoSys)); + l.add("mill.runner.MillServerMain"); + l.add(serverDir.toFile().getCanonicalPath()); - ProcessBuilder builder = new ProcessBuilder() - .command(l) - .redirectOutput(serverDir.resolve(ServerFiles.stdout).toFile()) - .redirectError(serverDir.resolve(ServerFiles.stderr).toFile()); + ProcessBuilder builder = new ProcessBuilder() + .command(l) + .redirectOutput(serverDir.resolve(ServerFiles.stdout).toFile()) + .redirectError(serverDir.resolve(ServerFiles.stderr).toFile()); - configureRunMillProcess(builder, serverDir); - } + configureRunMillProcess(builder, serverDir); + } - static Process configureRunMillProcess( - ProcessBuilder builder, - Path serverDir - ) throws Exception { + static Process configureRunMillProcess(ProcessBuilder builder, Path serverDir) throws Exception { - Path sandbox = serverDir.resolve(ServerFiles.sandbox); - Files.createDirectories(sandbox); - builder.environment().put(EnvVars.MILL_WORKSPACE_ROOT, new File("").getCanonicalPath()); + Path sandbox = serverDir.resolve(ServerFiles.sandbox); + Files.createDirectories(sandbox); + builder.environment().put(EnvVars.MILL_WORKSPACE_ROOT, new File("").getCanonicalPath()); - builder.directory(sandbox.toFile()); - return builder.start(); - } + builder.directory(sandbox.toFile()); + return builder.start(); + } - static File millJvmOptsFile() { - String millJvmOptsPath = System.getenv(EnvVars.MILL_JVM_OPTS_PATH); - if (millJvmOptsPath == null || millJvmOptsPath.trim().equals("")) { - millJvmOptsPath = ".mill-jvm-opts"; - } - return new File(millJvmOptsPath).getAbsoluteFile(); + static File millJvmOptsFile() { + String millJvmOptsPath = System.getenv(EnvVars.MILL_JVM_OPTS_PATH); + if (millJvmOptsPath == null || millJvmOptsPath.trim().equals("")) { + millJvmOptsPath = ".mill-jvm-opts"; } + return new File(millJvmOptsPath).getAbsoluteFile(); + } - static File millOptsFile() { - String millJvmOptsPath = System.getenv(EnvVars.MILL_OPTS_PATH); - if (millJvmOptsPath == null || millJvmOptsPath.trim().equals("")) { - millJvmOptsPath = ".mill-opts"; - } - return new File(millJvmOptsPath).getAbsoluteFile(); + static File millOptsFile() { + String millJvmOptsPath = System.getenv(EnvVars.MILL_OPTS_PATH); + if (millJvmOptsPath == null || millJvmOptsPath.trim().equals("")) { + millJvmOptsPath = ".mill-opts"; } - - static boolean millJvmOptsAlreadyApplied() { - final String propAppliedProp = System.getProperty("mill.jvm_opts_applied"); - return propAppliedProp != null && propAppliedProp.equals("true"); + return new File(millJvmOptsPath).getAbsoluteFile(); + } + + static boolean millJvmOptsAlreadyApplied() { + final String propAppliedProp = System.getProperty("mill.jvm_opts_applied"); + return propAppliedProp != null && propAppliedProp.equals("true"); + } + + static String millServerTimeout() { + return System.getenv(EnvVars.MILL_SERVER_TIMEOUT_MILLIS); + } + + static boolean isWin() { + return System.getProperty("os.name", "").startsWith("Windows"); + } + + static String javaExe() { + final String javaHome = System.getProperty("java.home"); + if (javaHome != null && !javaHome.isEmpty()) { + final File exePath = new File( + javaHome + File.separator + "bin" + File.separator + "java" + (isWin() ? ".exe" : "")); + if (exePath.exists()) { + return exePath.getAbsolutePath(); + } } - - static String millServerTimeout() { - return System.getenv(EnvVars.MILL_SERVER_TIMEOUT_MILLIS); + return "java"; + } + + static String[] millClasspath() throws Exception { + String selfJars = ""; + List vmOptions = new LinkedList<>(); + String millOptionsPath = System.getProperty("MILL_OPTIONS_PATH"); + if (millOptionsPath != null) { + + // read MILL_CLASSPATH from file MILL_OPTIONS_PATH + Properties millProps = new Properties(); + try (InputStream is = Files.newInputStream(Paths.get(millOptionsPath))) { + millProps.load(is); + } catch (IOException e) { + throw new RuntimeException("Could not load '" + millOptionsPath + "'", e); + } + + for (final String k : millProps.stringPropertyNames()) { + String propValue = millProps.getProperty(k); + if ("MILL_CLASSPATH".equals(k)) { + selfJars = propValue; + } + } + } else { + // read MILL_CLASSPATH from file sys props + selfJars = System.getProperty("MILL_CLASSPATH"); } - static boolean isWin() { - return System.getProperty("os.name", "").startsWith("Windows"); + if (selfJars == null || selfJars.trim().isEmpty()) { + // We try to use the currently local classpath as MILL_CLASSPATH + selfJars = System.getProperty("java.class.path").replace(File.pathSeparator, ","); } - static String javaExe() { - final String javaHome = System.getProperty("java.home"); - if (javaHome != null && !javaHome.isEmpty()) { - final File exePath = new File( - javaHome + File.separator + - "bin" + File.separator + - "java" + (isWin() ? ".exe" : "") - ); - if (exePath.exists()) { - return exePath.getAbsolutePath(); - } - } - return "java"; + if (selfJars == null || selfJars.trim().isEmpty()) { + throw new RuntimeException("MILL_CLASSPATH is empty!"); + } + String[] selfJarsArray = selfJars.split("[,]"); + for (int i = 0; i < selfJarsArray.length; i++) { + selfJarsArray[i] = new java.io.File(selfJarsArray[i]).getCanonicalPath(); } + return selfJarsArray; + } - static String[] millClasspath() throws Exception { - String selfJars = ""; - List vmOptions = new LinkedList<>(); - String millOptionsPath = System.getProperty("MILL_OPTIONS_PATH"); - if (millOptionsPath != null) { - - // read MILL_CLASSPATH from file MILL_OPTIONS_PATH - Properties millProps = new Properties(); - try (InputStream is = Files.newInputStream(Paths.get(millOptionsPath))) { - millProps.load(is); - } catch (IOException e) { - throw new RuntimeException("Could not load '" + millOptionsPath + "'", e); - } + static List millLaunchJvmCommand(boolean setJnaNoSys) throws Exception { + final List vmOptions = new ArrayList<>(); - for (final String k : millProps.stringPropertyNames()) { - String propValue = millProps.getProperty(k); - if ("MILL_CLASSPATH".equals(k)) { - selfJars = propValue; - } - } - } else { - // read MILL_CLASSPATH from file sys props - selfJars = System.getProperty("MILL_CLASSPATH"); - } + // Java executable + vmOptions.add(javaExe()); - if (selfJars == null || selfJars.trim().isEmpty()) { - // We try to use the currently local classpath as MILL_CLASSPATH - selfJars = System.getProperty("java.class.path").replace(File.pathSeparator, ","); - } - - if (selfJars == null || selfJars.trim().isEmpty()) { - throw new RuntimeException("MILL_CLASSPATH is empty!"); - } - String[] selfJarsArray = selfJars.split("[,]"); - for (int i = 0; i < selfJarsArray.length; i++) { - selfJarsArray[i] = new java.io.File(selfJarsArray[i]).getCanonicalPath(); - } - return selfJarsArray; + // jna + if (setJnaNoSys) { + vmOptions.add("-Djna.nosys=true"); } - static List millLaunchJvmCommand(boolean setJnaNoSys) throws Exception { - final List vmOptions = new ArrayList<>(); - - // Java executable - vmOptions.add(javaExe()); - - // jna - if (setJnaNoSys) { - vmOptions.add("-Djna.nosys=true"); - } + // sys props + final Properties sysProps = System.getProperties(); + for (final String k : sysProps.stringPropertyNames()) { + if (k.startsWith("MILL_") && !"MILL_CLASSPATH".equals(k)) { + vmOptions.add("-D" + k + "=" + sysProps.getProperty(k)); + } + } - // sys props - final Properties sysProps = System.getProperties(); - for (final String k : sysProps.stringPropertyNames()) { - if (k.startsWith("MILL_") && !"MILL_CLASSPATH".equals(k)) { - vmOptions.add("-D" + k + "=" + sysProps.getProperty(k)); - } - } + String serverTimeout = millServerTimeout(); + if (serverTimeout != null) vmOptions.add("-D" + "mill.server_timeout" + "=" + serverTimeout); - String serverTimeout = millServerTimeout(); - if (serverTimeout != null) vmOptions.add("-D" + "mill.server_timeout" + "=" + serverTimeout); + // extra opts + File millJvmOptsFile = millJvmOptsFile(); + if (millJvmOptsFile.exists()) { + vmOptions.addAll(Util.readOptsFileLines(millJvmOptsFile)); + } - // extra opts - File millJvmOptsFile = millJvmOptsFile(); - if (millJvmOptsFile.exists()) { - vmOptions.addAll(Util.readOptsFileLines(millJvmOptsFile)); - } + vmOptions.add("-cp"); + vmOptions.add(String.join(File.pathSeparator, millClasspath())); - vmOptions.add("-cp"); - vmOptions.add(String.join(File.pathSeparator, millClasspath())); + return vmOptions; + } - return vmOptions; - } + static List readMillJvmOpts() { + return Util.readOptsFileLines(millJvmOptsFile()); + } - static List readMillJvmOpts() { - return Util.readOptsFileLines(millJvmOptsFile()); - } + public static void runTermInfoThread(Path serverDir) throws Exception { + Terminal term = TerminalBuilder.builder().dumb(true).build(); + Thread termInfoPropagatorThread = new Thread( + () -> { + try { + while (true) { + Files.write( + serverDir.resolve(ServerFiles.terminfo), + (term.getWidth() + " " + term.getHeight()).getBytes()); - public static void runTermInfoThread(Path serverDir) throws Exception{ - Terminal term = TerminalBuilder.builder().dumb(true).build(); - Thread termInfoPropagatorThread = new Thread( - () -> { - try { - while(true){ - Files.write( - serverDir.resolve(ServerFiles.terminfo), - (term.getWidth() + " " + term.getHeight()).getBytes() - ); - - Thread.sleep(100); - } - }catch (Exception e){} - }, - "TermInfoPropagatorThread" - ); - termInfoPropagatorThread.start(); - } + Thread.sleep(100); + } + } catch (Exception e) { + } + }, + "TermInfoPropagatorThread"); + termInfoPropagatorThread.start(); + } } diff --git a/scalalib/backgroundwrapper/src/mill/scalalib/backgroundwrapper/BackgroundWrapper.java b/scalalib/backgroundwrapper/src/mill/scalalib/backgroundwrapper/BackgroundWrapper.java index 5e4c39c24ae..dbbcff8d34c 100644 --- a/scalalib/backgroundwrapper/src/mill/scalalib/backgroundwrapper/BackgroundWrapper.java +++ b/scalalib/backgroundwrapper/src/mill/scalalib/backgroundwrapper/BackgroundWrapper.java @@ -1,38 +1,38 @@ package mill.scalalib.backgroundwrapper; public class BackgroundWrapper { - public static void main(String[] args) throws Exception{ - String watched = args[0]; - String tombstone = args[1]; - String expected = args[2]; - Thread watcher = new Thread(new Runnable() { - @Override - public void run() { - while (true) { - try{ - Thread.sleep(50); - String token = java.nio.file.Files.readString(java.nio.file.Paths.get(watched)); - if (!token.equals(expected)) { - new java.io.File(tombstone).createNewFile(); - System.exit(0); - } - }catch(Exception e){ - try { - new java.io.File(tombstone).createNewFile(); - }catch(Exception e2){} - System.exit(0); - } - - } + public static void main(String[] args) throws Exception { + String watched = args[0]; + String tombstone = args[1]; + String expected = args[2]; + Thread watcher = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + Thread.sleep(50); + String token = java.nio.file.Files.readString(java.nio.file.Paths.get(watched)); + if (!token.equals(expected)) { + new java.io.File(tombstone).createNewFile(); + System.exit(0); + } + } catch (Exception e) { + try { + new java.io.File(tombstone).createNewFile(); + } catch (Exception e2) { } - }); - watcher.setDaemon(true); - watcher.start(); - String realMain = args[3]; - String[] realArgs = new String[args.length - 4]; - for(int i = 0; i < args.length-4; i++){ - realArgs[i] = args[i+4]; + System.exit(0); + } } - Class.forName(realMain).getMethod("main", String[].class).invoke(null, (Object)realArgs); + } + }); + watcher.setDaemon(true); + watcher.start(); + String realMain = args[3]; + String[] realArgs = new String[args.length - 4]; + for (int i = 0; i < args.length - 4; i++) { + realArgs[i] = args[i + 4]; } + Class.forName(realMain).getMethod("main", String[].class).invoke(null, (Object) realArgs); + } } diff --git a/testrunner/entrypoint/src/mill/testrunner/entrypoint/TestRunnerMain.java b/testrunner/entrypoint/src/mill/testrunner/entrypoint/TestRunnerMain.java index 046c3735dc3..11c6929105e 100644 --- a/testrunner/entrypoint/src/mill/testrunner/entrypoint/TestRunnerMain.java +++ b/testrunner/entrypoint/src/mill/testrunner/entrypoint/TestRunnerMain.java @@ -1,10 +1,9 @@ package mill.testrunner.entrypoint; import java.lang.reflect.Method; -import java.lang.reflect.Parameter; -import java.net.URLClassLoader; -import java.net.URL; import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; import java.util.stream.Stream; /** @@ -15,30 +14,31 @@ * nested classloaders. */ public class TestRunnerMain { - public static void main(String[] args) throws Exception { - URL[] testRunnerClasspath = - Stream.of(args[0].split(",")).map(s -> { - try { - return new URL(s); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - }).toArray(URL[]::new); + public static void main(String[] args) throws Exception { + URL[] testRunnerClasspath = Stream.of(args[0].split(",")) + .map(s -> { + try { + return new URL(s); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + }) + .toArray(URL[]::new); - URLClassLoader cl = new URLClassLoader(testRunnerClasspath, null) { - public Class findClass(String name) throws ClassNotFoundException { - if (name.startsWith("sbt.testing")) { - return TestRunnerMain.class.getClassLoader().loadClass(name); - } else { - return super.findClass(name); - } - } - }; + URLClassLoader cl = new URLClassLoader(testRunnerClasspath, null) { + public Class findClass(String name) throws ClassNotFoundException { + if (name.startsWith("sbt.testing")) { + return TestRunnerMain.class.getClassLoader().loadClass(name); + } else { + return super.findClass(name); + } + } + }; - Class testRunnerCls = cl.loadClass("mill.testrunner.TestRunnerMain0"); - Method mainMethod = testRunnerCls.getMethod("main0", String[].class, ClassLoader.class); + Class testRunnerCls = cl.loadClass("mill.testrunner.TestRunnerMain0"); + Method mainMethod = testRunnerCls.getMethod("main0", String[].class, ClassLoader.class); - // Wrap in String[][] to counter varargs expansion - mainMethod.invoke(null, args, TestRunnerMain.class.getClassLoader()); - } + // Wrap in String[][] to counter varargs expansion + mainMethod.invoke(null, args, TestRunnerMain.class.getClassLoader()); + } }