diff --git a/build.gradle b/build.gradle index 814beacb..a979aa27 100644 --- a/build.gradle +++ b/build.gradle @@ -29,6 +29,10 @@ repositories { mavenLocal() } +java { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 +} 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 166aa4a7..e997a9af 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1 +1 @@ -version=1.1.0 \ No newline at end of file +version=2.0.0 \ No newline at end of file diff --git a/src/main/java/com/ibm/cldk/CodeAnalyzer.java b/src/main/java/com/ibm/cldk/CodeAnalyzer.java index 8cdca67c..c4477d17 100644 --- a/src/main/java/com/ibm/cldk/CodeAnalyzer.java +++ b/src/main/java/com/ibm/cldk/CodeAnalyzer.java @@ -9,23 +9,9 @@ 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. -*/ - + */ package com.ibm.cldk; -import com.github.javaparser.Problem; -import com.google.common.reflect.TypeToken; -import com.google.gson.*; -import com.ibm.cldk.entities.JavaCompilationUnit; -import com.ibm.cldk.utils.BuildProject; -import com.ibm.cldk.utils.Log; -import com.ibm.wala.ipa.callgraph.CallGraphBuilderCancelException; -import com.ibm.wala.ipa.cha.ClassHierarchyException; -import org.apache.commons.lang3.tuple.Pair; -import picocli.CommandLine; -import picocli.CommandLine.Command; -import picocli.CommandLine.Option; - import java.io.File; import java.io.FileReader; import java.io.FileWriter; @@ -38,13 +24,32 @@ import java.util.Map; import java.util.stream.Collectors; +import org.apache.commons.lang3.tuple.Pair; + +import com.github.javaparser.Problem; +import com.google.common.reflect.TypeToken; +import com.google.gson.FieldNamingPolicy; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.ibm.cldk.entities.JavaCompilationUnit; +import com.ibm.cldk.utils.BuildProject; +import com.ibm.cldk.utils.Log; + +import picocli.CommandLine; +import picocli.CommandLine.Command; +import picocli.CommandLine.Option; class VersionProvider implements CommandLine.IVersionProvider { + public String[] getVersion() throws Exception { String version = getClass().getPackage().getImplementationVersion(); - return new String[]{ version != null ? version : "unknown" }; + return new String[]{version != null ? version : "unknown"}; } } + /** * The type Code analyzer. */ @@ -69,6 +74,8 @@ public class CodeAnalyzer implements Runnable { @Option(names = {"--no-build"}, description = "Do not build your application. Use this option if you have already built your application.") private static boolean noBuild = false; + @Option(names = {"-f", "--project-root-path"}, description = "Path to the root pom.xml/build.gradle file of the project.") + public static String projectRootPom; @Option(names = {"-a", "--analysis-level"}, description = "Level of analysis to perform. Options: 1 (for just symbol table) or 2 (for call graph). Default: 1") private static int analysisLevel = 1; @@ -83,6 +90,7 @@ public class CodeAnalyzer implements Runnable { .setPrettyPrinting() .disableHtmlEscaping() .create(); + /** * The entry point of application. * @@ -108,22 +116,26 @@ private static void analyze() throws Exception { JsonObject combinedJsonObject = new JsonObject(); Map symbolTable; + projectRootPom = projectRootPom == null ? input : projectRootPom; // First of all if, sourceAnalysis is provided, we will analyze the source code instead of the project. if (sourceAnalysis != null) { // Construct symbol table for source code Log.debug("Single file analysis."); Pair, Map>> symbolTableExtractionResult = SymbolTable.extractSingle(sourceAnalysis); symbolTable = symbolTableExtractionResult.getLeft(); - } - - else { + } else { // download library dependencies of project for type resolution String dependencies = null; - if (BuildProject.downloadLibraryDependencies(input)) { - dependencies = String.valueOf(BuildProject.libDownloadPath); - } else { + try { + if (BuildProject.downloadLibraryDependencies(input, projectRootPom)) { + dependencies = String.valueOf(BuildProject.libDownloadPath); + } else { + Log.warn("Failed to download library dependencies of project"); + } + } catch (IllegalStateException illegalStateException) { Log.warn("Failed to download library dependencies of project"); } + boolean analysisFileExists = output != null && Files.exists(Paths.get(output + File.separator + outputFileName)); // if target files are specified, compute symbol table information for the given files @@ -132,8 +144,8 @@ private static void analyze() throws Exception { // if target files specified for analysis level 2, downgrade to analysis level 1 if (analysisLevel > 1) { - Log.warn("Incremental analysis is supported at analysis level 1 only; " + - "performing analysis level 1 for target files"); + Log.warn("Incremental analysis is supported at analysis level 1 only; " + + "performing analysis level 1 for target files"); analysisLevel = 1; } @@ -158,12 +170,10 @@ private static void analyze() throws Exception { } symbolTable = existingSymbolTable; } - } - - else { + } else { // construct symbol table for project, write parse problems to file in output directory if specified - Pair, Map>> symbolTableExtractionResult = - SymbolTable.extractAll(Paths.get(input)); + Pair, Map>> symbolTableExtractionResult + = SymbolTable.extractAll(Paths.get(input)); symbolTable = symbolTableExtractionResult.getLeft(); } @@ -221,7 +231,8 @@ private static void emit(String consolidatedJSONString) throws IOException { } private static Map readSymbolTableFromFile(File analysisJsonFile) { - Type symbolTableType = new TypeToken>() {}.getType(); + Type symbolTableType = new TypeToken>() { + }.getType(); try (FileReader reader = new FileReader(analysisJsonFile)) { JsonObject jsonObject = JsonParser.parseReader(reader).getAsJsonObject(); return gson.fromJson(jsonObject.get("symbol_table"), symbolTableType); @@ -230,4 +241,4 @@ private static Map readSymbolTableFromFile(File ana } return null; } -} \ No newline at end of file +} diff --git a/src/main/java/com/ibm/cldk/SymbolTable.java b/src/main/java/com/ibm/cldk/SymbolTable.java index 584133ff..a589ec7c 100644 --- a/src/main/java/com/ibm/cldk/SymbolTable.java +++ b/src/main/java/com/ibm/cldk/SymbolTable.java @@ -10,7 +10,7 @@ import com.github.javaparser.ast.body.*; import com.github.javaparser.ast.expr.*; import com.github.javaparser.ast.nodeTypes.NodeWithName; -import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.*; import com.github.javaparser.ast.type.ReferenceType; import com.github.javaparser.ast.type.Type; import com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration; @@ -41,15 +41,13 @@ public class SymbolTable { private static Set unresolvedExpressions = new HashSet<>(); /** - * Processes the given compilation unit to extract information about classes and - * interfaces - * declared in the unit and returns a JSON object containing the extracted - * information. + * Processes the given compilation unit to extract information about classes + * and interfaces declared in the unit and returns a JSON object containing + * the extracted information. * * @param parseResult compilation unit to be processed * @return JSON object containing extracted information */ - // Let's store the known callables here for future use. public static Table declaredMethodsAndConstructors = Tables.newCustomTable(new HashMap<>(), () -> new HashMap<>() { @Override @@ -102,105 +100,104 @@ private static JavaCompilationUnit processCompilationUnit(CompilationUnit parseR // create array node for type declarations cUnit.setTypeDeclarations(parseResult.findAll(TypeDeclaration.class) - .stream().filter(typeDecl -> typeDecl.getFullyQualifiedName().isPresent()) - .map(typeDecl -> { - // get type name and initialize the type object - String typeName = typeDecl.getFullyQualifiedName().get().toString(); - com.ibm.cldk.entities.Type typeNode = new com.ibm.cldk.entities.Type(); - - if (typeDecl instanceof ClassOrInterfaceDeclaration) { - ClassOrInterfaceDeclaration classDecl = (ClassOrInterfaceDeclaration)typeDecl; - - // Add interfaces implemented by class - typeNode.setImplementsList(classDecl.getImplementedTypes().stream().map(SymbolTable::resolveType) - .collect(Collectors.toList())); - - // Add class modifiers - typeNode.setModifiers(classDecl.getModifiers().stream().map(m -> m.toString().strip()) - .collect(Collectors.toList())); - - // Add class annotations - typeNode.setAnnotations(classDecl.getAnnotations().stream().map(a -> a.toString().strip()) - .collect(Collectors.toList())); - - // add booleans indicating interfaces and inner/local classes - typeNode.setInterface(classDecl.isInterface()); - typeNode.setInnerClass(classDecl.isInnerClass()); - typeNode.setLocalClass(classDecl.isLocalClassDeclaration()); - - // Add extends - typeNode.setExtendsList(classDecl.getExtendedTypes().stream() - .map(SymbolTable::resolveType) - .collect(Collectors.toList())); - - } else if (typeDecl instanceof EnumDeclaration) { - EnumDeclaration enumDecl = (EnumDeclaration)typeDecl; - - // Add interfaces implemented by enum - typeNode.setImplementsList(enumDecl.getImplementedTypes().stream().map(SymbolTable::resolveType) - .collect(Collectors.toList())); - - // Add enum modifiers - typeNode.setModifiers(enumDecl.getModifiers().stream().map(m -> m.toString().strip()) - .collect(Collectors.toList())); - - // Add enum annotations - typeNode.setAnnotations(enumDecl.getAnnotations().stream().map(a -> a.toString().strip()) - .collect(Collectors.toList())); - - // Add enum constants - typeNode.setEnumConstants(enumDecl.getEntries().stream() - .map(SymbolTable::processEnumConstantDeclaration).collect(Collectors.toList())); - - } else { - // TODO: handle AnnotationDeclaration, RecordDeclaration - // set the common type attributes only - Log.warn("Found unsupported type declaration: "+typeDecl.toString()); - typeNode = new com.ibm.cldk.entities.Type(); - } + .stream().filter(typeDecl -> typeDecl.getFullyQualifiedName().isPresent()) + .map(typeDecl -> { + // get type name and initialize the type object + String typeName = typeDecl.getFullyQualifiedName().get().toString(); + com.ibm.cldk.entities.Type typeNode = new com.ibm.cldk.entities.Type(); + + if (typeDecl instanceof ClassOrInterfaceDeclaration) { + ClassOrInterfaceDeclaration classDecl = (ClassOrInterfaceDeclaration) typeDecl; + + // Add interfaces implemented by class + typeNode.setImplementsList(classDecl.getImplementedTypes().stream().map(SymbolTable::resolveType) + .collect(Collectors.toList())); + + // Add class modifiers + typeNode.setModifiers(classDecl.getModifiers().stream().map(m -> m.toString().strip()) + .collect(Collectors.toList())); + + // Add class annotations + typeNode.setAnnotations(classDecl.getAnnotations().stream().map(a -> a.toString().strip()) + .collect(Collectors.toList())); + + // add booleans indicating interfaces and inner/local classes + typeNode.setInterface(classDecl.isInterface()); + typeNode.setInnerClass(classDecl.isInnerClass()); + typeNode.setLocalClass(classDecl.isLocalClassDeclaration()); + + // Add extends + typeNode.setExtendsList(classDecl.getExtendedTypes().stream() + .map(SymbolTable::resolveType) + .collect(Collectors.toList())); + + } else if (typeDecl instanceof EnumDeclaration) { + EnumDeclaration enumDecl = (EnumDeclaration) typeDecl; + + // Add interfaces implemented by enum + typeNode.setImplementsList(enumDecl.getImplementedTypes().stream().map(SymbolTable::resolveType) + .collect(Collectors.toList())); + + // Add enum modifiers + typeNode.setModifiers(enumDecl.getModifiers().stream().map(m -> m.toString().strip()) + .collect(Collectors.toList())); + + // Add enum annotations + typeNode.setAnnotations(enumDecl.getAnnotations().stream().map(a -> a.toString().strip()) + .collect(Collectors.toList())); + + // Add enum constants + typeNode.setEnumConstants(enumDecl.getEntries().stream() + .map(SymbolTable::processEnumConstantDeclaration).collect(Collectors.toList())); + + } else { + // TODO: handle AnnotationDeclaration, RecordDeclaration + // set the common type attributes only + Log.warn("Found unsupported type declaration: " + typeDecl.toString()); + typeNode = new com.ibm.cldk.entities.Type(); + } - /* set common attributes of types that available in type declarations: + /* set common attributes of types that available in type declarations: is nested type, is class or interface declaration, is enum declaration, comments, parent class, callable declarations, field declarations */ - - // Set fields indicating nested, class/interface, enum, annotation, and record types - typeNode.setNestedType(typeDecl.isNestedType()); - typeNode.setClassOrInterfaceDeclaration(typeDecl.isClassOrInterfaceDeclaration()); - typeNode.setEnumDeclaration(typeDecl.isEnumDeclaration()); - typeNode.setAnnotationDeclaration(typeDecl.isAnnotationDeclaration()); - typeNode.setRecordDeclaration(typeDecl.isRecordDeclaration()); - - // Add class comment - typeNode.setComment(typeDecl.getComment().isPresent() ? typeDecl.getComment().get().asString() : ""); - - // add parent class (for nested type declarations) - typeNode.setParentType(typeDecl.getParentNode().get() instanceof TypeDeclaration ? - ((TypeDeclaration>)typeDecl.getParentNode().get()).getFullyQualifiedName().get() : ""); - - typeNode.setNestedTypeDeclarations(typeDecl.findAll(TypeDeclaration.class).stream() - .filter(typ -> typ.isClassOrInterfaceDeclaration() || typ.isEnumDeclaration()) - .filter(typ -> typ.getParentNode().isPresent() && typ.getParentNode().get() == typeDecl) - .map(typ -> typ.getFullyQualifiedName().get().toString()).collect(Collectors.toList())); - - // Add information about declared fields (filtering to fields declared in the - // type, not in a nested type) - typeNode.setFieldDeclarations(typeDecl.findAll(FieldDeclaration.class).stream() - .filter(f -> f.getParentNode().isPresent() && f.getParentNode().get() == typeDecl) - .map(SymbolTable::processFieldDeclaration).collect(Collectors.toList())); - List fieldNames = new ArrayList<>(); - typeNode.getFieldDeclarations().stream().map(fd -> fd.getVariables()).forEach(fieldNames::addAll); - - // Add information about declared methods (filtering to methods declared in the class, not in a nested class) - typeNode.setCallableDeclarations(typeDecl.findAll(CallableDeclaration.class).stream() - .filter(c -> c.getParentNode().isPresent() && c.getParentNode().get() == typeDecl) - .map(meth -> { - Pair callableDeclaration = processCallableDeclaration(meth, fieldNames, typeName, parseResult.getStorage().map(s -> s.getPath().toString()).orElse("")); - declaredMethodsAndConstructors.put(typeName, callableDeclaration.getLeft(), callableDeclaration.getRight()); - return callableDeclaration; - }).collect(Collectors.toMap(p -> p.getLeft(), p -> p.getRight()))); - - return Pair.of(typeName, typeNode); - }).collect(Collectors.toMap(p -> p.getLeft(), p -> p.getRight()))); + // Set fields indicating nested, class/interface, enum, annotation, and record types + typeNode.setNestedType(typeDecl.isNestedType()); + typeNode.setClassOrInterfaceDeclaration(typeDecl.isClassOrInterfaceDeclaration()); + typeNode.setEnumDeclaration(typeDecl.isEnumDeclaration()); + typeNode.setAnnotationDeclaration(typeDecl.isAnnotationDeclaration()); + typeNode.setRecordDeclaration(typeDecl.isRecordDeclaration()); + + // Add class comment + typeNode.setComment(typeDecl.getComment().isPresent() ? typeDecl.getComment().get().asString() : ""); + + // add parent class (for nested type declarations) + typeNode.setParentType(typeDecl.getParentNode().get() instanceof TypeDeclaration + ? ((TypeDeclaration>) typeDecl.getParentNode().get()).getFullyQualifiedName().get() : ""); + + typeNode.setNestedTypeDeclarations(typeDecl.findAll(TypeDeclaration.class).stream() + .filter(typ -> typ.isClassOrInterfaceDeclaration() || typ.isEnumDeclaration()) + .filter(typ -> typ.getParentNode().isPresent() && typ.getParentNode().get() == typeDecl) + .map(typ -> typ.getFullyQualifiedName().get().toString()).collect(Collectors.toList())); + + // Add information about declared fields (filtering to fields declared in the + // type, not in a nested type) + typeNode.setFieldDeclarations(typeDecl.findAll(FieldDeclaration.class).stream() + .filter(f -> f.getParentNode().isPresent() && f.getParentNode().get() == typeDecl) + .map(SymbolTable::processFieldDeclaration).collect(Collectors.toList())); + List fieldNames = new ArrayList<>(); + typeNode.getFieldDeclarations().stream().map(fd -> fd.getVariables()).forEach(fieldNames::addAll); + + // Add information about declared methods (filtering to methods declared in the class, not in a nested class) + typeNode.setCallableDeclarations(typeDecl.findAll(CallableDeclaration.class).stream() + .filter(c -> c.getParentNode().isPresent() && c.getParentNode().get() == typeDecl) + .map(meth -> { + Pair callableDeclaration = processCallableDeclaration(meth, fieldNames, typeName, parseResult.getStorage().map(s -> s.getPath().toString()).orElse("")); + declaredMethodsAndConstructors.put(typeName, callableDeclaration.getLeft(), callableDeclaration.getRight()); + return callableDeclaration; + }).collect(Collectors.toMap(p -> p.getLeft(), p -> p.getRight()))); + + return Pair.of(typeName, typeNode); + }).collect(Collectors.toMap(p -> p.getLeft(), p -> p.getRight()))); return cUnit; } @@ -219,7 +216,7 @@ private static EnumConstant processEnumConstantDeclaration(EnumConstantDeclarati // add enum constant arguments enumConstant.setArguments(enumConstDecl.getArguments().stream().map(a -> a.toString()) - .collect(Collectors.toList())); + .collect(Collectors.toList())); return enumConstant; } @@ -241,15 +238,15 @@ private static ParameterInCallable processParameterDeclaration(Parameter paramDe /** * Processes the given callable declaration to extract information about the - * declared method or - * constructor and returns a JSON object containing the extracted information. + * declared method or constructor and returns a JSON object containing the + * extracted information. * * @param callableDecl callable (method or constructor) to be processed * @return Callable object containing extracted information */ @SuppressWarnings("unchecked") private static Pair processCallableDeclaration(CallableDeclaration callableDecl, - List classFields, String typeName, String filePath) { + List classFields, String typeName, String filePath) { Callable callableNode = new Callable(); // Set file path @@ -269,14 +266,16 @@ private static Pair processCallableDeclaration(CallableDeclara // add exceptions declared in "throws" clause callableNode.setThrownExceptions( - ((NodeList)callableDecl.getThrownExceptions()) - .stream() - .map(SymbolTable::resolveType) - .collect(Collectors.toList())); + ((NodeList) callableDecl.getThrownExceptions()) + .stream() + .map(SymbolTable::resolveType) + .collect(Collectors.toList())); // add the complete declaration string, including modifiers, throws, and // parameter names - callableNode.setDeclaration(callableDecl.getDeclarationAsString(true, true, true).strip()); + callableNode.setDeclaration(callableDecl + .getDeclarationAsString(true, true, true) + .strip().replaceAll("//.*\n", "")); // add information about callable parameters: for each parameter, type, name, // annotations, @@ -292,8 +291,8 @@ private static Pair processCallableDeclaration(CallableDeclara // Same as above, a constructor declaration may not have a return type // and method declaration always has a return type. - callableNode.setReturnType((callableDecl instanceof MethodDeclaration) ? - resolveType(((MethodDeclaration)callableDecl).getType()) : null); + callableNode.setReturnType((callableDecl instanceof MethodDeclaration) + ? resolveType(((MethodDeclaration) callableDecl).getType()) : null); callableNode.setConstructor(callableDecl instanceof ConstructorDeclaration); callableNode.setStartLine(callableDecl.getRange().isPresent() ? callableDecl.getRange().get().begin.line : -1); @@ -304,15 +303,36 @@ private static Pair processCallableDeclaration(CallableDeclara callableNode.setAccessedFields(getAccessedFields(body, classFields, typeName)); callableNode.setCallSites(getCallSites(body)); callableNode.setVariableDeclarations(getVariableDeclarations(body)); + callableNode.setCyclomaticComplexity(getCyclomaticComplexity(callableDecl)); String callableSignature = (callableDecl instanceof MethodDeclaration) ? callableDecl.getSignature().asString() : callableDecl.getSignature().asString().replace(callableDecl.getSignature().getName(), ""); return Pair.of(callableSignature, callableNode); } + /** + * Computes cyclomatic complexity for the given callable. + * + * @param callableDeclaration Callable to compute cyclomatic complexity for + * @return cyclomatic complexity + */ + private static int getCyclomaticComplexity(CallableDeclaration callableDeclaration) { + int ifStmtCount = callableDeclaration.findAll(IfStmt.class).size(); + int loopStmtCount = callableDeclaration.findAll(DoStmt.class).size() + + callableDeclaration.findAll(ForStmt.class).size() + + callableDeclaration.findAll(ForEachStmt.class).size() + + callableDeclaration.findAll(WhileStmt.class).size(); + int switchCaseCount = callableDeclaration.findAll(SwitchStmt.class).stream() + .map(stmt -> stmt.getEntries().size()) + .reduce(0, Integer::sum); + int conditionalExprCount = callableDeclaration.findAll(ConditionalExpr.class).size(); + int catchClauseCount = callableDeclaration.findAll(CatchClause.class).size(); + return ifStmtCount + loopStmtCount + switchCaseCount + conditionalExprCount + catchClauseCount + 1; + } + /** * Processes the given field declaration to extract information about the - * declared field and - * returns a JSON object containing the extracted information. + * declared field and returns a JSON object containing the extracted + * information. * * @param fieldDecl field declaration to be processed * @return Field object containing extracted information @@ -345,8 +365,7 @@ private static Field processFieldDeclaration(FieldDeclaration fieldDecl) { /** * Computes and returns the set of types references in a block of statement - * (method or constructor - * body). + * (method or constructor body). * * @param blockStmt Block statement to compute referenced types for * @return List of types referenced in the block statement @@ -354,33 +373,33 @@ private static Field processFieldDeclaration(FieldDeclaration fieldDecl) { private static List getReferencedTypes(Optional blockStmt) { Set referencedTypes = new HashSet<>(); blockStmt.ifPresent(bs -> bs.findAll(VariableDeclarator.class) - .stream() - .filter(vd -> vd.getType().isClassOrInterfaceType()) - .map(vd -> resolveType(vd.getType())) - .forEach(referencedTypes::add)); + .stream() + .filter(vd -> vd.getType().isClassOrInterfaceType()) + .map(vd -> resolveType(vd.getType())) + .forEach(referencedTypes::add)); // add types of accessed fields to the set of referenced types blockStmt.ifPresent(bs -> bs.findAll(FieldAccessExpr.class) - .stream() - .filter(faExpr -> faExpr.getParentNode().isPresent() && !(faExpr.getParentNode().get() instanceof FieldAccessExpr)) - .map(faExpr -> { - if (faExpr.getParentNode().isPresent() && faExpr.getParentNode().get() instanceof CastExpr) { - return resolveType(((CastExpr)faExpr.getParentNode().get()).getType()); - } else { - return resolveExpression(faExpr); - } - }) - .filter(type -> !type.isEmpty()) - .forEach(referencedTypes::add)); + .stream() + .filter(faExpr -> faExpr.getParentNode().isPresent() && !(faExpr.getParentNode().get() instanceof FieldAccessExpr)) + .map(faExpr -> { + if (faExpr.getParentNode().isPresent() && faExpr.getParentNode().get() instanceof CastExpr) { + return resolveType(((CastExpr) faExpr.getParentNode().get()).getType()); + } else { + return resolveExpression(faExpr); + } + }) + .filter(type -> !type.isEmpty()) + .forEach(referencedTypes::add)); // TODO: add resolved method access expressions - return new ArrayList<>(referencedTypes); } /** - * Returns information about variable declarations in the given callable. The information includes - * var name, var type, var initializer, and position. + * Returns information about variable declarations in the given callable. + * The information includes var name, var type, var initializer, and + * position. * * @param blockStmt Callable to compute var declaration information for * @return list of variable declarations @@ -394,8 +413,8 @@ private static List getVariableDeclarations(Optional getVariableDeclarations(Optional getAccessedFields(Optional callableBody, List classFields, - String typeName) { + String typeName) { Set accessedFields = new HashSet<>(); // process field access expressions in the callable callableBody.ifPresent(cb -> cb.findAll(FieldAccessExpr.class) - .stream() - .filter(faExpr -> faExpr.getParentNode().isPresent() && !(faExpr.getParentNode().get() instanceof FieldAccessExpr)) - .map(faExpr -> { - String fieldDeclaringType = resolveExpression(faExpr.getScope()); - if (!fieldDeclaringType.isEmpty()) { - return fieldDeclaringType + "." + faExpr.getNameAsString(); - } else { - return faExpr.getNameAsString(); - } - }) - .forEach(accessedFields::add) + .stream() + .filter(faExpr -> faExpr.getParentNode().isPresent() && !(faExpr.getParentNode().get() instanceof FieldAccessExpr)) + .map(faExpr -> { + String fieldDeclaringType = resolveExpression(faExpr.getScope()); + if (!fieldDeclaringType.isEmpty()) { + return fieldDeclaringType + "." + faExpr.getNameAsString(); + } else { + return faExpr.getNameAsString(); + } + }) + .forEach(accessedFields::add) ); // process all names expressions in callable and match against names of declared fields @@ -454,8 +474,9 @@ private static List getAccessedFields(Optional callableBody, } /** - * Returns information about call sites in the given callable. The information includes: - * the method name, the declaring type name, and types of arguments used in method call. + * Returns information about call sites in the given callable. The + * information includes: the method name, the declaring type name, and types + * of arguments used in method call. * * @param callableBody callable to compute call-site information for * @return list of call sites @@ -478,8 +499,8 @@ private static List getCallSites(Optional callableBody) { if (declaringType.contains(" | ")) { declaringType = declaringType.split(" \\| ")[0]; } - String declaringTypeName = declaringType.contains(".") ? - declaringType.substring(declaringType.lastIndexOf(".")+1) : declaringType; + String declaringTypeName = declaringType.contains(".") + ? declaringType.substring(declaringType.lastIndexOf(".") + 1) : declaringType; if (declaringTypeName.equals(scopeExpr.toString())) { isStaticCall = true; } @@ -487,7 +508,7 @@ private static List getCallSites(Optional callableBody) { // compute return type for method call taking into account typecast of return value if (methodCallExpr.getParentNode().isPresent() && methodCallExpr.getParentNode().get() instanceof CastExpr) { - returnType = resolveType(((CastExpr)methodCallExpr.getParentNode().get()).getType()); + returnType = resolveType(((CastExpr) methodCallExpr.getParentNode().get()).getType()); } else { returnType = resolveExpression(methodCallExpr); } @@ -505,16 +526,15 @@ private static List getCallSites(Optional callableBody) { try { ResolvedMethodDeclaration resolvedMethodDeclaration = methodCallExpr.resolve(); accessSpecifier = resolvedMethodDeclaration.accessSpecifier(); - } - catch (RuntimeException exception) { + } catch (RuntimeException exception) { Log.debug("Could not resolve access specifier for method call: " + methodCallExpr + ": " + exception.getMessage()); } // resolve arguments of the method call to types List arguments = methodCallExpr.getArguments().stream() - .map(SymbolTable::resolveExpression).collect(Collectors.toList()); + .map(SymbolTable::resolveExpression).collect(Collectors.toList()); // add a new call site object callSites.add(createCallSite(methodCallExpr, methodCallExpr.getNameAsString(), receiverName, declaringType, - arguments, returnType, calleeSignature, isStaticCall, false, accessSpecifier)); + arguments, returnType, calleeSignature, isStaticCall, false, accessSpecifier)); } for (ObjectCreationExpr objectCreationExpr : callableBody.get().findAll(ObjectCreationExpr.class)) { @@ -523,7 +543,7 @@ private static List getCallSites(Optional callableBody) { // resolve arguments of the constructor call to types List arguments = objectCreationExpr.getArguments().stream() - .map(SymbolTable::resolveExpression).collect(Collectors.toList()); + .map(SymbolTable::resolveExpression).collect(Collectors.toList()); // resolve callee and get signature String calleeSignature = ""; @@ -535,20 +555,20 @@ private static List getCallSites(Optional callableBody) { // add a new call site object callSites.add(createCallSite(objectCreationExpr, "", - objectCreationExpr.getScope().isPresent() ? objectCreationExpr.getScope().get().toString() : "", - instantiatedType, arguments, instantiatedType, calleeSignature,false, true, AccessSpecifier.NONE)); + objectCreationExpr.getScope().isPresent() ? objectCreationExpr.getScope().get().toString() : "", + instantiatedType, arguments, instantiatedType, calleeSignature, false, true, AccessSpecifier.NONE)); } return callSites; } /** - * Creates and returns a new CallSite object for the given expression, which can be a method-call or - * object-creation expression. + * Creates and returns a new CallSite object for the given expression, which + * can be a method-call or object-creation expression. * * @param callExpr * @param calleeName - * @param receiverExpr + * @param receiverExpr * @param receiverType * @param arguments * @param isStaticCall @@ -556,8 +576,8 @@ private static List getCallSites(Optional callableBody) { * @return */ private static CallSite createCallSite(Expression callExpr, String calleeName, String receiverExpr, - String receiverType, List arguments, String returnType, - String calleeSignature, boolean isStaticCall, boolean isConstructorCall, AccessSpecifier accessSpecifier) { + String receiverType, List arguments, String returnType, + String calleeSignature, boolean isStaticCall, boolean isConstructorCall, AccessSpecifier accessSpecifier) { CallSite callSite = new CallSite(); callSite.setMethodName(calleeName); callSite.setReceiverExpr(receiverExpr); @@ -586,8 +606,8 @@ private static CallSite createCallSite(Expression callExpr, String calleeName, S } /** - * Calculates type for the given expression and returns the resolved type name, or empty string if - * exception occurs during type resolution. + * Calculates type for the given expression and returns the resolved type + * name, or empty string if exception occurs during type resolution. * * @param expression Expression to be resolved * @return Resolved type name or empty string if type resolution fails @@ -609,8 +629,10 @@ private static String resolveExpression(Expression expression) { } /** - * Resolves the given type and returns string representation of the resolved type. If type resolution - * fails, returns string representation (name) of the type. + * Resolves the given type and returns string representation of the resolved + * type. If type resolution fails, returns string representation (name) of + * the type. + * * @param type Type to be resolved * @return Resolved (qualified) type name */ @@ -628,18 +650,20 @@ private static String resolveType(Type type) { } /** - * Collects all source roots (e.g., "src/main/java", "src/test/java") under the given project root path - * using the symbol solver collection strategy. Parses all source files under each source root and - * returns the complete symbol table as map of file path and java compilation unit pairs. + * Collects all source roots (e.g., "src/main/java", "src/test/java") under + * the given project root path using the symbol solver collection strategy. + * Parses all source files under each source root and returns the complete + * symbol table as map of file path and java compilation unit pairs. * * @param projectRootPath root path of the project to be analyzed - * @return Pair of extracted symbol table map and parse problems map for project + * @return Pair of extracted symbol table map and parse problems map for + * project * @throws IOException */ public static Pair, Map>> extractAll(Path projectRootPath) throws IOException { SymbolSolverCollectionStrategy symbolSolverCollectionStrategy = new SymbolSolverCollectionStrategy(); ProjectRoot projectRoot = symbolSolverCollectionStrategy.collect(projectRootPath); - javaSymbolSolver = (JavaSymbolSolver)symbolSolverCollectionStrategy.getParserConfiguration().getSymbolResolver().get(); + javaSymbolSolver = (JavaSymbolSolver) symbolSolverCollectionStrategy.getParserConfiguration().getSymbolResolver().get(); Map symbolTable = new LinkedHashMap<>(); Map> parseProblems = new HashMap<>(); for (SourceRoot sourceRoot : projectRoot.getSourceRoots()) { @@ -647,8 +671,8 @@ public static Pair, Map>> if (parseResult.isSuccessful()) { CompilationUnit compilationUnit = parseResult.getResult().get(); symbolTable.put( - compilationUnit.getStorage().get().getPath().toString(), - processCompilationUnit(compilationUnit) + compilationUnit.getStorage().get().getPath().toString(), + processCompilationUnit(compilationUnit) ); } else { parseProblems.put(sourceRoot.getRoot().toString(), parseResult.getProblems()); @@ -682,7 +706,9 @@ public static Pair, Map>> } /** - * Parses the given set of Java source files from the given project and constructs the symbol table. + * Parses the given set of Java source files from the given project and + * constructs the symbol table. + * * @param projectRootPath * @param javaFilePaths * @return @@ -696,7 +722,7 @@ public static Pair, Map>> // create symbol solver and parser configuration SymbolSolverCollectionStrategy symbolSolverCollectionStrategy = new SymbolSolverCollectionStrategy(); ProjectRoot projectRoot = symbolSolverCollectionStrategy.collect(projectRootPath); - javaSymbolSolver = (JavaSymbolSolver)symbolSolverCollectionStrategy.getParserConfiguration().getSymbolResolver().get(); + javaSymbolSolver = (JavaSymbolSolver) symbolSolverCollectionStrategy.getParserConfiguration().getSymbolResolver().get(); ParserConfiguration parserConfiguration = new ParserConfiguration(); parserConfiguration.setSymbolResolver(javaSymbolSolver); diff --git a/src/main/java/com/ibm/cldk/SystemDependencyGraph.java b/src/main/java/com/ibm/cldk/SystemDependencyGraph.java index 4ea8b301..06fca3b9 100644 --- a/src/main/java/com/ibm/cldk/SystemDependencyGraph.java +++ b/src/main/java/com/ibm/cldk/SystemDependencyGraph.java @@ -13,10 +13,7 @@ package com.ibm.cldk; -import com.ibm.cldk.entities.AbstractGraphEdge; -import com.ibm.cldk.entities.CallEdge; -import com.ibm.cldk.entities.CallableVertex; -import com.ibm.cldk.entities.SystemDepEdge; +import com.ibm.cldk.entities.*; import com.ibm.cldk.utils.AnalysisUtils; import com.ibm.cldk.utils.Log; import com.ibm.cldk.utils.ScopeUtils; @@ -53,8 +50,7 @@ import java.util.function.Supplier; import java.util.stream.Collectors; -import static com.ibm.cldk.utils.AnalysisUtils.createAndPutNewCallableInSymbolTable; -import static com.ibm.cldk.utils.AnalysisUtils.getCallableFromSymbolTable; +import static com.ibm.cldk.utils.AnalysisUtils.*; @Data @@ -277,7 +273,13 @@ public static List construct( + Math.ceil((double) (System.currentTimeMillis() - start_time) / 1000) + " seconds."); // set cyclomatic complexity for callables in the symbol table - AnalysisUtils.setCyclomaticComplexity(callGraph); + callGraph.forEach(cgNode -> { + Callable callable = getCallableObjectFromSymbolTable(cgNode.getMethod()).getRight(); + if (callable != null) { + callable.setCyclomaticComplexity(getCyclomaticComplexity(cgNode.getIR())); + } + }); + // Build SDG graph Log.info("Building System Dependency Graph."); diff --git a/src/main/java/com/ibm/cldk/entities/CallSite.java b/src/main/java/com/ibm/cldk/entities/CallSite.java index 83dd5ba5..a0437884 100644 --- a/src/main/java/com/ibm/cldk/entities/CallSite.java +++ b/src/main/java/com/ibm/cldk/entities/CallSite.java @@ -19,6 +19,7 @@ public class CallSite { private boolean isUnspecified = false; private boolean isStaticCall; private boolean isConstructorCall; + private boolean isDatabase = false; private int startLine; private int startColumn; private int endLine; diff --git a/src/main/java/com/ibm/cldk/utils/AnalysisUtils.java b/src/main/java/com/ibm/cldk/utils/AnalysisUtils.java index 3313c75b..db7d0bce 100644 --- a/src/main/java/com/ibm/cldk/utils/AnalysisUtils.java +++ b/src/main/java/com/ibm/cldk/utils/AnalysisUtils.java @@ -9,8 +9,7 @@ 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. -*/ - + */ package com.ibm.cldk.utils; import static com.ibm.cldk.SymbolTable.declaredMethodsAndConstructors; @@ -35,6 +34,9 @@ import org.apache.commons.lang3.tuple.Pair; import org.objectweb.asm.Type; +import com.ibm.wala.ssa.ISSABasicBlock; +import com.ibm.wala.ssa.SSASwitchInstruction; + /** * The type Analysis utils. */ @@ -93,36 +95,31 @@ public static Map createAndPutNewCallableInSymbolTable(IMethod m } /** - * Computes and returns cyclomatic complexity for the given IR (for a method or constructor). + * Computes and returns cyclomatic complexity for the given IR (for a method + * or constructor). * * @param ir IR for method or constructor * @return int Cyclomatic complexity for method/constructor */ public static int getCyclomaticComplexity(IR ir) { - int branchCount = (int)Arrays.stream(ir.getInstructions()) - .filter(inst -> inst instanceof SSAConditionalBranchInstruction) - .count(); - return branchCount + 1; - } - - public static void setCyclomaticComplexity(CallGraph callGraph) { - callGraph.forEach( - cgNode -> { - if (cgNode.getMethod() != null) { - IMethod method = cgNode.getMethod(); - String declaringClassSignature = method.getDeclaringClass().getName().toString().substring(1).replace("/", ".").replace("$", "."); - List arguments = Arrays.stream(Type.getMethodType(method.getDescriptor().toString()).getArgumentTypes()).map(Type::getClassName).collect(Collectors.toList()); - String methodSignature = String.join("", method.getName().toString(), "(", String.join(", ", Optional.of(arguments).orElseGet(Collections::emptyList)), ")"); - Callable callable = declaredMethodsAndConstructors.get(declaringClassSignature, methodSignature); - if (callable != null) { - callable.setCyclomaticComplexity(getCyclomaticComplexity(cgNode.getIR())); - } - } - } - ); + if (ir == null) { + return 0; + } + int conditionalBranchCount = (int) Arrays.stream(ir.getInstructions()) + .filter(inst -> inst instanceof SSAConditionalBranchInstruction) + .count(); + int switchBranchCount = Arrays.stream(ir.getInstructions()) + .filter(inst -> inst instanceof SSASwitchInstruction) + .map(inst -> ((SSASwitchInstruction) inst).getCasesAndLabels().length).reduce(0, Integer::sum); + Iterable iterableBasicBlocks = ir::getBlocks; + int catchBlockCount = (int) StreamSupport.stream(iterableBasicBlocks.spliterator(), false) + .filter(ISSABasicBlock::isCatchBlock) + .count(); + return conditionalBranchCount + switchBranchCount + catchBlockCount + 1; } public static Map getCallableFromSymbolTable(IMethod method) { + // Get the class name, with a . representation. String declaringClassSignature = method.getDeclaringClass().getName().toString().substring(1).replace("/", ".").replace("$", "."); @@ -133,9 +130,9 @@ public static Map getCallableFromSymbolTable(IMethod method) { String methodSignature = String.join("", method.getName().toString(), "(", String.join(", ", Optional.of(arguments).orElseGet(Collections::emptyList)), ")"); Callable callable = declaredMethodsAndConstructors.get(declaringClassSignature, methodSignature); - if (callable == null) + if (callable == null) { return null; - else{ + } else { String signature = callable.getSignature(); if (signature.contains("")) { signature = signature.replace("", declaringClassSignature.substring(declaringClassSignature.lastIndexOf(".") + 1)); @@ -151,6 +148,21 @@ public static Map getCallableFromSymbolTable(IMethod method) { } } + public static Pair getCallableObjectFromSymbolTable(IMethod method) { + + // Get the class name, with a . representation. + String declaringClassSignature = method.getDeclaringClass().getName().toString().substring(1).replace("/", ".").replace("$", "."); + + // Get the method arguments, use a . notation for types. + List arguments = Arrays.stream(Type.getMethodType(method.getDescriptor().toString()).getArgumentTypes()).map(Type::getClassName).collect(Collectors.toList()); + + // Get the method signature. + String methodSignature = String.join("", method.getName().toString(), "(", String.join(", ", Optional.of(arguments).orElseGet(Collections::emptyList)), ")"); + + return Pair.of(declaringClassSignature, declaredMethodsAndConstructors.get(declaringClassSignature, methodSignature)); + } + + /** * Verfy if a class is an application class. * diff --git a/src/main/java/com/ibm/cldk/utils/BuildProject.java b/src/main/java/com/ibm/cldk/utils/BuildProject.java index ed0ce653..541eef0b 100644 --- a/src/main/java/com/ibm/cldk/utils/BuildProject.java +++ b/src/main/java/com/ibm/cldk/utils/BuildProject.java @@ -7,18 +7,47 @@ 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; import java.util.List; +import static com.ibm.cldk.CodeAnalyzer.projectRootPom; import static com.ibm.cldk.utils.ProjectDirectoryScanner.classFilesStream; public class BuildProject { public static Path libDownloadPath; private static final String LIB_DEPS_DOWNLOAD_DIR = "_library_dependencies"; - private static final String MAVEN_CMD = System.getProperty("os.name").toLowerCase().contains("windows") ? "mvn.cmd" : "mvn"; - private static final String GRADLE_CMD = System.getProperty("os.name").toLowerCase().contains("windows") ? "gradlew.bat" : "gradlew"; - public static Path tempInitScript; + private static final String MAVEN_CMD = BuildProject.getMavenCommand(); + private static final String GRADLE_CMD = BuildProject.getGradleCommand(); + + /** + * Gets the maven command to be used for building the project. + * + * @return the maven command + */ + 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; + } + + /** + * Gets the gradle command to be used for building the project. + * + * @return the gradle command + */ + 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"); + + return commandExists(gradleWrapper).getKey() ? gradleWrapper.toString() : gradleSystemCommand; + } + + public static Path tempInitScript; + static { try { tempInitScript = Files.createTempFile("gradle-init-", ".gradle"); @@ -26,28 +55,40 @@ public class BuildProject { throw new RuntimeException(e); } } - 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(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(String.valueOf(command), "--version").start(); + // Read the output stream + 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())); + while ((line = errorReader.readLine()) != null) { + output.append(line).append("\n"); + } + + int exitCode = process.waitFor(); + return new AbstractMap.SimpleEntry<>(exitCode == 0, output.toString().trim()); + } catch (IOException | InterruptedException exceptions) { + 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(buildCommand); - + ProcessBuilder processBuilder = new ProcessBuilder().directory(new File(projectRootPom)).command(buildCommand); try { Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); @@ -71,13 +112,12 @@ private static boolean buildWithTool(String[] buildCommand) { * @return true if Maven is installed, false otherwise. */ private static boolean isMavenInstalled() { - ProcessBuilder processBuilder = new ProcessBuilder(MAVEN_CMD, "--version"); + ProcessBuilder processBuilder = new ProcessBuilder().directory(new File(projectRootPom)).command(MAVEN_CMD, "--version"); try { Process process = processBuilder.start(); 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) { @@ -99,19 +139,19 @@ 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); } public static boolean gradleBuild(String projectPath) { // Adjust Gradle command as needed - String gradleWrapper = projectPath + File.separator + GRADLE_CMD; - String[] gradleCommand = {gradleWrapper, "clean", "compileJava", "-p", 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 { + gradleCommand = new String[]{GRADLE_CMD, "clean", "compileJava", "-p", projectPath}; + } return buildWithTool(gradleCommand); } @@ -143,18 +183,19 @@ private static boolean buildProject(String projectPath, String build) { * @return true if the streaming was successful, false otherwise. */ public static List buildProjectAndStreamClassFiles(String projectPath, String build) throws IOException { - return buildProject(projectPath, build) ? classFilesStream(projectPath) : null; + return buildProject(projectPath, build) ? classFilesStream(projectPath) : new ArrayList<>(); } /** - * Downloads library dependency jars of the given project so that the jars can be used - * for type resolution during symbol table creation. + * Downloads library dependency jars of the given project so that the jars + * can be used for type resolution during symbol table creation. * * @param projectPath Path to the project under analysis * @return true if dependency download succeeds; false otherwise */ - public static boolean downloadLibraryDependencies(String projectPath) throws IOException { + public static boolean downloadLibraryDependencies(String projectPath, String projectRootPom) throws IOException { // created download dir if it does not exist + String projectRoot = projectRootPom != null ? projectRootPom : projectPath; libDownloadPath = Paths.get(projectPath, LIB_DEPS_DOWNLOAD_DIR).toAbsolutePath(); if (!Files.exists(libDownloadPath)) { try { @@ -164,21 +205,40 @@ public static boolean downloadLibraryDependencies(String projectPath) throws IOE return false; } } - File pomFile = new File(projectPath, "pom.xml"); + 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."); - String[] mavenCommand = { - MAVEN_CMD, "--no-transfer-progress", "-f", - Paths.get(projectPath, "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(projectPath, "build.gradle").exists() || new File(projectPath, "build.gradle.kts").exists()) { - Log.info("Found build.gradle[.kts] in the project directory. Using Gradle to download dependencies."); + } else if (new File(projectRoot, "build.gradle").exists() || new File(projectRoot, "build.gradle.kts").exists()) { + 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 = {projectPath + File.separator + GRADLE_CMD, "--init-script", tempInitScript.toFile().getAbsolutePath(), "downloadDependencies", "-PoutputDir="+libDownloadPath.toString()}; - System.out.println(Arrays.toString(gradleCommand)); + 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 { + gradleCommand = new String[]{GRADLE_CMD, "--init-script", tempInitScript.toFile().getAbsolutePath(), "downloadDependencies", "-PoutputDir=" + libDownloadPath.toString()}; + } return buildWithTool(gradleCommand); } return false; @@ -188,10 +248,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/test/java/com/ibm/cldk/CodeAnalyzerIntegrationTest.java b/src/test/java/com/ibm/cldk/CodeAnalyzerIntegrationTest.java new file mode 100644 index 00000000..4b5a19f8 --- /dev/null +++ b/src/test/java/com/ibm/cldk/CodeAnalyzerIntegrationTest.java @@ -0,0 +1,145 @@ +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")), "/"); + + @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")), "/"); + + + @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.assertFalse(runCodeAnalyzerJar.getStdout().isEmpty(), "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 96b0df4f..00000000 --- a/src/test/java/com/ibm/cldk/CodeAnalyzerTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.ibm.cldk; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -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 testOutputJSONShape() { - - } - - private boolean compareJsonStructure(JsonElement referenceElement, JsonElement actualElement) { - if (referenceElement.isJsonObject() && actualElement.isJsonObject()) { - JsonObject referenceObject = referenceElement.getAsJsonObject(); - JsonObject actualObject = actualElement.getAsJsonObject(); - - // Ensure that all keys in the reference JSON are present in the actual JSON - for (String key : referenceObject.keySet()) { - if (!actualObject.has(key)) { - return false; - } - // Recursively compare the child elements - if (!compareJsonStructure(referenceObject.get(key), actualObject.get(key))) { - return false; - } - } - } else if (referenceElement.isJsonArray() && actualElement.isJsonArray()) { - // If both are arrays, compare their elements - JsonArray referenceArray = referenceElement.getAsJsonArray(); - JsonArray actualArray = actualElement.getAsJsonArray(); - if (referenceArray.size() != actualArray.size()) { - return false; - } - for (int i = 0; i < referenceArray.size(); i++) { - if (!compareJsonStructure(referenceArray.get(i), actualArray.get(i))) { - return false; - } - } - } - // If neither is an object or array, just return true (for primitives) - return true; - } -} \ 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/gradlew-corrupt-test/.dockerignore b/src/test/resources/gradlew-corrupt-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/resources/gradlew-corrupt-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/resources/gradlew-corrupt-test/.gitignore b/src/test/resources/gradlew-corrupt-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/resources/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/gradlew-corrupt-test/Dockerfile b/src/test/resources/gradlew-corrupt-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/resources/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/gradlew-corrupt-test/README.txt b/src/test/resources/gradlew-corrupt-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/resources/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/gradlew-corrupt-test/build.gradle b/src/test/resources/gradlew-corrupt-test/build.gradle new file mode 100644 index 00000000..c80e50c1 --- /dev/null +++ b/src/test/resources/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/gradlew-corrupt-test/build/tmp/compileJava/previous-compilation-data.bin b/src/test/resources/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/gradlew-corrupt-test/build/tmp/compileJava/previous-compilation-data.bin differ diff --git a/src/test/resources/gradlew-corrupt-test/gradle/wrapper/gradle-wrapper.jar b/src/test/resources/gradlew-corrupt-test/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..7454180f Binary files /dev/null and b/src/test/resources/gradlew-corrupt-test/gradle/wrapper/gradle-wrapper.jar differ diff --git a/src/test/resources/gradlew-corrupt-test/gradle/wrapper/gradle-wrapper.properties b/src/test/resources/gradlew-corrupt-test/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..2e6e5897 --- /dev/null +++ b/src/test/resources/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/gradlew-corrupt-test/gradlew b/src/test/resources/gradlew-corrupt-test/gradlew new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/gradlew-corrupt-test/gradlew.bat b/src/test/resources/gradlew-corrupt-test/gradlew.bat new file mode 100644 index 00000000..ac1b06f9 --- /dev/null +++ b/src/test/resources/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/gradlew-corrupt-test/settings.gradle b/src/test/resources/gradlew-corrupt-test/settings.gradle new file mode 100644 index 00000000..81f4ec38 --- /dev/null +++ b/src/test/resources/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/gradlew-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/resources/gradlew-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/resources/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/gradlew-corrupt-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/resources/gradlew-corrupt-test/src/main/java/com/demo/rest/RestApplication.java new file mode 100644 index 00000000..eb0e4660 --- /dev/null +++ b/src/test/resources/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/gradlew-corrupt-test/src/main/liberty/config/server.xml b/src/test/resources/gradlew-corrupt-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/resources/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/gradlew-corrupt-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/resources/gradlew-corrupt-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/gradlew-working-test/.dockerignore b/src/test/resources/gradlew-working-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/resources/gradlew-working-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/resources/gradlew-working-test/.gitignore b/src/test/resources/gradlew-working-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/resources/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/gradlew-working-test/Dockerfile b/src/test/resources/gradlew-working-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/resources/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/gradlew-working-test/README.txt b/src/test/resources/gradlew-working-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/resources/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/gradlew-working-test/build.gradle b/src/test/resources/gradlew-working-test/build.gradle new file mode 100644 index 00000000..c80e50c1 --- /dev/null +++ b/src/test/resources/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/gradlew-working-test/build/tmp/compileJava/previous-compilation-data.bin b/src/test/resources/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/gradlew-working-test/build/tmp/compileJava/previous-compilation-data.bin differ diff --git a/src/test/resources/gradlew-working-test/gradle/wrapper/gradle-wrapper.jar b/src/test/resources/gradlew-working-test/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..7454180f Binary files /dev/null and b/src/test/resources/gradlew-working-test/gradle/wrapper/gradle-wrapper.jar differ diff --git a/src/test/resources/gradlew-working-test/gradle/wrapper/gradle-wrapper.properties b/src/test/resources/gradlew-working-test/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..2e6e5897 --- /dev/null +++ b/src/test/resources/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/gradlew-working-test/gradlew b/src/test/resources/gradlew-working-test/gradlew new file mode 100755 index 00000000..1b6c7873 --- /dev/null +++ b/src/test/resources/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/gradlew-working-test/gradlew.bat b/src/test/resources/gradlew-working-test/gradlew.bat new file mode 100644 index 00000000..ac1b06f9 --- /dev/null +++ b/src/test/resources/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/gradlew-working-test/settings.gradle b/src/test/resources/gradlew-working-test/settings.gradle new file mode 100644 index 00000000..81f4ec38 --- /dev/null +++ b/src/test/resources/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/gradlew-working-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/resources/gradlew-working-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/resources/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/gradlew-working-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/resources/gradlew-working-test/src/main/java/com/demo/rest/RestApplication.java new file mode 100644 index 00000000..eb0e4660 --- /dev/null +++ b/src/test/resources/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/gradlew-working-test/src/main/liberty/config/server.xml b/src/test/resources/gradlew-working-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/resources/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/gradlew-working-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/resources/gradlew-working-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/mvnw-corrupt-test/.dockerignore b/src/test/resources/mvnw-corrupt-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/resources/mvnw-corrupt-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/resources/mvnw-corrupt-test/.gitignore b/src/test/resources/mvnw-corrupt-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/resources/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/mvnw-corrupt-test/.mvn/wrapper/maven-wrapper.properties b/src/test/resources/mvnw-corrupt-test/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..207aa436 --- /dev/null +++ b/src/test/resources/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/mvnw-corrupt-test/Dockerfile b/src/test/resources/mvnw-corrupt-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/resources/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/mvnw-corrupt-test/README.txt b/src/test/resources/mvnw-corrupt-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/resources/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/mvnw-corrupt-test/mvnw b/src/test/resources/mvnw-corrupt-test/mvnw new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/mvnw-corrupt-test/pom.xml b/src/test/resources/mvnw-corrupt-test/pom.xml new file mode 100644 index 00000000..9b78f42c --- /dev/null +++ b/src/test/resources/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/mvnw-corrupt-test/settings.gradle b/src/test/resources/mvnw-corrupt-test/settings.gradle new file mode 100644 index 00000000..81f4ec38 --- /dev/null +++ b/src/test/resources/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/mvnw-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/resources/mvnw-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/resources/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/mvnw-corrupt-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/resources/mvnw-corrupt-test/src/main/java/com/demo/rest/RestApplication.java new file mode 100644 index 00000000..eb0e4660 --- /dev/null +++ b/src/test/resources/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/mvnw-corrupt-test/src/main/liberty/config/server.xml b/src/test/resources/mvnw-corrupt-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/resources/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/mvnw-corrupt-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/resources/mvnw-corrupt-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/mvnw-working-test/.dockerignore b/src/test/resources/mvnw-working-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/resources/mvnw-working-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/resources/mvnw-working-test/.gitignore b/src/test/resources/mvnw-working-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/resources/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/mvnw-working-test/.mvn/wrapper/maven-wrapper.properties b/src/test/resources/mvnw-working-test/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..2f093d08 --- /dev/null +++ b/src/test/resources/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/mvnw-working-test/Dockerfile b/src/test/resources/mvnw-working-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/resources/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/mvnw-working-test/README.txt b/src/test/resources/mvnw-working-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/resources/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/mvnw-working-test/mvnw b/src/test/resources/mvnw-working-test/mvnw new file mode 100755 index 00000000..19529ddf --- /dev/null +++ b/src/test/resources/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/mvnw-working-test/mvnw.cmd b/src/test/resources/mvnw-working-test/mvnw.cmd new file mode 100644 index 00000000..b150b91e --- /dev/null +++ b/src/test/resources/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/mvnw-working-test/pom.xml b/src/test/resources/mvnw-working-test/pom.xml new file mode 100644 index 00000000..9b78f42c --- /dev/null +++ b/src/test/resources/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/mvnw-working-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/resources/mvnw-working-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/resources/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/mvnw-working-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/resources/mvnw-working-test/src/main/java/com/demo/rest/RestApplication.java new file mode 100644 index 00000000..eb0e4660 --- /dev/null +++ b/src/test/resources/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/mvnw-working-test/src/main/liberty/config/server.xml b/src/test/resources/mvnw-working-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/resources/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/mvnw-working-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/resources/mvnw-working-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/no-mvnw-test/.dockerignore b/src/test/resources/no-mvnw-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/resources/no-mvnw-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/resources/no-mvnw-test/.gitignore b/src/test/resources/no-mvnw-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/resources/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/no-mvnw-test/.mvn/wrapper/maven-wrapper.properties b/src/test/resources/no-mvnw-test/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..207aa436 --- /dev/null +++ b/src/test/resources/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/no-mvnw-test/Dockerfile b/src/test/resources/no-mvnw-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/resources/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/no-mvnw-test/README.txt b/src/test/resources/no-mvnw-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/resources/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/no-mvnw-test/pom.xml b/src/test/resources/no-mvnw-test/pom.xml new file mode 100644 index 00000000..9b78f42c --- /dev/null +++ b/src/test/resources/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/no-mvnw-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/resources/no-mvnw-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/resources/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/no-mvnw-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/resources/no-mvnw-test/src/main/java/com/demo/rest/RestApplication.java new file mode 100644 index 00000000..eb0e4660 --- /dev/null +++ b/src/test/resources/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/no-mvnw-test/src/main/liberty/config/server.xml b/src/test/resources/no-mvnw-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/resources/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/no-mvnw-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/resources/no-mvnw-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b diff --git a/src/test/test-applications copy/.gitignore b/src/test/test-applications copy/.gitignore new file mode 100644 index 00000000..4d81f976 --- /dev/null +++ b/src/test/test-applications copy/.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/test-applications copy/gradlew-corrupt-test/.dockerignore b/src/test/test-applications copy/gradlew-corrupt-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/test-applications copy/gradlew-corrupt-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/test-applications copy/gradlew-corrupt-test/.gitignore b/src/test/test-applications copy/gradlew-corrupt-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-corrupt-test/Dockerfile b/src/test/test-applications copy/gradlew-corrupt-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-corrupt-test/README.txt b/src/test/test-applications copy/gradlew-corrupt-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-corrupt-test/build.gradle b/src/test/test-applications copy/gradlew-corrupt-test/build.gradle new file mode 100644 index 00000000..c80e50c1 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-corrupt-test/gradle/wrapper/gradle-wrapper.properties b/src/test/test-applications copy/gradlew-corrupt-test/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..2e6e5897 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-corrupt-test/gradlew b/src/test/test-applications copy/gradlew-corrupt-test/gradlew new file mode 100644 index 00000000..e69de29b diff --git a/src/test/test-applications copy/gradlew-corrupt-test/gradlew.bat b/src/test/test-applications copy/gradlew-corrupt-test/gradlew.bat new file mode 100644 index 00000000..ac1b06f9 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-corrupt-test/settings.gradle b/src/test/test-applications copy/gradlew-corrupt-test/settings.gradle new file mode 100644 index 00000000..81f4ec38 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/test-applications copy/gradlew-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-corrupt-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/test-applications copy/gradlew-corrupt-test/src/main/java/com/demo/rest/RestApplication.java new file mode 100644 index 00000000..eb0e4660 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-corrupt-test/src/main/liberty/config/server.xml b/src/test/test-applications copy/gradlew-corrupt-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/test-applications copy/gradlew-corrupt-test/src/main/liberty/config/server.xml @@ -0,0 +1,42 @@ + + + + + + javaee-7.0 + microProfile-1.4 + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-applications copy/gradlew-corrupt-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/test-applications copy/gradlew-corrupt-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b diff --git a/src/test/test-applications copy/gradlew-working-test/.dockerignore b/src/test/test-applications copy/gradlew-working-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/test-applications copy/gradlew-working-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/test-applications copy/gradlew-working-test/.gitignore b/src/test/test-applications copy/gradlew-working-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-working-test/Dockerfile b/src/test/test-applications copy/gradlew-working-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-working-test/README.txt b/src/test/test-applications copy/gradlew-working-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-working-test/build.gradle b/src/test/test-applications copy/gradlew-working-test/build.gradle new file mode 100644 index 00000000..c80e50c1 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-working-test/gradle/wrapper/gradle-wrapper.properties b/src/test/test-applications copy/gradlew-working-test/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..2e6e5897 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-working-test/gradlew b/src/test/test-applications copy/gradlew-working-test/gradlew new file mode 100755 index 00000000..1b6c7873 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-working-test/gradlew.bat b/src/test/test-applications copy/gradlew-working-test/gradlew.bat new file mode 100644 index 00000000..ac1b06f9 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-working-test/settings.gradle b/src/test/test-applications copy/gradlew-working-test/settings.gradle new file mode 100644 index 00000000..81f4ec38 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-working-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/test-applications copy/gradlew-working-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-working-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/test-applications copy/gradlew-working-test/src/main/java/com/demo/rest/RestApplication.java new file mode 100644 index 00000000..eb0e4660 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/gradlew-working-test/src/main/liberty/config/server.xml b/src/test/test-applications copy/gradlew-working-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/test-applications copy/gradlew-working-test/src/main/liberty/config/server.xml @@ -0,0 +1,42 @@ + + + + + + javaee-7.0 + microProfile-1.4 + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-applications copy/gradlew-working-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/test-applications copy/gradlew-working-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b diff --git a/src/test/test-applications copy/mvnw-corrupt-test/.dockerignore b/src/test/test-applications copy/mvnw-corrupt-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/test-applications copy/mvnw-corrupt-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/test-applications copy/mvnw-corrupt-test/.gitignore b/src/test/test-applications copy/mvnw-corrupt-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-corrupt-test/.mvn/wrapper/maven-wrapper.properties b/src/test/test-applications copy/mvnw-corrupt-test/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..207aa436 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-corrupt-test/Dockerfile b/src/test/test-applications copy/mvnw-corrupt-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-corrupt-test/README.txt b/src/test/test-applications copy/mvnw-corrupt-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-corrupt-test/mvnw b/src/test/test-applications copy/mvnw-corrupt-test/mvnw new file mode 100644 index 00000000..e69de29b diff --git a/src/test/test-applications copy/mvnw-corrupt-test/pom.xml b/src/test/test-applications copy/mvnw-corrupt-test/pom.xml new file mode 100644 index 00000000..9b78f42c --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-corrupt-test/settings.gradle b/src/test/test-applications copy/mvnw-corrupt-test/settings.gradle new file mode 100644 index 00000000..81f4ec38 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/test-applications copy/mvnw-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-corrupt-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/test-applications copy/mvnw-corrupt-test/src/main/java/com/demo/rest/RestApplication.java new file mode 100644 index 00000000..eb0e4660 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-corrupt-test/src/main/liberty/config/server.xml b/src/test/test-applications copy/mvnw-corrupt-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/test-applications copy/mvnw-corrupt-test/src/main/liberty/config/server.xml @@ -0,0 +1,42 @@ + + + + + + javaee-7.0 + microProfile-1.4 + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-applications copy/mvnw-corrupt-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/test-applications copy/mvnw-corrupt-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b diff --git a/src/test/test-applications copy/mvnw-working-test/.dockerignore b/src/test/test-applications copy/mvnw-working-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/test-applications copy/mvnw-working-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/test-applications copy/mvnw-working-test/.gitignore b/src/test/test-applications copy/mvnw-working-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-working-test/.mvn/wrapper/maven-wrapper.properties b/src/test/test-applications copy/mvnw-working-test/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..2f093d08 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-working-test/Dockerfile b/src/test/test-applications copy/mvnw-working-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-working-test/README.txt b/src/test/test-applications copy/mvnw-working-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-working-test/mvnw b/src/test/test-applications copy/mvnw-working-test/mvnw new file mode 100755 index 00000000..19529ddf --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-working-test/mvnw.cmd b/src/test/test-applications copy/mvnw-working-test/mvnw.cmd new file mode 100644 index 00000000..b150b91e --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-working-test/pom.xml b/src/test/test-applications copy/mvnw-working-test/pom.xml new file mode 100644 index 00000000..9b78f42c --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-working-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/test-applications copy/mvnw-working-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-working-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/test-applications copy/mvnw-working-test/src/main/java/com/demo/rest/RestApplication.java new file mode 100644 index 00000000..eb0e4660 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/mvnw-working-test/src/main/liberty/config/server.xml b/src/test/test-applications copy/mvnw-working-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/test-applications copy/mvnw-working-test/src/main/liberty/config/server.xml @@ -0,0 +1,42 @@ + + + + + + javaee-7.0 + microProfile-1.4 + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-applications copy/mvnw-working-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/test-applications copy/mvnw-working-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b diff --git a/src/test/test-applications copy/no-mvnw-test/.dockerignore b/src/test/test-applications copy/no-mvnw-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/test-applications copy/no-mvnw-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/test-applications copy/no-mvnw-test/.gitignore b/src/test/test-applications copy/no-mvnw-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/no-mvnw-test/.mvn/wrapper/maven-wrapper.properties b/src/test/test-applications copy/no-mvnw-test/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..207aa436 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/no-mvnw-test/Dockerfile b/src/test/test-applications copy/no-mvnw-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/no-mvnw-test/README.txt b/src/test/test-applications copy/no-mvnw-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/no-mvnw-test/pom.xml b/src/test/test-applications copy/no-mvnw-test/pom.xml new file mode 100644 index 00000000..9b78f42c --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/no-mvnw-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/test-applications copy/no-mvnw-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/no-mvnw-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/test-applications copy/no-mvnw-test/src/main/java/com/demo/rest/RestApplication.java new file mode 100644 index 00000000..eb0e4660 --- /dev/null +++ b/src/test/test-applications copy/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/test-applications copy/no-mvnw-test/src/main/liberty/config/server.xml b/src/test/test-applications copy/no-mvnw-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/test-applications copy/no-mvnw-test/src/main/liberty/config/server.xml @@ -0,0 +1,42 @@ + + + + + + javaee-7.0 + microProfile-1.4 + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-applications copy/no-mvnw-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/test-applications copy/no-mvnw-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b diff --git a/src/test/test-applications/.gitignore b/src/test/test-applications/.gitignore new file mode 100644 index 00000000..4d81f976 --- /dev/null +++ b/src/test/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/test-applications/gradlew-corrupt-test/.dockerignore b/src/test/test-applications/gradlew-corrupt-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/test-applications/gradlew-corrupt-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/test-applications/gradlew-corrupt-test/.gitignore b/src/test/test-applications/gradlew-corrupt-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/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/test-applications/gradlew-corrupt-test/Dockerfile b/src/test/test-applications/gradlew-corrupt-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/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/test-applications/gradlew-corrupt-test/README.txt b/src/test/test-applications/gradlew-corrupt-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/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/test-applications/gradlew-corrupt-test/build.gradle b/src/test/test-applications/gradlew-corrupt-test/build.gradle new file mode 100644 index 00000000..c80e50c1 --- /dev/null +++ b/src/test/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/test-applications/gradlew-corrupt-test/gradle/wrapper/gradle-wrapper.properties b/src/test/test-applications/gradlew-corrupt-test/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..2e6e5897 --- /dev/null +++ b/src/test/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/test-applications/gradlew-corrupt-test/gradlew b/src/test/test-applications/gradlew-corrupt-test/gradlew new file mode 100644 index 00000000..e69de29b diff --git a/src/test/test-applications/gradlew-corrupt-test/gradlew.bat b/src/test/test-applications/gradlew-corrupt-test/gradlew.bat new file mode 100644 index 00000000..ac1b06f9 --- /dev/null +++ b/src/test/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/test-applications/gradlew-corrupt-test/settings.gradle b/src/test/test-applications/gradlew-corrupt-test/settings.gradle new file mode 100644 index 00000000..81f4ec38 --- /dev/null +++ b/src/test/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/test-applications/gradlew-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/test-applications/gradlew-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/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/test-applications/gradlew-corrupt-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/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/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/test-applications/gradlew-corrupt-test/src/main/liberty/config/server.xml b/src/test/test-applications/gradlew-corrupt-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/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/test-applications/gradlew-corrupt-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/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/test-applications/gradlew-working-test/.dockerignore b/src/test/test-applications/gradlew-working-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/test-applications/gradlew-working-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/test-applications/gradlew-working-test/.gitignore b/src/test/test-applications/gradlew-working-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/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/test-applications/gradlew-working-test/Dockerfile b/src/test/test-applications/gradlew-working-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/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/test-applications/gradlew-working-test/README.txt b/src/test/test-applications/gradlew-working-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/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/test-applications/gradlew-working-test/build.gradle b/src/test/test-applications/gradlew-working-test/build.gradle new file mode 100644 index 00000000..c80e50c1 --- /dev/null +++ b/src/test/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/test-applications/gradlew-working-test/gradle/wrapper/gradle-wrapper.properties b/src/test/test-applications/gradlew-working-test/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..2e6e5897 --- /dev/null +++ b/src/test/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/test-applications/gradlew-working-test/gradlew b/src/test/test-applications/gradlew-working-test/gradlew new file mode 100755 index 00000000..1b6c7873 --- /dev/null +++ b/src/test/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/test-applications/gradlew-working-test/gradlew.bat b/src/test/test-applications/gradlew-working-test/gradlew.bat new file mode 100644 index 00000000..ac1b06f9 --- /dev/null +++ b/src/test/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/test-applications/gradlew-working-test/settings.gradle b/src/test/test-applications/gradlew-working-test/settings.gradle new file mode 100644 index 00000000..81f4ec38 --- /dev/null +++ b/src/test/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/test-applications/gradlew-working-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/test-applications/gradlew-working-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/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/test-applications/gradlew-working-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/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/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/test-applications/gradlew-working-test/src/main/liberty/config/server.xml b/src/test/test-applications/gradlew-working-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/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/test-applications/gradlew-working-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/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/test-applications/mvnw-corrupt-test/.dockerignore b/src/test/test-applications/mvnw-corrupt-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/test-applications/mvnw-corrupt-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/test-applications/mvnw-corrupt-test/.gitignore b/src/test/test-applications/mvnw-corrupt-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/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/test-applications/mvnw-corrupt-test/.mvn/wrapper/maven-wrapper.properties b/src/test/test-applications/mvnw-corrupt-test/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..207aa436 --- /dev/null +++ b/src/test/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/test-applications/mvnw-corrupt-test/Dockerfile b/src/test/test-applications/mvnw-corrupt-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/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/test-applications/mvnw-corrupt-test/README.txt b/src/test/test-applications/mvnw-corrupt-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/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/test-applications/mvnw-corrupt-test/mvnw b/src/test/test-applications/mvnw-corrupt-test/mvnw new file mode 100644 index 00000000..e69de29b diff --git a/src/test/test-applications/mvnw-corrupt-test/pom.xml b/src/test/test-applications/mvnw-corrupt-test/pom.xml new file mode 100644 index 00000000..9b78f42c --- /dev/null +++ b/src/test/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/test-applications/mvnw-corrupt-test/settings.gradle b/src/test/test-applications/mvnw-corrupt-test/settings.gradle new file mode 100644 index 00000000..81f4ec38 --- /dev/null +++ b/src/test/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/test-applications/mvnw-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/test-applications/mvnw-corrupt-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/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/test-applications/mvnw-corrupt-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/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/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/test-applications/mvnw-corrupt-test/src/main/liberty/config/server.xml b/src/test/test-applications/mvnw-corrupt-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/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/test-applications/mvnw-corrupt-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/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/test-applications/mvnw-working-test/.dockerignore b/src/test/test-applications/mvnw-working-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/test-applications/mvnw-working-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/test-applications/mvnw-working-test/.gitignore b/src/test/test-applications/mvnw-working-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/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/test-applications/mvnw-working-test/.mvn/wrapper/maven-wrapper.properties b/src/test/test-applications/mvnw-working-test/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..2f093d08 --- /dev/null +++ b/src/test/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/test-applications/mvnw-working-test/Dockerfile b/src/test/test-applications/mvnw-working-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/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/test-applications/mvnw-working-test/README.txt b/src/test/test-applications/mvnw-working-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/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/test-applications/mvnw-working-test/mvnw b/src/test/test-applications/mvnw-working-test/mvnw new file mode 100755 index 00000000..19529ddf --- /dev/null +++ b/src/test/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/test-applications/mvnw-working-test/mvnw.cmd b/src/test/test-applications/mvnw-working-test/mvnw.cmd new file mode 100644 index 00000000..b150b91e --- /dev/null +++ b/src/test/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/test-applications/mvnw-working-test/pom.xml b/src/test/test-applications/mvnw-working-test/pom.xml new file mode 100644 index 00000000..9b78f42c --- /dev/null +++ b/src/test/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/test-applications/mvnw-working-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/test-applications/mvnw-working-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/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/test-applications/mvnw-working-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/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/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/test-applications/mvnw-working-test/src/main/liberty/config/server.xml b/src/test/test-applications/mvnw-working-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/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/test-applications/mvnw-working-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/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/test-applications/no-mvnw-test/.dockerignore b/src/test/test-applications/no-mvnw-test/.dockerignore new file mode 100644 index 00000000..326c2bc2 --- /dev/null +++ b/src/test/test-applications/no-mvnw-test/.dockerignore @@ -0,0 +1,3 @@ +target/ +!target/*.war +!target/liberty/wlp/usr/shared/resources/* diff --git a/src/test/test-applications/no-mvnw-test/.gitignore b/src/test/test-applications/no-mvnw-test/.gitignore new file mode 100644 index 00000000..fef207d2 --- /dev/null +++ b/src/test/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/test-applications/no-mvnw-test/.mvn/wrapper/maven-wrapper.properties b/src/test/test-applications/no-mvnw-test/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..207aa436 --- /dev/null +++ b/src/test/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/test-applications/no-mvnw-test/Dockerfile b/src/test/test-applications/no-mvnw-test/Dockerfile new file mode 100644 index 00000000..05e9a7e2 --- /dev/null +++ b/src/test/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/test-applications/no-mvnw-test/README.txt b/src/test/test-applications/no-mvnw-test/README.txt new file mode 100644 index 00000000..0e4c219b --- /dev/null +++ b/src/test/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/test-applications/no-mvnw-test/pom.xml b/src/test/test-applications/no-mvnw-test/pom.xml new file mode 100644 index 00000000..9b78f42c --- /dev/null +++ b/src/test/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/test-applications/no-mvnw-test/src/main/java/com/demo/CurrentTimeServlet.java b/src/test/test-applications/no-mvnw-test/src/main/java/com/demo/CurrentTimeServlet.java new file mode 100644 index 00000000..60ba828f --- /dev/null +++ b/src/test/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/test-applications/no-mvnw-test/src/main/java/com/demo/rest/RestApplication.java b/src/test/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/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/test-applications/no-mvnw-test/src/main/liberty/config/server.xml b/src/test/test-applications/no-mvnw-test/src/main/liberty/config/server.xml new file mode 100644 index 00000000..70e8fc1a --- /dev/null +++ b/src/test/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/test-applications/no-mvnw-test/src/main/resources/META-INF/microprofile-config.properties b/src/test/test-applications/no-mvnw-test/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 00000000..e69de29b