Can I exclude build output when running a Gradle project from IntelliJ? - java

I have a Gradle project being run from the latest version of IntelliJ IDEA (2021.1.1 Ultimate Edition). The project has a Java class with a main method that outputs its results to the console.
When I run this main method from IntelliJ IDEA, outputs the results of the program in the "Run" tab. However, it also outputs the Gradle build output as well. This is not desirable to me, since it makes the program output harder to visually distinguish, plus I have to carefully select just the program output, and can't just copy/paste the full output (click, ⌘A, ⌘C, click, ⌘V).
build.gradle
plugins {
id 'java'
}
Main.java
package com.example;
public class Main {
public static void main(String[] args) {
System.out.println("Program output line 1");
System.out.println("Program output line 2");
System.out.println("Program output line 3");
}
}
output
1:20:08 PM: Executing task 'Main.main()'...
> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes
> Task :Main.main()
Program output line 1
Program output line 2
Program output line 3
BUILD SUCCESSFUL in 508ms
2 actionable tasks: 2 executed
1:20:09 PM: Task execution finished 'Main.main()'.
Aside
Similar behavior occurs if I switch the project settings to build and run using IntelliJ IDEA rather than Gradle, in that it outputs the Java command and a "process finished" message. Even if I wanted to switch to running in this manner (which I don't for this project), I still run into a variant of this issue.
/Library/Java/JavaVirtualMachines/jdk-11.0.4.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=61588:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Users/Example/GradleMainOutput/out/production/classes com.example.Main
Program output line 1
Program output line 2
Program output line 3
Process finished with exit code 0
That all being said, is there a way to output only the program output in an IntelliJ IDEA Gradle project, and not the build output?

There is no way to hide Gradle build output when running in this mode.
The only way is to disable Gradle run delegation so that app is started directly by IntelliJ IDEA.
Hiding the command line and the exit code is also not possible.
You can only fold it.

Old question, but for anybody still interested to just get the output of the script, you can use the --quiet flag (https://docs.gradle.org/current/userguide/logging.html)
So having this in the build.gradle :
task(run, dependsOn: 'classes', type: JavaExec) {
main = 'com.multimodule.module.MainClass'
classpath = sourceSets.main.runtimeClasspath
}
and execturing the task:
./gradlew multimodule:module:run --quiet
you'll get just the output (.e.g any System.out.println you added on the main)

The --quiet flag helps, but it is not enough. For me the following flags combination works:
gradle --console-plain --quiet ...

Related

Gradle excecution freezes for 3 mins for certain tasks

I have 2 relatively simple Gradle 6.1.1 configs, one is using https://plugins.gradle.org/plugin/com.github.node-gradle.node to build a react app, and the other one is based on https://plugins.gradle.org/plugin/com.bmuschko.tomcat and runs a simple wicket app in embedded tomcat.
The 1st config for npm task is:
apply plugin: 'com.github.node-gradle.node'
node {
version = '12.16.0'
download = true
workDir = file "$project.buildDir/nodejs"
}
task "npmBuild"( type:NpmTask ) {
args = [ 'run', 'build' ]
}
and produces the following output in Windows 10:
>gradlew.bat npmBuild
Starting a Gradle Daemon (subsequent builds will be faster)
> Task :npmBuild
> layer-selection#0.1.0 build .....
> react-scripts build
Creating an optimized production build...
Compiled with warnings.
...
Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
File sizes after gzip:
90.99 KB build\static\js\2.17f9cda1.chunk.js
28.68 KB build\static\css\2.2f7f14af.chunk.css
3.43 KB build\static\js\main.1150707e.chunk.js
778 B build\static\js\runtime-main.989054bd.js
177 B build\static\css\main.f7c0afb8.chunk.css
...
Find out more about deployment here:
bit.ly/CRA-deploy
at this point the tasks lasted approx. 20 seconds, then it hangs for 3 min with CPU-load below 1% and continues:
BUILD SUCCESSFUL in 3m 18s
2 actionable tasks: 1 executed, 1 up-to-date
The strange thing is that running the same config on similar project on another Win10 machine results in clean run w/o freezes.
Also the tasks:
task "npm-install"( type:NpmTask ) {
args = [ 'install' ]
}
task "npm-set-proxy"( type:NpmTask ) {
args = [ 'config', 'set', 'https-proxy', 'http://www.www.www:80/' ]
}
show the same 3-extra-minutes behavior.
The 2nd config looks like:
apply plugin: 'com.bmuschko.tomcat'
ext.tomcatVersion = '9.0.30'
dependencies {
// some deps
tomcat "org.apache.tomcat.embed:tomcat-embed-core:$tomcatVersion",
"org.apache.tomcat.embed:tomcat-embed-logging-juli:9.0.0.M6",
"org.apache.tomcat.embed:tomcat-embed-jasper:$tomcatVersion",
"org.apache.tomcat:tomcat-jdbc:$tomcatVersion",
"org.apache.tomcat:tomcat-dbcp:$tomcatVersion"
'org.postgresql:postgresql:42.2.12'
'log4j:log4j:1.2.17'
}
tomcat {
httpProtocol = 'org.apache.coyote.http11.Http11Nio2Protocol'
ajpProtocol = 'org.apache.coyote.ajp.AjpNio2Protocol'
httpPort = 8088
}
and produces the output in Win10:
>gradlew.bat tomcatRun
> Configure project :
> Task :compileJava
> Task :processResources UP-TO-DATE
> Task :classes
> Task :tomcatRun
at this point it hangs for again for around 3 mins with CPU-load below 18% and then continues:
LOG .......
LOG 2020-04-24 12:45:10,971 [Execution worker for ':'] INFO : - ActiveMq URL tcp://localhost:61620
Started Tomcat Server
The Server is running at http://localhost:8088/racy10
<=========----> 75% EXECUTING [4m 2s]
So for no reason (from my POV) the gradle excecution hangs for 3 mins either after or before certain tasks.
Any hints and ideas are welcome!
TIA
Check the permissions of %userprofile%\.gradle directory, which is a common culprit. On Windows 10 this might be affected by Windows Defender, but this should only slow down a little. Testing how it behaves when running it from directly the command-line suggested, because this would help to narrow the down root cause. Instead using an Exec task might also be an option, which would provide full control over the CLI; for example.

Got error: > Process 'command '/Library/Java/JavaVirtualMachines/jdk1.8.0_77.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1

Execution failed for task ':Main.main()'.
Process 'command '/Library/Java/JavaVirtualMachines/jdk1.8.0_77.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1
This is a java project with Gradle. Not sure what this error means.
This is a very generic error which I've faced as well with my Java Gradle Spring-Boot project. The reason being it so difficult to debug is that it doesn't give out any useful clue as to where the error occurred even if you provide the --stacktrace or --debug arguments to your gradle bootRun command.
However this can be easily determined if you wrap your Spring-Boot bootstrapper code in a try-catch and print the exception stacktrace as below:
#SpringBootApplication
public class MyApplicationServer {
public static void main(String[] args) {
try {
SpringApplication.run(MyApplicationServer.class, args);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In my case, the exception was due to an unquoted special character (*) in application.yml which lead to a parsing failure. Excerpt of stacktrace below:
java.lang.IllegalStateException: Failed to load property source from location 'classpath:/application-local.yml'
at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:535)
...(truncated logs)
at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:358)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:317)
at com.ekart.citylogistics.payout.MyApplicationServer.main(MyApplicationServer.java:24) Caused by: while scanning an alias in 'reader', line 5, column 44:
... endpoints.web.exposure.include: *
^ expected alphabetic or numeric character, but found (10) in 'reader', line 5, column 45:
... ndpoints.web.exposure.include: *
^
at org.yaml.snakeyaml.scanner.ScannerImpl.scanAnchor(ScannerImpl.java:1447)
at org.yaml.snakeyaml.scanner.ScannerImpl.fetchAlias(ScannerImpl.java:918)
at org.yaml.snakeyaml.scanner.ScannerImpl.fetchMoreTokens(ScannerImpl.java:366)
...(truncated logs)
This error is actually very general. I saw this error in my Scala project too. You need to click on the parent error with the line main(), which would show you the actual error. In my case, it is because I didn't download a specific file and there is a null pointer issue. Hope this helps!
For those who use IntelliJ IDE, if the solutions above don't work for your project, I have another solution:
Prefereces->Build, Exectution, Deployment->Build Tools->Gradle->Build and run
change "build and run using" and "run testing using" from Gradle to IntelliJ IDEA, then reload all Gradle projects
build and run
reload Gradle projects
This error goes away after updating IDE Compiler version rightly when you have multiple JDK installed on your machine (In my Mac, had JDK8 and JDK11). You may need to restart IDE once you make changes if needed. As in my case IntelliJ IDE, It works after doing invalidate cache and restart IDE.
Try clicking on the parent error with the line Main.main(). This should show you the actual error that occurred. For me, this was occurring because I hadn't set up a database connection in the application.properties file. Hope this helps.
This error maybe due to the port already being in use. Try again after closing other running instances of the application.
Hope this works!

I get a failure every time I try and execute this

When I use Scanners or try to get a user input, I get the message:
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':run'.
Process 'command 'C:\Program Files\Java\jdk-13.0.1\bin\java.exe'' finished with non-zero exit value 1
Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
Get more help at https://help.gradle.org
BUILD FAILED in 0s
2 actionable tasks: 1 executed, 1 up-to-date
When I just use a system.out.println();
It goes through successfully.
Here is my code:
/**
*
* #author boaz5
*/
import java.io.IOException;
import java.util.Scanner;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
System.out.println("What is your name?");
Scanner name = new Scanner(System.in);
String nameString = name.next();
System.out.println("Hi," + nameString);
}
}
I'm not sure what I'm doing wrong. I am a complete newbie and this is one of my first Java projects. Thanks!
Not much to go on here, but I can give a couple suggestions to get started:
1.) Update your Gradle plug-in. The compilation issue may not be code related, but instead a problem with the tooling.
2.) If above fails replace the IOException with Exception and see if we get any further output.
Let us know
you should review your environment, I did copy your code and work for me.
12:26:02 AM: Executing task 'Test.main()'...
Task :compileJava
Task :processResources NO-SOURCE
Task :classes
Task :Test.main()
What is your name?
Alvaro
Hi,Alvaro
Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See
There is no problem in your code. The code is running without any error.
I think you added the processor as a compile dependency. You should add it as 'provided'.

Gradle task failing on GitLab CI main method not found

I'm in the process of setting up a new GitLab CI pipeline for a project.
As a start, my goal is to create a basic pipeline that builds, tests and analyzes the project (3 simple stages).
My problem is that, that my second stage (test) depends on a Gradle task that generates a bit of documentation (we generated on the fly documentation based on tests). Said task invokes the main of a utility to generate a simple piece of documentation.
While all tasks work fine when I run them under a Windows host, doing the same on GitLab's CI using an Alpine Linux based image fails with the following error:
> Task :compileTestJava
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
> Task :processTestResources NO-SOURCE
> Task :testClasses
> Task :test
> Task :generatePermissionsDocument FAILED
Error: Could not find or load main class
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':generatePermissionsDocument'.
> Process 'command '/opt/java/openjdk/bin/java'' finished with non-zero exit value 1
I have tried enabling Gradle stacktraces but I did not manage to get any good information out of them. For the most part both my build script and the GitLab CI script look OK (included below for reference):
image: adoptopenjdk/openjdk8:jdk8u222-b10-alpine
include:
- project: "devops/ci-templates"
ref: "master"
file: "sonar/sonar-gradle.yml"
variables:
GRADLE_OPTS: "-Dorg.gradle.daemon=false"
before_script:
- export GRADLE_USER_HOME=`pwd`/.gradle
- apk add --no-cache tzdata
- cp /usr/share/zoneinfo/America/New_York /etc/localtime
- echo "America/New_York" > /etc/timezone
stages:
- build
- test
- analysis
build:
stage: build
script: ./gradlew --build-cache clean assemble -PMARKETING_SKIP_INT_TESTS
cache:
key: "$CI_COMMIT_REF_NAME"
paths:
- build
- .gradle
- src/main/java/fts/marketing/util/Version.java
retry: 2
only:
- merge_requests
- master
- /^support\/\d+[.]\d+$/
- tags
except:
- api
test:
stage: test
script: ./gradlew test -PMARKETING_SKIP_INT_TESTS --stacktrace
cache:
key: "$CI_COMMIT_REF_NAME"
policy: pull
paths:
- build
- .gradle
- src/main/java/fts/marketing/util/Version.java
only:
- merge_requests
- master
- /^support\/\d+[.]\d+$/
- tags
except:
- api
Initially I though that the this would be a caching or permission related problem, but I checked both the integrity or the cache produced by the build task as well as the permissions of the generated folder and everything looks fine.
For reference the task I'm trying to invoke is this one:
task generatePermissionsDocument(type: JavaExec, group: 'application') {
description = 'Will generate API Permissions adoc'
main = 'fts.marketing.tools.GeneratePermissionsDocument'
classpath = sourceSets.main.runtimeClasspath
//jvmArgs = applicationDefaultJvmArgs
workingDir = generatedDocumentation
}
Can anyone shed some light as to why this is failing and what must be done to resolve it?
I managed to find out the root cases of this. I was doing some conditional setting of the application's default JVM args which apparently was wrong. Said process was including a trailing ',' in the args passed in by Gradle to the JVM.
For some reason this was not well liked when running from a Unix like environment, whereas it was working fine on Windows hosts. I re-worked the conditional part of the arg setting and everything worked like a charm.

how to pass dynamic input pararm to gradle java exec task?

I have this Gradle task:
task resources_cleaner_bl(type: JavaExec) {
classpath sourceSets.main.runtimeClasspath
systemProperties['cleanTarget'] = 'bl'
main = "com.m.ResourcesCleanerRunner"
}
How can I edit this such that 'bl' will be entered dynamically when I run this gradle task.
You can simply eliminate the configuration systemProperties['cleanTarget'] = 'bl' by setting the system property from the command line using the -D flag, i.e. running gradlew resources_cleaner_bl -DcleanTarget=bl.
You can read more about project and system properties in Gradle user guide here.

Categories