I created a simple gradle project which includes the application plugin. I ran the distZip task to create a zip of all the jars. Below is the code I used:
build.gradle
apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'eclipse'
sourceCompatibility = 1.7
version = '1.0'
repositories {
mavenCentral()
}
project(':Module') {
jar {
manifest {
attributes 'Main-Class': 'com.sample.HelloWorld'
}
}
}
dependencies{
compile 'joda-time:joda-time:2.7'
testCompile group: 'junit', name: 'junit', version: '4.11'
}
mainClassName = "com.sample.HelloWorld"
com.sample.HelloWorld.java
package com.sample;
import org.joda.time.LocalTime;
public class HelloWorld {
public static void main(String[] args) {
LocalTime currentTime = new LocalTime();
System.out.println("The current local time is: " + currentTime);
}
}
After running the distZip task, I unzip the generated build/distribution/Module-1.0.zip archive which has the following directory structure:
Module-1.0
|__bin
|__lib
|__Module-1.0.jar
|__joda-time-2.7.jar
Within the lib directory, I tried the command:
java com.sample.HelloWorld -cp Module-1.0.jar;joda-time-2.7.jar
Which gives the following output:
Error: Could not find or load main class com.sample.HelloWorld
Then I tried:
java -jar Module-1.0.jar -cp joda-time-2.7.jar
Which gave the output:
Exception in thread "main" java.lang.noClassDefFoundError: org/joda/time/LocalTime...
I made sure that in my Manifest.MF file, the Main Class attribute is set to com.sample.HelloWorld, so my question is why does running the java command lead to a 'no main class found' error but using the java -jar command does not lead to that error?
Also, why is it that Java cannot find the joda-time-2.7.jar dependency when I run the java -jar command?
I know that you can run the program using the gradlew run command -- I tried that and it works perfectly. I am just very curious as to why running traditional java commands do not work.
Try this:
java -cp Module-1.0.jar:joda-time-2.7.jar:. com.sample.HelloWorld
Your command line arguments to java are wrong. You need to specify the -cp parameter before -jar. After the argument to -jar everything else is command line arguments to your main class. So what you want is this:
$ java -cp joda-time-2.7.jar-jar Module-1.0.jar
Also, you don't need to do this at all, the Grade application plugin will have built you a shell script (*nix systems) and .bat file (windows) to launch your program with, so if you're on *nix, do this instead:
$ Module-1.0/bin/<name_of_the_script_here>
Related
I have a working IntelliJ IDEA run configuration. It uses Spring Boot.
I'd like to execute the same run from the MacOS command line. How can I get IntelliJ IDEA to show the command (or commands) that I need execute the run configuration.
This is the gradle build.gradle file:
plugins {
id 'org.springframework.boot' version '2.6.4'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'org.mountsinai'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = "15"
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2'
runtimeOnly 'com.microsoft.sqlserver:mssql-jdbc'
implementation group: 'org.springframework', name: 'spring-aspects', version: '5.3.15'
implementation group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect', version: '3.0.0'
implementation group: 'com.jayway.jsonpath', name: 'json-path', version: '2.7.0'
implementation group: 'com.github.pcj', name: 'google-options', version: '1.0.0'
implementation 'com.google.code.gson:gson:2.9.0'
}
tasks.named('test') {
useJUnitPlatform()
minHeapSize = "1024m" // initial heap size
maxHeapSize = "2048m" // maximum heap size
}
targetCompatibility = JavaVersion.VERSION_15
And this is the configuration element in the ./.idea/workspace.xml corresponding to the run I'd like to automate on the command line:
<configuration name="IrwMetadataIntegrationApplication" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="org.mountsinai.IRWMetadataIntegration.main" />
<option name="SPRING_BOOT_MAIN_CLASS" value="org.mountsinai.IRWMetadataIntegration.IrwMetadataIntegrationApplication" />
<option name="PROGRAM_PARAMETERS" value="--algorithm=batch --numOfStudiesToRetrieve=600" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="true" />
<option name="ALTERNATIVE_JRE_PATH" value="15" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
My original question can now be asked more concretely How can one convert an IDEA configuration and workspace.xml file into a command (or script) that can be executed outside IntelliJ IDEA?
Using
IntelliJ IDEA 2021.3.2 (Ultimate Edition) Build #IU-213.6777.52, built on January 27, 2022
Thanks, Arthur
At the top of your console
Notice there's a command something something... java, normally it collapses into such short form, but if you click on that:
Notice it will expand and show you the full command:
In this case, for example, ultimately, the command is something like this:
/Users/hoaphan/.sdkman/candidates/java/17.0.4-amzn/bin/java -XX:TieredStopAtLevel=1
-Dspring.output.ansi.enabled=always
-Dcom.sun.management.jmxremote
-Dspring.jmx.enabled=true
-Dspring.liveBeansView.mbeanDomain
-Dspring.application.admin.enabled=true
...blahblahblahblahblah...
com.example.bootgradlej17.Bootgradlej17Application
So you can mimic intelliJ by running such long command.
But I would suggest if this is springboot, and build by gradle, what you actually want to do is at project root, in the dir where your build.gradle is do:
./gradlew bootRun
Now if you want to mimic the JVM option IntelliJ did, you can just capture such info from an IntelliJ run using tool like VisualVM:
Then you can configure your bootRun to start with such config for JVM like:
bootRun {
jvmArgs = "-Dspring.application.admin.enabled=true", "-Dnannana=nenenene" (etc)....
}
Execute your program through the run configuration and check the first line of the output. It should contain the call that is executed by the IDE, often something like java -jar ….
e.g. when running a Scratch file, I get the following in the output window as first line:
/usr/lib/jvm/java-1.11.0-openjdk-amd64/bin/java -javaagent:/home/user/bin/idea-IU-222.3345.47/lib/idea_rt.jar=37117:/home/user/bin/idea-IU-222.3345.47/bin -Dfile.encoding=UTF-8 -classpath /home/user/.cache/JetBrains/IntelliJIdea2022.3/compile-server/backend_dd2372d5/scratches/out:... Scratch
Continuing my comment above ...
On my computer (running macOS Big Sur 11.6) VisualVM cannot find the JVM arguments:
Instead, they can be found in the java command that you explain how to reveal. E.g., mine are:
-Dspring.output.ansi.enabled=always
-Dcom.sun.management.jmxremote
-Dspring.jmx.enabled=true
-Dspring.liveBeansView.mbeanDomain
-Dspring.application.admin.enabled=true
...
Please explain your
bootRun {
jvmArgs = "-Dspring.application.admin.enabled=true", "-Dnannana=nenenene" (etc)....
}
example. Where and how should this text be used?
One also needs to provide any command-line arguments that are in the IDEA configuration. These can be passed via the gradlew --args option, like this:
--args='--algorithm=batch --numOfStudiesToRetrieve=600'
Overall, however, this approach is more ad hoc than I'd like. It requires that one hack a) IDEA's java command to obtain the JVM arguments, b) the command-line arguments in via gradlew's --args. But I assume that the silence of IntelliJ IDEA's developers indicates that they do not support this important functionality.
Another comment in an answer because the formatting limitations of comments are so limiting:
Thanks, #HoaPhan. However, when I insert a bootRun section like this in build.gradle,
bootRun {
jvmArgs = "-Dspring.output.ansi.enabled=always"
}
IntelliJ IDEA raises
Could not compile build file '<path>/build.gradle'.
> startup failed:
build file '<path>/build.gradle': 1: Unexpected input: '{' # line 1, column 9.
bootRun {
^
This appears to occur wherever the section is placed in the file.
However, this does work:
bootRun {
jvmArgs = [ "-Dspring.output.ansi.enabled=always",
"-Dcom.sun.management.jmxremote",
"-Dspring.jmx.enabled=true",
"-Dspring.liveBeansView.mbeanDomain",
"-Dspring.application.admin.enabled=true",
"-Dfile.encoding=UTF-8"
]
}
It's unclear why the first bootRun { appears to generate a syntax error and this does not.
I am trying to build an application with gradle from within a docker container.
This is my Dockerfile:
FROM openjdk:8-jdk
#install git
RUN apt-get install -y git
RUN git clone https://github.com/SFRJ/yurl.git
#install gradle
RUN wget https://downloads.gradle-dn.com/distributions/gradle-6.5-bin.zip
RUN unzip gradle-6.5-bin.zip
ENV GRADLE_HOME /gradle-6.5
ENV PATH $PATH:/gradle-6.5/bin
#compile and run app
RUN cd yurl
RUN gradle clean build --rerun-tasks --no-build-cache
ENTRYPOINT ["java", "-jar", "/yurlapp.jar"]
Everything goes well until the point where the build command is executed. It throws the following:
Step 9/10 : RUN gradle clean build --rerun-tasks --no-build-cache
---> Running in a25d344c3571
Welcome to Gradle 6.5!
Here are the highlights of this release:
- Experimental file-system watching
- Improved version ordering
- New samples
For more details see https://docs.gradle.org/6.5/release-notes.html
Starting a Gradle Daemon (subsequent builds will be faster)
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring root project ''.
> The project name must not be empty. Set the 'rootProject.name' or adjust the 'include' statement (see https://docs.gradle.org/6.5/dsl/org.gradle.api.initialization.Settings.html#org.gradle.api.initialization.Settings:include(java.lang.String[]) for more details).
* 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 3s
ERROR: Service 'yurlapp' failed to build: The command '/bin/sh -c gradle clean build --rerun-tasks --no-build-cache' returned a non-zero code: 1
I just don't understand what it is. The app builds perfectly fine when I run the same command outside of docker but inside docker fails. This is not a multi module project not sure why it complains about rootProject.
I can confirm that I have a settings.gradle file and inside I have this
rootProject.name = 'yurl'
Also this is my build.gradle
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath "org.postgresql:postgresql:42.2.11"
}
}
plugins {
id 'org.springframework.boot' version '2.2.4.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
id 'org.flywaydb.flyway' version '6.3.0'
id 'nu.studer.jooq' version '4.1'
}
group 'com.javing.yurl'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
annotationProcessor 'org.projectlombok:lombok:1.18.8'
implementation 'org.jooq:jooq'
implementation 'org.jooq:jooq-codegen'
jooqRuntime 'org.postgresql:postgresql:42.2.11'
compile 'org.postgresql:postgresql:42.2.11'
implementation 'org.projectlombok:lombok:1.18.8'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-jooq'
implementation 'io.vavr:vavr:0.10.2'
implementation 'com.konghq:unirest-java:3.7.00'
testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile group: 'org.mockito', name: 'mockito-core', version: '2.1.0'
testCompile group: 'org.assertj', name: 'assertj-core', version: '3.15.0'
}
jooq {
sample(sourceSets.main) {
jdbc {
driver = 'org.postgresql.Driver'
url = 'jdbc:postgresql://yurldb:5432/yurldb'
user = 'postgres'
password = 'somepassword'
}
generator {
database() {
name = 'org.jooq.meta.postgres.PostgresDatabase'
inputSchema = 'public'
includes = '.*'
}
target {
packageName = 'com.javing.yurl'
directory = 'build/generated/java'
}
}
}
}
tasks.generateSampleJooqSchemaSource.with {
def out = new ByteArrayOutputStream()
javaExecSpec = { JavaExecSpec s ->
s.standardOutput = out
s.errorOutput = out
s.ignoreExitValue = true
s.jvmArgs '-Xmx512M'
}
execResultHandler = { ExecResult r ->
if (r.exitValue != 0) {
throw new RuntimeException('jOOQ source code generation failed:\n\n' + out.toString())
}
}
}
flyway {
url = 'jdbc:postgresql://localhost:5432/yurldb'
user = 'postgres'
password = 'somepassword'
schemas = ['public']
locations = ["filesystem:$project.projectDir/src/main/resources/db/migration"]
}
I don't know how to fix this I tried multiple things but nothing worked. I need to build this app from within docker using gradle. I know gradle is installed correctly because if I add the version command (RUN gradle -v) in the Dockerfile, I can see this printed when docker is running:
------------------------------------------------------------
Gradle 6.5
------------------------------------------------------------
Build time: 2020-06-02 20:46:21 UTC
Revision: a27f41e4ae5e8a41ab9b19f8dd6d86d7b384dad4
Kotlin: 1.3.72
Groovy: 2.5.11
Ant: Apache Ant(TM) version 1.10.7 compiled on September 1 2019
JVM: 1.8.0_252 (Oracle Corporation 25.252-b09)
OS: Linux 4.18.0-25-generic amd64
So my gradle and configuration of gradle seems ok. Also I know the installation of git and the clonning of the project is fine because if I add a RUN ls -s in my Dockerfile it will correctly print all the content of the project.
Something is wrong maybe in the build.gradle or settings.gradle file. Any idea what could be?
Can you try the below Dockerfile as have changed a little bit.
FROM openjdk:8-jdk
#install git
RUN apt-get install -y git
RUN git clone https://github.com/SFRJ/yurl.git
#install gradle
RUN wget https://downloads.gradle-dn.com/distributions/gradle-6.5-bin.zip
RUN unzip gradle-6.5-bin.zip
ENV GRADLE_HOME /gradle-6.5
ENV PATH $PATH:/gradle-6.5/bin
#compile and run app
WORKDIR yurl
RUN gradle clean build --rerun-tasks --no-build-cache
ENTRYPOINT ["java", "-jar", "/yurlapp.jar"]
The problem was, you mentioned a stageRUN cd yurl in which you are changing a directory, which is only valid for that particular stage not for the remaining stages. If you want to use that particular directory for the other stages as well. Use WORKDIR to run that operation which I did above.
P.S.:- If you want to use that directory only for 1 stage, then instead of WORKDIR use RUN cd DIR && ls -lart like command in 1 stage itself.
I'm trying to run Gradle project with JavaFX in IntelliJ IDEA Ultimate on Windows. JavaFX was added in our latest Git push, before it was working.
I can build project without problems. I'm getting an errror while running main:
I have:
JDK 11.0.5 (the one from Oracle site, not openJDK), I'm using Java 11, all configured in IntelliJ
JDK installation directory (specifically /bin directory in it) added to my PATH
JAVA_HOME environment variable added with JDK installation directory
Project structure:
build.gradle (it was not built by me, I don't understand exactly what is written there and why):
plugins {
id 'java'
id 'application'
id 'org.openjfx.javafxplugin' version '0.0.8'
}
group 'transportCompany'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile 'org.mongodb:mongodb-driver-sync:3.11.2'
compile group: 'org.openjfx', name: 'javafx', version: '11.0.2', ext: 'pom'
}
javafx {
version = "11.0.2"
modules = [ 'javafx.controls', 'javafx.fxml' ]
}
Main.java:
public class TransportCompanyApp extends Application {
private Stage primaryStage;
private MainAppPresenter presenter;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("My first JavaFX app");
presenter = new MainAppPresenter(primaryStage);
this.presenter.initRootLayout();
//this.primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
If I understand correctly, IntelliJ sees all files, there are no unresolved references in code, all imports work.
JavaFX jars are downloaded by Gradle:
They are configured as "Libraries", not "Global libraries", since they shouldn't be, with Gradle it should just be built, download everything and run, if I understand correctly.
I've tried creating new project with Git Checkout, it didn't work. Curiously though it worked for my colleagues (they have the same setup: JDK 11, Java 11, Windows; some even don't have JAVA_HOME at all and it works for them).
What I've tried:
JavaFX getting started
Error: JavaFX runtime components are missing, and are required to run this application with JDK 11
Error: JavaFX runtime components are missing - JavaFX 11 and OpenJDK 11 and Eclipse IDE
https://intellij-support.jetbrains.com/hc/en-us/community/posts/360000909940-Openjfx-11
https://openjfx-dev.openjdk.java.narkive.com/aFiw9uqi/error-javafx-runtime-components-are-missing-and-are-required-to-run-this-application
using JDK 13 and Java 13
changing project to modular
using JavaFX as Global Library and importing it to modules
What else can I do? I just want Gradle to download whatever I need and run this project. We've done that at university with JavaFX introduction with similar project and it did work on my current configuration (the only difference was that that one was with Maven).
EDIT
After running gradlew --info run I got:
> Task :run FAILED
Task ':run' is not up-to-date because:
Task has not declared any outputs despite executing actions.
Starting process 'command 'C:\Program Files\Java\jdk-11.0.5\bin\java.exe''. Working directory:
C:\Users\Lenovo\Desktop\TO Command: C:\Program Files\Java\jdk-11.0.5\bin\java.exe --add-modules
javafx.controls,javafx.fxml --module-path C:\Users\Lenovo\.gradle\caches\modules-2\files-2.1\o
rg.openjfx\javafx-fxml\11.0.2\b3242e4c031558574de2a1da685bb5fcdbb8a530\javafx-fxml-11.0.2-win.j
ar;C:\Users\Lenovo\.gradle\caches\modules-2\files-2.1\org.openjfx\javafx-controls\11.0.2\6c7637
07769c18adce406904c771c2ad1fcc370b\javafx-controls-11.0.2-win.jar;C:\Users\Lenovo\.gradle\cache
s\modules-2\files-2.1\org.openjfx\javafx-graphics\11.0.2\20459ea2cf714942bcbeb78a7f70ba3531dc1a
44\javafx-graphics-11.0.2-win.jar;C:\Users\Lenovo\.gradle\caches\modules-2\files-2.1\org.openjf
x\javafx-base\11.0.2\1852e57b8cf9a9b6488c33605bccd5d06ff210e1\javafx-base-11.0.2-win.jar -Dfile
.encoding=windows-1250 -Duser.country=PL -Duser.language=pl -Duser.variant -cp C:\Users\Lenovo\
Desktop\TO\build\classes\java\main;C:\Users\Lenovo\Desktop\TO\build\resources\main;C:\Users\Len
ovo\.gradle\caches\modules-2\files-2.1\org.mongodb\mongodb-driver-sync\3.11.2\a011ecee75c110e95
d33ece066f4bee149d5487a\mongodb-driver-sync-3.11.2.jar;C:\Users\Lenovo\.gradle\caches\modules-2
\files-2.1\org.openjfx\javafx\11.0.2\6e90384c9fb4ec7ed8186c0e916c419c87a24cbf\javafx-11.0.2.pom
;C:\Users\Lenovo\.gradle\caches\modules-2\files-2.1\org.openjfx\javafx-fxml\11.0.2\b3242e4c0315
58574de2a1da685bb5fcdbb8a530\javafx-fxml-11.0.2-win.jar;C:\Users\Lenovo\.gradle\caches\modules-
2\files-2.1\org.openjfx\javafx-controls\11.0.2\6c763707769c18adce406904c771c2ad1fcc370b\javafx-
controls-11.0.2-win.jar;C:\Users\Lenovo\.gradle\caches\modules-2\files-2.1\org.openjfx\javafx-c
ontrols\11.0.2\4ab633cf1eea60f76e2ae9905aedac862da88b08\javafx-controls-11.0.2.jar;C:\Users\Len
ovo\.gradle\caches\modules-2\files-2.1\org.openjfx\javafx-graphics\11.0.2\20459ea2cf714942bcbeb
78a7f70ba3531dc1a44\javafx-graphics-11.0.2-win.jar;C:\Users\Lenovo\.gradle\caches\modules-2\fil
es-2.1\org.openjfx\javafx-graphics\11.0.2\e522eb4ea422eceeee207b1c266ba3db19b2343a\javafx-graph
ics-11.0.2.jar;C:\Users\Lenovo\.gradle\caches\modules-2\files-2.1\org.openjfx\javafx-base\11.0.
2\1852e57b8cf9a9b6488c33605bccd5d06ff210e1\javafx-base-11.0.2-win.jar;C:\Users\Lenovo\.gradle\c
aches\modules-2\files-2.1\org.openjfx\javafx-base\11.0.2\7fb2e4a8528ec9e434a9ac9ee98b39af79e6dc
b8\javafx-base-11.0.2.jar;C:\Users\Lenovo\.gradle\caches\modules-2\files-2.1\org.mongodb\mongod
b-driver-core\3.11.2\798e2d948326c5bfd9924e524bab22ee39c8f4f\mongodb-driver-core-3.11.2.jar;C:\
Users\Lenovo\.gradle\caches\modules-2\files-2.1\org.mongodb\bson\3.11.2\96b17202f1250736ba83021
ff56550e83e8fd8c5\bson-3.11.2.jar TransportCompanyApp
Successfully started process 'command 'C:\Program Files\Java\jdk-11.0.5\bin\java.exe''
Error: Could not find or load main class TransportCompanyApp
Caused by: java.lang.ClassNotFoundException: TransportCompanyApp
:run (Thread[Daemon worker,5,main]) completed. Took 0.367 secs.
FAILURE: Build failed with an exception.
The problem was solved. What I did:
Removed compile group: 'org.openjfx', name: 'javafx', version: '11.0.2', ext: 'pom' as dependency from gradle.build.
Changed mainClassName in gradle.build to mainClassName = "app.TransportCompanyApp".
Changed Run option in IntelliJ to use gradle run.
I am new to JAVA9 modular architecture and trying to compile and run module inside a JAR from windows command line.
I have created simple HelloWorld.java main class and project architecture is as below :
I was successfully able to compile and create JAR file using following command.
Compile :
javac -d target/HelloWorld src/HelloWorld/com/java/modularity/test1/HelloWorld.java src/HelloWorld/module-info.java
Create a HelloWorld.jar file in "jarfile" directory :
jar -cfe jarfile/HelloWorld.jar com.java.modularity.test1.HelloWorld target/HelloWorld/module-info.class target/HelloWorld/com/java/modularity/test1/HelloWorld.class
Getting following error while trying to run module from JAR file :
D:\sts_workspace\java9tutorial>java -p jarfile -m HelloWorld
module HelloWorld does not have a ModuleMainClass attribute, use -m <module>/<main-class>
Getting following error while slide change in command :
D:\sts_workspace\java9tutorial>java -p jarfile -m target/HelloWorld/com.java.modularity.test1.HelloWorld
Error occurred during initialization of boot layer
java.lang.module.FindException: Module target not found
Here is my entry class HelloWorld.java :
package com.java.modularity.test1;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Testing first HelloWorld module ...");
}
}
Here is HelloWorld module description :
module HelloWorld {
}
I also tried by extracting my generated HelloWorld.jar file and "Main-Class" attribute is also present in MANIFEST.MF file :
Manifest-Version: 1.0
Created-By: 1.8.0_172 (Oracle Corporation)
Main-Class: com.java.modularity.test1.HelloWorld
Do I need to export the entry class in my module definition ? Any suggestion will help me to fix the issue.
Try changing
-m target/HelloWorld/com.java.modularity.test1.HelloWorld
to
-m HelloWorld/com.java.modularity.test1.HelloWorld
for the syntax is module[/mainclass]
I have a Gradle project (say, MyProject) that has a main method that I only want to use to run a small Java app. Say, the script is in a class and package as follows:
MyScript.Java
package com.car.ant;
import com.3rdparty.library.LibraryException;
public class MyScript {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
I build the project with $ ./gradlew clean build, no problem. I am trying to run this via command line, but when I do, I get an Exception when trying to run:
$ pwd
~/workspace/MyProject/build/classes/java/main
$ java com.car.ant.MyScript
Exception in thread "main" java.lang.NoClassDefFoundError: com/3rdparty/library/exception/LibraryException
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
... 7 more
This script is not the main part of the app, but I just want it in there to run every once in a while, and I'd like to figure out how to run it by itself command line. Is there a way to do this without importing anymore libraries? I've seen this done with one-jar, but I thought I could do this without one-jar.
UPDATE:
Tried to add a classpath after reading this, but now I'm getting a different error:
$ java -cp com/3rdparty/library/exception/LibraryException com.car.ant.MyScript
Error: Could not find or load main class com.car.ant.MyScript
You can read about how to do this at the Gradle Docs.
apply plugin: 'application'
mainClassName = "com.mycompany.myapplication.MyScript"
applicationDefaultJvmArgs = [
"-Djava.util.logging.config.file=src/main/resources/logging.properties"
]
Then simply use gradlew run to run your application.
As an added benefit, this plugin helps you to package your app for distribution. Use the gradle distZip command for that.
Try this.
plugins {
id 'java-library'
id 'application'
}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
/*
sourceCompatibility is "Java version compatibility to use when compiling Java source."
targetCompatibility is "Java version to generate classes for."
*/
repositories {
jcenter()
}
dependencies {
}
//To run the class name from command line using gradle run
mainClassName = 'com.sam.home.HelloWorld'
//To create a runnable jar in GradleJavaProject\build\libs then java -jar GradleJavaProject.jar
jar {
manifest {
attributes 'Main-Class': 'com.sam.home.HelloWorld'
}
}
//Beyond this line evertyhing is optional
//Alternatively you can run it as a task too gradle -q runWithJavaExec
task runWithJavaExec(type: JavaExec) {
group = "Execution"
description = "Run the main class with JavaExecTask"
classpath = sourceSets.main.runtimeClasspath
main = 'com.sam.home.HelloWorld'
}
wrapper {
gradleVersion = '5.5'
distributionType = Wrapper.DistributionType.BIN
}
In command line type either gradle run or gradle -q runWithJavaExec