home.


Tagged: jar


Gradle: Hello world Java with a fat jar

Create your build.gradle with your dependencies and a jar section that collects all your libraries into the jar and sets the Main class file.

apply plugin: 'java'

repositories {
   mavenCentral()
}

dependencies {
    compile 'org.mindrot:jbcrypt:0.3m'
}

jar {
    from {
        (configurations.runtime).collect {
            it.isDirectory() ? it : zipTree(it)
        }
    }
    manifest {
        attributes("Main-Class": "Main" )
    }
}

Now create a basic hello world, using the library we imported:

import org.mindrot.jbcrypt.BCrypt;

public class Main {
        public static void main(String[] args) {
                String password = BCrypt.hashpw("password", BCrypt.gensalt(10));
                System.out.println(password);
        }
}

Now build and run your jar:

$ gradle clean build && java -jar build/libs/THE_NAME_OF_YOUR_JAR.jar
...
$2a$10$R6q8LOed8LqXCOIhBnzhMecyebv/8v1urKjU76JMJGUctnZ8VkyZu
java gradle fat-jar jar bcrypt

Gradle: Running a jar file

You can get Gradle to run a jar file for you by modifying ‘javaexec’:

javaexec { main='-jar'; args jar.archivePath }

This says the main class is ‘-jar’ and we’re passing our jar archive as the argument. It’s the same as running ‘java -jar YourArchive.jar’.

You an add this onto the end of the jaring process:

task runJar(dependsOn:jar) << {
  javaexec { main="-jar"; args jar.archivePath } 
}

‘gradle runJar’ will now run the jar task and then run the jar afterwards.

gradle gradle-jar gradle-java gradle-javaexec

ant-simple

Here’s a fairly bare-bones ant example, the one I’m using for BriefWebServer.

It makes a jar in build/jar, and optionally run the jar.

<project name="BriefWebServer" basedir="." default="jar">
    <property name="src.dir" value="src" />
    <property name="build.dir" value="build" />
    <property name="classes.dir" value="${build.dir}/classes" />
    <property name="jar.dir" value="${build.dir}/jar" />
    <property name="jar.name" value="BriefWebServer.jar" />
    <property name="package.name" value="org.denevell.briefwebserver" />

    <target name="compile">
        <mkdir dir="${classes.dir}" />
        <javac srcdir="${src.dir}" destdir="${classes.dir}" />
    </target>

    <target name="jar" depends="compile">
        <mkdir dir="${jar.dir}" />
        <jar destfile="${jar.dir}/${jar.name}" basedir="${classes.dir}">
          <manifest>
            <attribute name="Main-Class" value="org.denevell.briefwebserver.BriefWebServer" />
          </manifest>
        </jar>
    </target>

    <target name="run">
        <java jar="build/jar/BriefWebServer.jar" fork="true" />
    </target>

    <target name="clean">
        <delete dir="${build.dir}" />
    </target>

</project>
ant ant-basic ant-delete ant-mkdir ant-property ant-javac ant-jar

Page 1 of 1