Tuesday, March 25, 2014

Personal

R;wlsdev/guddom
weblogic
gmsequence
Feb 15 2014:

2.157 gms     2862
5.97   gms     2862

-------------------
23260 Only Gold price(2862 per gram)
26500 Actual given by me to shop kalyana kanchi
--------
3240 Extra not for gold which is 12.22% for making and charges

May 24 2014

3.77 gms 2646 VA 1747.09 amount 11723 dis 450.72 11272.28
0.256       2646        110.26  amount    788   dis   30.57      757.43


HBK:Orgsequence

rishitha
ubuntu pwd

Oracle
hr
hr
sys or system

Mysql

1) Install the libaio1 package .
             sudo apt-get install libaio1

2) Install the Oracle 10g XE :
             dpkg -i oracle-xe_10.2.0.1-1.0_i386.deb

3) Configure the installation:
             /etc/init.d/oracle-xe configure

Enter the following configuration information:
A valid HTTP port for the Oracle Application Express (the default is 8080)
A valid port for the Oracle database listener (the default is 1521)
A password for the SYS and SYSTEM administrative user accounts
Confirm password for SYS and SYSTEM administrative user accounts 
Whether you want the database to start automatically when the computer starts (next reboot). 

4) Set-up the environment variables :
Add following lines to .bashrc of the user which you will using to access the Oracle 10g XE:
export ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/server
export ORACLE_SID=XE
export PATH=$ORACLE_HOME/bin:$PATH

5) Start a new shell ( terminal window ) for the changes to take effect or execute the .profile to force the changes made in the same session.
         . ./.profile

6) Use the command "sqlplus sys as sysdba" and the password which you created while configuration to connect to the database.

Swap space problem came


http://www.facebook.com/l.php?u=http%3A%2F%2Fubuntuone.com%2F2wvJRVBirvGD5zUpWCtP2X&h=9AQFQaxm6 for deb download


ufaagc
uvf467 IRCTC

ufaagc
Sub@32313029

CHINTHA
Boc@sequence
Rtn@sequence

vnailkumar21
Sop
4c7cf2









Saturday, February 22, 2014

How to Map Composite Primary Key using annotations in Hibernate ?

What is Composite primary key ?

Sometimes you may not have primary key for table.In such cases you use combination of properties
to uniquely identify a record in the table.The combination of fields is called composite primary key.

Normally in hibernate you map primary key with @Id.

To map composite primary key you have to define a new class with the properties that
uniquely identify a record.This class should implement Serializable.

This class need to be annotated with @Embeddable annotation.

Example:

CustomerId.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 hibex;

import java.io.Serializable;
import javax.persistence.Embeddable;

/**
 *
 * @author Rishitha
 */
@Embeddable
public class CustomerId implements Serializable{
  private String cfname;
  private String clname;
  public CustomerId(){}
  public CustomerId(String cfname, String clname) {
    this.cfname = cfname;
    this.clname = clname;
  }

    public String getCfname() {
        return cfname;
    }

    @Override
    public boolean equals(Object obj) {
        CustomerId cp =(CustomerId)obj;
        if(this.cfname.equals(cp.getCfname()) && this.clname.equals(cp.getClname())){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public int hashCode() {
        return this.cfname.hashCode()+this.clname.hashCode();
    }

    public void setCfname(String cfname) {
        this.cfname = cfname;
    }

    public String getClname() {
        return clname;
    }

    public void setClname(String clname) {
        this.clname = clname;
    }
 
 
}

Customer.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 hibex;

import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Id;

/**
 *
 * @author Rishitha
 */
@Entity
public class Customer {
 @Id
  private CustomerId id;

  private String email;

   
  public CustomerId getId() {
        return id;
    }

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

  
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
 
  public Customer(){}
 
 
 
}


/*
 * 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 hibex;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Order;
import org.jl.vo.StudentTo;

/**
 *
 * @author Rishitha
 */
public class CustomerCompTest {
    public static void main(String args[]){
       
         SessionFactory sf = new Configuration().configure("hibernate.cfgComp.xml").buildSessionFactory();
       
     
        Session ses = sf.openSession();
      
        Transaction tx = null;
        try{
            tx = ses.beginTransaction();
            CustomerId cid = new CustomerId("Anil","Chintha");
           
            Customer c =(Customer)ses.get(Customer.class, cid);
          
            if(c!= null)
                System.out.println("Email of customer is "+c.getEmail());
           
            //Save new student
            CustomerId scid = new CustomerId("Prasanna","Chintha");
            Customer sc = new Customer();
            sc.setId(scid);
            sc.setEmail("sunil@gmail.com");
            ses.save(sc);
            tx.commit();
        }catch(Exception e ){
            e.printStackTrace();
        }
       
  }
}



<?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.dialect">org.hibernate.dialect.OracleDialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
    <property name="hibernate.connection.username">hr</property>
    <property name="hibernate.connection.password">hr</property>
    <property name="hibernate.hbm2ddl.auto" >update</property>
    <property name="hibernate.show_sql">true</property>
    <mapping class="hibex.Customer"/>
   
   
  </session-factory>
</hibernate-configuration>







Sunday, February 16, 2014

How to maintain Transaction Management in hibernate using Spring HibernateTransactionManager ?

StudentController.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 org.jl.controllers;

import org.jl.services.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 * @author Rishitha
 */
@Controller
public class StudentController {

    @Autowired
    StudentService regService;
    @Autowired
    HibernateTransactionManager ptm;

    @RequestMapping("/studentReg.spring")

    String saveStudentRegDetails(StudentTo st) {
        TransactionStatus td = ptm.getTransaction(new DefaultTransactionDefinition());

        try {
            //This calls dao and tries
            //to insert student details in to 2 tables
            //student
            regService.registerStudent(st);
        } catch (Exception e) {
            ptm.rollback(td);
            return "failure";
        }
        ptm.commit(td);
        return "success";

    }

}

2)StudentTo.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 org.jl.controllers;

import java.io.Serializable;

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

/**
 *
 * @author Rishitha
 */
@Entity
@Table(name = "studentdet")
public class StudentTo implements Serializable {
    @Id
    @GeneratedValue
    private Integer sid;
    private String sname;
    private String scity;

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }
   
    public StudentTo(){
       
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getScity() {
        return scity;
    }

    public void setScity(String scity) {
        this.scity = scity;
    }
   
   
   
}

3)StudentToCopy.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 org.jl.controllers;

import java.io.Serializable;

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

/**
 *
 * @author Rishitha
 */
@Entity
@Table(name = "studentdet")
public class StudentTo implements Serializable {
    @Id
    @GeneratedValue
    private Integer sid;
    private String sname;
    private String scity;

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }
   
    public StudentTo(){
       
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getScity() {
        return scity;
    }

    public void setScity(String scity) {
        this.scity = scity;
    }
   
   
   
}


4)StudentDAOI.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 org.jl.dao;

import org.jl.controllers.StudentTo;
import org.jl.controllers.StudentToCopy;

/**
 *
 * @author Rishitha
 */
public interface StudentDAOI {
   
    public void saveStudentDet(StudentTo st ) throws Exception;
    public void saveStudentDetCopy(StudentToCopy st ) throws Exception;
   
}


5)StudentHibDAO.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 org.jl.dao;



import org.jl.controllers.StudentTo;
import org.jl.controllers.StudentToCopy;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Rishitha
 */
@Repository
public class StudentHibDAO implements StudentDAOI{
    @Autowired
    private HibernateTemplate ht;
   
    public void saveStudentDet(StudentTo st)  {
        ht.save(st);
       
       
    }

    public void saveStudentDetCopy(StudentToCopy st) throws Exception  {
       ht.save(st);
       if(true)throw new Exception("Intentionally Throwing to test roll back "
               + " both tables.Remove this if you want to store"
               + "in both tables succesfully ");
       
    }

 
   
}


6)

StudentService.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 org.jl.services;

import org.jl.controllers.StudentTo;
import org.jl.controllers.StudentToCopy;
import org.jl.dao.StudentDAOI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * @author Rishitha
 */
@Service
public class StudentService {
    @Autowired
    StudentDAOI sdao;
    public void registerStudent(StudentTo st ) throws Exception{
        sdao.saveStudentDet(st);//This tries to save details in to studentdet
        //What I am doing here is just I want
        // to store the student details passed
        // from UI in to two different tables
        //studentdet and studentdetcopy
        //If any problem occurs it has to be rollbacked
        //from both tables
        //I have used hibernatetransactionmanager
        StudentToCopy stss = new StudentToCopy();
        stss.setSname(st.getSname());
        stss.setScity(st.getScity());
        sdao.saveStudentDetCopy(stss);//This tries to save details in to studentdetcopy
       
       
       
    }
    public StudentService(){
       
    }
    public StudentDAOI getSdao() {
        return sdao;
    }

    public void setSdao(StudentDAOI sdao) {
        this.sdao = sdao;
    }
   
   
   
}


7)
dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd" >

     <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource"
        p:driverClassName="oracle.jdbc.driver.OracleDriver"
        p:url="jdbc:oracle:thin:@localhost:1521:XE"
        p:username="hr" p:password="hr" />
  
     <bean name="ht" class="org.springframework.orm.hibernate3.HibernateTemplate" c:_0-ref="sessionFactory">
     </bean>
  
     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
     <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/"
          p:suffix=".jsp" />
     <bean id="ptm" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
            c:_0-ref="sessionFactory">
         
     </bean>
    
    
   <bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource">
    <ref bean="ds"/>
  </property>
  <property name="annotatedClasses">
   <list>
    <value>org.jl.controllers.StudentTo</value>
    <value>org.jl.controllers.StudentToCopy</value>
    </list>
  </property>
  <property name="hibernateProperties">
    <props>
    
      <prop key="hibernate.show_sql">true</prop>
      <prop key="hibernate.max_fetch_depth">2</prop>
      <prop key="hibernate.hbm2ddl.auto">update</prop>
    </props>
  </property>
</bean>    
    <context:component-scan base-package="org.jl"/>

</beans>

8)
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>

9)
failure.jsp

<%--
    Document   : failure
    Created on : Jan 1, 2014, 8:10:53 PM
    Author     : Rishitha
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Student Registration Failed </h1>
    </body>
</html>

10)
studentReg.jsp

<%--
    Document   : studentReg
    Created on : Jan 1, 2014, 1:07:25 PM
    Author     : Rishitha
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form action="studentReg.spring" method="post">
           <table>
               <tr>
                   <td>StudentName:</td>
                   <td><input type="text" name="sname"/></td>
               </tr>
               <tr>
                   <td>City</td>
                   <td><input type="text" name="scity"/></td>
               </tr>
               <tr>
                   <td colspan="2"><input type="submit" value="Register"/></td>
               </tr>
           </table>
        </form>
    </body>
</html>

11)
success.jsp

<%--
    Document   : success
    Created on : Jan 1, 2014, 3:45:48 PM
    Author     : Rishitha
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Student Registration Success</h1>
    </body>
</html>

Note:Add Spring libraries,Hibernate Libraries,ojdbc.jar,commons-dbcp.jar,commons-pool.jar,
commons-logging.jar,


Saturday, February 15, 2014

How to create Scrollable ResultSet and Updatable ResultSet ?


Normally if you create resultset you can iterate or move only in one direction
you can't move back.

With scrollable resultset you can iterate in both directions.You can go to last row
or firstrow or any particualr row using last(),first() and absolute(3) methods...

We will see an example now on how to create scrollable resultset

What is Updatable ResultSet ?

Generally you call executeUpdate on statement object to execute any updates right ?
But with Updatable ResultSet you can update the rows or insertrows or delte rows
using methods from resultset.

We will see an example below




/*
 * 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 jdbcsample;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Rishitha
 */
public class ScrollableResultSetExample {
   
     public static Connection getConnection() {

        try {

            Class.forName("oracle.jdbc.driver.OracleDriver");

        } catch (ClassNotFoundException e) {

            System.out.println("Please add ojdbc6.jar in your classpath if you are using oracle,"
                    + "otherwise set the respective database driver jar file.In netbeans right click on"
                    + "libraries,click on add jar/folder and provide your jar file");

        }
        Connection connection = null;

        try {
            //XE -- Here Give your database name
            //hr -- Give Your database username
            //hr -- Give your database password
            //You have to add ojdbc.jar in your classpath

            connection = DriverManager.getConnection(
                    "jdbc:oracle:thin:@localhost:1521:XE", "hr",
                    "hr");
            System.out.println("Hurrah got connection " + connection);

        } catch (SQLException e) {

            System.out.println("Please check if database name username password are correct ?");

        }
        return connection;

    }
    public static void main(String args[]) throws SQLException{
       
          Connection con = getConnection();
        

//    DatabaseMetaData dbmd = con.getMetaData();
//  
//
//    if (dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE,
//                                          ResultSet.CONCUR_READ_ONLY)) {
//         System.out.println("Updatable ResultSets are supported ");
//    }
//    else {
//         System.out.println("Updatable ResultSets not supported ");
//    }
          Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
          //st = con.createStatement();//un comment this and you will
          //get error because you cant move to first again using non scrollable
          //resultset
          ResultSet scrollRs = null;
         
          scrollRs = st.executeQuery("SELECT fname,lname FROM students ");
          while(scrollRs.next()){
             
              System.out.println(" "+scrollRs.getString(1)+" "+scrollRs.getString(2));
              System.out.println("Current Row is "+scrollRs.getRow());
             
          }
          //iterating the rows in reverse direction using previous method
           while(scrollRs.previous()){
             
              System.out.println(" "+scrollRs.getString(1)+" "+scrollRs.getString(2));
              System.out.println("Current Row is "+scrollRs.getRow());
             
          }
          
           scrollRs.last();//This is to go to last record
          
           System.out.println("Total No of Records in table are "+scrollRs.getRow());
           //scrollRs.getRow gives the no of the record you are on currently


           
           //Now we will see how to update
           //Now to create the statement object that produces scrollable and
           //updatable resultset you have to specify new arguments to statement
           //creation
           //If you observe I have modified second argument to CONCUR_UPDATABLE
           st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
           scrollRs = st.executeQuery("SELECT fname,lname,sid FROM students ");
           //Now we will move to last row and update it
          
           System.out.println("Current values of last row are ");
           scrollRs.last();
           System.out.println(" "+scrollRs.getString(1)+" "+scrollRs.getString(2));
          
           //Now we start modifying
           scrollRs.updateString("fname", "AnilModified");
           scrollRs.updateString("lname","KumarModified");
           scrollRs.updateRow();
          
           System.out.println("Values of last row are ");
         
           System.out.println(" "+scrollRs.getString(1)+" "+scrollRs.getString(2));
          
           //How to delte first Row
           //Move to first row using first method
           //and call deleteRow method
           scrollRs.first();
           scrollRs.deleteRow();
           scrollRs.last();
          
           System.out.println("After deleting Total No of Records in table are "+scrollRs.getRow());
     
            //How to insert a new row
           scrollRs.moveToInsertRow();
           scrollRs.updateString(1, "new Row");
           scrollRs.updateString(2, "new Row");
           scrollRs.updateInt(3,100);
           scrollRs.insertRow();
          
           scrollRs.last();
           System.out.println("Total no of rows are "+scrollRs.getRow());       


    }
   
   
   
}

Imp Note:

If you select * from students... updatable resultsets may not work.
You have to select specific columns like
select fname,lname from students;














Monday, February 10, 2014

Good Sites on Various Java technologies

Hibernate:
-------------
http://www.mkyong.com/struts/struts-hibernate-integration-example/
http://edn.embarcadero.com/article/36524
(Good Example on Struts Hib Sprin Integration)
http://bobcares.com/blog/struts-hibernate-integration/
Good Example on Struts Hib Integration

Saturday, February 8, 2014

How to parse the xml and validate the xml against schema ?

1)javalearnersWithErrors.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->

<javalearners >

    <learner age="30"><fname>        Anilkumar         </fname><lname>Chintha</lname></learner>
    <learner age="1">
       <fname>Rishitha</fname>
       <lname>Chintha</lname>
     </learner>
    <learner age="34">
       <fname>Sunil</fname>
       <lname>Chintha</lname>
    </learner>
   

</javalearners>


2)MyErrorHandler.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 xmlproject;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 *
 * @author Rishitha
 */
public class MyErrorHandler implements ErrorHandler{

    @Override
    public void warning(SAXParseException exception) throws SAXException {
        System.out.println("Warning "+exception.getMessage()); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void error(SAXParseException exception) throws SAXException {
        System.out.println("Error Anil"+exception.getMessage() );//To change body of generated methods, choose Tools | Templates.
        throw exception;
    }

    @Override
    public void fatalError(SAXParseException exception) throws SAXException {
        System.out.println("fatalError "+exception.getMessage());
        throw exception;
        //To change body of generated methods, choose Tools | Templates.
    }
   
}

3)XmlProjectWithValidator.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 xmlproject;

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author Rishitha
 */
public class XmlprojectWithValidator {

    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
        // TODO code application logic here

        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        fac.setIgnoringElementContentWhitespace(false);
        fac.setIgnoringComments(true);

        SchemaFactory schemaFactory
                = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

        fac.setSchema(schemaFactory.newSchema(
                new Source[]{new StreamSource("jlxsd.xsd")}));

        DocumentBuilder bu = fac.newDocumentBuilder();
        bu.setErrorHandler(new MyErrorHandler());

        Document doc = bu.parse(new File("javalearnersWithErrors.xml"));

        Element rootNode = doc.getDocumentElement();

        NodeList list = rootNode.getElementsByTagName("learner");
        for (int i = 0; i < list.getLength(); i++) {

            Element learner = (Element) list.item(i);
            NodeList learnerEleFirstList = learner.getElementsByTagName("fname");
            Node fnameNode = learnerEleFirstList.item(0);
            System.out.println(fnameNode.getFirstChild().getNodeValue());
            NodeList learnerEleLastList = learner.getElementsByTagName("lname");
            Node lnameNode = learnerEleLastList.item(0);
            System.out.println(lnameNode.getFirstChild().getNodeValue());

        }

    }
}

4)jlxsd.xsd

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="javalearners">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="learner" maxOccurs="unbounded" minOccurs="0">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:string" name="fname"/>
              <xs:element type="xs:string" name="lname"/>
            </xs:sequence>
            <xs:attribute type="xs:byte" name="age" use="optional"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

If you want to see errors... remove some element or make a mistake in xml.

Organize the above files as given in below screen shot.
Also add xml and xsd in the root of xmlproject.