Create a new Groovy project using maven

Posted on Updated on

This is a first exercise of writing a groovy program in IntelliJ IDE. See the first post of What is Groovy here?

Below is the complete example of Groovy using maven setup.

  • Create a folder as Project name i.e GroovyExample in your project folder.
  • Create an XML ( pom.xml )file under GroovyExample folder and named it as pom.xml.
  • Copy and paste the content of pom.xml as given inline below.
  • Open IntelliJ IDE and Click on File-> Open and select pom.xml file under GroovyExample folder by navigating it through.
  •  While importing all dependencies in given pom.xml into your project then you can start writing Groovy program.
  • Right click on Project and Create a directory i.e /src/main/groovy under which all groovy file will be placed.
  • Next, Select /groovy folder and right-click to create a new Groovy file.
  • Give proper groovy file name and click OK.
  • A Groovy file will be open then continue with Groovy code as given.

Maven POM.xml file

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">

    <description>Demo project for Groovy Example</description>



Groovy file here :-



What is Groovy?

Posted on Updated on


What is Groovy?

Groovy is an optionally Typed, Dynamically language that runs on JVM. It is tightly integrated with the Java Language and its feature is enabled as rich and  Java friendly.

Groovy supports standard Java constructs including annotations, generics, static imports, enums, varargs and lambda expression.

Groovy source code is compiled into Java byte-code by the Groovy compiler. To run Groovy code in a Java virtual machine, only the Groovy JAR file must be present in the classpath at runtime.

A Groovy source files ends with the .groovy extension. This file can contain a Groovy script or a Groovy class.

Compatibility with Java

Groovy runs on the JVM and can use Java libraries. Every Groovy type is a subclass ofjava.lang.Object.

Groovy does currently not support Java 8 lambda expressions.

Reasons to use Groovy

Groovy focus on simplicity and very productive.

  • Simplification : – Groovy does not require a semicolon to terminate the line. return type can be omitted, by default Groovy return the last expression of the line as return type. public keyword can be omitted, it is a Default in Groovy, Also it allows optional typing.
  • Ease of use – Groovy has list, maps and regular expressions directly build into the language.
  • Simplification in I/O – parsing and creating XML, JSON and files are very simple with Groovy.
  • Flexibility – Groovy allows to change classes and methods at runtime, e.g. if a method is called which does not exist on a class, the class can intercept this call and react to it. This allows for example that Groovy provides a very flexible builder pattern.
  • Easy to use : – Groovy has list, maps and regular expressions directly build into the language.
  • Simplification in I/O – parsing and creating XML, JSON and files are very simple with Groovy.

Setup Groovy in IntelliJ:-

Steps to follow to install Groovy in you IntelliJ.

  • Open IntellJ IDE.
  • Go to File->Settings -> plugin
  •  Choose Groovy in plugin Text box and install.
  • Once Groovy get installed in your IDE, then you will able to create a Groovy file and run it.
  • groovy-setup


Exercise :-


JSON Schema Validation example in java

Posted on

Validating input is a good programming practice than spending times to trying to guard each line of codes against all the way the input goes wrong.

This is especially true when we are writing a web service that deal with input data of a PUT,POST,DELETE and GET method with MIME type JavaScript Object Notation (JSON) .  JSON data is formatted as a key & value pair and each key & value represent a properties name and value separated by the colon (:).

In last post, we have seen the Jackson framework that is used to marshaling and unmarshalling the JSON data to Java object and vice-versa, But validating JSON data is another task, unfortunately Jackson framework does not  provide to do validate JSON data.

json-schema-validator available at https://github.com is quite popular with Java developer to validate JSON data against Schema file.

JSON schema is:

  • A way of describing your existing data format
  • Written in clear, human and machine readable, documentation
  • Complete structural validation useful for
    • Automated testing
    • Validating client submitted data

Look at the below Schema file. This schema file exactly tells, in Input JSON data , “id” must be String type, “amount” properties must be any Number type and “Currency” must be out of four currency else throw validation exception. As you can created own Schema file base on the incoming input date.


trade-schema.json under /src/main/resources/schema folder

  "title": "Daily Trade Transaction",
  "description": "Daily Trade Transaction",
  "type": "object",
  "properties": {
      "enum":["INR", "HKD", "EUR", "USD"]

ref link:-
validate Schema online :-

Let’s build a simple Application :-

trade.json :- Input data store in a file.



JsonSchemaManager.Java : Used to validate all Java Object with specific Schema.

package com.example.utilities;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.RuntimeJsonMappingException;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.core.report.ProcessingMessage;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.main.JsonValidator;
import com.google.common.collect.Lists;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static javafx.scene.input.KeyCode.J;

 * Created by MYPC on 7/17/2016.
public class JsonSchemaManager {
    private final JsonValidator validator = JsonSchemaFactory.byDefault().getValidator();
    private Map<Class<?>, JsonNode> jsonNodeMap = new HashMap<>();

    public void load(Class<?> className, String schema) throws IOException {
        JsonNode schemaFromDisk = JsonLoader.fromURL(this.getClass().getResource(schema));
        jsonNodeMap.put(className, schemaFromDisk);

    public void check(Class<?> className, JsonNode toBeValidate) {

        ProcessingReport report = null;
        try {
            report = validator.validate(jsonNodeMap.get(className), toBeValidate);
            if (!report.isSuccess()) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(" Oops!! failed JSON validation ");
                List messages = Lists.newArrayList(report);

                for (int i = 0; i < messages.size(); i++) { stringBuilder.append("- "); stringBuilder.append(messages.get(i).toString()); stringBuilder.append((i == (messages.size()) - 1) ? "" : "\r"); } throw new RuntimeException(stringBuilder.toString()); } } catch (ProcessingException e) { throw new RuntimeJsonMappingException("ERROR -->" + e.toString());

Main Class that validate the JSON data.

package com.example;

import com.example.model.Transaction;
import com.example.service.CSVReader;
import com.example.utilities.JsonSchemaManager;
import com.fasterxml.jackson.databind.JsonNode;

import java.io.IOException;
import java.util.List;

 * Created by MYPC on 7/18/2016.
public class JSONSchemaReaderApp {

    public static void main(String[] args) throws IOException {

        JsonSchemaManager jsonSchemaManager = new JsonSchemaManager();
        CSVReader csvReader = new CSVReader();
        // Load schema file from resource folder.
        jsonSchemaManager.load(Transaction.class, "/schema/trade-schema.json");
        // Load JSON data from file system and convert into JsonNode Object
        List lists = csvReader.load(Transaction.class, JSONSchemaReaderApp.class.getClassLoader().getResource("trade.csv"));
        for (int i = 0; i < lists.size(); i++) {
            //validate each JsonNode of Type Transaction to Schema file.
            jsonSchemaManager.check(Transaction.class, lists.get(i));

complete src download here


Difference between WHERE vs HAVING clause in SQL

Posted on Updated on

MySQLThis is frequently asked questions in Database interview , .Net interview and Java Interview. Developer should know the basic differences of these two clauses in SQL.

Where” clause is used for selection a row or set of rows from table, base on criteria like primary key or other column fields table rows get retrieved. It can be used in update, delete and select statement base on the criteria or more than one criteria.

Having” clause used with aggregate function that is work over Group by selection, Having clause always followed by Group by clause or it does not perform like where clause. It boosts the better performance by avoiding unnecessary column sorting and grouping

Aggregate Function below:- 

  • AVG() – Returns the average value
  • COUNT() – Returns the number of rows
  • FIRST() – Returns the first value
  • LAST() – Returns the last value
  • MAX() – Returns the largest value
  • MIN() – Returns the smallest value
  • SUM() – Returns the sum

Difference between WHERE vs HAVING

  1. The WHERE clause specifies the criteria which individual records must meet to be selected by a query. It can be used without the GROUP BY clause. The HAVING clause cannot be used without the GROUP BY clause.
  2. The WHERE clause selects rows before grouping. The HAVING clause selects rows after grouping.
  3. The WHERE clause cannot contain aggregate functions. The HAVING clause can contain aggregate functions.
  4. The WHERE clause is used in any DML form like Select, Update and Delete Query while Having clause can be only used with Select statement.
  5. The Where clause can be applied individual row while Having clause can be applied only a group of rows.

Note: Having and Where clause can not be used together.


SQL Interview Question

Posted on Updated on





Concatenate multiple row into a single row :


This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values. The full syntax is as follows:

GROUP_CONCAT([DISTINCT] expr [,expr …] [ORDER BY {unsigned_integer | col_name | expr} [ASC | DESC] [,col_name …]] [SEPARATOR str_val])

mysql>SELECT NAME, reminder_date,STATUS FROM enquiry;











 Find nth largest Salary in Employee Table:-

Select all Employee rows by Salary descending order.

 mysql>SELECT * FROM employee ORDER BY salary DESC;






Fetch 4th largest salary holder Employee :-

syntax : 

select * from <table-name> t2 where ( n-1 ) = ( select count(distinct(<t2>.<column-name>)) from <table-name> t2 where t2.salary > t1.salary);

example :-

         mysql>SELECT * FROM employee e1
WHERE  (4-1) = ( SELECT COUNT(DISTINCT(e2.salary)) FROM employee e2 WHERE                                      e2.`salary` >   e1.`salary`)



Design patterns usage in Java SE and Java EE

Aside Posted on Updated on




GoF Design patterns used in Java & J2EE.

Creational patterns

Abstract factory (recognizeable by creational methods returning the factory itself which in turn can be used to create another abstract/interface type)

Builder (recognizeable by creational methods returning the instance itself)

Factory method (recognizeable by creational methods returning an implementation of an abstract/interface type)

Prototype (recognizeable by creational methods returning a different instance of itself with the same properties)

Singleton (recognizeable by creational methods returning the same instance (usually of itself) everytime)

Structural patterns

Adapter (recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own/another abstract/interface type which decorates/overrides the given instance)

Bridge (recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own abstract/interface type which delegates/uses the given instance)

  • None comes to mind yet. A fictive example would be new LinkedHashMap(LinkedHashSet<K>, List<V>) which returns an unmodifiable linked map which doesn’t clone the items, but usesthem. The java.util.Collections#newSetFromMap() and singletonXXX() methods however comes close.

Composite (recognizeable by behavioral methods taking an instance of same abstract/interface type into a tree structure)

Decorator (recognizeable by creational methods taking an instance of same abstract/interface type which adds additional behaviour)

Facade (recognizeable by behavioral methods which internally uses instances of different independent abstract/interface types)

Flyweight (recognizeable by creational methods returning a cached instance, a bit the “multiton” idea)

Proxy (recognizeable by creational methods which returns an implementation of given abstract/interface type which in turn delegates/uses a different implementation of given abstract/interface type)

The Wikipedia example is IMHO a bit poor, lazy loading has actually completely nothing to do with the proxy pattern at all.

Behavioral patterns

Chain of responsibility (recognizeable by behavioral methods which (indirectly) invokes the same method inanother implementation of same abstract/interface type in a queue)

Command (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been encapsulated by the command implementation during its creation)

Interpreter (recognizeable by behavioral methods returning a structurally different instance/type of the given instance/type; note that parsing/formatting is not part of the pattern, determining the pattern and how to apply it is)

Iterator (recognizeable by behavioral methods sequentially returning instances of a different type from a queue)

Mediator (recognizeable by behavioral methods taking an instance of different abstract/interface type (usually using the command pattern) which delegates/uses the given instance)

Memento (recognizeable by behavioral methods which internally changes the state of the whole instance)

Observer (or Publish/Subscribe) (recognizeable by behavioral methods which invokes a method on an instance of another abstract/interface type, depending on own state)

State (recognizeable by behavioral methods which changes its behaviour depending on the instance’s state which can be controlled externally)

Strategy (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been passed-in as method argument into the strategy implementation)

Template method (recognizeable by behavioral methods which already have a “default” behaviour definied by an abstract type)

Visitor (recognizeable by two different abstract/interface types which has methods definied which takes each the otherabstract/interface type; the one actually calls the method of the other and the other executes the desired strategy on it)