public static void printAlphabitFromNumber(){
for(int i=0;i<26;i++)
System.out.print((char)('A'+i));// ABCDEFGHIJKLMNOPQRSTUVWXYZ
}
Tuesday, September 22, 2009
Enum with case Insensitive pattern (?i:)
public static enum SubjectType {
//case Insensitive pattern ?i:
MICRO_CENTRIFUGE("(?i:MIX)","max"),
FATHER("(?i:F[C2BV])", "F");
final String _suffix;
final String _lowercase;
//this contractor execute two times.
SubjectType(String suffix,String lowercase) {
_suffix = suffix;
_lowercase=lowercase;
}
//suffix : any String .."fc"
public static SubjectType parse(String suffix) {
for (SubjectType s : values()) {
//know matches()works as case Insensitive..for 'fc' also it return true.
if (suffix.matches(s._suffix)) return s;
}
return null;
}
}
//case Insensitive pattern ?i:
MICRO_CENTRIFUGE("(?i:MIX)","max"),
FATHER("(?i:F[C2BV])", "F");
final String _suffix;
final String _lowercase;
//this contractor execute two times.
SubjectType(String suffix,String lowercase) {
_suffix = suffix;
_lowercase=lowercase;
}
//suffix : any String .."fc"
public static SubjectType parse(String suffix) {
for (SubjectType s : values()) {
//know matches()works as case Insensitive..for 'fc' also it return true.
if (suffix.matches(s._suffix)) return s;
}
return null;
}
}
DateDiffDays and max date detween two date's
1.Date Diff Days :
static public long dateDiffDays(Date d1, Date d2)
{
Calendar c = Calendar.getInstance();
c.clear();
c.setTime(d1);
long t1 = c.getTimeInMillis();
c.clear();
c.setTime(d2);
long t2 = c.getTimeInMillis();
return (t1 - t2) / 1000L / 60L / 60L / 24L;
}
2. Max date :
static public Date max(Date d1, Date d2) {
if (d1==null) return d2;
if (d2==null) return d1;
if (d1.after(d2)) return d1;
return d2;
}
static public long dateDiffDays(Date d1, Date d2)
{
Calendar c = Calendar.getInstance();
c.clear();
c.setTime(d1);
long t1 = c.getTimeInMillis();
c.clear();
c.setTime(d2);
long t2 = c.getTimeInMillis();
return (t1 - t2) / 1000L / 60L / 60L / 24L;
}
2. Max date :
static public Date max(Date d1, Date d2) {
if (d1==null) return d2;
if (d2==null) return d1;
if (d1.after(d2)) return d1;
return d2;
}
Remove Special Characters from String using Regular Expression
The following two examples space also consider as special char so I added /s in pattern. If you don't want you remove that.
1. Remove Special Characters from String using Regular Expression with Matcher.
String inputStr = "Shekhar' reddy* optra# systems?";
String patternStr = "([^a-zA-Z0-9 /s])";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
StringBuffer buf = new StringBuffer();
while ((matcher.find())) {
matcher.appendReplacement(buf, "");
}
matcher.appendTail(buf);
String result = buf.toString();
System.out.println(result);//Shekhar reddy optra systems
2. Remove Special Characters from String using Regular Expression with split() method.
String inputStr = "Shekhar' reddy* optra# systems?";
String patternStr2 = "[^a-zA-Z0-9 /s]";
Pattern pattern2 = Pattern.compile(patternStr2);
String[] str=pattern2.split(inputStr);
StringBuffer buf1 = new StringBuffer();
for(String str1:str){
buf1.append(str1);
}
System.out.println(buf1);//Shekhar reddy optra systems
1. Remove Special Characters from String using Regular Expression with Matcher.
String inputStr = "Shekhar' reddy* optra# systems?";
String patternStr = "([^a-zA-Z0-9 /s])";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
StringBuffer buf = new StringBuffer();
while ((matcher.find())) {
matcher.appendReplacement(buf, "");
}
matcher.appendTail(buf);
String result = buf.toString();
System.out.println(result);//Shekhar reddy optra systems
2. Remove Special Characters from String using Regular Expression with split() method.
String inputStr = "Shekhar' reddy* optra# systems?";
String patternStr2 = "[^a-zA-Z0-9 /s]";
Pattern pattern2 = Pattern.compile(patternStr2);
String[] str=pattern2.split(inputStr);
StringBuffer buf1 = new StringBuffer();
for(String str1:str){
buf1.append(str1);
}
System.out.println(buf1);//Shekhar reddy optra systems
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;
}
}
}
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;
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.
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
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();
}
}
}
Xml file: foo.xml
Pojo classes :
RootElement.java
package com.client.optrasystems.service;
@XmlRootElement
public class RootElement {
int step;
List
List
@XmlAttribute
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
@XmlElementWrapper(name="list")
@XmlElement(name="Element")
public List
return element;
}
public void setElement(List
this.element = element;
}
@XmlElement(name="SubElement")
public List
return subElement;
}
public void setSubElement(List
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
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
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 "";
}
--------
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 "";
}
Monday, July 27, 2009
Getting Image meta data using image File path
the following method return list of metadata info
public static List> readMetaData(String file) {
try {
// Crating image reader for given image.
IFormatReader reader = new ImageReader();
reader.setMetadataFiltered(true);
reader.setOriginalMetadataPopulated(true);
//Passing image path to reader.
reader.setId(file);
List> result = new ArrayList>();
// Extracting core Metadata.
ArrayList coreMataData = new ArrayList();
// Core Mata Data
coreMataData.add(new ImageMatadata("Image Count", reader
.getImageCount()));
coreMataData.add(new ImageMatadata("RGB", reader.isRGB() + " ("
+ reader.getRGBChannelCount() + ")"));
coreMataData.add(new ImageMatadata("Interleaved", reader
.isInterleaved()));
coreMataData.add(new ImageMatadata("Indexed", reader.isIndexed()));
coreMataData.add(new ImageMatadata("Width", reader.getSizeX()));
coreMataData.add(new ImageMatadata("Height", reader.getSizeY()));
coreMataData.add(new ImageMatadata("SizeZ", reader.getSizeZ()));
coreMataData.add(new ImageMatadata("SizeT", reader.getSizeC()));
coreMataData.add(new ImageMatadata("SizeC", reader.getSizeT()));
coreMataData.add(new ImageMatadata("Thumbnail size", reader
.getThumbSizeX()
+ " x " + reader.getThumbSizeY()));
coreMataData.add(new ImageMatadata("Endianness", reader
.isLittleEndian() ? "intel (little)" : "motorola (big)"));
coreMataData
.add(new ImageMatadata("Dimension order", reader
.getDimensionOrder()
+ (reader.isOrderCertain() ? " (certain)"
: " (uncertain)")));
coreMataData.add(new ImageMatadata("Pixel type", FormatTools
.getPixelTypeString(reader.getPixelType())));
coreMataData.add(new ImageMatadata("Metadata complete", reader
.isMetadataComplete()));
coreMataData.add(new ImageMatadata("Thumbnail series", reader
.isThumbnailSeries()));
result.add(coreMataData);
// Extracting Format Specific Data
ArrayList formatSpecificMeta = new ArrayList();
Hashtable formatMeta = reader.getMetadata();
if (formatSpecificMeta != null && formatMeta.size() > 0) {
Enumeration keys = formatMeta.keys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
formatSpecificMeta.add(new ImageMatadata(key, formatMeta
.get(key)));
}
}
result.add(formatSpecificMeta);
return result;
} catch (FormatException e) {
logger.debug("Problem in getting matadata ", e);
} catch (IOException e) {
logger.debug("Problem in getting matadata ", e);
}
return null;
}
ImageMatadata .java:
public class ImageMatadata implements Serializable{
private String name;
private Object value;
public ImageMatadata(String name, Object value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
public static List
try {
// Crating image reader for given image.
IFormatReader reader = new ImageReader();
reader.setMetadataFiltered(true);
reader.setOriginalMetadataPopulated(true);
//Passing image path to reader.
reader.setId(file);
List
// Extracting core Metadata.
ArrayList
// Core Mata Data
coreMataData.add(new ImageMatadata("Image Count", reader
.getImageCount()));
coreMataData.add(new ImageMatadata("RGB", reader.isRGB() + " ("
+ reader.getRGBChannelCount() + ")"));
coreMataData.add(new ImageMatadata("Interleaved", reader
.isInterleaved()));
coreMataData.add(new ImageMatadata("Indexed", reader.isIndexed()));
coreMataData.add(new ImageMatadata("Width", reader.getSizeX()));
coreMataData.add(new ImageMatadata("Height", reader.getSizeY()));
coreMataData.add(new ImageMatadata("SizeZ", reader.getSizeZ()));
coreMataData.add(new ImageMatadata("SizeT", reader.getSizeC()));
coreMataData.add(new ImageMatadata("SizeC", reader.getSizeT()));
coreMataData.add(new ImageMatadata("Thumbnail size", reader
.getThumbSizeX()
+ " x " + reader.getThumbSizeY()));
coreMataData.add(new ImageMatadata("Endianness", reader
.isLittleEndian() ? "intel (little)" : "motorola (big)"));
coreMataData
.add(new ImageMatadata("Dimension order", reader
.getDimensionOrder()
+ (reader.isOrderCertain() ? " (certain)"
: " (uncertain)")));
coreMataData.add(new ImageMatadata("Pixel type", FormatTools
.getPixelTypeString(reader.getPixelType())));
coreMataData.add(new ImageMatadata("Metadata complete", reader
.isMetadataComplete()));
coreMataData.add(new ImageMatadata("Thumbnail series", reader
.isThumbnailSeries()));
result.add(coreMataData);
// Extracting Format Specific Data
ArrayList
Hashtable formatMeta = reader.getMetadata();
if (formatSpecificMeta != null && formatMeta.size() > 0) {
Enumeration keys = formatMeta.keys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
formatSpecificMeta.add(new ImageMatadata(key, formatMeta
.get(key)));
}
}
result.add(formatSpecificMeta);
return result;
} catch (FormatException e) {
logger.debug("Problem in getting matadata ", e);
} catch (IOException e) {
logger.debug("Problem in getting matadata ", e);
}
return null;
}
ImageMatadata .java:
public class ImageMatadata implements Serializable{
private String name;
private Object value;
public ImageMatadata(String name, Object value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
Hibernate : how to get the data from many to many relation tables
Hibernate : how to get the data from many to many relation tables :
Query : select project from Project as project join project.users user where user.userID=:userId
Example:
List projectList =(ArrayList)getHibernateTemplate().execute(new HibernateCallback(){
@Override
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
String lHql="select project from Project as project join project.users user where user.userID=:userId";
Query lQuery=session.createQuery(lHql);
lQuery.setLong("userId", pUserId);
List lProject=lQuery.list();
return lProject;
}
});
Query : select project from Project as project join project.users user where user.userID=:userId
Example:
List
@Override
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
String lHql="select project from Project as project join project.users user where user.userID=:userId";
Query lQuery=session.createQuery(lHql);
lQuery.setLong("userId", pUserId);
List
return lProject;
}
});
Thursday, July 23, 2009
imp Queris in Promotion dao
package com.meijer.foodlab.dao.spring;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.HibernateCallback;
import com.meijer.foodlab.dao.IPromotionDao;
import com.meijer.foodlab.model.domain.Coupon;
import com.meijer.foodlab.model.domain.CouponListResult;
import com.meijer.foodlab.model.domain.IngredientItemPromotion;
import com.meijer.foodlab.model.domain.Promotion;
import com.meijer.foodlab.model.domain.PromotionCategory;
import com.meijer.foodlab.model.domain.PromotionList;
import com.meijer.foodlab.model.domain.Special;
import com.meijer.foodlab.model.domain.UpcPromotion;
/**
* @author kiranreddy
*
*/
public class PromotionDao extends BaseSpringDao implements IPromotionDao {
private static final Logger LOG = Logger.getLogger(PromotionDao.class);
protected JdbcTemplate m_jdbcTemplate;
public PromotionDao() {
super(Promotion.class, "Promotion");
}
public PromotionDao(Class pClazz, String pEntityName) {
super(pClazz, pEntityName);
}
public List findByIds(final List pPromotionIds) {
if (LOG.isDebugEnabled()) {
LOG.debug("finding Promotions by Ids");
}
try {
List lPromotion = (List)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
return pSession.createQuery(
"select this from Promotion as this where this.promotionId in (:pIds)")
.setParameterList("pIds", pPromotionIds)
.list();
}
});
if (null != lPromotion) {
if (LOG.isDebugEnabled()) {
LOG.debug("finding Promotions by Ids");
}
}
return lPromotion;
} catch (RuntimeException lRe) {
LOG.error("finding Promotions by Ids", lRe);
throw lRe;
}
}
public List findSpecialsByStoreId( final Integer pStoreId){
List lList = new ArrayList();
if(pStoreId == null){
lList = (List)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
return pSession.createQuery("select this from Promotion this left join this.stores store" +
" where store.storeId is NULL and this.status='ACTIVE' and this.special=true" +
" and (current_date() between date(this.activationDate) and date(this.expirationDate))" +
" order by this.promotionId")
.list();
}
});
}else{
lList = (List)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
return pSession.createQuery("select this from Promotion this left join this.stores store" +
" where (store.storeId = :pStoreId or this.store.storeId is NULL) and this.status='ACTIVE' and this.special=true" +
" and (current_date() between date(this.activationDate) and date(this.expirationDate))" +
" order by this.promotionId")
.setInteger("pStoreId", pStoreId)
.list();
}
});
}
return lList;
}
public CouponListResult findCouponsByStoreId( final Integer pChainId, final Integer pStoreId,final Integer pOffset,final Integer pMaxResults){
CouponListResult lList = new CouponListResult();
String join = " left join this.brand br ";
String where = " and (br.chain.id IS NULL";
if(null != pChainId){
where += " or br.chain.id = "+pChainId+") ";
} else {
where += ")";
}
final String lChainJoinCriteria = join;
final String lChainWhereCriteria = where;
if(pStoreId == null){
lList = (CouponListResult)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
Long lCount = (Long)pSession.createQuery("select count(distinct this) from Promotion this left join this.ingredientPromotions itempro left join itempro.ingredientItem ingitem left join ingitem.ingredients ings " +
" left join this.stores store " + lChainJoinCriteria +
" where store.storeId is NULL and this.status='ACTIVE' and this.special=false" +
" and (current_date() between date(this.activationDate) and date(this.expirationDate)) " + lChainWhereCriteria +
" order by ings.category desc")
.uniqueResult();
List
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.HibernateCallback;
import com.meijer.foodlab.dao.IPromotionDao;
import com.meijer.foodlab.model.domain.Coupon;
import com.meijer.foodlab.model.domain.CouponListResult;
import com.meijer.foodlab.model.domain.IngredientItemPromotion;
import com.meijer.foodlab.model.domain.Promotion;
import com.meijer.foodlab.model.domain.PromotionCategory;
import com.meijer.foodlab.model.domain.PromotionList;
import com.meijer.foodlab.model.domain.Special;
import com.meijer.foodlab.model.domain.UpcPromotion;
/**
* @author kiranreddy
*
*/
public class PromotionDao extends BaseSpringDao
private static final Logger LOG = Logger.getLogger(PromotionDao.class);
protected JdbcTemplate m_jdbcTemplate;
public PromotionDao() {
super(Promotion.class, "Promotion");
}
public PromotionDao(Class pClazz, String pEntityName) {
super(pClazz, pEntityName);
}
public List
if (LOG.isDebugEnabled()) {
LOG.debug("finding Promotions by Ids");
}
try {
List
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
return pSession.createQuery(
"select this from Promotion as this where this.promotionId in (:pIds)")
.setParameterList("pIds", pPromotionIds)
.list();
}
});
if (null != lPromotion) {
if (LOG.isDebugEnabled()) {
LOG.debug("finding Promotions by Ids");
}
}
return lPromotion;
} catch (RuntimeException lRe) {
LOG.error("finding Promotions by Ids", lRe);
throw lRe;
}
}
public List
List
if(pStoreId == null){
lList = (List
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
return pSession.createQuery("select this from Promotion this left join this.stores store" +
" where store.storeId is NULL and this.status='ACTIVE' and this.special=true" +
" and (current_date() between date(this.activationDate) and date(this.expirationDate))" +
" order by this.promotionId")
.list();
}
});
}else{
lList = (List
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
return pSession.createQuery("select this from Promotion this left join this.stores store" +
" where (store.storeId = :pStoreId or this.store.storeId is NULL) and this.status='ACTIVE' and this.special=true" +
" and (current_date() between date(this.activationDate) and date(this.expirationDate))" +
" order by this.promotionId")
.setInteger("pStoreId", pStoreId)
.list();
}
});
}
return lList;
}
public CouponListResult findCouponsByStoreId( final Integer pChainId, final Integer pStoreId,final Integer pOffset,final Integer pMaxResults){
CouponListResult lList = new CouponListResult();
String join = " left join this.brand br ";
String where = " and (br.chain.id IS NULL";
if(null != pChainId){
where += " or br.chain.id = "+pChainId+") ";
} else {
where += ")";
}
final String lChainJoinCriteria = join;
final String lChainWhereCriteria = where;
if(pStoreId == null){
lList = (CouponListResult)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
Long lCount = (Long)pSession.createQuery("select count(distinct this) from Promotion this left join this.ingredientPromotions itempro left join itempro.ingredientItem ingitem left join ingitem.ingredients ings " +
" left join this.stores store " + lChainJoinCriteria +
" where store.storeId is NULL and this.status='ACTIVE' and this.special=false" +
" and (current_date() between date(this.activationDate) and date(this.expirationDate)) " + lChainWhereCriteria +
" order by ings.category desc")
.uniqueResult();
List
imp queries PromotionCategorydao
package com.meijer.foodlab.dao.spring;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.HibernateCallback;
import com.meijer.foodlab.dao.IPromotionCategoryDao;
import com.meijer.foodlab.model.domain.PromotionCategory;
import com.meijer.foodlab.model.domain.PromotionCategoryList;
/**
* @author dbusch
*/
public class PromotionCategoryDaoImpl extends BaseSpringDao implements IPromotionCategoryDao {
private static final Logger LOG = Logger.getLogger(PromotionCategoryDaoImpl.class);
protected JdbcTemplate m_jdbcTemplate;
public PromotionCategoryDaoImpl() {
super(PromotionCategory.class, "PromotionCategory");
}
public PromotionCategoryDaoImpl(Class pClazz, String pEntityName) {
super(pClazz, pEntityName);
}
public PromotionCategory findByRefName(final String pName) {
if (LOG.isDebugEnabled()) {
LOG.debug("finding PromotionCategory by refName");
}
try {
PromotionCategory lCategory = (PromotionCategory)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
return pSession.createQuery(
"select this from PromotionCategory as this join fetch this.promotions where this.refName = :refName")
.setString("refName", pName)
.uniqueResult();
}
});
if (null != lCategory) {
if (LOG.isDebugEnabled()) {
LOG.debug("finding PromotionCategory by refName successful");
}
}
return lCategory;
} catch (RuntimeException lRe) {
LOG.error("finding PromotionCategory by refName failed", lRe);
throw lRe;
}
}
public List getActivePromotionsForStore(final Integer pStoreId) {
if (LOG.isDebugEnabled()) {
LOG.debug("finding active promotions by store");
}
try {
List lResult = (List) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
List lCounts = pSession.createQuery(
"select cat.name, count(distinct promo.promotionId) as qty, cat.image " +
" from PromotionCategory cat" +
" inner join cat.promotions as promo " +
" inner join promo.stores store" +
" where cat.active = true " +
" and promo.special = true" +
" and promo.status = 'ACTIVE'" +
" and store.unitId = :pStoreId" +
" and store.status = 'ACTIVE'" +
" and ( now() between date(promo.activationDate) and date(promo.expirationDate) )" +
" group by cat.name " +
" having count(distinct promo.promotionId) > 0 " +
" order by cat.sortIdx")
.setInteger("pStoreId", pStoreId)
.list();
return lCounts;
}
});
if (null != lResult) {
if (LOG.isDebugEnabled()) {
LOG.debug("finding active promotions by store successful, found: " + lResult.size());
}
}
return lResult;
} catch (RuntimeException lRe) {
LOG.error("finding active promotions by store failed", lRe);
throw lRe;
}
}
/**
* Find the number of promotion map with the category.
* @return int
*/
public int findByPromotionCategoryByIds(final Integer pPromotionId, final Integer pPromotionCategoryId) {
if (LOG.isDebugEnabled()) {
LOG.debug("finding PromotionCategoryByIds for Promotion Id ["+pPromotionId+"] And PromotionCategoryId ["+pPromotionCategoryId+"]");
}
Integer count = new Integer(0);
try {
count = (Integer) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
//forming queries
String lQueryforCount = "select count(1) as count from fl_promotion_category_membership this where" +
" this.promotion_category_id = "+pPromotionCategoryId+" and this.promotion_id = "+pPromotionId;
//execute the query for the entity count
Query lCountQuery = pSession.createSQLQuery(lQueryforCount).addScalar("count", Hibernate.INTEGER);
Integer count = (Integer)lCountQuery.uniqueResult();
if (LOG.isDebugEnabled()) {
LOG.debug("findPromotionCategoryByIds successful. Found count ["+(count == null ? 0 : count.intValue())+"]");
}
if(count == null) {
return 0;
} else {
return count.intValue();
}
}
});
return count.intValue();
} catch (RuntimeException e) {
LOG.error("findPromotionCategoryByIds failed", e);
throw e;
}
}
/**
* Find PromotionCategory based on 'name' field value.
*/
public PromotionCategory findByName(final String pName) {
if (LOG.isDebugEnabled()) {
LOG.debug("finding PromotionCategory by Name ["+(pName == null ? "NA" : pName)+"]");
}
try {
PromotionCategory lCategory = (PromotionCategory)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
List lList = pSession.createQuery(
"select this from PromotionCategory as this where this.name = :pName")
.setString("pName", pName)
.setMaxResults(1)
.list();
if(lList == null || lList.isEmpty()) {
return null;
}
return lList.get(0);
}
});
if (LOG.isDebugEnabled()) {
LOG.debug("finding PromotionCategory by Name successful");
}
return lCategory;
} catch (RuntimeException lRe) {
LOG.error("finding PromotionCategory by Name failed", lRe);
throw lRe;
}
}
public PromotionCategoryList searchCategory(final String pName, final boolean pActive, final int pOffset, final int pMaxResults) {
try {
Object lResult = getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
String lStatusCriteria = "";
if(!pActive){
lStatusCriteria = " where category.active= 1 ";
} else {
lStatusCriteria = " where (category.active=0 OR category.active=1)";
}
String lNameCriteria = "", lName = pName;
if(pName != null) {
if(pName.indexOf("'")!=-1){
lName = pName.replaceAll("'", "_");
}
lNameCriteria = "category.name like '%"+ lName +"%'";
}
String lChainCriteria = "";
//forming queries
String lQueryforCount = "select count(category) from PromotionCategory category" +
lStatusCriteria + (lNameCriteria == "" ? "" : " and ") +
lNameCriteria + (lChainCriteria == "" ? "" : " and ") +
lChainCriteria + " order by category.promotionCategoryId asc" ;
String lQueryForCategory = "select category from PromotionCategory category" +
lStatusCriteria + (lNameCriteria == "" ? "" : " and ") +
lNameCriteria + (lChainCriteria == "" ? "" : " and ") +
lChainCriteria + " order by category.sortIdx asc" ;
Long count = (Long)pSession.createQuery(lQueryforCount).uniqueResult();
List lResult = pSession.createQuery(lQueryForCategory)
.setFirstResult(pOffset)
.setMaxResults(pMaxResults)
.list();
PromotionCategoryList lResults = new PromotionCategoryList();
lResults.setCategories(lResult);
lResults.setMaxResults(pMaxResults);
lResults.setOffset(pOffset);
lResults.setTotalCount(count.intValue());
if (LOG.isDebugEnabled()) {
LOG.debug("searchCategory successfull. found " + lResult.size() + " PromotionCategory");
}
return lResults;
}
});
PromotionCategoryList lPromotionCategories = (PromotionCategoryList)lResult;
return lPromotionCategories;
} catch (RuntimeException e) {
LOG.error("searchCategory failed", e);
throw e;
}
}
/**
* Delete the PromotionCategory and associated membership of the category
* @param pCategoryId
* @return
*/
public Integer deleteCategory(final Integer pCategoryId) {
if (LOG.isDebugEnabled()) {
LOG.debug("Deleting PromotionCategory by CategoryId");
}
try {
String[] lDeleteQueries = new String[] {
"delete cm from fl_promotion_category_membership cm " +
"where cm.promotion_category_id = " +pCategoryId ,
"delete p from fl_promotion_category p where p.promotion_category_id = " + pCategoryId};
int[] lCounts = m_jdbcTemplate.batchUpdate(lDeleteQueries);
//last result
Integer lResult = lCounts[lCounts.length -1];
//force cache clearing
getHibernateTemplate().getSessionFactory().evict(PromotionCategory.class);
if (LOG.isDebugEnabled()) {
LOG.debug("deleted " + lResult + " promotioncategory");
}
return lResult;
}catch (RuntimeException e) {
LOG.error("deleteCategory failed", e);
throw e;
}
}
public List getActiveCategories() {
return getHibernateTemplate().find("from PromotionCategory where active is true order by sortIdx asc");
}
@SuppressWarnings("unchecked")
public List findCategoriesByName(final String pName) {
List lResult = new ArrayList();
try {
lResult = (List) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
String lNameCriteria = "";
if(pName != null) {
lNameCriteria = " category.name = :pName ";
}
//forming queries
String lQueryForCategory =
"select category from PromotionCategory category " +
"where" + lNameCriteria +
" order by category.promotionCategoryId asc";
Query lQuery = pSession.createQuery(lQueryForCategory);
if(pName != null){
lQuery.setString("pName", pName);
}
List lResult = (List) lQuery.list();
if (LOG.isDebugEnabled()) {
LOG.debug("findCategoriesByNameChain successfull. found " + lResult.size() + " PromotionCategory");
}
return lResult;
}
});
return lResult;
} catch (RuntimeException e) {
LOG.error("findCategoriesByNameChain failed", e);
throw e;
}
}
public int[] updatePromotionCategories(Integer pPromotionId,List pCategoryIds){
try{
String lQueryString="delete cm from fl_promotion_category_membership cm where cm.promotion_id ="+pPromotionId;
m_jdbcTemplate.update(lQueryString);
String[] lDeleteQueries = new String[pCategoryIds.size()];
for(int i=0;i lDeleteQueries[i]= "insert into fl_promotion_category_membership values ("+ pCategoryIds.get(i)+","+pPromotionId+")";
}
int[] upadtes=m_jdbcTemplate.batchUpdate(lDeleteQueries);
return upadtes;
}catch(RuntimeException ex){
LOG.error("error while updating the Promotion Categories :"+ex.getMessage());
throw ex;
}
}
public List getPromotionCategoriesWithPromotionId(final Integer pPomotionIds){
try {
List lResult = (List) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
//forming queries
String lQueryForCategory ="select promotion_category_id from fl_promotion_category_membership where promotion_id ="+pPomotionIds;
Query lQuery = pSession.createSQLQuery(lQueryForCategory);
return lQuery.list();
}
});
return lResult;
}catch(Exception ex){
LOG.error("error while getting the Promotion CategoryIds :"+ex.getMessage());
}
return null;
}
public List getActivePromotionsForStoreIds(final List storeIds,final String promotionType){
if (LOG.isDebugEnabled()) {
LOG.debug("finding active promotions by store");
}
try {
List lResult = (List) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
String lSelectClause="select cat, count(distinct promo.promotionId) as qty, cat.image " +
" from PromotionCategory cat" +
" inner join cat.promotions as promo " +
" inner join promo.stores store" ;
String lWhereClause=" where cat.active = true " +
" and promo.status = 'ACTIVE'" +
" and store.status = 'ACTIVE'" +
" and ( now() between date(promo.activationDate) and date(promo.expirationDate))" +
" and store.unitId in (:ids) " ;
if (null!=promotionType){
if ("SPECIAL".equals(promotionType))
lWhereClause+=" and promo.special = true";
else if("COUPON".equals(promotionType))
lWhereClause+=" and promo.special = false";
}
lWhereClause+=" group by cat.name " +
" having count(distinct promo.promotionId) > 0 " +
" order by cat.sortIdx";
List lCounts = pSession.createQuery(lSelectClause+lWhereClause)
.setParameterList("ids", storeIds)
.list();
return lCounts;
}
});
if (LOG.isDebugEnabled()) {
LOG.debug("finding active promotions by store ids successful, found: " + lResult.size());
}
return lResult;
} catch (RuntimeException lRe) {
LOG.error("finding active promotions by store failed", lRe);
throw lRe;
}
}
public JdbcTemplate getJdbcTemplate() {
return this.m_jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate pJdbcTemplate) {
this.m_jdbcTemplate = pJdbcTemplate;
}
}
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.HibernateCallback;
import com.meijer.foodlab.dao.IPromotionCategoryDao;
import com.meijer.foodlab.model.domain.PromotionCategory;
import com.meijer.foodlab.model.domain.PromotionCategoryList;
/**
* @author dbusch
*/
public class PromotionCategoryDaoImpl extends BaseSpringDao
private static final Logger LOG = Logger.getLogger(PromotionCategoryDaoImpl.class);
protected JdbcTemplate m_jdbcTemplate;
public PromotionCategoryDaoImpl() {
super(PromotionCategory.class, "PromotionCategory");
}
public PromotionCategoryDaoImpl(Class pClazz, String pEntityName) {
super(pClazz, pEntityName);
}
public PromotionCategory findByRefName(final String pName) {
if (LOG.isDebugEnabled()) {
LOG.debug("finding PromotionCategory by refName");
}
try {
PromotionCategory lCategory = (PromotionCategory)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
return pSession.createQuery(
"select this from PromotionCategory as this join fetch this.promotions where this.refName = :refName")
.setString("refName", pName)
.uniqueResult();
}
});
if (null != lCategory) {
if (LOG.isDebugEnabled()) {
LOG.debug("finding PromotionCategory by refName successful");
}
}
return lCategory;
} catch (RuntimeException lRe) {
LOG.error("finding PromotionCategory by refName failed", lRe);
throw lRe;
}
}
public List
if (LOG.isDebugEnabled()) {
LOG.debug("finding active promotions by store");
}
try {
List
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
List lCounts = pSession.createQuery(
"select cat.name, count(distinct promo.promotionId) as qty, cat.image " +
" from PromotionCategory cat" +
" inner join cat.promotions as promo " +
" inner join promo.stores store" +
" where cat.active = true " +
" and promo.special = true" +
" and promo.status = 'ACTIVE'" +
" and store.unitId = :pStoreId" +
" and store.status = 'ACTIVE'" +
" and ( now() between date(promo.activationDate) and date(promo.expirationDate) )" +
" group by cat.name " +
" having count(distinct promo.promotionId) > 0 " +
" order by cat.sortIdx")
.setInteger("pStoreId", pStoreId)
.list();
return lCounts;
}
});
if (null != lResult) {
if (LOG.isDebugEnabled()) {
LOG.debug("finding active promotions by store successful, found: " + lResult.size());
}
}
return lResult;
} catch (RuntimeException lRe) {
LOG.error("finding active promotions by store failed", lRe);
throw lRe;
}
}
/**
* Find the number of promotion map with the category.
* @return int
*/
public int findByPromotionCategoryByIds(final Integer pPromotionId, final Integer pPromotionCategoryId) {
if (LOG.isDebugEnabled()) {
LOG.debug("finding PromotionCategoryByIds for Promotion Id ["+pPromotionId+"] And PromotionCategoryId ["+pPromotionCategoryId+"]");
}
Integer count = new Integer(0);
try {
count = (Integer) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
//forming queries
String lQueryforCount = "select count(1) as count from fl_promotion_category_membership this where" +
" this.promotion_category_id = "+pPromotionCategoryId+" and this.promotion_id = "+pPromotionId;
//execute the query for the entity count
Query lCountQuery = pSession.createSQLQuery(lQueryforCount).addScalar("count", Hibernate.INTEGER);
Integer count = (Integer)lCountQuery.uniqueResult();
if (LOG.isDebugEnabled()) {
LOG.debug("findPromotionCategoryByIds successful. Found count ["+(count == null ? 0 : count.intValue())+"]");
}
if(count == null) {
return 0;
} else {
return count.intValue();
}
}
});
return count.intValue();
} catch (RuntimeException e) {
LOG.error("findPromotionCategoryByIds failed", e);
throw e;
}
}
/**
* Find PromotionCategory based on 'name' field value.
*/
public PromotionCategory findByName(final String pName) {
if (LOG.isDebugEnabled()) {
LOG.debug("finding PromotionCategory by Name ["+(pName == null ? "NA" : pName)+"]");
}
try {
PromotionCategory lCategory = (PromotionCategory)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
List
"select this from PromotionCategory as this where this.name = :pName")
.setString("pName", pName)
.setMaxResults(1)
.list();
if(lList == null || lList.isEmpty()) {
return null;
}
return lList.get(0);
}
});
if (LOG.isDebugEnabled()) {
LOG.debug("finding PromotionCategory by Name successful");
}
return lCategory;
} catch (RuntimeException lRe) {
LOG.error("finding PromotionCategory by Name failed", lRe);
throw lRe;
}
}
public PromotionCategoryList searchCategory(final String pName, final boolean pActive, final int pOffset, final int pMaxResults) {
try {
Object lResult = getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
String lStatusCriteria = "";
if(!pActive){
lStatusCriteria = " where category.active= 1 ";
} else {
lStatusCriteria = " where (category.active=0 OR category.active=1)";
}
String lNameCriteria = "", lName = pName;
if(pName != null) {
if(pName.indexOf("'")!=-1){
lName = pName.replaceAll("'", "_");
}
lNameCriteria = "category.name like '%"+ lName +"%'";
}
String lChainCriteria = "";
//forming queries
String lQueryforCount = "select count(category) from PromotionCategory category" +
lStatusCriteria + (lNameCriteria == "" ? "" : " and ") +
lNameCriteria + (lChainCriteria == "" ? "" : " and ") +
lChainCriteria + " order by category.promotionCategoryId asc" ;
String lQueryForCategory = "select category from PromotionCategory category" +
lStatusCriteria + (lNameCriteria == "" ? "" : " and ") +
lNameCriteria + (lChainCriteria == "" ? "" : " and ") +
lChainCriteria + " order by category.sortIdx asc" ;
Long count = (Long)pSession.createQuery(lQueryforCount).uniqueResult();
List
.setFirstResult(pOffset)
.setMaxResults(pMaxResults)
.list();
PromotionCategoryList lResults = new PromotionCategoryList();
lResults.setCategories(lResult);
lResults.setMaxResults(pMaxResults);
lResults.setOffset(pOffset);
lResults.setTotalCount(count.intValue());
if (LOG.isDebugEnabled()) {
LOG.debug("searchCategory successfull. found " + lResult.size() + " PromotionCategory");
}
return lResults;
}
});
PromotionCategoryList lPromotionCategories = (PromotionCategoryList)lResult;
return lPromotionCategories;
} catch (RuntimeException e) {
LOG.error("searchCategory failed", e);
throw e;
}
}
/**
* Delete the PromotionCategory and associated membership of the category
* @param pCategoryId
* @return
*/
public Integer deleteCategory(final Integer pCategoryId) {
if (LOG.isDebugEnabled()) {
LOG.debug("Deleting PromotionCategory by CategoryId");
}
try {
String[] lDeleteQueries = new String[] {
"delete cm from fl_promotion_category_membership cm " +
"where cm.promotion_category_id = " +pCategoryId ,
"delete p from fl_promotion_category p where p.promotion_category_id = " + pCategoryId};
int[] lCounts = m_jdbcTemplate.batchUpdate(lDeleteQueries);
//last result
Integer lResult = lCounts[lCounts.length -1];
//force cache clearing
getHibernateTemplate().getSessionFactory().evict(PromotionCategory.class);
if (LOG.isDebugEnabled()) {
LOG.debug("deleted " + lResult + " promotioncategory");
}
return lResult;
}catch (RuntimeException e) {
LOG.error("deleteCategory failed", e);
throw e;
}
}
public List
return getHibernateTemplate().find("from PromotionCategory where active is true order by sortIdx asc");
}
@SuppressWarnings("unchecked")
public List
List
try {
lResult = (List
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
String lNameCriteria = "";
if(pName != null) {
lNameCriteria = " category.name = :pName ";
}
//forming queries
String lQueryForCategory =
"select category from PromotionCategory category " +
"where" + lNameCriteria +
" order by category.promotionCategoryId asc";
Query lQuery = pSession.createQuery(lQueryForCategory);
if(pName != null){
lQuery.setString("pName", pName);
}
List
if (LOG.isDebugEnabled()) {
LOG.debug("findCategoriesByNameChain successfull. found " + lResult.size() + " PromotionCategory");
}
return lResult;
}
});
return lResult;
} catch (RuntimeException e) {
LOG.error("findCategoriesByNameChain failed", e);
throw e;
}
}
public int[] updatePromotionCategories(Integer pPromotionId,List
try{
String lQueryString="delete cm from fl_promotion_category_membership cm where cm.promotion_id ="+pPromotionId;
m_jdbcTemplate.update(lQueryString);
String[] lDeleteQueries = new String[pCategoryIds.size()];
for(int i=0;i
}
int[] upadtes=m_jdbcTemplate.batchUpdate(lDeleteQueries);
return upadtes;
}catch(RuntimeException ex){
LOG.error("error while updating the Promotion Categories :"+ex.getMessage());
throw ex;
}
}
public List
try {
List
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
//forming queries
String lQueryForCategory ="select promotion_category_id from fl_promotion_category_membership where promotion_id ="+pPomotionIds;
Query lQuery = pSession.createSQLQuery(lQueryForCategory);
return lQuery.list();
}
});
return lResult;
}catch(Exception ex){
LOG.error("error while getting the Promotion CategoryIds :"+ex.getMessage());
}
return null;
}
public List
if (LOG.isDebugEnabled()) {
LOG.debug("finding active promotions by store");
}
try {
List
public Object doInHibernate(Session pSession)
throws HibernateException, SQLException {
String lSelectClause="select cat, count(distinct promo.promotionId) as qty, cat.image " +
" from PromotionCategory cat" +
" inner join cat.promotions as promo " +
" inner join promo.stores store" ;
String lWhereClause=" where cat.active = true " +
" and promo.status = 'ACTIVE'" +
" and store.status = 'ACTIVE'" +
" and ( now() between date(promo.activationDate) and date(promo.expirationDate))" +
" and store.unitId in (:ids) " ;
if (null!=promotionType){
if ("SPECIAL".equals(promotionType))
lWhereClause+=" and promo.special = true";
else if("COUPON".equals(promotionType))
lWhereClause+=" and promo.special = false";
}
lWhereClause+=" group by cat.name " +
" having count(distinct promo.promotionId) > 0 " +
" order by cat.sortIdx";
List lCounts = pSession.createQuery(lSelectClause+lWhereClause)
.setParameterList("ids", storeIds)
.list();
return lCounts;
}
});
if (LOG.isDebugEnabled()) {
LOG.debug("finding active promotions by store ids successful, found: " + lResult.size());
}
return lResult;
} catch (RuntimeException lRe) {
LOG.error("finding active promotions by store failed", lRe);
throw lRe;
}
}
public JdbcTemplate getJdbcTemplate() {
return this.m_jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate pJdbcTemplate) {
this.m_jdbcTemplate = pJdbcTemplate;
}
}
Subscribe to:
Posts (Atom)