Binod Java Solution
http://binodsuman.blogspot.com/
Maximum try to solve your issue and give some useful information on java technology.
  • Struts2 example with Annotation. Struts 2 with annotation. First Struts 2 with annotation.2012/02/23


    Struts2 First Example.

    1. Create one Dynamic Project in Eclipse Say StrutsAnno
    2. Put all these below jar file inside WEB-INF\lib folder
    struts2-core-2.1.6.jar
    xwork-2.1.2.jar
    commons-logging-1.1.jar
    freemarker-2.3.8.jar
    ognl-2.6.11.jar
    struts2-convention-plugin-2.1.6.jar

    3. Change your web.xml (WEB-INF\web.xml) file as below:

    Struts2 First Example

       struts2
       org.apache.struts2.dispatcher.FilterDispatcher

        struts2
        /*

            index.jsp

    There is no use of struts.xml if you use Annotation. :)

    4. Create one package inside src folder say binod.suman
    UserAction.java (StrutsAnno\src\binod\suman\UserAction.java)

    package binod.suman;

    import org.apache.struts2.convention.annotation.Action;
    import org.apache.struts2.convention.annotation.Result;

    public class WelcomeUserAction {
    private String userName;
    private String message;

    @Action(value="/welcome",results={@Result(name="success",location="/successPage.jsp"),@Result(name="error",location="/error.jsp")})
    public String execute() {
    message = "Welcome " + userName + " !";
    System.out.println("Message : "+message);
    if(userName.equals("Binod")){
     return "success";
    }else{return "error";}
    }

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

    public void setMessage(String message) {
    this.message = message;
    }

    public String getUserName() {
    return userName;
    }

    public String getMessage() {
    return message;
    }
    }

    5. These below JSP page inside the WebContent
    index.jsp

       
           
            Hello World
       
       
           
               
               
           
       

    error.jsp

      Some Error
     

    Error!
    This error page is being shown because any of following reasons:

    Field(s) left blank.
    Invalid Data Entered.(For example: String in place of Integer.)

    You have entered but you should suppose to enter Binod

    successPage.jsp

    pageEncoding="ISO-8859-1"%>

    Welcome User

    .

    Only one web.xml, one java class and some jsp pages.

    http://localhost:8080/StrutsAnno/

    Put UserName Binod
    Output:
    Welcome Binod !.

    That's it ............... :)

    Thanks,

    Binod Suman

    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • First Example on Struts2, Struts2 Tutorial, Struts2 Easy Example2012/02/23


    Why Struts2.

    First Example on Struts2:

    1. Create one Dynamic Project in Eclipse Say Struts2
    2. Put all these below jar file inside WEB-INF\lib folder
    struts2-core-2.0.6.jar
    xwork-2.0.1.jar
    commons-logging-1.1.jar
    freemarker-2.3.8.jar
    ognl-2.6.11.jar

    3. Change your web.xml (WEB-INF\web.xml) file as below:
    web.xml

    Struts2 First Example

       struts2
       org.apache.struts2.dispatcher.FilterDispatcher

        struts2
        /*

            index.jsp

    4. In Struts2/src folder, put these two file:
    ClientAction.java

    import com.opensymphony.xwork2.ActionSupport;

    public class ClientAction extends ActionSupport{

    String name;

    public String getName(){
    return name;
    }

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

    public String execute() throws Exception{
    if(getName().equals("")){
          return ERROR;
            }
    else{
    return SUCCESS;
    }
    }

    }

    struts.xml

     
     

    /client.jsp
    /error.jsp
    /error.jsp

       

    5. Write some jsp file inside Struts2\WebContent
    index.jsp

     
         
       
     
     
     

    client.jsp

    Thank you! .

    error.jsp

      Some Error
     

    Error!
    This error page is being shown because any of following reasons:

    Field(s) left blank.
    Invalid Data Entered.(For example: String in place of Integer.)

    That's it .........

    Add any application Server inside the Eclipse and run .....
    If you are getting some error that might be for update code.
    So, In Eclipse bottom tab one Server tab is there -> locate your application server -> then right click on Struts1 (Project) -> click on "Clean Module Work Directory".

    Now go to internet explorer and type URL:

    http://localhost:8080/Struts2

    and type your name in text box, you should suppose to get output like this

    Thank you! Your Name.

    Thanks,

    Binod Suman

    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • Struts2 why more powerful than Struts1. Struts2 Vs Struts1 . Compare between Struts1 and Struts22012/02/23


    STRUTS2 = STRUTS1 + Interceptor (=XWork) + OGNL - FormBean

    1. Easy web.xml

    STRUTS1:

    action
    org.apache.struts.action.ActionServlet

       
    config

       
    /WEB-INF/struts-config.xml

    2

    action
    *.do

     
    STRUTS2:

    webwork

       org.apache.struts.action2.dispatcher.FilterDispatcher

    webwork
    /*

    No struts-config.xml inside WEB-INF folder.

    2. Easy Action Class.

    STRUTS1:
    public class MyAction extends Action {
        public ActionForward execute(ActionMapping mapping,
                                     ActionForm form,
                                     HttpServletRequest request,
                                     HttpServletResponse response)
                throws Exception {
            // do the work
            return (mapping.findForward("success"));
        }
    }

    All actions have to be thread-safe, as only a single action instance is created.
    Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action.
    Because the actions have to be thread-safe, all the objects that may be needed in the processing of the action are passed in the method signature.

    STRUTS2:
    Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues.
    public class MyAction {
       public String execute() throws Exception {
            // do the work
            return "success";
       }
    }

    Here no need to extends other class and no need to pass every thing in execute method.

    If you want to use any session or request ro response object then use xxxxAware, example:
    public class MyAction implements ServletRequestAware {
       private HttpServletRequest request;
       public void setServletRequest(HttpServletRequest request) {
            this.request = request;
       }
       public String execute() throws Exception {
            // do the work using the request
            return Action.SUCCESS;
       }
    }

    3. No Action From

    STRUTS1:
    Struts 1 uses an ActionForm object to capture input. Like Actions, all ActionForms must extend a base class. Since  other JavaBeans cannot be used as ActionForms, developers often create redundant classes to capture input. DynaBeans can used as an alternative to creating conventional ActionForm classes, but, here too, developers may be redescribing existing JavaBeans.

    STRUTS2:
    All data of ActionForm will do here in action class, so need to create one more class.The Action properties can be accessed from the web page via the taglibs.

    4. Advanced Expression Language:

    STRUTS1:
    Struts 1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support.

    STRUTS2:
    Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).

    5. Easy Validation

    STRUTS1:
    Struts 1 supports manual validation via a validate method on the ActionForm, or through an extension to the Commons Validator.

    STRUTS2:
    Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.

    Content Source.
    Another Source.

    Thanks,

    Binod Suman

    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • Java Random number generation of 4 digits2012/02/23


    import java.util.Random;

    System.out.println("***** Generating Random Number of 4 digit *****");
    Random random = new Random();
    for(int i=0;i     long fraction = (long)(1000 * random.nextDouble());
        int PIN= (int)(fraction + 1000);
        System.out.println(PIN);
     }

    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • Spring RowMapper Example, Use of RowMapper, RowMapper Tutorial, jdbcTemplate Example with RowMapper2011/06/01

    Interface RowMapper:

    org.springframework.jdbc.core.RowMapper
    An interface used by JdbcTemplate for mapping rows of a ResultSet on a per-row basis. Implementations of this interface perform the actual work of mapping each row to a result object. One very useful thing is that you can collect all the column of one recrod into java collection.

    public class Student {
      private Map data = new HashMap();
      int roll;
    }

    Means, all the data will be there in map and only one primary column be there outside.

    Example here:

    Student.java

    package binod.suman.rowmapper.domain;
    import java.util.HashMap;
    import java.util.Map;
    public class Student {
     private Map data = new HashMap();

     int roll;

     public void putObject(String key, Object value) {
      data.put(key, value);
     }

     public Object getObject(String key) {
      return data.get(key);
     }

     public Student(int roll) {
      super();
      this.roll = roll;
     }
     public int getRoll() {
      return roll;
     }
     public void setRoll(int roll) {
      this.roll = roll;
     }
     @Override
     public String toString() {
      return "Name : "+data.get("sname")+" \nCity : "+data.get("city")+" \nRoll Number : "+roll;
     }

    }

    StudentResultSetReader.java

    package binod.suman.rowmapper.dao;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import org.springframework.jdbc.core.RowMapper;
    import binod.suman.rowmapper.domain.Student;
    public class StudentResultSetReader implements RowMapper {
     public StudentResultSetReader() {
     }

     public Student read(ResultSet rs) throws SQLException {
      Student t = new Student(rs.getInt("roll"));
      ResultSetMetaData md = rs.getMetaData();
      int numCols  = rs.getMetaData().getColumnCount();
      for (int i = 1; i StudentDAO.java

    package binod.suman.rowmapper.dao;

    import java.util.List;
    import binod.suman.rowmapper.domain.Student;
    public interface StudentDAO {
    // public void insertStudent(Student s);
     public Student selectStudent(int roll);
     public List selectAllStudent();
    }

    beanx.xml

    http://www.springframework.org/schema/beans/spring-beans.xsd"/  >

     
           

           

           

           

       
     
     
      

     

    Main.java

    package binod.suman.rowmapper.dao;
    import java.util.List;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import binod.suman.rowmapper.domain.Student;

    public class Main {
     public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
      StudentDAO studentDAO = (StudentDAO) context.getBean("studentDAO");
    //  Student student = new Student(251,"Binod Suman", "Espoo");
    //  studentDAO.insertStudent(student);
      Student ss = (Student)studentDAO.selectStudent(150);
      System.out.println(ss);
     
      List ssList = studentDAO.selectAllStudent();
      System.out.println("Total Record :: "+ssList.size());
      for(Student s : ssList){
       System.out.println("******************");
       System.out.println(s);
       }
      }
    }

    Jar files required:
    org.springframework.asm-3.0.0.M3.jar
    org.springframework.beans-3.0.0.M3.jar
    org.springframework.context-3.0.0.M3.jar
    org.springframework.context.support-3.0.0.M3.jar
    org.springframework.core-3.0.0.M3.jar
    org.springframework.expression-3.0.0.M3.jar
    org.springframework.jdbc-3.0.0.M3.jar
    org.springframework.transaction-3.0.0.M3.jar
    mysql-connector-java-3.1.12-bin.jar
    antlr-runtime-3.0.jar
    commons-dbcp.jar
    commons-logging-1.0.4.jar
    commons-pool.jar
    hsqldb.jar

    You need to create one database schema with name suman and one student table shoule be there:

    CREATE TABLE student (
      sname varchar(100) default NULL,
      roll int(4) NOT NULL,
      city varchar(100) default NULL,
      PRIMARY KEY  (`roll`)
    )

    and some data should be there:
    insert into student ('Binod',150,'Helsinki');

    Details documentation on RowMapper . 

    Thanks,

    Binod Suman

    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • Spring Integration Messaging tutorial, Spring Integration in 10 Minutes2011/05/10


    There are many things in Spring Integration:

    1. Messaging
    2. Routing
    3. Mediation
    4. Invocation
    5. CEP (Complex Event Processing)
    6. File Transfer
    7. Shared database
    8. Remote Procedure call

    Here I am posting Spring Integration Messaging (Kind of JMS) example here:

    Create one project in Eclipse say SpringIntegrationDemo and add these below jar file to that project:

    1. spring-core-3.0.5.RELEASE.jar
    2. spring-integration-core-2.0.0.BUILD-SNAPSHOT.jar
    3. jar/commons-logging-1.1.jar
    4. spring-context-3.0.5.RELEASE.jar
    5. spring-beans-3.0.5.RELEASE.jar
    6. spring-asm-3.0.5.RELEASE.jar
    7. spring-expression-3.0.5.RELEASE.jar
    8. spring-aop-3.0.5.RELEASE.jar
    9. aopalliance-1.0.jar

    In src folder, create these three files:
    1. MyService.java
    2. myServiceDemo.xml
    3. MyServiceDemo.java

    MyService.java

    public class MyService {

     public String sayHello2(String name) {
      return "Suman Hello :  " + name;
      }

    }

    myServiceDemo.xml

    ⁢beans:beans xmlns="http://www.springframework.org/schema/integration "
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance "
     xmlns:beans="http://www.springframework.org/schema/beans "
     xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/integration
       http://www.springframework.org/schema/integration/spring-integration.xsd"  >

     
     
      
     
     
     
     

    MyServiceDemo.java

    import org.springframework.context.support.AbstractApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.integration.MessageChannel;
    import org.springframework.integration.core.PollableChannel;
    import org.springframework.integration.message.GenericMessage;
    public class MyServiceDemo {

     public static void main(String[] args) {
      AbstractApplicationContext context = new ClassPathXmlApplicationContext("myServiceDemo.xml", MyServiceDemo.class);

      MessageChannel inputChannel =  context.getBean("inputChannel", MessageChannel.class);
      PollableChannel outputChannel =  context.getBean("outputChannel", PollableChannel.class);

    // Just senging messages into message channel.
      for(int i=0;i("World : "+(i+1)));
      }
     
      // Getting message from message channel
      System.out.println("==> Returning from MyService : " + outputChannel.receive(0).getPayload());
      System.out.println("==> Returning from MyService : " + outputChannel.receive(0).getPayload());
      System.out.println("==> Returning from MyService : " + outputChannel.receive(0).getPayload());
      System.out.println("==> Returning from MyService : " + outputChannel.receive(0).getPayload());
      System.out.println("==> Returning from MyService : " + outputChannel.receive(0).getPayload());
     
     }
    }

    Now you can run MyServiceDemo file, will get result. :)

     

    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • How to implement MySql replication Master Master on same Windows machine2011/05/07


    How to implement MySql replication Master Master on same windows machine.
    In Master Master replication, the change effect to reflect vice varsa. If you change in one master it will effect automatically into other master also and vice varsa.

    1. First install mysql-5.5.11-win32.msi on windows machine. While installing choose custom installation and change installation path to D:\MySQL\MySQL Server 5.5
    2. Use all the default parameter like Service name is MYSQL and port number is 3306 and setup bin path.
    3. And also modify root password to mysql.
    3. Now check whether your installation is correct or not.
    4.Open dos prompt and type below command.

    c:\> mysql -uroot -pmysql -hlocalhost -P3306;
    If you get mysql command then everything is ok.
    We will treat mysql 5.5 is ACTIVE MASTER.
    Now create one database:
    mysql> create database suman;

    5. Now install another version of mysql (mysql-5.1.56-win32.msi from http://dev.mysql.com/downloads/mysql/5.1.html )  for Passive MASTER. Again while installing choose custome installation and change installation path to D:\MySQL\MySQL Server 5.1

    6. Change service name to MYSQL2 and port number to 3307
    7. Modify root password to root.
    8.Now check whether your installation is correct or not.
    9.Open new dos prompot and type below command.

    c:\> mysql -uroot -proot -hlocalhost -P3307;
    If you get mysql command then everything is ok.
    We will treat mysql 5.1 is PASSIVE MASTER.

    Up to here two mysql instance are running in your windows machine.
    Now start the replication implementation.

    1. Open D:\MySQL\MySQL Server 5.5\my.ini then add four options to the [mysqld] section of the my.ini file

    [mysqld]
    # The TCP/IP Port the MySQL Server will listen on
    port=3306
    server-id = 1
    log_bin = mysql-bin.log
    binlog_do_db = suman

    save it.
    Restart the MYSQL service from your pc. MyComputer -> Right click -> click on Manage -> Services and Application -> Services ->
    search MYSQL on right side, right click on that MYSQL and click on restart.

    The next step in setting up replication is creating an account that will be used exclusively for replication. We strongly advise creating a dedicated replication user be created for better security so you won't need to grant any additional privileges besides replication permissions. Create an account on the master server that the slave server can use to connect. As mentioned, this account must be given the REPLICATION SLAVE privilege.

    Open one dos windows for all MASTER operation.
    c:\>mysql -uroot -pmysql -hlocalhost -P3306;
    mysql> create user 'user1' identified by 'password';

    mysql> grant replication slave on *.* to 'user1'@'%'  identified by 'password';

    mysql> flush privileges;
    mysql> FLUSH TABLES WITH READ LOCK;
    mysql> show master status;
    +------------------+----------+--------------+------------------+
    | File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
    +------------------+----------+--------------+------------------+
    | mysql-bin.000002 |      107 | suman        |                  |
    +------------------+----------+--------------+------------------+
    1 row in set (0.00 sec)
    Please note down this file name and position, it will use to later.

    Now some change on PASSIVE MASTER side:
    1. Open D:\MySQL\MySQL Server 5.1\my.ini then add four options to the [mysqld] section of the my.ini file

    [mysqld]
    # The TCP/IP Port the MySQL Server will listen on
    port=3307
    server-id = 2
    log_bin = mysql-bin.log
    binlog_do_db = suman

    Restart the MYSQL2 service from your pc. MyComputer -> Right click -> click on Manage -> Services and Application -> Services ->
    search MYSQL on right side, right click on that MYSQL2 and click on restart.
    Open one dos windows for all SLAVE operation.
    c:\>mysql -uroot -proot -hlocalhost -P3307;
    mysql> stop slave;
    mysql> CHANGE MASTER TO
    MASTER_HOST='localhost
    MASTER_USER='user1',
    MASTER_PASSWORD='password',
    MASTER_PORT=3306,
    MASTER_LOG_FILE='mysql-bin.000002',
    MASTER_LOG_POS=107;

    Note: Values for the above command taken from Active Master 'show master status' command output.

    mysql> show slave status\G;
    Output will come huge, among two line should be like:
        Slave_IO_Running: No
        Slave_SQL_Running: No
       
    Because slave is stopped now.
    Now time came to start slave.
    on slave side:
    mysql> start slave;
    Now check slave status:
    mysql> show slave status\G;
    Output will come huge, among two line should be like:
        Slave_IO_Running: Yes
        Slave_SQL_Running: Yes
       
     If both values are Yes, then everything are ok.

     Now create user on Passive Master side and give previleges.

    mysql> GRANT REPLICATION SLAVE ON *.* TO 'user2'@'%' IDENTIFIED BY 'password';

    mysql> show master status;
     +------------------+----------+--------------+------------------+
     | File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
     +------------------+----------+--------------+------------------+
     | mysql-bin.000001 |      106 | suman        |                  |
     +------------------+----------+--------------+------------------+
     1 row in set (0.00 sec)

     Now come again on Active Master side (3306) console and type below command:
      
     mysql> stop slave;

     mysql> CHANGE MASTER TO
     MASTER_HOST='localhost',
     MASTER_USER='user2',
     MASTER_PASSWORD='password',
     MASTER_PORT=3307,
     MASTER_LOG_FILE='mysql-bin.000001',
     MASTER_LOG_POS=106;
    Note: Values for the above command taken from Passive Master 'show master status' command output.

    mysql> start slave;
    mysql> show slave status\G;

     Now you can check your replication work.

     Create some table in MASTER suman database or any database then check at passive MASTER side. Now do some database operation
     at Passive MASTER side and check at Active MASTER side.
    Thanks:

    Binod Suman

    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • How to implement MySql replication Master Master on same Windows machine2011/05/07


    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • How to implement MySql replication on same Windows machine.2011/05/05


    1. First install mysql-5.5.11-win32.msi on windows machine. While installing choose custom installation and change
    installation path to D:\MySQL\MySQL Server 5.5
    2. Use all the default parameter like Service name is MYSQL and port number is 3306 and setup bin path.
    3. And also modify root password to mysql.
    3. Now check whether your installation is correct or not.
    4.Open dos prompt and type below command.
    c:\> mysql -uroot -pmysql -hlocalhost -P3306;

    If you get mysql command then everything is ok.
    We will treat mysql 5.5 is MASTER.
    Now create one database:

    mysql> create database suman;

    5. Now install another version of mysql (mysql-5.1.56-win32.msi)  for SLAVE. Again while installing choose custome
    installation and change installation path to D:\MySQL\MySQL Server 5.1
    6. Change service name to MYSQL2 and port number to 3307
    7. Modify root password to root.
    8.Now check whether your installation is correct or not.
    9.Open new dos prompot and type below command.

    c:\> mysql -uroot -proot -hlocalhost -P3307;

    If you get mysql command then everything is ok.
    We will treat mysql 5.1 is SLAVE.
    Now create one database:
    mysql> create database suman;

    Up to here two mysql instance are running in your windows machine.

    Now start the replication implementation.

    1. Open D:\MySQL\MySQL Server 5.5\my.ini then add four options to the [mysqld] section of the my.ini file

    [mysqld]
    log-bin=dellxp1-bin.log
    server-id=1
    innodb_flush_log_at_trx_commit=1
    sync_binlog=1

    save it.
    Restart the MYSQL service from your pc. MyComputer -> Right click -> click on Manage -> Services and Application -> Services ->
    search MYSQL on right side, right click on that MYSQL and click on restart.

    The next step in setting up replication is creating an account that will be used exclusively for replication. We strongly advise creating a dedicated replication user be created for better security so you won't need to grant any additional privileges besides replication permissions. Create an account on the master server that the slave server can use to connect. As mentioned, this account must be given the REPLICATION SLAVE privilege.

    Open one dos windows for all MASTER operation.
    c:\>mysql -uroot -pmysql -hlocalhost -P3306;
    mysql> create user 'replication_user' identified by 'password';
    mysql> grant replication slave on *.* to 'replication_user'@'%' identified by 'password';
    mysql> flush privileges;
    mysql> FLUSH TABLES WITH READ LOCK;
    mysql> SHOW MASTER STATUS;

    +--------------------+----------+--------------+------------------+
    | File               | Position | Binlog_Do_DB | Binlog_Ignore_DB |
    +--------------------+----------+--------------+------------------+
    | dellxp1-bin.000001 |     338 |              |                  |
    +--------------------+----------+--------------+------------------+
    1 row in set (0.00 sec)

    Please note down this file name and position, it will use to later.

    Now take your backup of your MASTER database as we have new database so this below step are not required. But when you have to create SLAVE of running database then it step must be required, so lets go these below step too.

    Open new dos prompt.

    Taking backup from MASTER:
    C:\>mysqldump -uroot -pmysql -hlocalhost -P3306 suman > d:\test2.sql

    Now export this back to SLAVE, run below command on same dos windows.
    C:\Users\sumankbi>mysql -uroot -proot -hlocalhost -P3307 suman Right click -> click on Manage -> Services and Application -> Services ->
    search MYSQL on right side, right click on that MYSQL2 and click on restart.

    Open one dos windows for all SLAVE operation.
    c:\>mysql -uroot -proot -hlocalhost -P3307;

    mysql> stop slave;
    mysql> CHANGE MASTER TO
    MASTER_HOST='localhost',
    MASTER_USER='replication_user',
    MASTER_PASSWORD='password',
    MASTER_PORT=3306,
    MASTER_LOG_FILE='dellxp1-bin.000001',
    MASTER_LOG_POS=338;

    mysql> show slave status\G;
    Output will come huge, among two line should be like:
        Slave_IO_Running: No
        Slave_SQL_Running: No
       
    Because slave is stopped now.
    Now time came to start slave.
    on slave side:

    mysql> start slave;
    Now check slave status:
    mysql> show slave status\G;
    Output will come huge, among two line should be like:
        Slave_IO_Running: Yes
        Slave_SQL_Running: Yes
       
     If both values are Yes, then everything are ok.

     Now you can check your replication work.

     Create some table in MASTER suman database or any database (those should be there at SLAVE side) then check at slave side.

     Now you stop slave again then you change of MASTER will not come but once again you will start slave then  slave will get automatically updated from last time stopped pointer.

    More details on http://dev.mysql.com/doc/refman/5.0/en/replication.html

    Thanks:

    Binod Suman

    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • How to use and install Yourkit, Java Profiler with YourKit2010/06/05


    Java Profiling:

    In software engineering, program profiling, software profiling or simply profiling, a form of dynamic program analysis, is the investigation of a program's behavior using information gathered as the program executes. The usual purpose of this analysis is to determine which sections of a program to optimize - to increase its overall speed, decrease its memory requirement or sometimes both.

    There are many profiler are available in the market for Java. But I use yourkit java profile and going to step by step setup.

    How you can profile your java application using yourkit Java profiler.

    1. Download yourkit java profiler from here . You can download trial version for 2 weeks and see the website for more information.
    2. During installation it will ask path to insatll the yourkit. Give any path but without space like c:\yourkit
    3. Create one small project in Eclipse say(JavaTest)
    4. Create one simple Java file to check in profiler say (App.java)

    App.java
    package com.binod.suman;

    /**
    * Author @ Binod Suman
    */

    public class App
    {
    public static void main( String[] args )
    {
    System.out.println( "Hello World!" );
    App test = new App();
    test.check();
    }

    public void check(){
    String name="Binod";
    System.out.println(getName(name));
    }

    public String getName(String s){
    System.out.println("YES :: "+s);
    for(int i=0;itry { Thread.sleep(1000); }
    catch (InterruptedException e) { e.printStackTrace(); }
    System.out.println(s);
    } return s;
    }
    }

    5. First start the yourkit. (Start -> All Programs -> Yourkit java profiler -> Yourkit java profiler .
    The profiler can automatically detect all locally running profiled applications. If more than one is found, you will be asked to select one. If only one application is found, the profiler will connect to it without prompting you.

    6. Now run your App.java now see the YourKit Profiler

    It will show one Application runnig (com.binod.suman.App) started without profiler. If you will double click on the application,

    YourKit will show one error message that The application cannot be profiled because it has not been started with the profiler.

    So, now how you will connect your application with YourKit profiler

    1. In Eclispe, right click on the mail java file (App.java) -> Run As -> Run Configurations ... -> Go to Second Tab Argumetns -> Go to VM arguments: and paste
    -agentpath:C:\yourkit\bin\win32\yjpagent.dll
    click on Apply then Run.

    Next time onward no need to do all these thing, just run it.

    Now come to Yourkit profiler this time it will show Started with profiler
    Now you can double click on your application (App) and it will show all the CPU, Thread, Memory, Deadloccks, Garbage Collection, Summary details of the your application.

    Source

    Thanks .......... :)
    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • VXML Getting Started, VXML fundamental, VXML easy example2010/03/29

    VXML (=Voice XML)
    Ref: http://www.ibm.com/developerworks/library/wa-voicexml/

    Java is very famous for develop web application. In web application we will have UI and we can enter any dataor fetch data using that UI. Nowadays Phone or mobiel are very common, so we should have some technology to access our java code using the mobile and that is called VXML technology.

    A simple VXML page (Say First.vxml)

    Hi Binod your first VXML Applciationi is working fine, Congratulations.

    Save this file say (D:\Binod)

    You can check your vxml syntax here at cafe.bevocal.com. First need registration then you can check your code here itself. Really very nice.

    To access this file, we have to upload this file for publically accessible. Some vxml interpreter should be thereto understand all vxml tags. The famous server is telco server. But to run vxml example from home or for learing purposem, we can use https://evolution.voxeo.com/ site.
    Unlike traditional Web applications, you can't just open up a Web browser and surf on over to your VXML file; at least, not if you want a voice response. To test out a phone-based application, you obviously need a phone, and that implies a number to call. There are plenty of high-dollar approaches to mapping numbers to VoiceXML applications, but for testing, staging, and development, Voxeo offers a great free mapping service.
    Navigate over to http://evolution.voxeo.com/,create username and password and log in (using the fields on the upper left side of the page). Under Account menu, select File, Logs, & Report option -> doulbe click on www -> go to first upload file secion and click on Browse and choose d:\Binod\First.vxml click open. Now click on Upload button.
    Again click on Account menu then click on Application Manager ->

    Add Application Give any name to your application say Binod_First_IVRThen click on Voice Phone Calls option, DONT change any option in voice application type. in Voice URLclick on file manager hyperlink you will be getting here your uploade file First.vxml, select this fileand click on map button. DONOT change any thing in Phone number combo box. Simple click on Create Application button.

    You will be getting one mail to your mail box. :)

    click on Contact Methods tab.copy Skype voip number and dial same number from your skype account.(If you dont have skype account then please go to http://www.skype.com/ and download skype and create one account then only you will be able to call this number).

    If you want to edit your vxml file then Account -> Aplication Manager -> click on Binod_First_IVR, click on edit file (option is near to * Voice URL)Once file will get open you can change and just click on save change. Now you can check your new update after calling from skype.

    For debugging: Account -> Application Debugger now call from skype then data will be show here in debugger.

    Some other example on Input.
    Second.vxml

    welcome to ivrs process BY Binod.
    Please select the desired language.
    press 1 for english.
    press 2 for HINDI.

    YOU HAVE ENTERD ENGLISH

    YOU HAVE ENTERD HINDI

    Please choose correct option

    Some more advacne input program.

    If user does not give correct input then it should repromt for 3 times.

    welcome to TecnoTree IVR.
    Please select the desired language.
    press 1 for english.
    press 2 for HINDI.

    YOU HAVE ENTERD ENGLISH

    YOU HAVE ENTERD HINDI

    We didnt get any input from you

    not a valid input

    You have reached maximum tried

    This will only work for * or # incase of no match.

    Another Example:
    Take one input and prompt same number:

    Enter any digit

    you have entered

    calculator.vxml

    -->

    Welcome to IVR Calculator. Enter any digit

    you have entered

    Enter Second any digit

    var zz= Number(x)+Number(y);

    you have entered Second digit
    -->

    -->

    The Answer after addition two number is

    Press 1 for add another number.
    Press 2 for exit.

    YOU HAVE SELECTED ONE

    YOU HAVE SELECTED TWO

    Recording Example

    Good Morning. Welcome to Binod Suman IVR. You can record your message after hear beep.

    after you are finished, Please press hash button

    your recording was THANK YOU FOR USING BINOD IVR APPLICATION.

    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • First EJB3.0 example, EJB3.0 tutorial, @EJB not working2009/10/07
    Here I am putting very easy example for EJB3.0. It has Session Bean, Entity Bean and JPA example. All these examples are in very step wise. I have used glassfish application server. For other application server I was getting error when I used @EJB. So decided to use glassfish application server.

    1. Install glassfish-tools-bundle-for-eclipse-1.1.exe
    2. start -> All Program -> GlassFish tool bundle for eclipse 1.1 -> GlassFish tool bundle for eclipse
    3. File -> New Project -> EJB
    4. Put name of Project say school -> click on add project to EAR say SchoolEAR
    5. File -> New Project -> Dynamic Web Project -> Put name of Project say schoolWEB -> click on add project to EAR say SchoolEAR
    6. Click on SchoolWEB -> Webcontent -> Right click and create one JSP page say search.jsp

    search.jsp

    Student Search Page

    ABC SCHOOL

    Enter Student Roll

    7. Go to Server Pan and start server (Bundled GlassFish V2.1)
    8. Add project SchoolEAR to server
    9. Run http://localhost:8082/SchoolWEB/search.jsp (Just for test whether page is coming) now you should able to see the search page in your browser.

    Now Add one servlet:
    1. Go to School Project -> ejbModule -> create Servlet -> put Package Name: com and classname: SearchServlet -> Finish
    2. SearchServlet.java

    package com;
    import java.io.IOException;
    import javax.ejb.EJB;import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class SearchServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public SearchServlet()
    { super();
    System.out.println("SearchServlet IS CALLING");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("THIS IS SEARCH SERVLET");
    int roll = Integer.parseInt(request.getParameter("roll"));
    System.out.println("Roll Entered :: "+roll);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("THIS IS DO POST METHOD");
    }
    }

    3. Your web.xml of SchoolWEB should be like this: (Path C:\GlassFish_Workspace\EJB3\Practice_1\SchoolWEB\WebContent\WEB-INF\web.xml)
    SchoolWEB

    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp

    SearchServlet
    SearchServlet
    com.SearchServlet

    SearchServlet
    /SearchServlet

    NOTE: One problem with this version of Glassfish that every time when you change code you have to clean your project and restart server. :(

    4. Change little bit your JSP code to call this new servlet.
    Search.jsp

    Student Search Page

    ABC SCHOOL

    Enter Student Roll

    5. Clean your all project and restart the servercall on browser: http://localhost:8082/SchoolWEB/search.jsp
    Put some roll number and see the server log file (say entered 110)you should get the output like INFO: THIS IS SEARCH SERVLETINFO: Roll Entered :: 110

    Now add Session Bean: [IMPORTANT]
    1. Click on School project -> ejbModule -> Right click -> New -> Interface -> package com and class name: ISearchBean

    ISearchBean.java
    package com;
    public interface ISearchBean {
    public String search(int roll);
    }
    2. Click on School project -> ejbModule -> Right click -> New -> SessionBean -> package com and class name: SearchBean
    SessionType: StatelessSearchBean.java

    package com;
    import javax.ejb.Stateless;
    @Statelesspublic class SearchBean implements ISearchBean{
    public SearchBean() { }
    @Override
    public String search(int roll) {
    if(roll == 110){ return "Binod Kumar Suman"; }
    return "Name does not match";
    }
    }

    Note: You used here first EJB annotation @Stateless :)
    3. Change servlet to call this session bean with use of @EBJ annotation

    SearchServlet.java
    package com;
    import java.io.IOException;
    import javax.ejb.EJB;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class SearchServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @EJB
    private ISearchBean searchBean;

    public SearchServlet() {
    super();
    System.out.println("SearchServlet IS CALLING");
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("THIS IS SEARCH SERVLET");
    int roll = Integer.parseInt(request.getParameter("roll"));
    System.out.println("Roll Entered :: "+roll);
    if(searchBean == null){ System.out.println("SearchBean is still null"); }
    else{ System.out.println("Search Bean is working fine");
    System.out.println("Result :: "+searchBean.search(roll)); }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("THIS IS DO POST METHOD"); }
    }

    4. Now run the jsp file from browser:http://localhost:8082/SchoolWEB/search.jsp
    Put roll number 110and check server output:
    INFO: SearchServlet IS CALLINGINFO: THIS IS SEARCH SERVLET
    INFO: Roll Entered :: 110
    INFO: Search Bean is working fine
    INFO: Result :: Binod Kumar Suman

    *********** NOW ADD JPA Persistence part *****************
    Now we will see how to save data using EJB3.0 JPA (Plesae get introduction of EJB3.0 JPA from this URL http://binodsuman.blogspot.com/2009/10/jpa-introduction-what-is-jpa-java.html )
    1. To use JPA in EJB3.0, you have to add persistence.xml in META-INF folder, thatshould have your database connection information.
    2. Create one entity class say student
    student.java in com.entity folder

    package com.entity;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    @Entity
    @Table(name = "studentinfo")
    public class Student {
    private int roll; private String name; private String cell;
    @Id
    @Column(name="roll",unique=true,updatable=true)
    public int getRoll() { return roll; }

    public void setRoll(int roll) { this.roll = roll; }
    @Column(name="sname",updatable=true)
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getCell() { return cell; }
    public void setCell(String cell) { this.cell = cell; }

    }
    persistence.xml in (C:\GlassFish_Workspace\EJB3\Practice_1\School\ejbModule\META-INF\persistence.xml )

    oracle.toplink.essentials.PersistenceProvider

    com.entity.Student



    I have used here postgres sql, you can use any database.Create one table studentinfo
    CREATE TABLE studentinfo(
    roll int4 NOT NULL,
    sname char(100),
    cell char(15), CONSTRAINT "studentinfo_PK" PRIMARY KEY (roll)
    )

    Now change in SearchBean.java

    package com;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
    import com.entity.Student;
    @Stateless
    public class SearchBean implements ISearchBean{
    private static EntityManagerFactory emf;
    private static EntityManager em;
    public SearchBean() { }
    @Override
    public String search(int roll) {
    if(roll == 110){ return "Binod Kumar Suman"; }
    return "Name does not match";
    }

    @Override
    public void saveStudent(Student student) {
    System.out.println("IN SEARCH BEAN TO SAVE STUDENT RECORD");
    try{
    emf = Persistence.createEntityManagerFactory("student_unit");
    em = emf.createEntityManager();
    // Begin transaction
    em.getTransaction().begin();
    em.persist(student);
    em.getTransaction().commit();
    // Close this EntityManager
    em.close();
    System.out.println("***** RECORD SAVED SUCCESSFULLY ***************");
    }
    catch(Exception e){
    System.out.println("SOME PROBLEM DURING SAVE STUDENT :: "+e);
    e.printStackTrace(); }
    }
    }
    And change in SearchServlet.java

    package com;
    import java.io.IOException;
    import javax.ejb.EJB;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.entity.Student;

    public class SearchServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @EJB
    private ISearchBean searchBean;
    public SearchServlet() {
    super();
    System.out.println("SearchServlet IS CALLING");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("THIS IS SEARCH SERVLET");
    int roll = Integer.parseInt(request.getParameter("roll"));
    System.out.println("Roll Entered :: "+roll);
    if(searchBean == null){ System.out.println("SearchBean is still null"); }
    else{ System.out.println("Search Bean is working fine");
    System.out.println("Result :: "+searchBean.search(roll));
    Student student = new Student();
    student.setRoll(150);
    student.setName("Manish");
    student.setCell("12345678");
    searchBean.saveStudent(student);
    System.out.println("******** One record of Student has been saved ********");
    }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("THIS IS DO POST METHOD"); }
    }

    Now you can http://localhost:8082/SchoolWEB/search.jsp and put any roll number. Onc student record would be saveed in database.
    Easy ...................... :)
    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • JPA Introduction, What is JPA, Java Persistence API tutorial2009/10/04
    Java Persistence API (JPA) provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data. One of the great benefits of JPA is that it is an independent API and can nicely integrate with J2EE as well as J2SE applications.

    A fundamental question for many Java developers is "Why JPA? Why do I need to know how to use this API when object-relational mapping tools like Hibernate and Toplink are already available?" The answer is that JPA is not a new technology; rather, it has collected the best ideas from existing persistence technologies like Hibernate, TopLink, and JDO. The result is a standardized specification that helps you build a persistence layer that is independent of any particular persistence provider.

    Although it all started with entity beans and is packaged with Java EE 5.0, JPA can be used outside the container in a Java SE environment.

    What is JPA?
    JPA is just an specification from Sun, which is released under JEE 5 specification. JPA standardized the ORM persistence technology for Java developers. JPA is not a product and can't be used as it is for persistence. It needs an ORM implementation to work and persist the Java Objects. ORM frameworks that can be used with JPA are Hibernate, Toplink, Open JPA etc.

    These days most of the persistence vendors are releasing the JPA implementation of their persistence frameworks. So, developers can choose the best ORM implementation according to the application requirement. For example, production can be started from the free versions of ORM implementation and when the needs arise it can be switched to the commercial version of the ORM framework. You can switch the persistence provides without changing the code. So, ORM framework independence is another another big benefit of JPA.

    Here are the benefits of JPA
    1. Simplified Persistence technology
    2. ORM frameworks independence: Any ORM framework can be used
    3. Data can be saved in ORM way
    4. Supported by industry leaders

    ORM frameworks
    Here are the list of ORM frameworks that can be used with JPA specification.
    Hibernate
    Toplink
    iBatis
    Open JPA

    Why JPA?
    1. JPA is standardized specification and part of EJB3 specification
    2. Many free ORM frameworks are available with can be used to develop applications of any size 3. Application developed in JPA is portable across many servers and persistence products (ORM frameworks).
    4. Can be used with both JEE and JSE applications
    5. JSE 5 features such as annotations can be used
    6. Both annotations and xml based configuration support
    source: http://roseindia.net/jpa/jpa-introduction.shtml

    The persistence.xml file is a standard configuration file in JPA. It has to be included in the META-INF directory that contains the entity beans. The persistence.xml file must define a persistence-unit with a unique name in the current scoped classloader. The provider attribute specifies the underlying implementation of the JPA EntityManager. In JBoss Application Server, the default and only supported / recommended JPA provider is Hibernate.
    You do not have to specify the persistence provider if you’re using the default persistence provider integrated with your Java EE 5 container. For example, if you want Hibernate’s persistence provider in the JBoss Application Server or TopLink Essentials persistence provider with Sun GlassFish or the Oracle Application Server, you don’t have to define the provider element in persistence.xml. But if you decide to go with the EJB 3 persistence provider from the GlassFish project with either JBoss or Apache Geronimo, then you must specify the provider element as follows:

    oracle.toplink.essentials.PersistenceProvider

    Obviously this example specifies Oracle TopLink as the persistence provider; you can specify the provider element for Hibernate as follows:

    org.hibernate.ejb.HibernatePersistence

    This is helpful when using JPA outside the container.

    Template of persistence.xml

    oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider
    entity.Customer entity.Order

    "/>
    "/>
    "/>
    "/>

    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • JPA example outside the container, jpa standalone application example2009/10/03
    One simple JPA example outside the container

    1. Create one java project in Eclipse (Say JAPDEMO)
    2. Put toplink-essentials.jar and postgresql-8.1dev-403.jdbc2ee.jar in project (into classpath)
    3. put Userinfo.java into JAPDEMO\src folder
    4. put Client. java into JAPDEMO\src folder
    5. put persistence.xml into JAPDEMO\src\META-INF folder.
    6. Setup a database and make sure you can access it with the correct given information. I used Postgres SQL and I have put the jar for this database.I also used a simple "userinfo" table for my testing, columns: id, name, fullName, passwordinfo, email.

    Userinfo.java
    import java.io.Serializable;
    import javax.persistence.Entity;
    import javax.persistence.Id;

    @Entity
    public class Userinfo implements Serializable {
    @Id
    private int id;
    private String email;
    private String fullname;
    private String passwordinfo;
    private String name;
    private static final long serialVersionUID = 1L;

    public Userinfo() { super(); }
    public int getId() { return this.id; }
    public void setId(int id) { this.id = id; }
    public String getEmail() { return this.email; }
    public void setEmail(String email) { this.email = email; }
    public String getFullname() { return this.fullname; }
    public void setFullname(String fullname) { this.fullname = fullname; }
    public String getPassword() { return this.passwordinfo; }
    public void setPassword(String password) { this.passwordinfo = password; }
    public String getName() { return this.name; }
    public void setName(String name) { this.name = name; }
    }

    Client.java
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
    import oracle.toplink.essentials.ejb.cmp3.EntityManager;

    public class Client {
    public static void main(String[] args) {
    EntityManagerFactory emf; emf = Persistence.createEntityManagerFactory("sumanunit", new java.util.HashMap());
    EntityManager entityManager = (EntityManager) emf.createEntityManager(); entityManager.getTransaction().begin();
    Userinfo user = new Userinfo();
    user.setId(2);
    user.setEmail("binod@abc.com ");
    user.setFullname("Binod Suman");
    user.setPassword("minmax");
    user.setName("Binod");
    entityManager.persist(user);
    entityManager.getTransaction().commit(); }
    }

    persistence.xml

    oracle.toplink.essentials.PersistenceProvider

    Userinfo



    compile the code and see the database with one new entry. :)

    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • How to convert number to word in java, Number to Word2009/08/13
    Just use String().subString() method and you can develop java code to convert number to word. Like 12345678 to
    one Crore twenty three Lakh forty five thousand six hundred seventy eight.

    import java.text.DecimalFormat;

    public class NumberToWord {
    public static void main(String[] args) {
    System.out.println(convert(12345678));
    }
    private static final String[] tensNames = { "", " ten", " twenty", " thirty", " forty", " fifty", " sixty", " seventy", " eighty", " ninety" };

    private static final String[] numNames = { "", " one", " two", " three", " four", " five", " six", " seven", " eight", " nine", " ten", " eleven", " twelve", " thirteen", " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", " nineteen" };

    private static String convertLessThanOneThousand(int number) {
    String soFar;
    if (number % 100 file://b//s%7B2,%7D//b ", " "); }
    }
    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • How to delete recursively empty folder using java, Recursively Delete Empty Folders2009/07/08
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;

    public class DeleteEmptyFolder {
    public static void main(String[] args) throws IOException {
    deleteEmptyFolders("C:\\temp");
    }

    public static void deleteEmptyFolders(String folderName) throws FileNotFoundException {
    File aStartingDir = new File(folderName);
    List emptyFolders = new ArrayList();
    findEmptyFoldersInDir(aStartingDir, emptyFolders);
    List fileNames = new ArrayList();
    for (File f : emptyFolders) {
    String s = f.getAbsolutePath(); fileNames.add(s);
    }
    for (File f : emptyFolders) {
    boolean isDeleted = f.delete();
    if (isDeleted) {
    System.out.println(f.getPath() + " deleted");
    }
    }
    }

    public static boolean findEmptyFoldersInDir(File folder, List emptyFolders) {
    boolean isEmpty = false;
    File[] filesAndDirs = folder.listFiles();
    List filesDirs = Arrays.asList(filesAndDirs);
    if (filesDirs.size() == 0) { isEmpty = true; }
    if (filesDirs.size() > 0) {
    boolean allDirsEmpty = true;
    boolean noFiles = true;
    for (File file : filesDirs) {
    if (!file.isFile()) {
    boolean isEmptyChild = findEmptyFoldersInDir(file, emptyFolders);
    if (!isEmptyChild) { allDirsEmpty = false; }
    }
    if (file.isFile()) { noFiles = false; }
    }
    if (noFiles == true && allDirsEmpty == true) { isEmpty = true; }
    } if (isEmpty) { emptyFolders.add(folder); }
    return isEmpty;
    }
    }

    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • How to get recursively listing all files in directory using Java2009/07/08
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;

    public class AllFilesInFolder {
    public static void main(String[] args) throws FileNotFoundException {
    String folderName = "C:\\temp";
    List fileNames = getAllFiles(folderName);
    System.out.println("All Files :: " + fileNames);
    }

    public static List getAllFiles(String folderName) throws FileNotFoundException {
    File aStartingDir = new File(folderName);
    List result = getFileListingNoSort(aStartingDir);
    List fileNames = new ArrayList();
    for (File f : result) {
    String s = f.getAbsolutePath();
    fileNames.add(s);
    }

    Collections.sort(result);
    Collections.sort(fileNames);
    return fileNames;
    }

    public static List getFileListingNoSort(File aStartingDir) throws FileNotFoundException {
    List result = new ArrayList();
    File[] filesAndDirs = aStartingDir.listFiles();
    List filesDirs = Arrays.asList(filesAndDirs);
    for (File file : filesDirs) {
    if (!file.isDirectory()) result.add(file);
    if (!file.isFile()) {
    List deeperList = getFileListingNoSort(file);
    result.addAll(deeperList);
    }
    }
    return result;
    }
    }
    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • how to unzip file in java; Java Unzip file,2009/07/06
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipInputStream;

    public class MakeUnZip {
    public static void main(String argv[]) {
    String zipFileName = "src\\myZip.zip";
    unZip(zipFileName);
    }

    public static void unZip(String zipFileName) {
    int BUFFER = 2048;
    try {
    BufferedOutputStream dest = null;
    FileInputStream fileInputStream = new FileInputStream(zipFileName);
    ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(fileInputStream));
    ZipEntry zipEntry;
    int count=0;
    while ((zipEntry = zipInputStream.getNextEntry()) != null) {
    System.out.println("Extracting File Name :: " + zipEntry);
    count++; int length;
    byte data[] = new byte[BUFFER];
    FileOutputStream fileOutputStream = new FileOutputStream(zipEntry.getName());
    dest = new BufferedOutputStream(fileOutputStream, BUFFER);
    while ((length = zipInputStream.read(data, 0, BUFFER)) != -1) {
    dest.write(data, 0, length);
    }

    dest.flush();
    dest.close();
    }

    zipInputStream.close();
    System.out.println("Total "+count+ " Files Unziped Successfully ");
    } catch (Exception e) { e.printStackTrace(); }
    }
    }
    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • Get contents of a ZIP file in Java, how to get file names in zip file in java2009/07/05
    import java.io.File;
    import java.io.IOException;
    import java.util.Enumeration;
    import java.util.zip.ZipFile;

    public class ZipContents {
    public static void main(String[] args) {
    File zipFileName = new File("src\\myZip.zip");
    getContentsInZip(zipFileName);
    }

    public static void getContentsInZip(File zipFileName){
    try{ ZipFile zipFile = new ZipFile(zipFileName);
    Enumeration em = zipFile.entries();
    for (Enumeration enumer = zipFile.entries(); enumer.hasMoreElements();) {
    System.out.println(enumer.nextElement());
    }
    }catch(IOException e){ e.printStackTrace(); }
    }
    }

    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • How to make Zip file using Java, Creating a ZIP file in Java2009/07/05
    To run this tutorial
    1. Create one folder src
    2. Put test1.txt and test2.txt in src folder.
    3. After run this code, you will get myZip.zip file in src folder.

    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;

    public class MakeZip {
    public static void main(String[] args) {
    String[] filesToZip = {"src\\test1.txt","src\\test2.txt"};
    //String[] filesToZip = {"src\\test1.txt"};
    String ZipedFileName = "src\\myZip.zip";
    zipConversion(filesToZip, ZipedFileName);
    }

    public static void zipConversion(String[] files, String ZipedFileName){
    byte[] buffer = new byte[1024];
    try{
    FileOutputStream outputFile = new FileOutputStream(ZipedFileName);
    ZipOutputStream zipFile = new ZipOutputStream(outputFile);
    for(int i=0;i 0) {
    zipFile.write(buffer, 0, length); }

    zipFile.closeEntry();
    inFile.close();
    }

    zipFile.close();
    System.out.println("Files Ziped Successfully");
    }catch(IOException e){ e.printStackTrace(); }
    }
    }

    You can either give one file to zip or any number of files in fileToZip string array.
    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • AJAX Program for Firefox, Ajax does not work with Firefox, Ajax not working in firefox but works with IE, Ajax for Mozilla2009/06/25
    There are many questions are floating on internet that AJAX code doesnot work for Mozilla FireFox. And interesting there is no such exact solution for this. Some days back I have also posted one article on my blog regarding one simple tutorial on Ajax and it was very fine with IE. One day I got one comment that my tutorial is not working for Firefox. I asked this question to one of my friend and she gave the solution. Thanks MP.

    Complete Example:

    [Please follow my prior posting to setup this tutorial ]

    1. ShowStudentInfo.jsp (C:\Ajax_workspace\blog_demo\WebContent\ShowStudentInfo.jsp)
    2. StudentInfo.java (C:\Ajax_workspace\blog_demo\src\StudentInfo.java) This is a servlet.

    ShowStudentInfo.jsp

    Binod Java Solution AJAX

    var request; function getName(){
    var roll = document.getElementById("roll").value;
    var url = "http://localhost:8080/blog_demo/StudentInfo?roll="+roll;

    if(window.ActiveXObject){
    request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest){
    request = new XMLHttpRequest();
    }

    request.onreadystatechange = showResult;
    request.open("POST",url,true);
    request.send(null);
    }
    function showResult(){
    if(request.readyState == 4){
    if ( request.status == 200 ) {
    var response = request.responseXML;
    var students = response.getElementsByTagName("Student");
    var student = students[0];

    document.getElementById("NamelH1").innerHTML = student.getElementsByTagName("Name")[0].childNodes[0].data;
    document.getElementById("HostelH1").innerHTML = student.getElementsByTagName("Hostel")[0].childNodes[0].data;
    document.getElementById("ContactH1").innerHTML = student.getElementsByTagName("Contact")[0].childNodes[0].data;

    }
    }
    }

    GET STUDENT INFO

    Enter Roll Number

    Name :

    Hostel :

    Contact :

    StudentInfo.java

    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class StudentInfo extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    static final long serialVersionUID = 1L;
    public StudentInfo() { super(); }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request,response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String roll = request.getParameter("roll");
    PrintWriter out = response.getWriter();
    response.setContentType("text/xml");
    System.out.println(getResult(roll)); out.println(getResult(roll));
    }
    public String getResult(String roll){
    String name = "";
    String hostel = "";
    String contact = "";
    if(roll.equalsIgnoreCase("110")){
    name = "Binod Kumar Suman"; hostel = "Ganga"; contact = "999999999";
    } else if(roll.equalsIgnoreCase("120")){
    name = "Pramod Kumar Modi"; hostel = "Godawari"; contact = "111111111111";
    } else{ name = "Roll Number not found"; }
    String result = "";
    result += ""; result += "" + name + " ";
    result += "" +hostel + " ";
    result += "" +contact + " ";
    result += " "; result += " ";
    return result;
    }
    }

    This code also work well with IE.
    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • How to read an XML file and extract values for the attributes using ANT script, XML Manipulation using XMLTask, XMLTASK example, Parse XML file in ANT2009/06/22
    Parse XML file in ANT using XMLTASK

    1. Write one ant script (xmlRead.xml)
    2. Write one xml fiel (tests2.xml)
    3. Download jar file (xmltask-v1.15.1.jar) from here and put in lib folder (c:\xmltask\lib)

    1. xmlRead.xml (c:\xmltask\src)



    Test Case Details = @{val}

    2. tests2.xml (c:\xmltask\src)

    ReceiveImageTest
    ValidateImageTest
    PublishImageTest

    ReceiveImageTest2
    ValidateImageTest2
    PublishImageTest2

    After run the build.xml, output would be

    Buildfile: C:\xmltask\src\\xmlRead.xml
    readXML:
    [echo] Test Case Details = ReceiveImageTest
    [echo] Test Case Details = ValidateImageTest
    [echo] Test Case Details = PublishImageTest
    [echo] Test Case Details = ReceiveImageTest2
    [echo] Test Case Details = ValidateImageTest2
    [echo] Test Case Details = PublishImageTest2
    BUILD SUCCESSFULTotal time: 562 milliseconds
    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • How to parse XML file in ANT Script, read xml file in Ant, how to use 2009/06/21
    Some time we need to parse xml file using Ant script to run the java file or read some property value and more like this.
    It is very easy, we can do this with tag called . This tag loads the xml file and it convert all the values of xml file in ant property value internally and we can use those value as ant property. For example :

    bar

    is roughly equivalent to this into ant script file as:

    and you can print this value with ${root.properties.foo}.

    Complete Example:
    1. Create one xml file say Info.xml
    2. Create one ant script say Check.xml

    Info.xml

    Binod Kumar Suman
    110
    Bangalore

    Check.xml

    Student Name :: ${Students.Student.name}
    Roll :: ${Students.Student.roll}
    City :: ${Students.Student.city}

    Now after run this (Check.xml) ant script, you will get output

    Buildfile: C:\XML_ANT_Workspace\XML_ANT\src\Check.xmlinit:
    [echo] Student Name :: Binod Kumar Suman
    [echo] Roll :: 110
    [echo] City :: Bangalore
    BUILD SUCCESSFULTotal time: 125 milliseconds

    It was very simple upto here, but if you have multiple records in xml (StudentsInfo.xml) then it will show all record with comma seperated like this

    Buildfile: C:\XML_ANT_Workspace\XML_ANT\src\Check.xmlinit:

    [echo] Student Name :: Binod Kumar Suman, Pramod Modi, Manish Kumar
    [echo] Roll :: 110,120,130
    [echo] City :: Bangalore,Japan,Patna

    BUILD SUCCESSFULTotal time: 109 milliseconds

    Now if you want to get indiviual data without comma seperation then we have to use tag in ant script and for that we have to add one more jar file ant-contrib-0.6.jar in lib folder.

    Complete Example:
    1. One xml file say StudentsInfo.xml (C:\XML_Workspace\XML_ANT\src\StudentsInfo.xml)
    2. One ant script say Binod.xml (C:\XML_Workspace\XML_ANT\src\Binod.xml)
    3. Put jar ant-contrib-0.6.jar in C:\XML_Workspace\XML_ANT\lib, you can download from here .

    StudentsInfo.xml

    Binod Kumar Suman
    110
    Bangalore

    Pramod Modi
    120
    Japan

    Manish Kumar
    130
    Patna

    Binod.xml



    TEST FOR EACH

    After run the Binod.xml ant script, output will be

    Buildfile: C:\XML_ANT_Workspace\XML_ANT\src\Binod2.xmlinit:for-each:
    [echo] TEST FOR EACH loop:
    [echo] Name :: Binod Kumar Sumanloop:
    [echo] Name :: Pramod Modiloop:
    [echo] Name :: Manish Kumar
    BUILD SUCCESSFULTotal time: 219 milliseconds
    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • How to run java class using ant script, getting started with ANT, ANT easy example with java2009/06/21
    It is very easy to compile and run any java file using ANT Script.

    1. Write one build.xml (Ant Sciprt)
    2. Write one java file First.java
    3. Ant jar file should in classpath
    4. Java compiler should also in classpath

    First.java (C:\AntExample\src\First.java)

    public class First {
    public static void main(String[] args) {
    System.out.println("Fist Data :: "+args[0]);
    System.out.println("Second Data :: "+args[1]);
    }
    }

    build.xml (C:\AntExample\build.xml)

    Build folder crateing ..........

    Compilation going on ..........

    Running java class .........

    Now run the ant scriptc:\AntExample> ant You will get output like this
    Buildfile: C:\AntExample\build.xml
    init:
    [echo] Build folder crateing ..........
    build:
    [echo] Compilation going on ..........
    execute:
    [echo] Running java class .........
    [java] Fist Data :: 10
    [java] Second Data :: 20
    BUILD SUCCESSFULTotal time: 468 milliseconds

    You will get one build\class folder inside the AntExample folder having First.class file
    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com

  • JMS easy example, Get start with JMS, JMS tutorial, JMS easy code2009/06/15


    JMS : Java Messaging Service

    I was searching an easy and running example on JMS, but could not. I saw in many tutorial they explained in very hard manner to how to setup the administrative object to run the JSM example. But in real it is very easy.
    Here I am using IBM Rational Software Architect (RSA) as Java IDE and WebSphere Application Server V6.1 that comes with RSA. [ Image Source ]

    NOTE : If you want to execute this tutorial on RAD [IBM Rational Architect Developer] IDE then plesae click below link.

    http://binodjava.blogspot.com/2009/06/jms-easy-example-in-rad-get-started.html

    Just follows these step and your example will run:

    1. start the server and go to admin console
    2. Service Integration -> Buses -> New -> Give Bus Name: BinodBus ->
    Next -> Finish
    3. click on BinodBus -> In Topology Section, click on Bus Member -> Add -> next -> Chosse File Store -> next -> next -> Finish -> Save
    4. Agin click on BinodBus -> In Destination Resource, click on Destination -> check Queue Type present or not. If not present then click on Next -> Choose Queue -> Next ->
    put Identifier QueueDestination -> Next -> Finish -> Save
    5. Open Resources Tree from left panel

    6. click on JMS -> Connection Factories -> New -> Choose Default messaging provider -> OK -> Name -> BinodConnectionProvider ->
    JNDI Name -> jms/BinodConnectionProvider -> Bus Name -> BinodBus ->
    click on OK -> Save

    7. From left side Resources -> JMS -> Queue -> New -> choose Default messaging provider -> OK ->
    Name -> BinodQueue -> JNDI -> jms/BinodQueue -> Bus Name ->
    BinodBus -> QueueName -> QueueDestination -> OK -> Save

    [All the bold latter is Admin object name]

    8. Restart the server.
    9. Create one Dynamic Web Project (JMSSECOND )and Write two servlet to check the simple example

    10. Write first servlet (ProducerServlet.java )

    import java.io.IOException;
    import javax.jms.Connection;
    import javax.jms.ConnectionFactory;
    import javax.jms.Destination;
    import javax.jms.JMSException;
    import javax.jms.MessageProducer;
    import javax.jms.Session;
    import javax.jms.TextMessage;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class ProducerServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("******** THIS IS MESSAGE PRODUCER SERVLET **********");
    check();
    }

    public void check(){
    System.out.println("********* Producer check **********");
    String destName = "jms/BinodQueue";
    final int NUM_MSGS = 5;
    Context jndiContext = null;

    try { jndiContext = new InitialContext(); }
    catch (NamingException e) { System.out.println("Could not create JNDI API context: " + e.toString()); System.exit(1);
    }

    ConnectionFactory connectionFactory = null;
    Destination dest = null;

    try {
    connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/BinodConnectionProvider");
    dest = (Destination) jndiContext.lookup(destName); }
    catch (Exception e) { System.out.println("JNDI API lookup failed: " + e.toString()); e.printStackTrace(); System.exit(1);
    }

    Connection connection = null;
    MessageProducer producer = null;
    try {
    connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(dest);
    TextMessage message = session.createTextMessage();

    for (int i = 0; i ConsumerServlet.java )

    import java.io.IOException;
    import javax.jms.Connection;
    import javax.jms.ConnectionFactory;
    import javax.jms.Destination;
    import javax.jms.JMSException;
    import javax.jms.Message;
    import javax.jms.MessageConsumer;
    import javax.jms.Session;
    import javax.jms.TextMessage;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class ConsumerServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("********** MESSAGE CONSUMER SERVLET 2 ************");
    check();
    }

    public void check(){
    System.out.println("********* Consumer check **********");
    String destName = "jms/BinodQueue";
    Context jndiContext = null;
    ConnectionFactory connectionFactory = null;
    Connection connection = null;
    Session session = null;
    Destination dest = null;
    MessageConsumer consumer = null;
    TextMessage message = null;
    System.out.println("Destination name is " + destName);

    try {
    jndiContext = new InitialContext();
    }catch (NamingException e) { System.out.println("Could not create JNDI API context: " + e.toString()); System.exit(1);
    }

    try {
    connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/BinodConnectionProvider");
    dest = (Destination) jndiContext.lookup(destName);
    } catch (Exception e) { System.out.println("JNDI API lookup failed: " + e.toString()); System.exit(1);
    }

    try {
    connection = connectionFactory.createConnection();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    consumer = session.createConsumer(dest);
    connection.start();
    while (true) {
    Message m = consumer.receive(1);
    if (m != null) {
    if (m instanceof TextMessage) {
    message = (TextMessage) m;
    System.out.println("Reading message: " + message.getText()); }
    else { break; }
    }
    }
    } catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); }
    finally { if (connection != null) { try { connection.close(); }
    catch (JMSException e) { }
    }
    }
    }
    }

    First run Producer Servlet:
    http://localhost:9080/JMSSECOND/ProducerServlet
    Output:

    Sending message: This is message from JMSSECOND DEMO 1
    Sending message: This is message from JMSSECOND DEMO 2
    Sending message: This is message from JMSSECOND DEMO 3
    Sending message: This is message from JMSSECOND DEMO 4
    Sending message: This is message from JMSSECOND DEMO 5

    Then run Consumer Servlet:
    http://localhost:9080/JMSSECOND/ConsumerServlet
    Output:

    Reading message: This is message from JMSSECOND DEMO 1
    Reading message: This is message from JMSSECOND DEMO 2
    Reading message: This is message from JMSSECOND DEMO 3
    Reading message: This is message from JMSSECOND DEMO 4
    Reading message: This is message from JMSSECOND DEMO 5

    Please put your comments. I am able to write this article after a lot struggle.
    Source of example.

    Please dont forget to put your feedback. Please also give
    suggestion to improve this blog.

    Other useful blogs.

    http://binodjava.blogspot.com
    http://binodsumanflex.blogspot.com
    http://binodservlet.blogspot.com
    http://binodjsf.blogspot.com
    http://binodstock.blogspot.com


radyo dinle aşı takvimi podcast multimedia blog bedava dinle izle kongreler online dinle selected videos nasheed music videos