Swing Worker Thread Explained with Progress Bar.

When performing a time consuming task usually we prefer another worker thread since the time consuming activity should not block the GUI events.
Java has a special class called SwingWorker to do such background activities by keeping GUI responsive.

SwingWorker provides a number of communication and control features:

Here I will give an example for Swingworker with some background activity having a progress bar to show it’s status.
The following example is a file locker application by which we can lock a file.Here we we have used basic XOR encryption with ‘1’ to encrypt the file, to unlock a file encrypt already locked file one more time.
Mainframe.java

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Locale;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;


public class Mainframe extends JFrame implements ActionListener {

	public void createGUI(){
		setTitle("File Locker");
		fileSelectBtn = new JButton("::");
		fileSelectBtn.addActionListener(this);

		pb = new JProgressBar(0, 100);
		//	pb.setValue(0);		
		pb.setIndeterminate(false);
		pb.setStringPainted(true);
		pb.setVisible(true);

		JPanel panel = new JPanel();
		label = new JLabel("File");

		textField = new JTextField(15);
		//	textField.setEditable(false);
		panel.add(label);
		panel.add(textField);
		panel.add(fileSelectBtn);


		JPanel panel1 = new JPanel();
		panel1.setLayout(new BorderLayout());
		panel1.add(panel, BorderLayout.NORTH);	

		JPanel panel2 = new JPanel();
		encryptBtn    = new JButton("Encrypt");
		encryptBtn.addActionListener(this);
		panel2.add(encryptBtn);
		panel2.add(pb);
		panel1.add(panel2, BorderLayout.CENTER);	
		panel1.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
		setContentPane(panel1);
		pack();
		setResizable(false);
		setSize(400, 150);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public void actionPerformed(ActionEvent e) {
		if(e.getSource().equals(fileSelectBtn)){
			JFileChooser filechooser = new JFileChooser(".");

			if (filechooser.showOpenDialog(this) ==  JFileChooser.APPROVE_OPTION)
			{							
				selectedFile = filechooser.getSelectedFile();	
				textField.setText(selectedFile.getAbsolutePath());
				textField.setToolTipText(selectedFile.getAbsolutePath());
			}
		}else if(e.getSource().equals(encryptBtn)){
			FileInputStream fin = null;
			try {
				// create FileInputStream object
				if(selectedFile == null){
					JOptionPane.showMessageDialog(this, "Please select any file.", "Error Message", JOptionPane.INFORMATION_MESSAGE);
					return;
				}
				fin = new FileInputStream(selectedFile);				
				long length = selectedFile.length();
				byte fileContent[] = new byte[(int)selectedFile.length()];

				// Reads up to certain bytes of data from this input stream into an array of bytes.
				fin.read(fileContent);
				fin.close();

				FileEncryptPerformer actionPerform = new FileEncryptPerformer(this, fileContent,
						selectedFile.getAbsolutePath(),
						pb);
				actionPerform.execute();	

			}
			catch (FileNotFoundException ex) {
				JOptionPane.showMessageDialog(this, "File not found.", "Error Message", JOptionPane.INFORMATION_MESSAGE);
				System.out.println("File not found" + ex);
			}
			catch (IOException ioe) {
				JOptionPane.showMessageDialog(this, "Exception while reading file.", "Error Message", JOptionPane.INFORMATION_MESSAGE);
				System.out.println("Exception while reading file " + ioe);
			}
			finally {
				// close the streams using close method
				try {
					if (fin != null) {
						fin.close();
					}
				}
				catch (IOException ioe) {
					JOptionPane.showMessageDialog(this, "Error while closing stream.", "Error Message", JOptionPane.INFORMATION_MESSAGE);
					System.out.println("Error while closing stream: " + ioe);
				}
			}
		}
	}			

	private JButton fileSelectBtn;
	private JButton encryptBtn;
	private JProgressBar pb;
	JTextField textField;
	JLabel label;
	File selectedFile;

}


FileEncryptPerformer.java

import java.awt.Cursor;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

class FileEncryptPerformer extends SwingWorker {

	JProgressBar fProgressBar;
	private byte fileContent[];
	private String fileName;
	Mainframe mainFrame ;

	public FileEncryptPerformer(Mainframe mainFrame, byte fileContent[],String fileName, JProgressBar progressBar) {
		this.mainFrame   = mainFrame;
		this.fileContent = fileContent;
		this.fileName = fileName;
		this.fProgressBar = progressBar;		
	}

	protected String doInBackground() throws Exception {
		mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		setStatusText(0);
		encrypt();
		writeToFile();
		return "Finished";
	}

	private void writeToFile() throws IOException {
		BufferedOutputStream bos = null;
		try {
			//create an object of FileOutputStream
			FileOutputStream fos = new FileOutputStream(new File(fileName));
			//create an object of BufferedOutputStream
			bos = new BufferedOutputStream(fos);		
			bos.write(fileContent);			

		}catch (FileNotFoundException e) {
			if(bos !=null)
				bos.close();
			done();
			JOptionPane.showMessageDialog(mainFrame, "File not found.", "Error Message", JOptionPane.INFORMATION_MESSAGE);
			return ;
		}
		catch (IOException e) {
			if(bos !=null)
				bos.close();
			done();
			JOptionPane.showMessageDialog(mainFrame, "Exception while reading file.", "Error Message", JOptionPane.INFORMATION_MESSAGE);
			return ;
		}

	}

	protected void done() { 
		mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
		setStatusText(100);
		
	}

	public void encrypt() {
		int stepSize = fileContent.length/100;
		for ( int i = 0; i < fileContent.length; i++) {
			fileContent[i] = (byte) (fileContent[i] ^ (byte)1);
			float stepCount = (float)i/fileContent.length;
			final int count = (int)(stepCount*100);		
			//fProgressBar.setValue(count);
			setStatusText(count);			
		}    
	}
	
	public void setStatusText(final int status) {
		SwingUtilities.invokeLater(new Runnable(){

			//@Override
			public void run() {

				fProgressBar.setValue(status);
			}

		});
	}
}

following class is the main class.
SwingProgressBar.java

public class SwingProgressBar{   
    public static void main(String[] args) {
        Mainframe frame = new Mainframe();
        frame.createGUI();
    }
}

Returning array of user defined objects in JNI.

Returning an array of complex object is not straight forward in JNI, Here I will explain an example doing it.

JAVA part.

StudentRecord.java

package com.test;
public class  StudentRecord {
	public String name;  
	public int rollNumber;  
	public String departement; 
	public float    totalMark;
	boolean hasReservation;

	public  StudentRecord(){
		name           = new String("");
		rollNumber     = 0;
		departement    = new String("");
		totalMark      = 0;
		hasReservation = false;
	}
	public String toString() {   
		return "[" + departement+ ","+ name + "," + rollNumber +"]";   
	}
}

Main class is as shown below
Test.java

package com.test;
public class Test {	
	public native static StudentRecord[] getStudentDetails(); 	
	public static void main(String[] args) {
		System.loadLibrary("Sample");
		int a= 10;
		StudentRecord[] records = getStudentDetails();		
		for(StudentRecord record:records){
			System.out.println("Name:"+record.name);
			System.out.println("Roll Number:"+record.rollNumber);
			System.out.println("Departement:"+record.departement);
			System.out.println("Total Marks:"+record.totalMark);
			System.out.println("Has Reservation:"+record.hasReservation);
		}

	}	
}

Next step would be to generate native method header file from java code.
as you know java has a tool javah for it, following figure shows the command.

The above command generates com_test_Test.h as shwown below.

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_test_Test */

#ifndef _Included_com_test_Test
#define _Included_com_test_Test
#ifdef __cplusplus
extern "C" {
#endif
    /*
    * Class:     com_test_Test
    * Method:    getStudentDetails
    * Signature: ()[Lcom/test/StudentRecord;
    */
    JNIEXPORT jobjectArray JNICALL Java_com_test_Test_getStudentDetails
        (JNIEnv *, jclass);

#ifdef __cplusplus
}
#endif
#endif

Implementation of JNI method is shown below
Sample.cpp

#include<stdafx.h>
#include<string>
#include<vector>
#include "com_test_Test.h"


typedef struct _JNI_POSREC {
    jclass cls;
    jmethodID constructortorID;
    jfieldID nameID;
    jfieldID rollNumberID;
    jfieldID departementID;
    jfieldID totalMarkID;
    jfieldID hasReservationID;
} JNI_POSREC;

/**
*   Return Search class.
*/
struct SearchRecord {
    std::string name;
    int rollNumber;
    std::string departement;
    float    totalMark;
    bool   hasReservation;
};

JNI_POSREC * jniPosRec = NULL;

/**
*   Fills the Student Record Details.
*/
void FillStudentRecordDetails(std::vector<SearchRecord*>* searchRecordResult ){
    SearchRecord *pRecord1 = new SearchRecord();
    pRecord1->name = "Ram";
    pRecord1->rollNumber = 1;
    pRecord1->departement = "Computer Science";
    pRecord1->totalMark = 512.500;
    pRecord1->hasReservation = true;
    searchRecordResult->push_back(pRecord1);

    SearchRecord *pRecord2 = new SearchRecord();
    pRecord2->name = "Raju";
    pRecord2->rollNumber = 2;
    pRecord2->departement = "Electronics";
    pRecord2->totalMark = 572.25;
    pRecord2->hasReservation = false;
    searchRecordResult->push_back(pRecord2);
}

/**
*   Fills JNI details.
*/
void LoadJniPosRec(JNIEnv * env) {

    if (jniPosRec != NULL)
        return;

    jniPosRec = new JNI_POSREC;

    jniPosRec->cls = env->FindClass("com/test/StudentRecord");

    if(jniPosRec->cls != NULL)
        printf("sucessfully created class");

    jniPosRec->constructortorID = env->GetMethodID(jniPosRec->cls, "<init>", "()V");
    if(jniPosRec->constructortorID != NULL){
        printf("sucessfully created ctorID");
    }

    jniPosRec->nameID = env->GetFieldID(jniPosRec->cls, "name", "Ljava/lang/String;");
    jniPosRec->rollNumberID = env->GetFieldID(jniPosRec->cls, "rollNumber", "I");
    jniPosRec->departementID = env->GetFieldID(jniPosRec->cls, "departement", "Ljava/lang/String;");
    jniPosRec->totalMarkID = env->GetFieldID(jniPosRec->cls, "totalMark", "F");
    jniPosRec->hasReservationID = env->GetFieldID(jniPosRec->cls, "hasReservation", "Z");

}

void FillStudentRecValuesToJni(JNIEnv * env, jobject jPosRec, SearchRecord* cPosRec) {

    env->SetObjectField(jPosRec, jniPosRec->nameID, env->NewStringUTF(cPosRec->name.c_str()));
    jint rollNum = (jint)cPosRec->rollNumber;
    env->SetIntField(jPosRec, jniPosRec->rollNumberID, rollNum);
    env->SetObjectField(jPosRec, jniPosRec->departementID, env->NewStringUTF(cPosRec->departement.c_str()));
    jfloat totalMark = (jfloat)cPosRec->totalMark;
    env->SetFloatField( jPosRec, jniPosRec->totalMarkID, totalMark);
    jboolean hasReservation = cPosRec->hasReservation;
    env->SetBooleanField( jPosRec, jniPosRec->hasReservationID, hasReservation);
}

/**
* JNI method calling from JAVA 
*/
JNIEXPORT jobjectArray JNICALL Java_com_test_Test_getStudentDetails( JNIEnv *env, jclass cls)
{
    jniPosRec = NULL;
    LoadJniPosRec(env);
    std::vector<SearchRecord*> searchRecordResult ;
    FillStudentRecordDetails(&searchRecordResult);
    printf("\nsearchRecordResult size is"+searchRecordResult.size());
    jobjectArray jPosRecArray = env->NewObjectArray(searchRecordResult.size(), jniPosRec->cls, NULL);

    for (size_t i = 0; i < searchRecordResult.size(); i++) {
        jobject jPosRec = env->NewObject(jniPosRec->cls, jniPosRec->constructortorID);
        FillStudentRecValuesToJni(env, jPosRec, searchRecordResult[i]);
        env->SetObjectArrayElement(jPosRecArray, i, jPosRec);
    }

    return jPosRecArray;
}

Building MinGW dll for JNI.

I think you are familiar with Java Native Interface (JNI), Simply it is a Java technology with which a Java application can call a library method written with such as C, C++ and assembly.

When using JNI with MSVC dll it is straight forward, but with MinGw there is some compiler option need to be set while building MinGW dll . If we follow the normal steps to create the native dll, while calling from JAVA “java.lang.UnsatisfiedLinkError” will be thrown.Here I will explain the special steps to be followed while building a JNI MinGW dll.
while compiling the MinGW DLL following compiler option should be added.

“-Wall -D_JNI_IMPLEMENTATION_ -Wl,–kill-at”

for eg: suppose I need to compile “sample.cpp” to generate JNI library “sample.dll”

g++ -Wall -D_JNI_IMPLEMENTATION_ -Wl,–kill-at Sample.cpp -shared -o Sample.dll -I.C:/Program Files/Java/jdk1.6.0_10/include -I.C:/Program Files/Java/jdk1.6.0_10/include/win32

Here “C:/Program Files/Java/jdk1.6.0_10” is the installation directory of JAVA.

CSV File Writer Class In JAVA

While saving any table data’s to file, it is better to choose a CSV file.
CSV files are just comma separated plain text files.
In my current project I created a CSV file writer class in java.
Here it is!!!

CsvFileWriter.java


import java.awt.List;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Pattern;


public class CsvFileWriter extends BufferedWriter
{
	/**
	 * Parameterized constructor
	 * @param fileName
	 * @throws IOException
	 */
	public CsvFileWriter(String fileName) throws IOException{
		super(new FileWriter(fileName));
	}
   
	/**
	 * Writes a single row to a CSV file.
	 * @param row
	 * @throws IOException
	 */
	public void WriteRow(CsvRow row) throws IOException
	{
		StringBuilder builder = new StringBuilder();
		boolean firstColumn = true;
		for(String column : row ){
			if (!firstColumn)
				builder.append(',');
			if(column != null)
			{
				if (StringUtilities.indexOfFirstContainedCharacter(column, "\"+-,") !=-1){
					column = column.replaceAll("\"", "\"\"");
					builder.append(String.format("\"%s\"",column));;
				}
				else
					builder.append(column);
				firstColumn = false;
			} 
		}
		row.lineText = builder.toString();
		write(row.lineText);
		newLine();	
	}
	
	/**
	 * 
	 *  Class to store one CSV row.
	 *
	 */
	public class CsvRow extends  ArrayList<String>
	{
		String lineText;
		
		public String getlineText(){
			return lineText;
		}
		
		public void setLineText(String lineText){
			this.lineText = lineText;
		}

	}
}

StringUtilities.java

import java.util.HashSet;
import java.util.Set;

public class StringUtilities
{	
	public static int indexOfFirstContainedCharacter(String s1, String s2) {
		if (s1 == null || s1.isEmpty())
			return -1;
		Set<Character> set = new HashSet<Character>();
		for (int i=0; i<s2.length(); i++) {
			set.add(s2.charAt(i)); // Build a constant-time lookup table.
		}
		for (int i=0; i<s1.length(); i++) {
			if (set.contains(s1.charAt(i))) {
				return i; // Found a character in s1 also in s2.
			}
		}
		return -1; // No matches.
	}
	
	public static boolean isNumeric(String str)  
	{  
	  try  
	  {  
	    double d = Double.parseDouble(str);  
	  }  
	  catch(NumberFormatException nfe)  
	  {  
	    return false;  
	  }  
	  return true;  
	}
}

CsvFileWriterSample.java


import java.io.IOException;

public class CsvFileWriterSample {
	public static void main(String[] args) throws IOException {
		CsvFileWriter fileWriter = new CsvFileWriter("sample.csv");
		
		CsvFileWriter.CsvRow headerRow = fileWriter.new CsvRow();			
		headerRow.add("No");
		headerRow.add("Name");
		headerRow.add("Age");
		headerRow.add("Sex");
		headerRow.add("Height");
		headerRow.add("Weight");		
		/**
		 * adding header row 
		 */
		fileWriter.WriteRow(headerRow);
		
		CsvFileWriter.CsvRow dataRow1 = fileWriter.new CsvRow();			
		dataRow1.add("1");
		dataRow1.add("Jhon");
		dataRow1.add("20");
		dataRow1.add("Male");
		dataRow1.add("1.72 cm");
		dataRow1.add("60 kg");		
		/**
		 * adding data row  1 
		 */
		fileWriter.WriteRow(dataRow1);
		
		CsvFileWriter.CsvRow dataRow2 = fileWriter.new CsvRow();			
		dataRow2.add("2");
		dataRow2.add("Salam");
		dataRow2.add("25");
		dataRow2.add("Male");
		dataRow2.add("1.76 cm");
		dataRow2.add("70 kg");			
		/**
		 * adding data  row 2
		 */
		fileWriter.WriteRow(dataRow2);
		
		/* always close the csv writer object after use */
		fileWriter.close();
	}
}

Generating XSD from XML file

Have you ever faced any situation to generate XSD from XML file?
Third party tools are available for generating XSD schemas from XSD.
In my last project I used a tool named Trang, It is very easy to use.
To know how to use it, Please follow the instruction as shown below.
I have an xml File simple.xml as shown below, I need to generate XSD corresponding to this XML.

simple.xml

<?xml version="1.0" encoding="utf-8"?>
<breakfast_menu>
  <food>
    <name>Belgian Waffles</name>
    <price>$5.95</price>
    <description>Two of our famous Belgian Waffles with plenty of
    real maple syrup</description>
    <calories>650</calories>
  </food>
  <food>
    <name>Strawberry Belgian Waffles</name>
    <price>$7.95</price>
    <description>Light Belgian waffles covered with strawberries
    and whipped cream</description>
    <calories>900</calories>
  </food>
</breakfast_menu>

As this application is written in JAVA,Java Run time Environment(JRE) is required to run this application.As a prerequisite ,Install JRE suitable for your platform from the link:http://www.oracle.com/technetwork/java/javase/downloads/jre7-downloads-1880261.html

1) Download Trang from http://jing-trang.googlecode.com/files/trang-20081028.zip
2) Extract the content to your system.
3) you can find directory as shown below.
4) Now copy the XML file(simple.xml) to this directory
5) Now open command prompt and move to the above directory.
6) Now type the command: java -jar trang.jar simple.xml simple.xsd , as shown below.
7) This will generate simple.xsd corresponding to simple.xml to the same folder. Output is shown below.

simple.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="breakfast_menu">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" ref="food"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="food">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="name"/>
        <xs:element ref="price"/>
        <xs:element ref="description"/>
        <xs:element ref="calories"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="name" type="xs:string"/>
  <xs:element name="price" type="xs:string"/>
  <xs:element name="description" type="xs:string"/>
  <xs:element name="calories" type="xs:integer"/>
</xs:schema>

Remove Specific Element of a Integer List in Java

I have a list of integers containing following elements say ‘1’,’3′,’5′,’7′,’34’;
it can be initailized as folllows,
List myList = Arrays.asList(1, 3, 5, 7, 34);

suppose I need to delete element ‘3’ from the list

then What we do normally is, call List’s remove method.
remove has two overloaded methods.

remove(int index); // which removes an element at a particular index.
remove (Object o); // which removes a particular element.

But if we call myList.remove(3), then elemnt at 3rd index will be deleted.
To remove element ‘3’ from the list remove should be called as follows.

myList.remove((Integer)3); // which calls  remove (Object o) method of list.

A Simple SQL Query Builder Class In JAVA For SQLITE .

When creating SQL queries Dynamically, It is very much useful to have a utility class for managing it.
SQL_QUERY_GENERATOR
In my current project I have created a simple Query builder class in JAVA supporting SQLITE Compatible queries.
Here it is!!!

SqlQueryGenerator.java

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
class SqlQueryGenerator {

	/**
	 * To add a table to the query.
	 * @param tableName name o the table to be added.
	 */
	public boolean addTable(String tableName){
		if(!QTableList.contains(tableName)){
			QTableList.add(tableName);
			return true;
		}else{
			return false;
		}
	}


	/**
	 * 
	 * @param fieldName
	 * @param value
	 * @param dataType data type of the field (Specify it as "text" for string types , "num" for numerical types)
	 * @return
	 */
	public boolean addField(String fieldName, String value, String dataType){



		if(dataType.equals("text")){

			boolean isWildchar = (StringUtilities.indexOfFirstContainedCharacter(value, "'") !=-1);
			value = getInsertValueLeftChar(isWildchar)+value+getInsertValueRightChar(isWildchar);	
		}

		QField field = new QField(fieldName, value, dataType);

		QFieldList.add(field);

		return true;
	}
	/**
	 * To add a field for Select query.
	 * @param fieldName Field name to be added.
	 * @param aliasName Alias name for the select field.
	 * @return
	 */
	public boolean addSelectField(String fieldName, String aliasName){

		if(StringUtilities.indexOfFirstContainedCharacter(fieldName, " /-") !=-1){	     
			fieldName = "`"+fieldName+"`"; 
		}

		if(StringUtilities.indexOfFirstContainedCharacter(aliasName, " /-") !=-1){	     
			aliasName = "`"+aliasName+"`"; 
		}

		QSelectField field = new QSelectField(fieldName, aliasName);

		QSelectFieldList.add(field);

		return true;
	}

	/**
	 * Overloaded function To add a field for Select query.
	 * @param fieldName Field name to be added.
	 * @return
	 */
	public boolean addSelectField(String fieldName){

		if(StringUtilities.indexOfFirstContainedCharacter(fieldName, " /-") !=-1){	     
			fieldName = "`"+fieldName+"`"; 
		}
		QSelectField field = new QSelectField(fieldName);

		QSelectFieldList.add(field);

		return true;
	}

	/**
	 * To add where condition in a query.
	 * @param fieldName Field name for the condition.
	 * @param val       Value for the field to be compared.
	 * @param op        Operator('=', '<', '>' etc...for the condition)
	 * @return
	 */
	public boolean addWhereField(String fieldName, String val, String op){

		if(StringUtilities.indexOfFirstContainedCharacter(fieldName, " /-") !=-1){	     
			fieldName = "`"+fieldName+"`"; 
		}
		QWhereField field = new QWhereField(fieldName, val,op,"AND",false);

		QWhereFieldList.add(field);
		return true;
	}
    
	/**
	 * To add where condition in a query.
	 * @param fieldName Field name for the condition.
	 * @param val       Value for the field to be compared.
	 * @param op        Operator('=', '<', '>' etc...for the condition)
	 * @param concat    Operator for the where field ('AND' or 'OR')
	 * @return
	 */
	public boolean addWhereField(String fieldName, String val, String op, String concat){

		if(StringUtilities.indexOfFirstContainedCharacter(fieldName, " /-") !=-1){	     
			fieldName = "`"+fieldName+"`"; 
		}
		QWhereField field = new QWhereField(fieldName, val,op, concat,false);

		QWhereFieldList.add(field);
		return true;
	}
    
	/**
	 * To add where condition in a query.
	 * @param fieldName Field name for the condition.
	 * @param val       Value for the field to be compared.
	 * @return
	 */
	public boolean addWhereField(String fieldName, String val){

		if(StringUtilities.indexOfFirstContainedCharacter(fieldName, " /-") !=-1){	     
			fieldName = "`" + fieldName + "`"; 
		}
		QWhereField field = new QWhereField(fieldName, val, "=", "AND", false);

		QWhereFieldList.add(field);

		return true;
	}
    
	/**
	 * To add a sub query for condition in a query.
	 * @param fieldName Field name for the condition.
	 * @param val       Value for the field to be compared.
	 * @return
	 */
	public boolean addWhereSubquery(String fieldName, String subQuery){

		if(StringUtilities.indexOfFirstContainedCharacter(fieldName, " /-") !=-1){	     
			fieldName = "`" + fieldName + "`"; 
		}
		QWhereField field = new QWhereField(fieldName, subQuery,"=", "AND", true);

		QWhereFieldList.add(field);

		return true;
	}

	public boolean addJoinField(String leftFielield, String rightField, String op){

		if(StringUtilities.indexOfFirstContainedCharacter(leftFielield, " /-") !=-1){	     
			leftFielield = "`"+leftFielield+"`"; 
		}

		if(StringUtilities.indexOfFirstContainedCharacter(rightField, " /-") !=-1){	     
			rightField = "`"+rightField+"`"; 
		}

		QWhereField field = new QWhereField(leftFielield, rightField,op,"AND", false);

		QJoinFieldList.add(field);
		return true;
	}

	/**
	 * overloaded function To add to  join query, here default operator is '='.
	 * @param fieldName1 Left field
	 * @param fieldName2 Right field
	 * @return
	 */
	public boolean addJoinField(String leftField, String rightField){

		if(StringUtilities.indexOfFirstContainedCharacter(leftField, " /-") !=-1){	     
			leftField = "`" + leftField + "`"; 
		}
		QWhereField field = new QWhereField(leftField, rightField,"=","AND", false);

		QJoinFieldList.add(field);

		return true;
	}

	/**
	 * To get the insert query.
	 * @returns Insert query.
	 */
	public String getInsertQuery(){
		String sQuery = new String("INSERT INTO ");

		sQuery += QTableList.get(0)+" ( ";

		boolean bFlag = false;
		String sField = new String();


		Iterator<QField>qFieldListItr = QFieldList.iterator();	

		while(qFieldListItr.hasNext())
		{
			sField ="";
			QField field = qFieldListItr.next();        	
			if(bFlag)	
				sField +=",";
			sField += field.fieldName;			
			sQuery += sField;
			bFlag = true;
		}

		sQuery += ") VALUES(";
		bFlag = false;

		qFieldListItr = QFieldList.iterator();	

		while(qFieldListItr.hasNext())
		{
			sField ="";
			QField field = qFieldListItr.next();        	
			if(bFlag)	
				sField +=",";
			sField += field.value;
			sQuery += sField;
			bFlag = true;
		}

		sQuery += (")");
		return sQuery;
	}
    
	/**
	 * To get the select query.
	 * @returns select query.
	 */
	public String getSelectQuery(){
		String sQuery = new String("SELECT ");
		String sField;
		boolean bFlag = false;
		Iterator<QSelectField>qSelectFieldListItr = QSelectFieldList.iterator();
		while(qSelectFieldListItr.hasNext())
		{
			QSelectField selectField = qSelectFieldListItr.next();
			sField="";
			if(bFlag)
				sField +=  ", ";
			sField += selectField.fieldName;
			if(!selectField.alias.equals(""))
				sField += " AS "+selectField.alias;

			sQuery +=  sField;
			bFlag = true;

		}

		sQuery += " FROM ";
		bFlag = false;
		Iterator<String>qTableListItr = QTableList.iterator();		
		while(qTableListItr.hasNext())
		{
			String tableName  = qTableListItr.next();
			if(bFlag)
				sQuery +=  ", ";			
			sQuery +=  tableName;
			bFlag = true;
		}

		if(!QWhereFieldList.isEmpty() || (!QJoinFieldList.isEmpty()))
			sQuery += " WHERE ";

		bFlag = false;
		Iterator<QWhereField>qWhereFieldListItr = QWhereFieldList.iterator();		

		while(qWhereFieldListItr.hasNext())
		{
			QWhereField whereField  = qWhereFieldListItr.next();
			if(bFlag)
				sQuery +=  " " + whereField.concat + " ";
			sQuery+=  whereField.fieldName + " " + whereField.operand + " " + getWhereFieldLeftSeperatorChar(whereField.isSubQuery) 
			+ whereField.value + getWhereFieldRightSeperatorChar(whereField.isSubQuery);
			bFlag = true;
		}

		if(!QJoinFieldList.isEmpty() && !QWhereFieldList.isEmpty() )
			sQuery += " AND ";

		bFlag = false;
		Iterator<QWhereField>qJoinFieldListItr = QJoinFieldList.iterator();		
		while(qJoinFieldListItr.hasNext())
		{
			QWhereField joinField  = qJoinFieldListItr.next();
			if(bFlag)
				sQuery +=  " " + joinField.concat  + " ";
			sQuery+=  joinField.fieldName + " " + joinField.operand + joinField.value ;
			bFlag = true;
		}

		return sQuery;
	}

	/**
	 * To get the delete query.
	 * @returns Delete query as String.
	 */
	public String  getDeleteQuery() {

		String sQuery ="DELETE ";
		sQuery += " FROM ";
		boolean bFlag = false;
		Iterator<String>qTableListItr = QTableList.iterator();		
		while(qTableListItr.hasNext())
		{
			String tableName  = qTableListItr.next();
			if(bFlag)
				sQuery +=  ", ";			
			sQuery +=  tableName;
			bFlag = true;
		}

		if(!QWhereFieldList.isEmpty())
			sQuery += " WHERE ";

		bFlag = false;
		Iterator<QWhereField>qWhereFieldListItr = QWhereFieldList.iterator();		
		while(qWhereFieldListItr.hasNext())
		{
			QWhereField whereField  = qWhereFieldListItr.next();
			if(bFlag)
				sQuery +=  " " + whereField.concat + " ";
			sQuery+=  whereField.fieldName + " " + whereField.operand + " '" + whereField.value + "'";
			bFlag = true;
		}

		if(!QJoinFieldList.isEmpty())
			sQuery += " WHERE ";

		bFlag = false;
		Iterator<QWhereField>qJoinFieldListItr = QJoinFieldList.iterator();		
		while(qJoinFieldListItr.hasNext())
		{
			QWhereField joinField  = qJoinFieldListItr.next();
			if(bFlag)
				sQuery +=  " " + joinField.concat + " ";
			sQuery+=  joinField.fieldName + " " + joinField.operand + " '" + joinField.value + "'";
			bFlag = true;
		}

		return sQuery;
	}

	/**
	 * To clear the query generator .
	 * @returns
	 */
	public void clear(){
		QTableList.clear();
		QFieldList.clear();
		QSelectFieldList.clear();
		QWhereFieldList.clear();
		QJoinFieldList.clear();
	}

	protected String getWhereFieldLeftSeperatorChar(boolean isSubQuery ){
		return (isSubQuery ? "(" :"\"");
	}

	protected String getWhereFieldRightSeperatorChar(boolean isSubQuery ){
		return (isSubQuery ? ")" :"\"");
	}

	protected String getInsertValueLeftChar(boolean isWildChar ){
		return (isWildChar ? "\"" :"'");
	}

	protected String getInsertValueRightChar(boolean isWildChar ){
		return (isWildChar ? "\"" :"'");
	}

	protected class QField {
		public String fieldName = new String();
		public String value     = new String();
		public String dataType  = new String();

		public QField(){
			fieldName = "";
			value     = "";
			dataType  = "";
		}
		public QField(String fieldName, String value, String dataType){
			this.fieldName = fieldName;
			this.value     = value;
			this.dataType  = dataType;

		}
	};

	protected class QWhereField {
		public String fieldName      = new String();
		public String value          = new String();
		public String operand        = new String();
		public String concat         = new String();
		public boolean isSubQuery    = false;
		public QWhereField(){
			fieldName  = "";
			value      = "";
			operand    = "";
			concat     = "";
			isSubQuery = false;
		}
		public QWhereField(String fieldName, String value, String operand, String concat,boolean isSubQuery){
			this.fieldName  = fieldName;							
			this.value      = value;
			this.operand    = operand;
			this.concat     = concat;
			this.isSubQuery = isSubQuery;
		}
	};

	protected class QSelectField {
		public String fieldName = new String();		
		public String alias     = new String();

		public QSelectField(){
			fieldName = "";
			alias     = "";			
		}

		public QSelectField(String fieldName){
			this.fieldName = fieldName;
			alias     = "";			
		}

		public QSelectField(String fieldName, String alias){
			this.fieldName = fieldName;
			this.alias     = alias;

		}
	};

	private List<String> QTableList             = new ArrayList<String>();
	private List<QField> QFieldList             = new ArrayList<QField>();	
	private List<QSelectField> QSelectFieldList = new ArrayList<QSelectField>();
	private List<QWhereField> QWhereFieldList   = new ArrayList<QWhereField>();
	private List<QWhereField> QJoinFieldList    = new ArrayList<QWhereField>();

}

StringUtilities.java

package util;

import java.util.HashSet;
import java.util.Set;

public class StringUtilities
{
	/**
	 * Utility function to check a string contains a set of characters.
	 * @param str
	 * @param token
	 * @return
	 */
	public static int indexOfFirstContainedCharacter(String str, String token) {
		Set<Character> set = new HashSet<Character>();
		for (int i=0; i<token.length(); i++) {
			set.add(token.charAt(i)); // Build a constant-time lookup table.
		}
		for (int i=0; i<str.length(); i++) {
			if (set.contains(str.charAt(i))) {
				return i; // Found a character in s1 also in s2.
			}
		}
		return -1; // No matches.
	}
}

Here I will give an example using above utility class
Sample.java

public static void main(String[] args) {
  SqlQueryGenerator queryGenerator = new SqlQueryGenerator();
  queryGenerator.addTable("Credentials");
  queryGenerator.addField("uname", "sadique", "text");
  queryGenerator.addField("pwd", "abc", "text");
  String query = queryGenerator.getInsertQuery();
  System.out.println("Query generated is:"+query);
  
  queryGenerator.clear();
  queryGenerator.addTable("Credentials");
  queryGenerator.addSelectField("uname");
  queryGenerator.addSelectField("pwd");
  queryGenerator.addWhereField("uname", "user1");
  queryGenerator.addWhereField("pwd", "myPassword");
  query = queryGenerator.getSelectQuery();
  System.out.println("Query generated is:"+query);
}