Repository: lukaszlenart/launch4j-maven-plugin Branch: main Commit: 81cfb20c4eae Files: 40 Total size: 235.7 KB Directory structure: gitextract_occv47_e/ ├── .claude/ │ └── settings.json ├── .github/ │ ├── FUNDING.yaml │ └── workflows/ │ └── maven.yml ├── .gitignore ├── .mvn/ │ ├── extensions.xml │ ├── maven.config │ └── wrapper/ │ ├── MavenWrapperDownloader.java │ └── maven-wrapper.properties ├── CLAUDE.md ├── LICENSE ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml ├── renovate.json └── src/ ├── main/ │ ├── java/ │ │ └── com/ │ │ └── akathist/ │ │ └── maven/ │ │ └── plugins/ │ │ └── launch4j/ │ │ ├── ClassPath.java │ │ ├── Jre.java │ │ ├── Launch4jMojo.java │ │ ├── MavenLog.java │ │ ├── Messages.java │ │ ├── SingleInstance.java │ │ ├── Splash.java │ │ ├── VersionInfo.java │ │ ├── generators/ │ │ │ ├── CopyrightGenerator.java │ │ │ └── Launch4jFileVersionGenerator.java │ │ └── tools/ │ │ └── ResourceIO.java │ ├── legal/ │ │ ├── LICENSE.txt │ │ ├── XStream.LICENSE.txt │ │ └── commons.LICENSE.txt │ └── resources/ │ ├── META-INF/ │ │ └── resources/ │ │ └── manifest-require_admin_rights-v1.xml │ ├── MOJO.md │ ├── README.adoc │ ├── TODO │ └── VERSIONINFO.md ├── site/ │ └── site.xml └── test/ ├── java/ │ └── com/ │ └── akathist/ │ └── maven/ │ └── plugins/ │ └── launch4j/ │ ├── Launch4jMojoTest.java │ ├── VersionInfoTest.java │ └── generators/ │ ├── CopyrightGeneratorTest.java │ └── Launch4jFileVersionGeneratorTest.java └── resources/ └── unit/ └── launch4j-config/ └── launch4j-full-plugin-config.xml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .claude/settings.json ================================================ { "permissions": { "allow": [ "WebFetch(domain:github.com)", "Bash(mvn test:*)", "Bash(javac:*)", "Bash(java:*)", "mcp__jetbrains" ], "deny": [] } } ================================================ FILE: .github/FUNDING.yaml ================================================ # These are supported funding model platforms github: [lukaszlenart] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] ================================================ FILE: .github/workflows/maven.yml ================================================ # 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. name: Java CI on: pull_request: push: branches: - main workflow_dispatch: # Sets permissions of the GITHUB_TOKEN to allow to apply a label and merge # https://docs.github.com/en/code-security/dependabot/working-with-dependabot/automating-dependabot-with-github-actions permissions: contents: write issues: write pull-requests: write repository-projects: write concurrency: ci-${{ github.ref }} jobs: build: runs-on: ubuntu-latest strategy: matrix: java: [ 17, 21, 25 ] steps: - name: Checkout code uses: actions/checkout@v6.0.2 - name: Set up cache uses: actions/cache@v5.0.5 with: path: ~/.m2/repository key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} restore-keys: | ${{ runner.os }}-maven- - name: Set up JDK ${{ matrix.java }} uses: actions/setup-java@v5 with: distribution: adopt java-version: ${{ matrix.java }} - name: Build with Maven on Java ${{ matrix.java }} run: mvn -V test -Ddoclint=all --file pom.xml --no-transfer-progress ================================================ FILE: .gitignore ================================================ *.ipr *.iml *.iws .settings/* .project .classpath .factorypath target/ .idea/ .java-version .mvn/wrapper/maven-wrapper.jar .DS_Store .claude/settings.local.json ================================================ FILE: .mvn/extensions.xml ================================================ fr.jcgay.maven maven-profiler 3.2 ================================================ FILE: .mvn/maven.config ================================================ -Daether.checksums.algorithms=SHA-512,SHA-256,SHA-1,MD5 -Daether.connector.smartChecksums=false ================================================ FILE: .mvn/wrapper/MavenWrapperDownloader.java ================================================ /* * 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. */ import java.io.IOException; import java.io.InputStream; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.net.URI; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.concurrent.ThreadLocalRandom; public final class MavenWrapperDownloader { private static final String WRAPPER_VERSION = "3.3.4"; private static final boolean VERBOSE = Boolean.parseBoolean(System.getenv("MVNW_VERBOSE")); public static void main(String[] args) { log("Apache Maven Wrapper Downloader " + WRAPPER_VERSION); if (args.length != 2) { System.err.println(" - ERROR wrapperUrl or wrapperJarPath parameter missing"); System.exit(1); } try { log(" - Downloader started"); final URL wrapperUrl = URI.create(args[0]).toURL(); final Path baseDir = Paths.get(".").toAbsolutePath().normalize(); final Path wrapperJarPath = baseDir.resolve(args[1]).normalize(); if (!wrapperJarPath.startsWith(baseDir)) { throw new IOException("Invalid path: outside of allowed directory"); } downloadFileFromURL(wrapperUrl, wrapperJarPath); log("Done"); } catch (IOException e) { System.err.println("- Error downloading: " + e.getMessage()); if (VERBOSE) { e.printStackTrace(); } System.exit(1); } } private static void downloadFileFromURL(URL wrapperUrl, Path wrapperJarPath) throws IOException { log(" - Downloading to: " + wrapperJarPath); if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { final String username = System.getenv("MVNW_USERNAME"); final char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } Path temp = wrapperJarPath .getParent() .resolve(wrapperJarPath.getFileName() + "." + Long.toUnsignedString(ThreadLocalRandom.current().nextLong()) + ".tmp"); try (InputStream inStream = wrapperUrl.openStream()) { Files.copy(inStream, temp, StandardCopyOption.REPLACE_EXISTING); Files.move(temp, wrapperJarPath, StandardCopyOption.REPLACE_EXISTING); } finally { Files.deleteIfExists(temp); } log(" - Downloader complete"); } private static void log(String msg) { if (VERBOSE) { System.out.println(msg); } } } ================================================ FILE: .mvn/wrapper/maven-wrapper.properties ================================================ wrapperVersion=3.3.4 distributionType=source distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.15/apache-maven-3.9.15-bin.zip wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar ================================================ FILE: CLAUDE.md ================================================ # CLAUDE.md This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. ## Project Overview This is a Maven plugin that wraps JAR files into Windows executables using Launch4j. The plugin allows generating Windows `.exe` files from Java applications as part of the Maven build process. **Requirements:** - Java 17 (specified in `` in pom.xml) - Maven 3.6.x or higher ## Build Commands ```bash # Build the project ./mvnw clean install # Run tests only ./mvnw test # Run a single test class ./mvnw test -Dtest=Launch4jMojoTest # Run a single test method ./mvnw test -Dtest=Launch4jMojoTest#testConfigurationWithIcon # Skip tests during build ./mvnw clean install -DskipTests # Generate site documentation ./mvnw site ``` ## Architecture ### Core Components - **`Launch4jMojo`** (`src/main/java/.../Launch4jMojo.java`) - The main Maven Mojo that executes during the `package` phase. Handles: - Loading configuration (either from POM or external Launch4j XML config via ``) - Downloading platform-specific Launch4j binaries (win32, linux, linux64, mac, solaris) - Building the Windows executable using Launch4j's `Builder` - **Configuration POJOs** - Mirror Launch4j's XML configuration structure: - `ClassPath` - Classpath configuration with Maven dependency support - `Jre` - JRE path and version requirements - `VersionInfo` - Windows executable version information - `Splash` - Splash screen configuration - `SingleInstance` - Mutex-based single instance support - `Messages` - Custom error messages - **`generators/`** - Default value generators: - `CopyrightGenerator` - Generates copyright string from project metadata - `Launch4jFileVersionGenerator` - Converts Maven version to Windows version format (x.x.x.x) ### Plugin Configuration The plugin binds to the `package` phase by default. Key configuration parameters: - `headerType` - `gui` or `console` (default: `console`) - `outfile` - Output executable path - `jar` - Input JAR file - `skip` / `-DskipLaunch4j` - Skip plugin execution - `parallelExecution` - Synchronize execution for thread safety ### Test Structure Tests use `maven-plugin-testing-harness` with mock Maven projects in `src/test/resources/unit/launch4j-config/`. ## Platform-Specific Binaries Launch4j requires platform-specific binaries (ld, windres) that are downloaded as Maven artifacts with classifiers like `workdir-win32`, `workdir-linux64`, `workdir-mac`. These are unpacked to the local Maven repository and reused. ================================================ FILE: LICENSE ================================================ Maven Launch4j Plugin 1.0 A plugin for using Launch4j in Maven projects. Copyright (c) 2006 Paul Jungwirth Copyright (c) 2011-2025 Lukasz Lenart This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA A complete copy of this license may be found in src/main/legal/LICENSE.txt of the source distribution. ================================================ FILE: README.md ================================================ # Launch4j Maven Plugin Originally hosted at http://9stmaryrd.com/tools/launch4j-maven-plugin/ [![GH Actions](https://github.com/lukaszlenart/launch4j-maven-plugin/actions/workflows/maven.yml/badge.svg)](https://github.com/lukaszlenart/launch4j-maven-plugin/actions/workflows/maven.yml) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.akathist.maven.plugins.launch4j/launch4j-maven-plugin/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.akathist.maven.plugins.launch4j/launch4j-maven-plugin/) - [Documentation](#documentation) - [Version Notes](#version-notes) - [FAQ](#faq) # Documentation Please check [this](src/main/resources/README.adoc) document for more detailed info on how to use the plugin. Please also check [Launch4j's Configuration file](http://launch4j.sourceforge.net/docs.html#Configuration_file) page. The full list of all the parameters is available [here](src/main/resources/MOJO.md) **NOTE**: Since version 2.0.x this plugin requires to be used with Maven 3.6.x at least. # Version Notes Please check the [releases](../../releases) page for the exact versions notes ## Version notes 2.3.3 - 2023-03-11 - updates maven wrapper to official 3.1.1, adds sha-512 & sha-256 checksums, adds a profiler extension, see PR [#252](../../pull/252) ## Version notes 2.3.2 - 2023-01-30 - fixes broken Project Reports when running `maven-project-info-reports-plugin`, see Issue [#223](../../issues/223) and PR [#227](../../pull/227) ## Version notes 2.3.1 - 2023-01-16 - logs only warnings instead of throwing exception, when cannot fulfill default values for `` (no configuration data required by the formula), see Issue [#213](../../issues/213) and PR [#216](../../pull/216) ## Version notes 2.3.0 - 2023-01-06 - provides default values for plugin configuration, especially for ``, see Issue [#98](../../issues/98) - adds a `disableVersionInfoDefaults` parameter to be able to disable provided defaults, see PR [#205](../../pull/205) - adds documentation notes regarding a new defaults, see [VERSIONINFO.md](src/main/resources/VERSIONINFO.md) - throwing exceptions with detailed description of default values formula, when cannot fulfill default values (no configuration data for a formula), it helps plugin user with debugging what is wrong ## Version notes 2.2.0 - 2022-11-24 - upgrades Launch4j to version 3.50 and adopts config to the bew requirements, see Issue [#199](../../issues/199) and PR [#200](../../pull/200) for more details what has to be changed ## Version notes 2.1.3 - 2022-10-24 - allows to skip execution of the plugin using either `true` configuration option or `-DskipLaunch4j` property, see [#190](../../pull/190) ## Version notes 2.1.1 - 2021-05-04 - creates parent folder if `outfile` was configured, see [#141](../../issues/141) ## Version notes 2.1.0 - 2021-05-04 - upgrades Maven API to version 3.8.1 (it should be compatible with Maven 3.6.x), see [#132](../../pull/132), [#133](../../pull/133), [#134](../../pull/134), [#135](../../pull/135), [#136](../../pull/136) ## Version notes 2.0.1 - 2021-03-21 - fixes problem with NPE, see [#128](../../issues/128) ## Version notes 2.0.0 - 2021-03-17 **DO NOT USE THIS VERSION** - uses Launch4j version 3.14 (which requires Java 8), see [#126](../../pull/126) - switches to Java 8 as minimal supported version ## Version notes 1.7.25 - creates parent directories of an obj file, see [#99](../../pull/99) ## Version notes 1.7.24 - adds a `threadSafe` flag to the Mojo to properly mark that the plugin is thread safe, see [#72](../../issues/72) ## Version notes 1.7.23 - adds a `parallelExecution` flag that will allow to run only one instance of the plugin in the given time, see [#72](../../issues/72) ## Version notes 1.7.22 - upgrades to Launch4j version 3.12, see [#75](../../issues/75) ## Version notes 1.7.21 - fixes issue with detecting OSX, see [#58](../../issues/58) ## Version notes 1.7.20 - uses the `linux64` platform when run on 64-bit Linux, see [#59](../../pull/59) ## Version notes 1.7.19 - upgrades to the version 3.11 of Launch4j ## Version notes 1.7.18 - reverts changes introduced in **1.7.17**, see [#55](../../pull/55) ## Version notes 1.7.17 - adds support for unwrapped jar, see [#55](../../pull/55) ## Version notes 1.7.16 - detects different OSX versions to properly use proper binary bundle, see [#54](../../pull/54) ## Version notes 1.7.15 - allows override some properties loaded from an external Launch4j config file, see [#49](../../issues/49) ## Version notes 1.7.14 - fixes issue with setting `language`, see [#50](../../issues/50) ## Version notes 1.7.13 - upgrades maven plugins to latest versions, see [#47](../../issues/47) ## Version notes 1.7.12 - adds support for missing options, see [#45](../../issues/45) - `language` - please use one of the values as defined for the `` tag - `trademarks` - a free text used as a trademarks ## Version notes 1.7.11 - upgrades to Launch4j version 3.9 ## Version notes 1.7.10 - fixes broken `` when not using `` ## Version notes 1.7.9 - adds capability of loading Launch4j native configuration file ```xml ${project.basedir}/src/main/resources/my-app-config.xml ``` By default it will take from `${project.basedir}/src/main/resources/${project.artifactId}-launch4j.xml`. Plugin execution goal should be set to `install`. It's an optional configuration, you can either use your existing configuration as it was in previous version or use native **Launch4j** [config file](http://launch4j.sourceforge.net/docs.html#Configuration_file) via ``. ## Version notes 1.7.8 - fixes issue with spaces in path to maven repository on non-Windows systems, see [#27](../../issues/27), [#28](../../issues/28) ## Version notes 1.7.7 - once again fixes problem with including dependencies in scope `runtime` (now it should be the final solution), see [#5](../../issues/5) - adds support for `bundledJreAsFallback` and `bundledJre64Bit` properties, see [#23](../../issues/23) - upgrades Launch4j to 3.8.0, see [#21](../../issues/21) ## Version notes 1.7.6 - fixes again problem with including dependencies in scope `runtime`, see [#5](../../issues/5) ## Version notes 1.7.5 - allows add custom headers and libraries to working dir [#22](../../pull/22) ## Version notes 1.7.4 - fixes type in default value for `outfile` parameter [#17](../../pull/17) ## Version notes 1.7.3 - uses Maven annotation instead of JavaDoc parameters [#15](../../pull/15) - upgrades Maven plugins [#15](../../pull/15) - converts tabs to spaces [5b0619](../../commit/5b0619) ## Version notes 1.7.2 - adds support for `restartOnCrash` Launch4j's option [#14](../../pull/14) ## Version notes 1.7.1 - launch4j's `abeille` dependency was excluded [#11](../../pull/11) - versions of several plugins were updated [#11](../../pull/11) - tabs were converted to spaces [#11](../../pull/11) ## Version notes 1.7 - uses the latest version of Launch4j (3.5.0) - contains support for `runtimeBits`, see [#6](../../issues/6) - ~~fixes problem with including dependencies in scope `runtime`, see [#5](../../issues/5)~~ ## Version notes 1.6 - dropped Launch4j source and based on artifacts from Maven Central, see [#8](../../issues/8) - uses the latest version of Launch4j (3.4.0) - at least Java 1.7 is required # FAQ Q: I cannot build my project because `dsol-xml` dependency is missing? A: Add this repository to your `~/.m2/settings.xml` ```xml dsol-xml Simulation @ TU Delft http://simulation.tudelft.nl/maven/ ``` Q: Where can I find -SNAPSHOT builds? A: Use the Sonatype OSS repo ```xml sonatype-nexus-snapshots Sonatype Nexus Snapshots https://oss.sonatype.org/content/repositories/snapshots/ false true ``` Q: Can I use Launch4j on 64bit OS? A: Yes but you will have to install these libs to avoid problems: - lib32z1 - lib32ncurses5 - lib32bz2-1.0 (has been ia32-libs in older Ubuntu versions) - zlib.i686 - ncurses-libs.i686 - bzip2-libs.i686 See [#4](../../issues/4) for more details. Q: How can I skip execution of the plugin? A: You can either use `true` configuration option or provide `-DskipLaunch4j` property to JVM See PR [#190](../../pull/190) for more details. ================================================ FILE: mvnw ================================================ #!/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.4 # # Required ENV vars: # ------------------ # JAVA_HOME - location of a JDK home dir # # Optional ENV vars # ----------------- # MAVEN_OPTS - parameters passed to the Java VM when running Maven # e.g. to debug Maven itself, use # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 # MAVEN_SKIP_RC - flag to disable loading of mavenrc files # ---------------------------------------------------------------------------- if [ -z "$MAVEN_SKIP_RC" ]; then if [ -f /usr/local/etc/mavenrc ]; then . /usr/local/etc/mavenrc fi if [ -f /etc/mavenrc ]; then . /etc/mavenrc fi if [ -f "$HOME/.mavenrc" ]; then . "$HOME/.mavenrc" fi fi # OS specific support. $var _must_ be set to either true or false. cygwin=false darwin=false mingw=false case "$(uname)" in CYGWIN*) cygwin=true ;; MINGW*) mingw=true ;; Darwin*) darwin=true # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home # See https://developer.apple.com/library/mac/qa/qa1170/_index.html if [ -z "$JAVA_HOME" ]; then if [ -x "/usr/libexec/java_home" ]; then JAVA_HOME="$(/usr/libexec/java_home)" export JAVA_HOME else JAVA_HOME="/Library/Java/Home" export JAVA_HOME fi fi ;; esac if [ -z "$JAVA_HOME" ]; then if [ -r /etc/gentoo-release ]; then JAVA_HOME=$(java-config --jre-home) fi fi # For Cygwin, ensure paths are in UNIX format before anything is touched if $cygwin; then [ -n "$JAVA_HOME" ] \ && JAVA_HOME=$(cygpath --unix "$JAVA_HOME") [ -n "$CLASSPATH" ] \ && CLASSPATH=$(cygpath --path --unix "$CLASSPATH") fi # For Mingw, ensure paths are in UNIX format before anything is touched if $mingw; then [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] \ && JAVA_HOME="$( cd "$JAVA_HOME" || ( echo "cannot cd into $JAVA_HOME." >&2 exit 1 ) pwd )" fi if [ -z "$JAVA_HOME" ]; then javaExecutable="$(which javac)" if [ -n "$javaExecutable" ] && ! [ "$(expr "$javaExecutable" : '\([^ ]*\)')" = "no" ]; then # readlink(1) is not available as standard on Solaris 10. readLink=$(which readlink) if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then if $darwin; then javaHome="$(dirname "$javaExecutable")" javaExecutable="$(cd "$javaHome" && pwd -P)/javac" else javaExecutable="$(readlink -f "$javaExecutable")" fi javaHome="$(dirname "$javaExecutable")" javaHome=$(expr "$javaHome" : '\(.*\)/bin') JAVA_HOME="$javaHome" export JAVA_HOME fi fi fi if [ -z "$JAVACMD" ]; then 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 else JAVACMD="$( \unset -f command 2>/dev/null \command -v java )" fi fi if [ ! -x "$JAVACMD" ]; then echo "Error: JAVA_HOME is not defined correctly." >&2 echo " We cannot execute $JAVACMD" >&2 exit 1 fi if [ -z "$JAVA_HOME" ]; then echo "Warning: JAVA_HOME environment variable is not set." >&2 fi # traverses directory structure from process work directory to filesystem root # first directory with .mvn subdirectory is considered project base directory find_maven_basedir() { if [ -z "$1" ]; then echo "Path not specified to find_maven_basedir" >&2 return 1 fi basedir="$1" wdir="$1" while [ "$wdir" != '/' ]; do if [ -d "$wdir"/.mvn ]; then basedir=$wdir break fi # workaround for JBEAP-8937 (on Solaris 10/Sparc) if [ -d "${wdir}" ]; then wdir=$( cd "$wdir/.." || exit 1 pwd ) fi # end of workaround done printf '%s' "$( cd "$basedir" || exit 1 pwd )" } # concatenates all lines of a file concat_lines() { if [ -f "$1" ]; then # Remove \r in case we run on Windows within Git Bash # and check out the repository with auto CRLF management # enabled. Otherwise, we may read lines that are delimited with # \r\n and produce $'-Xarg\r' rather than -Xarg due to word # splitting rules. tr -s '\r\n' ' ' <"$1" fi } log() { if [ "$MVNW_VERBOSE" = true ]; then printf '%s\n' "$1" fi } BASE_DIR=$(find_maven_basedir "$(dirname "$0")") if [ -z "$BASE_DIR" ]; then exit 1 fi MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} export MAVEN_PROJECTBASEDIR log "$MAVEN_PROJECTBASEDIR" 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:]' } ########################################################################################## # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central # This allows using the maven wrapper in projects that prohibit checking in binary data. ########################################################################################## wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" if [ -r "$wrapperJarPath" ]; then log "Found $wrapperJarPath" else log "Couldn't find $wrapperJarPath, downloading it ..." if [ -n "$MVNW_REPOURL" ]; then wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar" else wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar" fi while IFS="=" read -r key value; do case "$key" in wrapperUrl) wrapperUrl=$(trim "${value-}") break ;; esac done <"$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" log "Downloading from: $wrapperUrl" if $cygwin; then wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") fi if command -v wget >/dev/null; then log "Found wget ... using wget" [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then wget ${QUIET:+"$QUIET"} "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" else wget ${QUIET:+"$QUIET"} --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" fi elif command -v curl >/dev/null; then log "Found curl ... using curl" [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then curl ${QUIET:+"$QUIET"} -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" else curl ${QUIET:+"$QUIET"} --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" fi else log "Falling back to using Java to download" javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" # For Cygwin, switch paths to Windows format before running javac if $cygwin; then javaSource=$(cygpath --path --windows "$javaSource") javaClass=$(cygpath --path --windows "$javaClass") fi if [ -e "$javaSource" ]; then if [ ! -e "$javaClass" ]; then log " - Compiling MavenWrapperDownloader.java ..." ("$JAVA_HOME/bin/javac" "$javaSource") fi if [ -e "$javaClass" ]; then log " - Running MavenWrapperDownloader.java ..." ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" fi fi fi fi ########################################################################################## # End of extension ########################################################################################## # If specified, validate the SHA-256 sum of the Maven wrapper jar file wrapperSha256Sum="" while IFS="=" read -r key value; do case "$key" in wrapperSha256Sum) wrapperSha256Sum=$(trim "${value-}") break ;; esac done <"$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" if [ -n "$wrapperSha256Sum" ]; then wrapperSha256Result=false if command -v sha256sum >/dev/null; then if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c - >/dev/null 2>&1; then wrapperSha256Result=true fi elif command -v shasum >/dev/null; then if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c >/dev/null 2>&1; then wrapperSha256Result=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 'wrapperSha256Sum' from your maven-wrapper.properties." >&2 exit 1 fi if [ $wrapperSha256Result = false ]; then echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 exit 1 fi fi MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" # For Cygwin, switch paths to Windows format before running java if $cygwin; then [ -n "$JAVA_HOME" ] \ && JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") [ -n "$CLASSPATH" ] \ && CLASSPATH=$(cygpath --path --windows "$CLASSPATH") [ -n "$MAVEN_PROJECTBASEDIR" ] \ && MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") fi # Provide a "standardized" way to retrieve the CLI args that will # work with both Windows and non-Windows executions. MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*" export MAVEN_CMD_LINE_ARGS WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain # shellcheck disable=SC2086 # safe args exec "$JAVACMD" \ $MAVEN_OPTS \ $MAVEN_DEBUG_OPTS \ -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" ================================================ FILE: mvnw.cmd ================================================ @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.4 @REM @REM Required ENV vars: @REM JAVA_HOME - location of a JDK home dir @REM @REM Optional ENV vars @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven @REM e.g. to debug Maven itself, use @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files @REM ---------------------------------------------------------------------------- @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' @echo off @REM set title of command window title %0 @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% @REM set %HOME% to equivalent of $HOME if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") @REM Execute a user defined script before this one if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre @REM check for pre script, once with legacy .bat ending and once with .cmd ending if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* :skipRcPre @setlocal set ERROR_CODE=0 @REM To isolate internal variables from possible post scripts, we use another setlocal @setlocal @REM ==== START VALIDATION ==== if not "%JAVA_HOME%" == "" goto OkJHome echo. >&2 echo Error: JAVA_HOME not found in your environment. >&2 echo Please set the JAVA_HOME variable in your environment to match the >&2 echo location of your Java installation. >&2 echo. >&2 goto error :OkJHome if exist "%JAVA_HOME%\bin\java.exe" goto init echo. >&2 echo Error: JAVA_HOME is set to an invalid directory. >&2 echo JAVA_HOME = "%JAVA_HOME%" >&2 echo Please set the JAVA_HOME variable in your environment to match the >&2 echo location of your Java installation. >&2 echo. >&2 goto error @REM ==== END VALIDATION ==== :init @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". @REM Fallback to current working directory if not found. set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir set EXEC_DIR=%CD% set WDIR=%EXEC_DIR% :findBaseDir IF EXIST "%WDIR%"\.mvn goto baseDirFound cd .. IF "%WDIR%"=="%CD%" goto baseDirNotFound set WDIR=%CD% goto findBaseDir :baseDirFound set MAVEN_PROJECTBASEDIR=%WDIR% cd "%EXEC_DIR%" goto endDetectBaseDir :baseDirNotFound set MAVEN_PROJECTBASEDIR=%EXEC_DIR% cd "%EXEC_DIR%" :endDetectBaseDir IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig @setlocal EnableExtensions EnableDelayedExpansion for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% :endReadAdditionalConfig SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar" FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B ) @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central @REM This allows using the maven wrapper in projects that prohibit checking in binary data. if exist %WRAPPER_JAR% ( if "%MVNW_VERBOSE%" == "true" ( echo Found %WRAPPER_JAR% ) ) else ( if not "%MVNW_REPOURL%" == "" ( SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar" ) if "%MVNW_VERBOSE%" == "true" ( echo Couldn't find %WRAPPER_JAR%, downloading it ... echo Downloading from: %WRAPPER_URL% ) powershell -Command "&{"^ "$webclient = new-object System.Net.WebClient;"^ "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ "}"^ "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ "}" if "%MVNW_VERBOSE%" == "true" ( echo Finished downloading %WRAPPER_JAR% ) ) @REM End of extension @REM If specified, validate the SHA-256 sum of the Maven wrapper jar file SET WRAPPER_SHA_256_SUM="" FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B ) IF NOT %WRAPPER_SHA_256_SUM%=="" ( powershell -Command "&{"^ "Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash;"^ "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ " Write-Error 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ " Write-Error 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ " Write-Error 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ " exit 1;"^ "}"^ "}" if ERRORLEVEL 1 goto error ) @REM Provide a "standardized" way to retrieve the CLI args that will @REM work with both Windows and non-Windows executions. set MAVEN_CMD_LINE_ARGS=%* %MAVEN_JAVA_EXE% ^ %JVM_CONFIG_MAVEN_PROPS% ^ %MAVEN_OPTS% ^ %MAVEN_DEBUG_OPTS% ^ -classpath %WRAPPER_JAR% ^ "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* if ERRORLEVEL 1 goto error goto end :error set ERROR_CODE=1 :end @endlocal & set ERROR_CODE=%ERROR_CODE% if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost @REM check for post script, once with legacy .bat ending and once with .cmd ending if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" :skipRcPost @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' if "%MAVEN_BATCH_PAUSE%"=="on" pause if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% cmd /C exit /B %ERROR_CODE% ================================================ FILE: pom.xml ================================================ 4.0.0 com.akathist.maven.plugins.launch4j launch4j-maven-plugin maven-plugin 2.7.1-SNAPSHOT Maven Launch4j Plugin This plugin creates Windows executables from Java jar files using the Launch4j utility. https://orphan.software/ 2025 UTF-8 3.50 17 17 0.9.0 3.4.0 3.12.0 3.5.0 3.1.4 3.3.1 3.2.8 GNU General Public License v3.0 https://www.gnu.org/licenses/gpl-3.0.txt repo scm:git:git@github.com:orphan-oss/launch4j-maven-plugin.git git@github.com:orphan-oss/launch4j-maven-plugin.git scm:git:git@github.com:orphan-oss/launch4j-maven-plugin.git HEAD Github Issues https://github.com/orphan-oss/launch4j-maven-plugin/issues lukaszlenart lukasz.lenart@gmail.com Lead maintainer net.sf.launch4j launch4j ${launch4j.version} core com.ibm.icu icu4j abeille net.java.abeille com.thoughtworks.xstream xstream org.apache.ant ant org.apache.ant ant 1.10.17 com.thoughtworks.xstream xstream 1.4.21 org.apache.maven maven-plugin-api 3.9.15 provided org.apache.maven maven-model 3.9.15 provided org.apache.maven maven-artifact 3.9.15 provided org.apache.maven maven-core 3.9.15 provided org.apache.maven.plugin-tools maven-plugin-annotations 3.15.2 provided org.apache.commons commons-lang3 3.20.0 junit junit 4.13.2 test pl.pragmatists JUnitParams 1.1.1 test org.mockito mockito-core 5.23.0 test org.apache.maven.plugin-testing maven-plugin-testing-harness 3.5.1 test org.apache.maven maven-compat 3.9.15 test org.apache.maven.plugins maven-compiler-plugin 3.15.0 org.apache.maven.plugins maven-plugin-plugin 3.15.2 true default-descriptor descriptor process-classes help-descriptor helpmojo process-classes org.apache.maven.plugins maven-plugin-plugin 3.15.2 mojo-descriptor descriptor help-goal helpmojo org.apache.maven.plugins maven-site-plugin 3.21.0 org.apache.maven.doxia doxia-core 2.1.0 org.apache.maven.doxia doxia-module-markdown 2.1.0 org.apache.maven.plugins maven-jar-plugin ${maven-jar-plugin.version} true true ognl org.apache.maven.plugins maven-source-plugin ${maven-source-plugin.version} true true true attach-sources jar-no-fork org.apache.maven.plugins maven-javadoc-plugin ${maven-javadoc-plugin.version} true true 1.8 https://docs.oracle.com/javase/8/docs/api/ none true UTF-8 attach-source jar org.apache.maven.plugins maven-deploy-plugin ${maven-deploy-plugin.version} org.apache.maven.plugins maven-release-plugin ${maven-release-plugin.version} release org.sonatype.central central-publishing-maven-plugin ${central-publishing-maven-plugin.version} true central eclipse m2e.version org.eclipse.m2e lifecycle-mapping 1.0.0 org.apache.maven.plugins maven-plugin-plugin [3.4,) helpmojo descriptor release deploy maven-gpg-plugin maven-gpg-plugin ${maven-gpg-plugin.version} sign-artifacts verify sign org.apache.maven.plugins maven-project-info-reports-plugin 3.9.0 index summary licenses dependencies plugins org.apache.maven.plugins maven-plugin-plugin 3.15.2 org.apache.maven.plugins maven-javadoc-plugin 3.12.0 ================================================ FILE: renovate.json ================================================ { "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ "config:recommended" ], "packageRules": [ { "matchUpdateTypes": ["major","minor", "patch"], "matchCurrentVersion": "!/^0/", "automerge": true } ] } ================================================ FILE: src/main/java/com/akathist/maven/plugins/launch4j/ClassPath.java ================================================ /* * Maven Launch4j Plugin * Copyright (c) 2006 Paul Jungwirth * Copyright (c) 2011-2025 Lukasz Lenart * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.akathist.maven.plugins.launch4j; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugins.annotations.Parameter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; public class ClassPath { /** * The main class to run. This is not required if you are wrapping an executable jar. */ @Parameter String mainClass; /** * The launch4j executable sets up a classpath before running your jar, but it must know what the * classpath should be. If you set this property to true, the plugin will indicate a classpath * based on all the dependencies your program will need at runtime. You can augment this classpath * using the preCp and postCp properties. */ @Parameter(defaultValue = "true") boolean addDependencies = true; /** * If you want maven to build the classpath from dependencies, you can optionally set the jarLocation, * which is the location of the jars in your distro relative to the executable. So if your distro * has the exe at the top level and all the jars in a lib directory, you could set this to "lib." * This property does not affect preCp and postCp. */ @Parameter String jarLocation; /** * Part of the classpath that the executable should give to your application. * Paths are relative to the executable and should be in Windows format (separated by a semicolon). * You don't have to list all your dependencies here; the plugin will include them by default * after this list. */ @Parameter String preCp; /** * Part of the classpath that the executable should give to your application. * Paths are relative to the executable and should be in Windows format (separated by a semicolon). * You don't have to list all your dependencies here; the plugin will include them by default * before this list. */ @Parameter String postCp; private void addToCp(List cp, String cpStr) { cp.addAll(Arrays.asList(cpStr.split("\\s*;\\s*"))); } net.sf.launch4j.config.ClassPath toL4j(Set dependencies) { net.sf.launch4j.config.ClassPath ret = new net.sf.launch4j.config.ClassPath(); ret.setMainClass(mainClass); List cp = new ArrayList<>(); if (preCp != null) addToCp(cp, preCp); if (addDependencies) { if (jarLocation == null) jarLocation = ""; else if (!jarLocation.endsWith("/")) jarLocation += "/"; for (Artifact dependency : dependencies) { String depFilename; depFilename = dependency.getFile().getName(); // System.out.println("dependency = " + depFilename); cp.add(jarLocation + depFilename); } } if (postCp != null) addToCp(cp, postCp); ret.setPaths(cp); return ret; } @Override public String toString() { return "ClassPath{" + "mainClass='" + mainClass + '\'' + ", addDependencies=" + addDependencies + ", jarLocation='" + jarLocation + '\'' + ", preCp='" + preCp + '\'' + ", postCp='" + postCp + '\'' + '}'; } } ================================================ FILE: src/main/java/com/akathist/maven/plugins/launch4j/Jre.java ================================================ /* * Maven Launch4j Plugin * Copyright (c) 2006 Paul Jungwirth * Copyright (c) 2011-2025 Lukasz Lenart * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.akathist.maven.plugins.launch4j; import java.util.List; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.Parameter; /** * Details about which jre the executable should call. */ public class Jre { /** * The property is used to specify absolute or relative JRE paths, it does not rely * on the current directory or . * Note: the path is not checked until the actual application execution. * The is now required and always used for searching before the registry, * to ensure compatibility with the latest runtimes, which by default * do not add registry keys during installation. */ @Parameter(required = true) String path; /** * Sets jre's bundledJre64Bit flag * * @deprecated Replaced with which works during path and registry search. * @since using Launch4j 3.50 */ @Parameter(defaultValue = "false") @Deprecated String bundledJre64Bit; /** * Sets jre's bundledJreAsFallback flag * * @deprecated Removed, path search is always first and registry search second * in order to improve compatibility with modern runtimes * @since using Launch4j 3.50 */ @Parameter(defaultValue = "false") @Deprecated String bundledJreAsFallback; /** * When set to "true", limits the runtimes to 64-Bit only, "false" will use 64-Bit or 32-Bit * depending on which is found. This option works with path and registry search. * @since version 2.2.0 */ @Parameter(defaultValue = "false") boolean requires64Bit; /** * Use this property if you want the executable to search the system for a jre. * It names the minimum version acceptable, in x.x.x[_xx] format. *

* If you specify this property without giving a path, then the executable will search for a jre * and, none is found, display the java download page. *

* If you include a path also, the executable will try that path before searching for jre matching minVersion. *

* In either case, you can also specify a maxVersion. */ String minVersion; /** * If you specify minVersion, you can also use maxVersion to further constrain the search for a jre. * This property should be in the format x.x.x[_xx]. */ String maxVersion; /** * Allows you to specify a preference for a public JRE or a private JDK runtime. *

* Valid values are: * * * * * * * * * * * * * * * * * *
jreOnlyAlways use a public JRE
preferJrePrefer a public JRE, but use a JDK private runtime if it is newer than the public JRE
preferJdkPrefer a JDK private runtime, but use a public JRE if it is newer than the JDK
jdkOnlyAlways use a private JDK runtime (fails if there is no JDK installed)
* * @deprecated Replaces with which works during path and registry search. * @since using Launch4j 3.50 */ @Parameter(defaultValue = "preferJre") @Deprecated String jdkPreference; /** * When set to "true" only a JDK will be used for execution. An additional check will be performed * if javac is available during path and registry search. * @since version 2.2.0 */ @Parameter(defaultValue = "false") boolean requiresJdk; /** * Sets java's initial heap size in MB, like the -Xms flag. */ int initialHeapSize; /** * Sets java's initial heap size in percent of free memory. */ int initialHeapPercent; /** * Sets java's maximum heap size in MB, like the -Xmx flag. */ int maxHeapSize; /** * Sets java's maximum heap size in percent of free memory. */ int maxHeapPercent; /** * Use this to pass arbitrary options to the java/javaw program. * For instance, you can say: *

     * <opt>-Dlaunch4j.exedir="%EXEDIR%"</opt>
     * <opt>-Dlaunch4j.exefile="%EXEFILE%"</opt>
     * <opt>-Denv.path="%Path%"</opt>
     * <opt>-Dsettings="%HomeDrive%%HomePath%\\settings.ini"</opt>
     * 
*/ List opts; /** * Sets JVM version to use: 32 bits, 64 bits or 64/32 bits * Possible values: 32, 64, 64/32 - it will fallback to default value if different option was used * Default value is: 64/32 * * @deprecated Replaced with which works during path and registry search. * @since using Launch4j 3.50 */ @Parameter(defaultValue = "64/32") @Deprecated String runtimeBits; net.sf.launch4j.config.Jre toL4j() { net.sf.launch4j.config.Jre ret = new net.sf.launch4j.config.Jre(); ret.setPath(path); ret.setRequires64Bit(requires64Bit); ret.setMinVersion(minVersion); ret.setMaxVersion(maxVersion); ret.setRequiresJdk(requiresJdk); ret.setInitialHeapSize(initialHeapSize); ret.setInitialHeapPercent(initialHeapPercent); ret.setMaxHeapSize(maxHeapSize); ret.setMaxHeapPercent(maxHeapPercent); ret.setOptions(opts); return ret; } @Override public String toString() { return "Jre{" + "path='" + path + '\'' + ", requires64Bit=" + requires64Bit + ", minVersion='" + minVersion + '\'' + ", maxVersion='" + maxVersion + '\'' + ", requiresJdk=" + requiresJdk + ", initialHeapSize=" + initialHeapSize + ", initialHeapPercent=" + initialHeapPercent + ", maxHeapSize=" + maxHeapSize + ", maxHeapPercent=" + maxHeapPercent + ", opts=" + opts + '}'; } public void deprecationWarning(Log log) { if (this.bundledJreAsFallback != null) { log.warn(" has been removed! It has no effect!"); } if (this.bundledJre64Bit != null) { log.warn(" is deprecated, use instead!"); } if (this.runtimeBits != null) { log.warn(" is deprecated, use instead!"); } if (this.jdkPreference != null) { log.warn(" is deprecated, use instead!"); } } } ================================================ FILE: src/main/java/com/akathist/maven/plugins/launch4j/Launch4jMojo.java ================================================ /* * Maven Launch4j Plugin * Copyright (c) 2006 Paul Jungwirth * Copyright (c) 2011-2025 Lukasz Lenart * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.akathist.maven.plugins.launch4j; import com.akathist.maven.plugins.launch4j.tools.ResourceIO; import net.sf.launch4j.Builder; import net.sf.launch4j.BuilderException; import net.sf.launch4j.config.Config; import net.sf.launch4j.config.ConfigPersister; import net.sf.launch4j.config.ConfigPersisterException; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.project.MavenProject; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.impl.ArtifactResolver; import org.eclipse.aether.repository.LocalArtifactRequest; import org.eclipse.aether.repository.LocalArtifactResult; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.resolution.ArtifactRequest; import org.eclipse.aether.resolution.ArtifactResolutionException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.stream.Collectors; /** * Wraps a jar in a Windows executable. */ @Mojo( name = "launch4j", defaultPhase = LifecyclePhase.PACKAGE, requiresDependencyResolution = ResolutionScope.RUNTIME, threadSafe = true ) public class Launch4jMojo extends AbstractMojo { @Parameter(defaultValue = "launch4j", required = true) private String launch4jArtifactId; @Parameter(defaultValue = "net.sf.launch4j", required = true) private String launch4jGroupId; // intentionally non-static non-final so it can be hacked with reflection if someone really needs to private String DEF_REQADMMAN_RES = "META-INF/resources/manifest-require_admin_rights-v1.xml"; // intentionally non-static non-final so it can be hacked with reflection if someone really needs to private String DEF_REQADMMAN_FILE = "target/classes/META-INF/manifest-requireAdminRights.xml"; /** * Maven Session. */ @Parameter(defaultValue = "${session}", required = true, readonly = true) private MavenSession session; @Parameter(defaultValue = "${project.remoteProjectRepositories}", required = true, readonly = true) private List repositories; /** * The dependencies required by the project. */ @Parameter(defaultValue = "${project.artifacts}", required = true, readonly = true) private Set dependencies; /** * The user's current project. */ @Parameter(defaultValue = "${project}", required = true, readonly = true) private MavenProject project; /** * Used to look up Artifacts in the remote repository. */ @Component(role = RepositorySystem.class) private RepositorySystem repositorySystem; /** * The user's local repository. */ @Parameter(defaultValue = "${repositorySystemSession}", required = true, readonly = true) private RepositorySystemSession repositorySystemSession; /** * The artifact resolver used to grab the binary bits that launch4j needs. */ @Component(role = ArtifactResolver.class) private ArtifactResolver resolver; /** * The dependencies of this plugin. * Used to get the Launch4j artifact version. */ @Parameter(defaultValue = "${plugin.artifacts}") private List oldPluginArtifacts; /** * The base of the current project. */ @Parameter(defaultValue = "${project.basedir}", required = true, readonly = true) private File basedir; /** * Whether you want a gui or console app. * Valid values are "gui" and "console." * If you say gui, then launch4j will run your app from javaw instead of java * in order to avoid opening a DOS window. * Choosing gui also enables other options like taskbar icon and a splash screen. */ @Parameter(defaultValue = "console", required = true) private String headerType; /** * The name of the Launch4j native configuration file * The path, if relative, is relative to the pom.xml. */ @Parameter private File infile; /** * The name of the executable you want launch4j to produce. * The path, if relative, is relative to the pom.xml. */ @Parameter(defaultValue = "${project.build.directory}/${project.artifactId}.exe") private File outfile; /** * The jar to bundle inside the executable. * The path, if relative, is relative to the pom.xml. *

* If you don't want to wrap the jar, then this value should be the runtime path * to the jar relative to the executable. You should also set dontWrapJar to true. *

* You can only bundle a single jar. Therefore, you should either create a jar that contains * your own code plus all your dependencies, or you should distribute your dependencies alongside * the executable. */ @Parameter(defaultValue = "${project.build.directory}/${project.build.finalName}.jar") private String jar; /** * Whether the executable should wrap the jar or not. */ @Parameter(defaultValue = "false") private boolean dontWrapJar; /** * The title of the error popup if something goes wrong trying to run your program, * like if java can't be found. If this is a console app and not a gui, then this value * is used to prefix any error messages, as in ${errTitle}: ${errorMessage}. */ @Parameter(defaultValue = "${project.name}") private String errTitle; /** * downloadUrl (?). */ @Parameter private String downloadUrl; /** * supportUrl (?). */ @Parameter private String supportUrl; /** * Constant command line arguments to pass to your program's main method. * Actual command line arguments entered by the user will appear after these. */ @Parameter private String cmdLine; /** * Changes to the given directory, relative to the executable, before running your jar. * If set to . the current directory will be where the executable is. * If omitted, the directory will not be changed. */ @Parameter private String chdir; /** * Priority class of windows process. * Valid values are "normal" (default), "idle" and "high". * * @see MSDN: Scheduling Priorities */ @Parameter(defaultValue = "normal") private String priority; /** * If true, the executable waits for the java application to finish before returning its exit code. * Defaults to false for gui applications. Has no effect for console applications, which always wait. */ @Parameter(defaultValue = "false") private boolean stayAlive; /** * If true, when the application exits, any exit code other than 0 is considered a crash and * the application will be started again. */ @Parameter(defaultValue = "false") private boolean restartOnCrash; /** * The icon to use in the taskbar. Must be in ico format. */ @Parameter private File icon; /** * Whether the executable should ask for admin rights (Windows only). */ @Parameter(defaultValue = "false") private boolean requireAdminRights; /** * Object files to include. Used for custom headers only. */ @Parameter private List objs; /** * Win32 libraries to include. Used for custom headers only. */ @Parameter private List libs; /** * Variables to set. */ @Parameter private List vars; /** * Details about the supported jres. */ @Parameter private Jre jre; /** * Details about the classpath your application should have. * This is required if you are not wrapping a jar. */ @Parameter private ClassPath classPath; /** * Details about whether to run as a single instance. */ @Parameter private SingleInstance singleInstance; /** * Details about the splash screen. */ @Parameter private Splash splash; /** * Lots of information you can attach to the windows process. */ @Parameter private VersionInfo versionInfo; /** * If set to true, it will prevent filling out the VersionInfo params with default values. */ @Parameter(defaultValue = "false") private boolean disableVersionInfoDefaults; /** * Various messages you can display. */ @Parameter private Messages messages; /** * Windows manifest file (a XML file) with the same name as .exe file (myapp.exe.manifest) */ @Parameter private File manifest; /** * If set to true it will save final config into a XML file */ @Parameter(defaultValue = "false") private boolean saveConfig = false; /** * If {@link #saveConfig} is set to true, config will be written to this file */ @Parameter(defaultValue = "${project.build.directory}/launch4j-config.xml") private File configOutfile; /** * If set to true, a synchronized block will be used to protect resources */ @Parameter(defaultValue = "false") private boolean parallelExecution = false; /** * If set to true, execution of the plugin will be skipped */ @Parameter(defaultValue = "false") private boolean skip = false; private File getJar() { return new File(jar); } @Override public void execute() throws MojoExecutionException { if (parallelExecution) { synchronized (Launch4jMojo.class) { doExecute(); } } else { doExecute(); } } private void doExecute() throws MojoExecutionException { if (this.skipExecution()) { getLog().debug("Skipping execution of the plugin"); return; } processRequireAdminRights(); fillSensibleJreDefaults(); if (!disableVersionInfoDefaults) { try { if (versionInfo == null) { versionInfo = new VersionInfo(); } versionInfo.setLog(getLog()); versionInfo.tryFillOutByDefaults(project, outfile); } catch (RuntimeException exception) { throw new MojoExecutionException("Cannot fill out VersionInfo by defaults", exception); } } final File workDir = setupBuildEnvironment(); if (infile != null) { if (infile.exists()) { try { if (getLog().isDebugEnabled()) { getLog().debug("Trying to load Launch4j native configuration using file=" + infile.getAbsolutePath()); } // load launch4j config file from ConfigPersister.getInstance().load(infile); // overwrite several properties analogous to the ANT task // https://sourceforge.net/p/launch4j/git/ci/master/tree/src/net/sf/launch4j/ant/Launch4jTask.java#l84 // retrieve the loaded configuration for manipulation Config c = ConfigPersister.getInstance().getConfig(); String jarDefaultValue = project.getBuild().getDirectory() + "/" + project.getBuild().getFinalName() + ".jar"; if (jar != null && !jar.equals(jarDefaultValue)) { getLog().debug("Overwriting config file property 'jar' (='" + c.getJar().getAbsolutePath() + "') with local value '" + getJar().getAbsolutePath() + "'"); // only overwrite when != defaultValue (should be != null anytime because of the default value) c.setJar(getJar()); } File outFileDefaultValue = new File(project.getBuild().getDirectory() + "/" + project.getArtifactId() + ".exe"); if (outfile != null && !outfile.getAbsolutePath().equals(outFileDefaultValue.getAbsolutePath())) { // only overwrite when != defaultValue (should be != null anytime because of the default value) getLog().debug("Overwriting config file property 'outfile' (='" + c.getOutfile().getAbsolutePath() + "') with local value '" + outfile.getAbsolutePath() + "'"); c.setOutfile(outfile); } if (icon != null) { c.setIcon(icon); } if (versionInfo != null) { if (versionInfo.fileVersion != null) { getLog().debug("Overwriting config file property 'versionInfo.fileVersion' (='" + c.getVersionInfo().getFileVersion() + "') with local value '" + versionInfo.fileVersion + "'"); c.getVersionInfo().setFileVersion(versionInfo.fileVersion); } if (versionInfo.txtFileVersion != null) { getLog().debug("Overwriting config file property 'versionInfo.txtFileVersion' (='" + c.getVersionInfo().getTxtFileVersion() + "') with local value '" + versionInfo.txtFileVersion + "'"); c.getVersionInfo().setTxtFileVersion(versionInfo.txtFileVersion); } if (versionInfo.productVersion != null) { getLog().debug("Overwriting config file property 'versionInfo.productVersion' (='" + c.getVersionInfo().getProductVersion() + "') with local value '" + versionInfo.productVersion + "'"); c.getVersionInfo().setProductVersion(versionInfo.productVersion); } if (versionInfo.txtProductVersion != null) { getLog().debug("Overwriting config file property 'versionInfo.txtProductVersion' (='" + c.getVersionInfo().getTxtProductVersion() + "') with local value '" + versionInfo.txtProductVersion + "'"); c.getVersionInfo().setTxtProductVersion(versionInfo.txtProductVersion); } } ConfigPersister.getInstance().setAntConfig(c, infile.getParentFile()); } catch (ConfigPersisterException e) { getLog().error(e); throw new MojoExecutionException("Could not load Launch4j native configuration file", e); } } else { throw new MojoExecutionException("Launch4j native configuration file [" + infile.getAbsolutePath() + "] does not exist!"); } } else { final Config c = new Config(); c.setHeaderType(headerType); c.setOutfile(outfile); c.setJar(getJar()); c.setDontWrapJar(dontWrapJar); c.setErrTitle(errTitle); c.setDownloadUrl(downloadUrl); c.setSupportUrl(supportUrl); c.setCmdLine(cmdLine); c.setChdir(chdir); c.setPriority(priority); c.setStayAlive(stayAlive); c.setRestartOnCrash(restartOnCrash); c.setManifest(manifest); c.setIcon(icon); c.setHeaderObjects(relativizeAndCopy(workDir, objs)); c.setLibs(relativizeAndCopy(workDir, libs)); c.setVariables(vars); if (classPath != null) { c.setClassPath(classPath.toL4j(dependencies)); } if (jre != null) { jre.deprecationWarning(getLog()); c.setJre(jre.toL4j()); } if (singleInstance != null) { c.setSingleInstance(singleInstance.toL4j()); } if (splash != null) { c.setSplash(splash.toL4j()); } if (versionInfo != null) { c.setVersionInfo(versionInfo.toL4j()); } if (messages != null) { if (messages.bundledJreErr != null) { getLog().warn(" is deprecated, use instead!"); } c.setMessages(messages.toL4j()); } ConfigPersister.getInstance().setAntConfig(c, getBaseDir()); } if (getLog().isDebugEnabled()) { printState(); } final Builder builder = new Builder(new MavenLog(getLog()), workDir); try { builder.build(); } catch (BuilderException e) { getLog().error(e); throw new MojoExecutionException("Failed to build the executable; please verify your configuration.", e); } if (saveConfig) { try { ConfigPersister.getInstance().save(configOutfile); } catch (ConfigPersisterException e) { throw new MojoExecutionException("Cannot save config into a XML file", e); } } } private void fillSensibleJreDefaults() throws MojoExecutionException { if (jre == null) { jre = new Jre(); } if (jre.path == null) { String pathDef = "%JAVA_HOME%;%PATH%"; getLog().warn("jre.path not set, defaulting to \"" + pathDef + "\""); jre.path = pathDef; } } private void processRequireAdminRights() throws MojoExecutionException { if (requireAdminRights) { getLog().warn("Modifying the resulting exe to always require Admin rights."); getLog().warn("Make sure it's necessary. Consider writing your own manifest file."); if (manifest != null) { getLog().warn("manifest param is already set, overriding. Make sure that's what's intended."); } try { File metaInfDir = new File(basedir, "target/classes/META-INF"); metaInfDir.mkdir(); File manFile = new File(basedir, DEF_REQADMMAN_FILE); byte[] manBytes = ResourceIO.readResourceAsBytes(DEF_REQADMMAN_RES); ResourceIO.writeBytesIfDiff(manFile, manBytes); byte[] savedBytes = ResourceIO.readBytes(manFile); if (Arrays.equals(manBytes, savedBytes)) { getLog().info("Manifest file written to " + manFile); } manifest = manFile; } catch (Exception e) { getLog().error(e); throw new MojoExecutionException(e); } } } /** * Prepares a little directory for launch4j to do its thing. Launch4j needs a bunch of object files * (in the w32api and head directories) and the ld and windres binaries (in the bin directory). * The tricky part is that launch4j picks this directory based on where its own jar is sitting. * In our case, the jar is going to be sitting in the user's ~/.m2 repository. That's okay: we know * maven is allowed to write there. So we'll just add our things to that directory. *

* This approach is not without flaws. * It risks two processes writing to the directory at the same time. * But fortunately, once the binary bits are in place, we don't do any more writing there, * and launch4j doesn't write there either. * Usually ~/.m2 will only be one system or another. * But if it's an NFS mount shared by several system types, this approach will break. *

* Okay, so here is a better proposal: package the plugin without these varying binary files, * and put each set of binaries in its own tarball. Download the tarball you need to ~/.m2 and * unpack it. Then different systems won't contend for the same space. But then I'll need to hack * the l4j code so it permits passing in a work directory and doesn't always base it on * the location of its own jarfile. * * @return the work directory. */ private File setupBuildEnvironment() throws MojoExecutionException { createParentFolder(); Artifact binaryBits = chooseBinaryBits(); if (retrieveBinaryBits(binaryBits)) { return unpackWorkDir(binaryBits); } else { throw new MojoExecutionException("Artifact: " + binaryBits + " is not available!"); } } private void createParentFolder() { if (outfile != null) { File parent = outfile.getParentFile(); if (!parent.exists()) { getLog().debug("Parent " + parent.getPath() + " does not exist, creating it!"); boolean created = parent.mkdirs(); if (created) { getLog().debug("Parent " + parent.getPath() + " has been created!"); } else { getLog().warn("Cannot create parent " + parent.getPath() + "!"); } } } } /** * Unzips the given artifact in-place and returns the newly-unzipped top-level directory. * Writes a marker file to prevent unzipping more than once. */ private File unpackWorkDir(Artifact artifact) throws MojoExecutionException { getLog().debug("Trying normal search first, all-repo search if normal fails"); LocalArtifactRequest request = new LocalArtifactRequest(artifact, null, null); LocalArtifactResult localArtifact = repositorySystemSession.getLocalRepositoryManager().find(repositorySystemSession, request); if (localArtifact == null || localArtifact.getFile() == null) { getLog().warn("Cannot obtain file path to " + artifact + ", trying all-repo search"); request = new LocalArtifactRequest(artifact, repositories, null); localArtifact = repositorySystemSession.getLocalRepositoryManager().find(repositorySystemSession, request); if (localArtifact == null || localArtifact.getFile() == null) { String err = "Cannot obtain file path to " + artifact + " with both normal and all-repo search"; getLog().error(err); throw new MojoExecutionException(err); } } boolean artifactIsSnapshot = !artifact.getVersion().equals(artifact.getBaseVersion()); getLog().debug("Unpacking " + localArtifact + " into " + localArtifact.getFile()); File platJar = localArtifact.getFile(); File dest = platJar.getParentFile(); File marker = new File(dest, platJar.getName() + ".unpacked"); String n = platJar.getName(); File workdir = new File(dest, n.substring(0, n.length() - 4)); // If the artifact is a SNAPSHOT, then a.getVersion() will report the long timestamp, // but getFile() will be 1.1-SNAPSHOT. // Since getFile() doesn't use the timestamp, all timestamps wind up in the same place. // WRONG. getFile returns names like // "lbfork-launch4j-3.53-20240105.004437-1-workdir-win32.jar" as of // 2024-01-05. // QUESTION: maybe it depends on Maven's version? Need to support both. // FIX: if it contains expanded version replace it back by expandable version. if (artifactIsSnapshot && workdir.toString().contains(artifact.getVersion())) { String oldWorkdirStr = workdir.toString(); String newWorkdirStr = oldWorkdirStr.replace(artifact.getVersion(), artifact.getBaseVersion()); getLog().info("Unexpected workdir, correcting from " + oldWorkdirStr + " to " + newWorkdirStr); workdir = new File(newWorkdirStr); } // Therefore we need to expand the jar every time, if the marker file is stale. if (marker.exists() && marker.lastModified() > platJar.lastModified()) { // if (marker.exists() && marker.platJar.getName().indexOf("SNAPSHOT") == -1) { getLog().info("Platform-specific work directory already exists: " + workdir.getAbsolutePath()); } else { // trying to use plexus-archiver here is a miserable waste of time: try (JarFile jf = new JarFile(platJar)) { Enumeration en = jf.entries(); while (en.hasMoreElements()) { JarEntry je = en.nextElement(); File outFile = new File(dest, je.getName()); if (!outFile.toPath().normalize().startsWith(dest.toPath().normalize())) { throw new RuntimeException("Bad zip entry"); } File parent = outFile.getParentFile(); if (parent != null) parent.mkdirs(); if (je.isDirectory()) { outFile.mkdirs(); } else { try (InputStream in = jf.getInputStream(je)) { try (FileOutputStream fout = new FileOutputStream(outFile)) { byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) >= 0) { fout.write(buf, 0, len); } } } outFile.setLastModified(je.getTime()); } } } catch (IOException e) { throw new MojoExecutionException("Error unarchiving " + platJar, e); } try { marker.createNewFile(); marker.setLastModified(new Date().getTime()); } catch (IOException e) { getLog().warn("Trouble creating marker file " + marker, e); } } setPermissions(workdir); getLog().info("Using workdir " + workdir); return workdir; } /** * Chmods the helper executables ld and windres on systems where that is necessary. */ private void setPermissions(File workdir) { if (!System.getProperty("os.name").startsWith("Windows")) { try { new ProcessBuilder("chmod", "755", workdir + "/bin/ld").start().waitFor(); new ProcessBuilder("chmod", "755", workdir + "/bin/windres").start().waitFor(); } catch (InterruptedException e) { getLog().warn("Interrupted while chmodding platform-specific binaries", e); } catch (IOException e) { getLog().warn("Unable to set platform-specific binaries to 755", e); } } } /** * If custom header objects or libraries shall be linked, they need to sit inside the launch4j working dir. */ private List relativizeAndCopy(File workdir, List paths) throws MojoExecutionException { if (paths == null) return null; List result = new ArrayList<>(); for (String path : paths) { Path source = basedir.toPath().resolve(path); Path dest = workdir.toPath().resolve(basedir.toPath().relativize(source)); if (!source.startsWith(basedir.toPath())) { throw new MojoExecutionException("File must reside in the project directory: " + path); } if (Files.exists(source)) { try { Files.createDirectories(dest.getParent()); Path target = Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING); result.add(workdir.toPath().relativize(target).toString()); } catch (IOException e) { throw new MojoExecutionException("Can't copy file to workdir", e); } } else { result.add(path); } } return result; } /** * Downloads the platform-specific parts, if necessary. */ private boolean retrieveBinaryBits(Artifact a) throws MojoExecutionException { getLog().debug("Retrieving artifact: " + a + " stored in " + a.getFile()); try { ArtifactRequest request = new ArtifactRequest(a, repositories, null); return repositorySystem.resolveArtifact(repositorySystemSession, request).isResolved(); } catch (IllegalArgumentException e) { throw new MojoExecutionException("Illegal Argument Exception", e); } catch (ArtifactResolutionException e) { throw new MojoExecutionException("Can't retrieve platform-specific components", e); } } /** * Decides which platform-specific bundle we need, based on the current operating system. */ private Artifact chooseBinaryBits() throws MojoExecutionException { String plat; String os = System.getProperty("os.name"); String arch = System.getProperty("os.arch"); getLog().debug("OS = " + os); getLog().debug("Architecture = " + arch); // See here for possible values of os.name: // http://lopica.sourceforge.net/os.html if (os.startsWith("Windows")) { plat = "win32"; } else if ("Linux".equals(os)) { if ("amd64".equals(arch)) { plat = "linux64"; } else { plat = "linux"; } } else if ("Solaris".equals(os) || "SunOS".equals(os)) { plat = "solaris"; } else if ("Mac OS X".equals(os) || "Darwin".equals(os)) { plat = "mac"; } else { throw new MojoExecutionException("Sorry, Launch4j doesn't support the '" + os + "' OS."); } Artifact artifact = new DefaultArtifact(launch4jGroupId, launch4jArtifactId, "workdir-" + plat, "jar", getLaunch4jVersion()); try { ArtifactRequest request = new ArtifactRequest(artifact, repositories, null); return repositorySystem.resolveArtifact(repositorySystemSession, request).getArtifact(); } catch (ArtifactResolutionException e) { throw new MojoExecutionException(e); } } private File getBaseDir() { return basedir; } /** * Just prints out how we were configured. */ private void printState() { Log log = getLog(); Config c = ConfigPersister.getInstance().getConfig(); log.debug("headerType = " + c.getHeaderType()); log.debug("outfile = " + c.getOutfile()); log.debug("jar = " + c.getJar()); log.debug("dontWrapJar = " + c.isDontWrapJar()); log.debug("errTitle = " + c.getErrTitle()); log.debug("downloadUrl = " + c.getDownloadUrl()); log.debug("supportUrl = " + c.getSupportUrl()); log.debug("cmdLine = " + c.getCmdLine()); log.debug("chdir = " + c.getChdir()); log.debug("priority = " + c.getPriority()); log.debug("stayAlive = " + c.isStayAlive()); log.debug("restartOnCrash = " + c.isRestartOnCrash()); log.debug("icon = " + c.getIcon()); log.debug("objs = " + c.getHeaderObjects()); log.debug("libs = " + c.getLibs()); log.debug("vars = " + c.getVariables()); if (c.getSingleInstance() != null) { log.debug("singleInstance.mutexName = " + c.getSingleInstance().getMutexName()); log.debug("singleInstance.windowTitle = " + c.getSingleInstance().getWindowTitle()); } else { log.debug("singleInstance = null"); } if (c.getJre() != null) { log.debug("jre.path = " + c.getJre().getPath()); log.debug("jre.minVersion = " + c.getJre().getMinVersion()); log.debug("jre.maxVersion = " + c.getJre().getMaxVersion()); log.debug("jre.requiresJdk = " + c.getJre().getRequiresJdk()); log.debug("jre.requires64Bit = " + c.getJre().getRequires64Bit()); log.debug("jre.initialHeapSize = " + c.getJre().getInitialHeapSize()); log.debug("jre.initialHeapPercent = " + c.getJre().getInitialHeapPercent()); log.debug("jre.maxHeapSize = " + c.getJre().getMaxHeapSize()); log.debug("jre.maxHeapPercent = " + c.getJre().getMaxHeapPercent()); log.debug("jre.opts = " + c.getJre().getOptions()); } else { log.debug("jre = null"); } if (c.getClassPath() != null) { log.debug("classPath.mainClass = " + c.getClassPath().getMainClass()); } if (classPath != null) { log.debug("classPath.addDependencies = " + classPath.addDependencies); log.debug("classPath.jarLocation = " + classPath.jarLocation); log.debug("classPath.preCp = " + classPath.preCp); log.debug("classPath.postCp = " + classPath.postCp); } else { log.info("classpath = null"); } if (c.getSplash() != null) { log.debug("splash.file = " + c.getSplash().getFile()); log.debug("splash.waitForWindow = " + c.getSplash().getWaitForWindow()); log.debug("splash.timeout = " + c.getSplash().getTimeout()); log.debug("splash.timoutErr = " + c.getSplash().isTimeoutErr()); } else { log.debug("splash = null"); } if (c.getVersionInfo() != null) { log.debug("versionInfo.fileVersion = " + c.getVersionInfo().getFileVersion()); log.debug("versionInfo.txtFileVersion = " + c.getVersionInfo().getTxtFileVersion()); log.debug("versionInfo.fileDescription = " + c.getVersionInfo().getFileDescription()); log.debug("versionInfo.copyright = " + c.getVersionInfo().getCopyright()); log.debug("versionInfo.productVersion = " + c.getVersionInfo().getProductVersion()); log.debug("versionInfo.txtProductVersion = " + c.getVersionInfo().getTxtProductVersion()); log.debug("versionInfo.productName = " + c.getVersionInfo().getProductName()); log.debug("versionInfo.companyName = " + c.getVersionInfo().getCompanyName()); log.debug("versionInfo.internalName = " + c.getVersionInfo().getInternalName()); log.debug("versionInfo.originalFilename = " + c.getVersionInfo().getOriginalFilename()); log.debug("versionInfo.language = " + c.getVersionInfo().getLanguage()); log.debug("versionInfo.languageIndex = " + c.getVersionInfo().getLanguageIndex()); log.debug("versionInfo.trademarks = " + c.getVersionInfo().getTrademarks()); } else { log.debug("versionInfo = null"); } if (c.getMessages() != null) { log.debug("messages.startupErr = " + c.getMessages().getStartupErr()); log.debug("messages.jreNotFoundErr = " + c.getMessages().getJreNotFoundErr()); log.debug("messages.jreVersionErr = " + c.getMessages().getJreVersionErr()); log.debug("messages.launcherErr = " + c.getMessages().getLauncherErr()); log.debug("messages.instanceAlreadyExistsMsg = " + c.getMessages().getInstanceAlreadyExistsMsg()); } else { log.debug("messages = null"); } } /** * A version of the Launch4j used by the plugin. * We want to download the platform-specific bundle whose version matches the Launch4j version, * so we have to figure out what version the plugin is using. * * @return version of Launch4j * @throws MojoExecutionException when version is null */ private String getLaunch4jVersion() throws MojoExecutionException { String version = null; Set pluginArtifacts = oldPluginArtifacts.stream().map(old -> new DefaultArtifact(old.getGroupId(), old.getArtifactId(), old.getClassifier(), null, old.getVersion()) ).collect(Collectors.toSet()); for (Artifact artifact : pluginArtifacts) { if (launch4jGroupId.equals(artifact.getGroupId()) && launch4jArtifactId.equals(artifact.getArtifactId()) && "core".equals(artifact.getClassifier())) { version = artifact.getVersion(); getLog().info("Found launch4j version " + version); break; } } if (version == null) { throw new MojoExecutionException("Impossible to find which Launch4j version to use, no compatible version found in classpath"); } return version; } /** * Checks if execution of the plugin should be skipped * * @return true to skip execution */ private boolean skipExecution() { getLog().debug("skip = " + this.skip); getLog().debug("skipLaunch4j = " + System.getProperty("skipLaunch4j")); return skip || System.getProperty("skipLaunch4j") != null; } @Override public String toString() { return "Launch4jMojo{" + "headerType='" + headerType + '\'' + ", infile=" + infile + ", outfile=" + outfile + ", jar='" + jar + '\'' + ", dontWrapJar=" + dontWrapJar + ", errTitle='" + errTitle + '\'' + ", downloadUrl='" + downloadUrl + '\'' + ", supportUrl='" + supportUrl + '\'' + ", cmdLine='" + cmdLine + '\'' + ", chdir='" + chdir + '\'' + ", priority='" + priority + '\'' + ", stayAlive=" + stayAlive + ", restartOnCrash=" + restartOnCrash + ", icon=" + icon + ", requireAdminRights=" + requireAdminRights + ", objs=" + objs + ", libs=" + libs + ", vars=" + vars + ", jre=" + jre + ", classPath=" + classPath + ", singleInstance=" + singleInstance + ", splash=" + splash + ", versionInfo=" + versionInfo + ", disableVersionInfoDefaults=" + disableVersionInfoDefaults + ", messages=" + messages + ", manifest=" + manifest + ", saveConfig=" + saveConfig + ", configOutfile=" + configOutfile + ", parallelExecution=" + parallelExecution + ", skip=" + skip + '}'; } } ================================================ FILE: src/main/java/com/akathist/maven/plugins/launch4j/MavenLog.java ================================================ /* * Maven Launch4j Plugin * Copyright (c) 2006 Paul Jungwirth * Copyright (c) 2011-2025 Lukasz Lenart * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.akathist.maven.plugins.launch4j; import org.apache.maven.plugin.logging.Log; public class MavenLog extends net.sf.launch4j.Log { Log _log; public MavenLog(Log log) { _log = log; } @Override public void clear() { _log.info(""); } @Override public void append(String line) { _log.info("launch4j: " + line); } } ================================================ FILE: src/main/java/com/akathist/maven/plugins/launch4j/Messages.java ================================================ /* * Maven Launch4j Plugin * Copyright (c) 2006 Paul Jungwirth * Copyright (c) 2011-2025 Lukasz Lenart * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.akathist.maven.plugins.launch4j; import net.sf.launch4j.config.Msg; import org.apache.maven.plugins.annotations.Parameter; /** * Details about messages you can pass. */ public class Messages { @Parameter String startupErr; @Parameter @Deprecated String bundledJreErr; @Parameter String jreVersionErr; @Parameter String launcherErr; @Parameter String instanceAlreadyExistsMsg; @Parameter String jreNotFoundErr; Msg toL4j() { Msg ret = new Msg(); ret.setStartupErr(startupErr); ret.setJreVersionErr(jreVersionErr); ret.setLauncherErr(launcherErr); ret.setInstanceAlreadyExistsMsg(instanceAlreadyExistsMsg); /* since Launch4j 3.50 */ ret.setJreNotFoundErr(jreNotFoundErr); return ret; } @Override public String toString() { return "Messages{" + "startupErr='" + startupErr + '\'' + ", jreVersionErr='" + jreVersionErr + '\'' + ", launcherErr='" + launcherErr + '\'' + ", instanceAlreadyExistsMsg='" + instanceAlreadyExistsMsg + '\'' + ", jreNotFoundErr='" + jreNotFoundErr + '\'' + '}'; } } ================================================ FILE: src/main/java/com/akathist/maven/plugins/launch4j/SingleInstance.java ================================================ /* * Maven Launch4j Plugin * Copyright (c) 2006 Paul Jungwirth * Copyright (c) 2011-2025 Lukasz Lenart * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.akathist.maven.plugins.launch4j; import org.apache.maven.plugins.annotations.Parameter; /** * Details about running your application as a single instance. */ public class SingleInstance { @Parameter String mutexName; @Parameter String windowTitle; net.sf.launch4j.config.SingleInstance toL4j() { net.sf.launch4j.config.SingleInstance ret = new net.sf.launch4j.config.SingleInstance(); ret.setMutexName(mutexName); ret.setWindowTitle(windowTitle); return ret; } } ================================================ FILE: src/main/java/com/akathist/maven/plugins/launch4j/Splash.java ================================================ /* * Maven Launch4j Plugin * Copyright (c) 2006 Paul Jungwirth * Copyright (c) 2011-2025 Lukasz Lenart * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.akathist.maven.plugins.launch4j; import java.io.*; import org.apache.maven.plugins.annotations.Parameter; public class Splash { /** * The path (relative to the executable when distributed) to the splash page image. */ @Parameter File file; /** * If true, the splash screen will close automatically as soon as an error window or java window appears. * If false, the splash screen will not close until {@link #timeout} sections. Defaults to true. */ @Parameter(defaultValue = "true") boolean waitForWindow; /** * The number of seconds to keep the splash screen open before automatically closing it. * Defaults to 60. */ @Parameter(defaultValue = "60") int timeout; /** * If true, an error message will appear if the app hasn't started in {@link #timeout} seconds. * If false, the splash screen will close quietly. Defaults to true. */ @Parameter(defaultValue = "true") boolean timeoutErr; net.sf.launch4j.config.Splash toL4j() { net.sf.launch4j.config.Splash ret = new net.sf.launch4j.config.Splash(); ret.setFile(file); ret.setWaitForWindow(waitForWindow); ret.setTimeout(timeout); ret.setTimeoutErr(timeoutErr); return ret; } @Override public String toString() { return "Splash{" + "file=" + file + ", waitForWindow=" + waitForWindow + ", timeout=" + timeout + ", timeoutErr=" + timeoutErr + '}'; } } ================================================ FILE: src/main/java/com/akathist/maven/plugins/launch4j/VersionInfo.java ================================================ /* * Maven Launch4j Plugin * Copyright (c) 2006 Paul Jungwirth * Copyright (c) 2011-2025 Lukasz Lenart * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.akathist.maven.plugins.launch4j; import com.akathist.maven.plugins.launch4j.generators.CopyrightGenerator; import com.akathist.maven.plugins.launch4j.generators.Launch4jFileVersionGenerator; import net.sf.launch4j.config.LanguageID; import org.apache.commons.lang3.StringUtils; import org.apache.maven.model.Organization; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import java.io.File; import java.util.HashMap; import java.util.Map; /** * Information that appears in the Windows Explorer. */ public class VersionInfo { private static final Map LANGUAGE_TO_LANGUAGE_ID; static { LANGUAGE_TO_LANGUAGE_ID = new HashMap<>(); for (LanguageID languageID : LanguageID.values()) { LANGUAGE_TO_LANGUAGE_ID.put(languageID.name(), languageID); } } /** * Version number in x.x.x.x format. */ @Parameter String fileVersion; /** * Free-form version number, like "1.20.RC1." */ @Parameter String txtFileVersion; /** * File description shown to the user. */ @Parameter String fileDescription; /** * Legal copyright. */ @Parameter String copyright; /** * Version number in x.x.x.x format. */ @Parameter String productVersion; /** * Free-form version number, like "1.20.RC1." */ @Parameter String txtProductVersion; /** * The product name. */ @Parameter String productName; /** * The company name. */ @Parameter String companyName; /** * The internal name. For instance, you could use the filename without extension or the module name. */ @Parameter String internalName; /** * The original filename without path. Setting this lets you determine whether a user has renamed the file. */ @Parameter String originalFilename; /** * Language to be used during installation, default ENGLISH_US */ @Parameter String language = LanguageID.ENGLISH_US.name(); /** * Trademarks of author */ @Parameter String trademarks; private Log log; public VersionInfo() { } public VersionInfo(String fileVersion, String txtFileVersion, String fileDescription, String copyright, String productVersion, String txtProductVersion, String productName, String companyName, String internalName, String originalFilename, String language, String trademarks, Log log) { this.fileVersion = fileVersion; this.txtFileVersion = txtFileVersion; this.fileDescription = fileDescription; this.copyright = copyright; this.productVersion = productVersion; this.txtProductVersion = txtProductVersion; this.productName = productName; this.companyName = companyName; this.internalName = internalName; this.originalFilename = originalFilename; this.language = language; this.trademarks = trademarks; this.log = log; } public void setLog(Log log) { this.log = log; } net.sf.launch4j.config.VersionInfo toL4j() { net.sf.launch4j.config.VersionInfo ret = new net.sf.launch4j.config.VersionInfo(); ret.setFileVersion(fileVersion); ret.setTxtFileVersion(txtFileVersion); ret.setFileDescription(fileDescription); ret.setCopyright(copyright); ret.setProductVersion(productVersion); ret.setTxtProductVersion(txtProductVersion); ret.setProductName(productName); ret.setCompanyName(companyName); ret.setInternalName(internalName); ret.setOriginalFilename(originalFilename); setLanguage(ret); ret.setTrademarks(trademarks); return ret; } private void setLanguage(net.sf.launch4j.config.VersionInfo ret) { LanguageID languageID = LANGUAGE_TO_LANGUAGE_ID.get(language); if (languageID == null) { languageID = LanguageID.ENGLISH_US; } ret.setLanguage(languageID); } void tryFillOutByDefaults(MavenProject project, File outfile) { if (project == null) { throw new IllegalArgumentException("'project' is required, but it is null."); } if (outfile == null) { throw new IllegalArgumentException("'outfile' is required, but it is null."); } String version = getDefaultWhenSourceIsBlankAndLogWarn(project.getVersion(), "1.0.0", "project.version"); Organization organization = project.getOrganization(); String organizationName = "Default organization"; if(organization == null) { logWarningAboutDummyValue("project.organization.name", organizationName); } else { organizationName = getDefaultWhenSourceIsBlankAndLogWarn(organization.getName(), organizationName, "project.organization.name"); } tryFillOutByDefaultVersionInL4jFormat(version); tryFillOutCopyrightByDefaults( getDefaultWhenSourceIsBlankAndLogWarn(project.getInceptionYear(), "2020", "project.inceptionYear"), organizationName ); tryFillOutOrganizationRelatedDefaults(organizationName); tryFillOutSimpleValuesByDefaults( version, getDefaultWhenSourceIsBlankAndLogWarn(project.getName(), "Java Project", "project.name"), getDefaultWhenSourceIsBlankAndLogWarn(project.getArtifactId(), "java-project", "project.artifactId"), getDefaultWhenSourceIsBlankAndLogWarn(project.getDescription(), "A Java project.", "project.description") ); String outfileName = getDefaultWhenSourceIsBlankAndLogWarn(outfile.getName(), "app.exe", "outfile"); originalFilename = getDefaultWhenSourceIsBlank(originalFilename, outfileName); } private void tryFillOutByDefaultVersionInL4jFormat(String version) { String defaultFileVersion = Launch4jFileVersionGenerator.generate(version); fileVersion = getDefaultWhenSourceIsBlank(fileVersion, defaultFileVersion); productVersion = getDefaultWhenSourceIsBlank(productVersion, defaultFileVersion); } private void tryFillOutCopyrightByDefaults(String inceptionYear, String organizationName) { final String defaultCopyright = CopyrightGenerator.generate(inceptionYear, organizationName); copyright = getDefaultWhenSourceIsBlank(copyright, defaultCopyright); } private void tryFillOutOrganizationRelatedDefaults(String organizationName) { companyName = getDefaultWhenSourceIsBlank(companyName, organizationName); trademarks = getDefaultWhenSourceIsBlank(trademarks, organizationName); } private void tryFillOutSimpleValuesByDefaults(String version, String name, String artifactId, String description) { txtFileVersion = getDefaultWhenSourceIsBlank(txtFileVersion, version); txtProductVersion = getDefaultWhenSourceIsBlank(txtProductVersion, version); productName = getDefaultWhenSourceIsBlank(productName, name); internalName = getDefaultWhenSourceIsBlank(internalName, artifactId); fileDescription = getDefaultWhenSourceIsBlank(fileDescription, description); } private String getDefaultWhenSourceIsBlank(final String source, final String defaultValue) { if (StringUtils.isBlank(source)) { return defaultValue; } return source; } private String getDefaultWhenSourceIsBlankAndLogWarn(final String source, final String defaultValue, final String sourceParamName) { if (StringUtils.isBlank(source)) { logWarningAboutDummyValue(sourceParamName, defaultValue); return defaultValue; } return source; } private void logWarningAboutDummyValue(final String sourceParamName, final String dummyValue) { log.warn("Configuration param ${" + sourceParamName + "} is empty, so a dummy value \"" + dummyValue + "\" " + "might be used instead to fulfill some of VersionInfo params by defaults."); } @Override public String toString() { return "VersionInfo{" + "fileVersion='" + fileVersion + '\'' + ", txtFileVersion='" + txtFileVersion + '\'' + ", fileDescription='" + fileDescription + '\'' + ", copyright='" + copyright + '\'' + ", productVersion='" + productVersion + '\'' + ", txtProductVersion='" + txtProductVersion + '\'' + ", productName='" + productName + '\'' + ", companyName='" + companyName + '\'' + ", internalName='" + internalName + '\'' + ", originalFilename='" + originalFilename + '\'' + ", language='" + language + '\'' + ", trademarks='" + trademarks + '\'' + '}'; } } ================================================ FILE: src/main/java/com/akathist/maven/plugins/launch4j/generators/CopyrightGenerator.java ================================================ /* * 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. */ package com.akathist.maven.plugins.launch4j.generators; import org.apache.commons.lang3.StringUtils; import java.time.LocalDate; public class CopyrightGenerator { private CopyrightGenerator() { } /** * Parameters should be taken from MavenProject properties: * @param projectInceptionYear as ${project.inceptionYear} * @param projectOrganizationName as ${project.organization.name} * @return a string representing copyrights */ public static String generate(String projectInceptionYear, String projectOrganizationName) { String inceptionYear = generateInceptionYear(projectInceptionYear); int buildYear = LocalDate.now().getYear(); String organizationName = generateOrganizationName(projectOrganizationName); return String.format("Copyright © %s%d%s. All rights reserved.", inceptionYear, buildYear, organizationName); } private static String generateInceptionYear(String projectInceptionYear) { if(StringUtils.isNotBlank(projectInceptionYear)) { return projectInceptionYear + "-"; } return ""; } private static String generateOrganizationName(String projectOrganizationName) { if(StringUtils.isNotBlank(projectOrganizationName)) { return " " + projectOrganizationName; } return ""; } } ================================================ FILE: src/main/java/com/akathist/maven/plugins/launch4j/generators/Launch4jFileVersionGenerator.java ================================================ /* * 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. */ package com.akathist.maven.plugins.launch4j.generators; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Launch4jFileVersionGenerator { private static final int REQUIRED_NESTED_VERSION_LEVELS = 4; private static final String SIMPLE_PROJECT_VERSION_REGEX = "^((\\d(\\.)?)*\\d+)(-\\w+)?(?:-(?[\\w.-]+))?(?:\\+(?[\\w.-]+))?$"; private static final Pattern simpleProjectVersionPattern = Pattern.compile( SIMPLE_PROJECT_VERSION_REGEX, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE ); private Launch4jFileVersionGenerator() { } /** * Converts projectVersion into a format "x.x.x.x" ('x' as a number), which is required by Launch4j. *

* For shorter versions like "x.x.x" it will append zeros (to the 4th level) at the end like "x.x.x.0". * Every text flag like "-SNAPSHOT" or "-alpha" will be cut off. * Too many nested numbers (more than 4 levels) will be cut off as well: "1.2.3.4.5.6" into "1.2.3.4". * Leading zeros in version components are stripped to avoid "digit exceeds base" errors in windres. *

* Param should be taken from MavenProject property: * @param projectVersion as ${project.version} * @return a string representing a file version of format x.x.x.x */ public static String generate(String projectVersion) { if(projectVersion == null) { return null; } if(!simpleProjectVersionPattern.matcher(projectVersion).matches()) { throw new IllegalArgumentException("'project.version' is in invalid format. Regex pattern: " + SIMPLE_PROJECT_VERSION_REGEX); } String versionLevels = removeTextFlags(projectVersion); String normalizedVersionLevels = stripLeadingZeros(versionLevels); String limitedVersionLevels = cutOffTooManyNestedLevels(normalizedVersionLevels); return appendMissingNestedLevelsByZeros(limitedVersionLevels); } private static String removeTextFlags(String version) { Pattern pattern = Pattern.compile("[-+]"); Matcher matcher = pattern.matcher(version); if (matcher.find()) { return version.substring(0, matcher.start()); } else { return version; } } /** * Strips leading zeros from each version component to prevent "digit exceeds base" errors in windres. * For example, "302.08.01" becomes "302.8.1". * Special case: "0" remains "0" (doesn't become empty string). * * @param version version string with components separated by dots * @return version string with leading zeros stripped from each component */ private static String stripLeadingZeros(String version) { String[] levels = version.split("\\."); for (int i = 0; i < levels.length; i++) { // Parse as integer and convert back to string to remove leading zeros // This handles the special case where "000" becomes "0" try { levels[i] = String.valueOf(Integer.parseInt(levels[i])); } catch (NumberFormatException e) { // This should not happen given the regex validation, but keep original if it does // The existing validation should have caught invalid numbers already throw new IllegalArgumentException("Invalid number format in version component: " + levels[i], e); } } return String.join(".", levels); } private static String cutOffTooManyNestedLevels(String versionLevels) { String[] levels = versionLevels.split("\\."); if(levels.length > REQUIRED_NESTED_VERSION_LEVELS) { List limitedLevels = Arrays.asList(levels) .subList(0, REQUIRED_NESTED_VERSION_LEVELS); return String.join(".", limitedLevels); } return versionLevels; } private static String appendMissingNestedLevelsByZeros(String versionLevels) { String[] levels = versionLevels.split("\\."); StringBuilder filledLevels = new StringBuilder(versionLevels); for (int i = levels.length; i < REQUIRED_NESTED_VERSION_LEVELS; i++) { filledLevels.append(".0"); } return filledLevels.toString(); } } ================================================ FILE: src/main/java/com/akathist/maven/plugins/launch4j/tools/ResourceIO.java ================================================ /* * 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. */ package com.akathist.maven.plugins.launch4j.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; final public class ResourceIO { private static final int DEFAULT_BUFFER_SIZE = 4 * 1024; private ResourceIO() { // avoids creating an instance of this class } private static byte[] readAllBytes(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; int bytesRead; while ((bytesRead = is.read(buf)) != -1) { baos.write(buf, 0, bytesRead); } return baos.toByteArray(); } public static byte[] readResourceAsBytes(String resName) throws IOException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try (InputStream is = cl.getResourceAsStream(resName)) { if (is == null) { throw new IOException("Resource not found: " + resName); } return readAllBytes(is); } } public static void writeBytesIfDiff(File outFile, byte[] outBytes) throws IOException { if (outFile.exists()) { byte[] existingBytes = readBytes(outFile); if (Arrays.equals(outBytes, existingBytes)) { return; } } writeBytes(outFile, outBytes); } public static byte[] readBytes(File inFile) throws IOException { try ( FileInputStream fis = new FileInputStream(inFile); BufferedInputStream bis = new BufferedInputStream(fis) ) { return readAllBytes(bis); } } public static void writeBytes(File outFile, byte[] outBytes) throws IOException { try ( FileOutputStream fos = new FileOutputStream(outFile, false); BufferedOutputStream bos = new BufferedOutputStream(fos) ) { bos.write(outBytes); bos.flush(); } } } ================================================ FILE: src/main/legal/LICENSE.txt ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: src/main/legal/XStream.LICENSE.txt ================================================ Copyright (c) 2003-2006, Joe Walnes Copyright (c) 2006-2015 XStream Committers All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of XStream nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: src/main/legal/commons.LICENSE.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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 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. ================================================ FILE: src/main/resources/META-INF/resources/manifest-require_admin_rights-v1.xml ================================================ ================================================ FILE: src/main/resources/MOJO.md ================================================ # Launch4j Maven plugin – launch4j:launch4j **Description**: Wraps a jar in a Windows executable. **Attributes**: * Requires a Maven project to be executed. * Requires dependency resolution of artifacts in scope: `runtime`. * The goal is thread-safe and supports parallel builds. * Binds by default to the [lifecycle phase](http://maven.apache.org/ref/current/maven-core/lifecycles.html): `package`. ### Parameter Details #### **\** Changes to the given directory, relative to the executable, before running your jar. If set to `.` the current directory will be where the executable is. If omitted, the directory will not be changed. * **Type**: `java.lang.String` * **Required**: `No` * * * #### **\** Details about the classpath your application should have. This is required if you are not wrapping a jar. * **Type**: `com.akathist.maven.plugins.launch4j.ClassPath` * **Required**: `No` * * * #### **\** Constant command line arguments to pass to your program's main method. Actual command line arguments entered by the user will appear after these. * **Type**: `java.lang.String` * **Required**: `No` * * * #### **\** If `saveConfig` is set to true, config will be written to this file * **Type**: `java.io.File` * **Required**: `No` * **Default**: `${project.build.directory}/launch4j-config.xml` * * * #### **\** Whether the executable should wrap the jar or not. * **Type**: `boolean` * **Required**: `No` * **Default**: `false` * * * #### **\** downloadUrl (?). * **Type**: `java.lang.String` * **Required**: `No` * * * #### **\** The title of the error popup if something goes wrong trying to run your program, like if java can't be found. If this is a console app and not a gui, then this value is used to prefix any error messages, as in ${errTitle}: ${errorMessage}. * **Type**: `java.lang.String` * **Required**: `No` * **Default**: `${project.name}` * * * #### **\** Whether you want a gui or console app. Valid values are "gui" and "console." If you say gui, then launch4j will run your app from javaw instead of java in order to avoid opening a DOS window. Choosing gui also enables other options like taskbar icon and a splash screen. * **Type**: `java.lang.String` * **Required**: `No` * * * #### **\** The icon to use in the taskbar. Must be in ico format. * **Type**: `java.io.File` * **Required**: `No` * * * #### **\** The name of the Launch4j native configuration file The path, if relative, is relative to the pom.xml. * **Type**: `java.io.File` * **Required**: `No` * * * #### **\** The jar to bundle inside the executable. The path, if relative, is relative to the pom.xml. If you don't want to wrap the jar, then this value should be the runtime path to the jar relative to the executable. You should also set dontWrapJar to true. You can only bundle a single jar. Therefore, you should either create a jar that contains your own code plus all your dependencies, or you should distribute your dependencies alongside the executable. * **Type**: `java.lang.String` * **Required**: `No` * **Default**: `${project.build.directory}/${project.build.finalName}.jar` * * * #### **\** Details about the supported jres. * **Type**: `com.akathist.maven.plugins.launch4j.Jre` * **Required**: `No` * * * #### **\** Win32 libraries to include. Used for custom headers only. * **Type**: `java.util.List` * **Required**: `No` * * * #### **\** Windows manifest file (a XML file) with the same name as .exe file (myapp.exe.manifest) * **Type**: `java.io.File` * **Required**: `No` * * * #### **\** Various messages you can display. * **Type**: `com.akathist.maven.plugins.launch4j.Messages` * **Required**: `No` * * * #### **\** Object files to include. Used for custom headers only. * **Type**: `java.util.List` * **Required**: `No` * * * #### **\** The name of the executable you want launch4j to produce. The path, if relative, is relative to the pom.xml. * **Type**: `java.io.File` * **Required**: `No` * **Default**: `${project.build.directory}/${project.artifactId}.exe` * * * #### **\** If set to true, a synchronized block will be used to protect resources * **Type**: `boolean` * **Required**: `No` * **Default**: `false` * * * #### **\** The dependencies of this plugin. Used to get the Launch4j artifact version. * **Type**: `java.util.List` * **Required**: `No` * **Default**: `${plugin.artifacts}` * * * #### **\** Priority class of windows process. Valid values are "normal" (default), "idle" and "high". * **Type**: `java.lang.String` * **Required**: `No` * **Default**: `normal` * * * #### **\** If true, when the application exits, any exit code other than 0 is considered a crash and the application will be started again. * **Type**: `boolean` * **Required**: `No` * **Default**: `false` * * * #### **\** If set to true it will save final config into a XML file * **Type**: `boolean` * **Required**: `No` * **Default**: `false` * * * #### **\** Details about whether to run as a single instance. * **Type**: `com.akathist.maven.plugins.launch4j.SingleInstance` * **Required**: `No` * * * #### **\** If set to true, execution of the plugin will be skipped * **Type**: `boolean` * **Required**: `No` * **Default**: `false` * * * #### **\** Details about the splash screen. * **Type**: `com.akathist.maven.plugins.launch4j.Splash` * **Required**: `No` * * * #### **\** If true, the executable waits for the java application to finish before returning its exit code. Defaults to false for gui applications. Has no effect for console applications, which always wait. * **Type**: `boolean` * **Required**: `No` * **Default**: `false` * * * #### **\** supportUrl (?). * **Type**: `java.lang.String` * **Required**: `No` * * * #### **\** Variables to set. * **Type**: `java.util.List` * **Required**: `No` * * * #### **\** Lots of information you can attach to the windows process. * **Type**: `com.akathist.maven.plugins.launch4j.VersionInfo` * **Required**: `No` The full list of all the `VersionInfo` parameters is available [here](./VERSIONINFO.md). * * * #### **\** If `disableVersionInfoDefaults` is set to true, it will prevent filling out the VersionInfo params with default values. * **Type**: `boolean` * **Required**: `No` * **Default**: `false` * * * ================================================ FILE: src/main/resources/README.adoc ================================================ = Maven Launch4j Plugin Copyright (C) 2006 Paul Jungwirth with additional changes by Lukasz Lenart version 1.7.4, 13 February 2015 :toc: == Description http://launch4j.sourceforge.net/[Launch4j] by Grzegorz Kowal wraps a jar file in a Windows executable to ease deployment of Java desktop applications. You can either bundle a JRE or tell Launch4j to search the hard drive for an existing one. If none is found, then Launch4j will show the user a download page. Launch4j has many features. You can create either GUI or console applications. You can show a splash screen while the JRE loads, give your application a custom icon in the Windows task bar, set a more descriptive process name (other than "java"), and set a variety of other process attributes. You can run Launch4j on Windows, Linux, Solaris, or OS X. You specify the configuration through an XML file. Please see the Launch4j site for more information on this file. You can also set your configuration via the Launch4j GUI. The Maven plugin for Launch4j lets you generate the Launch4j executable as part of the Maven build process. It supports Maven 2.0.4 and Launch4j 3.x. Depending on your operating system, the plugin will download an additional artifact containing platform-specific binaries that Launch4j uses to create the executable. This artifact is treated like any other Maven dependency, so it is only downloaded the first time you need it. == Adding plugin to pom.xml Using the Maven plugin, you specify the Launch4j configuration in your POM. I hope to add support for external configuration files, but right now you have to use the POM. The format of this configuration is very similar to the standard Launch4j XML format. There are two main differences. First, any lists of like-named elements must appear in a wrapper element. For example, you can't say: [source,xml] ---- logo.bin this=that foo=bar blep=blurp ---- You must say: [source,xml] ---- logo.bin this=that foo=bar blep=blurp ---- Likewise for `` and `` elements. Second, the sub-elements of the `` element are a little different. This is so you can set the classpath based on your dependencies. `` still takes a `` element, but it does not take ``. Instead, it supports these children: * `` - If you set this to "true," the plugin will build your classpath based on all dependencies in the runtime and compile scopes. This is on by default. * `` - If you are using the addDependencies feature, you can use this option to add a prefix before each jar's name. This is useful if you are bundling your app with the executable alongside a lib directory that contains all your jars. If that's what you're doing, you would specify `lib/`. * `` - Use this to add classpath entries before the automatically- generated list. This element functions whether you have enabled `` or not. Entries in the list should be separated by semicolons, as in a Windows-style `CLASSPATH` variable. * `` - Use this to add classpath entries after the automatically- generated list. This element functions whether you have enabled `` or not. Entries in the list should be separated by semicolons, as in a Windows-style `CLASSPATH` variable. Other than these changes, the XML format is just like Launch4j's standard format. == Examples === Single-module project By default, the Launch4j plugin is bound to the package phase. Suppose you have a single-module project named encc. It is a console application, not a GUI. It is packaged as a jar, so the jarring runs automatically during the package phase before anything else. You want to use launch4j to create an executable and then use the assembly plugin to bundle everything up. You could bind both launch4j and assembly to the package phase with a POM like this: [source,xml] ---- . . . com.akathist.encc encc jar . . . com.akathist.maven.plugins.launch4j launch4j-maven-plugin l4j-clui package launch4j console target/encc.exe target/encc-1.0.jar encc com.akathist.encc.Clui false anything 1.5.0 -Djava.endorsed.dirs=./endorsed 1.2.3.4 txt file version? a description my copyright 4.3.2.1 txt product version E-N-C-C ccne original.exe maven-assembly-plugin assembly package single assembly.xml . . . ---- Note that when you bind the assembly plugin to a phase, you must use `assembly:single`, not `assembly:assembly`, to prevent its forking a parallel lifecycle and running everything twice. === GUI and console mode Or suppose your application can run in either GUI or console mode, and you want to create separate executables for each. Then your POM would look like this: [source,xml] ---- . . . com.akathist.encc encc jar . . . com.akathist.maven.plugins.launch4j launch4j-maven-plugin l4j-clui package launch4j console target/encc.exe target/encc-1.0.jar encc com.akathist.encc.Clui false anything 1.5.0 1.2.3.4 txt file version? a description my copyright 4.3.2.1 txt product version E-N-C-C ccne original.exe l4j-gui package launch4j gui target/enccg.exe target/encc-1.0.jar enccg com.akathist.encc.Gui 1.5.0 1.2.3.4 txt file version? a description my copyright 4.3.2.1 txt product version E-N-C-C ccne original.exe maven-assembly-plugin assembly package single assembly.xml . . . ---- === Example `assembly.xml` Here is a simple assmbly defintion to build a zip file with executable artifact included. ---- cdc-upgrade zip false ${project.build.directory}/package / *.exe ---- If you have any questions, please register a ticket! Enjoy! ================================================ FILE: src/main/resources/TODO ================================================ + Instead of distributing all the binary files together, distrubte them separately and pull down the right one as needed, based on a system property. Look at maven-dependency-plugin for code on grabbing dependencies--and unpacking them. + give version ranges for our dependencies so we play nice in people's projects. + By default, generate the element automatically from the dependencies. - What is up with downloading xstream every time? + Add a license file of my own. + Add license comment blocks to all files. + Use mvn site to generate a site for this plugin. - javadoc should include private fields. - put something like the README in the index.html file. + Use maven to generate a source distro for this plugin. - Use maven release to release new versions. - Add to : ... + Use ftp in to make updating my online repository easy. But don't put this in the POM with username & password, because that gets posted publicly! + getting NPE from ftp-wagon. (this was because I was missing a matching in ~/.m2/settings.xml) - add a snapshot repository, too. - Don't run launch4j unless the inputs are newer than the output? + Improve logic on whether to unjar: + After unjarring, write the marker file. + If the marker is there and newer than the jar, don't unjar. + But if the jar is newer, unjar anyway. + After unjarring, either write the marker file or touch it. - dontWrapJar doesn't work? from an email: However (sorry!) I can't get to work. I have tried every combination of "target/" or "./", including using backslashes (in case of a platform specific-issue) but each results in: "Specify runtime path of the jar relative to executable" I would expect the following config should have worked. I have confirmed that it works from the root of the project using the commandline launch4j. target/app.exe app-1.0.jar - support bundling the JRE (or figure out what parameters already allow this) . ================================================ FILE: src/main/resources/VERSIONINFO.md ================================================ # VersionInfo parameters ### Description. This file describes the `VersionInfo` parameters. * **Type**: `com.akathist.maven.plugins.launch4j.VersionInfo` Every parameter (including their parent `VersionInfo`) have a default value defined. To fulfill them by default values you need to make sure that **\** inside plugin configuration is set to `false`. ### Parameter Details #### **\** Version number in `x.x.x.x` format. * **Type**: `java.lang.String` * **Required**: `Yes` * **Default**: `${project.version}` converted into a `x.x.x.x` format. Conversion into a `x.x.x.x` format have specific constraints: * `x` as a number * shorter project versions like `x.x.x` will have appended zeros (to the 4th level) like `x.x.x.0` * every text flag like "-SNAPSHOT" or "-alpha" will be cut off * too many nested levels (>4) will be cut off as well. Example input: `1.2.3.4.5.6`, output: `1.2.3.4`. * * * #### **\** Free-form version number, like "1.20.RC1." * **Type**: `java.lang.String` * **Required**: `Yes` * **Default**: `${project.version}` * * * #### **\** File description shown to the user. * **Type**: `java.lang.String` * **Required**: `Yes` * **Default**: `${project.description}` * * * #### **\** Legal copyright. * **Type**: `java.lang.String` * **Required**: `Yes` * **Default**: `Copyright © ${project.inceptionYear}-${currentYear} ${project.organization.name}. All rights reserved.`. Where: * `${project.inceptionYear}` is not mandatory. * `${currentYear}` is generated programmatically. * `${project.organization.name}` is not mandatory. * * * #### **\** Version number in `x.x.x.x` format. * **Type**: `java.lang.String` * **Required**: `Yes` * **Default**: `${project.version}` converted into a `x.x.x.x` format. The same conversion such the one described regarding `fileVersion` parameter above. * * * #### **\** Free-form version number, like "1.20.RC1." * **Type**: `java.lang.String` * **Required**: `Yes` * **Default**: `${project.version}` * * * #### **\** The product name. * **Type**: `java.lang.String` * **Required**: `Yes` * **Default**: `${project.name}` * * * #### **\** The company name. * **Type**: `java.lang.String` * **Required**: `Yes` * **Default**: `${project.organization.name}` * * * #### **\** The internal name. For instance, you could use the filename without extension or the module name. * **Type**: `java.lang.String` * **Required**: `Yes` * **Default**: `${project.artifactId}` * * * #### **\** The original filename without path. Setting this lets you determine whether a user has renamed the file. * **Type**: `java.lang.String` * **Required**: `Yes` * **Default**: last path segment of the `${outfile}` configuration * * * #### **\** Language to be used during installation. * **Type**: `java.lang.String` * **Required**: `Yes` * **Default**: `ENGLISH_US` * * * #### **\** Trademarks of author. * **Type**: `java.lang.String` * **Required**: `Yes` * **Default**: `${project.organization.name}` * * * ================================================ FILE: src/site/site.xml ================================================

================================================ FILE: src/test/java/com/akathist/maven/plugins/launch4j/Launch4jMojoTest.java ================================================ /* * 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. */ package com.akathist.maven.plugins.launch4j; import org.apache.maven.plugin.testing.AbstractMojoTestCase; import java.io.File; public class Launch4jMojoTest extends AbstractMojoTestCase { public void testPrintOutFulfilledConfiguration() throws Exception { File testPom = new File(getBasedir(), "src/test/resources/unit/launch4j-config/launch4j-full-plugin-config.xml"); Launch4jMojo mojo = (Launch4jMojo) lookupMojo("launch4j", testPom); assertNotNull(mojo); assertEquals("Launch4jMojo{" + "headerType='gui', " + "infile=null, " + "outfile=${project.build.directory}" + File.separator + "app.exe, " + "jar='${project.build.directory}/${project.artifactId}-${project.version}.jar', " + "dontWrapJar=false, " + "errTitle='null', " + "downloadUrl='https://java.com/download', " + "supportUrl='null', " + "cmdLine='null', " + "chdir='null', " + "priority='null', " + "stayAlive=false, " + "restartOnCrash=false, " + "icon=null, " + "requireAdminRights=false, " + "objs=null, " + "libs=null, " + "vars=null, " + "jre=Jre{" + "path='%JAVA_HOME%;%PATH%', " + "requires64Bit=false, " + "minVersion='1.8', " + "maxVersion='null', " + "requiresJdk=true," + " initialHeapSize=0, " + "initialHeapPercent=0, " + "maxHeapSize=0, " + "maxHeapPercent=0, " + "opts=[-Dname=Lukasz]" + "}, " + "classPath=ClassPath{" + "mainClass='pl.org.lenart.launch4j.App', " + "addDependencies=true, " + "jarLocation='null', " + "preCp='anything', " + "postCp='null'" + "}, " + "singleInstance=null, " + "splash=null, " + "versionInfo=VersionInfo{" + "fileVersion='1.0.0.0', " + "txtFileVersion='${project.version}', " + "fileDescription='Launch4j Demo App', " + "copyright='Lukasz Lenart', " + "productVersion='1.0.0.0', " + "txtProductVersion='1.0.0.0', " + "productName='App', " + "companyName='Lukasz Lenart', " + "internalName='app', " + "originalFilename='app.exe', " + "language='ENGLISH_US', " + "trademarks='Luk ™'" + "}, " + "disableVersionInfoDefaults=true, " + "messages=Messages{" + "startupErr='null', " + "jreVersionErr='null', " + "launcherErr='null', " + "instanceAlreadyExistsMsg='null', " + "jreNotFoundErr='null'" + "}, " + "manifest=null, " + "saveConfig=false, " + "configOutfile=null, " + "parallelExecution=false, " + "skip=false" + "}", mojo.toString()); } } ================================================ FILE: src/test/java/com/akathist/maven/plugins/launch4j/VersionInfoTest.java ================================================ /* * 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. */ package com.akathist.maven.plugins.launch4j; import net.sf.launch4j.config.LanguageID; import org.apache.maven.model.Organization; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.io.File; import java.time.LocalDate; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) public class VersionInfoTest { // VersionInfo test params private String fileVersion = "1.0.0.0"; private String txtFileVersion = "1.0.0.0"; private String fileDescription = "Launch4j Test Application"; private String copyright = "Copyright Orphan OSS"; private String productVersion = "1.0.0.0"; private String txtProductVersion = "1.0.0.0"; private String productName = "Test App"; private String companyName = "Orphan OSS Company"; private String internalName = "app"; private String originalFilename = "app.exe"; private String language = LanguageID.ENGLISH_US.name(); private String trademarks = "Test ™"; // Mocks @Mock Organization organization; @Mock MavenProject project; @Mock File outfile; @Mock Log log; // Subject private VersionInfo versionInfo; @Before public void buildVersionInfoFromTestParams() { versionInfo = new VersionInfo(fileVersion, txtFileVersion, fileDescription, copyright, productVersion, txtProductVersion, productName, companyName, internalName, originalFilename, language, trademarks, log); } @Test public void shouldConvertIntoL4jFormatProperly() { // when net.sf.launch4j.config.VersionInfo l4jVersionInfo = versionInfo.toL4j(); // then assertEquals(versionInfo.fileVersion, l4jVersionInfo.getFileVersion()); assertEquals(versionInfo.txtFileVersion, l4jVersionInfo.getTxtFileVersion()); assertEquals(versionInfo.fileDescription, l4jVersionInfo.getFileDescription()); assertEquals(versionInfo.copyright, l4jVersionInfo.getCopyright()); assertEquals(versionInfo.productVersion, l4jVersionInfo.getProductVersion()); assertEquals(versionInfo.txtProductVersion, l4jVersionInfo.getTxtProductVersion()); assertEquals(versionInfo.productName, l4jVersionInfo.getProductName()); assertEquals(versionInfo.companyName, l4jVersionInfo.getCompanyName()); assertEquals(versionInfo.internalName, l4jVersionInfo.getInternalName()); assertEquals(versionInfo.originalFilename, l4jVersionInfo.getOriginalFilename()); assertEquals(versionInfo.trademarks, l4jVersionInfo.getTrademarks()); assertEquals(versionInfo.language, l4jVersionInfo.getLanguage().name()); } @Test public void shouldConvertIntoL4jFormat_For_All_Languages() { for (LanguageID languageId : LanguageID.values()) { // given versionInfo.language = languageId.name(); // when net.sf.launch4j.config.VersionInfo l4jVersionInfo = versionInfo.toL4j(); // then assertEquals(languageId, l4jVersionInfo.getLanguage()); } } @Test(expected = IllegalArgumentException.class) public void shouldThrowException_WhenTryingToFillOutDefaults_WithEmptyProject() { // expect throws versionInfo.tryFillOutByDefaults(null, outfile); } @Test(expected = IllegalArgumentException.class) public void shouldThrowException_WhenTryingToFillOutDefaults_WithEmptyOutfile() { // expect throws versionInfo.tryFillOutByDefaults(project, null); } @Test public void should_Not_FillOut_ByDefaultVersion_InL4jFormat_When_VersionInfoPropsWere_Filled() { // given String projectVersion = "4.3.2.1"; doReturn(projectVersion).when(project).getVersion(); // when versionInfo.tryFillOutByDefaults(project, outfile); // then assertNotEquals(projectVersion, versionInfo.fileVersion); assertEquals(fileVersion, versionInfo.fileVersion); assertNotEquals(projectVersion, versionInfo.productVersion); assertEquals(productVersion, versionInfo.productVersion); } @Test public void shouldFillOut_ByDefaultVersion_InL4jFormat_When_VersionInfoPropsWere_Empty() { // given String projectVersion = "1.2.3.4"; doReturn(projectVersion).when(project).getVersion(); versionInfo.fileVersion = null; versionInfo.productVersion = null; // when versionInfo.tryFillOutByDefaults(project, outfile); // then assertEquals(projectVersion, versionInfo.fileVersion); assertNotEquals(fileVersion, versionInfo.fileVersion); assertEquals(projectVersion, versionInfo.productVersion); assertNotEquals(productVersion, versionInfo.productVersion); } @Test public void should_Not_FillOut_Copyright_ByDefault_When_ItWas_Filled() { // given String projectInceptionYear = "2017"; doReturn(projectInceptionYear).when(project).getInceptionYear(); String organizationName = "Another OSS"; doReturn(organizationName).when(organization).getName(); doReturn(organization).when(project).getOrganization(); // when versionInfo.tryFillOutByDefaults(project, outfile); // then assertNotNull(versionInfo.copyright); assertEquals(copyright, versionInfo.copyright); assertFalse(versionInfo.copyright.contains(projectInceptionYear)); assertFalse(versionInfo.copyright.contains(organizationName)); } @Test public void shouldFillOut_Copyright_ByDefault_When_ItWas_Empty() { // given String projectInceptionYear = "2019"; doReturn(projectInceptionYear).when(project).getInceptionYear(); String organizationName = "Some OSS"; doReturn(organizationName).when(organization).getName(); doReturn(organization).when(project).getOrganization(); versionInfo.copyright = null; // when versionInfo.tryFillOutByDefaults(project, outfile); // then assertNotNull(versionInfo.copyright); assertNotEquals(copyright, versionInfo.copyright); assertTrue(versionInfo.copyright.contains(projectInceptionYear)); assertTrue(versionInfo.copyright.contains(organizationName)); } @Test public void should_Not_FillOutByDefaults_From_OrganizationName_When_VersionInfoPropsWere_Filled() { // given String organizationName = "Example OSS"; doReturn(organizationName).when(organization).getName(); doReturn(organization).when(project).getOrganization(); // when versionInfo.tryFillOutByDefaults(project, outfile); // then assertNotEquals(organizationName, versionInfo.companyName); assertEquals(companyName, versionInfo.companyName); assertNotEquals(organizationName, versionInfo.trademarks); assertEquals(trademarks, versionInfo.trademarks); } @Test public void shouldFillOutByDefaults_From_OrganizationName_When_OrganizationWas_Filled() { // given String organizationName = "Other OSS"; doReturn(organizationName).when(organization).getName(); doReturn(organization).when(project).getOrganization(); versionInfo.companyName = null; versionInfo.trademarks = null; // when versionInfo.tryFillOutByDefaults(project, outfile); // then assertEquals(organizationName, versionInfo.companyName); assertEquals(organizationName, versionInfo.trademarks); } @Test public void should_Not_FillOutByDefaults_SimpleValues_From_MavenProject_When_VersionInfoPropsWere_Filled() { // given String projectVersion = "1.21.1"; doReturn(projectVersion).when(project).getVersion(); String projectName = "launch4j-test-app"; doReturn(projectName).when(project).getName(); String projectArtifactId = "launch4j-test"; doReturn(projectArtifactId).when(project).getArtifactId(); String projectDescription = "Launch4j Test App"; doReturn(projectDescription).when(project).getDescription(); // when versionInfo.tryFillOutByDefaults(project, outfile); // then assertNotEquals(projectVersion, versionInfo.txtFileVersion); assertEquals(txtFileVersion, versionInfo.txtFileVersion); assertNotEquals(projectVersion, versionInfo.txtProductVersion); assertEquals(txtProductVersion, versionInfo.txtProductVersion); assertNotEquals(projectName, versionInfo.productName); assertEquals(productName, versionInfo.productName); assertNotEquals(projectArtifactId, versionInfo.internalName); assertEquals(internalName, versionInfo.internalName); assertNotEquals(projectDescription, versionInfo.fileDescription); assertEquals(fileDescription, versionInfo.fileDescription); } @Test public void shouldFillOutByDefaults_SimpleValues_From_MavenProject_When_VersionInfoPropsWere_Empty() { // given String projectVersion = "1.21.1"; doReturn(projectVersion).when(project).getVersion(); versionInfo.txtFileVersion = null; versionInfo.txtProductVersion = null; String projectName = "launch4j-test-app"; doReturn(projectName).when(project).getName(); versionInfo.productName = null; String projectArtifactId = "launch4j-test"; doReturn(projectArtifactId).when(project).getArtifactId(); versionInfo.internalName = null; String projectDescription = "Launch4j Test App"; doReturn(projectDescription).when(project).getDescription(); versionInfo.fileDescription = null; // when versionInfo.tryFillOutByDefaults(project, outfile); // then assertEquals(projectVersion, versionInfo.txtFileVersion); assertEquals(projectVersion, versionInfo.txtProductVersion); assertEquals(projectName, versionInfo.productName); assertEquals(projectArtifactId, versionInfo.internalName); assertEquals(projectDescription, versionInfo.fileDescription); } @Test public void should_Not_FillOut_ByDefault_LastSegmentOfOutfilePath_When_OriginalFilenameWas_Filled() { // given String outfileName = "testApp.exe"; doReturn(outfileName).when(outfile).getName(); // when versionInfo.tryFillOutByDefaults(project, outfile); // then assertNotEquals(outfileName, versionInfo.originalFilename); assertEquals(originalFilename, versionInfo.originalFilename); } @Test public void shouldFillOut_ByDefault_LastSegmentOfOutfilePath_When_OriginalFilenameWas_Empty() { // given String outfileName = "testApp.exe"; doReturn(outfileName).when(outfile).getName(); versionInfo.originalFilename = null; // when versionInfo.tryFillOutByDefaults(project, outfile); // then assertEquals(outfileName, versionInfo.originalFilename); } @Test public void shouldLogWarningsAboutDummyValues() { // given ArgumentCaptor logMessageCaptor = ArgumentCaptor.forClass(String.class); List missingParamNames = Arrays.asList( "project.version", "project.name", "project.artifactId", "project.description", "project.inceptionYear", "project.organization.name", "outfile" ); // when versionInfo.tryFillOutByDefaults(project, outfile); // then verify(log, times(missingParamNames.size())).warn(logMessageCaptor.capture()); List logMessages = logMessageCaptor.getAllValues(); missingParamNames.forEach(missingParamName -> { assertTrue(logMessages.stream().anyMatch(message -> message.contains(missingParamName))); }); } @Test public void shouldFillOut_ByDummyValues_When_OriginalValues_Empty_And_ProjectParams_Empty() { // given final String buildYear = String.valueOf(LocalDate.now().getYear()); VersionInfo emptyValuesVersionInfo = new VersionInfo(); emptyValuesVersionInfo.setLog(log); // when emptyValuesVersionInfo.tryFillOutByDefaults(project, outfile); // then assertEquals("1.0.0.0", emptyValuesVersionInfo.fileVersion); assertEquals("1.0.0", emptyValuesVersionInfo.txtFileVersion); assertEquals("A Java project.", emptyValuesVersionInfo.fileDescription); assertEquals("Copyright © 2020-" + buildYear + " Default organization. All rights reserved.", emptyValuesVersionInfo.copyright); assertEquals("1.0.0.0", emptyValuesVersionInfo.productVersion); assertEquals("1.0.0", emptyValuesVersionInfo.txtProductVersion); assertEquals("Java Project", emptyValuesVersionInfo.productName); assertEquals("Default organization", emptyValuesVersionInfo.companyName); assertEquals("java-project", emptyValuesVersionInfo.internalName); assertEquals("Default organization", emptyValuesVersionInfo.trademarks); assertEquals("app.exe", emptyValuesVersionInfo.originalFilename); } @Test public void shouldGenerateString_WithTestParams() { // when String result = versionInfo.toString(); // then assertNotNull(result); assertTrue(containsParam(result, "fileVersion", fileVersion)); assertTrue(containsParam(result, "txtFileVersion", txtFileVersion)); assertTrue(containsParam(result, "fileDescription", fileDescription)); assertTrue(containsParam(result, "copyright", copyright)); assertTrue(containsParam(result, "productVersion", productVersion)); assertTrue(containsParam(result, "txtProductVersion", txtProductVersion)); assertTrue(containsParam(result, "productName", productName)); assertTrue(containsParam(result, "companyName", companyName)); assertTrue(containsParam(result, "internalName", internalName)); assertTrue(containsParam(result, "originalFilename", originalFilename)); assertTrue(containsParam(result, "language", language)); assertTrue(containsParam(result, "trademarks", trademarks)); } private boolean containsParam(String result, String paramName, String paramValue) { return result.contains(paramName + "='" + paramValue + "'"); } } ================================================ FILE: src/test/java/com/akathist/maven/plugins/launch4j/generators/CopyrightGeneratorTest.java ================================================ package com.akathist.maven.plugins.launch4j.generators; import org.junit.Before; import org.junit.Test; import java.time.LocalDate; import static org.junit.Assert.*; public class CopyrightGeneratorTest { private static final String COPYRIGHT_PREFIX = "Copyright © "; private static final String COPYRIGHT_POSTFIX = ". All rights reserved."; private String buildYear; @Before public void initializeBuildYear() { buildYear = String.valueOf( LocalDate.now().getYear() ); } @Test public void shouldContain_BuildYear() { // when final String copyright = CopyrightGenerator.generate(null, null); // then String expected = concatAndWrapWithCopyright(buildYear); assertEquals(expected, copyright); } @Test public void shouldContain_InceptionYear_And_BuildYear() { // given final String projectInceptionYear = "2019"; // when final String copyright = CopyrightGenerator.generate(projectInceptionYear, null); // then String expected = concatAndWrapWithCopyright( projectInceptionYear, "-", buildYear ); assertEquals(expected, copyright); } @Test public void shouldContain_BuildYear_And_OrganizationName() { // given final String organizationName = "SoftwareMill"; // when final String copyright = CopyrightGenerator.generate(null, organizationName); // then String expected = concatAndWrapWithCopyright( buildYear, " ", organizationName ); assertEquals(expected, copyright); } @Test public void shouldContain_InceptionYear_And_BuildYear_And_OrganizationName() { // given final String projectInceptionYear = "2020"; final String organizationName = "Orphan OSS"; // when final String copyright = CopyrightGenerator.generate(projectInceptionYear, organizationName); // then String expected = concatAndWrapWithCopyright( projectInceptionYear, "-", buildYear, " ", organizationName ); assertEquals(expected, copyright); } private String concatAndWrapWithCopyright(String... elements) { StringBuilder builder = new StringBuilder(COPYRIGHT_PREFIX); for (String element : elements) { builder.append(element); } builder.append(COPYRIGHT_POSTFIX); return builder.toString(); } } ================================================ FILE: src/test/java/com/akathist/maven/plugins/launch4j/generators/Launch4jFileVersionGeneratorTest.java ================================================ package com.akathist.maven.plugins.launch4j.generators; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; @RunWith(JUnitParamsRunner.class) public class Launch4jFileVersionGeneratorTest { @Test public void shouldReturnNull_WhenProjectVersionIsNull() { // given String projectVersion = null; // expect assertNull(Launch4jFileVersionGenerator.generate(projectVersion)); } @Test(expected = IllegalArgumentException.class) @Parameters({ "", " ", "null", "alpha-1.2.3", "1a.2.3", "1.X.3", "1.2.3_11", "1.2.3;4", "1.2.3.4SNAPSHOT", "1.2.3.4.SNAPSHOT" }) public void shouldThrowException_WhenProjectVersion_HaveWrongFormat(String projectVersion) { // expect throws Launch4jFileVersionGenerator.generate(projectVersion); } @Test @Parameters({ "0, 0.0.0.0", "1, 1.0.0.0", "2, 2.0.0.0", "3.14, 3.14.0.0", "4.0.1, 4.0.1.0", "55.44.33, 55.44.33.0" }) public void shouldFillMissingPlacesByZeros(String projectVersion, String expected) { // when final String launch4jFileVersion = Launch4jFileVersionGenerator.generate(projectVersion); // then assertEquals(expected, launch4jFileVersion); } @Test @Parameters({ "1-SNAPSHOT, 1.0.0.0", "1.2.1-alpha, 1.2.1.0", "1.2.3.4-beta, 1.2.3.4", "0.0.1-snapshot, 0.0.1.0", "1.2.3.4-alpha+001, 1.2.3.4", "1.2.3-alpha+001, 1.2.3.0", "1.2.3.4-alpha+001, 1.2.3.4", "1.2.3+20130313144700, 1.2.3.0", "1.2.3.4+20130313144700, 1.2.3.4", "1.2.3-beta+exp.sha.5114f85, 1.2.3.0", "1.2.3.4-beta+exp.sha.5114f85, 1.2.3.4", }) public void shouldCutOffTextFlags(String projectVersion, String expected) { // when final String launch4jFileVersion = Launch4jFileVersionGenerator.generate(projectVersion); // then assertEquals(expected, launch4jFileVersion); } @Test @Parameters({ "0.0.0.0.1, 0.0.0.0", "1.22.333.4444.55555.666666, 1.22.333.4444", "9.8.7.6.5-SNAPSHOT, 9.8.7.6", "3.0.1.12.44.62.1.0.0.0.1-alpha, 3.0.1.12", }) public void shouldCutOffTooManyNestedDigits(String projectVersion, String expected) { // when final String launch4jFileVersion = Launch4jFileVersionGenerator.generate(projectVersion); // then assertEquals(expected, launch4jFileVersion); } @Test @Parameters({ "302.08, 302.8.0.0", "1.02.3, 1.2.3.0", "01.02.03.04, 1.2.3.4", "10.00.01, 10.0.1.0", "0.08.09, 0.8.9.0", "302.08-SNAPSHOT, 302.8.0.0", "1.02.03.04.05.06, 1.2.3.4", "000.001.002, 0.1.2.0" }) public void shouldStripLeadingZerosFromVersionComponents(String projectVersion, String expected) { // when final String launch4jFileVersion = Launch4jFileVersionGenerator.generate(projectVersion); // then assertEquals(expected, launch4jFileVersion); } @Test @Parameters({ "0, 0.0.0.0", "00, 0.0.0.0", "000, 0.0.0.0", "0.0, 0.0.0.0", "00.00, 0.0.0.0", "000.000, 0.0.0.0" }) public void shouldHandleZeroVersionsCorrectly(String projectVersion, String expected) { // when final String launch4jFileVersion = Launch4jFileVersionGenerator.generate(projectVersion); // then assertEquals(expected, launch4jFileVersion); } } ================================================ FILE: src/test/resources/unit/launch4j-config/launch4j-full-plugin-config.xml ================================================ 4.0.0 com.akathist.maven.plugins.launch4j.unit launch4j-default 1.0-SNAPSHOT jar launch4j-full com.akathist.maven.plugins.launch4j launch4j-maven-plugin gui ${project.build.directory}/${project.artifactId}-${project.version}.jar ${project.build.directory}/app.exe https://java.com/download pl.org.lenart.launch4j.App anything %JAVA_HOME%;%PATH% 1.8 true preferJre true true 32 -Dname=Lukasz true Test bundledJreErr 1.0.0.0 ${project.version} Launch4j Demo App Lukasz Lenart 1.0.0.0 1.0.0.0 App Lukasz Lenart app app.exe Luk ™