I am using jpackage to convert my libgdx game to an executable file. I am following this tutorial to do so. The jpackageImage task works perfectly fine but when the exe is created and I run it, it doesn't run but rather gives me an error: Child process exited with code 1 I am unaware what is causing this.
I am on windows 11 and im using JDK 18.0.1.1.
The JDK is set to JAVA_HOME which is set to the correct PATH.
I am using Badass-Runtime plugin as well which is defined in the first line of my build.gradle file.
Here is my build.gradle file for desktop:
plugins { id 'org.beryx.runtime' version '1.8.4' }
sourceCompatibility = 1.7
sourceSets.main.java.srcDirs = ["src/"]
sourceSets.main.resources.srcDirs = ["../core/assets"]
mainClassName = "com.mygdx.game.desktop.DesktopLauncher"
def osName = System.getProperty('os.name').toLowerCase(Locale.ROOT)
project.ext.assetsDir = new File("../core/assets")
task runGame(dependsOn: classes, type: JavaExec) {
main = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
standardInput = System.in
workingDir = project.assetsDir
ignoreExitValue = true
}
task debug(dependsOn: classes, type: JavaExec) {
main = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
standardInput = System.in
workingDir = project.assetsDir
ignoreExitValue = true
debug = true
}
task dist(type: Jar) {
manifest {
attributes 'Main-Class': project.mainClassName
}
dependsOn configurations.runtimeClasspath
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
with jar
destinationDirectory = file("$buildDir/lib")
}
jpackageImage.dependsOn dist
dist.dependsOn classes
eclipse.project.name = appName + "-desktop"
runtime {
options = ['--strip-debug',
'--compress', '2',
'--no-header-files',
'--no-man-pages',
'--strip-native-commands',
'--vm', 'server']
modules = ['java.base',
'java.desktop',
'jdk.unsupported']
distDir = file(buildDir)
jpackage {
jpackageHome = 'C:\\Users\\pc\\.jdks\\openjdk-18.0.1.1'
mainJar = dist.archiveFileName.get()
if (osName.contains('windows')) {
imageOptions = ["--icon", file("../icons/icon.ico")]
} else if (osName.contains('linux')) {
imageOptions = ["--icon", file("../icons/icon.png")]
} else if (osName.contains('mac')) {
imageOptions = ["--icon", file("../icons/icon.icns")]
}
}
}
Is it this bug? bugs.openjdk.org/browse/JDK-8284067 which triggers because your code exits with 1. Try doing with System.exit(0); , there is a workaround listed as well.
Related
Hi I got this zip task which works great:
def dir = new File("${projectDir.parentFile}/test/")
task testZip(type: Zip) {
from dir
destinationDirectory = dir
include 'toast/**'
archiveFileName = 'test.zip'
}
but then when I make the include property lazy (because I need to in my real case)
def dir = new File("${projectDir.parentFile}/test/")
task testZip(type: Zip) {
from dir
destinationDirectory = dir
include {
'toast/**'
}
archiveFileName = 'test.zip'
}
then it creates a zip that includes everything in the folder, (so the generated archive too). In this test case the inner zip is just corrupted (doesn't run infinitely) but in the real world case it does make an infinite zip. (Not sure why, maybe my best case has too few or small files). Either way the test case shows the problem, the generated zip contains a zip even though it should only contain the toast directory and all of its content.
How do I fix this? I need a lazy include because the directory I want to include is computed by other tasks. I get the exact same problem with Tar except it refuses to create the archive since it includes itself.
Using exclude '*.zip' is a dumb workaround which makes the archive include other folders I don't want. I only want to include a specific folder, lazyly.
Here's what the monster looks like in the real world case. I basically need to retrieve the version of the project from Java to then use that version to name the folders I'm packaging. (Making a libGDX game and packaging it with a jre using packr). The problematic tasks are 'makeArchive_' + platform.
String jumpaiVersion;
task fetchVersion(type: JavaExec) {
outputs.upToDateWhen { jumpaiVersion != null }
main = 'net.jumpai.Version'
classpath = sourceSets.main.runtimeClasspath
standardOutput new ByteArrayOutputStream()
doLast {
jumpaiVersion = standardOutput.toString().replaceAll("\\s+", "")
}
}
def names = [
'win64' : "Jumpai-%%VERSION%%-Windows-64Bit",
'win32' : "Jumpai-%%VERSION%%-Windows-32Bit",
'linux64' : "Jumpai-%%VERSION%%-Linux-64Bit",
'linux32' : "Jumpai-%%VERSION%%-Linux-32Bit",
'mac' : "Jumpai-%%VERSION%%-Mac.app"
]
def platforms = names.keySet() as String[]
def jdks = [
'win64' : 'https://cdn.azul.com/zulu/bin/zulu9.0.7.1-jdk9.0.7-win_x64.zip',
'win32' : 'https://cdn.azul.com/zulu/bin/zulu9.0.7.1-jdk9.0.7-win_i686.zip',
'linux64' : 'https://cdn.azul.com/zulu/bin/zulu9.0.7.1-jdk9.0.7-linux_x64.tar.gz',
'linux32' : 'https://cdn.azul.com/zulu/bin/zulu9.0.7.1-jdk9.0.7-linux_i686.tar.gz',
'mac' : 'https://cdn.azul.com/zulu/bin/zulu9.0.7.1-jdk9.0.7-macosx_x64.zip'
]
def formats = [
'win64' : 'ZIP',
'win32' : 'ZIP',
'linux64' : 'TAR_GZ',
'linux32' : 'TAR_GZ',
'mac' : 'ZIP'
]
File jdksDir = new File(project.buildscript.sourceFile.parentFile.parentFile, 'out/jdks')
File gameJar = new File("${projectDir.parentFile}/desktop/build/libs/Jumpai.jar")
File gameData = new File("${projectDir.parentFile}/desktop/build/libs/Jumpai.data")
File packrDir = new File("${projectDir.parentFile}/out/packr/")
File minimalTmpDir = new File("${projectDir.parentFile}/desktop/build/libs/minimal-tmp")
task minimizeGameJar {
dependsOn ':desktop:dist'
doFirst {
minimalTmpDir.mkdirs()
copy {
from zipTree(gameJar)
into minimalTmpDir
}
for(file in minimalTmpDir.listFiles())
if(file.getName().contains("humble"))
file.delete()
}
}
task makeMinimal(type: Zip) {
dependsOn minimizeGameJar
dependsOn fetchVersion
from minimalTmpDir
include '**'
archiveFileName = provider {
"Jumpai-${->jumpaiVersion}-Minimal.jar"
}
destinationDir packrDir
doLast {
minimalTmpDir.deleteDir()
}
}
task copyGameJar(type: Copy) {
outputs.upToDateWhen { gameData.exists() }
dependsOn ':desktop:dist'
from gameJar.getAbsolutePath()
into gameData.getParentFile()
rename("Jumpai.jar", "Jumpai.data")
}
task setWindowsIcons(type: Exec) {
dependsOn fetchVersion
workingDir '.'
commandLine 'cmd', '/c', 'set_windows_icons.bat', "${->jumpaiVersion}"
}
for(platform in platforms) {
task("getJdk_" + platform) {
String url = jdks[platform]
File jdkDir = new File(jdksDir, platform + "-jdk")
File jdkFile = new File(jdkDir, url.split("/").last())
outputs.upToDateWhen { jdkFile.exists() }
doFirst {
if(!jdkDir.exists())
jdkDir.mkdirs()
if(jdkFile.exists())
{
println jdkFile.getName() + " is already present"
return
}
else
{
println "Downloading " + jdkFile.getName()
new URL(url).withInputStream {
i -> jdkFile.withOutputStream { it << i }
}
}
for(file in jdkDir.listFiles()) {
if(file.equals(jdkFile))
continue
if(file.isFile()) {
if (!file.delete())
println "ERROR: could not delete " + file.getAbsoluteFile()
} else if(!file.deleteDir())
println "ERROR: could not delete content of " + file.getAbsoluteFile()
}
if(url.endsWith(".tar.gz"))// don't mix up archive type of what we downloaded vs archive type of what we compress (in formats)
{
copy {
from tarTree(resources.gzip(jdkFile))
into jdkDir
}
}
else if(url.endsWith(".zip"))
{
copy {
from zipTree(jdkFile)
into jdkDir
}
}
}
}
File packrInDir = new File(packrDir, platform)
String platformRawName = names[platform]
task("packr_" + platform, type: JavaExec) {
outputs.upToDateWhen { new File(packrDir, platformRawName.replace("%%VERSION%%", jumpaiVersion)).exists() }
dependsOn fetchVersion
dependsOn copyGameJar
dependsOn 'getJdk_' + platform
main = 'com.badlogicgames.packr.Packr'
classpath = sourceSets.main.runtimeClasspath
args 'tools/res/packr_config/' + platform + '.json'
workingDir = project.buildscript.sourceFile.parentFile.parentFile
doLast {
File packrOutDir = new File(packrDir, platformRawName.replace("%%VERSION%%", jumpaiVersion));
packrOutDir.deleteDir()
if(packrOutDir.exists())
{
println "ERROR Could not delete packr output " + packrOutDir.getAbsolutePath()
return
}
if(!packrInDir.renameTo(packrOutDir))
println "ERROR Could not rename packr output dir for " + packrInDir.getName()
}
}
if(formats[platform] == 'ZIP')
{
task('makeArchive_' + platform, type: Zip) {
if(platform.contains("win"))
dependsOn setWindowsIcons
dependsOn fetchVersion
dependsOn 'packr_' + platform
from packrDir
destinationDirectory = packrDir
include {
platformRawName.replace("%%VERSION%%", jumpaiVersion) + "/"
}
archiveFileName = provider {
platformRawName.replace("%%VERSION%%", jumpaiVersion) + ".zip"
}
}
}
else if(formats[platform] == 'TAR_GZ')
{
task('makeArchive_' + platform, type: Tar) {
dependsOn 'packr_' + platform
from packrDir
destinationDirectory = packrDir
include {
platformRawName.replace("%%VERSION%%", jumpaiVersion) + '/**'
}
archiveFileName = provider {
platformRawName.replace("%%VERSION%%", jumpaiVersion) + ".tar.gz"
}
extension 'tar'
compression = Compression.GZIP
}
}
else
println 'Unsupported format for ' + platform
}
task deploy {
dependsOn makeMinimal
for(platform in platforms)
dependsOn 'makeArchive_' + platform
}
How do I fix this? I need a lazy include because the directory I want to include is computed by other tasks. I get the exact same problem with Tar except it refuses to create the archive since it includes itself.
You can get what you want by using the doFirst method and modifiying the tasks properties with the passed action.
task('makeArchive_' + platform, type: Zip) {
if(platform.contains("win"))
dependsOn setWindowsIcons
dependsOn fetchVersion
dependsOn 'packr_' + platform
from packrDir
destinationDirectory = packrDir
archiveFileName = provider {
platformRawName.replace("%%VERSION%%", jumpaiVersion) + ".zip"
}
doFirst {
def includeDir = platformRawName.replace("%%VERSION%%", jumpaiVersion)
// Include only files and directories from 'includeDir'
include {
it.relativePath.segments[ 0 ].equalsIgnoreCase(includeDir)
}
}
}
Please have also a look at this answer to a similar question. My solution is just a workaround. If you know your version at configuration phase you can achieve what you want more easily. Writing your own custom tasks or plugins can also help to clean up your build script.
I want the task setupDB to execute if and only if the task fatJar or slimJar is run.
But after adding gradle.taskGraph.whenReady, commandLine './scripts/configureSQLiteDB.sh' is never running for any task.
Here is my code for the setupDB task:
//download bigg.sqlite if not present
task setupDB {
gradle.taskGraph.whenReady { graph ->
if (!project.file("resources/edu/ucsd/sbrg/bigg/bigg.sqlite").exists()
&& (graph.hasTask(slimJar)|| graph.hasTask(fatJar))) {
doFirst {
exec {
println "Setup DB"
commandLine './scripts/configureSQLiteDB.sh'
}
}
}
}
}
You can also view the build.gradle file:
apply plugin: "java"
defaultTasks "clean", "fatJar"
// Java versions for compilation and output
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
archivesBaseName = "ModelPolisher"
version = "1.7"
sourceSets {
main.java.srcDirs = ["src"]
main.resources.srcDirs = ["resources"]
main.resources.excludes = ["**/bigg.zip"]
test.java.srcDirs = ["test"]
}
repositories {
mavenCentral()
maven { url "http://www.ebi.ac.uk/~maven/m2repo" }
maven { url "http://jsbml.sourceforge.net/m2repo/" }
// local dependencies
flatDir {
dirs "lib/de/zbit/SysBio/1390"
}
}
dependencies {
compile "org.sbml.jsbml:jsbml:1.4"
compile "de.zbit:SysBio:1390"
compile "org.xerial:sqlite-jdbc:3.21.0"
compile "org.postgresql:postgresql:42.2.2"
compile "org.biojava:biojava-ontology:5.0.0"
compile "com.diffplug.matsim:matfilerw:3.0.1"
compile "com.fasterxml.jackson.core:jackson-core:2.9.9"
compile "com.fasterxml.jackson.core:jackson-databind:2.9.9"
testCompile "org.junit.jupiter:junit-jupiter-engine:5.1.0"
}
// config for all jar tasks
tasks.withType(Jar) {
dependsOn test
destinationDir = file("$rootDir/target")
manifest {
attributes(
"Version": version,
"Implementation-Title": "ModelPolisher",
"Implementation-Version": version,
"Specification-Vendor": "University of California, San Diego",
"Specification-Title": "ModelPolisher",
"Implementation-Vendor-Id": "edu.ucsd.sbrg",
"Implementation-Vendor": "University of California, San Diego",
"Main-Class": "edu.ucsd.sbrg.bigg.ModelPolisher"
)
}
}
// with dependencies
task fatJar(type: Jar) {
baseName = project.name + "-fat"
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
}
with jar
}
//with dependencies, without bigg.sqlite
task lightJar(type: Jar) {
exclude("**/bigg.sqlite")
baseName = project.name + "-noDB"
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
}
with jar
}
// without dependencies and bigg.sqlite
task bareJar(type: Jar) {
exclude("**/bigg.sqlite")
baseName = project.name + "-slim-noDB"
with jar
}
// without dependencies, bigg.sqlite included
// not included in release
task slimJar(type: Jar) {
baseName = project.name + "-slim"
with jar
}
// zip lib folder for release
task zipLibs(type: Zip) {
from "lib"
into "lib"
include "**/**"
archiveName = "lib.zip"
destinationDir = file("target/")
}
// zip script files for release
task zipScripts(type: Zip) {
from "scripts"
into "scripts"
include "**/**"
archiveName = "scripts.zip"
destinationDir = file("target/")
}
// create all three jars for release
task release() {
dependsOn fatJar
dependsOn bareJar
dependsOn lightJar
dependsOn tasks["zipLibs"]
dependsOn tasks["zipScripts"]
// necessary, as order is not defined by dependsOn
bareJar.mustRunAfter classes
// slimJar.mustRunAfter bareJar
lightJar.mustRunAfter slimJar
fatJar.mustRunAfter lightJar
}
// clean up target directory
clean.doFirst {
file(".gradle").deleteDir()
file("target").deleteDir()
}
//download bigg.sqlite if not present
task setupDB {
gradle.taskGraph.whenReady { graph ->
if (!project.file("resources/edu/ucsd/sbrg/bigg/bigg.sqlite").exists()
&& (graph.hasTask(slimJar)|| graph.hasTask(fatJar))) {
doFirst {
exec {
println "Setup DB"
commandLine './scripts/configureSQLiteDB.sh'
}
}
}
}
}
// bump jar version in travis.yml
if (project.file(".travis.yml").exists()) {
task bumpVersionTravis() {
replaceVersion(".travis.yml")
}
processResources.dependsOn bumpVersionTravis
}
// bump jar version in ModelPolisher.sh
if (project.file("./scripts/ModelPolisher.sh").exists()) {
task bumpVersionMP() {
replaceVersion("./scripts/ModelPolisher.sh")
}
processResources.dependsOn bumpVersionMP
}
def replaceVersion(path) {
ArrayList<String> content = new ArrayList<>()
File travisFile = new File(path)
String MPVersion = /ModelPolisher.*\d{1,2}(.\d{1,2}){1,2}.jar/
travisFile.eachLine {
line ->
content.add(line.replaceAll(MPVersion, "ModelPolisher-fat-" +
"${version}.jar"))
}
BufferedWriter writer = new BufferedWriter(new FileWriter(travisFile))
content.each {
line -> writer.writeLine(line)
}
writer.close()
}
You seem to have the wrong idea about gradle configuration. You shouldn't be changing task behavior based on inputs. You should be configuring dependencies between tasks and also configuring task inputs/outputs to control the "up-to-date" behaviour.
Eg:
task slimJar(type:Jar) {
dependsOn 'setupDB'
...
}
task fatJar(type:Jar) {
dependsOn 'setupDB'
...
}
task setupDB {
outputs.upToDateWhen { file("resources/edu/ucsd/sbrg/bigg/bigg.sqlite").exists() }
doFirst {
println "Setup DB"
exec {
commandLine './scripts/configureSQLiteDB.sh'
}
}
}
The following is also bad practice
if (project.file(".travis.yml").exists()) {
task bumpVersionTravis() {
replaceVersion(".travis.yml")
}
processResources.dependsOn bumpVersionTravis
}
The available tasks should NOT change based on files in your file system. They should always be there, regardless of your file system. You should instead set the "enabled" flag (or use task outputs) to control if the task executes or is skipped
Eg:
task bumpVersionTravis {
enabled = project.file(".travis.yml").exists()
doLast {
replaceVersion(".travis.yml")
}
}
processResources.dependsOn bumpVersionTravis
I am copying the structure of the example Xtext Web project for multiple dsl's using the Entities and StateMachine example. I am using Gradle as my build system. I have a class MyGeneratorModule in both of my grammar projects. In my workflow I reference it like this:
configuration = MyGeneratorModule {...}
I can run the workflow fine in each project, but when I try to perform a jettyRun from the web project I get this error:
Task :com.selinc.logic.program:generateXtextLanguage FAILED
0 [main] ERROR mf.mwe2.launch.runtime.Mwe2Launcher - [XtextLinkingDiagnostic: null:17 Couldn't resolve reference to JvmType 'MyGeneratorModule'.
Am i missing something in the workflow or gradle build? Here is a more complete example of my languages build.gradle file and workflow:
mwe2:
component = XtextGenerator {
configuration = MyGeneratorModule { // <- This is what is not resolving
project = StandardProjectConfig {
baseName = baseName
rootPath = rootPath
runtimeTest = {
enabled = true
}
web = {
enabled = true
root = "../myWebProject"
src = "../myWebProject/src/main/java"
srcGen = "../myWebProject/src/main/xtext-gen"
assets = "../myWebProject/src/main/webapp"
}
mavenLayout = true
}
code = {
encoding = "UTF-8"
lineDelimiter = "\r\n"
fileHeader = "/*\n * generated by Xtext \${version}\n */"
}
}
cleaner = {
exclude = "MyOtherLanguageWebModule.java"
}
language = StandardLanguage {
name = "MyLang"
fileExtensions = "lang"
serializer = {
generateStub = false
}
webSupport = {
generateHtmlExample = true
framework = "CODEMIRROR"
generateJsHighlighting = false
generateServlet = false
generateWebXml=true
}
junitSupport = {
junitVersion = "5"
}
}
}
build.gradle:
dependencies {
testCompile "org.junit.jupiter:junit-jupiter-api:5.1.0"
testRuntime "org.junit.jupiter:junit-jupiter-engine:5.1.0"
testCompile "org.eclipse.xtext:org.eclipse.xtext.testing:${xtextVersion}"
compile project(':myOtherLang')
compile project(':myXCoreModel')
compile project(":util")
compile group: 'org.eclipse.xtext', name: 'org.eclipse.xtext.ecore', version: '2.15.0'
compile "org.eclipse.xtext:org.eclipse.xtext.xbase:${xtextVersion}"
}
sourceSets {
mwe2 {}
}
configurations {
mwe2 {
extendsFrom compile
}
mwe2Compile.extendsFrom mainCompile
mwe2Runtime.extendsFrom mainRuntime
}
sourceSets.mwe2.java.srcDir 'generator'
dependencies {
mwe2Compile "org.eclipse.emf:org.eclipse.emf.mwe2.launch:2.9.1.201705291010"
mwe2Compile "org.eclipse.xtext:org.eclipse.xtext.common.types:${xtextVersion}"
mwe2Compile "org.eclipse.xtext:org.eclipse.xtext.xtext.generator:${xtextVersion}"
mwe2Compile "org.eclipse.xtext:xtext-antlr-generator:[2.1.1, 3)"
//added for xcore support
mwe2Compile 'org.eclipse.emf:org.eclipse.emf.ecore.xcore:1.3.1'
mwe2Compile 'org.eclipse.emf:org.eclipse.emf.codegen.ecore.xtext:+'
}
task generateXtextLanguage(type: JavaExec) {
main = 'org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher'
classpath = project.sourceSets.mwe2.runtimeClasspath
inputs.file "path/GenerateMyLang.mwe2"
inputs.file "path/MyLang.xtext"
outputs.dir "src-gen"
args += "path/GenerateMyLang.mwe2"
args += "-p"
args += "rootPath=/${projectDir}/.."
}
test {
useJUnitPlatform()
}
generateXtext.dependsOn(generateXtextLanguage)
clean.dependsOn(cleanGenerateXtextLanguage)
eclipse.classpath.plusConfigurations += [configurations.mwe2]
i have doubts if this will work. the code you copy from does not generate an xtext language
you should move custom modules to a separate gradle project and thus compile it separately. alernatively you can experiment with gradle buildSrc/separate source folder code
(am not sure if this works for this usecase)
dependencies {
compile "org.eclipse.xtext:org.eclipse.xtext:${xtextVersion}"
compile "org.eclipse.xtext:org.eclipse.xtext.xbase:${xtextVersion}"
}
sourceSets {
mwe2 {}
}
configurations {
mwe2 {
extendsFrom compile
}
mwe2Compile.extendsFrom mainCompile
mwe2Runtime.extendsFrom mainRuntime
}
sourceSets.mwe2.java.srcDir 'generator'
dependencies {
mwe2Compile "org.eclipse.emf:org.eclipse.emf.mwe2.launch:2.9.1.201705291010"
mwe2Compile "org.eclipse.xtext:org.eclipse.xtext.common.types:${xtextVersion}"
mwe2Compile "org.eclipse.xtext:org.eclipse.xtext.xtext.generator:${xtextVersion}"
mwe2Compile "org.eclipse.xtext:xtext-antlr-generator:[2.1.1, 3)"
}
task generateXtextLanguage(type: JavaExec) {
main = 'org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher'
classpath = project.sourceSets.mwe2.runtimeClasspath
inputs.file "src/org/xtext/example/mydsl/GenerateMyDsl.mwe2"
inputs.file "src/org/xtext/example/mydsl/MyDsl.xtext"
outputs.dir "src-gen"
args += "src/org/xtext/example/mydsl/GenerateMyDsl.mwe2"
args += "-p"
args += "rootPath=/${projectDir}/.."
}
generateXtext.dependsOn(generateXtextLanguage)
clean.dependsOn(cleanGenerateXtextLanguage)
eclipse.classpath.plusConfigurations += [configurations.mwe2]
Is it possible (if so, how I can do it?) using Gradle to compile Kotlin JS sources and then put them in Kotlin JVM project as jar resources?
I've used this build.gradle script once to build a jar with those compiled resources:
import com.eriwen.gradle.js.tasks.MinifyJsTask
plugins {
id "com.eriwen.gradle.js" version "2.12.0"
}
def outDir = new File(buildDir, 'out')
def out = new File(outDir, 'name.js')
def min = new File(outDir, 'name.min.js')
compileKotlin2Js {
kotlinOptions {
outputFile = out
metaInfo = false
noStdlib = true
sourceMap = true
}
}
task minifyKotlinJs(type : MinifyJsTask) {
source = out
dest = min
}
jar {
from (outDir) {
into("your/package/name")
include '*.js', '*.map'
}
include 'META-INF', 'your'
}
minifyKotlinJs.dependsOn classes
jar.dependsOn minifyKotlinJs
I have gradle code below and I don't know how to avoid huge output generated by JavaExec task. I haven't found any option of JavaExec for it. If anyone knows better way of ignoring it, please share it.
def getStubOutput() {
return new FileOutputStream(new File("${buildDir}/temp"))
}
configure(project(':jradius:dictionary-min')) {
evaluationDependsOn(':jradius')
sourceSets {
main {
java {
srcDir "${projectDir}/target/dictionary-src"
}
}
}
dependencies {
compile project(':jradius:core')
}
task genSources(type: JavaExec) {
main = 'net.jradius.freeradius.RadiusDictionary'
classpath configurations.all
args = ["net.jradius.dictionary", "${projectDir}/../freeradius/dict-min", "${projectDir}/target/dictionary-src"]
maxHeapSize = "800m"
standardOutput = getStubOutput()
}
jar {
archiveName = "jradius-dictionary-min-1.1.5-SNAPSHOT.jar"
}
genSources.dependsOn ':jradius:cloneJradius'
compileJava.dependsOn genSources
}
I simply use a dummy OutputStream that does nothing in its write method:
def dummyOutputStream = new OutputStream() {
#Override
public void write(int b) {}
}
exec {
executable = name
standardOutput = dummyOutputStream
errorOutput = dummyOutputStream
ignoreExitValue = true
}
A great solution I came across is to modify the logging level of the task. If you set it to INFO, then it will squelch all the output of that task, unless gradle is run with --info.
Alternatively, you can set the level to LogLevel.QUIET, which will completely silence it.
task chatty(type: Exec) {
....
logging.captureStandardOutput LogLevel.INFO
}
As in the comment I thought that standardOutput can be set to null but the following piece of code (taken from: org.gradle.process.internal.AbstractExecHandleBuilder) shows that's not possible:
public AbstractExecHandleBuilder setStandardOutput(OutputStream outputStream) {
if (outputStream == null) {
throw new IllegalArgumentException("outputStream == null!");
}
this.standardOutput = outputStream;
return this;
}
What You can do is to redirect the output to temporary file (file will be deleted!) with this oneliner:
task genSources(type: JavaExec) {
main = 'net.jradius.freeradius.RadiusDictionary'
classpath configurations.all
args = ["net.jradius.dictionary", "${projectDir}/../freeradius/dict-min", "${projectDir}/target/dictionary-src"]
maxHeapSize = "800m"
standardOutput = { def f = File.createTempFile('aaa', 'bbb' ); f.deleteOnExit(); f.newOutputStream() }()
}
or if You'd like to save this output for further reading:
task genSources(type: JavaExec) {
main = 'net.jradius.freeradius.RadiusDictionary'
classpath configurations.all
args = ["net.jradius.dictionary", "${projectDir}/../freeradius/dict-min", "${projectDir}/target/dictionary-src"]
maxHeapSize = "800m"
standardOutput = new File(project.buildDir, 'radius.log').newOutputStream()
}
The last option is to add apache commons-io to script dependencies and set standardOutput to NullOutputStream. In can be done as follows:
import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'commons-io:commons-io:2.4'
}
}
task genSources(type: JavaExec) {
main = 'net.jradius.freeradius.RadiusDictionary'
classpath configurations.all
args = ["net.jradius.dictionary", "${projectDir}/../freeradius/dict-min", "${projectDir}/target/dictionary-src"]
maxHeapSize = "800m"
standardOutput = NULL_OUTPUT_STREAM
}
That's all that comes to my head.
This disables the standard output from a javaExec task:
task myCustomTask(type: javaExec) {
standardOutput = new ByteArrayOutputStream()
classpath = ...
main = ...
args ....
}