Sunday, April 11, 2010

Process the command line with CLI in Java, common CLI example

CLI (=Command Line Interface)

How many times have you written a Java application and had had to rewrite a new way of specifying the input parameters to your application? Wouldn't it be nice if there were one single interface to the way you define the input parameters (mandatory vs. numbers vs. Boolean, etc.), parse these parameters (according to a set of rules), interrogate, and decide the path that your application will take? CLI is the answer.

To run this example, needs commons-cli-1.0.jar in the CLASSPATH. YOu can download from here

Refer of this tutorial.

In CLI, each parameter that you want to specify on the command line is an Option. Create an Options object, add individual Option objects to it, then use the CLI-supplied methods to parse the user's input parameters. An Option might require the user to input a value as well; for example, if the name of a file is required. In such a case, the Option must be created where this is explicitly specified.

Create your Options:

Options options = new Options();
options.addOption("n", true, "[name] your name");

2nd way is by creating an Option and then adding it
Option timeOption = new Option("t", false, "current time");
options.addOption(timeOption);

The addOption() method has three parameters.

1. The first parameter is a java.lang.String that represents the option (That would be given by user with - like -t or -n during execution of code).

2. The second parameter is a boolean that specifies whether the option requires an argument or not. For example -n Nik, here I gave Nik with -n because n is defined as true, if I will not give name then it would not be accept. For -t, no need to supply any argument as it is false. Even though if you give any argument, it would not be accept means it would be ignore that extra argument. In the case of a boolean option (sometimes referred to as a flag) an argument value is not present so false is passed.

3. The third parameter is the description of the option. This description will be used in the usage text of the application. When you will not give proper argument that time it will show like help command.

CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse( options, args);

The parse methods of CommandLineParser are used to parse the command line arguments. The PosixPaser is great when you need to handle options that are one character long, like the t option in this example. Else use BasicParser for more than one character input.

Now we need to check if the t option is present. To do this we will interrogate the CommandLine object. The hasOption method takes a java.lang.String parameter and returns true if the option represented by the java.lang.String is present, otherwise it returns false.


if(cmd.hasOption("t")) {
// print the date and time
}
else {
// print the some thing else;
}


One complete example on CLI :

import org.apache.commons.cli.*;


public class CLIDemo{

public static void main(String args[]){
Options options = new Options();
options.addOption("n", true, "[name] your name");
Option timeOption = new Option("t", false, "current time");
options.addOption(timeOption);

// ** now lets parse the input
CommandLineParser parser = new BasicParser();
CommandLine cmd;
try{
cmd = parser.parse(options, args);
}catch (ParseException pe){ usage(options); return; }

// ** now lets interrogate the options and execute the relevant parts

if(cmd.hasOption("t")){

System.out.println("You have given argument is t");
System.err.println("Date/Time: " + new java.util.Date());
}

if(cmd.hasOption("n")){
System.out.println("You have given argument is n");
System.err.println("Nice to meet you: " + cmd.getOptionValue('n'));
}

}

private static void usage(Options options){

// Use the inbuilt formatter class
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "CLIDemo", options );
}
}



In the above code, there is no any use to use cmd.getOptionValue('t') with t condition, as t has been setup false and it would be never get any extra argument as n.

How to run CLI example:

D:\JavaTest>javac CLIDemo.java

D:\JavaTest>java CLIDemo

D:\JavaTest>java CLIDemo -t
You have given argument is t
Date/Time: Sun Apr 11 21:19:50 EEST 2010

D:\JavaTest>java CLIDemo -n
usage: CLIDemo
-n [name] your name
-t current time

D:\JavaTest>java CLIDemo -n Nik
You have given argument is n
Nice to meet you: Nik

D:\JavaTest>java CLIDemo -n "Nik Suman"
You have given argument is n
Nice to meet you: Nik Suman

D:\JavaTest>

First time I did not give any argument, so there is no any output.
Second time I gave -t as argument then we got output as per our expectation.
Third time I gave -n. This time, durint parsing the input it got error so execute catch part. Actually -n has been setup with true so we have to have some

extra argument with -n. In catch block we are printing the help format.
Forth time I gave -n With some name, so it worked perfectly.

Saturday, April 10, 2010

MAVEN getting started, Maven in 10 Minutes

Download
apache-maven-3.0-alpha-7-bin.zip and unzip into any where (In my case it is D:\Software\apache-maven-3.0-alpha-7)
set path D:\Software\apache-maven-3.0-alpha-7\bin

open dos console and type mvn -v
To check for sucessfully install.

Create one folder to practice for maven project say D:\binod\Maven_Practice
Now execute command from dos console
D:\binod\Maven_Practice>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.bds -DartifactId=CheckMaven

CheckMaven is the project name
command exectued from D:\binod\Maven_Practice
it create one folder CheckMaven inside D:\binod\Maven_PracticeInside CheckMaven : src folder and pom.xml file
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; <modelVersion>4.0.0</modelVersion> <groupId>com.tecnotree.bds</groupId> <artifactId>CheckMaven</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>CheckMaven</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies></project>
src -> main and test. main -> java -> com -> tecnotree -> bds -> App.javatest -> java -> com -> tecnotree -> bds -> AppTest.java

App.java

package com.tecnotree.bds;
public class App {
public static void main( String[] args ) {
System.out.println( "Hello World!" );
}
}

AppTest.java

package com.tecnotree.bds;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/** * Unit test for simple App. */

public class AppTest extends TestCase{
/** * Create the test case * * @param testName name of the test case */
public AppTest( String testName ) { super( testName ); }
/** * @return the suite of tests being tested */
public static Test suite() { return new TestSuite( AppTest.class ); }
/** * Rigourous Test :-) */
public void testApp() { assertTrue( true ); }
}

D:\Binod\Maven_Practice\CheckMaven> mvn compile
It compile App.java and create new folder target and App.class put into D:\Binod\Maven_Practice\CheckMaven\target\classes\com\tecnotree\bds


without running above commannd
D:\Binod\Maven_Practice\CheckMaven>mvn test-compile then it will compile App.java and AppTest.java and put App.class into D:\Binod\Maven_Practice\CheckMaven\target\classes\com\tecnotree\bdsand AppTest.java into D:\Binod\Maven_Practice\CheckMaven\target\test-classes\com\tecnotree\bds

without running any above command
D:\Binod\Maven_Practice\CheckMaven> mvn test
It will do mvn test-compile and extra test. Means in target there would be create three folderlike about classes and test-classes and new is surefire-report.

Actually mvn test it runs the compiled unit tests and make report (txt & xml) and put into surefire-report folder.
This command will also show test result on console.

D:\Binod\Maven_Practice\CheckMaven> mvn package
It would be work of mvn test and extra create one folder maven-archiver and put one jar file CheckMaven-1.0-SNAPSHOT.jar into target folder.
Inside the maven-archiver one pom.properties file would be come with these details:
#Generated by Maven#Sat Apr 10 10:34:57 EEST 2010version=1.0-SNAPSHOTgroupId=com.tecnotree.bdsartifactId=CheckMaven

D:\Binod\Maven_Practice\CheckMaven>mvn integration-test
It will execute all above command internally and carries out acutal integartion tests. Right now no any differences from above command. We will see later.

Without running any above command
D:\Binod\Maven_Practice\CheckMaven> mvn install
It will run above command interally and adds the archive to the local Maven directory. This makes it available for any other modules that may depend on it.

My local repository set up into D:\.m2 folder.
(How to set up custome local maven repository:
I have install or unzip Maven file here D:\Software\apache-maven-3.0-alpha-7. Go into D:\Software\apache-maven-3.0-alpha-7\conf and change settings.xml
uncommented <localRepository> and changed to <localRepository>D:\.m2\repository</localRepository>
so, CheckMaven-1.0-SNAPSHOT.jar put into D:\.m2\repository\com\tecnotree\bds\CheckMaven\1.0-SNAPSHOT

Without running any above command
D:\Binod\Maven_Practice\CheckMaven> mvn deploy
It will run above command interally and adds the archive to the remote Maven directory. But here it wont work.
Because we dont have set up the repository element was not specified in the pom inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter -> [Help 1]

How to set remote maven repository.

open pom.xml (D:\Binod\Maven_Practice\CheckMaven\pom.xml)
Add <distributionManagement> like this
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; <modelVersion>4.0.0</modelVersion> <groupId>com.tecnotree.bds</groupId> <artifactId>CheckMaven</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>CheckMaven</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <distributionManagement> <repository> <id>BinodprojectRepository</id> <name>Binod Maven Repository Name</name> <url>file:///d:/MyRemoteMavenRepository</url>
</repository> <!-- site> <id>sample-project.website</id> <url>dav:https://dav.sample.com/sites/sample-project</url> </site --> </distributionManagement>
</project>

Now you will see after run mvn deploy.
one target file will be created as usual and archieve file will go to d:/MyRemoteMavenRepository (no need to createthis folder, it create automatically).
D:\Binod\Maven_Practice\CheckMaven> mvn cleanIt will delete the target forlder.


************************ CONCLUSION ********************
There are phases of the default life cycle of Maven
1. validate : Ensures that the current configuration and the content of the POM is valid. This includes validation of the tress of pom.xml files.
2. compile : Compiles the source code. The compiled classes are places into a target directory tree.
3. test-compile : Compile the source code of the unit tests.
4. test: Runs the compiled unit tests and showing the result on the console.
5. package: Bundles the exectable binaries into a distribution archive, such as a JAR or WAR.
6. integration-test : Carries out actual integration tests.
7. install : Adds the archive to the local Maven directory. This markes it available for any other modules that may depends on it.
8. deploy : Adds the archive to a remote Maven directory. This can make the artifact available to a larger audience.

Concept is here that if you run 3 then it will run 1, 2 and 3.
if you run 6 then it will run 1,2,3,4,5 and 6.
That is because if you call a build phase, it will execute not only that build phase, but also every build phase prior to the called build phase.

It should also be noted that the same command can be used in a multi-module scenario (i.e. a project with one or more subprojects). For example:mvn clean install (from root directory), this command will traverse into all of the subprojects and run clean, then install (including all of the prior steps).

mvn install -Dmaven.test.skip=true : it will do install but except test execution.


How to integrate with Eclipse
Now if you want to import this project into eclipse, it will not work. In eclipse you would not be able to import this project.
D:\Binod\Maven_Practice\CheckMaven> mvn eclipse:eclipse
It will create two file inside D:\Binod\Maven_Practice\CheckMaven folder. 1. .classpath and 2. .project. Now you can import into eclispe.

Open eclipse and set workplace is D:\Binod\Maven_Practice. File -> Import -> Import -> General -> Existing Projects into Workspace -> Browse (Select root directory, D:\Binod\Maven_Practice)then check CheckMaven -> Finish

Your project would be imported into workspace.
D:\Binod\Maven_Practice\CheckMaven> mvn eclipse:cleanIt will delete both generated file 1. .classpath and 2. .project.

D:\Binod\Maven_Practice\CheckMaven>mvn eclipse:clean eclipse:eclipse
Now we ensured that all previous eclipse resources are removed and generated again.
To let eclipse know where the local Maven 2 repository is located you should know where it is located. By default the Maven 2 repository is located at
/home/[USERNAME]/.m2/repositoryC:\Documents and Settings\sumankbi\.m2\repository
We should avoid avoid space in maven repository class path. Refer above settign to change local repository.

In Eclipse -> window -> Preferences -> Maven -> Installation -> User setting -> Browse -> D:\Software\apache-maven-3.0-alpha-7\conf\settings.xml then Local repository will be change as per the setting.xml and it become D:\.m2\repository.

Now check, In Eclipse -> window -> Preferences -> Java -> Build Path -> Classpath Variable -> M2_REPO shold be D:\.m2\repository.

mvn clean eclipse:clean eclipse:eclipse

Dependencies
Some dependencies often are needed to write your applications. Commonly we are using some open source libraries and frameworks (e.g. the spring application framework or apache commons-logging,...). Sometimes own libraries should be referenced by a java project. To solve this problem Maven delivers a very good dependency mechanism that manages the dependencies of your project transitivly.

How the maven download new jar file, if our project is needed for that jar file.
Maven will download all dependencies referenced by your pom.xml from the central Maven 2 repository automatically to local reposity (In my case D:\.m2\repository). Suppose my project is needed commons-logging jar file then put this jar info into pom.xml and run mvn package and watch console, maven will downloading this jar into your local repository.
You have to add commons-logging into pom.xml

<dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency>

Now complete pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; <modelVersion>4.0.0</modelVersion> <groupId>com.tecnotree.bds</groupId> <artifactId>CheckMaven</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>CheckMaven</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.5</version> <scope>test</scope> </dependency> </dependencies> <distributionManagement> <repository> <id>BinodprojectRepository</id> <name>Binod Maven Repository Name</name> <url>file:///d:/MyRemoteMavenRepository</url>
</repository> <!-- site> <id>sample-project.website</id> <url>dav:https://dav.sample.com/sites/sample-project</url> </site --> </distributionManagement>

</project>

Even I changed junit from 3.1 to 4.5. Now if I run mvn command (mvn clean package), it will download both jar file. You can watch d:\.m2\repository and console both.

Some more example

<dependency>
<groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>2.5.5</version> </dependency> <dependency>

<groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>2.5.5</version>
</dependency>

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>2.5.5</version> </dependency>

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>2.5.5</version> </dependency>

<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency>
</dependencies>

<dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency>

Properties : Same as Ant, we can set up any variable and use in the xml file.
In above example we are repeating same version number of all the spring jar file, so better put one place all the version number and use references. Use the properties tag.

<properties>
<spring-version>2.5.5</spring-version>
<junit-version>4.5</junit-version>
<commons-dbcp-version>1.2.2</commons-dbcp-version>
<commons-logging-version>1.1.1</commons-logging-version>
<mysql-version>5.1.6</mysql-version>
<servlet-version>1.1.2</servlet-version>
</properties>

<dependencies>
<!-- Spring Framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-version}</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-version}</version>
</dependency>

</dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${servlet-version}</version>
</dependency>

Scopes: The dependency scope defines to which part of the project's lifecycle the dependency is attached. For example the JUnit dependency is only added while running the tests. So i defined that this dependency is attached to the target "test".

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.5</version>
<scope>test</scope>
</dependency>
</dependencies>

There are at least 6 different scopes:
compile: This scope indicates the Maven compilation phase. It is the default scope that will be used if no scope is defined. provided: This scope defines that this dependency is provided by the container (e.g. Apache Tomcat) at runtime. runtime: This scope indicates that this Dependency isn't required in the compilation phase but it is needed at runtime. test: "test"-dependencies are only while compiling and running the tests. system: This scope indicates that the dependency is provided by the system.

ABOUT POM.XML
you must always think of a Maven POM in terms of the combinationof the Super POM, plus any parent POMs, and finally the current project’s POM. Maven starts with theSuper POM and then overrides default configuration with one or more parent POMs. Then it overridesthe resulting configuration with the current project’s POM.

Build element: it that handles things like declaring your project's directory structure and managing plugins; and the reporting element, that largely mirrors the build element for reporting purposes.

MultiProject in Maven

Create one folder say (MultiProjectCheck) D:\Binod\Maven_Practice\MultiProjectCheck
execute this command:
D:\Binod\Maven_Practice\MultiProjectCheck>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.mp -DartifactId=MultiProject

It will create MultiProject and put src and pom.xml.

Now go to pom.xml in D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject\pom.xmland change <packaging>jar</packaging> to <packaging>pom</packaging>.

By setting the packaging type to “pom”, any projects you generate from the root of the project directory will insert itself into the project by creating an entry into the modules section of the pom.xml for the site.

Now execute this below both command from MultiProject folder.

D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.mp -DartifactId=FirstSubModule

D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.mp -DartifactId=SecondModule

Now come to D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject\pom.xml (parent pom.xml), you will automatically added two module like this:

<modules>
<module>FirstSubModule</module> <module>SecondModule</module>
</modules>

You will see new tag in submodule pom.xml files.

<parent>
<artifactId>MultiProject</artifactId> <groupId>com.tecnotree.mp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>

Now if you run mvn test from parent folder

D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject
then it will create target forlder in both module. But if you run mvn test from insidet FirstSubModule folder then it will be creating only in this module, it wont effect on second module SecondModule.

How to import into Eclispe:

D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject>mvn eclipse:eclipse

Create workspace in eclipse D:\Binod\Maven_Practice\MultiProjectCheck\MultiProjectand import -> browse -> select D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject -> It will show both project, select both project and it will come to eclipse.

How to develop Maven site.
Maven site example.

come to D:\Binod\Maven_Practice
D:\Binod\Maven_Practice>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.mycompany.app -DartifactId=MavenSiteCheckand
execute this command to generate site folder inside src

D:\Binod\Maven_Practice>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-site -DgroupId=com.mycompany.app -DartifactId=MavenSiteCheck

go to D:\Binod\Maven_Practice\MavenSiteCheck\src\site\xdoc\xdoc.xml
Here you can write about your project.
Now,
D:\Binod\Maven_Practice\MavenSiteCheck>mvn site:site

It will create one target folder in D:\Binod\Maven_Practice\MavenSiteCheck.
One html file generate D:\Binod\Maven_Practice\MavenSiteCheck\target\site\xdoc.htmlyou can open this html file.

You can also run this page as web site using jetty
D:\Binod\Maven_Practice\MavenSiteCheck>mvn site:runURL: http://localhost:8080/xdoc.html

How you can put some picture here in documentcreate one resources inside the site folder (D:\Binod\Maven_Practice\MavenSiteCheck\src\site\resources) and put all your picutre here say suman.jpg

now come to xdoc.xml (D:\Binod\Maven_Practice\MavenSiteCheck\src\site\xdoc\xdoc.xml)
and write here <img src="suman.jpg"></img>
Now,
D:\Binod\Maven_Practice\MavenSiteCheck>mvn site:site

It will move all the images from D:\Binod\Maven_Practice\MavenSiteCheck\src\site\resources to D:\Binod\Maven_Practice\MavenSiteCheck\target\site.

now open D:\Binod\Maven_Practice\MavenSiteCheck\target\site\xdoc.html

Sunday, April 4, 2010

XML Handling in Groovy, XML with Groovy

Info.xml

<?xml version="1.0" ?>
<customers>
<corporate>
<customer name="Nik Kumar Suman" company="TecnoTree" />
<customer name="Pramod Kumar Modi" company="efi" />
<customer name="Mika" company="TecnoTree" />
</corporate>

<consumer>
<customer name="Nik" />
<customer name="Pramod" />
</consumer>

</customers>

ReadXML.gy

def customers = new XmlSlurper().parse(new File('Info.xml'))
for (customer in customers.corporate.customer){
println "${customer.@name} works for ${customer.@company}"
}

output:

D:\Nik\Groovy_Example>groovy ReadXML.gy
Nik Kumar Suman works for TecnoTree
Pramod Kumar Modi works for efi
Mika works for TecnoTree
D:\Nik\Groovy_Example>

Saturday, April 3, 2010

File Handling in Groovy

File Handling in Groovy

File handling in Groovy is made significantly easier with the addition of variousmethods to classes in the java.io package. A great example is the File.eachLine method.

FileHandle.gy

def number=0new File ('Nik.txt').eachLine {
line -> number++
println "$number: $line"
}

Nik.txt

My name is Ayush.
But you can call me Nik.
I am fully devoted to Java and want to something extra for java

Now run groovy file

D:\Nik\Groovy_Example>groovy FileHandle.gy
1: My name is Ayush.
2: But you can call me Nik.
3: I am fully devoted to Java and want to something extra for java

D:\Nik\Groovy_Example>

Friday, April 2, 2010

javax.script how to use, groovy with java, java ScriptEngineManager, java ScriptEngine

Browse this URL for groove fundamental and getting started with groovy

Java 6 includes built-in support for JSR 223: Scripting for the Java Platform API classes. This framework can be used to host Script Engines in Java Applications.

Here is the code to how to use groovy script inside the java code

EvalScriptFile.java

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.io.File;
import java.io.Reader;
import java.io.FileReader;
import java.io.FileNotFoundException;

public class EvalScriptFile {

public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("groovy");


try {
File script = new File("D:\\Nik\\Groovy_Example\\Second.gy");
Reader reader = new FileReader(script);
engine.eval(reader);
} catch (FileNotFoundException e) {
System.out.println("SOME ERROR 1 :: "+e);
e.printStackTrace();
} catch (ScriptException e) {
System.out.println("SOME ERROR 2 :: "+e);
e.printStackTrace();
}

}
}

Second.gy

class HelloWorld {

def name

def greet() { "Hello ${name}" }
}
def helloWorld = new HelloWorld()
helloWorld.name = "My name is groovy TEST "
println helloWorld.greet()


This below example is showing calling an invokable function:


import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.Invocable;

public class Factorial {
public static void main(String[] args) throws Exception {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("groovy");
String fact = "def factorialFun(n) { n == 1 ? 1 : n * factorialFun(n - 1) }";
engine.eval(fact);
Invocable inv = (Invocable) engine;
Object[] params = { new Integer(6) };
Object result = inv.invokeFunction("factorialFun", params);
System.out.println("The factorial of 6 is "result);
}
}

You will get result after run is
The factorial of 6 is 720









Groovy Getting started, How use groovy in Java, Groovy easy example, Groovy fundamental

What is Groovy?

The Groovy web site (http://groovy.codehaus.org/) gives one of the best definitionsof Groovy: “Groovy is an agile dynamic language for the Java Platform with manyfeatures that are inspired by languages like Python, Ruby and Smalltalk, makingthem available to Java developers using a Java-like syntax.

Everything you do in Groovy could be done in Java, it would be madness to writethe Java code required to work Groovy’s magic. Groovy performs a lot of workbehind the scenes to achieve its agility and dynamic nature.

The Groovy solution is short, precise, and more compact than normal Java. Groovy does not need to import the java.util package or specify the Date type;moreover, Groovy doesn’t require semicolons when it can understand the code without them.


import java.util.*; // Java
Date today = new Date(); // Java

today = new Date() // Groovy

How to install Groovy.

1. Download groovy-src-1.7.0.zip from
http://dist.codehaus.org/groovy/distributions/
2. Unzip this file and put any where in your pc. I have put at D:\Software\Groovy\groovy-1.7.0
3. Add a new System variable with the name GROOVY_HOME and the value of the directory groovy was installed in (In my case it is D:\Software\Groovy\groovy-1.7.0
4. add %GROOVY_HOME%\bin to your system path
5. Now open any dos window and type groovy. If every this is correct then you will get some opetion otherwise you will get error message like 'groovy' is not recognized as an internal or external command,operable program or batch file.

REF:
http://groovy.codehaus.org/Tutorial+1+-+Getting+started

Make one directory to put your all example code. In my case D:\Nik\Groovy_Example

FIRST GROOY CODE

HelloWorld.groovy

class HelloWorld
{
static main( args )
{ println "Hello World!" }
}

How to compile groovy file
Open dos window and navigate to D:\Nik\Groovy_Example
D:\Nik\Groovy_Example>groovyc HelloWorld.groovy
D:\Nik\Groovy_Example>

Now you will check one new class file (HelloWorld.class) has been generate in this folder (D:\Nik\Groovy_Example).

How to run the groovy class
D:\Nik\Groovy_Example>groovy HelloWorldHello World!
D:\Nil\Groovy_Example>
Even without compile the code you can direct use groovy command to run the code Like

D:\Nik\Groovy_Example>groovy HelloWorldor
D:\Nik\Groovy_Example>groovy HelloWorld.groovy

you can also use extension like gv or groovy

Here below, I am giving one java code and after that will convert same java code to Groovy

Second.java

public class Second {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() { return name; }
public String greet() { return "Hello " + name; }

public static void main(String[] args) {
Second second = new Second();
second.setName("My name is groovy");
System.out.println(second.greet());
}
}

Second.gy

class HelloWorld {
def name
def greet() { "Hello ${name}" }
}
def helloWorld = new HelloWorld()
helloWorld.name = "My name is groovy"
println helloWorld.greet()


NOTE: Groovy is an Object-Oriented language (a real one where numbers are also objects), and it supports the same programming model as Java. However, it's also a scripting language as it allows you to write some free form programs that don't require you to define a class structure. So in the last step of this tutorial, we're going to get rid of the main method altogether.

Both will give the same output.

D:\Nik\Groovy_Example>javac Second.java
D:\Nik\Groovy_Example>java SecondHello My name is groovy

D:\Nik\Groovy_Example>groovy Second.gyHello My name is groovy
D:\Nik\Groovy_Example>

Ref:
http://groovy.dzone.com/news/java-groovy-few-easy-steps

How to run groovy script using java program

Secong.gy

class HelloWorld {
def name
def greet() { "Hello ${name}" }
}

def helloWorld = new HelloWorld()
helloWorld.name = "My name is groovy TEST "
println helloWorld.greet()

GroovyTest.java

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import java.io.File;

public class GroovyTest {

public static void main(String[] args) throws Exception{
System.out.println("THIS IS FIRST GROOVY PROGRAM");
new GroovyTest().GroovyRun();
}

public void GroovyRun()throws Exception{
ClassLoader parent = getClass().getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);
Class groovyClass = loader.parseClass(new File("D:\\Nik\\Groovy_Example\\Second.gy"));
// let's call some method on an instance
GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
Object[] args = {}; groovyObject.invokeMethod("main", args);
}
}

D:\Nik\Groovy_Example>javac GroovyTest.java
D:\Nik\Groovy_Example>java GroovyTest
THIS IS FIRST GROOVY PROGRAMHello My name is groovy TEST

D:\Nik\Groovy_Example>