1 /* 2 * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 package jdk.jpackage.test; 25 26 import java.io.File; 27 import java.nio.file.Files; 28 import java.nio.file.Path; 29 import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; 30 import java.util.ArrayList; 31 import java.util.List; 32 33 34 /** 35 * Tool to compile Java sources and pack in a jar file. 36 */ 37 public final class JarBuilder { 38 39 public JarBuilder() { 40 sourceFiles = new ArrayList<>(); 41 } 42 43 public JarBuilder setOutputJar(Path v) { 44 outputJar = v; 45 return this; 46 } 47 48 public JarBuilder setMainClass(String v) { 49 mainClass = v; 50 return this; 51 } 52 53 public JarBuilder addSourceFile(Path v) { 54 sourceFiles.add(v); 55 return this; 56 } 57 58 public JarBuilder setModuleVersion(String v) { 59 moduleVersion = v; 60 return this; 61 } 62 63 public void create() { 64 TKit.withTempDirectory("jar-workdir", workDir -> { 65 if (!sourceFiles.isEmpty()) { 66 new Executor() 67 .setToolProvider(JavaTool.JAVAC) 68 .addArguments("-d", workDir.toString()) 69 .addPathArguments(sourceFiles) 70 .execute().assertExitCodeIsZero(); 71 } 72 73 Files.createDirectories(outputJar.getParent()); 74 if (Files.exists(outputJar)) { 75 TKit.trace(String.format("Delete [%s] existing jar file", outputJar)); 76 Files.deleteIfExists(outputJar); 77 } 78 79 Executor jarExe = new Executor() 80 .setToolProvider(JavaTool.JAR) 81 .addArguments("-c", "-f", outputJar.toString()); 82 if (moduleVersion != null) { 83 jarExe.addArguments(String.format("--module-version=%s", 84 moduleVersion)); 85 } 86 if (mainClass != null) { 87 jarExe.addArguments("-e", mainClass); 88 } 89 jarExe.addArguments("-C", workDir.toString(), "."); 90 jarExe.execute().assertExitCodeIsZero(); 91 }); 92 } 93 private List<Path> sourceFiles; 94 private Path outputJar; 95 private String mainClass; 96 private String moduleVersion; 97 }