Java · RESTFul · Spring · spring boot · Swagger

Swagger docs for Spring Boot

Spring boot is becoming famous and famous due to microservice architecture and advantage of spring framework support in it.As REST services are playing a huge role in microservice architecture, swagger introduces a better way to publish these REST services so that they can be tested, published as living documents.

Here is a simple spring boot application having a controlled on it. This controlled exposes a REST services. And this RESt service has been documented using SWAGGER with some simple annotations.

Most of the code is self-explanatory.

Git Link for Code

Run the code using >mvn spring-boot:run

and Access the swagger UI at http://localhost:8080/swagger-ui.html

Java · Java8

Recursive Action Task in Fork/Join Framework

Recursive Task is useful where the tasks are independent and caller is not expecting any return result from the task.

Note: make sure that you are waiting to complete the first task. i.e (action.isDone() check)

RecursiveTask

Here is the example which illustrates the Recursive Task

A Main program to start pool and first task,

/**
 * 
 */
package forkjoin;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

/**
 * @author prabhu kvn
 *
 */
public class EvenNumberFinderMain_Action {

 public static void main(String args[]) {

 // Mock Data: crate an array of 100 numbers
 List a = new ArrayList();

 for (int i = 0; i < 100; i++) {
 a.add(i);
 }
 // Initialize the Thread Pool
 ForkJoinPool pool = new ForkJoinPool(12);
 EvenNumberFinderAction action = new EvenNumberFinderAction(a);
 pool.execute(action);

 do {
 /*System.out.println("****************Pool****************");
 System.out.println("Parallesim:" + pool.getParallelism());
 System.out.println("Pool size:" + pool.getPoolSize());
 System.out.println("Active Thread count:" + pool.getActiveThreadCount());
 System.out.println("Queed Submission count:" + pool.getQueuedSubmissionCount());
 System.out.println("Qued Task count:" + pool.getQueuedTaskCount());
 System.out.println("Running Thread count:" + pool.getRunningThreadCount());
 System.out.println("Seal count:" + pool.getStealCount());*/

 } while (!action.isDone());
 System.out.println("Main thread One");
 pool.shutdown();
 System.out.println("Main thread Two");

 }
}

And RecusriveAction Class implementation,

package forkjoin;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveAction;
import java.util.stream.Collectors;

public class EvenNumberFinderAction extends RecursiveAction{

/**
*
*/
private static final long serialVersionUID = 1L;

List a=null;

public EvenNumberFinderAction() {
}

public EvenNumberFinderAction(List a) {
this.a=a;
}
@Override
protected void compute() {
// TODO Auto-generated method stub
List taskList = new ArrayList();
List subList=null;
List evenList = new ArrayList();
/*
* See if the list is greater than 10. if so divide the task.
*/
if(a.size()>10){
subList = a.subList(0, 10);
List remaining = a.subList(10, a.size());
EvenNumberFinderAction task = new EvenNumberFinderAction(remaining);
task.fork();
taskList.add(task);
}else{
subList=a;
}

if(subList!=null){
evenList=subList.parallelStream().filter(element -> {return element%2==0;}).collect(Collectors.toList());
}
System.out.println(“Sub Result:”+evenList);

}
}

Output:
Sub Result:[40, 42, 44, 46, 48]
Sub Result:[90, 92, 94, 96, 98]
Sub Result:[10, 12, 14, 16, 18]
Sub Result:[50, 52, 54, 56, 58]
Sub Result:[30, 32, 34, 36, 38]
Sub Result:[60, 62, 64, 66, 68]
Sub Result:[20, 22, 24, 26, 28]
Sub Result:[70, 72, 74, 76, 78]
Sub Result:[0, 2, 4, 6, 8]
Main thread One
Main thread Two
Sub Result:[80, 82, 84, 86, 88]

Sequence of above task,

forkjoinwithaction

Java · Java8

ForkJoin Demonstration in JAVA

Fork/Join Framework which is introduced in java7 is an important framework to achieve parallel processing in java.This is very useful if you have to execute recursive operations.

There are different kind of tasks which can be executed as part of fork join framework.

  1. RecursiveTask: A task which returns something after the execution
  2. RecursiveAction: A task which will not return anything
  3. CountedCompleter: A task can trigger other tasks on completion of some set of tasks.

RecursiveTask

The following program demonstrates the fork join concept with RecursiveTask. And attached sequence diagram which is best viewed in MS Paint gives the execution mechanism of this framework.

Aim of the program is to find even numbers from a given list.

Execution Environment: JDK8 and Windows 7

A main program to initialize pool and start the task.

/**
 * 
 */
package forkjoin;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

/**
 * @author prabhu kvn
 *
 */
public class EvenNumberFinderMain {

 public static void main(String args[]) {

 // Mock Data: crate an array of 100 numbers
 List a = new ArrayList();
 List evenNumbers = new ArrayList();
 for (int i = 0; i < 100; i++) {
 a.add(i);
 }
 // Initialize the Thread Pool
 ForkJoinPool pool = new ForkJoinPool(12);
 EvenNumberFinderTask task = new EvenNumberFinderTask(a);
 pool.execute(task);

 do {
 System.out.println("****************Pool****************");
 System.out.println("Parallesim:" + pool.getParallelism());
 System.out.println("Pool size:" + pool.getPoolSize());
 System.out.println("Active Thread count:" + pool.getActiveThreadCount());
 System.out.println("Queed Submission count:" + pool.getQueuedSubmissionCount());
 System.out.println("Qued Task count:" + pool.getQueuedTaskCount());
 System.out.println("Running Thread count:" + pool.getRunningThreadCount());
 System.out.println("Seal count:" + pool.getStealCount());

 } while (!task.isDone());
 pool.shutdown();
 // wait for 
 evenNumbers = task.join();
 System.out.println("Result:" + evenNumbers);

 }
}

Actual Task program

/**
*
*/
package forkjoin;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;
import java.util.stream.Collectors;

public class EvenNumberFinderTask extends RecursiveTask{

List a=null;

public EvenNumberFinderTask() {
}

public EvenNumberFinderTask(List a) {
this.a=a;
}
@Override
protected List compute() {
// TODO Auto-generated method stub
List taskList = new ArrayList();
List subList=null;
List evenList = new ArrayList();
/*
* See if the list is greater than 10. if so divide the task.
*/
if(a.size()>10){
subList = a.subList(0, 10);
List remaining = a.subList(10, a.size());
EvenNumberFinderTask task = new EvenNumberFinderTask(remaining);
task.fork();
taskList.add(task);
}else{
subList=a;
}

if(subList!=null){
evenList=subList.parallelStream().filter(element -> {return element%2==0;}).collect(Collectors.toList());
}
System.out.println(“Sub Result:”+evenList);

// wait for all the threads to join
for(EvenNumberFinderTask t: taskList){
evenList.addAll(t.join());
}

return evenList;
}
}

And check the out put of the program which is very interesting. And also sequence diagram

forkjoinseg1

Java · Java8

File Reading Using Java8 Streams

Here we can use Java8 streams to read a file content.

/**
 * 
 */
package java8pract.streams;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author prabhu kvn
 *
 */
public class StreamsInIO {

 /**
 * Using Java8 Streams to read the file
 */
 public StreamsInIO() {
 // TODO Auto-generated constructor stub
 }

 /**
 * @param args
 */
 public static void main(String[] args) {

 try {
 FileReader freader = new FileReader(new File("d:/text1.txt"));
 BufferedReader bReader = new BufferedReader(freader);
 Stream fileStream = bReader.lines();
 List fileContent = fileStream.collect(Collectors.toList());
 System.out.println(fileContent.size());
 System.out.println(fileContent);

 } catch (FileNotFoundException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }

 }

}
Java · WebSocket

A Simple WebSocket in Java

WebSocket is  a protocol to send full-duplex messages over a single TCP connection.

Once the connection is established between client and server, the same connection will be used to communicate for multiple times by both client and server.

Here client and server acts as two end points and they will exchange the data over a single connection.

Note: In order to run these programs, one should have web socket enables server like jetty 9.2.X, Firefox 47 and JDK7 and above.

WebSocket Server End point:

Server will just print the received message and send an ACK back.

/**
 *
 */
package com.websocket;

import java.io.IOException;

import javax.enterprise.context.ApplicationScoped;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 * @author prabhu kvn
 *
 */
@ApplicationScoped
@ServerEndpoint("/server")
public class WebSocketSimpleServer {

	/**
	 *
	 */
	public WebSocketSimpleServer() {
		// TODO Auto-generated constructor stub
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see javax.websocket.Endpoint#onOpen(javax.websocket.Session,
	 * javax.websocket.EndpointConfig)
	 */
	@OnOpen
	public void onOpen(Session session, EndpointConfig ednpointConfig) {
		System.out.println("--- On Open Call ---Session ID---"
				+ session.getId());

	}

	@OnClose
	public void onClose(Session session) {
		System.out.println("--- On Close Call--");
	}

	@OnMessage
	public void onMessage(String message, Session session) {
		try {

			System.out.println("Server Received:" + message);
			session.getBasicRemote().sendText(
					"(-- Server ACK --"+message+")");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

A Client End Point:

This will establish a connection and reuse same connection for sending messages:

/**
 *
 */
package com.websocket;

import java.io.IOException;
import java.net.URI;

import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

/**
 * @author prabhu kvn
 *
 */
@ClientEndpoint
public class WSSimpleClient {

	/**
	 *
	 */
	public WSSimpleClient() {
		// TODO Auto-generated constructor stub
	}

	private static Object waitLock = new Object();

	@OnMessage
	public void onMessage(String message) {
		System.out.println("Client Received:" + message);
	}

	public static void main(String[] args) {
		for (int i = 0; i < 1; i++) {
			connectAndSend();
		}
	}

	/**
	 *
	 */
	private static void connectAndSend() {
		WebSocketContainer container = null;//

		Session session = null;

		try {
			long startTime = System.currentTimeMillis();

			container = ContainerProvider.getWebSocketContainer();
			session = container
					.connectToServer(
							WSSimpleClient.class,
							URI.create("ws://localhost:8888/websockethome/server"));
			// send multiple data sets on same connection
			for(int j=0;j<100;j++){
			session.getBasicRemote().sendText("Client text...."+j);
			}
			System.out.println("Total Time:" + (System.currentTimeMillis() - startTime)+" ms");
			wait4TerminateSignal();

		} catch (DeploymentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void wait4TerminateSignal()

	{

		synchronized (waitLock)

		{
			try {

				waitLock.wait(100);

			} catch (InterruptedException e) {

			}
		}
	}

}

Play with I and j values in above program to under stand working of websockets.

Scenario 1: i=1 and j=100 , This will establish a connection once and reuse the same connection to send 100 messages.

Scenario 2: i=10 and j=1,  This will try to establish the connection 10 times, but it will get same connection for all the request. Observe the first connection against consecutive connection times.

Maven Pom Entries:

<!-- Java ee dependency -->

			javax
			javaee-api
			7.0

			org.apache.httpcomponents
			httpclient
			4.5.1

		<!-- Jetty Dependencies -->

			jetty
			jetty-plus
			6.0.2

			org.eclipse.jetty
			jetty-annotations
			9.3.8.v20160314

		<!-- Tyrus websoket client support -->

			org.glassfish.tyrus.bundles
			tyrus-standalone-client
			1.12

			org.glassfish.tyrus.bundles
			tyrus-standalone-client-jdk
			1.12

			org.glassfish
			javax.json
			1.0.4

		websockethome

				org.apache.maven.plugins
				maven-compiler-plugin
				2.0.2

					${java.version}
					${java.version}

				org.eclipse.jetty
				jetty-maven-plugin
				9.2.11.v20150529

					10

						/websockethome

						8888

>mvn jetty:run will start the server on 8888

Callback · Functional · Java

Callback Function in Java

                                                  The following program simulates the call back function feature in Java. This program has been written using functional interface and Callable feature in java. This can be understood by reading below code directly.

/**
 * The following program explains the mimicking of callback  function in java. 
 */
package java8pract;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Prabhu KVN
 *
 */
public class CallBackFunction {

	ExecutorService executorservice = Executors.newFixedThreadPool(2);

	/**
	 * 
	 */
	public CallBackFunction() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CallBackFunction fun = new CallBackFunction();
		double val = 100;

		// handleResult is the call back function
		fun.findRoot(val, new ResultHandler() {

			@Override
			public void handleResult(double n) {
				// TODO Auto-generated method stub
				System.out.println("Root of " + val + " is " + n);
			}
		});
		System.out.println("Finding root in progress...");

	}

	public void findRoot(double number, ResultHandler handler) {

		RootFinder finder = new RootFinder(number, handler);

		executorservice.submit(finder);
		executorservice.shutdown();

	};

}

@FunctionalInterface
interface ResultHandler {
	public void handleResult(double n);
}

/**
 * A callable function which will execute a login and will call handler to
 * propagate the logic to an handler.
 * 
 * @author prabhu kvn
 *
 */
class RootFinder implements Callable<Double> {
	double number;
	ResultHandler handler;

	public RootFinder(double number, ResultHandler handler) {
		// TODO Auto-generated constructor stub
		this.number = number;
		this.handler = handler;
	}

	@Override
	public Double call() throws Exception {
		// TODO Auto-generated method stub
		double sqrt = Math.sqrt(number);
		handler.handleResult(sqrt);

		return sqrt;
	}
}