Friday, March 3, 2017

Java 8 New Features - Introduction

INTRODUCTION

Java 8 came up with a lot of enhancements. Features like Lambda Expression and Streams plays a major role on simplicity and maintainable code.
This post aims to provide the outline of Java 8 new features.
  1. Lambda Expressions
  2. Functional Interfaces
  3. Method References
  4. Streams
  5. Interface Enhancements
  6. Collection Enhancements
  7. Date & Time API Enhancements

LAMBDA EXPRESSIONS

  • Lambda expression enables functional programming in java which is not present till Java 8
  • Simplifies the code and removes unwanted codes(boilerplate codes).
  • @FunctionalInterface annotation helps to create our own Functional Interfaces. A functional interface can contain only one method. An example is a Runnable Interface.
  • Syntax : argument(s) -> expression
  • Lambda expression can be defined without argument, one argument or multiple arguments
  • without argument
MyLambda myLambda = () -> System.out.println("Test");
myLambda.foo();
  • one argument
(a) -> System.out.println(a);
  • multiple argument
MyMath add = (a, b) -> a + b;
System.out.println("Sum is: " + add.calc(8, 4));

FUNCTIONAL INTERFACES

  • Functional Interfaces are the java interfaces which will contain only one method.
  • In Java 8, new package java.util.function has been introduced.
  • Main interfaces are:
    • Function - assignment for any lambda expressions
    • Predicate
    • Consumer
    • Supplier

METHOD REFERENCES

  • Method reference help to access the public & non-static method of any class.
  • Syntax : Class::method
  • Example: mylist.forEach(System.out::println)

STREAMS

  • Streams are functional style.
  • Mainly process the list of elements of any type.
  • In Java 8, new package java.util.stream has been introduced.
  • Main classes & Interfaces are
    • Stream
    • Collector
    • Collectors
  • Streams are processed without or multiple intermediate operations (intermediate streams) and terminal operations (final output).
  • Intermediate operations are lazy operations which mean it will accept the input and wait for processing till the terminal operation is encountered. Example operations are
    • filter
    • map
    • mapToInt
  • Terminal operations are
    • sum
    • average
    • min
    • max

INTERFACE ENHANCEMENTS

  • Java 8 provides another interesting feature in the interface like having concrete methods in it.
  • concrete methods in the interfaces are either static or default access modifier.
Example:

public interface Test {
 void food();
 
 default void speak() {
   System.out.println("i can't speak :(");
 }
 
 default double average() {
          return 20 / 5;
 }
 
 static void fly() {
   System.out.println("i can't fly :(");
 }
 
 static int add() {
   return 5 + 4;
 }
 
 static List<String> cities() {
   return Arrays.asList("Chennai", "Mumbai", "Bangalore");
 }
}

Hope this post gives a brief introduction to Java 8 new features and enhancements.
Please share your thoughts in the comment box.
Happy Knowledge Sharing!!!

Wednesday, March 1, 2017

Cannot change version of project facet Dynamic Web Module to 3.0

INTRODUCTION

We may get this error on any of the below cases.
  1. Creating a new Dynamic Web Project
  2. New Maven Maven Project
  3. Importing existing maven project.
Following are the different solution for this issue.

SOLUTION - 1

  1. Select your project
  2. Right click and go to Properties->Project Facets->Change the version 3.0 for Dynamic Web Module & also select Java version higher than JDK 6.
  3. Apply & OK

SOLUTION - 2

If it is a maven project, just add the below to your pom.xml
<build>
 <plugins>
     <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
<source>1.8</source>
<target>1.8</target>
    </configuration>
  </plugin>
 </plugins>
</build>


SOLUTION - 3

  1. Go to project root folder in your local disk
  2. Go to .settings folder
  3. Open org.eclipse.wst.common.project.facet.core.xml file and change the below
<installed facet="jst.web" version="3.0"/>
  1. Restart the Eclipse and Update your Maven Project.

SOLUTION - 4

  1. Go to web.xml and update the <web-app> below.
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   version="3.0">


  1. Clean the Project & Update your Maven Project.
Hope any of the above solutions will resolve this issue.

Happy Knowledge Sharing!!!

Thursday, August 4, 2016

H2 DB with Java Example

INTRODUCTION

  • H2 Database Engine is very fast, open source and lightweight.
  • It is another Java Database and it's completely written in java.
  • It is an in-memory database.
  • Easy installation.
  • Tables can be created in an in-memory or local disk.

SOFTWARES & TOOLS

  1. H2 DB
  2. Eclipse IDE (Mars 2)
  3. SQL-Workbench

INSTALLATION

  1. Download latest H2 DB Installer from http://www.h2database.com/html/main.html
  2. Install the DB to your local drive: C:\ranjiths\jbr\InstalledSofties\H2

CREATE DATABASE & TABLES

Unlike other Open Source In-Memory Database, there is no default DB Editor Tool within H2. So download SQL-WorkBench and install for running the SQL Queries.

Now, Open the SQL-WorkBench and enter below details to create a new connection.
  1. Default Group Name : JBR
  2. Driver : Select H2 Database(org.h2.Driver)
  3. URL: jdbc:h2:C:/ranjiths/jbr/InstalledSofties/h2db/db
  4. Username : ranjith
  5. Password : sekar
Click OK

Create a table and insert some data.
CREATE TABLE users (
 user_id INTEGER NOT NULL CONSTRAINT EMP_NO_PK PRIMARY KEY,
 first_name VARCHAR(30) NOT NULL,
 last_name VARCHAR(30) NOT NULL,
 email VARCHAR(40),
 phone INTEGER
   );

INSERT INTO users VALUES(1,'Ranjith','Sekar','ranjith@gmail.com',96000);
INSERT INTO users VALUES(2,'Manoj','Kumar','manoj@gmail.com',88000);
INSERT INTO users VALUES(3,'Sachin','Tendulkar','sachin@gmail.com',77000);

EXAMPLE JAVA PROGRAM

  1. Create a Java Project in Eclipse
  2. Add C:\ranjiths\jbr\InstalledSofties\H2\bin\h2-1.4.192.jar into the project classpath.

package jbr.h2db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class H2DBExample {
 public static void main(String[] args) {
   Connection connection = null;
   ResultSet resultSet = null;
   Statement statement = null;
   String URL = "jdbc:h2:c:/ranjiths/jbr/InstalledSofties/h2db/db";
   String username = "ranjith";
   String password = "sekar";
   try {
     Class.forName("org.h2.Driver");
     connection = DriverManager.getConnection(URL, username, password);
     statement = connection.createStatement();
     resultSet = statement.executeQuery("SELECT * FROM users");
     while (resultSet.next()) {
       System.out.println("User Name: " + resultSet.getString("FIRST_NAME")
+ " " + resultSet.getString("LAST_NAME"));
     }
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       resultSet.close();
       statement.close();
       connection.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }

HSQLDB With Java Example

INTRODUCTION

  • HSQLDB is called Hyper SQL Database and it is completely written in java.
  • Supports for embedding with java application as well as server mode.
  • Tables can be created in an in-memory or local disk.
  • It is 100% free and used in many of open source projects.

SOFTWARES & TOOLS

  1. HSQLDB
  2. Eclipse IDE (Mars 2)
  3. HSQLDB in-built DB Editor (Swing Based Application)

INSTALLATION

  1. Download latest HQLDB from https://sourceforge.net/projects/hsqldb/
  2. Unzip and copy to your local drive: C:\ranjiths\CommonSofties\hsqldb-2.3.4

CREATE DATABASE & TABLES

Go to C:\ranjiths\CommonSofties\hsqldb-2.3.4\bin and Click runManagerSwing.bat
Swing based Application will be opened and enter below details.

  1. Setting Name: JBR
  2. Type : HSQL Database Engine In-Memory
  3. Driver: org.hsqldb.jdbcDriver
  4. URL: jdbc:hsqldb:file:C:\ranjiths\jbr\hsqldb\db
  5. User: ranjith
  6. Password: sekar

Click OK

Create a table and insert some data.
CREATE TABLE users (
 user_id INTEGER NOT NULL CONSTRAINT EMP_NO_PK PRIMARY KEY,
 first_name VARCHAR(30) NOT NULL,
 last_name VARCHAR(30) NOT NULL,
 email VARCHAR(40),
 phone INTEGER
 );

INSERT INTO users VALUES(1,'Ranjith','Sekar','ranjith@gmail.com',96000);
INSERT INTO users VALUES(2,'Manoj','Kumar','manoj@gmail.com',88000);
INSERT INTO users VALUES(3,'Sachin','Tendulkar','sachin@gmail.com',77000);

EXAMPLE JAVA PROGRAM

  1. Create a Java Project in Eclipse
  2. Add all jars from C:\ranjiths\CommonSofties\hsqldb-2.3.4\lib into the project’s classpath.

package jbr.hsqldb;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class HSQLDBExample {
 public static void main(String[] args) {
   Connection connection = null;
   ResultSet resultSet = null;
   Statement statement = null;
   try {
     Class.forName("org.hsqldb.jdbcDriver");
     connection = DriverManager.getConnection("jdbc:hsqldb:file:
                  c:/ranjiths/jbr/hsqldb/db", "ranjith", "sekar");
     statement = connection.createStatement();
     resultSet = statement.executeQuery("SELECT * FROM users");
     while (resultSet.next()) {
       System.out.println("User Name: " + resultSet.getString("FIRST_NAME") \
            + " " + resultSet.getString("LAST_NAME"));
     }
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       resultSet.close();
       statement.close();
       connection.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
}