What is Groovy Truth

Groovy has its own way of defining what is true and what is false, this is called the Groovy Truth. In Java, we have to write statements like if(obj ==null), in groovy you can simply write if(obj) and you can define in what conditions this object will evaluate to true and when it will evaluate to false.

 Info

To define your custom logic for groovy Truth you need to define method

boolean asBoolean(){
 // your logic here
}

What is True in Groovy

Following evaluated to true in groovy

  1. boolean true
  2. Not null objects
  3. Non 0 numbers
  4. Not null and not empty Strings
  5. Not null and not empty lists, maps, collections

What is False in Groovy

Following things evaluates to false in groovy

  1. boolean false
  2. Numeric 0 number
  3. Null objects
  4. Null Strings
  5. Null or empty lists, maps, collections
def groovyTruth = {val->
  if(val)
     println "$val is true"
  else 
    println "$val is false"
}

boolean b1 = true
boolean b2 = false

groovyTruth(b1)  // true  
groovyTruth(b2) // false

int n1 = 0  
int n2 = 12
int n3 = -321

groovyTruth(n1) // false
groovyTruth(n2) // true
groovyTruth(n3) // true

String s1 = null
String s2 = ""
String s3 = "some string"

groovyTruth(s1)  // false
groovyTruth(s2)  // false
groovyTruth(s3)  // true

Object o1 = null
Object o2 = new Object()

groovyTruth(o1)  // false
groovyTruth(o2)  // true

List l1 = null
List l2 = []
List l3 = [1,2,3]

groovyTruth(l1) // false
groovyTruth(l2) // false
groovyTruth(l3) // true


Map m1 = null 
Map m2 = [:]
Map m3 = ['key': 'val']

groovyTruth(m1)  // false
groovyTruth(m2)  // false
groovyTruth(m3)  // true

When we run this code, it will give the following output

Output

true is true
false is false
0 is false
12 is true
-321 is true
null is false
is false
some string is true
null is false
java.lang.Object@37074b2c is true
null is false
[] is false
[1, 2, 3] is true
null is false
[:] is false
[key:val] is true


Custom Groovy Truth

You can also define your custom Groovy Truth, that is how object will evaluate to true and false . For this you need to override the method Boolean asBoolean() to return a boolean value which will be used to evaluate truth of the object.

Let's take a class Student and it should give true if the status of student is enrolled

class Student{  
  String name 
  String status

 boolean asBoolean(){
    return status == 'enrolled'
 }
 String toString(){
   return name
 }
}

Student s1 = new Student(name : 's1', status: 'enrolled')
Student s2 = new Student(name : 's2', status: 'applied')

def groovyTruth = {val->
  if(val)
     println "$val is true"
  else 
    println "$val is false"
}

groovyTruth(s1)
groovyTruth(s2)
​

So the above code will give the following output

Output

s1 is true
s2 is false


How to Customise groovy Truth for the existing Classes in Groovy

Let's say we want to make the string "null" to evaluate to false. Then we can override the asBoolean() method of the String class.

So, the following will evaluate to false in this scenario.

  1. null - null object
  2. "" - blank string
  3. "null" - string will null as a string
String.metaClass.asBoolean = {
  if(delegate == null || delegate == "" || delegate == "null")
     return false
  return true
}

String s1 = null
String s2 = ""
String s3 = "null"
String s4 = "some string"

def groovyTruth = {val->
  if(val)
     println "$val is true"
  else 
    println "$val is false"
}

groovyTruth(s1)
groovyTruth(s2)
groovyTruth(s3)
groovyTruth(s4)​

This will give the following output

Output

null is false
is false
null is false
some string is true


How to get Browserify

Use the following to download browserify.

npm install -g browserify

Automate Browserify Dependency

You can also create a package.json file by the following command.

npm init

This will create a basic package.json file. now run the command

npm install --save browserify

--save option will download the file and save its reference in package.json. Now on other machine you just need to run the command npm install and it will download the browserify plugin and save it on your machine.

This will download the browserify in node_modules folder. Now we can use browserify to download our node dependencies. For this we will first create a .js file named require.js, you can name it anything you want.

Let's see a sample file.

angular = require('angular');
ngSanitize = require('angular-sanitize');

Now, to make browserify work you should have all these modules installed on your system under node_modules.

npm install angular
npm install angular-sanitize

Now, you can package both files in a single file by running the following command.

browserify require.js > destFile.js

The above command will compile all the files in require.js to the destination file specified after > . You can specify both relative and absolute path.

So, now you do not need to include both angular.js and angualr-sanitize.js files in your html, rather you just need to include destFile.js.

Browserify reference to included file.

If you want a reference to your js file you can update your js file as follows.

// to include markdown dependency
global.md = require('markdown-it');

Now you can get the reference of your markdown library as md and use it in javascript or jquery as follows

var markdown = md();

This will make an instance of markdown and assign to variable markdown.

This post is based on the Gradle Cargo Plugin by bmuschko

Include the Plugin

You need to include the plugin in your build.gradle.

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.bmuschko:gradle-cargo-plugin:2.2.3'
    }
}

apply plugin: 'com.bmuschko.cargo'

buildscript block should be the first thing in the build.gradle file.

Include the Gradle Cargo plugin dependencies

Add the following in your gradledependencies block

dependencies {
    def cargoVersion = '1.4.5'
    cargo "org.codehaus.cargo:cargo-core-uberjar:$cargoVersion",
            "org.codehaus.cargo:cargo-ant:$cargoVersion"
}

Define the Tomcat Container

To deploy The war files to Tomcat you need to create a dsl by name cargo and define the mandatory containerId.

Note

ContainerId will define the version of tomcat you want to use. If your want to deploy to tomcat6 your containerId will tomcat6x.

See the complete list of possible contianerId's supported


Gradle task to deploy war file on Tomcat

Below is a sample gradle task that will deploy war file from given location to Tomcat.

task deployAppA(type: com.bmuschko.gradle.cargo.tasks.remote.CargoRedeployRemote) {
    description = "Deploys WAR to Tomcat ."  // description of task 
    hostname = '127.0.0.1' // ip of the tomcat 
    port = 8080 // port at which tomcat is running
    username = "tomcat" // username of tomcat
    password = "tomcat"  // password of the tomcat
    deployables = [
            new com.bmuschko.gradle.cargo.convention.Deployable(file: file('/path/to/war/appA.war'), context: 'appA')]
}

The above will deploy your war file appA.war on Tomcat running on your local machine.

Note

Your tomcat should have manager-script role to allow the plugin to deploy war on tomcat.


Adding Manage-Script role to Tomcat

To add the role to Tomcat, go to path-to-tomcat/conf folder and replace the contents of file with the following.

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="manager-script"/>
  <user username="tomcat" password="tomcat" roles="tomcat,manager-script"/>

</tomcat-users>

The above will set a user tomcat with password tomcat and roles tomcat and manager-script.

Now restart your tomcat server and run the gradle task with the command

gradle -q deployAppA

This should deploy your war file to tomcat.

Step 1 : Download and Extract tomcat

Download tomcat from the link in .zip format. Once download is complete extract the tomcat in the location you want, preferably C:\Tomcat\.
Tomcat extract

Step 2 : Install Tomcat as a Service

Go to the tomcat directory C:\Tomcat\bin. in the address bar write cmd. This will open the command prompt window.
Tomcat extract

Now in the command prompt window type the command

service.bat install <Service -Name>

Here <Service-Name> can be any name that you want to assign to your Service.

Tomcat extract

When you run this command you will see the following output.

Tomcat extract

Check the installed Service

Now, lets see if the service is created or not. For this open Services . It will give the following screen.

Tomcat extract

Configure Service to Run at Startup

We can make the service to run on windows startup, for this, open the Service setting by double click on the service. It will open the following screen

Tomcat extract

From the dropdown Startup type select Automatic . This will start the service when Windows starts/boots.

How To Exclude File from a Jar file.

Gradle task Jar has a property excludes which takes an array as an input and exclude these files from the Jar file it creates.

Let's assume the following directory structure

Project Structure

Following example excludes files from the Jar file.

task createExcludingFiles(type :Jar){
    from ('src'){
        excludes = ["main/java/com/ekiras/demo/D.java","main/java/com/ekiras/demo/E.java"]
    }
}

This will exclude files D.java, E.java from the jar file. Run the gradle task using command gradle -q createExcludingFiles. The Jar file created will have the following files.

META-INF/
META-INF/MANIFEST.MF
main/
main/java/
main/java/com/
main/java/com/ekiras/
main/java/com/ekiras/demo/
main/java/com/ekiras/demo/A.java
main/java/com/ekiras/demo/C.java
main/java/com/ekiras/demo/F.java
main/java/com/ekiras/demo/B.java
main/java/com/ekiras/demo/p1/
main/java/com/ekiras/demo/p1/X.java
main/java/com/ekiras/demo/p1/Z.java
main/java/com/ekiras/demo/p1/Y.java
test/
test/java/
main/resources/
test/resources/

Exclude Package in Jar file

task createExcludingPackage(type :Jar){
    from ('src'){
        excludes = ["main/java/com/ekiras/demo/D.java" ,"main/java/com/ekiras/demo/p1/**"]
    }
}

Run the task using command gradle -q createExcludingPackage. This will remove

  1. All the files from package p1
  2. Class D.java

The Jar file created will have the following files.

META-INF/
META-INF/MANIFEST.MF
main/
main/java/
main/java/com/
main/java/com/ekiras/
main/java/com/ekiras/demo/
main/java/com/ekiras/demo/A.java
main/java/com/ekiras/demo/E.java
main/java/com/ekiras/demo/C.java
main/java/com/ekiras/demo/F.java
main/java/com/ekiras/demo/B.java
test/
test/java/
main/resources/
test/resources/

How to name a Jar file

Lets take the following jar file for explaning the jar naming conventions.

customName_wrapper_2.0.1_SNAPSHOT.jar

A jar file has the following properties

Property Description
baseName customName
appendix wrapper
version 2.0.1
classifier SNAPSHOT
archiveName -

Here property archiveName if specified will override all the other naming conventions like baseName etc. It should be a fully qualified name of the Jar including the extension (.jar)

Other Properties of Gradle Task :: Jar

Property Description
destinationDir Destination where jar is to be created
manifest Include Manifest file
from Directory from where files are to be read

Creating a Jar file

Let's assume the following directory structure

Project Structure

Create a Jar file with all files.

We can write a gradle task to include all files in src to our jar file as follows

task createAll(type : Jar){
    from 'src'
}

When we run the gradle task as gradle -q createAll will give the following files in the jar

META-INF/
META-INF/MANIFEST.MF
main/
main/java/
main/java/com/
main/java/com/ekiras/
main/java/com/ekiras/demo/
main/java/com/ekiras/demo/D.java
main/java/com/ekiras/demo/A.java
main/java/com/ekiras/demo/E.java
main/java/com/ekiras/demo/C.java
main/java/com/ekiras/demo/F.java
main/java/com/ekiras/demo/B.java
main/java/com/ekiras/demo/p1/
main/java/com/ekiras/demo/p1/X.java
main/java/com/ekiras/demo/p1/Z.java
main/java/com/ekiras/demo/p1/Y.java
test/
test/java/
main/resources/
test/resources/

Create a Jar file from a Package.

task createFromPackage(type : Jar){
    from ("src/main/java/com/ekiras/demo/p1")
}

Run the above task with command gradle -q createFromPackage, it will give the following files in jar.

META-INF/
META-INF/MANIFEST.MF
X.java
Z.java
Y.java

Create a Jar file with Selected Files.

task createSelectedJar(type : Jar){
    from ('src/main/java/com/ekiras/demo'){
        includes = ["A.java","B.java", "p1/X.java", "p1/Y.java"]
    }
}

Run the above command with command gradle -q createSelectedJar

META-INF/
META-INF/MANIFEST.MF
A.java
B.java
p1/
p1/X.java
p1/Y.java

Create a Jar file excluding some files

task createExcludingFiles(type :Jar){
    from ('src'){
        excludes = ["main/java/com/ekiras/demo/D.java","main/java/com/ekiras/demo/E.java", "main/java/com/ekiras/demo/p1/**"]
    }
}

Run the gradle task with command gradle -q createExcludingFiles. It will result in a jar file with the following files

META-INF/
META-INF/MANIFEST.MF
main/
main/java/
main/java/com/
main/java/com/ekiras/
main/java/com/ekiras/demo/
main/java/com/ekiras/demo/A.java
main/java/com/ekiras/demo/C.java
main/java/com/ekiras/demo/F.java
main/java/com/ekiras/demo/B.java
test/
test/java/
main/resources/
test/resources/

To Sum up all the exmaples above

Following is a gradle task that create a jar file

task createJar(type: Jar){
    from ('src/main/java/com/ekiras/demo'){
        includes = ["A.java","B.java", "p1/**"]
        excludes = ["D.java","E.java"]
    }
    baseName = 'customName'
    appendix = 'wrapper'
    version = "2.0.1"
    classifier = 'SNAPSHOT'
    archiveName = "${baseName}_${appendix}_${version}_${classifier}.jar"
    extension  = "ext"
    destinationDir = new File("${buildDir}/test/a")

    manifest {
        attributes = [
                'Main-Class' : "com.ekiras.A",
                'Version'    : 2.0
         ]
    }
}

we can also write a gradle task to see the files that were created inside the jar file as follows

task showFiles(dependsOn : createJar){
    doLast{
        FileTree files = zipTree("${buildDir}/test/a/${archiveName}")
        files.each {
            println "${it.name}"
        }
    }
}

When we run the task gradle -q createJar showFiles or simply gradle -q showFiles , it will give the following result

A.java
B.java
MANIFEST.MF
X.java
Y.java
Z.java

How to start Tomcat on more than one Port.

Tomcat settings can be found in TomcatFolder/conf/server.xml file.

  1. Root element of the configuration is Server tag.
  2. You can add multiple Service under Server tag for running tomcat on more than one port.

Default Service Configuration should look as follows

  <Service name="Catalina">
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
    <Engine name="Catalina" defaultHost="localhost">

      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>
    </Engine>
  </Service>

The above configurations states the folllowing things

  1. Service name="Catalina" - Service name is Catalina, you can change it to give your application name.
  2. Connector port="8080" protocol="HTTP/1.1" - Tomcat will run on port 8080
  3. connectionTimeout="20000" - Connection timeout in 20000 mili seconds
  4. Connector port="8009" protocol="AJP/1.3" - AJP connection on port 8009.
  5. name="localhost" - Name of the host where tomcat will run.
  6. appBase="webapp" - Base directory for deployed apps is webapp
  7. unpackWARs="true" - The war files deplyed wll be unpacked

Running Tomcat on multiple ports.

To start tomcat on more than one port you can add multiple Service blocks under Server root tag as shown below

  <Service name="app1">
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
    <Engine name="Catalina" defaultHost="localhost">

      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="app1"
            unpackWARs="true" autoDeploy="true">

        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="app1_access_log." suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>
    </Engine>
  </Service>
  <Service name="app2">
    <Connector port="8090" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <Connector port="8091" protocol="AJP/1.3" redirectPort="8443" />
    <Engine name="Catalina" defaultHost="localhost">

      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="app2"
            unpackWARs="true" autoDeploy="true">

        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="app2_access_log." suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>
    </Engine>
  </Service>

Here in above configuration we have specified the following.

  1. Service app1 configuration will run on port 8080.
  2. Service app2 configuration will run on port 8090.
  3. app1 will keep files and war files in folder app1.
  4. app2 will keep files and war files in folder app2.
  5. app1 and app2 will write access logs in folder logs/app1_access_log.txt and logs/app2_access_log.txt respectively

Note : None of the above configuration will keep files or war files in webapp folder.

Also Read