package jdk.incubator.jpackage.internal;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.stream.Stream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Arguments {
private static final ResourceBundle I18N = ResourceBundle.getBundle(
"jdk.incubator.jpackage.internal.resources.MainResources");
private static final String FA_EXTENSIONS = "extension";
private static final String FA_CONTENT_TYPE = "mime-type";
private static final String FA_DESCRIPTION = "description";
private static final String FA_ICON = "icon";
public static final String MAC_CFBUNDLETYPEROLE = "mac.CFBundleTypeRole";
public static final String MAC_LSHANDLERRANK = "mac.LSHandlerRank";
public static final String MAC_NSSTORETYPEKEY = "mac.NSPersistentStoreTypeKey";
public static final String MAC_NSDOCUMENTCLASS = "mac.NSDocumentClass";
public static final String MAC_LSTYPEISPACKAGE = "mac.LSTypeIsPackage";
public static final String MAC_LSDOCINPLACE = "mac.LSSupportsOpeningDocumentsInPlace";
public static final String MAC_UIDOCBROWSER = "mac.UISupportsDocumentBrowser";
public static final String MAC_NSEXPORTABLETYPES = "mac.NSExportableTypes";
public static final String MAC_UTTYPECONFORMSTO = "mac.UTTypeConformsTo";
private static Pattern pattern = Pattern.compile(
"(?:(?:([\"'])(?:\\\\\\1|.)*?(?:\\1|$))|(?:\\\\[\"'\\s]|[^\\s]))++");
private DeployParams deployParams = null;
private int pos = 0;
private List<String> argList = null;
private List<CLIOptions> allOptions = null;
private String input = null;
private String output = null;
private boolean hasMainJar = false;
private boolean hasMainClass = false;
private boolean hasMainModule = false;
public boolean userProvidedBuildRoot = false;
private String buildRoot = null;
private String mainJarPath = null;
private static boolean runtimeInstaller = false;
private List<AddLauncherArguments> addLaunchers = null;
private static Map<String, CLIOptions> argIds = new HashMap<>();
private static Map<String, CLIOptions> argShortIds = new HashMap<>();
static {
(EnumSet.allOf(CLIOptions.class)).forEach(option -> {
argIds.put(option.getIdWithPrefix(), option);
if (option.getShortIdWithPrefix() != null) {
argShortIds.put(option.getShortIdWithPrefix(), option);
}
});
}
public Arguments(String[] args) {
argList = new ArrayList<String>(args.length);
for (String arg : args) {
argList.add(arg);
}
Log.verbose ("\njpackage argument list: \n" + argList + "\n");
pos = 0;
deployParams = new DeployParams();
allOptions = new ArrayList<>();
addLaunchers = new ArrayList<>();
output = Paths.get("").toAbsolutePath().toString();
deployParams.setOutput(new File(output));
}
public enum CLIOptions {
PACKAGE_TYPE("type", "t", OptionCategories.PROPERTY, () -> {
context().deployParams.setTargetFormat(popArg());
}),
INPUT ("input", "i", OptionCategories.PROPERTY, () -> {
context().input = popArg();
setOptionValue("input", context().input);
}),
OUTPUT ("dest", "d", OptionCategories.PROPERTY, () -> {
context().output = popArg();
context().deployParams.setOutput(new File(context().output));
}),
DESCRIPTION ("description", OptionCategories.PROPERTY),
VENDOR ("vendor", OptionCategories.PROPERTY),
APPCLASS ("main-class", OptionCategories.PROPERTY, () -> {
context().hasMainClass = true;
setOptionValue("main-class", popArg());
}),
NAME ("name", "n", OptionCategories.PROPERTY),
VERBOSE ("verbose", OptionCategories.PROPERTY, () -> {
setOptionValue("verbose", true);
Log.setVerbose();
}),
RESOURCE_DIR("resource-dir",
OptionCategories.PROPERTY, () -> {
String resourceDir = popArg();
setOptionValue("resource-dir", resourceDir);
}),
ARGUMENTS ("arguments", OptionCategories.PROPERTY, () -> {
List<String> arguments = getArgumentList(popArg());
setOptionValue("arguments", arguments);
}),
JLINK_OPTIONS ("jlink-options", OptionCategories.PROPERTY, () -> {
List<String> options = getArgumentList(popArg());
setOptionValue("jlink-options", options);
}),
ICON ("icon", OptionCategories.PROPERTY),
COPYRIGHT ("copyright", OptionCategories.PROPERTY),
LICENSE_FILE ("license-file", OptionCategories.PROPERTY),
VERSION ("app-version", OptionCategories.PROPERTY),
RELEASE ("linux-app-release", OptionCategories.PROPERTY),
JAVA_OPTIONS ("java-options", OptionCategories.PROPERTY, () -> {
List<String> args = getArgumentList(popArg());
args.forEach(a -> setOptionValue("java-options", a));
}),
FILE_ASSOCIATIONS ("file-associations",
OptionCategories.PROPERTY, () -> {
Map<String, ? super Object> args = new HashMap<>();
Map<String, String> initialMap = getPropertiesFromFile(popArg());
putUnlessNull(args, StandardBundlerParam.FA_EXTENSIONS.getID(),
initialMap.get(FA_EXTENSIONS));
putUnlessNull(args, StandardBundlerParam.FA_CONTENT_TYPE.getID(),
initialMap.get(FA_CONTENT_TYPE));
putUnlessNull(args, StandardBundlerParam.FA_DESCRIPTION.getID(),
initialMap.get(FA_DESCRIPTION));
putUnlessNull(args, StandardBundlerParam.FA_ICON.getID(),
initialMap.get(FA_ICON));
putUnlessNull(args, MAC_CFBUNDLETYPEROLE,
initialMap.get(MAC_CFBUNDLETYPEROLE));
putUnlessNull(args, MAC_LSHANDLERRANK,
initialMap.get(MAC_LSHANDLERRANK));
putUnlessNull(args, MAC_NSSTORETYPEKEY,
initialMap.get(MAC_NSSTORETYPEKEY));
putUnlessNull(args, MAC_NSDOCUMENTCLASS,
initialMap.get(MAC_NSDOCUMENTCLASS));
putUnlessNull(args, MAC_LSTYPEISPACKAGE,
initialMap.get(MAC_LSTYPEISPACKAGE));
putUnlessNull(args, MAC_LSDOCINPLACE,
initialMap.get(MAC_LSDOCINPLACE));
putUnlessNull(args, MAC_UIDOCBROWSER,
initialMap.get(MAC_UIDOCBROWSER));
putUnlessNull(args, MAC_NSEXPORTABLETYPES,
initialMap.get(MAC_NSEXPORTABLETYPES));
putUnlessNull(args, MAC_UTTYPECONFORMSTO,
initialMap.get(MAC_UTTYPECONFORMSTO));
ArrayList<Map<String, ? super Object>> associationList =
new ArrayList<Map<String, ? super Object>>();
associationList.add(args);
setOptionValue("file-associations", associationList);
}),
ADD_LAUNCHER ("add-launcher",
OptionCategories.PROPERTY, () -> {
String spec = popArg();
String name = null;
String filename = spec;
if (spec.contains("=")) {
String[] values = spec.split("=", 2);
name = values[0];
filename = values[1];
}
context().addLaunchers.add(
new AddLauncherArguments(name, filename));
}),
TEMP_ROOT ("temp", OptionCategories.PROPERTY, () -> {
context().buildRoot = popArg();
context().userProvidedBuildRoot = true;
setOptionValue("temp", context().buildRoot);
}),
INSTALL_DIR ("install-dir", OptionCategories.PROPERTY),
PREDEFINED_APP_IMAGE ("app-image", OptionCategories.PROPERTY),
PREDEFINED_RUNTIME_IMAGE ("runtime-image", OptionCategories.PROPERTY),
MAIN_JAR ("main-jar", OptionCategories.PROPERTY, () -> {
context().mainJarPath = popArg();
context().hasMainJar = true;
setOptionValue("main-jar", context().mainJarPath);
}),
MODULE ("module", "m", OptionCategories.MODULAR, () -> {
context().hasMainModule = true;
setOptionValue("module", popArg());
}),
ADD_MODULES ("add-modules", OptionCategories.MODULAR),
MODULE_PATH ("module-path", "p", OptionCategories.MODULAR),
BIND_SERVICES ("bind-services", OptionCategories.PROPERTY, () -> {
showDeprecation("bind-services");
setOptionValue("bind-services", true);
}),
MAC_SIGN ("mac-sign", "s", OptionCategories.PLATFORM_MAC, () -> {
setOptionValue("mac-sign", true);
}),
MAC_BUNDLE_NAME ("mac-package-name", OptionCategories.PLATFORM_MAC),
MAC_BUNDLE_IDENTIFIER("mac-package-identifier",
OptionCategories.PLATFORM_MAC),
MAC_BUNDLE_SIGNING_PREFIX ("mac-package-signing-prefix",
OptionCategories.PLATFORM_MAC),
MAC_SIGNING_KEY_NAME ("mac-signing-key-user-name",
OptionCategories.PLATFORM_MAC),
MAC_SIGNING_KEYCHAIN ("mac-signing-keychain",
OptionCategories.PLATFORM_MAC),
WIN_MENU_HINT ("win-menu", OptionCategories.PLATFORM_WIN, () -> {
setOptionValue("win-menu", true);
}),
WIN_MENU_GROUP ("win-menu-group", OptionCategories.PLATFORM_WIN),
WIN_SHORTCUT_HINT ("win-shortcut",
OptionCategories.PLATFORM_WIN, () -> {
setOptionValue("win-shortcut", true);
}),
WIN_PER_USER_INSTALLATION ("win-per-user-install",
OptionCategories.PLATFORM_WIN, () -> {
setOptionValue("win-per-user-install", false);
}),
WIN_DIR_CHOOSER ("win-dir-chooser",
OptionCategories.PLATFORM_WIN, () -> {
setOptionValue("win-dir-chooser", true);
}),
WIN_UPGRADE_UUID ("win-upgrade-uuid",
OptionCategories.PLATFORM_WIN),
WIN_CONSOLE_HINT ("win-console", OptionCategories.PLATFORM_WIN, () -> {
setOptionValue("win-console", true);
}),
LINUX_BUNDLE_NAME ("linux-package-name",
OptionCategories.PLATFORM_LINUX),
LINUX_DEB_MAINTAINER ("linux-deb-maintainer",
OptionCategories.PLATFORM_LINUX),
LINUX_CATEGORY ("linux-app-category",
OptionCategories.PLATFORM_LINUX),
LINUX_RPM_LICENSE_TYPE ("linux-rpm-license-type",
OptionCategories.PLATFORM_LINUX),
LINUX_PACKAGE_DEPENDENCIES ("linux-package-deps",
OptionCategories.PLATFORM_LINUX),
LINUX_SHORTCUT_HINT ("linux-shortcut",
OptionCategories.PLATFORM_LINUX, () -> {
setOptionValue("linux-shortcut", true);
}),
LINUX_MENU_GROUP ("linux-menu-group", OptionCategories.PLATFORM_LINUX);
private final String id;
private final String shortId;
private final OptionCategories category;
private final Runnable action;
private static Arguments argContext;
private CLIOptions(String id, OptionCategories category) {
this(id, null, category, null);
}
private CLIOptions(String id, String shortId,
OptionCategories category) {
this(id, shortId, category, null);
}
private CLIOptions(String id,
OptionCategories category, Runnable action) {
this(id, null, category, action);
}
private CLIOptions(String id, String shortId,
OptionCategories category, Runnable action) {
this.id = id;
this.shortId = shortId;
this.action = action;
this.category = category;
}
static void setContext(Arguments context) {
argContext = context;
}
public static Arguments context() {
if (argContext != null) {
return argContext;
} else {
throw new RuntimeException("Argument context is not set.");
}
}
public String getId() {
return this.id;
}
String getIdWithPrefix() {
return "--" + this.id;
}
String getShortIdWithPrefix() {
return this.shortId == null ? null : "-" + this.shortId;
}
void execute() {
if (action != null) {
action.run();
} else {
defaultAction();
}
}
private void defaultAction() {
context().deployParams.addBundleArgument(id, popArg());
}
private static void setOptionValue(String option, Object value) {
context().deployParams.addBundleArgument(option, value);
}
private static String popArg() {
nextArg();
return (context().pos >= context().argList.size()) ?
"" : context().argList.get(context().pos);
}
private static String getArg() {
return (context().pos >= context().argList.size()) ?
"" : context().argList.get(context().pos);
}
private static void nextArg() {
context().pos++;
}
private static boolean hasNextArg() {
return context().pos < context().argList.size();
}
}
enum OptionCategories {
MODULAR,
PROPERTY,
PLATFORM_MAC,
PLATFORM_WIN,
PLATFORM_LINUX;
}
public boolean processArguments() {
try {
CLIOptions.setContext(this);
String arg;
CLIOptions option;
for (; CLIOptions.hasNextArg(); CLIOptions.nextArg()) {
arg = CLIOptions.getArg();
if ((option = toCLIOption(arg)) != null) {
allOptions.add(option);
option.execute();
} else {
throw new PackagerException("ERR_InvalidOption", arg);
}
}
if (hasMainJar && !hasMainClass) {
String mainClass = getMainClassFromManifest();
if (mainClass != null) {
CLIOptions.setOptionValue(
CLIOptions.APPCLASS.getId(), mainClass);
}
}
validateArguments();
List<Map<String, ? super Object>> launchersAsMap =
new ArrayList<>();
for (AddLauncherArguments sl : addLaunchers) {
launchersAsMap.add(sl.getLauncherMap());
}
deployParams.addBundleArgument(
StandardBundlerParam.ADD_LAUNCHERS.getID(),
launchersAsMap);
deployParams.validate();
BundleParams bp = deployParams.getBundleParams();
ArrayList<String> usedNames = new ArrayList<String>();
usedNames.add(bp.getName());
for (AddLauncherArguments sl : addLaunchers) {
Map<String, ? super Object> slMap = sl.getLauncherMap();
String slName =
(String) slMap.get(Arguments.CLIOptions.NAME.getId());
if (slName == null) {
throw new PackagerException("ERR_NoAddLauncherName");
}
DeployParams.validateName(slName, false);
for (String usedName : usedNames) {
if (slName.equals(usedName)) {
throw new PackagerException("ERR_NoUniqueName");
}
}
usedNames.add(slName);
}
if (runtimeInstaller && bp.getName() == null) {
throw new PackagerException("ERR_NoJreInstallerName");
}
generateBundle(bp.getBundleParamsAsMap());
return true;
} catch (Exception e) {
if (Log.isVerbose()) {
Log.verbose(e);
} else {
String msg1 = e.getMessage();
Log.error(msg1);
if (e.getCause() != null && e.getCause() != e) {
String msg2 = e.getCause().getMessage();
if (msg2 != null && !msg1.contains(msg2)) {
Log.error(msg2);
}
}
}
return false;
}
}
private void validateArguments() throws PackagerException {
String type = deployParams.getTargetFormat();
String ptype = (type != null) ? type : "default";
boolean imageOnly = deployParams.isTargetAppImage();
boolean hasAppImage = allOptions.contains(
CLIOptions.PREDEFINED_APP_IMAGE);
boolean hasRuntime = allOptions.contains(
CLIOptions.PREDEFINED_RUNTIME_IMAGE);
boolean installerOnly = !imageOnly && hasAppImage;
runtimeInstaller = !imageOnly && hasRuntime && !hasAppImage &&
!hasMainModule && !hasMainJar;
for (CLIOptions option : allOptions) {
if (!ValidOptions.checkIfSupported(option)) {
throw new PackagerException("ERR_UnsupportedOption",
option.getIdWithPrefix());
}
if (imageOnly) {
if (!ValidOptions.checkIfImageSupported(option)) {
throw new PackagerException("ERR_InvalidTypeOption",
option.getIdWithPrefix(), type);
}
} else if (installerOnly || runtimeInstaller) {
if (!ValidOptions.checkIfInstallerSupported(option)) {
if (runtimeInstaller) {
throw new PackagerException("ERR_NoInstallerEntryPoint",
option.getIdWithPrefix());
} else {
throw new PackagerException("ERR_InvalidTypeOption",
option.getIdWithPrefix(), ptype);
}
}
}
}
if (hasRuntime) {
if (hasAppImage) {
throw new PackagerException("ERR_MutuallyExclusiveOptions",
CLIOptions.PREDEFINED_RUNTIME_IMAGE.getIdWithPrefix(),
CLIOptions.PREDEFINED_APP_IMAGE.getIdWithPrefix());
}
if (allOptions.contains(CLIOptions.ADD_MODULES)) {
throw new PackagerException("ERR_MutuallyExclusiveOptions",
CLIOptions.PREDEFINED_RUNTIME_IMAGE.getIdWithPrefix(),
CLIOptions.ADD_MODULES.getIdWithPrefix());
}
if (allOptions.contains(CLIOptions.BIND_SERVICES)) {
throw new PackagerException("ERR_MutuallyExclusiveOptions",
CLIOptions.PREDEFINED_RUNTIME_IMAGE.getIdWithPrefix(),
CLIOptions.BIND_SERVICES.getIdWithPrefix());
}
if (allOptions.contains(CLIOptions.JLINK_OPTIONS)) {
throw new PackagerException("ERR_MutuallyExclusiveOptions",
CLIOptions.PREDEFINED_RUNTIME_IMAGE.getIdWithPrefix(),
CLIOptions.JLINK_OPTIONS.getIdWithPrefix());
}
}
if (hasMainJar && hasMainModule) {
throw new PackagerException("ERR_BothMainJarAndModule");
}
if (imageOnly && !hasMainJar && !hasMainModule) {
throw new PackagerException("ERR_NoEntryPoint");
}
}
private jdk.incubator.jpackage.internal.Bundler getPlatformBundler() {
boolean appImage = deployParams.isTargetAppImage();
String type = deployParams.getTargetFormat();
String bundleType = (appImage ? "IMAGE" : "INSTALLER");
for (jdk.incubator.jpackage.internal.Bundler bundler :
Bundlers.createBundlersInstance().getBundlers(bundleType)) {
if (type == null) {
if (bundler.isDefault()
&& bundler.supported(runtimeInstaller)) {
return bundler;
}
} else {
if ((appImage || type.equalsIgnoreCase(bundler.getID()))
&& bundler.supported(runtimeInstaller)) {
return bundler;
}
}
}
return null;
}
private void generateBundle(Map<String,? super Object> params)
throws PackagerException {
boolean bundleCreated = false;
StandardBundlerParam.TEMP_ROOT.fetchFrom(params);
jdk.incubator.jpackage.internal.Bundler bundler = getPlatformBundler();
if (bundler == null) {
throw new PackagerException("ERR_InvalidInstallerType",
deployParams.getTargetFormat());
}
Map<String, ? super Object> localParams = new HashMap<>(params);
try {
bundler.validate(localParams);
File result = bundler.execute(localParams, deployParams.outdir);
if (result == null) {
throw new PackagerException("MSG_BundlerFailed",
bundler.getID(), bundler.getName());
}
Log.verbose(MessageFormat.format(
I18N.getString("message.bundle-created"),
bundler.getName()));
} catch (ConfigException e) {
Log.verbose(e);
if (e.getAdvice() != null) {
throw new PackagerException(e, "MSG_BundlerConfigException",
bundler.getName(), e.getMessage(), e.getAdvice());
} else {
throw new PackagerException(e,
"MSG_BundlerConfigExceptionNoAdvice",
bundler.getName(), e.getMessage());
}
} catch (RuntimeException re) {
Log.verbose(re);
throw new PackagerException(re, "MSG_BundlerRuntimeException",
bundler.getName(), re.toString());
} finally {
if (userProvidedBuildRoot) {
Log.verbose(MessageFormat.format(
I18N.getString("message.debug-working-directory"),
(new File(buildRoot)).getAbsolutePath()));
} else {
bundler.cleanup(localParams);
}
}
}
static CLIOptions toCLIOption(String arg) {
CLIOptions option;
if ((option = argIds.get(arg)) == null) {
option = argShortIds.get(arg);
}
return option;
}
static Map<String, String> getPropertiesFromFile(String filename) {
Map<String, String> map = new HashMap<>();
File file = new File(filename);
Properties properties = new Properties();
try (FileInputStream in = new FileInputStream(file)) {
properties.load(in);
} catch (IOException e) {
Log.error("Exception: " + e.getMessage());
}
for (final String name: properties.stringPropertyNames()) {
map.put(name, properties.getProperty(name));
}
return map;
}
static List<String> getArgumentList(String inputString) {
List<String> list = new ArrayList<>();
if (inputString == null || inputString.isEmpty()) {
return list;
}
Matcher m = pattern.matcher(inputString);
while (m.find()) {
String s = inputString.substring(m.start(), m.end()).trim();
if (!s.isEmpty()) {
list.add(unquoteIfNeeded(s));
}
}
return list;
}
static void putUnlessNull(Map<String, ? super Object> params,
String param, Object value) {
if (value != null) {
params.put(param, value);
}
}
private static String unquoteIfNeeded(String in) {
if (in == null) {
return null;
}
if (in.isEmpty()) {
return "";
}
StringBuilder sb = new StringBuilder();
int codeLen = in.codePointCount(0, in.length());
int quoteChar = -1;
for (int i = 0; i < codeLen; i++) {
int code = in.codePointAt(i);
if (code == '"' || code == '\'') {
if (i > 0 && in.codePointAt(i - 1) == '\\') {
sb.deleteCharAt(sb.length() - 1);
sb.appendCodePoint(code);
continue;
}
if (quoteChar != -1) {
if (code == quoteChar) {
quoteChar = -1;
} else {
sb.appendCodePoint(code);
}
} else {
quoteChar = code;
}
} else {
sb.appendCodePoint(code);
}
}
return sb.toString();
}
private String getMainClassFromManifest() {
if (mainJarPath == null ||
input == null ) {
return null;
}
JarFile jf;
try {
File file = new File(input, mainJarPath);
if (!file.exists()) {
return null;
}
jf = new JarFile(file);
Manifest m = jf.getManifest();
Attributes attrs = (m != null) ? m.getMainAttributes() : null;
if (attrs != null) {
return attrs.getValue(Attributes.Name.MAIN_CLASS);
}
} catch (IOException ignore) {}
return null;
}
private static void showDeprecation(String option) {
Log.error(MessageFormat.format(I18N.getString("warning.deprecation"),
option));
}
}