Features of Java8 explained

Hi all time is passing so fast that Oracle has published its road map for “Java 9”, now in this post let me explain the best features that are available in Java 8.
Java 8 allow us to write a non abstract methods inside the interface by utilizing the keyword “default” below is the code snippet.

/**
 * 
 */
package com.spark.java8.tutorial.interfaces;

/**
 * @author Sony
 *
 */
public interface ICalculator {

	double getSquareOf(double a);
	
	default double getSquareRoot(double a){
		return Math.sqrt(a);
	}
}

The implementation of the above said interface can be done as shown below.

/**
 * 
 */
package com.spark.java8.tutorial.interfaces.impl;

import com.spark.java8.tutorial.interfaces.ICalculator;

/**
 * @author Sony
 *
 */
public class MyCalculator implements ICalculator {

	/* (non-Javadoc)
	 * @see com.spark.java8.tutorial.interfaces.ICalculator#getSquareOf(double)
	 */
	@Override
	public double getSquareOf(double a) {
		return a*a;
	}

}

To test the above implementation and default implementation method of interface, write the below code in main class and run.

                MyCalculator myCalculator = new MyCalculator();
		double result1 = myCalculator.getSquareOf(10);
		System.out.println(result1);
		double result2 = myCalculator.getSquareRoot(4);
		System.out.println(result2);

Let us start with Lambda Expression: let us have a look at how to sort a list of strings in prior versions of Java

List<String> names = Arrays.asList("Vishal","Keshav","Pavan Kumar","Sudheer","Achary","Kranthi","Deepak");
		
		Collections.sort(names,new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return o2.compareTo(o1);
			}
		});
		System.out.println(names);

Instead of creating anonymous objects all day long, Java 8 comes with a much shorter syntax, lambda expressions:

Collections.sort(names, (String a, String b) -> {
    return b.compareTo(a);
});

the above code can be more simplified as follows.

Collections.sort(names, (String a, String b) -> b.compareTo(a));

For single line method bodies you can skip braces {} and the return keyword. the above can be made still more shoter as below.

Collections.sort(names, (a,b) -> a.compareTo(b));
		System.out.println(names);

Functional Interfaces:
An interface with only one abstract method is called functional interface. Java 8 provides us with an annotation called @FunctionalInterface to make any interface as functional interface, also in java 8 we can pass Method and Constructor references to functional interfaces below are the code snippets which demonstrate this concept.

/**
 * 
 */
package com.spark.java8.tutorial.interfaces;
/**
 * @author Sony
 *
 */
@FunctionalInterface
public interface Converter<F,T> {
	T convert(F from);
}

CharecterOperations.java

/**
 * 
 */
package com.spark.java8.test;

/**
 * @author Sony
 *
 */
public class CharecterOperations {

	public String getFirstChar(String str){
		return String.valueOf(str.charAt(0));
	}
}

using the above interface and class definition we can do something as below.

Converter<String, Integer> converter = Integer::valueOf;
		Integer value = converter.convert("123");
		System.out.println(value+10);

CharecterOperations charecterOperations = new CharecterOperations();
		Converter<String, String> converter2 = charecterOperations::getFirstChar;
		String val = converter2.convert("Java8");
		System.out.println(val);

There are lot many features available in Java 8 like “Scopes in lambda Expressions”, “Built in Functional Interfaces”, “Streams in Collections” and many more let us look them in my next post.

Happy Coding 🙂
Happy Java 8.

WebSockets in HTML5 and JBoss

Hi all, its a long time i put my pen in the blog, these days got little busy with my little kid, however i took little time to write about the next-generation client(browser) server communication using WebSockets. In the advent of HTML5 technology all the modern browser are capable of talking to latest servers using WebSockets API.

Web Sockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers.

Once you get a Web Socket connection with the web server or an Application Server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler.

All the latest Web Servers and Application Servers has got implementation of WebSockets API as this is been included as part of JavaEE stack.

Let us look at the simple application which i created using JBoss Wildfly 8.1 and Maven

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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spark.websockets</groupId>
	<artifactId>WebSocketsExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>WebSocketsExample</name>
	<description>WebSocketsExample</description>

	<dependencies>
		<dependency>
			<groupId>org.jboss.spec.javax.websocket</groupId>
			<artifactId>jboss-websocket-api_1.0_spec</artifactId>
			<version>1.0.0.Final</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

once all the required and dependent jars got downloaded, let us code with our java server side handler class.
WebSocketHandler.java

/**
 * 
 */
package com.spark.websockets.handler;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 * @author Sony
 *
 */
@ServerEndpoint("/hello")
public class WebSocketHandler {

	@OnMessage
	public String onMessage(String message){
		System.out.println("-------------------------> Received : "+message);
		return "Response from Server ";
	}
	
	@OnOpen
	public void onOpenConnection(Session session){
		System.out.println("---------------------> Web Socket Connection Opened : "+session.getId());
	}
	
	@OnClose
	public void onCloseConnection(CloseReason closeReason){
		System.out.println("--------------> Close Reason : "+closeReason.getReasonPhrase());
	}

}

Once we are done with our java handler, let us start with our html and java script as below.
index.html

<html>
    <head>
        <title>HelloWorld Web sockets</title>
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
    </head>
    <body>
        
        <script language="javascript" type="text/javascript">
            var wsUri = getRootUri() + "/WebSocketsExample/hello";
            function getRootUri() {
                return "ws://" + (document.location.hostname == "" ? "localhost" : document.location.hostname) + ":" +
                        (document.location.port == "" ? "8080" : document.location.port);
            }
            function init() {
                output = document.getElementById("output");
            }
            function send_message() {
                websocket = new WebSocket(wsUri);
                websocket.onopen = function(evt) {
                    onOpen(evt)
                };
                websocket.onmessage = function(evt) {
                    onMessage(evt)
                };
                websocket.onerror = function(evt) {
                    onError(evt)
                };
                websocket.onclose = function (evt) {
                	cloaseConnection();
                };
            }
            function onOpen(evt) {
                writeToScreen("Connected to Endpoint!");
                doSend(textID.value);
            }
            function onMessage(evt) {
                writeToScreen("Message Received: " + evt.data);
            }
            function onError(evt) {
                writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
            }
            function doSend(message) {
                writeToScreen("Message Sent: " + message);
                websocket.send(message);
            }
            function cloaseConnection(){
            	writeToScreen("Closing Connection"+message);
            	websocket.close("closing socket !")
            }
            function writeToScreen(message) {
                var pre = document.createElement("p");
                pre.style.wordWrap = "break-word";
                pre.innerHTML = message;
                output.appendChild(pre);
            }
            
            window.addEventListener("load", init, false);
        </script>
        <h2 style="text-align: center;">Hello World WebSocket Client</h2>
        <br>
        <div style="text-align: center;">
            <form action="">
                <input onclick="send_message()" value="Send" type="button">
                <input id="textID" name="message" value="Hello WebSocket!" type="text"><br>
                <input onclick="closeConnection()" value="Close Connection" type="button">
            </form>
        </div>
        <div id="output"></div>
</body>
</html>

finally we are done with our coding part and ready for deployment, please deploy the war file in JBoss Wildfly 8.1 and hit http://localhost:8080/WebSocketsExample/ in the browser and start playing with web sockets.

Happy WebSockets, Happy Coding 🙂