Sunday, March 22, 2009

How to use IN clause in iBatis

How to use IN clause in iBatis

1. Table Structure (Table Name: users)

CREATE TABLE users(
username varchar(15) NOT NULL,
name varchar(255) NOT NULL,
password varchar(15) NOT NULL,
CONSTRAINT users_pkey PRIMARY KEY (username))

2. Insert data in this table

3. DAO Methos to fetch username with IN clause
public void getAllUserByName() {
List users;
try {
List names = new ArrayList();
names.add("Bond");
names.add("Josef");
names.add("Robert");
names.add("abcd");

users = sqlMap.queryForList("getAllUserByName",names);
for (int i = 0; i < user =" (User)">NOTE: If you use IN clause then iBatis expects that either you will send List or array. For example you can use names as array like String names[] = {"Robert","Bush","abcd"};

4. Code in SQL config file

<resultMap id="UserMap" class="com.domain.User">
<result property="name" column="username" />
<result property="pass" column="password" />
</resultMap>

<select id="getAllUserByName" resultMap="UserMap">
SELECT username, password from users
WHERE username IN
<iterate open="(" close=")" conjunction=",">
#[]#
</iterate>
</select>

NOTE : In select tag, no need to use parameterClass, it will take either List or array as you send during call the sqlMap.queryForList("getAllUserByName",names);

:) :)

Thursday, March 19, 2009

Create XSD file from XML file

There are many tools to generate XSD from XML file, but I am using here trang.

STEP 1: First download trang from here (choose trang-20030619.zip)
STEP 2: Unzip this file at any location say C:\jar\trang-20030619\trang-20030619
STEP 3: Create one xml file at any location say C:\workspaceAll\XSD\XMLTOXSD\src\StudentInfo.xml

StudentInfo.xml

<?xml version="1.0" encoding="UTF-8"?><StudentData xmlns="http://mycompany.com/hr/schemas;
<Student>
<RollNo>110</RollNo>
<FirstName>Ultimate</FirstName>
<LastName>Answer</LastName>
<ContactNo>9900990011</ContactNo>
</Student>
<Hostel>
<Name>Ganga</Name>
<Location>South Corner</Location>
<RoomNo>20</RoomNo>
</Hostel>
</StudentData>

STEP 4: Now use this command

C:\workspaceAll\XSD\XMLTOXSD\src>java -jar C:\jar\trang-20030619\trang-20030619\trang.jar StudentInfo.xml StudentRecord.xsd

STEP 5: Now you will get StudentRecord.xsd at C:\workspaceAll\XSD\XMLTOXSD\src location. And StudentRecord.xsd will like this

<?xml version="1.0" encoding="UTF-8"?><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://mycompany.com/hr/schemas" xmlns:schemas="http://mycompany.com/hr/schemas;
<xs:element name="StudentData">
<xs:complexType>
<xs:sequence>
<xs:element ref="schemas:Student"/>
<xs:element ref="schemas:Hostel"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Student">
<xs:complexType>
<xs:sequence>
<xs:element ref="schemas:RollNo"/>
<xs:element ref="schemas:FirstName"/>
<xs:element ref="schemas:LastName"/>
<xs:element ref="schemas:ContactNo"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="RollNo" type="xs:integer"/>
<xs:element name="FirstName" type="xs:NCName"/>
<xs:element name="LastName" type="xs:NCName"/>
<xs:element name="ContactNo" type="xs:integer"/>
<xs:element name="Hostel">
<xs:complexType>
<xs:sequence>
<xs:element ref="schemas:Name"/>
<xs:element ref="schemas:Location"/>
<xs:element ref="schemas:RoomNo"/>
</xs:sequence>

</xs:complexType>
</xs:element> <xs:element name="Name" type="xs:NCName"/>
<xs:element name="Location" type="xs:string"/>
<xs:element name="RoomNo" type="xs:integer"/>
</xs:schema>

It is very easy :)

IMP: If you want to develop any XSD file, so it would be better idea that first write XML file then using trang utility create XSD file. For example, I have below xml (persons.xml)
<?xml version="1.0" ?>
<information>
<person id="1">
<name>Binod</name>
<age>24</age>
<gender>Male</gender>
</person>

<person id="2">
<name>Pramod</name>
<age>22</age>
<gender>Male</gender>
</person>

<person id="3">
<name>Swetha</name>
<age>19</age>
<gender>Female</gender>
</person>
</information>
Now use the trang command and get your XSD file. I kind suggestion, never dig your head to develop XSD file by using XSD tags. Always use trang command. :)
java -jar c:\jar\trang-20030619\trang-20030619\trang.jar persons.xml personsFormat.xsd
personsFormat.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="information">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" ref="person"/>
</xs:sequence>
</xs:complexType>

</xs:element>
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element ref="name"/>
<xs:element ref="age"/>
<xs:element ref="gender"/>
</xs:sequence>
<xs:attribute name="id" use="required" type="xs:integer"/>
</xs:complexType>
</xs:element>
<xs:element name="name" type="xs:NCName"/>
<xs:element name="age" type="xs:integer"/>
<xs:element name="gender" type="xs:NCName"/>
</xs:schema>



Validate XML file using XSD in Java

XSD stands for XML Schema Definition.
XSD can be used to express a set of rules to which an XML document must conform in order to be considered 'valid' according to that schema. It used to validate the xml file.

Here we have :
1.one xml file (holiday-request.xml),
2. one xsd file (hr.xsd) and
3. one jave file (ValidateXMLUsingXSD.java) to validate xml file using the xsd file.
4. You have to add two jar file in your project (jaxb1-impl.jar and dom4j-1.6.1.jar) that you can google and download.

holiday-request.xml
<?xml version="1.0" encoding="UTF-8"?>
<HolidayRequest xmlns="http://mycompany.com/hr/schemas;
<Holiday>
<StartDate>2006-07-03</StartDate>
<EndDate>2006-07-07</EndDate>
</Holiday>

<Employee>
<Number>42</Number>
<FirstName>Binod</FirstName>
<LastName>Suman</LastName>
</Employee>
</HolidayRequest>

hr.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
targetNamespace="http://mycompany.com/hr/schemas"
xmlns:schemas="http://mycompany.com/hr/schemas;
<xs:element name="HolidayRequest">
<xs:complexType>
<xs:sequence>
<xs:element ref="schemas:Holiday"/>
<xs:element ref="schemas:Employee"/>
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:element name="Holiday">
<xs:complexType>
<xs:sequence>
<xs:element ref="schemas:StartDate"/>
<xs:element ref="schemas:EndDate"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="StartDate" type="xs:NMTOKEN"/>
<xs:element name="EndDate" type="xs:NMTOKEN"/>
<xs:element name="Employee"> <xs:complexType>
<xs:sequence>
<xs:element ref="schemas:Number"/>
<xs:element ref="schemas:FirstName"/>
<xs:element ref="schemas:LastName"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Number" type="xs:integer"/>
<xs:element name="FirstName" type="xs:NCName"/>
<xs:element name="LastName" type="xs:NCName"/>
</xs:schema>

ValidateXMLUsingXSD.java

import java.io.File;
import org.iso_relax.verifier.Schema;
import org.iso_relax.verifier.Verifier;
import org.iso_relax.verifier.VerifierFactory;
import org.iso_relax.verifier.VerifierHandler;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXWriter;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
public class ValidateXMLUsingXSD {
private String schemaURI;
private Document document;
public ValidateXMLUsingXSD(Document document, String schemaURI) {
this.schemaURI = schemaURI;
this.document = document;
}
public boolean validate() throws Exception {
VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl();
Schema schema = factory.compileSchema(schemaURI);
Verifier verifier = schema.newVerifier();
verifier.setErrorHandler(new ErrorHandler() {
public void error(SAXParseException saxParseEx) {
System.out.println("ERROR :: ");
saxParseEx.printStackTrace();
}
public void fatalError(SAXParseException saxParseEx) {
System.out.println("FATAL ERROR :: ");
saxParseEx.printStackTrace();
}
public void warning(SAXParseException saxParseEx) {
System.out.println("WARNING :: ");
saxParseEx.printStackTrace();
}
});
VerifierHandler handler = verifier.getVerifierHandler();
SAXWriter writer = new SAXWriter(handler);
writer.write(document);
return handler.isValid();
}
public static void main(String []args) throws DocumentException{
SAXReader reader=new SAXReader();
Document document=reader.read(new File("src\\holiday-request.xml"));
ValidateXMLUsingXSD val=new ValidateXMLUsingXSD(document,"src\\hr.xsd");
try {
System.out.println("Result :: "+val.validate());
if(val.validate()){
System.out.println("XML IS COMPATIBLE WITH XSD SCHEMA");
}
} catch (Exception e) {
System.out.println("0");
e.printStackTrace();
}
}
}

Now, if you will run, then you will get "XML IS COMPATIBLE WITH XSD SCHEMA" output, if your xml is compatible with xsd otherwise you will get error output.
For test you can change any datatype in xml file and check the result.
So, simple ............. :)

java

How to put restriction in XSD file to validate XML

In XSD file you can put data restriction then XML should satisfy those restriction, otherwise XML would not get validated.
Suppose some number I want only from 100 to 500. Or some name I want only India, US, UK. In this situation We can put the restriction in XSD file.
I am giving one example below, as per the this XSD number can only accept from 100 (Inclusice) to upto 500 (exclusive) and name would accept only Binod, Pramod, Manish.
Using this below XSD you can check xml with give some thing other than restricted value.

hrrecord.xsd

<?xml version="1.0" encoding="UTF-8"?><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://mycompany.com/hr/schemas" xmlns:schemas="http://mycompany.com/hr/schemas;
<xs:element name="HolidayRequest">
<xs:complexType>
<xs:sequence> <xs:element maxOccurs="unbounded" ref="schemas:Student"/>
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:element name="Student">
<xs:complexType>
<xs:sequence>
<xs:element ref="schemas:Holiday"/>
<xs:element ref="schemas:Employee"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Holiday">
<xs:complexType>
<xs:sequence>
<xs:element ref="schemas:StartDate"/>
<xs:element ref="schemas:EndDate"/>
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:element name="StartDate" type="xs:NMTOKEN"/>
<xs:element name="EndDate" type="xs:NMTOKEN"/>
<xs:element name="Employee"> <xs:complexType>
<xs:sequence>
<xs:element ref="schemas:Number"/>
<xs:element ref="schemas:FirstName"/>
<xs:element ref="schemas:LastName"/> </xs:sequence> </xs:complexType> </xs:element>
<xs:element name="Number">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="100"></xs:minInclusive>
<xs:maxExclusive value="500"></xs:maxExclusive>
</xs:restriction>
</xs:simpleType>
</xs:element>

<xs:element name="FirstName">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Binod"></xs:enumeration>
<xs:enumeration value="Pramod"></xs:enumeration>
<xs:enumeration value="Manish"></xs:enumeration>
</xs:restriction>
</xs:simpleType>
</xs:element>

<xs:element name="LastName" type="xs:NCName"/>
</xs:schema>

If you will give name other than specfied in XSD you will get this error
com.sun.msv.verifier.ValidityViolation: the value is not a member of the enumeration: ("Binod"/"Manish"/"Pramod")
at com.sun.msv.verifier.Verifier.onError(Verifier.java:367)

If you will give number more than or equal to 500 then you will get error
com.sun.msv.verifier.ValidityViolation: the value is out of the range (maxExclusive specifies 500).
at com.sun.msv.verifier.Verifier.onError(Verifier.java:367)

Wednesday, February 25, 2009

Struts easy Example, First Struts example, Struts tutorial

1. Create one MyFirstStruts Web Dynamic Project (Say C:\workspaceAll\Struts\FirstStruts)

2. Create JSP pages
a) CustomerForm.jsp (C:\workspaceAll\Struts\MyFirstStruts\WebContent)
b) Success.jsp (C:\workspaceAll\Struts\MyFirstStruts\WebContent\Success.jsp)

3. Configuration Files
a) web.xml (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\web.xml)
b) struts-config.xml (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\struts-config.xml)

4. Java Files
a) CustomerForm.java (C:\workspaceAll\Struts\MyFirstStruts\src\CustomerForm.java)
b) CustomerAction.java (C:\workspaceAll\Struts\MyFirstStruts\src\CustomerAction.java)

5. Put these jar files (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\lib)
a) commons-beanutils.jar
b) commons-collections.jar
c) commons-digester.jar
d) commons-logging.jar
e) struts.jar

6. Put struts-html.tld into C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\struts-html.tld

CustomerForm.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:html xhtml="true">
<body>
<html:form action="/submitCustomerForm">
Put Customer First Name <html:text property="firstName" size="16" maxlength="16"/> <BR/>
Put Customer Last Name <html:text property="lastName" size="16" maxlength="16"/> <BR/> <P/>
<html:submit>Save</html:submit>
</html:form>
</body>
</html:html>

Success.jsp
<html>
<h1> THIS IS SUCCESS PAGE </h1>
</html>

CustomerForm.java
import org.apache.struts.action.ActionForm;
public class CustomerForm extends ActionForm {
private String firstName;
private String lastName;
public CustomerForm() { firstName = ""; lastName = ""; }
public String getFirstName() { return firstName; }
public void setFirstName(String s) { this.firstName = s; }
public String getLastName() { return lastName; }
public void setLastName(String s) { this.lastName = s; }
}

CustomerAction.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class CustomerAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward nextPage = null;
CustomerForm custForm = (CustomerForm) form;
String firstName = custForm.getFirstName();
String lastName = custForm.getLastName();
System.out.println("Customer First name is " + firstName);
System.out.println("Customer Last name is " + lastName);
nextPage = mapping.findForward("success");
return nextPage; }
}

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Hello World Struts Application</display-name>
<servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
<servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <taglib> <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> </web-app>

struts-config.xml
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">;<struts-config> <form-beans> <form-bean name="myForm" type="CustomerForm" /> </form-beans>
<action-mappings> <action path="/submitCustomerForm" type="CustomerAction" name="myForm" scope="request"> <forward name="success" path="/Success.jsp" /> </action> </action-mappings>
</struts-config>

Start the server:
http://localhost:8080/MyFirstStruts/CustomerForm.jsp
Put First Name: Binod
Put Second Name: Suman
Click on Save button and check the server console, you should be get
Customer First name is Binod
Customer Last name is Suman

and new success page will come with message:
THIS IS SUCCESS PAGE

That's it.

Tuesday, February 24, 2009

Spring MVC simple example : Spring Tutorial

This is very basic running example for spring MVC. I developed this project in IMB RAD (
Rational Software Development Platform 6.0) and WebSphere Application Server v6.0.

Step1: Create one Dynamic web project (File -> New -> Dynamic Web Project) and give some name (Say SpringTrans).
Step2: Add spring.jar to project and copy spring.jar to WEB-INF\lib folder
Step3: Edit web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd%22&gt;
<display-name>SpringTrans</display-name>
<servlet>
<servlet-name>SpringTrans</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringTrans</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>

Step 4: Create one xml file SpringTrans-servlet.xml
Note: Name must be SpringTrans-servlet.xml, since we have given the servlet name SpringTrans, so it is SpringTrans-servlet.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd%22&gt;
<beans>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/loginCheck.htm" value-ref="userController"/>
</map>
</property>
</bean>
<bean id="userController" class="com.controller.UserController">
<property name="methodNameResolver">
<bean class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
<property name="mappings">
<props>
<prop key="/loginCheck.htm">loginHandler</prop>
</props>
</property>
</bean>
</property>
</bean>
</beans>

Step 5: In Java Resource, create one package com.controller
Step 6: Create one Java file in this package UserController.java

package com.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class UserController extends MultiActionController {
public ModelAndView loginHandler( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("*********** FROM CONTROLLER *************");
String userInfoName = request.getParameter("userName");
String pass = request.getParameter("password");
System.out.println("User Name :: "+userInfoName);
System.out.println("Password :: "+pass);
return new ModelAndView("/SucessPage.jsp","user",userInfoName);
}
}

Step 7: Create jsp file inside WebContent folder
login.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Login Page</TITLE>
</HEAD>
<BODY>
<P>LOGIN PAGE<BR></P>
<form action="loginCheck.htm">
<TABLE>
<TBODY>
<TR>
<TD width="326" align="right">User Name</TD>
<TD width="311"><input type="text" name="userName"/></TD>
</TR>
<TR>
<TD width="326" align="right">Password</TD>
<TD width="311"><input type="text" name="password"/></TD>
</TR>
<TR>
<TD width="326" align="right"><input type="submit" value="OK"/></TD>
<TD width="311"><input type="button" value="Cancel"/></TD>
</TR>
</TBODY>
</TABLE>
</form>
</BODY>
</HTML>

Step 8: SucessPage.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>SucessPage Page</TITLE>
</HEAD>
<BODY>
<P>Your Login is Sucessfull</P>
<%
String userName = request.getParameter("userName");
try{ out.print(userName); }catch(Exception e){}
%>
</BODY>
</HTML>

Step9:
Run http://localhost:9080/SpringTrans/