Wednesday, 17 September 2014

How to use CRUD with Mysql in Java

Leave a Comment
In my previous post i am telling you crud on Hibernate and if we're beginner then we need to start our program with starting .That's why you read here how to use crud function with mysql for your java projects.
This tutorial gives you overview of Hibernate and ease to understand them in future.
I will demostrate how to create table named “Person”, how to select all records, how to select specific record (by id), how to insert a new record, how to update existing record and how to delete record.
CONNECT JAVA APPLICATION TO MYSQL DATABASE AND PERFORM CRUD OPERATIONS,JAVA APPLICATION TO MYSQL DATABASE AND PERFORM CRUD OPERATIONS,APPLICATION TO MYSQL DATABASE AND PERFORM CRUD OPERATIONS,MYSQL DATABASE AND PERFORM CRUD OPERATIONS,DATABASE AND PERFORM CRUD OPERATIONS,PERFORM CRUD OPERATIONS,CRUD OPERATIONS,How to use CRUD with Mysql in Java,use CRUD with Mysql in Java,CRUD with Mysql in Java,Mysql in Java,

First of all you need to create java bean class named “Person.java”:
public class Person {
 
    private int id;
    private String firstName;
    private String lastName;
 
    public Person() {
 
    }
 
    public Person(String firstName,String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getFirstName() {
        return firstName;
    }
 
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
 
    public String getLastName() {
        return lastName;
    }
 
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}
Next thing you are going to do is to create a small utility class named “ConnectionConfiguration” with a single method which will return a connection to database named “test”:
public class ConnectionConfiguration {
    public static final String URL = "jdbc:mysql://localhost:3306/test";
    /**
     * In my case username is "root" *
     */
    public static final String USERNAME = "root";
    /**
     * In my case password is "1234" *
     */
    public static final String PASSWORD = "geekonjava";
 
    public static Connection getConnection() {
        Connection connection = null;
 
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return connection;
    }
 
}
And finally, last class you will create is a class named “PersonDaoImpl” where all magic happens.
public class PersonDaoImpl implements PersonDao {
 
    /**Creates table named Person with three columns (id, first_name, last_name)**/
   
    public void createPersonTable() {
        Connection connection = null;
        Statement statement = null;
 
        try {
            connection = ConnectionConfiguration.getConnection();
            statement = connection.createStatement();
            statement.execute("CREATE TABLE IF NOT EXISTS person (id int primary key unique auto_increment," +
                    "first_name varchar(55), last_name varchar(55))");
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
 
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    /**Inserts new record in Person table as you pass new Person instance**/
   
    public void insert(Person person) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
 
        try {
            connection = ConnectionConfiguration.getConnection();
            preparedStatement = connection.prepareStatement("INSERT INTO person (first_name,last_name)" +
                    "VALUES (?, ?)");
            preparedStatement.setString(1, person.getFirstName());
            preparedStatement.setString(2, person.getLastName());
            preparedStatement.executeUpdate();
            System.out.println("INSERT INTO person (first_name,last_name)" +
                    "VALUES (?, ?)");
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
 
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    /**Returns specific record (single person object) from table depending on "id" you provide**/
   
    public Person selectById(int id) {
        Person person = new Person();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
 
        try {
            connection = ConnectionConfiguration.getConnection();
            preparedStatement = connection.prepareStatement("SELECT * FROM person WHERE id = ?");
            preparedStatement.setInt(1, id);
            resultSet = preparedStatement.executeQuery();
 
            while (resultSet.next()) {
                person.setId(resultSet.getInt("id"));
                person.setFirstName(resultSet.getString("first_name"));
                person.setLastName(resultSet.getString("last_name"));
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
 
        return person;
    }
 
    /**Returns all records from table as a List of person objects**/
   
    public List<Person> selectAll() {
        List<Person> persons = new ArrayList<Person>();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
 
        try {
            connection = ConnectionConfiguration.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery("SELECT * FROM person");
 
            while (resultSet.next()) {
                Person person = new Person();
                person.setId(resultSet.getInt("id"));
                person.setFirstName(resultSet.getString("first_name"));
                person.setLastName(resultSet.getString("last_name"));
 
                persons.add(person);
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
 
        return persons;
    }
 
    /**Deletes single record depending on "id" you provide**/
   
    public void delete(int id) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
 
        try {
            connection = ConnectionConfiguration.getConnection();
            preparedStatement = connection.prepareStatement("DELETE FROM person WHERE id = ?");
            preparedStatement.setInt(1, id);
            preparedStatement.executeUpdate();
 
            System.out.println("DELETE FROM person WHERE id = ?");
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    /**Updates a specific record depending on "id"
     * after you pass new Person object with new values**/
    
    public void update(Person person, int id) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
 
        try {
            connection = ConnectionConfiguration.getConnection();
            preparedStatement = connection.prepareStatement("UPDATE person SET " +
                    "first_name = ?, last_name = ? WHERE id = ?");
 
            preparedStatement.setString(1, person.getFirstName());
            preparedStatement.setString(2, person.getLastName());
            preparedStatement.setInt(3, id);
            preparedStatement.executeUpdate();
 
            System.out.println("UPDATE person SET " +
                    "first_name = ?, last_name = ? WHERE id = ?");
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Note that I intensively used PreparedStatement which protects us from SQL injection attacks.
Also, you can create a single class where you can test your data access model:
public class App {
 
    public static void main(String [] args) {
        PersonDaoImpl pdi = new PersonDaoImpl();
 
        /**Create table. Note that you can always run this
         * method. Table will be created only once (if it doesn't exist)**/
        pdi.createPersonTable();
 
        /**Insert a new record. Create a new Person instance and just
         * pass it as an argument in "insert" method**/
        Person person = new Person("John","Johnson");
        pdi.insert(person);
 
        /**Select by id**/
        Person personSelect = pdi.selectById(2);
        System.out.println(personSelect.getId()+", "+personSelect.getFirstName()+", "+personSelect.getLastName());
 
        /**Delete person by id**/
        pdi.delete(3);
 
        /**Update person**/
        Person personUpdate = new Person("Tom","Johnson");
        pdi.update(personUpdate,1);
 
        /**Select all persons**/
        List<Person> persons = pdi.selectAll();
        /**To retrieve values, you will have to use "for each" loop
         * to iterate through list**/
        for(Person p : persons) {
            System.out.println(p.getId()+", "+p.getFirstName()+", "+p.getLastName());
        }
 
    }
}

Hope it useful for you.

Read More

Thursday, 11 September 2014

Hibernate CRUD example using HQL query language

Leave a Comment
Hello all beginners today i am telling you a CRUD example in hibernate by which you can be make a small example until you make a expert.
By this example you got some knowledge of HQL (Hibernate Query Language).
If you're novice in Hibernate then this example obviously help you to understand them.

In this demo first of all you need to make a java project and add the project capabilities of Hibernate.
Here i use a simple example on Student( Insert,Update,Read and Write ).
Hibernate CRUD example using HQL query language,CRUD example using HQL query language,example using HQL query language, HQL query language,hql example,hibernate tutorial,hibernate crud

In this example two package :
  • com.demo.gsfile
all the getter setter and methods exist in this package
Sudent.java is variable and getter setter file.
  • com.demo.dbfile
all the database functions are exist in this package.
StudentDB.java  is database function file
StudentWork.java  is main file which would be run.

Hibernate function using HQL
package com.demo.dbfile;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

import com.demo.gsfile.Student;

public class StudentDb 
{
 
 private static SessionFactory factory; 
    
    
    
    public static SessionFactory SessionData()
    {
     try{
           factory = new Configuration().configure().buildSessionFactory();
        }catch (Throwable ex) { 
           System.err.println("Failed to create sessionFactory object." + ex);
           throw new ExceptionInInitializerError(ex); 
        }
     return factory;
    }
    /* Method to INSERT student in the database */
    public static Integer addStudent(String stuname,String sturoll,String stuage,String stuschool)
    {
     factory=StudentDb.SessionData();
       Session session = factory.openSession();
       Transaction tx = null;
       Integer employeeID = null;
       try{
          tx = session.beginTransaction();
          Student stu = new Student(stuname,sturoll,stuage,stuschool);
          employeeID = (Integer) session.save(stu); 
          tx.commit();
       }catch (HibernateException e) {
          if (tx!=null) tx.rollback();
          e.printStackTrace(); 
       }finally {
          session.close(); 
          factory.close();
       }
       return employeeID;
    }
   //  Method to  READ all the students 
    public static List listStudents(String query1){
     factory=StudentDb.SessionData();
       Session session = factory.openSession();
       List list=null;
       Transaction tx = null;
       try{
          tx = session.beginTransaction();

          Query query=session.createQuery("from Student "+query1);//here persistent class name is Emp  
           list=query.list(); 
          tx.commit();
         
       }catch (HibernateException e) {
          if (tx!=null) tx.rollback();
          e.printStackTrace(); 
       }finally {
          session.close(); 
          factory.close();
       }
  return list;
    }
    // Method to UPDATE salary for an employee 
   public static int updateStudent(String query ){
     factory=StudentDb.SessionData();
       Session session = factory.openSession();
       int status=0;
       Transaction tx = null;
       try{
          tx = session.beginTransaction();
          Query q=session.createQuery("update Student "+query);  
          
            
           status=q.executeUpdate();  
          System.out.println(status);  
          tx.commit();
       }catch (HibernateException e) {
          if (tx!=null) tx.rollback();
          e.printStackTrace(); 
       }finally {
          session.close(); 
       }
       return status;
    }
     //Method to DELETE an employee from the records 
    public static void deleteStudent(String query){
     factory=StudentDb.SessionData();
       Session session = factory.openSession();
       int i=0; 
       Transaction tx = null;
       try{
          tx = session.beginTransaction();

          Query query1=session.createQuery("delete from Student "+query);  
        
        i=query1.executeUpdate();  
          tx.commit();
       }catch (HibernateException e) {
          if (tx!=null) tx.rollback();
          e.printStackTrace(); 
       }finally {
          session.close(); 
       }
    }
 



    
    
}

Download all program here.





Read More

Monday, 8 September 2014

EContact Android Project

Leave a Comment
Today i am giving you a project on Android which named is Econtact.
What is EContact ?
It  is designed to help users in emergency situation. Using E contact mobile app user can contact hospital, fire station, police, bock bank, emergency contact and ambulance. 
Project Introduction:

The bottom line is that the main idea behind this project was to create an android application that could be of great use in times of emergency. Our goal is to help set an official guideline to assist Emergency Response Teams in their efforts to save time and lives in the event of an emergency and help people in times of emergency.

EContact Android Project,Android Project,Emergency Response Teams,EContact ,LIFE SAVER android apps,econtact apps,google map project,contact project,college project


There would also be functionalities that would allow quick access to all relevant information that would be required at the times of an emergency. Thus, with only one click on your screen, we can send SMS alerts to all your saved contacts,call rescue workers.Thus, this application could be a LIFE SAVER in times of a calamity.

Download                       Documentation

E Contact APP Design:

Here are few high-level details of application:


EContact Android Project,Android Project,Emergency Response Teams,EContact ,LIFE SAVER android apps,econtact apps,google map project,contact project,college project


  1. Whenever you install the application for the first time, it is mandatory to enter your details and register yourself by providing your name,contact number, blood group, emergency contact name and emergency contact number.
  2. An option to update your and your emergency contact details is provided in the application under the “Settings” option. Incase you want to give your phone to someone, they can update their corresponding details instead of uninstalling and installing the app again.
  3. Feature to contact the emergency contact number is provided under “Help” option.
  4. Feature to contact rescue hotlines is provided under “SOS” session.
  5. Option to send a request for blood group by sending an SMS to all the contacts, which includes the current location of the user, blood group required is possible with the “Blood Bank” feature.
  6. Nearest hospitals, Ambulance Service, Fire Station, Police Stations available can be searched using the corresponding options provided in our application. 
Read More

Sunday, 7 September 2014

How to Expanding your dictionary of acoustic model in Sphinx project

Leave a Comment
Hello Everyone,

Today I’m going to tell you how to expand dictionary of acoustic model for Sphinx4. In simple words, This tutorial will tell you how you can add more words in Sphinx’s words database (Dictionary) and let it recognize those words, which are not available in default acoustic models provided by CMU Sphinx. This tutorial is based on “HelloWorld” example provided by CMU Sphinx.



Important Files in this example :

  1. HelloWorld.java
  2. hello.gram
  3. helloworld.config.xml

Acoustic Model used in this example : 
WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar

Now, I will tell you, How to add name of cities and states in dictionary.

PART ONE

  1. Create a txt file “words.txt”, Write all the names of cities and states in it and save.
  2. Open this link : http://www.speech.cs.cmu.edu/tools/lmtool.html
  3. On that page, go to “Sentence corpus file:” section, Browse to “words.txt” file and click “Compile Knowledge Base”.
  4. On next page, Click on “Dictionary” link and save that .DIC file.

PART TWO

  1. Extract WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar file.
  2. Go to edu\cmu\sphinx\model\acoustic\WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz\dict folder.
  3. Open “cmudict.0.6d” file in that folder.
  4. Copy data from .DIC file, you have downloaded in PART ONE, paste it in “cmudict.0.6d” file and save.
  5. Zip the extracted hierarchy back as it was and Zip file named should be same as JAR file.

Note:
Now, remove “WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar” file from Project’s CLASSPATH and add “WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.zip” instead of it.

That’s it ! We are done.  Now Sphinx will also recognize all name of cities and states that we wrote in “words.txt” file.

If you have any quires, Please feel free to ask.

Read More

Friday, 5 September 2014

How to Split only after comma 3 times appear in Java

Leave a Comment
Question asked by my friend :
I have a string that looks like this:
0,0,1,2,4,5,3,4,6
What I want returned is a string[] that was split after every 3rd comma, so it would look like this:
[ "0,0,1", "2,4,5", "3,4,6" ]
I have found similiar functions but they all don't split with the nth amount of commas.
You can try to use split method with (?<=\\G\\d+,\\d+,\\d+), regex
String data = "0,0,1,2,4,5,3,4,6";
String[] array = data.split("(?<=\\G\\d+,\\d+,\\d+),"); //Magic :) 
// to reveal magic see explanation below answer
for(String s : array){
    System.out.println(s);
}
How to Split only after comma 3 times appear in Java,Split only after comma 3 times appear in Java,only after comma 3 times appear in Java,comma 3 times appear in Java,3 times appear in Java,times appear in Java,appear in Java,

Output:

0,0,1
2,4,5
3,4,6
Explanation

  • \\d means one digit, same as [0-9], like 0 or 3
  • \\d+ means one or more digits like 1 or 23
  • \\d+, means one or more digits with comma after it, like 1, or 234,
  • \\d+,\\d+,\\d+ will accept three numbers with commas between them like 12,3,456
  • \\G means last match, or if there is none (in case of first usage) start of the string
  • (?<=...), is positive look-behind which will match comma , that has also some string described in (?<=...) before it
  • (?<=\\G\\d+,\\d+,\\d+), so will try to find comma that has three numbers before it, and these numbers have aether start of the string before it (like ^0,0,1 in your example) or previously matched comma, like 2,4,5 and 3,4,6.

Also in case you want to use other characters then digits you can also use other set of characters like

  • \\w which will match alphabetic characters, digits and _
  • \\S everything that is not white space
  • [^,] everything that is not comma
  • ... and so on. More info in Pattern documentation

By the way, this form will work with split on every 3rd, 5th, 7th, (and other odd numbers) comma, like split("(?<=\\G\\w+,\\w+,\\w+,\\w+,\\w+),") will split on every 5th comma.

To split on every 2nd, 4th, 6th, 8th (and rest of even numbers) comma you will need to replace + with {1,maxLengthOfNumber} like split("(?<=\\G\\w{1,3},\\w{1,3},\\w{1,3},\\w{1,3}),") to split on every 4th comma when numbers can have max 3 digits (0, 00, 12, 000, 123, 412, 999).

Hope if you face same problem and then you got answer.
Read More

Thursday, 4 September 2014

How to Upload file with Text Easily in Java Using GOJFileUpload

Leave a Comment
Hello friends in my previous post i am telling you how to upload your file in java using GOJFileUpload.jar.
But when we need a form where file upload button and some textfields are also exist then you need to do nothing more.
How to Upload file with Text Easily in Java Using GOJFileUpload,Upload file with Text Easily in Java Using GOJFileUpload,file with Text Easily in Java Using GOJFileUpload,Text Easily in Java Using GOJFileUpload,Easily in Java Using GOJFileUpload,Java Using GOJFileUpload,GOJFileUpload,

What would you do ?
see below friends...
uploadfilewithtext.jsp
 <form action="FetchDataAndFile.jsp" enctype="multipart/form-data" name="form1" id="form1" method="post">
  
  First Text:<input type="text" name="firsttext"><br>
  Second Text:<input type="text" name="secondtext"><br>
   First Image:<input type="file" name="img1"><br>
   Second Image:<input type="file" name="img2"><br>
  Third Text:<input type="text" name="thirdtext"><br>
   <input type="submit" name="submit" value="Submit Product">
   </form>
FetchDataAndFile.jsp
<%@page import="com.geekonjava.fileupload.FileUploading"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.HashMap"%>
<%
String imagepath=config.getServletContext().getRealPath("/")+"files\\";


ArrayList<String> imagename = new ArrayList<String>();
      imagename.add("img1");
      imagename.add("img2");
      
ArrayList<String> dataname = new ArrayList<String>();
      dataname.add("firsttext");
     dataname.add("secondtext");
      dataname.add("thirdtext");
 
HashMap map = FileUploading.UploadFile(imagepath,dataname,imagename,request);
out.println(map.get("error")+"<br>");
out.println(map.get("img1")+"<br>");
out.println(map.get("firsttext")+"<br>");
out.println(map.get("img2")+"<br>");
out.println(map.get("secondtext")+"<br>");
out.println(map.get("thirdtext")+"<br>");

%>
After that we need to upload package named : com.geekonjava.fileupload.FileUploading

GOJLibrary give you UploadFile method which has four parameter :

imagepath- this is a field for set the uploading path.
dataname-this is a field for all text data name by using ArrayList.
imagename-this is a field for all images name by using ArrayList.
request-its not for programmer and not be changed.
They'll return you the all file name which you uploaded after uploading at your given destination folder.
Read More

How to Upload file in Java Using GOJFileUpload library

Leave a Comment
Hello friends i face the problem on uploading files and many of types for them in java. If you want to upload single file or file with text data at that time you really face problem in your web project.
Obviously you use servlet for  them but today i am telling you a proper solution for them and the solution is
GOJFileUpload-1.0.1.jar
This jar file gives you a easy way to upload your files easily and how can you achieve them.
You need five libraries for it
  1. commons-fileupload-1.2.1.jar
  2. commons-io-1.4.jar
  3. GOJFileUpload-1.0.1.jar
  4. javax.servlet.jar
  5. org-apache-commons-codec.jar

How to Upload file in Java Using GOJFileUpload library,Upload file in Java Using GOJFileUpload library,file in Java Using GOJFileUpload library,Java Using GOJFileUpload library,Using GOJFileUpload library,GOJFileUpload library,Easy way to upload file in java,way to upload file in java,upload file in java,file in java,

index.jsp
<form action="FetchData.jsp" enctype="multipart/form-data" name="form1" id="form1" method="post">
  
 
   First Image:<input type="file" name="img1"><br>
   Second Image:<input type="file" name="img2"><br>
  
   <input type="submit" name="submit" value="Submit Product">
   </form>
Above coding is a frond end where have file upload button and action goes to FetchData.jsp where our upload coding exist.


FetchData.jsp
<%@page import="com.geekonjava.fileupload.FileUploading"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.HashMap"%>
<%
String imagepath=config.getServletContext().getRealPath("/")+"files\\";


ArrayList<String> imagename = new ArrayList<String>();
      imagename.add("img1");// name from index page of first image
      imagename.add("img2");// name from index page of second image

HashMap map = FileUploading.UploadFile(imagepath,imagename,request);
out.println(map.get("error")+"<br>");
out.println(map.get("img1")+"<br>");
out.println(map.get("img2")+"<br>");

%>

After that we need to upload package named : com.geekonjava.fileupload.FileUploading
GOJLibrary give you UploadFile method which has three parameter :

  • imagepath- this is a field for set the uploading path.
  • imagename-this is a field for all images name by using ArrayList.
  • request-its not for programmer and not be changed.
They'll return you the all file name which you uploaded after uploading at your given destination folder.

If you want to upload file with textfield data then check this
Read More