Thursday, May 5, 2011

How to implement MySql replication on same Windows machine.


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 < d:\test2.sql

Now some change on SLAVE 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]
server-id=2

save it.
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='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

Saturday, June 5, 2010

How to use and install Yourkit, Java Profiler with YourKit



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;i<10000;i++){
try { 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 .......... :)

Monday, March 29, 2010

VXML Getting Started, VXML fundamental, VXML easy example

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)
<?xml version="1.0" encoding="UTF-8"?>
<vxml version="2.1">
<form>
<block>
<prompt> Hi Binod your first VXML Applciationi is working fine, Congratulations. </prompt>
</block>
</form>
</vxml>

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

<vxml version="2.1">
<property name="inputmodes" value="dtmf"/>
<form id="mainmenu">

<field name="xx" type="digits">
<prompt>
welcome to ivrs process BY Binod.
Please select the desired language.
press 1 for english.
press 2 for HINDI.
</prompt>

<filled>

<if cond="xx==1"> <prompt> YOU HAVE ENTERD ENGLISH </prompt> <elseif cond="xx==2"/> <prompt> YOU HAVE ENTERD HINDI </prompt> <else/> <prompt> Please choose correct option </prompt>
</if>
</filled>
</field>
</form>
</vxml>

Some more advacne input program.

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

<vxml version="2.1">
<property name="inputmodes" value="dtmf"/>
<form id="mainmenu">
<field name="xx" type="digits">
<prompt>
welcome to TecnoTree IVR.
Please select the desired language.
press 1 for english.
press 2 for HINDI.
</prompt>
<filled>

<if cond="xx==1">
<prompt> YOU HAVE ENTERD ENGLISH </prompt>
<elseif cond="xx==2"/> <prompt> YOU HAVE ENTERD HINDI </prompt> </if> </filled> </field>
<noinput>
<prompt> We didnt get any input from you </prompt>
<reprompt/>

</noinput>
<nomatch>
<prompt> not a valid input</prompt> <reprompt/> </nomatch>

<nomatch count="3">
<prompt> You have reached maximum tried</prompt> <exit/> </nomatch>
</form>
</vxml>
This will only work for * or # incase of no match.

Another Example:
Take one input and prompt same number:

<vxml version="2.1">
<property name="inputmodes" value="dtmf"/>
<form id="mainmenu">
<field name="xx" type="digits">

<prompt> Enter any digit </prompt>
<filled>
<prompt> you have entered <value expr="xx"/> </prompt> </filled>
</field>
</form>
</vxml>

calculator.vxml

<vxml version="2.1">
<property name="inputmodes" value="dtmf"/>
<form id="mainmenu">
<var name="x" expr="0"/>
<var name="y" expr="0"/>
<!-- <var name="zz" expr="0"/> -->
<field name="xx" type="number">
<prompt>Welcome to IVR Calculator. Enter any digit </prompt>

<filled>
<assign name="x" expr="xx"/>
<prompt> you have entered <value expr="xx"/> </prompt>
<goto nextitem="yy"/>
</filled>
</field>

<field name="yy" type="number">
<prompt> <break time="2s"/> Enter Second any digit </prompt> <filled> <assign name="y" expr="yy"/>
<script>
var zz= Number(x)+Number(y);
</script>
<prompt> you have entered Second digit <value expr="yy"/>
<!-- Now the total value <value expr="xx+yy"/> -->
</prompt>
<!-- <assign name="zz" expr="Number(x)+Number(y)"/> --> <prompt> <break time="2s"/> The Answer after addition two number is <value expr="zz"/> </prompt>
</filled>
</field>

<field name="again" type="number">
<prompt> <break time="1s"/>
Press 1 for add another number.
Press 2 for exit.
</prompt>
<filled>
<if cond="again==1"> <prompt> YOU HAVE SELECTED ONE </prompt> <goto nextitem="xx"/>
<elseif cond="again==2"/> <prompt> YOU HAVE SELECTED TWO </prompt> <exit/>
</if>
</filled>
</field>
</form>
</vxml>

Recording Example
<?xml version="1.0" encoding="UTF-8"?>
<vxml version = "2.1">
<form id="F1">
<record name="R_1" beep="true" dtmfterm="true">
<prompt> Good Morning. Welcome to Binod Suman IVR. You can record your message after hear beep.
</prompt>

<prompt> after you are finished, Please press hash button </prompt>

<filled> <log expr="R_1$.duration"/> <log expr="R_1$.termchar"/> <log expr="R_1$.size"/>
<prompt> your recording was <value expr="R_1"/> THANK YOU FOR USING BINOD IVR APPLICATION. </prompt> </filled>
</record>
</form>
</vxml>

Wednesday, October 7, 2009

First EJB3.0 example, EJB3.0 tutorial, @EJB not working

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
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Search Page</title>
</head>
<body bgcolor="green"><h1> ABC SCHOOL </h1>
<table align="center">
<tr><td>Enter Student Roll </td><td><input type="text" name="roll"></td>
</tr><tr><td><input type="submit" name="searchStudent" value="Search""></td>
</tr>
</table>
</body>
</html>

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)
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SchoolWEB</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>SearchServlet</display-name>
<servlet-name>SearchServlet</servlet-name>
<servlet-class>com.SearchServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SearchServlet</servlet-name>
<url-pattern>/SearchServlet</url-pattern>

</servlet-mapping>
</web-app>

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
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Search Page</title>
</head>
<body bgcolor="green">
<h1> ABC SCHOOL </h1>
<form action="SearchServlet">
<table align="center"><tr>
<td>Enter Student Roll </td><td><input type="text" name="roll"></td>
</tr><tr><td>
<input type="submit" name="searchStudent" value="Search""></td>
</tr>
</table>
</form>
</body>
</html>

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)
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0">
<persistence-unit name="student_unit" transaction-type="RESOURCE_LOCAL">
<provider>oracle.toplink.essentials.PersistenceProvider</provider>
<class>com.entity.Student</class>
<properties>
<property name="toplink.logging.level" value="FINEST" />
<property name="toplink.jdbc.driver" value="org.postgresql.Driver" />
<property name="toplink.jdbc.url" value="jdbc:postgresql://localhost:5432/postgres" />
<property name="toplink.jdbc.user" value="postgres" />
<property name="toplink.jdbc.password" value="suman" />
</properties>
</persistence-unit>
</persistence>

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 ...................... :)

Sunday, October 4, 2009

JPA Introduction, What is JPA, Java Persistence API tutorial

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:

<provider>oracle.toplink.essentials.PersistenceProvider</provider>

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

<provider>org.hibernate.ejb.HibernatePersistence</provider>

This is helpful when using JPA outside the container.


Template of persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0"> <persistence-unit name="pu1"> <provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider> <class>entity.Customer</class> <class>entity.Order</class> <properties> <property name="toplink.jdbc.driver" value="<database driver>"/> <property name="toplink.jdbc.url" value="<database url>"/> <property name="toplink.jdbc.user" value="<user>"/> <property name="toplink.jdbc.password" value="<password>"/> <property name="toplink.logging.level" value="INFO"/> </properties>
</persistence-unit>
</persistence>

Saturday, October 3, 2009

JPA example outside the container, jpa standalone application example

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
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0"> <persistence-unit name="sumanunit" transaction-type="RESOURCE_LOCAL"> <provider>oracle.toplink.essentials.PersistenceProvider</provider>
<class>Userinfo</class>
<properties> <property name="toplink.logging.level" value="FINEST" />
<property name="toplink.jdbc.driver" value="org.postgresql.Driver" />
<property name="toplink.jdbc.url" value="jdbc:postgresql://localhost:5432/postgres" />
<property name="toplink.jdbc.user" value="postgres" />
<property name="toplink.jdbc.password" value="suman" />
</properties>
</persistence-unit>
</persistence>

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





Thursday, August 13, 2009

How to convert number to word in java, Number to Word

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 < 20){ soFar = numNames[number % 100]; number /= 100; } else { soFar = numNames[number % 10]; number /= 10;
soFar = tensNames[number % 10] + soFar; number /= 10; } if (number == 0) return soFar; return numNames[number] + " hundred" + soFar; }
public static String convert(long number) {
// 0 to 999 999 999 999
if (number == 0) { return "zero"; }
String snumber = Long.toString(number);
// pad with "0"
String mask = "000000000000"; DecimalFormat df = new DecimalFormat(mask); snumber = df.format(number);
int hyndredCrore = Integer.parseInt(snumber.substring(3,5));
int hundredLakh = Integer.parseInt(snumber.substring(5,7));
int hundredThousands = Integer.parseInt(snumber.substring(7,9));
int thousands = Integer.parseInt(snumber.substring(9,12));
String tradBillions;
switch (hyndredCrore) { case 0: tradBillions = ""; break; case 1 : tradBillions = convertLessThanOneThousand(hyndredCrore) + " Crore "; break; default : tradBillions = convertLessThanOneThousand(hyndredCrore) + " Crore "; }

String result = tradBillions;
String tradMillions;
switch (hundredLakh) { case 0: tradMillions = ""; break; case 1 : tradMillions = convertLessThanOneThousand(hundredLakh) + " Lakh "; break; default : tradMillions = convertLessThanOneThousand(hundredLakh) + " Lakh "; }
result = result + tradMillions;
String tradHundredThousands;

switch (hundredThousands) { case 0: tradHundredThousands = ""; break; case 1 : tradHundredThousands = "one thousand "; break; default : tradHundredThousands = convertLessThanOneThousand(hundredThousands) + " thousand "; }
result = result + tradHundredThousands;

String tradThousand;
tradThousand = convertLessThanOneThousand(thousands);
result = result + tradThousand;return result.replaceAll("^\\s+", "").replaceAll("file://b//s%7B2,%7D//b", " "); }
}