Friday, September 26, 2014

Basic difference between scheduleAtFixedRate vs scheduleWithFixedDelay

Info

Code simply executes a single thread with fixed initial delay, and fixed interval. using two separate methods scheduleAtFixedRate  and scheduleWithFixedDelay. In first run we have used scheduleAtFixedRate  method, then in second run we will use the scheduleWithFixedDelay method. Inside the run method thread sleep for 6secs

/*
     Author: Raj Kirpalsinh
*/ 

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class SchedularTest {
private ScheduledExecutorService scheduledExecutorService ;
private WorkerThread scanner = new WorkerThread();

public static void main(String... args) {
new SchedularTest().go();
}

private void go() {

  this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
          scheduledExecutorService.scheduleAtFixedRate(scanner, scanner.getInitialDelay(),             scanner.getIntervalTime(), TimeUnit.SECONDS);

              
     //scheduledExecutorService.scheduleWithFixedDelay(scanner,scanner.getInitialDelay(),      //scanner.getIntervalTime(), TimeUnit.SECONDS);

}

private class WorkerThread implements Runnable { 

public long getInitialDelay() {
return 1;
}

public long getIntervalTime() {
return 2;
}

@Override
public void run() {
System.out.println(new Date());
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Output using scheduleWithFixedDelay

Fri Sep 26 17:00:26 IST 2014
Fri Sep 26 17:00:34 IST 2014
Fri Sep 26 17:00:42 IST 2014
Fri Sep 26 17:00:50 IST 2014
Fri Sep 26 17:00:58 IST 2014
Fri Sep 26 17:01:06 IST 2014
Fri Sep 26 17:01:14 IST 2014
Fri Sep 26 17:01:22 IST 2014
Fri Sep 26 17:01:30 IST 2014

Note : fixedDelay method consumes 
Total Time = 
IntervalTime + Thread Task Completion Time

check the total time between each output line you could understand it easily.

Output using scheduleAtFixedRate

Fri Sep 26 17:03:23 IST 2014
Fri Sep 26 17:03:29 IST 2014
Fri Sep 26 17:03:35 IST 2014
Fri Sep 26 17:03:41 IST 2014
Fri Sep 26 17:03:47 IST 2014
Fri Sep 26 17:03:53 IST 2014
Fri Sep 26 17:03:59 IST 2014

Note : fixedRate method consumes 
Total Time = 
IntervalTime

Keep Visiting :) 


Wednesday, September 24, 2014

Java Utility

Info
Useful java utility method for String, Collections and Array

import java.io.Closeable;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import junit.framework.Assert;

/*
 * Author: Raj Kirpalsinh
 * */

public class JavaUtility {

/* checking not null and not empty on the string object without trimming */
public static boolean isNotNullAndNotEmpty(String reference) {
return (reference != null && reference.trim().length()>0);
}


/* checking null/empty on the string object without trimming */
public static boolean isNullOrEmpty(String reference) {
return (reference == null || reference.trim().length()==0);
}

/* checking not null and  not empty on the Collection (interface) object */
public static boolean isNotNullAndNotEmpty(Collection<?> reference) {
return (reference != null && reference.size()>0);
}

/* checking null/empty on the Collection (interface) object */
public static boolean isNullOrEmpty(Collection<?> reference) {
return (reference == null || reference.size()==0);
}

/* checking not null and not empty on the Map (interface) object */
public static boolean isNotNullAndNotEmpty(Map<?,?> reference) {
return (reference != null && reference.size()>0);
}

/* checking null/empty on the Map (interface) object */
public static boolean isNullOrEmpty(Map<?,?> reference) {
return (reference == null || reference.size()==0);
}

/* trimming string array all elements values*/
public static String[] trim(String[] refArray) {
        if (refArray == null) {
            return refArray;
        }
        for (int i = 0, len = refArray.length; i < len; i++) {
            refArray[i] = refArray[i].trim();
        }
        return refArray;
    }

/* checking not null and not empty on the Array (Object[])*/
public static boolean isNotNullAndNotEmpty(Object[] reference) {
return (reference != null && reference.length>0);
}

/* checking null/empty on the Array (Object[])*/
public static boolean isNullOrEmpty(Object[] reference) {
return (reference == null || reference.length==0);
}

/* Closing all the objects/streams have Closeable interface nature */
public static void closeMe(Closeable reference) {
if(reference!=null) {
try {
reference.close();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
}

/* Converting any string (i.e word/line) in Camel-Case
* i.e hello good morning buddy -->> Hello Good Morning Buddy 
* */
public static String toCamelCase(String reference) {
if(isNullOrEmpty(reference) == false) {
String words[] = reference.split(" ");
StringBuilder line = new StringBuilder();
for(String word : words) {
word = word.trim().toLowerCase();
if(isNotNullAndNotEmpty(word)){
word = word.replaceFirst(String.valueOf(word.charAt(0)), String.valueOf(word.charAt(0)).toUpperCase());
line.append(word).append(" ");
}
}
return line.toString().trim();  
}
return reference;
}


public static void main(String dataBag[]) {
System.out.println("------BEGIN------");

String str = "  hello good morning buddy  ";
System.out.println("toCamelCase: "+toCamelCase(str));

String test = "";

Assert.assertEquals((isNotNullAndNotEmpty(test) == false), (isNullOrEmpty(test) == true));
Assert.assertEquals((isNotNullAndNotEmpty("") == false), (isNullOrEmpty("") == true));
Assert.assertEquals((isNotNullAndNotEmpty("adfa") == true), (isNullOrEmpty("") == false));

System.out.println("------END------");
     }
}

Keep Visiting :)

Java Factory Pattern Simple Code

Info
In simple words, if we have a super class and n sub-classes, and based on data provided, 
we have to return the object of one of the sub-classes,  then we should use a factory pattern concept

Code
class Person {

public String name;
private String gender;

public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}

public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}

}


class Male extends Person {
  public Male(String fullName) {
setName(fullName);
setGender("Male");
}
public String toString(){
System.out.println("----Person Detail----- ");
System.out.println("Mr. "+getName());
System.out.println("Name : "+getName());
System.out.println("Gender : "+getGender());
return "";
}
}

class Female extends Person {
  public Female(String fullName) {
setName(fullName);
setGender("Female");
}
public String toString(){
System.out.println("----Person Detail----- ");
System.out.println("Ms. "+getName());
System.out.println("Name : "+getName());
System.out.println("Gender : "+getGender());
return "";
}

}

class FactoryPatternEngine{
  public static void main(String args[]) {

FactoryPatternEngine  factory = new FactoryPatternEngine();
Person  person = factory.getPerson(args[0], args[1]);
System.out.println(person);

}
public Person getPerson(String name, String gender) {
if (gender.equals("M")){
return new Male(name);
}else if(gender.equals("F")){
return new Female(name);
}else{
return null;
}
}

}

Keep Visiting :)

Java Singleton Design Pattern

Info
given ways to create Singleton design pattern class
1) Using private constructor  and a getter method for an Instance
2) Using private constructor and public static final Instance of a Class

package com.raj.dp;
class Universal {

private Universal(){
universe =  this;
}

public void printMessages(){
System.out.println("Good morning. Have a beautiful day.");
}

public static Universal getUniverse(){
return universe;
}

public static void initialize(){
universe = new Universal();
}

public String toString(){
return "Hello friend.\nMy name is Universal and i m a Singleton Factory pattern class.";
}

public static Universal universe;
}

//Singleton with public final field
class Earth {
public static final Earth INSTANCE = new Earth();
private Earth() { 

}
public void makeMyEarthGreen() { 
System.out.println("Hello ");
}
}

class SingletonEngine{

public static void main(String rk[]){
System.out.println("----->Start<-----\n");
Universal.initialize();
Universal universe = Universal.getUniverse();
System.out.println("Universe : "+universe);

universe.printMessages();
Earth.INSTANCE.makeMyEarthGreen();
System.out.println("\n-----> End <-----");
}

}

Java code : Batch Operation with Insert and Update Operation

Info
In this code during the batch operation  if the Insert operation get failed it will perform Update operation 

package com.raj.db;

import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


class Student{

private int id;
private String name;
private String queryType;

Student(){}

Student(int id, String name, String queryType){
this.id = id;
this.name = name;
this.queryType = queryType;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getQueryType() {
return queryType;
}

public void setQueryType(String queryType) {
this.queryType = queryType;
}
}

class DBManager{

private final String INSERT_QUERY = "INSERT INTO STUDENTS_DATA (ID, NAME) VALUES (?, ?)";
private final String UPDATE_QUERY = "UPDATE STUDENTS_DATA SET NAME = ?  WHERE ID = ?";

private Connection connection = null;

public void loadDriver(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("URL","DB_NAME","DB_PASSWORD");
} catch (Exception e) {
System.out.println("Error while executing preparedstatement, Reason: "+e.getMessage());
}
}

public void insertData(){
int response[] = null;
PreparedStatement prepStmt = null;
List<Student> studentList =  new ArrayList<Student>();

try{

connection.setAutoCommit(false);
prepStmt = connection.prepareStatement(INSERT_QUERY);

int starter = 7;
for(int i=starter; i<=starter+4; i++){
studentList.add(new Student(i,"student"+i, "INSERT"));
prepStmt.setInt(1, i);
prepStmt.setString(2, "Student"+i);
prepStmt.addBatch();
}
response = prepStmt.executeBatch();

} catch (BatchUpdateException be) {

try{
connection.rollback();
}catch(Exception ex){}

/*for(int command:be.getUpdateCounts()){
if(command == Statement.SUCCESS_NO_INFO){
System.out.println("SUCCESS "+command );
}else if(command == Statement.EXECUTE_FAILED){
System.out.println("FAILED "+command );
}
}*/
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(new Worker(studentList));
executor.shutdown();
System.out.println("Thread ShutDown");

}catch (Exception e) {
System.out.println("Error while executing batch, Reason: "+e.getMessage());
if(response!=null){
System.out.println("Response: "+response.length);
}

}finally{
closeQuietly(prepStmt);
closeQuietly(connection);
}
}

public void closeQuietly(Statement statement){
try {
            if (statement != null) {
            statement.close();
            }
        } catch (SQLException e) { }
}

public void closeQuietly(Connection connection){
try {
            if (connection != null) {
            connection.close();
            }
        } catch (SQLException e) { }
}


class Worker implements Runnable{


List<Student> dataList = null;
PreparedStatement insertPrepStmt = null;
PreparedStatement updatePrepStmt = null;
Worker(List<Student> data){
this.dataList = data;
}

@Override
public void run() {
loadDriver();
try{
insertPrepStmt = connection.prepareStatement(INSERT_QUERY);
updatePrepStmt = connection.prepareStatement(UPDATE_QUERY);

for(Student student: dataList){
String message = executeTask(student);
if(message.equalsIgnoreCase("INSERT_FAILED")){
System.out.println("INSERT FAILED");
student.setQueryType("UPDATE");
executeTask(student);
}
}

}catch(Exception ex){
System.out.println("Exception while executing preparedStatement, Reason: "+ex.getMessage());
}finally{
closeQuietly(insertPrepStmt);
closeQuietly(connection);
}
}


public String executeTask(Student data){
try{
if(data.getQueryType().equalsIgnoreCase("INSERT")){
System.out.println("INSERTING RECORD AGAING NOW");
insertPrepStmt.setInt(1, data.getId());
insertPrepStmt.setString(2,data.getName());
insertPrepStmt.execute();

}else if(data.getQueryType().equalsIgnoreCase("UPDATE")){
System.out.println("UPDATING NOW");
updatePrepStmt.setString(1,data.getName()+"-UPDATED");
updatePrepStmt.setString(2,data.getId()+"");
updatePrepStmt.executeUpdate();
}
connection.commit();
}catch(Exception ex){
return "INSERT_FAILED";
}
return "SUCCESS";
}
}
}

public class BatchOperationFlight {
public static void main(String bag[]){
System.out.println("--START--");
DBManager dbmanager = new DBManager();
dbmanager.loadDriver();
dbmanager.insertData();
System.out.println("--END--");
}
}

Keep Visiting :)

Java PreparedStatement using COMMIT WORK WRITE BATCH command


package com.raj.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;

public class CommitWriteBatchTestFlight {

public static void main(String[] dataTrays){
System.out.println("--BEGIN--");
String commitCommand = "COMMIT WORK WRITE BATCH";

final String TBL_NAME = "PLAYERS";
final String COL_ID = "ID";
final String COL_NAME = "NAME";
final String COL_TEAM = "TEAM";
final String COL_TOTAL_RUNS = "TOTAL_RUNS";

String createTableQuery = "CREATE TABLE PLAYERS ( " +
"ID INT, " +
"NAME VARCHAR(255), " +
"TEAM VARCHAR(255), " +
"TOTAL_RUNS VARCHAR(255)" +
")";

try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@IP_ADDRESS:1521:db_name","username","password");

Statement stmt = connection.createStatement();
stmt.execute(createTableQuery);
System.out.println("Table create Successfully");
stmt.close();

PreparedStatement commitPrepStmt = connection.prepareStatement(commitCommand);
PreparedStatement prepStmt = connection.prepareStatement("INSERT INTO PLAYERS (ID, NAME, TEAM, TOTAL_RUNS) VALUES (?, ?, ?, ?)");

long startTime = System.currentTimeMillis();

for(int i=1; i<=11; i++){
prepStmt.setInt(1, i);
prepStmt.setString(2, "Player"+i);
prepStmt.setString(3, "Team"+i);
prepStmt.setString(4, "100"+i);
prepStmt.executeUpdate();
}
prepStmt.close();

//connection.commit();
//System.out.println("Execution Time: "+(System.currentTimeMillis()-startTime)+" ms");

commitPrepStmt.executeUpdate();
System.out.println("Execution Time: "+(System.currentTimeMillis()-startTime)+" ms");

connection.close();

} catch (Exception e) {
System.out.println("Error while executing preparedstatement, Reason: "+e.getMessage());
}

System.out.println("--END--");
}
}

Keep Visiting :)

Convert Number to Local Currency Using Java

package com;

import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;

public class NumberToCurrencyEngine
{
   public static void main(String[] args)
   {
      //This is the amount which we want to format
      Double currencyAmount = new Double(50000);
       
      //Get current locale information
      Locale currentLocale = Locale.getDefault();
       
      //Get currency instance from locale; This will have all currency related information
      Currency currentCurrency = Currency.getInstance(currentLocale);
       
      //Currency Formatter specific to locale
      NumberFormat currencyFormatter =      NumberFormat.getCurrencyInstance(currentLocale);

      //Test the output
      System.out.println(currentLocale.getDisplayName());
       
      //System.out.println(currentCurrency.getDisplayName());
       
      System.out.println(currencyFormatter.format(currencyAmount));
   }
}

Output
English (India)

Rs.50,000.00

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...