Donation

If you found the contents in this blog useful, then please make a donation to keep this blog running. You can make donations via Skrill with email address shazin.sadakath@gmail.com

Friday, August 19, 2011

Spring Dynamic Modules for OSGi (1)

Lately I have been testing out Spring Dynamic Modules for OSGi. Open Service Gateway Initiative (OSGi) is a dynamic module and service system for Java. It enables modules (well known as bundles) with specific functionality to be installed, started, stopped, removed without interrupting or stopping the execution life cycle.

OSGi specifies an API to develop bundled applications which are;

  • Modular
  • Flexible
  • Independent
  • Dynamic
An OSGi bundled application can be run in many OSGi containers available such as;

  • Apache Felix
  • Eclipse Equinox
  • Knopflerfish
and many more...

But the problem with OSGi is that it restricts the developer to use a strictly specified set of API classes and doesn't enable the flexibility offered in spring enabled application where everything is defined in beans. To tackle this spring has put forward a framework for Dynamic Modules in OSGi while leveraging the flexibility of the Spring framework.

Expect more in the coming posts...

Wednesday, August 17, 2011

Performance Testing

On my spare time I have been doing some Performance Testing mechanisms in Java.
I just wrote a small code snippet and ran it in a Worker thread and tried to improve
the performance of it. Even though this is small the lesson I learned was immense.

This is the worker class I used.

import java.util.concurrent.*;


public class Callee implements Callable<Integer> {
public Integer call() {
int i = 0;
while(i < 10000) {
System.out.println(i);
i++;
}
return i;
}
}


And the worker was called by the following class

import java.util.concurrent.*;

import java.awt.*;

public class Caller {
public static void main(String[] args)throws Exception {
long startFreeMemory = Runtime.getRuntime().freeMemory();
long startTime = System.currentTimeMillis();
ExecutorService exec = Executors.newCachedThreadPool();
Future<Integer> f = exec.submit(new Callee());
exec.shutdown();
System.out.println("Future is "+f.get());
long endTime = System.currentTimeMillis();
long endFreeMemory = Runtime.getRuntime().freeMemory();
System.out.println("Memory used : "+(startFreeMemory - endFreeMemory));
System.out.println("Duration : "+(endTime - startTime));
}
}


Testing was done in Intel Core 2 Duo Process with 2.93 GHz and 2 Gb of RAM.

The initial program ran for 672 Milliseconds and Used 674408 units of RAM.

Then the Callee class was changed to the following.

import java.util.concurrent.*;


public class Callee implements Callable<Integer> {
public Integer call() {
int i = 0;
StringBuilder sb = new StringBuilder();
while(i < 10000) {
sb.append(i+"\n");
i++;
}
System.out.print(sb.toString());
return i;
}
}


Using a StringBuffer without directly printing to the screen reduced the execution time by 188 Milliseconds but the RAM units used increased to 828288.

But just changing

sb.append(i+"\n");



to

sb.append(i).append("\n");



reduced the RAM Usage by almost half from the previous implementation.

Wednesday, August 10, 2011

Eiffel Programming

As part of degree studies I had to learn a Programming Language named Eiffel which enables to write programs which doesn't unintentionally kill or injure people/assets. Simply put it enables to write Secure programs.

The Eiffel language many features to make this possible such as Design by Contract, Multiple Inheritance, Method Rename and so on.

While doing Eiffel I wanted to try out a Small thread based code I did in Java in Eiffel. The code just takes in a String and prints one character after another in the console like in those Action Movies where the secret location name will be printed.

After some reading I managed to do this with the following code in Eiffel.

slow_prompt(text : STRING) is

require
valid_text : text /= void
local
counter : INTEGER
do
from
counter := 1;
until
counter > text.count
loop
io.put_character (text.at (counter));
sleep(7812500); -- Sleep for 7812500 nano seconds
counter := counter + 1;
end
end


For this method to work however the class EXECUTION_ENVIRONMENT needs to facility inherited.

Tuesday, August 9, 2011

Java 7 Hands On

I have been trying out Java 7 this week and Tested out the latest features in JDK 7. They have given some serious thought on minimizing the coding strain of the developer by providing some new features. My favorite one is Binary Literals. There are quite more features which are;

  • Try with Resources
  • Multi Catch Statements
  • Diamond Syntax
  • Binary Literals
  • Underscore Between Literals
  • String in Switch
I wrote a small class to Test out all those features which is shown below.
import java.io.*;

import java.awt.Color;
import java.util.*;

public class Test {
public static void main(String[] args)throws IOException {
try{
try (FileInputStream in = new FileInputStream(args[0])) { // Try with Resources


int i = in.read();

}
} catch(FileNotFoundException | ArrayIndexOutOfBoundsException e) { // Multi Catch Statements
e.printStackTrace();
}


List<Color> colors = new ArrayList<>(); // Diamond Syntax

int no = 4 << 1;
int bi8 = 0b1000; // Binary Literals

System.out.println(" 4 << 1 == 0b1000 > "+(no == bi8));

int oldOneMillion = 1000000;
int newOneMillion = 1_000_000; // Underscore Between Literals

System.out.println("1000000 == 1_000_000 ? "+(oldOneMillion == newOneMillion));


/* String in Switch */

final String RED = "Red";
final String GREEN = "Green";
final String BLUE = "Blue";

Scanner sn = new Scanner(System.in);
System.out.print("Enter choice (Red, Green, Blue): ");
String input = sn.nextLine();
switch(input) {
case RED :
colors.add(Color.RED);
break;
case GREEN :
colors.add(Color.GREEN);
break;
case BLUE :
colors.add(Color.BLUE);
break;
default :
System.out.println("None");
}
}
}


Great Features, Thanks Sun/Oracle Engineers. Hope you all fix the minor bugs soon!

Saturday, August 6, 2011

MIT Problem Set Solution

As part of my degree program I had to do a coursework which had a Problem Set to be Solved which was given as part of the Introduction to Algorithms module of Electrical Engineering and Computer Science course taught at the prestigious Massachusetts Institute of Technology (MIT).

The problem set I had to solve is available in this PDF as Problem Set 8-2 Video Game Design.

In short the problem is that there is a Game with Rooms and Corridors connecting those rooms. Each Room will have either a monster or a life potion. Encountering the monster decreases life and drinking life potion increases life. The objective of the algorithm was to find the minimum life points required to start the Game.

I used Floyd and Warshall Algorithm as the base to solve the problem and modified it to get the output. I had the following assumptions in place;

  • Maximum life points a player can have is 100. If a maze requires more than 100 at the start of the maze to finish the maze that maze is not r-admissible.
  • The mazes will only have a maximum of 100 rooms or less. This is because the player will be frustrated to finish the maze if it is longer than that.
  • From start room there is at least two paths to the destination.
Following are the two part flow chart diagrams of the algorithm.



Implementation of the algorithm is seen below;

public double RAdmissible() {

if (maze != null) {
// Variable to store the result
double r = 0d;
// Constant to store No of vertices in the Maze
final int MAZE_LENGTH = maze.getSize();
// Variable to store Adjacency Matrix of the Maze
double matrix[][] = maze.getAdjacencyMatrix();
// Variable to store Predecessor of the Longest path
double pred[][] = new double[MAZE_LENGTH][MAZE_LENGTH];
/*
*
* If there is a positive cycle
* then with minimum of r = 1 maze is navigable
* Else have to find the least costly path from start to end of the maze
*
*
*/
// Variable to store whether this maze contains a positive cycle
boolean positiveCycle = false;
/*
* Modified version of Floyd-Warshall Algorithm. Runs at O(N^3).
* This is used to find the least cost path from start to finish
* and to find whether there are positive cycles in the maze.
*/
for (int k = 0; k &lt; MAZE_LENGTH &amp;&amp; !positiveCycle; k++) {
for (int i = 0; i &lt; MAZE_LENGTH &amp;&amp; !positiveCycle; i++) {
for (int j = 0; j &lt; MAZE_LENGTH &amp;&amp; !positiveCycle; j++) { if (matrix[k][j] != Double.NEGATIVE_INFINITY &amp;&amp; matrix[i][k] + matrix[k][j] &gt; matrix[i][j]) {
// Assigning the new least cost path
matrix[i][j] = matrix[i][k] + matrix[k][j];
// Assigning the new predecessor
pred[i][j] = k;
/*
* If i == j then it is a cycle.
* But we have to determine whether it is a positive cycle.
* For that we check whether the new path is not Negative Infinity and it is positive.
*/
if (i == j &amp;&amp; matrix[i][j] != Double.NEGATIVE_INFINITY &amp;&amp; matrix[i][j] &gt; 0) {
positiveCycle = true;
}
}
}
}

// Minimum r is the cost to go from start to finish
double minimumR = matrix[0][MAZE_LENGTH - 1];
// If Minimum r is Negative Infinity then cost from start to next to finish is taken
minimumR = minimumR == Double.NEGATIVE_INFINITY ? matrix[0][MAZE_LENGTH - 2] : minimumR;
/*
* If a positive cycle is available then Minimum r is 1
* This is because life points necessary to safely navigate
* the maze can be gained by going through the positive cycle.
*
* If no positive cycle is found then
* If Minimum r is Negative or Zero the Minimum r should be
* one greater than the absolute value of Minimum r.
*
* If Minimum r is Positive then
* Minimum r is 1 this is because there is safe path
* from start to end where the player's lifepoints will
* never become 0 or less.
*
*/
minimumR = positiveCycle ? 1.0 : minimumR &lt;= 0 ? abs(minimumR) + 1.0 : 1.0; /*
* If Minimum r is greater than 100 then * r is 0 which means there is no safe path in the maze. *
* Note : This is based on the assumption that a player can have a maximum of * 100 life points.
*/
r = minimumR &gt; 100 ? 0 : minimumR;
}
// Return the Minimum r
return r;
} else {
throw new IllegalStateException("Maze is invalid");
}
}



The Maze is a Adjacency Matrix implementation with Two Dimensional Double array. I used the following maze designs to test the algorithm.



Many couldn't finish this task in my batch and I was awarded highest marks (91) for the coursework.


Wednesday, August 3, 2011

Integrating EJB3 Session Bean with Spring Security 3

During my BSc education I had a coursework which required to be developed using Enterprise Java Beans. All the business logics were to be captured using Session Beans and they were to be made as the one and only access point to the data layer.

But to implement the Authentication and Authorization in the web application I wanted to use Spring Security Framework 3. But it had a different mechanism to connect with the database and retrieve the user credentials and authorizations.

I wanted the same EJB Session Beans which handles User related logics to be used in the authentication as well. Then after reading some materials online and some coding I managed to use my EJB Session Bean UserController along with the Spring Security authentication and authorization mechanism.

package com.lkbotics.business;


import com.lkbotics.entity.Country;
import com.lkbotics.entity.Customer;
import com.lkbotics.entity.User;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
*
* @author Shazin Sadakath
*/
@Stateless
public class UserController implements UserControllerRemote, UserControllerLocal {

/**
* Entity Manager for Accessing Tables in Database
*/
@PersistenceContext(name="LKBotics")
private EntityManager entityManager;

/**
*
* @param username - Username of the user
* @return User
*/
public User getUserByUsername(String username) {
Query query = entityManager.createQuery("FROM User as u WHERE u.username = ?1");
query.setParameter(1, username);
User user = (User) query.getSingleResult();
return user;
}


Spring Security 3 Uses something called an Authentication Provider to get Authentication details. This could be an XML Tag with hard coded values or a database table with dynamic values. But in this scenario we require a custom Authentication Provider which uses the EJB Session Bean UserController to get the user credentials. For that purpose Spring Security 3 provides an Interface named UserDetailsService.

/*

* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package com.lkbotics.services;

import com.lkbotics.business.UserControllerRemote;
import com.lkbotics.dto.UserDetailsAdaptor;
import com.lkbotics.entity.User;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.NoResultException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
*
* @author Shazin Sadakath
*/
@RequestScoped
public class UserDetailsServiceImpl implements UserDetailsService{


private UserControllerRemote userController;

public UserDetailsServiceImpl(){
try {
InitialContext ctx = new InitialContext();
userController = (UserControllerRemote) ctx.lookup("com.lkbotics.business.UserControllerRemote");
} catch (NamingException ex) {
Logger.getLogger(UserDetailsServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserDetailsAdaptor userDetails = null;
try{
User user = userController.getUserByUsername(username);
userDetails = new UserDetailsAdaptor(user);
}catch(NoResultException e){
throw new UsernameNotFoundException(username);
}
return userDetails;
}
}


As seen above UserDetailsService has a method named loadUserByUsername which needs to be overridden and implemented to use the EJB3 Session Bean. This enable user credentials to be retrieved via the EJB instead of direct JDBC calls, centralizing the data access to EJB Persistence Context.

Hope this helped.