Wednesday, August 26, 2009

PDF_read_write_diplay_operations

Invoking service to display the PDF file (the PDF file DB)
Jsp file

Table creation:
DROP TABLE IF EXISTS `thorlabswebservice`.`pdf`;
CREATE TABLE `thorlabswebservice`.`pdf` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(45) default NULL,
`file` blob,
`content_type` varchar(45) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;





Thorlab : User Login


Open PDF




Controller Class: PDFController .java
package com.optrasystems.PDF;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.optrasystems.model.User;
import com.optrasystems.mvc.validator.LoginValidator;
import com.optrasystems.mvc.validator.UserValidator;
import com.optrasystems.service.ImageProcessService;
import com.optrasystems.service.PilotSystemWebservice;
import com.optrasystems.service.UserService;
import com.optrasystems.util.PDF;

@Controller
public class PDFController {

/**
* this controller
*/
@RequestMapping("/PDF")
public String PDFOpen(HttpServletRequest request,HttpServletResponse response) {

//PDF pdf=userService.getPDF();
//request.getSession().setAttribute("pdf",pdf);
InputStream inputStream =null;
try
{
response.setContentType("application/pdf");

byte byteArray[] = new byte[5000];
PDF pdf=getPDF();
inputStream =pdf.getInputStream();

//following method open dialog box for "open", "save", nad "cancel"
//response.setHeader("Content-disposition", "attachment; filename="+pdf.getFileName()+".pdf");

//following method open the file directly....this method open the file in current page so need to open in pop-up
response.setHeader("Content-disposition", "inline; filename="+pdf.getFileName()+".pdf");

ServletOutputStream outStream = response.getOutputStream();

int n = 0;
while ( ( n = inputStream.read(byteArray)) != -1)
{
outStream.write(byteArray, 0, n);
}

outStream.flush();

inputStream.close();
outStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}finally{
try{inputStream.close();

}catch (Exception e) {
e.printStackTrace();
}
}
//return "viewPDF";
return null;
}

//reading Pdf from DB.
public PDF getPDF(){

try{
// PDF class is DTO class
PDF result = (PDF) this.getHibernateTemplate().execute(
(new HibernateCallback() {

public PDF doInHibernate(Session session)
throws HibernateException, SQLException {
//reading Pdf from DB.
String squery = " SELECT name,file FROM PDF WHERE id = 3";
Statement statement = session.connection().createStatement();
ResultSet resultSet = statement.executeQuery(squery.toString());
resultSet.next();
PDF pdf=new PDF();
pdf.setFileName(resultSet.getString(1));
pdf.setInputStream(resultSet.getBinaryStream(2));
return pdf;
}

}));
return result;

}catch (Exception e) {
logger.error(""+ e.getMessage());
}
return null;
}
}

'PDF' DTO class: PDF.java
package com.optrasystems.util;
import java.io.InputStream;

/**
* @author k.panchani
*
*/
public class PDF {

private String fileName;
private InputStream inputStream;


public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
}
==========================================================================
General Reading and writing PDF file with DB

/**
*
*/
package com.optrasystems.PDF;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

/**
* @author k.panchani
* this class having oprations related to PDF file
*
*/
public class TestConnection {

/**
* @param args
*/
public static void main(String[] args) {
try{
TestWritePDF();
//TestReadPDF();
//Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "c:\\chart.pdf");
}catch (Exception e) {
e.printStackTrace();
}

}
/** this method takes pdf file from C:\\Visio-PilotSystemSequence.pdf and
* inserting Pdf file into DB
*/
public static void TestWritePDF()throws Exception{
Connection c=null;
try{
c=getConnection();
String sql = "INSERT INTO PDF VALUES (?, ?, ?,?)";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setInt(1, 3);
stmt.setString(2, "Visioccccccc");

File image = new File("C:\\Visio-PilotSystemSequence.pdf");
FileInputStream fis = new FileInputStream(image);
stmt.setBinaryStream(3, fis, (int) image.length());
//stmt.setInt(4,image.)
stmt.execute();
c.close();

}catch (Exception e) {
e.printStackTrace();
}finally{
if(c!=null){
c.close();
}
}
}
//reading PDF file from DB and Storing in "E" drive
public static void TestReadPDF()throws Exception{
Connection c=null;
try {
c=getConnection();
String sql = "SELECT name,file FROM PDF WHERE id = 2 ";
PreparedStatement stmt = c.prepareStatement(sql);
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
String name = resultSet.getString(1);
File image = new File("E:\\"+name+".pdf");
FileOutputStream fos = new FileOutputStream(image);

byte[] buffer = new byte[1];
InputStream is = resultSet.getBinaryStream(2);
while (is.read(buffer) > 0) {
fos.write(buffer);
}
}
}catch (Exception e) {
e.printStackTrace();
}finally{
if(c!=null){
c.close();
}
}
}

//this method get the Pdf file as bytes and return to caller
public static byte[] getBLOB() throws Exception {
Connection conn=null;
ResultSet rs = null;
PreparedStatement pstmt = null;
String query = "SELECT file FROM PDF WHERE id = ?";
try {
conn=getConnection();
pstmt = conn.prepareStatement(query);
pstmt.setInt(1, 2);
rs = pstmt.executeQuery();
rs.next();
Blob blob = rs.getBlob("file");
// materialize BLOB onto client
return blob.getBytes(1, (int) blob.length());
} finally {
rs.close();
pstmt.close();
conn.close();
}
}
public Connection getConnection(){
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
return DriverManager.getConnection("jdbc:mysql://localhost:3306/thorlabs","root","");
//return DriverManager.getConnection("jdbc:mysql://192.168.100.137:3306/formsjsf","root","pass");

}
catch(Exception e){
System.out.println("error:ConnectionMaker::getConnection()");
e.printStackTrace();
return null;
}
}

}

Thursday, August 20, 2009

How to use ENUM in Hibernate

Using ENUM in Hibernate
1. create enum type
public enum LoginStatus {

ACTIVE,
INACTIVE
}

2. add property with Enum type
private LoginStatus status;

public LoginStatus getStatus() {
return status;
}

public void setStatus(LoginStatus status) {
this.status = status;
}

3. if we use the above code this will insert the entries as index of ENUM values (0,1) in DB insteade of ACTIVE,INACTIVE values

if we want to insert as values then we need to create new table with ENUM values.

Complete JAXB Example

Complete JAXB Example
Xml file: foo.xml




shekhar

12
Hyb
AP



Kajal

12
Hyb
AP




12
Hyb
AP


12
Hyb
AP



Pojo classes :
RootElement.java
package com.client.optrasystems.service;
@XmlRootElement
public class RootElement {
int step;
List element=new ArrayList();
List subElement=new ArrayList();

@XmlAttribute
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
@XmlElementWrapper(name="list")
@XmlElement(name="Element")
public List getElement() {
return element;
}

public void setElement(List element) {
this.element = element;
}

@XmlElement(name="SubElement")
public List getSubElement() {
return subElement;
}
public void setSubElement(List subElement) {
this.subElement = subElement;
}

}
SubElement.java
package com.client.optrasystems.service;
@XmlRootElement
public class SubElement {

private Integer home;
private String city;
private String state;

@XmlElement
public Integer getHome() {
return home;
}
public void setHome(Integer home) {
this.home = home;
}
@XmlElement
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}

@XmlElement
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}

}
Element.java
package com.client.optrasystems.service;
@XmlRootElement
public class Element {
Integer size;
String name;
Address address;

@XmlAttribute
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement(name="address")
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address.java
package com.client.optrasystems.service;
public class Address {

private Integer home;
private String city;
private String state;

@XmlElement
public Integer getHome() {
return home;
}
public void setHome(Integer home) {
this.home = home;
}
@XmlElement
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@XmlElement
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
Test class
package com.client.optrasystems.service;
import java.io.File;
import java.io.FileOutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

public class TestWS {
public static void main(String[] args) {
try
{
JAXBContext jc=JAXBContext.newInstance(RootElement.class);
//creating java object from XML.
Unmarshaller u =jc.createUnmarshaller();
JAXBElement root = u.unmarshal(new StreamSource(new File("D:\\workspace\\webservice_client\\src\\com\\client\\optrasystems\\service\\foo.xml")),RootElement.class);
RootElement foo = root.getValue();
//creating xml file from java object using Jaxb
Marshaller marshaller=jc.createMarshaller();
marshaller.marshal(foo, new FileOutputStream(new File("c:\\foo.xml")));
}catch(Exception e){
e.printStackTrace();
}
}
}

converting java.util.Date to java.sql.Date and java.sql.Date to java.util.Date

Date lDate=new Date();
System.out.println("date :"+lDate);
// convert util date to sql with pattern (sql date supports yyyy-MM-dd only)
SimpleDateFormat m_dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date lDate1=java.sql.Date.valueOf(m_dateFormat1.format(lDate));
System.out.println("Sql date :"+lDate1.toString());

// convert sql date to util date with pattern
SimpleDateFormat m_dateFormat2 = new SimpleDateFormat("yyyyMMdd");
String ldateDate=m_dateFormat1.format(lDate1);
System.out.println("util date :"+m_dateFormat2.parse(ldateDate));


OutPut:

date :Thu Aug 20 17:20:26 IST 2009
Sql date :2009-08-20
util date :Mon Dec 08 00:00:00 IST 2008

Tuesday, August 4, 2009

java code to parse XML using Dom parser

1.xml file
--------

























2.java code to parse the data. here ThorImageExperimentXML is pojo class having all related properties


@Override
public ThorImageExperimentXML getExperimentInformationFromXML(String xmlPath) {
// TODO Auto-generated method stub
ParseXMLFile(xmlPath);
webserviceImageProcessDao.saveXMLExperiment(thorImageExperimentXML);
return thorImageExperimentXML;
}

private ThorImageExperimentXML ParseXMLFile(String xmlFileName) {
Node root;
try {
Document doc = parseFile(xmlFileName);
root = doc.getDocumentElement();

return writeDocumentToOutput(root, 0);

} catch (Exception e) {
e.printStackTrace();
} finally {
root = null;

}
return writeDocumentToOutput(root, 0);
}

private Document parseFile(String fileName) {
Document doc = null;
try {
DocumentBuilder docBuilder;
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
docBuilderFactory.setIgnoringElementContentWhitespace(true);
docBuilder = docBuilderFactory.newDocumentBuilder();
File sourceFile = new File(fileName);
try {
doc = docBuilder.parse(sourceFile);
sourceFile = null;
} catch (SAXException e) {
return null;
}
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Error occured while parsing xml "
+ e.getMessage());
}
}
return doc;
}

private ThorImageExperimentXML writeDocumentToOutput(Node node, int indent) {
String value = "";

try {
// get element name

String nodeName = node.getNodeName();

// get element value
String nodeValue = getElementValue(node);
// get attributes of element
NamedNodeMap attributes = node.getAttributes();

if (nodeName.toString().equals("Name")) {
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
if (attribute.getNodeName().toString().equals("name")) {
System.out.println("The Exact attribute Name== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setName(attribute.getNodeValue().toString());
}
}
}

if (nodeName.toString().equals("Date")) {
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
if (attribute.getNodeName().toString().equals("date")) {
System.out.println("The Exact attribute Date== "
+ attribute.getNodeValue().toString().replace("/", "-"));
//java.sql.Date.valueOf(attribute.getNodeValue().toString().replace("/", "-"))
thorImageExperimentXML.setDate(attribute.getNodeValue().toString());
}
}
}

if (nodeName.toString().equals("User")) {
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
if (attribute.getNodeName().toString().equals("name")) {
System.out.println("The Exact attribute User== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setUserName(attribute.getNodeValue().toString());
}
}
}

if (nodeName.toString().equals("Computer")) {
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
if (attribute.getNodeName().toString().equals("name")) {
System.out.println("The Exact attribute Computer== "
+ attribute.getNodeValue().toString());
}
thorImageExperimentXML.setComputerName(attribute.getNodeValue().toString());
}
}

if (nodeName.toString().equals("Software")) {
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
if (attribute.getNodeName().toString().equals("version")) {
System.out.println("The Exact attribute Software== "
+ attribute.getNodeValue().toString());
}
thorImageExperimentXML.setSoftwareVersion(Float.parseFloat(attribute.getNodeValue().toString()));
}
}

if (nodeName.toString().equals("Camera")) {
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
if (attribute.getNodeName().toString().equals("name")) {
System.out.println("The Exact attribute Camera== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setCameraName(attribute.getNodeValue().toString());
}
if (attribute.getNodeName().toString().equals("width")) {
System.out.println("The Exact attribute Camera== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setCameraWidth(Float.parseFloat(attribute.getNodeValue().toString()));
}
if (attribute.getNodeName().toString().equals("height")) {
System.out.println("The Exact attribute Camera== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setCameraHeight(Float.parseFloat(attribute.getNodeValue().toString()));
}
if (attribute.getNodeName().toString()
.equals("pixelSizeUM")) {
System.out.println("The Exact attribute Camera== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setCameraPixelSizeUM(Float.parseFloat(attribute.getNodeValue().toString()));
}
}
}

if (nodeName.toString().equals("Magnification")) {
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
if (attribute.getNodeName().toString().equals("mag")) {
System.out.println("The Exact attribute Magnification== "
+ attribute.getNodeValue().toString());
}
thorImageExperimentXML.setMagnificationMag(Float.parseFloat(attribute.getNodeValue().toString()));
}
}

if (nodeName.toString().equals("Wavelength")) {
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
if (attribute.getNodeName().toString().equals("name")) {
System.out.println("The Exact attribute Wavelength== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setWavelengthName(attribute.getNodeValue().toString());
}
if (attribute.getNodeName().toString().equals(
"exposureTimeMS")) {
System.out.println("The Exact attribute Wavelength== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setWavelengthExposureTimeMS(Float.parseFloat(attribute.getNodeValue().toString()));
}
}
}

if (nodeName.toString().equals("ZStage")) {
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
if (attribute.getNodeName().toString().equals("name")) {
System.out.println("The Exact attribute ZStage== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setZstageName(attribute.getNodeValue().toString());
}
if (attribute.getNodeName().toString().equals("steps")) {
System.out.println("The Exact attribute ZStage== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setZstageSteps(Float.parseFloat(attribute.getNodeValue().toString()));
}
if (attribute.getNodeName().toString().equals("stepSizeUM")) {
System.out.println("The Exact attribute ZStage== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setZstageStepSizeUM(Float.parseFloat(attribute.getNodeValue().toString()));
}
}
}

if (nodeName.toString().equals("Timelapse")) {
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
if (attribute.getNodeName().toString().equals("timepoints")) {
System.out.println("The Exact attribute Timelapse== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setTimelapseIntervalSec(Float.parseFloat(attribute.getNodeValue().toString()));
}
if (attribute.getNodeName().toString()
.equals("intervalSec")) {
System.out.println("The Exact attribute Timelapse== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setTimelapseTimePoints(Float.parseFloat(attribute.getNodeValue().toString()));
}
}
}

if (nodeName.toString().equals("Sample")) {
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
if (attribute.getNodeName().toString().equals("type")) {
System.out.println("The Exact attribute Sample type== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setSampleType(Float.parseFloat(attribute.getNodeValue().toString()));
}
if (attribute.getNodeName().toString().equals("offsetXMM")) {
System.out.println("The Exact attribute Sample X== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setSampleOffsetXMM(Float.parseFloat(attribute.getNodeValue().toString()));
}
if (attribute.getNodeName().toString().equals("offsetYMM")) {
System.out.println("The Exact attribute Sample Y== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setSampleOffsetYMM(Float.parseFloat(attribute.getNodeValue().toString()));
}
}
}

if (nodeName.toString().equals("Wells")) {
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
if (attribute.getNodeName().toString().equals("rows")) {
System.out.println("The Exact attribute Wells== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setWellsRows(Float.parseFloat(attribute.getNodeValue().toString()));
}
if (attribute.getNodeName().toString().equals("columns")) {
System.out.println("The Exact attribute Wells== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setWellsColumns(Float.parseFloat(attribute.getNodeValue().toString()));
}
if (attribute.getNodeName().toString().equals(
"wellOffsetXMM")) {
System.out.println("The Exact attribute Wells== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setWellsWellOffsetXMM(Float.parseFloat(attribute.getNodeValue().toString()));
}
if (attribute.getNodeName().toString().equals(
"wellOffsetYMM")) {
System.out.println("The Exact attribute Wells== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setWellsWellOffsetYMM(Float.parseFloat(attribute.getNodeValue().toString()));
}
}
}

if (nodeName.toString().equals("SubImages")) {
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
if (attribute.getNodeName().toString().equals("subRows")) {
System.out.println("The Exact attribute SubImages== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setSubimagesSubRows(Float.parseFloat(attribute.getNodeValue().toString()));
}
if (attribute.getNodeName().toString().equals("subColumns")) {
System.out.println("The Exact attribute SubImages== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setSubimagesSubColumns(Float.parseFloat(attribute.getNodeValue().toString()));
}
if (attribute.getNodeName().toString().equals(
"transOffsetXMM")) {
System.out.println("The Exact attribute SubImages== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setSubimagesTransOffsetXMM(Float.parseFloat(attribute.getNodeValue().toString()));
}
if (attribute.getNodeName().toString().equals(
"transOffsetYMM")) {
System.out.println("The Exact attribute SubImages== "
+ attribute.getNodeValue().toString());
thorImageExperimentXML.setSubimagesTransOffsetYMM(Float.parseFloat(attribute.getNodeValue().toString()));
}
}
}

if (nodeName.toString().equals("Comments")) {
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
if (attribute.getNodeName().toString().equals("text")) {
System.out.println("The Exact attribute Comments== "
+ attribute.getNodeValue().toString());
}
thorImageExperimentXML.setCommentsText(attribute.getNodeValue().toString());
}
}
// write all child nodes recursively
NodeList children = node.getChildNodes();

// middle="";
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
// if(node.getNodeName().equals("Computer"))
valuecount = i;
writeDocumentToOutput(child, indent + 2);

}
}
nodeName = null;
nodeValue = null;
} catch (Exception e) {
if (logger.isDebugEnabled()) {
e.printStackTrace();
logger
.debug("Error occured in Comman Class while writing to document "
+ e.getMessage());
}
}
return thorImageExperimentXML;
}

private final String getElementValue(Node elem) {
try {
Node kid;
if (elem != null) {
if (elem.hasChildNodes()) {
for (kid = elem.getFirstChild(); kid != null; kid = kid
.getNextSibling()) {
if (kid.getNodeType() == Node.TEXT_NODE) {
return kid.getNodeValue();
}
}
}
}
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger
.debug("Error occured in Comman Class while getting element value "
+ e.getMessage());
}
}
return "";
}