package com.jijo.servlet;
import java.io.*;
import java.util.zip.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ZipView extends HttpServlet
{
/**
* Display the contents of a zip file
*/
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
try
{
String zipFile = request.getParameter("fileNames");//specify the zip file
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<table><tr><th>File Name</th><th>Size</th><th>Date </th><th>Compressed Size</th></tr>");
if(zipFile != null && zipFile.trim().length()>0){
//BufferedOutputStream out = null;
ZipInputStream in = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile)));
ZipEntry entry;
while((entry = in.getNextEntry()) != null)
{
out.println("<tr><td>"+ entry.getName()+"</td><td>"+ entry.getSize()+"</td><td>"+ entry.getTime() +" </td><td>"+ entry.getCompressedSize() +" </td></tr>");
/*System.out.println(entry.getName());
int count;
byte data[] = new byte[1000];
out = new BufferedOutputStream(new FileOutputStream("C:/pdf/out.txt"),1000);
while ((count = in.read(data,0,1000)) != -1)
{
out.write(data,0,count);
}
out.flush();
out.close();
*/
}
}
out.println("</table>");
out.flush();
out.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
//Put the servlet entry in web.xml file
Thursday, March 4, 2010
Download selected files as Zip
package com.jijo.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author jijo
* This servlet class is used to download the list files as a zip
*/
public class ZipDownload extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
byte[] files = null;
try {
String random = this.generateRamdomCode(10, 15);
//Specify the files names seperated by '@!'
String reqFile = request.getParameter("fileNames");
if(reqFile != null && reqFile.trim().length()>0){
String filenames[] = reqFile.split("@!");
ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(random + ".zip"));
for (String filename : filenames) {
try{
filename = filename.trim();
if(filename.length()>0){
FileInputStream fin = new FileInputStream(filename);
File file = new File(filename);
zipFile.putNextEntry(new ZipEntry(filename.substring(filename
.lastIndexOf("/") + 1, filename.length())));
files = new byte[(int) file.length()];
fin.read(files);
zipFile.write(files);
fin.close();
zipFile.closeEntry();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
zipFile.close();
FileInputStream zip = new FileInputStream(random + ".zip");
File f = new File(random + ".zip");
files = new byte[(int) f.length()];
zip.read(files);
zip.close();
f.delete();
//response
response.setContentType("application/zip");
response.setContentLength(files.length);
response.setHeader("Content-Disposition",
"attachment; filename=\"jijo.zip\"");
try {
response.getOutputStream().write(files);
} catch (Exception e) {
e.printStackTrace();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
}
}
private String generateRamdomCode(double min, double max){
String code = "";
int totalChars = (int)((Math.random() * min)+max);
char startChar = 'A';
for(int i=0;i<totalChars;i++){
int selNum = (int)(Math.random() * 13.0);
if(selNum <= 4){
startChar = 'A';
code += (char)((Math.random()*26.0)+startChar);
}else if(selNum >=5 && selNum<= 9){
code += (int)(Math.random() * 10.0);
}else if(selNum >=10){
startChar = 'a';
code += (char)((Math.random()*26.0)+startChar);
}
}
System.out.println(code);
return code;
}
}
Put the servlet entry and url mapping in web.xml file.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author jijo
* This servlet class is used to download the list files as a zip
*/
public class ZipDownload extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
byte[] files = null;
try {
String random = this.generateRamdomCode(10, 15);
//Specify the files names seperated by '@!'
String reqFile = request.getParameter("fileNames");
if(reqFile != null && reqFile.trim().length()>0){
String filenames[] = reqFile.split("@!");
ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(random + ".zip"));
for (String filename : filenames) {
try{
filename = filename.trim();
if(filename.length()>0){
FileInputStream fin = new FileInputStream(filename);
File file = new File(filename);
zipFile.putNextEntry(new ZipEntry(filename.substring(filename
.lastIndexOf("/") + 1, filename.length())));
files = new byte[(int) file.length()];
fin.read(files);
zipFile.write(files);
fin.close();
zipFile.closeEntry();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
zipFile.close();
FileInputStream zip = new FileInputStream(random + ".zip");
File f = new File(random + ".zip");
files = new byte[(int) f.length()];
zip.read(files);
zip.close();
f.delete();
//response
response.setContentType("application/zip");
response.setContentLength(files.length);
response.setHeader("Content-Disposition",
"attachment; filename=\"jijo.zip\"");
try {
response.getOutputStream().write(files);
} catch (Exception e) {
e.printStackTrace();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
}
}
private String generateRamdomCode(double min, double max){
String code = "";
int totalChars = (int)((Math.random() * min)+max);
char startChar = 'A';
for(int i=0;i<totalChars;i++){
int selNum = (int)(Math.random() * 13.0);
if(selNum <= 4){
startChar = 'A';
code += (char)((Math.random()*26.0)+startChar);
}else if(selNum >=5 && selNum<= 9){
code += (int)(Math.random() * 10.0);
}else if(selNum >=10){
startChar = 'a';
code += (char)((Math.random()*26.0)+startChar);
}
}
System.out.println(code);
return code;
}
}
Put the servlet entry and url mapping in web.xml file.
Display or download Files using servlet
/**
*
*/
package com.jijo.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author jijo
* This servlet class is used to display or download the file
*
*/
public class DownloadFile extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
ServletOutputStream outputStream = null;
InputStream input = null;
try {
outputStream = response.getOutputStream();
String filePath = request.getParameter("fileNames"); //filepath
if(filePath != null && filePath.trim().length()>0){
String download = request.getParameter("download");//download or display
File prefile = new File(filePath);
byte buff[] = new byte[8192];
input = new FileInputStream(prefile);
String contenttype = filePath.substring(filePath.lastIndexOf(".")+1, filePath.length());
contenttype = contenttype.toLowerCase();
if(download != null && download.trim().length()>0){
response.setContentType("application/octet-stream");
}
else{
if (contenttype != null) {
String responseType = getResponseContentType(contenttype);
response.setContentType(responseType);
} else {
response.setContentType("application/octet-stream");
}
}
response.setHeader("Content-Length", String.valueOf(prefile.length()));
if(download != null && download.trim().length()>0){
response.setHeader("Content-Disposition","attachment; filename=\""+ prefile.getName()+"\"");
}
else{
response.setHeader("Content-disposition", (new StringBuilder("inline; filename=")).append(prefile.getName()).toString());
}
response.addHeader("Cache-Control", "no-transform, max-age=0");
int i = 0;
while ((i = input.read(buff)) > 0) {
outputStream.write(buff, 0, i);
outputStream.flush();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (input != null)
input.close();
if (outputStream != null)
outputStream.close();
}
}
private String getResponseContentType(String contenttype){
String responseType = "";
if(contenttype.indexOf("doc")>-1){
responseType = "application/vnd.ms-word";
}
if(contenttype.indexOf("rtf")>-1){
responseType = "application/rtf";
}
else if(contenttype.indexOf("xls")>-1){
responseType = "application/vnd.ms-excel";
}
else if(contenttype.indexOf("ppt")>-1){
responseType = "application/ppt";
}
else if(contenttype.indexOf("xml")>-1){
responseType = "text/xml";
}
else if(contenttype.indexOf("html")>-1){
responseType = "text/html";
}
else if(contenttype.indexOf("htm")>-1){
responseType = "text/htm";
}
else if(contenttype.indexOf("txt")>-1 || contenttype.indexOf("log")>-1){
responseType = "text/plain";
}
else if(contenttype.indexOf("pdf")>-1){
responseType = "application/pdf";
}
else if(contenttype.indexOf("gif")>-1){
responseType = "image/gif";
}
else if(contenttype.indexOf("png")>-1){
responseType = "image/png";
}
else if(contenttype.indexOf("jpg")>-1){
responseType = "image/jpg";
}
else if(contenttype.indexOf("jpeg")>-1){
responseType = "image/JPEG";
}
else if(contenttype.indexOf("jpe")>-1){
responseType = "image/JPEG";
}
else if(contenttype.indexOf("bmp")>-1){
responseType = "image/bmp";
}
else if(contenttype.indexOf("jpeg")>-1){
responseType = "image/JPEG";
}
else if(contenttype.indexOf("tiff")>-1){
responseType = "image/tiff";
}
else if(contenttype.indexOf("tif")>-1){
responseType = "image/tiff";
}
else if(contenttype.indexOf("html")>-1){
responseType = "text/html";
}
else{
responseType = "application/octet-stream";
}
return responseType;
}
}
in web.xml
<servlet>
<servlet-name>ViewFile</servlet-name>
<servlet-class>com.jijo.servlet.DownloadFile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ViewFile</servlet-name>
<url-pattern>*.viewfile</url-pattern>
</servlet-mapping>
<mime-mapping>
<extension>pptx</extension>
<mime-type>
application/vnd.openxmlformats-officedocument.presentationml.presentation
</mime-type>
</mime-mapping>
<mime-mapping>
<extension>docx</extension>
<mime-type>application/vnd.openxmlformats-officedocument.wordprocessingml.document</mime-type>
</mime-mapping>
<mime-mapping>
<extension>xlsx</extension>
<mime-type>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mime-type>
</mime-mapping>
in jsp
<form name='form1' method="post" action="file.viewfile" target="fileframe"/>
<input type='hidden' name='fileNames' id='fileNames' value='C:/jijo/resume.txt'/>
<input type='hidden' name='download' id='download' value='true'/>//set as blank when u want to display
<input type='Submit' name='Submit' id='Submit' value='Display'/>
</form>
<frame name="fileframe" id="fileframe"></frame>
*
*/
package com.jijo.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author jijo
* This servlet class is used to display or download the file
*
*/
public class DownloadFile extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
ServletOutputStream outputStream = null;
InputStream input = null;
try {
outputStream = response.getOutputStream();
String filePath = request.getParameter("fileNames"); //filepath
if(filePath != null && filePath.trim().length()>0){
String download = request.getParameter("download");//download or display
File prefile = new File(filePath);
byte buff[] = new byte[8192];
input = new FileInputStream(prefile);
String contenttype = filePath.substring(filePath.lastIndexOf(".")+1, filePath.length());
contenttype = contenttype.toLowerCase();
if(download != null && download.trim().length()>0){
response.setContentType("application/octet-stream");
}
else{
if (contenttype != null) {
String responseType = getResponseContentType(contenttype);
response.setContentType(responseType);
} else {
response.setContentType("application/octet-stream");
}
}
response.setHeader("Content-Length", String.valueOf(prefile.length()));
if(download != null && download.trim().length()>0){
response.setHeader("Content-Disposition","attachment; filename=\""+ prefile.getName()+"\"");
}
else{
response.setHeader("Content-disposition", (new StringBuilder("inline; filename=")).append(prefile.getName()).toString());
}
response.addHeader("Cache-Control", "no-transform, max-age=0");
int i = 0;
while ((i = input.read(buff)) > 0) {
outputStream.write(buff, 0, i);
outputStream.flush();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (input != null)
input.close();
if (outputStream != null)
outputStream.close();
}
}
private String getResponseContentType(String contenttype){
String responseType = "";
if(contenttype.indexOf("doc")>-1){
responseType = "application/vnd.ms-word";
}
if(contenttype.indexOf("rtf")>-1){
responseType = "application/rtf";
}
else if(contenttype.indexOf("xls")>-1){
responseType = "application/vnd.ms-excel";
}
else if(contenttype.indexOf("ppt")>-1){
responseType = "application/ppt";
}
else if(contenttype.indexOf("xml")>-1){
responseType = "text/xml";
}
else if(contenttype.indexOf("html")>-1){
responseType = "text/html";
}
else if(contenttype.indexOf("htm")>-1){
responseType = "text/htm";
}
else if(contenttype.indexOf("txt")>-1 || contenttype.indexOf("log")>-1){
responseType = "text/plain";
}
else if(contenttype.indexOf("pdf")>-1){
responseType = "application/pdf";
}
else if(contenttype.indexOf("gif")>-1){
responseType = "image/gif";
}
else if(contenttype.indexOf("png")>-1){
responseType = "image/png";
}
else if(contenttype.indexOf("jpg")>-1){
responseType = "image/jpg";
}
else if(contenttype.indexOf("jpeg")>-1){
responseType = "image/JPEG";
}
else if(contenttype.indexOf("jpe")>-1){
responseType = "image/JPEG";
}
else if(contenttype.indexOf("bmp")>-1){
responseType = "image/bmp";
}
else if(contenttype.indexOf("jpeg")>-1){
responseType = "image/JPEG";
}
else if(contenttype.indexOf("tiff")>-1){
responseType = "image/tiff";
}
else if(contenttype.indexOf("tif")>-1){
responseType = "image/tiff";
}
else if(contenttype.indexOf("html")>-1){
responseType = "text/html";
}
else{
responseType = "application/octet-stream";
}
return responseType;
}
}
in web.xml
<servlet>
<servlet-name>ViewFile</servlet-name>
<servlet-class>com.jijo.servlet.DownloadFile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ViewFile</servlet-name>
<url-pattern>*.viewfile</url-pattern>
</servlet-mapping>
<mime-mapping>
<extension>pptx</extension>
<mime-type>
application/vnd.openxmlformats-officedocument.presentationml.presentation
</mime-type>
</mime-mapping>
<mime-mapping>
<extension>docx</extension>
<mime-type>application/vnd.openxmlformats-officedocument.wordprocessingml.document</mime-type>
</mime-mapping>
<mime-mapping>
<extension>xlsx</extension>
<mime-type>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mime-type>
</mime-mapping>
in jsp
<form name='form1' method="post" action="file.viewfile" target="fileframe"/>
<input type='hidden' name='fileNames' id='fileNames' value='C:/jijo/resume.txt'/>
<input type='hidden' name='download' id='download' value='true'/>//set as blank when u want to display
<input type='Submit' name='Submit' id='Submit' value='Display'/>
</form>
<frame name="fileframe" id="fileframe"></frame>
Tuesday, February 2, 2010
Track Session out in DWR
Create a filter class,
package com.jijo;
import java.lang.reflect.Method;
import org.directwebremoting.AjaxFilter;
import org.directwebremoting.AjaxFilterChain;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.extend.LoginRequiredException;
public class DwrFilter implements AjaxFilter {
public Object doFilter(Object obj, Method method, Object[] params, AjaxFilterChain chain) throws Exception {
//Check if session has timedout/invalidated
String username = WebContextFactory.get().getSession().getAttribute("username");
if (username != null) {
}
else{
throw new LoginRequiredException( "sessionout" );
//sessionout is a message,access this message in the jsp or html
}
return chain.doFilter( obj, method, params );
}
}
configure this filter class in your bean tage inside the
dwr.xml
filter tag
eg:
<filter class="com.jijo.DwrFilter" >
Also in your dwr.xml file configure,
covert tag starts
<convert match="org.directwebremoting.extend.LoginRequiredException" converter="bean" />
Then in your jsp page inside the javascript tag,
first include the
/dwr/engine.js and also the
//start javascript tag
dwr.engine.setErrorHandler(errorHandler);
function errorHandler(message, exception){
//forwrd to login page
if(message == 'sessionout'){ //'sessionout'- is message from the filter class you configured
window.location = "login.jsp"
}
}
//end of javascript tag
package com.jijo;
import java.lang.reflect.Method;
import org.directwebremoting.AjaxFilter;
import org.directwebremoting.AjaxFilterChain;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.extend.LoginRequiredException;
public class DwrFilter implements AjaxFilter {
public Object doFilter(Object obj, Method method, Object[] params, AjaxFilterChain chain) throws Exception {
//Check if session has timedout/invalidated
String username = WebContextFactory.get().getSession().getAttribute("username");
if (username != null) {
}
else{
throw new LoginRequiredException( "sessionout" );
//sessionout is a message,access this message in the jsp or html
}
return chain.doFilter( obj, method, params );
}
}
configure this filter class in your bean tage inside the
dwr.xml
filter tag
eg:
<filter class="com.jijo.DwrFilter" >
Also in your dwr.xml file configure,
covert tag starts
<convert match="org.directwebremoting.extend.LoginRequiredException" converter="bean" />
Then in your jsp page inside the javascript tag,
first include the
/dwr/engine.js and also the
//start javascript tag
dwr.engine.setErrorHandler(errorHandler);
function errorHandler(message, exception){
//forwrd to login page
if(message == 'sessionout'){ //'sessionout'- is message from the filter class you configured
window.location = "login.jsp"
}
}
//end of javascript tag
Thursday, January 28, 2010
XML parsing using Castor
Put the castor-1.2.jar in you lib folder.
This is object to xml mapping.
Example is given,
In this Students object is mapped to an xml.Each tag is mapped to different nodes in the XML.
Students.java
/**
*
*/
package com.jijo;
import java.util.ArrayList;
import java.util.List;
/**
* @author jijo
*
*/
public class Students {
private List<Student> students = new ArrayList<Student>();
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
Student.java
package com.jijo;
public class Student {
private String rollNo;
private String name;
private String className;
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
studentmapping.xml
<?xml version="1.0"?>
<mapping>
<class name="com.jijo.Students">
<field name="students" type="com.jijo.Student" collection="collection">
<bind-xml name="student" /> <!-- bind xml tag name -->
</field>
</class>
<class name="com.jijo.Student">
<!--
<field name="regNo" type="string">
<bind-xml name="regNo" node="attribute" /> attribute parsing
</field>
-->
<field name="rollNo" type="string">
<bind-xml name="rollno"/>
</field>
<field name="name" type="string">
<bind-xml name="name"/>
</field>
<field name="className" type="string">
<bind-xml name="classname" />
</field>
</class>
</mapping>
XmlUtil.java
/**
*
*/
package com.jijo;
import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.Unmarshaller;
import org.xml.sax.InputSource;
/**
* @author jijo
*
*/
public class XmlUtil {
/**
* This method will convert the data got from the data source to the appropriate
* form for the next process.
*
* @param className
* @param xmlFileName
* @param mappingFileName
* @throws Exception
* @throws MappingException
*/
public Object xmltoObject(String className, String xmlFileName, String mappingFileName) {
Object obj = null;
FileReader reader = null;
try {
// Load the mapping information from the file
URL mappingURL = getClass().getClassLoader().getResource(mappingFileName);
Mapping mapping=new Mapping();
mapping.loadMapping(mappingURL);
// Create a Reader to the file to unmarshal from
reader = new FileReader(xmlFileName);
// Unmarshal the data
Unmarshaller unmarshaller = new Unmarshaller(Class
.forName(className));
unmarshaller.setMapping(mapping);
obj = (Object) unmarshaller.unmarshal(reader);
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return obj;
}
/**
* This method is used to cast the xml-string to object
* @param className
* @param xmlString
* @param mappingFileName
* @return
*/
public Object xmlStringtoObject(String className,String xmlString,String mappingFileName) {
ByteArrayInputStream Bis1=null;
try {
Bis1 = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e1) {
}
InputSource in = new InputSource();
Object obj = null;
try {
// Load the mapping information from the file
URL mappingURL = getClass().getClassLoader().getResource(mappingFileName);
Mapping mapping=new Mapping();
mapping.loadMapping(mappingURL);
// Create a Reader to the file to unmarshal from
in.setByteStream(Bis1);
// Unmarshal the data
Unmarshaller unmarshaller = new Unmarshaller(Class
.forName(className));
unmarshaller.setMapping(mapping);
obj = (Object) unmarshaller.unmarshal(in);
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
Bis1.close();
Bis1=null;
in=null;
} catch (Exception e) {
e.printStackTrace();
}
}
return obj;
}
}
Main.java
package com.jijo;
import java.util.List;
public class Main {
public static void main(String[] args) {
try{
XmlUtil xmlUtil = new XmlUtil();
Students obj = (Students) xmlUtil.xmltoObject("com.jijo.Students", "C:/jijo/xml/students.xml", "com/jijo/studentmapping.xml");
if(obj != null){
List<Student> students = obj.getStudents();
if(students != null){
System.out.println("not null");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
students.xml
<students>
<student>
<rollno>1</rollno>
<name>Jijo</name>
<classname>10</classname>
</student>
<student>
<rollno>2</rollno>
<name>Mathew</name>
<classname>10</classname>
</student>
<student>
<rollno>3</rollno>
<name>Ajeesh</name>
<classname>10</classname>
</student>
<student>
<rollno>4</rollno>
<name>Prathyush</name>
<classname>10</classname>
</student>
</students>
For more details visit http://www.castor.org.
This is object to xml mapping.
Example is given,
In this Students object is mapped to an xml.Each tag is mapped to different nodes in the XML.
Students.java
/**
*
*/
package com.jijo;
import java.util.ArrayList;
import java.util.List;
/**
* @author jijo
*
*/
public class Students {
private List<Student> students = new ArrayList<Student>();
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
Student.java
package com.jijo;
public class Student {
private String rollNo;
private String name;
private String className;
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
studentmapping.xml
<?xml version="1.0"?>
<mapping>
<class name="com.jijo.Students">
<field name="students" type="com.jijo.Student" collection="collection">
<bind-xml name="student" /> <!-- bind xml tag name -->
</field>
</class>
<class name="com.jijo.Student">
<!--
<field name="regNo" type="string">
<bind-xml name="regNo" node="attribute" /> attribute parsing
</field>
-->
<field name="rollNo" type="string">
<bind-xml name="rollno"/>
</field>
<field name="name" type="string">
<bind-xml name="name"/>
</field>
<field name="className" type="string">
<bind-xml name="classname" />
</field>
</class>
</mapping>
XmlUtil.java
/**
*
*/
package com.jijo;
import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.Unmarshaller;
import org.xml.sax.InputSource;
/**
* @author jijo
*
*/
public class XmlUtil {
/**
* This method will convert the data got from the data source to the appropriate
* form for the next process.
*
* @param className
* @param xmlFileName
* @param mappingFileName
* @throws Exception
* @throws MappingException
*/
public Object xmltoObject(String className, String xmlFileName, String mappingFileName) {
Object obj = null;
FileReader reader = null;
try {
// Load the mapping information from the file
URL mappingURL = getClass().getClassLoader().getResource(mappingFileName);
Mapping mapping=new Mapping();
mapping.loadMapping(mappingURL);
// Create a Reader to the file to unmarshal from
reader = new FileReader(xmlFileName);
// Unmarshal the data
Unmarshaller unmarshaller = new Unmarshaller(Class
.forName(className));
unmarshaller.setMapping(mapping);
obj = (Object) unmarshaller.unmarshal(reader);
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return obj;
}
/**
* This method is used to cast the xml-string to object
* @param className
* @param xmlString
* @param mappingFileName
* @return
*/
public Object xmlStringtoObject(String className,String xmlString,String mappingFileName) {
ByteArrayInputStream Bis1=null;
try {
Bis1 = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e1) {
}
InputSource in = new InputSource();
Object obj = null;
try {
// Load the mapping information from the file
URL mappingURL = getClass().getClassLoader().getResource(mappingFileName);
Mapping mapping=new Mapping();
mapping.loadMapping(mappingURL);
// Create a Reader to the file to unmarshal from
in.setByteStream(Bis1);
// Unmarshal the data
Unmarshaller unmarshaller = new Unmarshaller(Class
.forName(className));
unmarshaller.setMapping(mapping);
obj = (Object) unmarshaller.unmarshal(in);
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
Bis1.close();
Bis1=null;
in=null;
} catch (Exception e) {
e.printStackTrace();
}
}
return obj;
}
}
Main.java
package com.jijo;
import java.util.List;
public class Main {
public static void main(String[] args) {
try{
XmlUtil xmlUtil = new XmlUtil();
Students obj = (Students) xmlUtil.xmltoObject("com.jijo.Students", "C:/jijo/xml/students.xml", "com/jijo/studentmapping.xml");
if(obj != null){
List<Student> students = obj.getStudents();
if(students != null){
System.out.println("not null");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
students.xml
<students>
<student>
<rollno>1</rollno>
<name>Jijo</name>
<classname>10</classname>
</student>
<student>
<rollno>2</rollno>
<name>Mathew</name>
<classname>10</classname>
</student>
<student>
<rollno>3</rollno>
<name>Ajeesh</name>
<classname>10</classname>
</student>
<student>
<rollno>4</rollno>
<name>Prathyush</name>
<classname>10</classname>
</student>
</students>
For more details visit http://www.castor.org.
XML parsing using XPath
XML Parsing using XPath example
//Student.java
package com.jijo;
public class Student {
private String rollNo;
private String name;
private String className;
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
//XPathRead.java
package com.jijo;
/**
* @author jijo
*
*/
import java.io.IOException;
import java.io.InputStream;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class XPathRead {
private Document xmlDocument;
private XPath xPath;
public XPathRead(String xmlFile) {
initObjects(xmlFile);
}
public XPathRead(InputStream inputStream) {
initObjects(inputStream);
}
private void initObjects(String xmlFile){
try {
xmlDocument = DocumentBuilderFactory.
newInstance().newDocumentBuilder().
parse(xmlFile);
xPath = XPathFactory.newInstance().
newXPath();
} catch (IOException ex) {
ex.printStackTrace();
} catch (SAXException ex) {
ex.printStackTrace();
} catch (ParserConfigurationException ex) {
ex.printStackTrace();
}
}
private void initObjects(InputStream inputStream){
try {
xmlDocument = DocumentBuilderFactory.
newInstance().newDocumentBuilder().
parse(inputStream);
xPath = XPathFactory.newInstance().
newXPath();
} catch (IOException ex) {
ex.printStackTrace();
} catch (SAXException ex) {
ex.printStackTrace();
} catch (ParserConfigurationException ex) {
ex.printStackTrace();
}
}
public Object read(String expression,
QName returnType){
try {
XPathExpression xPathExpression =
xPath.compile(expression);
return xPathExpression.evaluate
(xmlDocument, returnType);
} catch (XPathExpressionException ex) {
ex.printStackTrace();
return null;
}
}
public Document getXmlDocument() {
return xmlDocument;
}
public void setXmlDocument(Document xmlDocument) {
this.xmlDocument = xmlDocument;
}
}
//XmlParser.java
/**
*
*/
package com.jijo;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.xpath.XPathConstants;
import org.w3c.dom.DOMException;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* @author jijo
*
*/
public class XmlParser {
private static XPathRead reader;
public XmlParser(XPathRead xpathreader) {
this.reader=xpathreader;
}
public static XPathRead getXPathRead(String xmlData){
XPathRead pathReader = null;
try{
ByteArrayInputStream Bis1 = new ByteArrayInputStream(xmlData.getBytes("UTF-8"));
pathReader=new XPathRead(Bis1);
}
catch (Exception e) {
e.printStackTrace();
}
return pathReader;
}
public List<Student> getStudents(){
List<Student> students = new ArrayList<Student>();
try {
String expression = "/students/student"; //parsing expression
NodeList logCurves = (NodeList)reader.read(expression, XPathConstants.NODESET);
for(int index=0;index<logCurves.getLength();index++){
NodeList curveDetails = logCurves.item(index).getChildNodes();
Student student=new Student();
for(int curveItemIndex=0;curveItemIndex<curveDetails.getLength();curveItemIndex++){
if(curveDetails.item(curveItemIndex).getNodeType()!=Node.TEXT_NODE){
if(curveDetails.item(curveItemIndex).getNodeName().equals("rollno"))
student.setRollNo(curveDetails.item(curveItemIndex).getTextContent());
if(curveDetails.item(curveItemIndex).getNodeName().equals("name"))
student.setName(curveDetails.item(curveItemIndex).getTextContent());
if(curveDetails.item(curveItemIndex).getNodeName().equals("classname"))
student.setClassName(curveDetails.item(curveItemIndex).getTextContent());
}
}
students.add(student);
}
} catch (DOMException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return students;
}
}
//Main.java
package com.jijo;
import java.util.List;
public class Main {
public static void main(String[] args) {
try{
/**
* using xpath
*/
XPathRead pathRead = new XPathRead("C:/jijo/xml/students.xml");
XmlParser parser = new XmlParser(pathRead);
List<Student> students = parser.getStudents();//contains all students data
}
catch (Exception e) {
e.printStackTrace();
}
}
}
XML is given
students.xml
<students>
<student>
<rollno>1</rollno>
<name>Jijo</name>
<classname>10</classname>
</student>
<student>
<rollno>2</rollno>
<name>Mathew</name>
<classname>10</classname>
</student>
<student>
<rollno>3</rollno>
<name>Ajeesh</name>
<classname>10</classname>
</student>
<student>
<rollno>4</rollno>
<name>Prathyush</name>
<classname>10</classname>
</student>
</students>
//Student.java
package com.jijo;
public class Student {
private String rollNo;
private String name;
private String className;
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
//XPathRead.java
package com.jijo;
/**
* @author jijo
*
*/
import java.io.IOException;
import java.io.InputStream;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class XPathRead {
private Document xmlDocument;
private XPath xPath;
public XPathRead(String xmlFile) {
initObjects(xmlFile);
}
public XPathRead(InputStream inputStream) {
initObjects(inputStream);
}
private void initObjects(String xmlFile){
try {
xmlDocument = DocumentBuilderFactory.
newInstance().newDocumentBuilder().
parse(xmlFile);
xPath = XPathFactory.newInstance().
newXPath();
} catch (IOException ex) {
ex.printStackTrace();
} catch (SAXException ex) {
ex.printStackTrace();
} catch (ParserConfigurationException ex) {
ex.printStackTrace();
}
}
private void initObjects(InputStream inputStream){
try {
xmlDocument = DocumentBuilderFactory.
newInstance().newDocumentBuilder().
parse(inputStream);
xPath = XPathFactory.newInstance().
newXPath();
} catch (IOException ex) {
ex.printStackTrace();
} catch (SAXException ex) {
ex.printStackTrace();
} catch (ParserConfigurationException ex) {
ex.printStackTrace();
}
}
public Object read(String expression,
QName returnType){
try {
XPathExpression xPathExpression =
xPath.compile(expression);
return xPathExpression.evaluate
(xmlDocument, returnType);
} catch (XPathExpressionException ex) {
ex.printStackTrace();
return null;
}
}
public Document getXmlDocument() {
return xmlDocument;
}
public void setXmlDocument(Document xmlDocument) {
this.xmlDocument = xmlDocument;
}
}
//XmlParser.java
/**
*
*/
package com.jijo;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.xpath.XPathConstants;
import org.w3c.dom.DOMException;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* @author jijo
*
*/
public class XmlParser {
private static XPathRead reader;
public XmlParser(XPathRead xpathreader) {
this.reader=xpathreader;
}
public static XPathRead getXPathRead(String xmlData){
XPathRead pathReader = null;
try{
ByteArrayInputStream Bis1 = new ByteArrayInputStream(xmlData.getBytes("UTF-8"));
pathReader=new XPathRead(Bis1);
}
catch (Exception e) {
e.printStackTrace();
}
return pathReader;
}
public List<Student> getStudents(){
List<Student> students = new ArrayList<Student>();
try {
String expression = "/students/student"; //parsing expression
NodeList logCurves = (NodeList)reader.read(expression, XPathConstants.NODESET);
for(int index=0;index<logCurves.getLength();index++){
NodeList curveDetails = logCurves.item(index).getChildNodes();
Student student=new Student();
for(int curveItemIndex=0;curveItemIndex<curveDetails.getLength();curveItemIndex++){
if(curveDetails.item(curveItemIndex).getNodeType()!=Node.TEXT_NODE){
if(curveDetails.item(curveItemIndex).getNodeName().equals("rollno"))
student.setRollNo(curveDetails.item(curveItemIndex).getTextContent());
if(curveDetails.item(curveItemIndex).getNodeName().equals("name"))
student.setName(curveDetails.item(curveItemIndex).getTextContent());
if(curveDetails.item(curveItemIndex).getNodeName().equals("classname"))
student.setClassName(curveDetails.item(curveItemIndex).getTextContent());
}
}
students.add(student);
}
} catch (DOMException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return students;
}
}
//Main.java
package com.jijo;
import java.util.List;
public class Main {
public static void main(String[] args) {
try{
/**
* using xpath
*/
XPathRead pathRead = new XPathRead("C:/jijo/xml/students.xml");
XmlParser parser = new XmlParser(pathRead);
List<Student> students = parser.getStudents();//contains all students data
}
catch (Exception e) {
e.printStackTrace();
}
}
}
XML is given
students.xml
<students>
<student>
<rollno>1</rollno>
<name>Jijo</name>
<classname>10</classname>
</student>
<student>
<rollno>2</rollno>
<name>Mathew</name>
<classname>10</classname>
</student>
<student>
<rollno>3</rollno>
<name>Ajeesh</name>
<classname>10</classname>
</student>
<student>
<rollno>4</rollno>
<name>Prathyush</name>
<classname>10</classname>
</student>
</students>
Tuesday, January 26, 2010
Get submap,firstkey , last key from Map(TreeMap)
TreeMap
//get submap from a index to another index
Map subMap = treeMap.subMap(object, object);
//get firstKey
Object firstKey = treeMap.firstKey();
//get last key
Object lastKey = treeMap.lastKey();
//get submap from a index to another index
Map
//get firstKey
Object firstKey = treeMap.firstKey();
//get last key
Object lastKey = treeMap.lastKey();
Compare two objects using Comparable interface
/**
* Object class
*/
package com.jijo;
/**
* @author jijo
*
*/
public class ComparableExample implements Comparable {
private String id;
private String userName;
private String password;
private String firstName;
private String lastName;
public int compareTo(ComparableExample arg0) {
if(this.userName.equals(arg0.getUserName()))
return 0;
else
return 1;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public boolean equals(Object obj) {
if(this.getUserName() != null && this.getUserName().equalsIgnoreCase(((ComparableExample )obj).getUserName())){
return true;
}
else{
return false;
}
}
@Override
public int hashCode() {
if(this.userName != null){
return this.userName.hashCode();
}else{
return 0;
}
}
}
//Main class
package com.jijo;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List list = new ArrayList();
ComparableExample comp = new ComparableExample();
comp.setUserName("jijo");
comp.setFirstName("jijo");
list.add(comp);
ComparableExample comp1 = new ComparableExample();
comp1.setUserName("mathew");
comp1.setFirstName("mathew");
list.add(comp1);
ComparableExample comp2 = new ComparableExample();
comp2.setUserName("jijo");
comp2.setFirstName("jijomathew");
if(list.contains(comp2)){
System.out.println("true");//returns true
}
else{
System.out.println("false");
}
comp1 = new ComparableExample();
comp1.setUserName("jijomathew");
if(list.contains(comp1)){
System.out.println("true");
}
else{
System.out.println("false"); //returns false
}
}
}
* Object class
*/
package com.jijo;
/**
* @author jijo
*
*/
public class ComparableExample implements Comparable
private String id;
private String userName;
private String password;
private String firstName;
private String lastName;
public int compareTo(ComparableExample arg0) {
if(this.userName.equals(arg0.getUserName()))
return 0;
else
return 1;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public boolean equals(Object obj) {
if(this.getUserName() != null && this.getUserName().equalsIgnoreCase(((ComparableExample )obj).getUserName())){
return true;
}
else{
return false;
}
}
@Override
public int hashCode() {
if(this.userName != null){
return this.userName.hashCode();
}else{
return 0;
}
}
}
//Main class
package com.jijo;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List
ComparableExample comp = new ComparableExample();
comp.setUserName("jijo");
comp.setFirstName("jijo");
list.add(comp);
ComparableExample comp1 = new ComparableExample();
comp1.setUserName("mathew");
comp1.setFirstName("mathew");
list.add(comp1);
ComparableExample comp2 = new ComparableExample();
comp2.setUserName("jijo");
comp2.setFirstName("jijomathew");
if(list.contains(comp2)){
System.out.println("true");//returns true
}
else{
System.out.println("false");
}
comp1 = new ComparableExample();
comp1.setUserName("jijomathew");
if(list.contains(comp1)){
System.out.println("true");
}
else{
System.out.println("false"); //returns false
}
}
}
Thursday, July 2, 2009
startsWith and endsWith functions in Javascript
inside script tag,
var data = "Helloo Good Morning";
startsWith
String.prototype.startsWith = function(data)
{
return (this.match("^"+data)==data)
}
eg:
data.startsWith("Helloo");
returns true
-----------------------------------------------------------------------
endsWith
String.prototype.endsWith = function(data)
{
return (this.match(data+"$")==data)
}
eg:
data.endsWith("Helloo");
returns false;
----------------------------------------------------------
trim
String.prototype.trim = function()
{
return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))
}
eg:
var tm = data.trim();
for more ...
http://www.tek-tips.com
var data = "Helloo Good Morning";
startsWith
String.prototype.startsWith = function(data)
{
return (this.match("^"+data)==data)
}
eg:
data.startsWith("Helloo");
returns true
-----------------------------------------------------------------------
endsWith
String.prototype.endsWith = function(data)
{
return (this.match(data+"$")==data)
}
eg:
data.endsWith("Helloo");
returns false;
----------------------------------------------------------
trim
String.prototype.trim = function()
{
return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))
}
eg:
var tm = data.trim();
for more ...
http://www.tek-tips.com
Date showing wrong in JSF outputText or with dataTable
Some times in , h:outputText with dataTable or without , java.util.Date showing wrong, means one date before the actual date is showing.
We can solve this problem using Converter.
One example :
DateConverter.java
package com.converter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
/**
* This class is is used to convert a date to dd-MMM-yyyy format
* @author jijo
*
*/
public class DateConverter implements Converter {
public String getAsString(FacesContext context, UIComponent c, Object object)
throws ConverterException {
if(object!=null && !object.toString().equals("")){
final Date date = (Date) object;
String dt=null;
if(date!=null){
SimpleDateFormat formatter=new SimpleDateFormat("dd-MMM-yyyy");
dt=formatter.format(date);
return dt;
}}
return null;
}
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2)
throws ConverterException {
return null;
}
}
In
faces-config.xml
<converter>
<converter-id>dateConvert<converter-id>
<converter-class>com.converter.DateConverter</converter-class>
</converter>
In your jsp page
<h:outputText value="#{item.onDate}" converter="dateConvert" />
We can solve this problem using Converter.
One example :
DateConverter.java
package com.converter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
/**
* This class is is used to convert a date to dd-MMM-yyyy format
* @author jijo
*
*/
public class DateConverter implements Converter {
public String getAsString(FacesContext context, UIComponent c, Object object)
throws ConverterException {
if(object!=null && !object.toString().equals("")){
final Date date = (Date) object;
String dt=null;
if(date!=null){
SimpleDateFormat formatter=new SimpleDateFormat("dd-MMM-yyyy");
dt=formatter.format(date);
return dt;
}}
return null;
}
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2)
throws ConverterException {
return null;
}
}
In
faces-config.xml
<converter>
<converter-id>dateConvert<converter-id>
<converter-class>com.converter.DateConverter</converter-class>
</converter>
In your jsp page
<h:outputText value="#{item.onDate}" converter="dateConvert" />
Subscribe to:
Posts (Atom)
