diff --git a/build.gradle b/build.gradle index 814beacb..74e59006 100644 --- a/build.gradle +++ b/build.gradle @@ -29,6 +29,10 @@ repositories { mavenLocal() } +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} if (project.hasProperty('mainClass')) { mainClassName = project.getProperty('mainClass') @@ -119,7 +123,25 @@ dependencies { implementation('org.jgrapht:jgrapht-ext:1.5.2') implementation('com.github.javaparser:javaparser-symbol-solver-core:3.25.9') - testImplementation group: 'junit', name: 'junit', version: '4.13.2' + // TestContainers + testImplementation 'org.testcontainers:testcontainers:1.19.3' + testImplementation 'org.testcontainers:junit-jupiter:1.19.3' + + // JUnit 5 + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.1' + testImplementation 'org.junit.jupiter:junit-jupiter-params:5.10.1' // for @ParameterizedTest + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.10.1' + + // SLF4J - for TestContainers logging + testImplementation 'org.slf4j:slf4j-api:2.0.9' + testImplementation 'org.slf4j:slf4j-simple:2.0.9' + +} + +test { + useJUnitPlatform() + // Optional: Enable TestContainers reuse to speed up tests + systemProperty 'testcontainers.reuse.enable', 'true' } task fatJar(type: Jar) { diff --git a/gradle.properties b/gradle.properties index cc8f4774..619a0679 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1 +1,2 @@ -version=1.0.10 +version=1.1.0 + diff --git a/src/main/java/com/ibm/cldk/SystemDependencyGraph.java b/src/main/java/com/ibm/cldk/SystemDependencyGraph.java index 950c3c6d..f252d01d 100644 --- a/src/main/java/com/ibm/cldk/SystemDependencyGraph.java +++ b/src/main/java/com/ibm/cldk/SystemDependencyGraph.java @@ -206,7 +206,7 @@ public static String construct( // Initialize scope AnalysisScope scope = ScopeUtils.createScope(input, dependencies, build); - IClassHierarchy cha = ClassHierarchyFactory.make(scope, + IClassHierarchy cha = ClassHierarchyFactory.makeWithRoot(scope, new ECJClassLoaderFactory(scope.getExclusions())); Log.done("There were a total of " + cha.getNumberOfClasses() + " classes of which " + AnalysisUtils.getNumberOfApplicationClasses(cha) + " are application classes."); diff --git a/src/main/java/com/ibm/cldk/utils/BuildProject.java b/src/main/java/com/ibm/cldk/utils/BuildProject.java index 917d2cf0..9a426b4f 100644 --- a/src/main/java/com/ibm/cldk/utils/BuildProject.java +++ b/src/main/java/com/ibm/cldk/utils/BuildProject.java @@ -9,6 +9,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.text.MessageFormat; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; @@ -22,22 +23,17 @@ public class BuildProject { public static Path libDownloadPath; private static final String LIB_DEPS_DOWNLOAD_DIR = "_library_dependencies"; private static final String MAVEN_CMD = BuildProject.getMavenCommand(); - private static final String GRADLE_CMD = BuildProject.getGradleCmd(); + private static final String GRADLE_CMD = BuildProject.getGradleCommand(); /** * Gets the maven command to be used for building the project. * * @return the maven command */ - private static String getMavenCommand() { - Boolean isWindows = System.getProperty("os.name").toLowerCase().contains("windows"); - String mvnCommand; - if (isWindows) { - mvnCommand = new File(projectRootPom, "mvnw.cmd").exists() ? String.valueOf(new File(projectRootPom, "mvnw.cmd")) : "mvn.cmd"; - } else { - mvnCommand = new File(projectRootPom, "mvnw").exists() ? String.valueOf(new File(projectRootPom, "mvnw")) : "mvn"; - } - return mvnCommand; + public static String getMavenCommand() { + String mvnSystemCommand = Arrays.stream(System.getenv("PATH").split(System.getProperty("path.separator"))).map(path -> new File(path, System.getProperty("os.name").toLowerCase().contains("windows") ? "mvn.cmd" : "mvn")).filter(File::exists).findFirst().map(File::getAbsolutePath).orElse(null); + File mvnWrapper = System.getProperty("os.name").toLowerCase().contains("windows") ? new File(projectRootPom, "mvnw.cmd") : new File(projectRootPom, "mvnw"); + return commandExists(mvnWrapper).getKey() ? mvnWrapper.toString() : mvnSystemCommand; } /** @@ -45,24 +41,15 @@ private static String getMavenCommand() { * * @return the gradle command */ - private static String getGradleCmd() { - String GRADLE_CMD; - String osName = System.getProperty("os.name").toLowerCase(); - boolean isWindows = osName.contains("windows"); - String gradleWrapper = isWindows ? "gradlew.bat" : "gradlew"; - String gradle = isWindows ? "gradle.bat" : "gradle"; - - String gradleWrapperExists = new File(projectRootPom, gradleWrapper).exists() ? "true" : "false"; + public static String getGradleCommand() { + String gradleSystemCommand = Arrays.stream(System.getenv("PATH").split(System.getProperty("path.separator"))).map(path -> new File(path, System.getProperty("os.name").toLowerCase().contains("windows") ? "gradle.bat" : "gradle")).filter(File::exists).findFirst().map(File::getAbsolutePath).orElse(null); + File gradleWrapper = System.getProperty("os.name").toLowerCase().contains("windows") ? new File(projectRootPom, "gradlew.bat") : new File(projectRootPom, "gradlew"); - if (new File(projectRootPom, gradleWrapper).exists()) { - GRADLE_CMD = String.valueOf(new File(projectRootPom, gradleWrapper)); - } else { - GRADLE_CMD = gradle; - } - return GRADLE_CMD; + return commandExists(gradleWrapper).getKey() ? gradleWrapper.toString() : gradleSystemCommand; } - public static Path tempInitScript; + public static Path tempInitScript; + static { try { tempInitScript = Files.createTempFile("gradle-init-", ".gradle"); @@ -71,63 +58,39 @@ private static String getGradleCmd() { } } - private static final String GRADLE_DEPENDENCIES_TASK = "allprojects { afterEvaluate { project -> task downloadDependencies(type: Copy) {\n" + - " def configs = project.configurations.findAll { it.canBeResolved }\n\n" + - " dependsOn configs\n" + - " from configs\n" + - " into project.hasProperty('outputDir') ? project.property('outputDir') : \"${project.buildDir}/libs\"\n\n" + - " doFirst {\n" + - " println \"Downloading dependencies for project ${project.name} to: ${destinationDir}\"\n" + - " configs.each { config ->\n" + - " println \"Configuration: ${config.name}\"\n" + - " config.resolvedConfiguration.resolvedArtifacts.each { artifact ->\n" + - " println \"\t${artifact.moduleVersion.id}:${artifact.extension}\"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - "}"; + private static final String GRADLE_DEPENDENCIES_TASK = "allprojects { afterEvaluate { project -> task downloadDependencies(type: Copy) {\n" + " def configs = project.configurations.findAll { it.canBeResolved }\n\n" + " dependsOn configs\n" + " from configs\n" + " into project.hasProperty('outputDir') ? project.property('outputDir') : \"${project.buildDir}/libs\"\n\n" + " doFirst {\n" + " println \"Downloading dependencies for project ${project.name} to: ${destinationDir}\"\n" + " configs.each { config ->\n" + " println \"Configuration: ${config.name}\"\n" + " config.resolvedConfiguration.resolvedArtifacts.each { artifact ->\n" + " println \"\t${artifact.moduleVersion.id}:${artifact.extension}\"\n" + " }\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}"; - private static AbstractMap.SimpleEntry commandExists(String command) { + private static AbstractMap.SimpleEntry commandExists(File command) { StringBuilder output = new StringBuilder(); + if (!command.exists()) { + return new AbstractMap.SimpleEntry<>(false, MessageFormat.format("Command {0} does not exist.", command)); + } try { - Process process = new ProcessBuilder().directory(new File(projectRootPom)).command(command, "--version").start(); + Process process = new ProcessBuilder().directory(new File(projectRootPom)).command(String.valueOf(command), "--version").start(); // Read the output stream - BufferedReader reader = new BufferedReader( - new InputStreamReader(process.getInputStream()) - ); + BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { output.append(line).append("\n"); } // Read the error stream - BufferedReader errorReader = new BufferedReader( - new InputStreamReader(process.getErrorStream()) - ); + BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); while ((line = errorReader.readLine()) != null) { output.append(line).append("\n"); } - int exitCode = process.waitFor(); - return new AbstractMap.SimpleEntry<>( - exitCode == 0, - output.toString().trim() - ); + return new AbstractMap.SimpleEntry<>(exitCode == 0, output.toString().trim()); } catch (IOException | InterruptedException exceptions) { - return new AbstractMap.SimpleEntry<>( - false, - exceptions.getMessage() - ); + Log.error(exceptions.getMessage()); + return new AbstractMap.SimpleEntry<>(false, exceptions.getMessage()); } } private static boolean buildWithTool(String[] buildCommand) { Log.info("Building the project using " + buildCommand[0] + "."); ProcessBuilder processBuilder = new ProcessBuilder().directory(new File(projectRootPom)).command(buildCommand); - try { Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); @@ -157,7 +120,6 @@ private static boolean isMavenInstalled() { BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = reader.readLine(); // Read the first line of the output if (line != null && line.contains("Apache Maven")) { - Log.info("Maven is installed: " + line); return true; } } catch (IOException e) { @@ -179,11 +141,7 @@ private static boolean mavenBuild(String projectPath) { Log.info("Checking if Maven is installed."); return false; } - String[] mavenCommand = { - MAVEN_CMD, "clean", "compile", "-f", projectPath + "/pom.xml", "-B", "-V", "-e", "-Drat.skip", - "-Dfindbugs.skip", "-Dcheckstyle.skip", "-Dpmd.skip=true", "-Dspotbugs.skip", "-Denforcer.skip", - "-Dmaven.javadoc.skip", "-DskipTests", "-Dmaven.test.skip.exec", "-Dlicense.skip=true", - "-Drat.skip=true", "-Dspotless.check.skip=true"}; + String[] mavenCommand = {MAVEN_CMD, "clean", "compile", "-f", projectPath + "/pom.xml", "-B", "-V", "-e", "-Drat.skip", "-Dfindbugs.skip", "-Dcheckstyle.skip", "-Dpmd.skip=true", "-Dspotbugs.skip", "-Denforcer.skip", "-Dmaven.javadoc.skip", "-DskipTests", "-Dmaven.test.skip.exec", "-Dlicense.skip=true", "-Drat.skip=true", "-Dspotless.check.skip=true"}; return buildWithTool(mavenCommand); } @@ -193,8 +151,7 @@ public static boolean gradleBuild(String projectPath) { String[] gradleCommand; if (GRADLE_CMD.equals("gradlew") || GRADLE_CMD.equals("gradlew.bat")) { gradleCommand = new String[]{projectPath + File.separator + GRADLE_CMD, "clean", "compileJava", "-p", projectPath}; - } - else { + } else { gradleCommand = new String[]{GRADLE_CMD, "clean", "compileJava", "-p", projectPath}; } return buildWithTool(gradleCommand); @@ -252,31 +209,38 @@ public static boolean downloadLibraryDependencies(String projectPath, String pro } File pomFile = new File(projectRoot, "pom.xml"); if (pomFile.exists()) { + if (MAVEN_CMD == null || !commandExists(new File(MAVEN_CMD)).getKey()) { + String msg = MAVEN_CMD == null ? + "Could not find Maven or a valid Maven Wrapper" : + MessageFormat.format("Could not verify that {0} exists", MAVEN_CMD); + Log.error(msg); + throw new IllegalStateException("Unable to execute Maven command. " + + (MAVEN_CMD == null ? + "Could not find Maven or a valid Maven Wrapper" : + "Attempt failed with message\n" + commandExists(new File(MAVEN_CMD)).getValue() + )); + } Log.info("Found pom.xml in the project directory. Using Maven to download dependencies."); - AbstractMap.SimpleEntry mavenCheck = commandExists(MAVEN_CMD); - if (!mavenCheck.getKey()) - throw new IllegalStateException("Unable to execute Maven command. Attempt failed with message\n" + mavenCheck.getValue()); - - String[] mavenCommand = { - MAVEN_CMD, "--no-transfer-progress", "-f", - Paths.get(projectRoot, "pom.xml").toString(), - "dependency:copy-dependencies", - "-DoutputDirectory=" + libDownloadPath.toString() - }; + String[] mavenCommand = {MAVEN_CMD, "--no-transfer-progress", "-f", Paths.get(projectRoot, "pom.xml").toString(), "dependency:copy-dependencies", "-DoutputDirectory=" + libDownloadPath.toString()}; return buildWithTool(mavenCommand); } else if (new File(projectRoot, "build.gradle").exists() || new File(projectRoot, "build.gradle.kts").exists()) { - Log.info("Found build.gradle or build.gradle.kts in the project directory. Using gradle to download dependencies."); - AbstractMap.SimpleEntry gradleCheck = commandExists(GRADLE_CMD); - if (!gradleCheck.getKey()) - throw new IllegalStateException("Could not execute Gradle command. Attempt failed with message\n" + gradleCheck.getValue()); - - Log.info("Found build.gradle[.kts] in the project directory. Using Gradle to download dependencies."); + if (GRADLE_CMD == null || !commandExists(new File(GRADLE_CMD)).getKey()) { + String msg = GRADLE_CMD == null ? + "Could not find Gradle or valid Gradle Wrapper" : + MessageFormat.format("Could not verify that {0} exists", GRADLE_CMD); + Log.error(msg); + throw new IllegalStateException("Unable to execute Maven command. " + + (GRADLE_CMD == null ? + "Could not find Gradle or valid Gradle Wrapper" : + "Attempt failed with message\n" + commandExists(new File(GRADLE_CMD)).getValue() + )); + } + Log.info("Found build.gradle or build.gradle.kts in the project directory. Using Gradle to download dependencies."); tempInitScript = Files.writeString(tempInitScript, GRADLE_DEPENDENCIES_TASK); String[] gradleCommand; if (GRADLE_CMD.equals("gradlew") || GRADLE_CMD.equals("gradlew.bat")) { gradleCommand = new String[]{projectRoot + File.separator + GRADLE_CMD, "--init-script", tempInitScript.toFile().getAbsolutePath(), "downloadDependencies", "-PoutputDir=" + libDownloadPath.toString()}; - } - else { + } else { gradleCommand = new String[]{GRADLE_CMD, "--init-script", tempInitScript.toFile().getAbsolutePath(), "downloadDependencies", "-PoutputDir=" + libDownloadPath.toString()}; } return buildWithTool(gradleCommand); @@ -288,10 +252,7 @@ public static void cleanLibraryDependencies() { if (libDownloadPath != null) { Log.info("Cleaning up library dependency directory: " + libDownloadPath); try { - Files.walk(libDownloadPath) - .filter(Files::isRegularFile) - .map(Path::toFile) - .forEach(File::delete); + Files.walk(libDownloadPath).filter(Files::isRegularFile).map(Path::toFile).forEach(File::delete); Files.delete(libDownloadPath); } catch (IOException e) { Log.error("Error deleting library dependency directory: " + e.getMessage()); diff --git a/src/main/java/com/ibm/cldk/utils/ScopeUtils.java b/src/main/java/com/ibm/cldk/utils/ScopeUtils.java index 7572a16a..3daa2790 100644 --- a/src/main/java/com/ibm/cldk/utils/ScopeUtils.java +++ b/src/main/java/com/ibm/cldk/utils/ScopeUtils.java @@ -21,6 +21,7 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.FileVisitOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -28,6 +29,7 @@ import java.util.Objects; import java.util.UUID; import java.util.jar.JarFile; +import java.util.stream.Stream; import org.apache.commons.io.FileUtils; @@ -70,7 +72,7 @@ public static AnalysisScope createScope(String projectPath, String applicationDe throw new RuntimeException("JAVA_HOME is not set."); } - String[] stdlibs = Files.walk(Paths.get(System.getenv("JAVA_HOME"), "jmods")) + String[] stdlibs = Files.walk(getJmodsPath()) .filter(path -> path.toString().endsWith(".jmod")) .map(path -> path.toAbsolutePath().toString()) .toArray(String[]::new); @@ -130,6 +132,19 @@ public static AnalysisScope createScope(String projectPath, String applicationDe return scope; } + private static Path getJmodsPath() { + try { + try (Stream paths = Files.walk(Path.of(System.getenv("JAVA_HOME")), Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS)) { + return paths + .filter(path -> path.getFileName().toString().equals("jmods")) + .findFirst() + .orElseThrow(() -> new RuntimeException("jmods directory not found in " + System.getenv("JAVA_HOME"))); + } + } catch (IOException e) { + throw new RuntimeException("Error searching for jmods directory", e); + } + } + private static AnalysisScope addDefaultExclusions(AnalysisScope scope) throws IOException { Log.info("Add exclusions to scope."); diff --git a/src/test/java/com/ibm/cldk/CodeAnalyzerIntegrationTest.java b/src/test/java/com/ibm/cldk/CodeAnalyzerIntegrationTest.java new file mode 100644 index 00000000..9183dc04 --- /dev/null +++ b/src/test/java/com/ibm/cldk/CodeAnalyzerIntegrationTest.java @@ -0,0 +1,148 @@ +package com.ibm.cldk; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Assertions; +import org.testcontainers.containers.BindMode; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.MountableFile; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.MessageFormat; +import java.util.Properties; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +@Testcontainers +@SuppressWarnings("resource") +public class CodeAnalyzerIntegrationTest { + + /** + * Creates a Java 11 test container that mounts the build/libs folder. + */ + static String codeanalyzerVersion; + static final String javaVersion = "17"; + + static { + // Build project first + try { + Process process = new ProcessBuilder("./gradlew", "fatJar") + .directory(new File(System.getProperty("user.dir"))) + .start(); + if (process.waitFor() != 0) { + throw new RuntimeException("Build failed"); + } + } catch (IOException | InterruptedException e) { + throw new RuntimeException("Failed to build codeanalyzer", e); + } + } + + @Container + static final GenericContainer container = new GenericContainer<>("openjdk:17-jdk") + .withCreateContainerCmdModifier(cmd -> cmd.withEntrypoint("sh")) + .withCommand("-c", "while true; do sleep 1; done") + .withFileSystemBind( + String.valueOf(Paths.get(System.getProperty("user.dir")).resolve("build/libs")), + "/opt/jars", + BindMode.READ_WRITE) + .withCopyFileToContainer(MountableFile.forHostPath(Paths.get(System.getProperty("user.dir")).resolve("build/libs")), "/opt/jars") + .withCopyFileToContainer(MountableFile.forHostPath(Paths.get(System.getProperty("user.dir")).resolve("src/test/resources/test-applications/mvnw-corrupt-test")), "/test-applications/mvnw-corrupt-test") + .withCopyFileToContainer(MountableFile.forHostPath(Paths.get(System.getProperty("user.dir")).resolve("src/test/resources/test-applications/mvnw-working-test")), "/test-applications/mvnw-working-test"); + + @Container + static final GenericContainer mavenContainer = new GenericContainer<>("maven:3.8.3-openjdk-17") + .withCreateContainerCmdModifier(cmd -> cmd.withEntrypoint("sh")) + .withCommand("-c", "while true; do sleep 1; done") + .withCopyFileToContainer(MountableFile.forHostPath(Paths.get(System.getProperty("user.dir")).resolve("build/libs")), "/opt/jars") + .withCopyFileToContainer(MountableFile.forHostPath(Paths.get(System.getProperty("user.dir")).resolve("src/test/resources/test-applications/mvnw-corrupt-test")), "/test-applications/mvnw-corrupt-test") + .withCopyFileToContainer(MountableFile.forHostPath(Paths.get(System.getProperty("user.dir")).resolve("src/test/resources/test-applications/mvnw-working-test")), "/test-applications/mvnw-working-test"); + + + @BeforeAll + static void setUp() { + Properties properties = new Properties(); + try (FileInputStream fis = new FileInputStream( + Paths.get(System.getProperty("user.dir"), "gradle.properties").toFile())) { + properties.load(fis); + } catch (IOException e) { + throw new RuntimeException(e); + } + codeanalyzerVersion = properties.getProperty("version"); + } + + @Test + void shouldHaveCorrectJavaVersionInstalled() throws Exception { + var baseContainerresult = container.execInContainer("java", "-version"); + var mvnContainerresult = mavenContainer.execInContainer("java", "-version"); + Assertions.assertTrue(baseContainerresult.getStderr().contains("openjdk version \"" + javaVersion), "Base container Java version should be " + javaVersion); + Assertions.assertTrue(mvnContainerresult.getStderr().contains("openjdk version \"" + javaVersion), "Maven container Java version should be " + javaVersion); + } + + @Test + void shouldHaveCodeAnalyzerJar() throws Exception { + var dirContents = container.execInContainer("ls", "/opt/jars/"); + Assertions.assertTrue(dirContents.getStdout().length() > 0, "Directory listing should not be empty"); + Assertions.assertTrue(dirContents.getStdout().contains("codeanalyzer"), "Codeanalyzer.jar not found in the container."); + } + + @Test + void shouldBeAbleToRunCodeAnalyzer() throws Exception { + var runCodeAnalyzerJar = container.execInContainer( + "java", + "-jar", + String.format("/opt/jars/codeanalyzer-%s.jar", codeanalyzerVersion), + "--help" + ); + + Assertions.assertEquals(0, runCodeAnalyzerJar.getExitCode(), + "Command should execute successfully"); + Assertions.assertTrue(runCodeAnalyzerJar.getStdout().length() > 0, + "Should have some output"); + } + + @Test + void corruptMavenShouldNotBuildWithWrapper() throws IOException, InterruptedException { + // Make executable + mavenContainer.execInContainer("chmod", "+x", "/test-applications/mvnw-corrupt-test/mvnw"); + // Let's start by building the project by itself + var mavenProjectBuildWithWrapper = mavenContainer.withWorkingDirectory("/test-applications/mvnw-corrupt-test").execInContainer("/test-applications/mvnw-corrupt-test/mvnw", "clean", "compile"); + Assertions.assertNotEquals(0, mavenProjectBuildWithWrapper.getExitCode()); + } + + @Test + void corruptMavenShouldProduceAnalysisArtifactsWhenMVNCommandIsInPath() throws IOException, InterruptedException { + // Let's start by building the project by itself + var corruptMavenProjectBuild = mavenContainer.withWorkingDirectory("/test-applications/mvnw-corrupt-test").execInContainer("mvn", "-f", "/test-applications/mvnw-corrupt-test/pom.xml", "clean", "compile"); + Assertions.assertEquals(0, corruptMavenProjectBuild.getExitCode(), "Failed to build the project with system's default Maven."); + // NOw run codeanalyzer and assert if analysis.json is generated. + var runCodeAnalyzer = mavenContainer.execInContainer("java", "-jar", String.format("/opt/jars/codeanalyzer-%s.jar", codeanalyzerVersion), "--input=/test-applications/mvnw-corrupt-test", "--output=/tmp/", "--analysis-level=2", "--verbose", "--no-build"); + var codeAnalyzerOutputDirContents = mavenContainer.execInContainer("ls", "/tmp/analysis.json"); + String codeAnalyzerOutputDirContentsStdOut = codeAnalyzerOutputDirContents.getStdout(); + Assertions.assertTrue(codeAnalyzerOutputDirContentsStdOut.length() > 0, "Could not find 'analysis.json'."); + // mvnw is corrupt, so we should see an error message in the output. + Assertions.assertTrue(runCodeAnalyzer.getStdout().contains("[ERROR]\tCannot run program \"/test-applications/mvnw-corrupt-test/mvnw\"") && runCodeAnalyzer.getStdout().contains("/mvn.")); + // We should correctly identify the build tool used in the mvn command from the system path. + Assertions.assertTrue(runCodeAnalyzer.getStdout().contains("[INFO]\tBuilding the project using /usr/bin/mvn.")); + } + + @Test + void corruptMavenShouldNotTerminateWithErrorWhenMavenIsNotPresentUnlessAnalysisLevel2() throws IOException, InterruptedException { + // When analysis level 2, we should get a Runtime Exception + var runCodeAnalyzer = container.execInContainer( + "java", + "-jar", + String.format("/opt/jars/codeanalyzer-%s.jar", codeanalyzerVersion), + "--input=/test-applications/mvnw-corrupt-test", + "--output=/tmp/", + "--analysis-level=2" + ); + Assertions.assertEquals(1, runCodeAnalyzer.getExitCode()); + Assertions.assertTrue(runCodeAnalyzer.getStderr().contains("java.lang.RuntimeException")); + } +} \ No newline at end of file diff --git a/src/test/java/com/ibm/cldk/CodeAnalyzerTest.java b/src/test/java/com/ibm/cldk/CodeAnalyzerTest.java deleted file mode 100644 index 9fb695d2..00000000 --- a/src/test/java/com/ibm/cldk/CodeAnalyzerTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.ibm.cldk; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class CodeAnalyzerTest { - - @BeforeEach - void setUp() { - } - - @AfterEach - void tearDown() { - } - - @Test - void main() { - } - - @Test - void run() { - } -} \ No newline at end of file diff --git a/src/test/java/com/ibm/cldk/utils/BuildProjectTest.java b/src/test/java/com/ibm/cldk/utils/BuildProjectTest.java new file mode 100644 index 00000000..48e3aae0 --- /dev/null +++ b/src/test/java/com/ibm/cldk/utils/BuildProjectTest.java @@ -0,0 +1,4 @@ +package com.ibm.cldk.utils; + +public class BuildProjectTest { +} diff --git a/src/test/resources/test-applications/.gitignore b/src/test/resources/test-applications/.gitignore new file mode 100644 index 00000000..4d81f976 --- /dev/null +++ b/src/test/resources/test-applications/.gitignore @@ -0,0 +1,51 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear +*.zip +*.tar.gz +*.rar + +# Don't ignore jar files in any level of binary and dependencies +!**/binaries/**/*.jar +!**/libs/**/*.jar + +# virtual machine crash logs +hs_err_pid* + +# Ignore Gradle files +.gradle/ +build/ + +# Ignore Maven target folder +target/ + +# Ignore IntelliJ IDEA files +.idea/ +*.iml +*.iws +*.ipr + +# Ignore Eclipse files +.settings/ +*.classpath +*.project + +# Ignore VS Code files +.vscode/ + +# Ignore everything in codeql-db except the directory itself +codeql-db/* +!codeql-db/.keep diff --git a/src/test/resources/test-applications/gradlew-corrupt-test/.dockerignore b/src/test/resources/test-applications/gradlew-corrupt-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-corrupt-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/resources/test-applications/gradlew-corrupt-test/.gitignore b/src/test/resources/test-applications/gradlew-corrupt-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-corrupt-test/.gitignore @@ -0,0 +1,11 @@ +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +# https://github.com/takari/maven-wrapper#usage-without-binary-jar +.mvn/wrapper/maven-wrapper.jar \ No newline at end of file diff --git a/src/test/resources/test-applications/gradlew-corrupt-test/Dockerfile b/src/test/resources/test-applications/gradlew-corrupt-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-corrupt-test/Dockerfile @@ -0,0 +1,10 @@ + +FROM icr.io/appcafe/open-liberty:kernel-slim-java17-openj9-ubi + +COPY --chown=1001:0 /src/main/liberty/config /config + +RUN features.sh + +COPY --chown=1001:0 target/*.war /config/apps + +RUN configure.sh diff --git a/src/test/resources/test-applications/gradlew-corrupt-test/README.txt b/src/test/resources/test-applications/gradlew-corrupt-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/resources/test-applications/gradlew-corrupt-test/README.txt @@ -0,0 +1,35 @@ +After you generate a starter project, these instructions will help you with what to do next. + +The Open Liberty starter gives you a simple, quick way to get the necessary files to start building +an application on Open Liberty. There is no need to search how to find out what to add to your +Maven build files. A simple RestApplication.java file is generated for you to start +creating a REST based application. A server.xml configuration file is provided with the necessary +features for the MicroProfile and Jakarta EE versions that you previously selected. + +If you plan on developing and/or deploying your app in a containerized environment, the included +Dockerfile will make it easier to create your application image on top of the Open Liberty Docker +image. + +1) Once you download the starter project, unpackage the .zip file on your machine. +2) Open a command line session, navigate to the installation directory, and run `./mvnw liberty:dev` (Linux/Mac) or `mvnw liberty:dev` (Windows). + This will install all required dependencies and start the default server. When complete, you will + see the necessary features installed and the message "server is ready to run a smarter planet." + +For information on developing your application in dev mode using Maven, see the +dev mode documentation (https://openliberty.io/docs/latest/development-mode.html). + +For further help on getting started actually developing your application, see some of our +MicroProfile guides (https://openliberty.io/guides/?search=microprofile&key=tag) and Jakarta EE +guides (https://openliberty.io/guides/?search=jakarta%20ee&key=tag). + +If you have problems building the starter project, make sure the Java SE version on your +machine matches the Java SE version you picked from the Open Liberty starter on the downloads +page (https://openliberty.io/downloads/). You can test this with the command `java -version`. + +Open Liberty performs at its best when running using Open J9 which can be obtained via IBM Semeru +(https://developer.ibm.com/languages/java/semeru-runtimes/downloads/). For a full list of supported +Java SE versions and where to obtain them, reference the Java SE support page +(https://openliberty.io/docs/latest/java-se.html). + +If you find any issues with the starter project or have recommendations to improve it, open an +issue in the starter GitHub repo (https://github.com/OpenLiberty/start.openliberty.io). diff --git a/src/test/resources/test-applications/gradlew-corrupt-test/build.gradle b/src/test/resources/test-applications/gradlew-corrupt-test/build.gradle new file mode 100644 index 00000000..c80e50c1 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-corrupt-test/build.gradle @@ -0,0 +1,37 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +plugins { + id 'java' + id 'maven-publish' +} + +repositories { + mavenLocal() + maven { + url = uri('https://repo.maven.apache.org/maven2/') + } +} + +dependencies { + compileOnly 'javax:javaee-api:7.0' + compileOnly 'org.eclipse.microprofile:microprofile:1.4' +} + +group = 'com.demo' +version = '1.0-SNAPSHOT' +description = 'my-javaee-mvn' +java.sourceCompatibility = JavaVersion.VERSION_1_8 + +publishing { + publications { + maven(MavenPublication) { + from(components.java) + } + } +} + +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} diff --git a/src/test/resources/test-applications/gradlew-corrupt-test/build/tmp/compileJava/previous-compilation-data.bin b/src/test/resources/test-applications/gradlew-corrupt-test/build/tmp/compileJava/previous-compilation-data.bin new file mode 100644 index 00000000..0b2935da Binary files /dev/null and b/src/test/resources/test-applications/gradlew-corrupt-test/build/tmp/compileJava/previous-compilation-data.bin differ diff --git a/src/test/resources/test-applications/gradlew-corrupt-test/gradle/wrapper/gradle-wrapper.jar b/src/test/resources/test-applications/gradlew-corrupt-test/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..7454180f Binary files /dev/null and b/src/test/resources/test-applications/gradlew-corrupt-test/gradle/wrapper/gradle-wrapper.jar differ diff --git a/src/test/resources/test-applications/gradlew-corrupt-test/gradle/wrapper/gradle-wrapper.properties b/src/test/resources/test-applications/gradlew-corrupt-test/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..2e6e5897 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-corrupt-test/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/src/test/resources/test-applications/gradlew-corrupt-test/gradlew b/src/test/resources/test-applications/gradlew-corrupt-test/gradlew new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/test-applications/gradlew-corrupt-test/gradlew.bat b/src/test/resources/test-applications/gradlew-corrupt-test/gradlew.bat new file mode 100644 index 00000000..ac1b06f9 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-corrupt-test/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/test/resources/test-applications/gradlew-corrupt-test/settings.gradle b/src/test/resources/test-applications/gradlew-corrupt-test/settings.gradle new file mode 100644 index 00000000..81f4ec38 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-corrupt-test/settings.gradle @@ -0,0 +1,5 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +rootProject.name = 'my-javaee-mvn' diff --git a/src/test/resources/test-applications/gradlew-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/resources/test-applications/gradlew-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/resources/test-applications/gradlew-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java @@ -0,0 +1,29 @@ +// Assisted by watsonx Code Assistant + +package com.demo; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Date; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebServlet("/currentTime") +public class CurrentTimeServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println("

Current Time

"); + out.println("

The current date and time is:

"); + out.println("

" + new Date() + "

"); + } + +} diff --git a/src/test/resources/test-applications/gradlew-corrupt-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/resources/test-applications/gradlew-corrupt-test/src/main/java/com/demo/rest/RestApplication.java new file mode 100644 index 00000000..eb0e4660 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-corrupt-test/src/main/java/com/demo/rest/RestApplication.java @@ -0,0 +1,9 @@ +package com.demo.rest; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("/api") +public class RestApplication extends Application { + +} \ No newline at end of file diff --git a/src/test/resources/test-applications/gradlew-corrupt-test/src/main/liberty/config/server.xml b/src/test/resources/test-applications/gradlew-corrupt-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/resources/test-applications/gradlew-corrupt-test/src/main/liberty/config/server.xml @@ -0,0 +1,42 @@ + + + + + + javaee-7.0 + microProfile-1.4 + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/test-applications/gradlew-corrupt-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/resources/test-applications/gradlew-corrupt-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/test-applications/gradlew-working-test/.dockerignore b/src/test/resources/test-applications/gradlew-working-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-working-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/resources/test-applications/gradlew-working-test/.gitignore b/src/test/resources/test-applications/gradlew-working-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-working-test/.gitignore @@ -0,0 +1,11 @@ +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +# https://github.com/takari/maven-wrapper#usage-without-binary-jar +.mvn/wrapper/maven-wrapper.jar \ No newline at end of file diff --git a/src/test/resources/test-applications/gradlew-working-test/Dockerfile b/src/test/resources/test-applications/gradlew-working-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-working-test/Dockerfile @@ -0,0 +1,10 @@ + +FROM icr.io/appcafe/open-liberty:kernel-slim-java17-openj9-ubi + +COPY --chown=1001:0 /src/main/liberty/config /config + +RUN features.sh + +COPY --chown=1001:0 target/*.war /config/apps + +RUN configure.sh diff --git a/src/test/resources/test-applications/gradlew-working-test/README.txt b/src/test/resources/test-applications/gradlew-working-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/resources/test-applications/gradlew-working-test/README.txt @@ -0,0 +1,35 @@ +After you generate a starter project, these instructions will help you with what to do next. + +The Open Liberty starter gives you a simple, quick way to get the necessary files to start building +an application on Open Liberty. There is no need to search how to find out what to add to your +Maven build files. A simple RestApplication.java file is generated for you to start +creating a REST based application. A server.xml configuration file is provided with the necessary +features for the MicroProfile and Jakarta EE versions that you previously selected. + +If you plan on developing and/or deploying your app in a containerized environment, the included +Dockerfile will make it easier to create your application image on top of the Open Liberty Docker +image. + +1) Once you download the starter project, unpackage the .zip file on your machine. +2) Open a command line session, navigate to the installation directory, and run `./mvnw liberty:dev` (Linux/Mac) or `mvnw liberty:dev` (Windows). + This will install all required dependencies and start the default server. When complete, you will + see the necessary features installed and the message "server is ready to run a smarter planet." + +For information on developing your application in dev mode using Maven, see the +dev mode documentation (https://openliberty.io/docs/latest/development-mode.html). + +For further help on getting started actually developing your application, see some of our +MicroProfile guides (https://openliberty.io/guides/?search=microprofile&key=tag) and Jakarta EE +guides (https://openliberty.io/guides/?search=jakarta%20ee&key=tag). + +If you have problems building the starter project, make sure the Java SE version on your +machine matches the Java SE version you picked from the Open Liberty starter on the downloads +page (https://openliberty.io/downloads/). You can test this with the command `java -version`. + +Open Liberty performs at its best when running using Open J9 which can be obtained via IBM Semeru +(https://developer.ibm.com/languages/java/semeru-runtimes/downloads/). For a full list of supported +Java SE versions and where to obtain them, reference the Java SE support page +(https://openliberty.io/docs/latest/java-se.html). + +If you find any issues with the starter project or have recommendations to improve it, open an +issue in the starter GitHub repo (https://github.com/OpenLiberty/start.openliberty.io). diff --git a/src/test/resources/test-applications/gradlew-working-test/build.gradle b/src/test/resources/test-applications/gradlew-working-test/build.gradle new file mode 100644 index 00000000..c80e50c1 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-working-test/build.gradle @@ -0,0 +1,37 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +plugins { + id 'java' + id 'maven-publish' +} + +repositories { + mavenLocal() + maven { + url = uri('https://repo.maven.apache.org/maven2/') + } +} + +dependencies { + compileOnly 'javax:javaee-api:7.0' + compileOnly 'org.eclipse.microprofile:microprofile:1.4' +} + +group = 'com.demo' +version = '1.0-SNAPSHOT' +description = 'my-javaee-mvn' +java.sourceCompatibility = JavaVersion.VERSION_1_8 + +publishing { + publications { + maven(MavenPublication) { + from(components.java) + } + } +} + +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} diff --git a/src/test/resources/test-applications/gradlew-working-test/build/tmp/compileJava/previous-compilation-data.bin b/src/test/resources/test-applications/gradlew-working-test/build/tmp/compileJava/previous-compilation-data.bin new file mode 100644 index 00000000..0b2935da Binary files /dev/null and b/src/test/resources/test-applications/gradlew-working-test/build/tmp/compileJava/previous-compilation-data.bin differ diff --git a/src/test/resources/test-applications/gradlew-working-test/gradle/wrapper/gradle-wrapper.jar b/src/test/resources/test-applications/gradlew-working-test/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..7454180f Binary files /dev/null and b/src/test/resources/test-applications/gradlew-working-test/gradle/wrapper/gradle-wrapper.jar differ diff --git a/src/test/resources/test-applications/gradlew-working-test/gradle/wrapper/gradle-wrapper.properties b/src/test/resources/test-applications/gradlew-working-test/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..2e6e5897 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-working-test/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/src/test/resources/test-applications/gradlew-working-test/gradlew b/src/test/resources/test-applications/gradlew-working-test/gradlew new file mode 100755 index 00000000..1b6c7873 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-working-test/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/src/test/resources/test-applications/gradlew-working-test/gradlew.bat b/src/test/resources/test-applications/gradlew-working-test/gradlew.bat new file mode 100644 index 00000000..ac1b06f9 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-working-test/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/test/resources/test-applications/gradlew-working-test/settings.gradle b/src/test/resources/test-applications/gradlew-working-test/settings.gradle new file mode 100644 index 00000000..81f4ec38 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-working-test/settings.gradle @@ -0,0 +1,5 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +rootProject.name = 'my-javaee-mvn' diff --git a/src/test/resources/test-applications/gradlew-working-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/resources/test-applications/gradlew-working-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/resources/test-applications/gradlew-working-test/src/main/java/com/demo/CurrentTimeServlet.java @@ -0,0 +1,29 @@ +// Assisted by watsonx Code Assistant + +package com.demo; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Date; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebServlet("/currentTime") +public class CurrentTimeServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println("

Current Time

"); + out.println("

The current date and time is:

"); + out.println("

" + new Date() + "

"); + } + +} diff --git a/src/test/resources/test-applications/gradlew-working-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/resources/test-applications/gradlew-working-test/src/main/java/com/demo/rest/RestApplication.java new file mode 100644 index 00000000..eb0e4660 --- /dev/null +++ b/src/test/resources/test-applications/gradlew-working-test/src/main/java/com/demo/rest/RestApplication.java @@ -0,0 +1,9 @@ +package com.demo.rest; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("/api") +public class RestApplication extends Application { + +} \ No newline at end of file diff --git a/src/test/resources/test-applications/gradlew-working-test/src/main/liberty/config/server.xml b/src/test/resources/test-applications/gradlew-working-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/resources/test-applications/gradlew-working-test/src/main/liberty/config/server.xml @@ -0,0 +1,42 @@ + + + + + + javaee-7.0 + microProfile-1.4 + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/test-applications/gradlew-working-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/resources/test-applications/gradlew-working-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/test-applications/mvnw-corrupt-test/.dockerignore b/src/test/resources/test-applications/mvnw-corrupt-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/resources/test-applications/mvnw-corrupt-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/resources/test-applications/mvnw-corrupt-test/.gitignore b/src/test/resources/test-applications/mvnw-corrupt-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/resources/test-applications/mvnw-corrupt-test/.gitignore @@ -0,0 +1,11 @@ +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +# https://github.com/takari/maven-wrapper#usage-without-binary-jar +.mvn/wrapper/maven-wrapper.jar \ No newline at end of file diff --git a/src/test/resources/test-applications/mvnw-corrupt-test/.mvn/wrapper/maven-wrapper.properties b/src/test/resources/test-applications/mvnw-corrupt-test/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..207aa436 --- /dev/null +++ b/src/test/resources/test-applications/mvnw-corrupt-test/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.1/apache-maven-3.9.1-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar diff --git a/src/test/resources/test-applications/mvnw-corrupt-test/Dockerfile b/src/test/resources/test-applications/mvnw-corrupt-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/resources/test-applications/mvnw-corrupt-test/Dockerfile @@ -0,0 +1,10 @@ + +FROM icr.io/appcafe/open-liberty:kernel-slim-java17-openj9-ubi + +COPY --chown=1001:0 /src/main/liberty/config /config + +RUN features.sh + +COPY --chown=1001:0 target/*.war /config/apps + +RUN configure.sh diff --git a/src/test/resources/test-applications/mvnw-corrupt-test/README.txt b/src/test/resources/test-applications/mvnw-corrupt-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/resources/test-applications/mvnw-corrupt-test/README.txt @@ -0,0 +1,35 @@ +After you generate a starter project, these instructions will help you with what to do next. + +The Open Liberty starter gives you a simple, quick way to get the necessary files to start building +an application on Open Liberty. There is no need to search how to find out what to add to your +Maven build files. A simple RestApplication.java file is generated for you to start +creating a REST based application. A server.xml configuration file is provided with the necessary +features for the MicroProfile and Jakarta EE versions that you previously selected. + +If you plan on developing and/or deploying your app in a containerized environment, the included +Dockerfile will make it easier to create your application image on top of the Open Liberty Docker +image. + +1) Once you download the starter project, unpackage the .zip file on your machine. +2) Open a command line session, navigate to the installation directory, and run `./mvnw liberty:dev` (Linux/Mac) or `mvnw liberty:dev` (Windows). + This will install all required dependencies and start the default server. When complete, you will + see the necessary features installed and the message "server is ready to run a smarter planet." + +For information on developing your application in dev mode using Maven, see the +dev mode documentation (https://openliberty.io/docs/latest/development-mode.html). + +For further help on getting started actually developing your application, see some of our +MicroProfile guides (https://openliberty.io/guides/?search=microprofile&key=tag) and Jakarta EE +guides (https://openliberty.io/guides/?search=jakarta%20ee&key=tag). + +If you have problems building the starter project, make sure the Java SE version on your +machine matches the Java SE version you picked from the Open Liberty starter on the downloads +page (https://openliberty.io/downloads/). You can test this with the command `java -version`. + +Open Liberty performs at its best when running using Open J9 which can be obtained via IBM Semeru +(https://developer.ibm.com/languages/java/semeru-runtimes/downloads/). For a full list of supported +Java SE versions and where to obtain them, reference the Java SE support page +(https://openliberty.io/docs/latest/java-se.html). + +If you find any issues with the starter project or have recommendations to improve it, open an +issue in the starter GitHub repo (https://github.com/OpenLiberty/start.openliberty.io). diff --git a/src/test/resources/test-applications/mvnw-corrupt-test/mvnw b/src/test/resources/test-applications/mvnw-corrupt-test/mvnw new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/test-applications/mvnw-corrupt-test/pom.xml b/src/test/resources/test-applications/mvnw-corrupt-test/pom.xml new file mode 100644 index 00000000..9b78f42c --- /dev/null +++ b/src/test/resources/test-applications/mvnw-corrupt-test/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + com.demo + my-javaee-mvn + 1.0-SNAPSHOT + war + + + 17 + 17 + UTF-8 + + + + + javax + javaee-api + 7.0 + provided + + + org.eclipse.microprofile + microprofile + 1.4 + pom + provided + + + + + my-javaee-mvn + + + + org.apache.maven.plugins + maven-war-plugin + 3.3.2 + + + io.openliberty.tools + liberty-maven-plugin + 3.11.1 + + + + + + io.openliberty.tools + liberty-maven-plugin + + + + diff --git a/src/test/resources/test-applications/mvnw-corrupt-test/settings.gradle b/src/test/resources/test-applications/mvnw-corrupt-test/settings.gradle new file mode 100644 index 00000000..81f4ec38 --- /dev/null +++ b/src/test/resources/test-applications/mvnw-corrupt-test/settings.gradle @@ -0,0 +1,5 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +rootProject.name = 'my-javaee-mvn' diff --git a/src/test/resources/test-applications/mvnw-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/resources/test-applications/mvnw-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/resources/test-applications/mvnw-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java @@ -0,0 +1,29 @@ +// Assisted by watsonx Code Assistant + +package com.demo; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Date; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebServlet("/currentTime") +public class CurrentTimeServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println("

Current Time

"); + out.println("

The current date and time is:

"); + out.println("

" + new Date() + "

"); + } + +} diff --git a/src/test/resources/test-applications/mvnw-corrupt-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/resources/test-applications/mvnw-corrupt-test/src/main/java/com/demo/rest/RestApplication.java new file mode 100644 index 00000000..eb0e4660 --- /dev/null +++ b/src/test/resources/test-applications/mvnw-corrupt-test/src/main/java/com/demo/rest/RestApplication.java @@ -0,0 +1,9 @@ +package com.demo.rest; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("/api") +public class RestApplication extends Application { + +} \ No newline at end of file diff --git a/src/test/resources/test-applications/mvnw-corrupt-test/src/main/liberty/config/server.xml b/src/test/resources/test-applications/mvnw-corrupt-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/resources/test-applications/mvnw-corrupt-test/src/main/liberty/config/server.xml @@ -0,0 +1,42 @@ + + + + + + javaee-7.0 + microProfile-1.4 + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/test-applications/mvnw-corrupt-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/resources/test-applications/mvnw-corrupt-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/test-applications/mvnw-working-test/.dockerignore b/src/test/resources/test-applications/mvnw-working-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/resources/test-applications/mvnw-working-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/resources/test-applications/mvnw-working-test/.gitignore b/src/test/resources/test-applications/mvnw-working-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/resources/test-applications/mvnw-working-test/.gitignore @@ -0,0 +1,11 @@ +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +# https://github.com/takari/maven-wrapper#usage-without-binary-jar +.mvn/wrapper/maven-wrapper.jar \ No newline at end of file diff --git a/src/test/resources/test-applications/mvnw-working-test/.mvn/wrapper/maven-wrapper.properties b/src/test/resources/test-applications/mvnw-working-test/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..2f093d08 --- /dev/null +++ b/src/test/resources/test-applications/mvnw-working-test/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.5/apache-maven-3.9.5-bin.zip diff --git a/src/test/resources/test-applications/mvnw-working-test/Dockerfile b/src/test/resources/test-applications/mvnw-working-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/resources/test-applications/mvnw-working-test/Dockerfile @@ -0,0 +1,10 @@ + +FROM icr.io/appcafe/open-liberty:kernel-slim-java17-openj9-ubi + +COPY --chown=1001:0 /src/main/liberty/config /config + +RUN features.sh + +COPY --chown=1001:0 target/*.war /config/apps + +RUN configure.sh diff --git a/src/test/resources/test-applications/mvnw-working-test/README.txt b/src/test/resources/test-applications/mvnw-working-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/resources/test-applications/mvnw-working-test/README.txt @@ -0,0 +1,35 @@ +After you generate a starter project, these instructions will help you with what to do next. + +The Open Liberty starter gives you a simple, quick way to get the necessary files to start building +an application on Open Liberty. There is no need to search how to find out what to add to your +Maven build files. A simple RestApplication.java file is generated for you to start +creating a REST based application. A server.xml configuration file is provided with the necessary +features for the MicroProfile and Jakarta EE versions that you previously selected. + +If you plan on developing and/or deploying your app in a containerized environment, the included +Dockerfile will make it easier to create your application image on top of the Open Liberty Docker +image. + +1) Once you download the starter project, unpackage the .zip file on your machine. +2) Open a command line session, navigate to the installation directory, and run `./mvnw liberty:dev` (Linux/Mac) or `mvnw liberty:dev` (Windows). + This will install all required dependencies and start the default server. When complete, you will + see the necessary features installed and the message "server is ready to run a smarter planet." + +For information on developing your application in dev mode using Maven, see the +dev mode documentation (https://openliberty.io/docs/latest/development-mode.html). + +For further help on getting started actually developing your application, see some of our +MicroProfile guides (https://openliberty.io/guides/?search=microprofile&key=tag) and Jakarta EE +guides (https://openliberty.io/guides/?search=jakarta%20ee&key=tag). + +If you have problems building the starter project, make sure the Java SE version on your +machine matches the Java SE version you picked from the Open Liberty starter on the downloads +page (https://openliberty.io/downloads/). You can test this with the command `java -version`. + +Open Liberty performs at its best when running using Open J9 which can be obtained via IBM Semeru +(https://developer.ibm.com/languages/java/semeru-runtimes/downloads/). For a full list of supported +Java SE versions and where to obtain them, reference the Java SE support page +(https://openliberty.io/docs/latest/java-se.html). + +If you find any issues with the starter project or have recommendations to improve it, open an +issue in the starter GitHub repo (https://github.com/OpenLiberty/start.openliberty.io). diff --git a/src/test/resources/test-applications/mvnw-working-test/mvnw b/src/test/resources/test-applications/mvnw-working-test/mvnw new file mode 100755 index 00000000..19529ddf --- /dev/null +++ b/src/test/resources/test-applications/mvnw-working-test/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/src/test/resources/test-applications/mvnw-working-test/mvnw.cmd b/src/test/resources/test-applications/mvnw-working-test/mvnw.cmd new file mode 100644 index 00000000..b150b91e --- /dev/null +++ b/src/test/resources/test-applications/mvnw-working-test/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/src/test/resources/test-applications/mvnw-working-test/pom.xml b/src/test/resources/test-applications/mvnw-working-test/pom.xml new file mode 100644 index 00000000..9b78f42c --- /dev/null +++ b/src/test/resources/test-applications/mvnw-working-test/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + com.demo + my-javaee-mvn + 1.0-SNAPSHOT + war + + + 17 + 17 + UTF-8 + + + + + javax + javaee-api + 7.0 + provided + + + org.eclipse.microprofile + microprofile + 1.4 + pom + provided + + + + + my-javaee-mvn + + + + org.apache.maven.plugins + maven-war-plugin + 3.3.2 + + + io.openliberty.tools + liberty-maven-plugin + 3.11.1 + + + + + + io.openliberty.tools + liberty-maven-plugin + + + + diff --git a/src/test/resources/test-applications/mvnw-working-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/resources/test-applications/mvnw-working-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/resources/test-applications/mvnw-working-test/src/main/java/com/demo/CurrentTimeServlet.java @@ -0,0 +1,29 @@ +// Assisted by watsonx Code Assistant + +package com.demo; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Date; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebServlet("/currentTime") +public class CurrentTimeServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println("

Current Time

"); + out.println("

The current date and time is:

"); + out.println("

" + new Date() + "

"); + } + +} diff --git a/src/test/resources/test-applications/mvnw-working-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/resources/test-applications/mvnw-working-test/src/main/java/com/demo/rest/RestApplication.java new file mode 100644 index 00000000..eb0e4660 --- /dev/null +++ b/src/test/resources/test-applications/mvnw-working-test/src/main/java/com/demo/rest/RestApplication.java @@ -0,0 +1,9 @@ +package com.demo.rest; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("/api") +public class RestApplication extends Application { + +} \ No newline at end of file diff --git a/src/test/resources/test-applications/mvnw-working-test/src/main/liberty/config/server.xml b/src/test/resources/test-applications/mvnw-working-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/resources/test-applications/mvnw-working-test/src/main/liberty/config/server.xml @@ -0,0 +1,42 @@ + + + + + + javaee-7.0 + microProfile-1.4 + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/test-applications/mvnw-working-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/resources/test-applications/mvnw-working-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/test-applications/mvnw-working-test/target/classes/META-INF/microprofile-config.properties b/src/test/resources/test-applications/mvnw-working-test/target/classes/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/test-applications/mvnw-working-test/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/src/test/resources/test-applications/mvnw-working-test/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst new file mode 100644 index 00000000..7c90d2c7 --- /dev/null +++ b/src/test/resources/test-applications/mvnw-working-test/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst @@ -0,0 +1,2 @@ +com/demo/CurrentTimeServlet.class +com/demo/rest/RestApplication.class diff --git a/src/test/resources/test-applications/mvnw-working-test/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/src/test/resources/test-applications/mvnw-working-test/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst new file mode 100644 index 00000000..00564bbe --- /dev/null +++ b/src/test/resources/test-applications/mvnw-working-test/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst @@ -0,0 +1,2 @@ +/Users/rkrsn/Downloads/test/src/main/java/com/demo/rest/RestApplication.java +/Users/rkrsn/Downloads/test/src/main/java/com/demo/CurrentTimeServlet.java diff --git a/src/test/resources/test-applications/no-mvnw-test/.dockerignore b/src/test/resources/test-applications/no-mvnw-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/resources/test-applications/no-mvnw-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/resources/test-applications/no-mvnw-test/.gitignore b/src/test/resources/test-applications/no-mvnw-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/resources/test-applications/no-mvnw-test/.gitignore @@ -0,0 +1,11 @@ +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +# https://github.com/takari/maven-wrapper#usage-without-binary-jar +.mvn/wrapper/maven-wrapper.jar \ No newline at end of file diff --git a/src/test/resources/test-applications/no-mvnw-test/.mvn/wrapper/maven-wrapper.properties b/src/test/resources/test-applications/no-mvnw-test/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..207aa436 --- /dev/null +++ b/src/test/resources/test-applications/no-mvnw-test/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.1/apache-maven-3.9.1-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar diff --git a/src/test/resources/test-applications/no-mvnw-test/Dockerfile b/src/test/resources/test-applications/no-mvnw-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/resources/test-applications/no-mvnw-test/Dockerfile @@ -0,0 +1,10 @@ + +FROM icr.io/appcafe/open-liberty:kernel-slim-java17-openj9-ubi + +COPY --chown=1001:0 /src/main/liberty/config /config + +RUN features.sh + +COPY --chown=1001:0 target/*.war /config/apps + +RUN configure.sh diff --git a/src/test/resources/test-applications/no-mvnw-test/README.txt b/src/test/resources/test-applications/no-mvnw-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/resources/test-applications/no-mvnw-test/README.txt @@ -0,0 +1,35 @@ +After you generate a starter project, these instructions will help you with what to do next. + +The Open Liberty starter gives you a simple, quick way to get the necessary files to start building +an application on Open Liberty. There is no need to search how to find out what to add to your +Maven build files. A simple RestApplication.java file is generated for you to start +creating a REST based application. A server.xml configuration file is provided with the necessary +features for the MicroProfile and Jakarta EE versions that you previously selected. + +If you plan on developing and/or deploying your app in a containerized environment, the included +Dockerfile will make it easier to create your application image on top of the Open Liberty Docker +image. + +1) Once you download the starter project, unpackage the .zip file on your machine. +2) Open a command line session, navigate to the installation directory, and run `./mvnw liberty:dev` (Linux/Mac) or `mvnw liberty:dev` (Windows). + This will install all required dependencies and start the default server. When complete, you will + see the necessary features installed and the message "server is ready to run a smarter planet." + +For information on developing your application in dev mode using Maven, see the +dev mode documentation (https://openliberty.io/docs/latest/development-mode.html). + +For further help on getting started actually developing your application, see some of our +MicroProfile guides (https://openliberty.io/guides/?search=microprofile&key=tag) and Jakarta EE +guides (https://openliberty.io/guides/?search=jakarta%20ee&key=tag). + +If you have problems building the starter project, make sure the Java SE version on your +machine matches the Java SE version you picked from the Open Liberty starter on the downloads +page (https://openliberty.io/downloads/). You can test this with the command `java -version`. + +Open Liberty performs at its best when running using Open J9 which can be obtained via IBM Semeru +(https://developer.ibm.com/languages/java/semeru-runtimes/downloads/). For a full list of supported +Java SE versions and where to obtain them, reference the Java SE support page +(https://openliberty.io/docs/latest/java-se.html). + +If you find any issues with the starter project or have recommendations to improve it, open an +issue in the starter GitHub repo (https://github.com/OpenLiberty/start.openliberty.io). diff --git a/src/test/resources/test-applications/no-mvnw-test/pom.xml b/src/test/resources/test-applications/no-mvnw-test/pom.xml new file mode 100644 index 00000000..9b78f42c --- /dev/null +++ b/src/test/resources/test-applications/no-mvnw-test/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + com.demo + my-javaee-mvn + 1.0-SNAPSHOT + war + + + 17 + 17 + UTF-8 + + + + + javax + javaee-api + 7.0 + provided + + + org.eclipse.microprofile + microprofile + 1.4 + pom + provided + + + + + my-javaee-mvn + + + + org.apache.maven.plugins + maven-war-plugin + 3.3.2 + + + io.openliberty.tools + liberty-maven-plugin + 3.11.1 + + + + + + io.openliberty.tools + liberty-maven-plugin + + + + diff --git a/src/test/resources/test-applications/no-mvnw-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/resources/test-applications/no-mvnw-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/resources/test-applications/no-mvnw-test/src/main/java/com/demo/CurrentTimeServlet.java @@ -0,0 +1,29 @@ +// Assisted by watsonx Code Assistant + +package com.demo; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Date; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebServlet("/currentTime") +public class CurrentTimeServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println("

Current Time

"); + out.println("

The current date and time is:

"); + out.println("

" + new Date() + "

"); + } + +} diff --git a/src/test/resources/test-applications/no-mvnw-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/resources/test-applications/no-mvnw-test/src/main/java/com/demo/rest/RestApplication.java new file mode 100644 index 00000000..eb0e4660 --- /dev/null +++ b/src/test/resources/test-applications/no-mvnw-test/src/main/java/com/demo/rest/RestApplication.java @@ -0,0 +1,9 @@ +package com.demo.rest; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("/api") +public class RestApplication extends Application { + +} \ No newline at end of file diff --git a/src/test/resources/test-applications/no-mvnw-test/src/main/liberty/config/server.xml b/src/test/resources/test-applications/no-mvnw-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/resources/test-applications/no-mvnw-test/src/main/liberty/config/server.xml @@ -0,0 +1,42 @@ + + + + + + javaee-7.0 + microProfile-1.4 + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/test-applications/no-mvnw-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/resources/test-applications/no-mvnw-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b