Showing posts with label Groovy. Show all posts
Showing posts with label Groovy. Show all posts

Sunday, 28 December 2014

Skipping Gradle Tasks

Background

Gradle simply speaking is a build tool like Apache ant but it does more that that and in an efficient way. It handles dependency management as well. You can say -

Gradle = Apapch Ant + Apache Ivy

In the background Gradle is all Groovy.  So if you are aware of groovy writing tasks in gradle is no big deal.

Make sure you have JDK configured and gradle installed.



Gradle Task Build Life Cycle

Gradle has 3 distinct phases -
  1. Initialization
  2. Configuration
  3. Execution

For more details on each of the phases refer Gradle Build Life Cycle . To quickly understand this build life cycle put following code in build.gradle file and run it - 

logger.lifecycle("This is executed during configuration phase");
task A() {
    logger.lifecycle("This is also executed during configuration phase");
    doFirst {
      logger.lifecycle('In task A : This is executed first in the execution phase.')
    }
    doLast {
        logger.lifecycle("In task A :This is executed last in execution phase");
    }    
}


and the output is



Hope you got the idea. Configuration and Execution phases are what we are going to concentrate on.

Lets first see how to write dependents Tasks in gradle.

Writing Dependent Tasks in Gradle


Create a file build.gradle and copy following code in it.

task A(dependsOn: 'B') {
    
    doLast {
        logger.info("In task A");
    }    
}

task B(dependsOn: 'C') {
    doLast {
        logger.info("In task B");
    }
}

task C {

    doLast {
        logger.info("In task C");
    }

}


Above code essentially declares three gradle tasks - A, B and C. Also there are dependencies between them. Notices the dependsOn keyword in bracket. Task A depends on Task B which in turn depends on Task C. Now lets run this. Output is -



Note 1 :

You can also define type of a Task. There are various predefined tasks in gradle. Something like -

task copyFiles(type: Copy, dependsOn: 'SomeAnotherTask') {
    from 'src/main/documentation'
    into 'build/target/documentation'
}


Note 2 :

You can also simply say - 

task A << {
    logger.lifecycle("In task A : Execution phase");
}


The '<<' symbol you see is just a shortcut to execute thing is Execution phase. This defines a task called A with a single closure to execute.

Ok now lets come to the intended purpose of this post which is - how to skip tasks.

Skipping Tasks in Gradle

Goal : Goal is to skip task A and all subsequent tasks that A depends on. Lets say we decide this with a property that we provide to gradle from commandline. Lets call it 'skipA'. If 'skipA' is provided in command line arguments we do not execute any task.

For this lets use onlyIf first.

task A(dependsOn: 'B') {
    onlyIf {
        !project.hasProperty('skipA')
    }
   
    doLast {
        logger.lifecycle("In task A");
    }   
}

task B(dependsOn: 'C') {
    doLast {
        logger.lifecycle("In task B");
    }
}

task C {
    doLast {
        logger.lifecycle("In task C");
    }
}


and the output is




Lets analyze what happened here.Yes Task A was skipped as we intended but what about other tasks they were run.

Don't argue that you can put onlyIf and condition in all tasks :) you are smarter than that!

Note : One important point to note is onlyIf is executed during execution phase and by that time gradle has figured out what all tasks it needs to run. Skipping a single task will not skip the task the skipped task depends on. We need to add skipping logic in configuration phase.

There is another way to do this and that is to set enabled = false; inside a task. This will skip the given task. Also we need two other things.

  1. Implement skipping logic in Configuration phase.
  2. Remove all the tasks that the task to be skipped was depending on (This needs point 1.)

So lets see how can we do that. Copy following code in build.gradle file -

task A(dependsOn: 'B') {
    if(project.hasProperty('skipA')) {
        logger.lifecycle("Skipping Project : " + project.name);
        enabled = false;
        dependsOn = [];
    }
   
    doLast {
        logger.lifecycle("In task A");
    }   
}

task B(dependsOn: 'C') {
    doLast {
        logger.lifecycle("In task B");
    }
}

task C {
    doLast {
        logger.lifecycle("In task C");
    }
}


and the output is


Yes we got what we wanted. Now lets see how we did it.

  • First of all see the if statement in task A. It is outside any doFirst() or doLast() method. This ensures it will be run in configuration phase.
  • Then we checked out condition. If it is true then we set enabled  = false for the task. This will skip task A.
  • To stop other tasks from running that A depends on we removed all those tasks by saying dependsOn = []; Again note this worked because we did it in configuration phase.

Related Links

Saturday, 16 August 2014

Using Groovy to send Emails

Background

In this post we will see how can we write a groovy script to send emails. I am going to use javax.mail and javax.activation for this. To setup groovy environment you can refer to one of my earlier posts - 




Code

/**
 * @author athakur
 *
 */

@Grapes([
    @Grab(group='javax.mail', module='mail', version='1.4.7'),
    @Grab(group='javax.activation', module='activation', version='1.1.1'),
    @GrabConfig(systemClassLoader=true)
])

import javax.mail.internet.*;
import javax.mail.*
import javax.activation.*

class EmailSender {
    
    public static void main(def args){
        //to test the script
        EmailSender emailSender = new EmailSender();
        emailSender.sendmail();
    }
    
    def static message = "Test Message";
    def static subject = "Test Message Subject";
    def static toAddress = "test1@opensourceforgeeks.com";
    def static fromAddress = "test2@opensourceforgeeks.com";
    def static host = "test.email.opensourceforgeeks.com";
    def static port = "25";
    
    public EmailSender() {
        
    }

    def static sendmail() {
        sendmail(message, subject, toAddress, fromAddress, host, port);
    }
    
    def static sendmail(String message ,String subject, String toAddress, String fromAddress, String host, String port){
        Properties mprops = new Properties();
        mprops.setProperty("mail.transport.protocol","smtp");
        mprops.setProperty("mail.host",host);
        mprops.setProperty("mail.smtp.port",port);

        Session lSession = Session.getDefaultInstance(mprops,null);
        MimeMessage msg = new MimeMessage(lSession);

        StringTokenizer tok = new StringTokenizer(toAddress,";");
        ArrayList emailTos = new ArrayList();
        while(tok.hasMoreElements()){
            emailTos.add(new InternetAddress(tok.nextElement().toString()));
        }
        InternetAddress[] to = new InternetAddress[emailTos.size()];
        to = (InternetAddress[]) emailTos.toArray(to);
        msg.setRecipients(MimeMessage.RecipientType.TO,to);
        msg.setFrom(new InternetAddress(fromAddress));
        msg.setSubject(subject);
        msg.setText(message)

        Transport transporter = lSession.getTransport("smtp");
        transporter.connect();
        transporter.send(msg);
        
        println("Message sent");
    }
}



 Then you can simply run it with groovy EmailSender.groovy.

Note :  you can import all packages you need using the grab syntax mentioned in the top of the script.
 To know the group, module and version you can search the Maven repository.  In the link there is a separate tab for grape like there is for ivy, maven or gradle. So you can directly pick up the syntax from there. For example if you search for javax.activation you can see the following syntax under grape tab - 


@Grapes(

        @Grab(group='javax.mail', module='mailapi', version='1.4.3')

)



Friday, 15 August 2014

How to capture arguments passed to a Groovy script?

It is very much similar to Java and you can use the same java syntax. For eg.

class TestExecutor {

    public static void main(def args) {
        println("Printing arguments");
        for(String arguments : args) {
            println (arguments);
        }
    }
} 


Run it and you should see the arguments printed



Also note if you do not provide main method or provide one like in above example then you can get arguments as args[i] but you can change the name of the array (again same as java). So you can have something like -

public static void main(def argsNew) {

    println("Printing arguments");

    for(String arguments : argsNew) {

        //using args in above for loop will throw error

        println (arguments);

    }

}


Point being it's not something that is hard-coded. Finally as suggested in other answer you can always use CliBuilder for smart parsing. But again in that too it internally used def options = cli.parse(args).

Finally there is always the hard way to do things (Just putting here for code coverage and additional information - no need to use this code for fetching arguments) -

import groovy.lang.Binding;
Binding binding = new Binding();
int x = 1
for (a in this.args) {
  println("arg$x: " + a)
  binding.setProperty("arg$x", a);
  x=x+1
}
println binding.getProperty("arg1")
println binding.getProperty("arg2")
println binding.getProperty("arg3") 

Important Links

Wednesday, 13 August 2014

Executing Shell commands in Groovy

Background

Groovy is a dynamic java language that runs on JVM. If you are familiar with Java that you will find it very easy to understand and code in Groovy. Will not go into much details now. You can refer to my earlier posts - 

Goal of this post is to show how easy it is to execute shell commands from Groovy. I am using Windows for demonstrating this but should be irrespective of OS you are using. All you have to do is make sure cURL is installed on your system which I will be using to demonstrate this example. You can refer to following posts on cURL


To the code....

 Put the following code in a file name GroovyTest.groovy and run it

class GroovyTest {
    public static void main(def args){
        def url = 'http://mail.google.com';
        println("Output : " + executeCurlCommand(url));
    }    
    
    def static executeCurlCommand(URL){
        
        def url = "curl " + URL;
        def proc = url.execute();
        def outputStream = new StringBuffer();
        proc.waitForProcessOutput(outputStream, System.err)
        return outputStream.toString();
        
        
    }
}

After running you can see the output same as executing the command on your console. If you need all outputs on standard output you can do

proc.waitForProcessOutput(System.out, System.err);


You can see the output by executing the same command in console

Saturday, 2 August 2014

Installing Groovy plugin in Eclipse

Background

You may want to go through the previous post on what is groovy and how to set the environment required to run Groovy programs. In this post I will show how to install it's Eclipse plugin.


Getting Started

  1. In Eclipse go to Help -> Install new Software .


  2. For the plugin site refer to the Groovy page for Eclipse plugin. The site depends on which version on Eclipse you are using. I am using Juno. So link for me is http://dist.springsource.org/release/GRECLIPSE/e4.2/.


  3. Select "Groovy-Eclipse" and click on next.



  4. Check install Details and Click on Next. Accept the agreement and click install. It will take some time to install the plugin depending on your internet bandwidth. You can see the progress at the bottom of Eclipse or from Progress tab.

Create a new groovy Project

  1.  Create a new Groovy project named GroovyTestProject.



  2. Create a groovy class named GroovyTest.groovy. Enter the following code and then run it as Groovy Script.

    class GroovyTest {
        public static void main(def args){
            println("Hello World!")
        }
     }
    


  3.  You should see the output in console.

Setting up Groovy environment

What is Groovy?

Groovy is a dynamic language that runs on the JVM and is tightly integrated with the Java language.  Groovy provides lots of simplifications compared to standard Java language features and advanced language features as properties, closures, native support for lists, maps and regular expressions, duck typing and the elvis operator.


Setting up groovy environment

Groovy requires Java, so you need to have a version available (while groovy 1.6 supported JDK 1.4 or greater, for groovy 1.7 onwards, minimum JDK 1.5 is needed)

Download the latest version from Groovy.  Unzip it and put it in some folder on your hard drive.
Then you have to set the GROOVY_HOME environment variable and add %GROOVY_HOME%/bin  to your PATH variable (Similar to JAVA_HOME. See above link on how to set up java environment).

Open groovyConsole.bat by double clicking on the icon in the bin directory of the Groovy distribution. If that does not work you may want to open the command line, navigate to bin directory and execute the bat file. Even if it does not open you will see the errors responsible for not starting the bat file.

Type in println("Hello World from yourName!")  and you should see it printed on the console (screenshot attached). After typing do Ctrl + R to execute the code.



Loading external jars in Grrovy

If you see your groovy-2.3.6\conf folder you will see groovy-starter.conf file which looks like - 


And if you notice it loads jars from
  1. {groovy.home}/lib/*.jar or
  2. !{user.home}/.groovy/lib/*.jar
You can put your jars in any of the above folder. Also .gradle folder should be automatically be created in your user directory. For me it's C:\Users\athakur\.groovy.

Difference between Groovy and Java

  •  In Java 'java.lang' package is imported by default, but in groovy some others general purpose packages and classes are imported by default. Eg   
    • groovy.lang.*,
    • groovy.util.*,
    • java.io.*,
    • java.net.*,
    • java.util.*,
    • java.lang.*
  • In Java '==' operator is used for comparing primitive types and .equals is used to compare Objects but in grooby we can use '==' to compare both primitive and objects.
  • Semicolon is optional in groovy
  • In groovy all classes and methods and public by default.
  • Array is initialized as int[] array = [1,2,3] in groovy unlike Java where you do int[] array = { 1, 2, 3}.
  • In groovy you need to specify a variable of it is primitive or instance of some class. All you have to do is use keyword 'def' and groovy is smart enough to understand the instance type. Eg. def str = "Hello World!"
  • The return keyword is optional.
  • You can use the this keyword inside static methods (which refers to this class).
     

Reference to more information 

t> UA-39527780-1 back to top