Tuesday, 20 December 2016

Converting JSONArray into CSV file in java

package com.loginController;

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONObject;
/**
 *
 * @author anand
 *
 */
public class ConvertArray {
    public static void main(String myHelpers[]){
        String jsonArrayString = "{\"fileName\": [{\"name\": \"Anand\",\"last\": \"Dwivedi\",\"place\": \"Bangalore\"}]}";

        JSONObject output;
        try {
            output = new JSONObject(jsonArrayString);


            JSONArray docs = output.getJSONArray("fileName");

            File file=new File("JSONSEPERATOR.csv");
            String csv = CDL.toString(docs);
            FileUtils.writeStringToFile(file, csv);
            System.out.println("Data has been Sucessfully Writeen to "+file);
        } catch (Exception e) {
            e.printStackTrace();
        }    
    }

}

Sunday, 18 December 2016

Custom Sorting in Java

How Custom Sorting will work in java

# Some time we may got the requirement to Sort generic Class level list into Default Sorting order in that case we will have to write own custom logic for that . below is the code to perform Custom logic in java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com;

import java.util.*;

/**
 *
 * @author anand
 */
public class CustomSorting {

    private String username;
    private String userplace;
    private String userdesignation;

    static List<CustomSorting> details = null;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUserplace() {
        return userplace;
    }

    public void setUserplace(String userplace) {
        this.userplace = userplace;
    }

    public String getUserdesignation() {
        return userdesignation;
    }

    public void setUserdesignation(String userdesignation) {
        this.userdesignation = userdesignation;
    }

    public CustomSorting(String username, String userplace, String userdesignation) {
        this.username = username;
        this.userplace = userplace;
        this.userdesignation = userdesignation;
    }

    public static void main(String[] args) {
        details = new ArrayList<CustomSorting>();

        CustomSorting customDetails = new CustomSorting("Anand", "Bangalore", "Software Developer");
        CustomSorting customDetails1 = new CustomSorting("Ajeet", "Pune", "Testing Lead");
        CustomSorting customDetails3 = new CustomSorting("Antrish", "Chennai", "C# Lead");
        CustomSorting customDetails5 = new CustomSorting("Sachin", "Rewa", "SBI Manager");
        CustomSorting customDetails6 = new CustomSorting("Anand", "Mumbai", "Software Developer");

        details.add(customDetails);
        details.add(customDetails1);
        details.add(customDetails3);
        details.add(customDetails5);
        details.add(customDetails6);

        System.out.println("==========Before Sorting==============");
        for (CustomSorting custom : details) {
            System.out.println(custom.getUsername());
        }

        Collections.sort(details, new Comparator<CustomSorting>() {

            @Override
            public int compare(CustomSorting t, CustomSorting t1) {
                if (t.getUsername().equals(t1.getUsername())) {
                    return t.getUserplace().compareTo(t1.getUserplace());
                } else {

                    return t.getUsername().compareTo(t1.getUsername());
                }

            }

        });

        System.out.println("===========After Sorting =============");
        for (CustomSorting custom : details) {
            System.out.println(custom.getUsername()+"\t"+custom.getUserplace());
        }
    }

}

Saturday, 17 December 2016

How to read CSV File in Java

Here we can learn how to read CSV file comma seprated in java below is the code

--> Use apache API to read CSV or use BufferReader
--> here i have used Buffer Reader


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
 *
 * @author anand
 *
 */
public class ReadCSVFile {

    public static void main(String[] args) {

     
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = ","; //Comma seprated

        try {

            br = new BufferedReader(new FileReader("Your_CSV_FILE_NAME"));
            while ((line = br.readLine()) != null) {
                System.out.println("Content \t"+line);

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }}

Saturday, 19 November 2016

Attribute Override in Hibernate

Model Class

/**
 *
 */
package com.learnjavabyanand;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author ananddw
 *
 */
@Entity
@Table(name="student_details")
public class Student {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int studentrollnumber;

@Column(name="student_name")
private String studentName;


@AttributeOverrides({
@AttributeOverride(name="company_location",column=@Column(name="company1_location")),
@AttributeOverride(name="company_name",column=@Column(name="company1_name"))})
private CompanyDetails comany_detalils;



public CompanyDetails getComany_detalils2() {
return comany_detalils2;
}

public void setComany_detalils2(CompanyDetails comany_detalils2) {
this.comany_detalils2 = comany_detalils2;
}

@Embedded
private CompanyDetails comany_detalils2;


public CompanyDetails getComany_detalils() {
return comany_detalils;
}

public void setComany_detalils(CompanyDetails comany_detalils) {
this.comany_detalils = comany_detalils;
}

public int getStudentrollnumber() {
return studentrollnumber;
}

public void setStudentrollnumber(int studentrollnumber) {
this.studentrollnumber = studentrollnumber;
}

public String getStudentName() {
return studentName;
}

public void setStudentName(String studentName) {
this.studentName = studentName;
}




}



Model Class 2 : 


package com.learnjavabyanand;

import javax.persistence.Embeddable;

@Embeddable
public class CompanyDetails {
private String company_name;
private String company_location;
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getCompany_location() {
return company_location;
}
public void setCompany_location(String company_location) {
this.company_location = company_location;
}

}


Hibernate Client : 


package com.learnjavabyanand;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
/**
 * @author ananddw
 *
 */
public class StudentClient {

public static void main(String[] args) {
// TODO Auto-generated method stub

Student student= new Student();
student.setStudentName("Anand Dwivedi");
CompanyDetails comp= new CompanyDetails();
comp.setCompany_name("Rediff");
comp.setCompany_location("Bangalore");
CompanyDetails comp2= new CompanyDetails();
comp2.setCompany_name("Google");
comp2.setCompany_location("Hyderabad");
student.setComany_detalils(comp);
student.setComany_detalils2(comp2);
try{
SessionFactory factory=new AnnotationConfiguration().configure().buildSessionFactory();
Session session=factory.openSession();
session.beginTransaction();
session.save(student);
session.getTransaction().commit();
session.close();
}catch(Exception e){
e.printStackTrace();
}
}

}


hibernate Configuration 


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
  <!--  Postgres DB Details  -->
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5432/hibernate</property>
    <property name="hibernate.connection.username">postgres</property>
    <property name="hibernate.connection.password">password</property>
      <!--  Postgres DB Details End  -->
    
    <!-- Postgres Dialect has information of list of  queries avil in Postgres DB -->
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <!-- Postgres Dialect End -->
    
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    
    <!--  Echo show Query  -->
    <property name="show_sql">true</property>
     <!--  Echo show Query End  -->
    
    <property name="format_sql">true</property>
    
    <!--  Create every time table and insert Data -->
    <property name="hibernate.hbm2ddl.auto">create</property>
    <!--  Create every time table and insert Data End -->
    
    <!--  Define Package for mapping class -->
    
    <mapping class="com.learnjavabyanand.Student"/>
    <!--  Define Package for mapping class End -->
   
  </session-factory>
</hibernate-configuration>



Snapshot : 




PS: Add all the required jars

Class Embedded In Hibernate

Model Class


/**
 *
 */
package com.learnjavabyanand;

import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author ananddw
 *
 */
@Entity
@Table(name="student_details")
public class Student {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int studentrollnumber;

@Column(name="student_name")
private String studentName;


@Embedded
private CompanyDetails comany_detalils;


public CompanyDetails getComany_detalils() {
return comany_detalils;
}

public void setComany_detalils(CompanyDetails comany_detalils) {
this.comany_detalils = comany_detalils;
}

public int getStudentrollnumber() {
return studentrollnumber;
}

public void setStudentrollnumber(int studentrollnumber) {
this.studentrollnumber = studentrollnumber;
}

public String getStudentName() {
return studentName;
}

public void setStudentName(String studentName) {
this.studentName = studentName;
}




}


Model Class 2 

package com.learnjavabyanand;

import javax.persistence.Embeddable;

@Embeddable
public class CompanyDetails {
private String company_name;
private String company_location;
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getCompany_location() {
return company_location;
}
public void setCompany_location(String company_location) {
this.company_location = company_location;
}

}


Client Programe : 


package com.learnjavabyanand;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
/**
 * @author ananddw
 *
 */
public class StudentClient {

public static void main(String[] args) {
// TODO Auto-generated method stub

Student student= new Student();
student.setStudentName("Anand Dwivedi");
CompanyDetails comp= new CompanyDetails();
comp.setCompany_name("Rediff");
comp.setCompany_location("Bangalore");
student.setComany_detalils(comp);
try{
SessionFactory factory=new AnnotationConfiguration().configure().buildSessionFactory();
Session session=factory.openSession();
session.beginTransaction();
session.save(student);
session.getTransaction().commit();
session.close();
}catch(Exception e){
e.printStackTrace();
}
}

}


hibernate Configuration 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
  <!--  Postgres DB Details  -->
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5432/hibernate</property>
    <property name="hibernate.connection.username">postgres</property>
    <property name="hibernate.connection.password">password</property>
      <!--  Postgres DB Details End  -->
    
    <!-- Postgres Dialect has information of list of  queries avil in Postgres DB -->
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <!-- Postgres Dialect End -->
    
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    
    <!--  Echo show Query  -->
    <property name="show_sql">true</property>
     <!--  Echo show Query End  -->
    
    <property name="format_sql">true</property>
    
    <!--  Create every time table and insert Data -->
    <property name="hibernate.hbm2ddl.auto">create</property>
    <!--  Create every time table and insert Data End -->
    
    <!--  Define Package for mapping class -->
    
    <mapping class="com.learnjavabyanand.Student"/>
    <!--  Define Package for mapping class End -->
   
  </session-factory>
</hibernate-configuration>


Snapshot : 



PS: Add all the required jars 

Auto Increment Column Name in Hibernate

Model Class


/**
 *
 */
package com.learnjavabyanand;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author ananddw
 *
 */
@Entity
@Table(name="student_details")
public class Student {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int studentrollnumber;

@Column(name="student_name")
private String studentName;

public int getStudentrollnumber() {
return studentrollnumber;
}

public void setStudentrollnumber(int studentrollnumber) {
this.studentrollnumber = studentrollnumber;
}

public String getStudentName() {
return studentName;
}

public void setStudentName(String studentName) {
this.studentName = studentName;
}




}


Client Class: 

package com.learnjavabyanand;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
/**
 * @author ananddw
 *
 */
public class StudentClient {

public static void main(String[] args) {
// TODO Auto-generated method stub

Student student= new Student();
student.setStudentName("Anand Dwivedi");
Student student2= new Student();
student2.setStudentName("Ajeet Singh");
Student student3= new Student();
student3.setStudentName("Antrish Mishra");
try{
SessionFactory factory=new AnnotationConfiguration().configure().buildSessionFactory();
Session session=factory.openSession();
session.beginTransaction();
session.save(student);
session.save(student2);
session.save(student3);
session.getTransaction().commit();
session.close();
}catch(Exception e){
e.printStackTrace();
}
}

}


hibernate Configuration file 


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
  <!--  Postgres DB Details  -->
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5432/hibernate</property>
    <property name="hibernate.connection.username">postgres</property>
    <property name="hibernate.connection.password">password</property>
      <!--  Postgres DB Details End  -->
    
    <!-- Postgres Dialect has information of list of  queries avil in Postgres DB -->
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <!-- Postgres Dialect End -->
    
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    
    <!--  Echo show Query  -->
    <property name="show_sql">true</property>
     <!--  Echo show Query End  -->
    
    <property name="format_sql">true</property>
    
    <!--  Create every time table and insert Data -->
    <property name="hibernate.hbm2ddl.auto">create</property>
    <!--  Create every time table and insert Data End -->
    
    <!--  Define Package for mapping class -->
    
    <mapping class="com.learnjavabyanand.Student"/>
    <!--  Define Package for mapping class End -->
   
  </session-factory>
</hibernate-configuration>




Snapshot : 



PS: Add all the required Jars 

Retrive Obect In Hibernate

Model Class

package com.learnjavabyanand;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

/**
 * @author ananddw
 *
 */
//@Entity will create table as per class name By if you specify name then table name must be the name what you will provide inside Entity
@Entity(name="employee_Details")
public class EmployeeDetails {

//we can put this annotation above getter as well
@Id
@Column(name="employee_name")
private String employeeName;

//ignore this variable and not create column for us
private String employeeNumber;

@Column(name="employee_location")
private String employeeLocation ;

//Used because to store Date not full time stamp
@Temporal(TemporalType.DATE)
private Date todayDate;

public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(String employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getEmployeeLocation() {
return employeeLocation;
}
public void setEmployeeLocation(String employeeLocation) {
this.employeeLocation = employeeLocation;
}
public Date getTodayDate() {
return todayDate;
}
public void setTodayDate(Date todayDate) {
this.todayDate = todayDate;
}



}


Client Class

package com.learnjavabyanand;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

/**
 * 
 * @author ananddw
 *
 */
public class HibernateClient {

public static void main(String[] args) {
// TODO Auto-generated method stub
EmployeeDetails employee= new EmployeeDetails();
employee.setEmployeeName("Anand Dwivedi");
employee.setEmployeeNumber("MER-13");
employee.setEmployeeLocation("Bangalore");
employee.setTodayDate(new Date());
try{
//get the configuration  and create a session factory once in out application 
SessionFactory factory=new AnnotationConfiguration().configure().buildSessionFactory();
//create session from session factory to save/retrive or other operation 
Session session=factory.openSession();
//new transaction and save object inside trans
session.beginTransaction();
//save Object 
session.save(employee);
//commit the session 
session.getTransaction().commit();
session.close();
//Retriving All the Object 
employee=null;
session=factory.openSession();
session.beginTransaction();
employee=(EmployeeDetails)session.get(EmployeeDetails.class, "Anand Dwivedi");
System.out.println(employee.getEmployeeName());
}catch(Exception e){
e.printStackTrace();
}

}

}


hibernate Configuration 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
  <!--  Postgres DB Details  -->
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5432/hibernate</property>
    <property name="hibernate.connection.username">postgres</property>
    <property name="hibernate.connection.password">password</property>
      <!--  Postgres DB Details End  -->
    
    <!-- Postgres Dialect has information of list of  queries avil in Postgres DB -->
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <!-- Postgres Dialect End -->
    
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    
    <!--  Echo show Query  -->
    <property name="show_sql">true</property>
     <!--  Echo show Query End  -->
    
    <property name="format_sql">true</property>
    
    <!--  Create every time table and insert Data -->
    <property name="hibernate.hbm2ddl.auto">create</property>
    <!--  Create every time table and insert Data End -->
    
    <!--  Define Package for mapping class -->
    <mapping class="com.learnjavabyanand.EmployeeDetails"/>
    <!--  Define Package for mapping class End -->
   
  </session-factory>
</hibernate-configuration>


Snapshot : 




PS: Add All the required Jars 

Transiant ,Temporaland table Annotation in Hibernate


Model Class: 


package com.learnjavabyanand;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

/**
 * @author ananddw
 *
 */
//@Entity will create table as per class name By if you specify name then table name must be the name what you will provide inside Entity
@Entity(name="employee_Details")
public class EmployeeDetails {

//we can put this annotation above getter as well
@Id
@Column(name="employee_name")
private String employeeName;

//ignore this variable and not create column for us
@Transient
private String employeeNumber;

@Column(name="employee_location")
private String employeeLocation ;

//Used because to store Date not full time stamp
@Temporal(TemporalType.DATE)
private Date todayDate;

public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(String employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getEmployeeLocation() {
return employeeLocation;
}
public void setEmployeeLocation(String employeeLocation) {
this.employeeLocation = employeeLocation;
}
public Date getTodayDate() {
return todayDate;
}
public void setTodayDate(Date todayDate) {
this.todayDate = todayDate;
}



}




HiberNate Client :-


package com.learnjavabyanand;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author ananddw
 *
 */
public class HibernateClient {

public static void main(String[] args) {
// TODO Auto-generated method stub

EmployeeDetails employee= new EmployeeDetails();
employee.setEmployeeName("Anand Dwivedi");
employee.setEmployeeNumber("MER-12");
employee.setEmployeeLocation("Bangalore");
employee.setTodayDate(new Date());

try{
//get the configuration  and create a session factory once in out application
SessionFactory factory=new AnnotationConfiguration().configure().buildSessionFactory();
//create session from session factory to save/retrive or other operation
Session session=factory.openSession();
//new transaction and save object inside trans
session.beginTransaction();
//save Object
session.save(employee);

//commit the session
session.getTransaction().commit();

}catch(Exception e){
e.printStackTrace();
}

}

}



hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
  <!--  Postgres DB Details  -->
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5432/hibernate</property>
    <property name="hibernate.connection.username">postgres</property>
    <property name="hibernate.connection.password">password</property>
      <!--  Postgres DB Details End  -->
    
    <!-- Postgres Dialect has information of list of  queries avil in Postgres DB -->
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <!-- Postgres Dialect End -->
    
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    
    <!--  Echo show Query  -->
    <property name="show_sql">true</property>
     <!--  Echo show Query End  -->
    
    <property name="format_sql">true</property>
    
    <!--  Create every time table and insert Data -->
    <property name="hibernate.hbm2ddl.auto">create</property>
    <!--  Create every time table and insert Data End -->
    
    <!--  Define Package for mapping class -->
    <mapping class="com.learnjavabyanand.EmployeeDetails"/>
    <!--  Define Package for mapping class End -->
   
  </session-factory>
</hibernate-configuration>


Folder Structure : 





PS: Please Add all the hibernate required jars as well as Database jars

HiberNate Simple Application Using Annotation


Model Class: 


package com.learnjavabyanand;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

/**
 * @author ananddw
 *
 */
//@Entity will create table as per class name By if you specify name then table name must be the name what you will provide inside Entity
@Entity(name="employee_Details")
public class EmployeeDetails {

//we can put this annotation above getter as well
@Id
@Column(name="employee_name")
private String employeeName;

@Column(name="employee_number")
private String employeeNumber;

@Column(name="employee_location")
private String employeeLocation ;


public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(String employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getEmployeeLocation() {
return employeeLocation;
}
public void setEmployeeLocation(String employeeLocation) {
this.employeeLocation = employeeLocation;
}



}



HiberNate Client :-


package com.learnjavabyanand;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

/**
 * 
 * @author ananddw
 *
 */
public class HibernateClient {

public static void main(String[] args) {
// TODO Auto-generated method stub
EmployeeDetails employee= new EmployeeDetails();
employee.setEmployeeName("Anand Dwivedi");
employee.setEmployeeNumber("MER-12");
employee.setEmployeeLocation("Bangalore");
try{
//get the configuration  and create a session factory once in out application 
SessionFactory factory=new AnnotationConfiguration().configure().buildSessionFactory();
//create session from session factory to save/retrive or other operation 
Session session=factory.openSession();
//new transaction and save object inside trans
session.beginTransaction();
//save Object 
session.save(employee);
//commit the session 
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
}

}

}


hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
  <!--  Postgres DB Details  -->
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5432/hibernate</property>
    <property name="hibernate.connection.username">postgres</property>
    <property name="hibernate.connection.password">password</property>
      <!--  Postgres DB Details End  -->
    
    <!-- Postgres Dialect has information of list of  queries avil in Postgres DB -->
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <!-- Postgres Dialect End -->
    
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    
    <!--  Echo show Query  -->
    <property name="show_sql">true</property>
     <!--  Echo show Query End  -->
    
    <property name="format_sql">true</property>
    
    <!--  Create every time table and insert Data -->
    <property name="hibernate.hbm2ddl.auto">create</property>
    <!--  Create every time table and insert Data End -->
    
    <!--  Define Package for mapping class -->
    <mapping class="com.learnjavabyanand.EmployeeDetails"/>
    <!--  Define Package for mapping class End -->
   
  </session-factory>
</hibernate-configuration>


Folder Structure : 





PS: Please Add all the hibernate required jars as well as Database jars

Friday, 21 October 2016

How to send Mail in Java

package com.sendMail;

import java.io.FileInputStream;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 *
 * @author ananddw
 *
 */

public class EmailService {

public boolean  SendMail(String voucherID){
  
    boolean flag=false;
    Properties props = System.getProperties();
    props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
    props.put("mail.smtp.port", "587"); //TLS Port
    props.put("mail.smtp.auth", "true"); //enable authentication
    props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS

    StringBuilder mailBody = new StringBuilder("Hi,<br/><br/>");
    mailBody.append("Mail is Created Succesfully<br/><br/>");
    mailBody.append(" Time: " + System.currentTimeMillis() + ""+ "<br/><br/>");
  
    mailBody.append("Send By : Anand <br/><br/><br/>");
    mailBody.append("Thanks & Regards<br/>Anand Dwivedi");

    Session session = Session.getInstance(props,null);
    MimeMessage message = new MimeMessage(session);

    System.out.println("Port: "+session.getProperty("mail.smtp.port"));

    // Create the email addresses involved
    try {
        String [] mailTo=new String[] {"test@gmail.com" };
        InternetAddress[] addressTo = new InternetAddress[mailTo.length];
        for (int i = 0; i < mailTo.length; i++) {
            addressTo[i] = new InternetAddress(mailTo[i]);
            addressTo[i].validate();
        }
        InternetAddress from = new InternetAddress("test@gmail.com");
        message.setSubject(" Message Mail");
        message.setFrom(from);
        message.addRecipients(Message.RecipientType.TO,addressTo);

        // Create a multi-part to combine the parts
        Multipart multipart = new MimeMultipart("alternative");

        // Create your text message part
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText("some text to send");

        // Add the text part to the multipart
        multipart.addBodyPart(messageBodyPart);

        // Create the html part
        messageBodyPart = new MimeBodyPart();
        String htmlMessage = mailBody.toString();
        messageBodyPart.setContent(htmlMessage, "text/html");


        // Add html part to multi part
        multipart.addBodyPart(messageBodyPart);

        // Associate multi-part with message
        message.setContent(multipart);

        // Send message
        Transport transport = session.getTransport("smtp");
        transport.connect("smtp.gmail.com", "test@gmail.com", "Gmail password");
        System.out.println("Transport: "+transport.toString());
        transport.sendMessage(message, message.getAllRecipients());

        flag=true;
    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        flag=false;
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        flag=false;
    }
    return flag;
}

public static void main(String []args){    
EmailService service=new EmailService();
  service.SendMail();
}
}


PS: Make sure that attache all the required Jars as well as 

Turn On This service if it is off: https://www.google.com/settings/security/lesssecureapps

Sunday, 9 October 2016

Action Message and Action Error in Struts2

Find below code to check how action Error and Action Message is working in Struts2

####login.jsp


<%--
    Document   : login
    Created on : Oct 09, 2016, 2:50:34 PM
    Author     : shiboo
--%>
<!DOCTYPE html>
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Login</title>
</head>
<body>
<center><h3>ActionMessage Example</h3>
<s:actionerror />
<s:form action="login">
<s:textfield name="userName"  label="Username" />
<s:password name="password"  label="password" />
<s:submit value="Login" />
</s:form>
</center>

</body>

</html>


####success.jsp

<%--
    Document   : success
    Created on : Oct 09, 2016, 2:41:34 PM
    Author     : shiboo
--%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
<h3>ActionError &amp; ActionMessage Examples</h3>
<s:actionmessage />
</body>
</html>

###Struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="login" class="com.Messageaction.LoginAction">
<result name="success">success.jsp</result>
<result name="input">login.jsp</result>
</action>
</package>
</struts>


###LoginAction.java

package com.Messageaction;
import com.opensymphony.xwork2.ActionSupport;

/**
 *
 * @author shiboo
 *
 */
public class LoginAction extends ActionSupport {

private static final long serialVersionUID = 6677091252031583948L;
private String userName;
private String password;


public String execute() {

return SUCCESS;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}


public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public void validate() {

if (userName.isEmpty()) {
addActionError("Username is not blanked");
} else {
if(password.isEmpty()){
addActionError("Password is not blanked");
}else{
addActionMessage("Welcome " + userName);
}}
}
}


#### web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Struts2</display-name>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
</web-app>


Please find below screenshot 







Friday, 7 October 2016

Hibernate Application Java

  • Hibernate framework simplifies the development of java application to interact with the database. Hibernate is an open source, lightweight  tool. 

  • An ORM tool simplifies the data creation, data manipulation and data access. It is a programming technique that maps the object to the data stored in the database.

Example

Student.java

package com.hibernate;
/**
 *
 * @author ananddw
 *
 */
public class Student {
   
    private int id;
    private String studentName;
    private String studentPlace;
   
    //Setter and Getters
   
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public String getStudentPlace() {
        return studentPlace;
    }
    public void setStudentPlace(String studentPlace) {
        this.studentPlace = studentPlace;
    }
   
   

}

 ==========StudentResourc.java ====================
package com.hibernate;
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
import org.hibernate.cfg.Configuration; 

/**
 *
 * @author ananddw
 *
 */
public class StudentResource { 
public static void main(String[] args) { 
    StudentResource studentresrouce=new StudentResource();
    studentresrouce.saveObject();
}
public boolean saveObject(){
    boolean flag=false;
try{  
  Configuration cfg=new Configuration(); 
  cfg.configure("hibernate.cfg.xml");
  SessionFactory factory=cfg.buildSessionFactory();  
  Session session=factory.openSession(); 
  Transaction t=session.beginTransaction();
 
  Student student = new Student();
  student.setId(3);
  student.setStudentName("Rahul");
  student.setStudentPlace("Mumbai");
  session.saveOrUpdate(student);
   
  t.commit();
  session.close(); 
   
  System.out.println("successfully saved"); 
}catch(Exception e){
    e.printStackTrace();
    flag=false;

  return flag;

}

=============hibernate.cfg.xml ========================





<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5432/hibernate</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>

        <mapping resource="com/hibernate/student.cfg.xml" />


    </session-factory>
</hibernate-configuration>




==================student.cfg.xml=============

<?xml version='1.0' encoding='UTF-8'?> 
    <!DOCTYPE hibernate-mapping PUBLIC 
     "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
     
     <hibernate-mapping> 
      <class name="com.hibernate.Student" table="student"> 
        <id name="id"> 
         <generator class="native"></generator> 
        </id> 
               
        <property name="studentName"></property> 
        <property name="studentPlace"></property> 
               
      </class> 
               
     </hibernate-mapping>



PS: Please Add Required Jars to run hibernate Application


hibernate3.jar
dom4j-1.6.1.jar
commons-logging-1.1.1.jar
commons-collections-2.1.1.jar
postgresql-8.3-603.jdbc3.jar
cglib-2.1_3.jar
cglib-nodep-2.1_3.jar
asm-1.5.2.jar
asm-analysis-1.5.2.jar
asm-attrs-1.5.2.jar
asm-tree-1.5.2.jar
asm-util-1.5.2.jar
asm-xml-1.5.2.jar
jta.jar
antlr.jar





Map class field to map

 import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class AutogeneratedClassMapper {     public static M...