Requirement Constraints

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Thursday, 26 July 2012

My date box Component

Posted on 06:16 by Unknown

Using jquery plugin, we will create our date box component in ZK and apply mask and water mark. You can download the jquery plugin from the following site
http://digitalbush.com/projects/masked-input-plugin/
http://digitalbush.com/projects/watermark-input-plugin/

 

Environment

  1. Eclipse 3.7 Indigo IDE
  2. Hibernate 4.1.1
  3. JavaSE 1.6
  4. MySQL 5.1
Project Name :MyDateComponent
Project Structure:

image

Step 1: 
ZK + Hibernate Setup
Please follow this post to setup the Project and related jar files needed for this example
Step 2:
SQL Setup. Create the following table in my sql.

CREATE TABLE `emp_master` (
  `ID` BIGINT(20) NOT NULL AUTO_INCREMENT,
  `EMP_NAME` VARCHAR(255) DEFAULT NULL,
  `DOB` DATE DEFAULT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=INNODB DEFAULT CHARSET=latin1

Step 3:
In the Webcontent folder, create a folder called js and attached the downloaded the plugin.
image

You can also download the files from my site as follows
Download this and this

Step 4:
Let us create all our classes and zul files

Datebox.java


package component;

import org.zkoss.zul.Textbox;

public class Datebox extends Textbox {

private static final long serialVersionUID = 1L;

public Datebox() {

setWidgetListener("onBind", "jq(this).mask('99/99/9999');jq(this).Watermark('mm/dd/yyyy','gray');");
}

}

MyDateFormatConverter.java




package component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.zkoss.bind.BindContext;
import org.zkoss.bind.Converter;
import org.zkoss.zk.ui.Component;


@SuppressWarnings("rawtypes")
public class MyDateFormatConverter implements Converter {
/**
* Convert Date to String.
*
* @param val
* date to be converted
* @param comp
* associated component
* @param ctx
* bind context for associate Binding and extra parameter (e.g.
* format)
* @return the converted String
*/

private static SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

public Object coerceToUi(Object val, Component comp, BindContext ctx) {
final Date date = (Date) val;
return date == null ? null : sdf.format(date);
}

/**
* Convert String to Date.
*
* @param val
* date in string form
* @param comp
* associated component
* @param ctx
* bind context for associate Binding and extra parameter (e.g.
* format)
* @return the converted Date
*/
public Object coerceToBean(Object val, Component comp, BindContext ctx) {
final String date = (String) val;

try {
return date == null ? null : sdf.parse(date);
} catch (ParseException e) {
comp.invalidate();
return null;

}
}

}

EmployeeDAO.java


package domainDAO;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Query;
import HibernateUtilities.HibernateUtil;
import mydomain.employee;

public class EmployeeDAO {

@SuppressWarnings("unchecked")
public List<employee> getAllEmployee() {
List<employee> allrecords = null;
try {
Session session = HibernateUtil.beginTransaction();
Query q1 = session.createQuery("from employee");
allrecords = q1.list();
HibernateUtil.CommitTransaction();
} catch (RuntimeException e) {
e.printStackTrace();
}
return allrecords;
}

public void saveOrUpdate(employee p1) {

try {
Session session = HibernateUtil.beginTransaction();
session.saveOrUpdate(p1);
HibernateUtil.CommitTransaction();
} catch (RuntimeException e) {
e.printStackTrace();
}

}
}


EmployeeCRUDVM.java


package domainVMS;

import java.util.HashMap;
import java.util.Map;

import mydomain.employee;

import org.zkoss.bind.BindUtils;

import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.ExecutionArgParam;
import org.zkoss.bind.annotation.Init;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Window;
import domainDAO.EmployeeDAO;

public class EmployeeCRUDVM {

@Wire("#win")
private Window win;

private employee selectedEmployee;
private boolean makeAsReadOnly;


public employee getSelectedEmployee() {
return selectedEmployee;
}

public void setSelectedEmployee(employee selectedEmployee) {
this.selectedEmployee = selectedEmployee;
}

public boolean isMakeAsReadOnly() {
return makeAsReadOnly;
}
public void setMakeAsReadOnly(boolean makeAsReadOnly) {
this.makeAsReadOnly = makeAsReadOnly;
}

@Init
public void initSetup(@ContextParam(ContextType.VIEW) Component view,
@ExecutionArgParam("selectedEmployee") employee selectedEmployee,
@ExecutionArgParam("recordMode") String recordMode) {
Selectors.wireComponents(view, this, false);
if (selectedEmployee== null)
this.selectedEmployee = new employee();
else
this.selectedEmployee = selectedEmployee;

if (recordMode == "READ") {
setMakeAsReadOnly(true);
win.setTitle(win.getTitle() + " (Readonly)");
}

}

@Command
public void save() {
new EmployeeDAO().saveOrUpdate(this.selectedEmployee);
Map args = new HashMap();
args.put("newadded", this.selectedEmployee);
BindUtils.postGlobalCommand(null, null, "refreshList", args);
win.detach();
}

@Command
public void closeThis() {
win.detach();
}
}


EmployeeListVM.java

package domainVMS;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.GlobalCommand;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Executions;
import domainDAO.EmployeeDAO;
import mydomain.employee;

public class EmployeeListVM {

private List<employee> employees= new ArrayList<employee>();
private employee curSelectedEmployee;

public List<employee> getallEmployees() {
return employees;
}


public employee getCurSelectedEmployee() {
return curSelectedEmployee;
}

public void setCurSelectedEmployee(employee curSelectedEmployee) {
this.curSelectedEmployee = curSelectedEmployee;
}

@Init
public void initSetup() {
employees= new EmployeeDAO().getAllEmployee();

}

@Command
public void editThisEmployee () {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("selectedEmployee", curSelectedEmployee);
map.put("recordMode", "EDIT");
Executions.createComponents("EmployeeCRUD.zul", null, map);
}

@Command
public void openAsReadOnly()
{
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("recordMode", "READ");
map.put("selectedEmployee", curSelectedEmployee);
Executions.createComponents("EmployeeCRUD.zul", null, map);

}

@Command
public void addNewEmployee() {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("selectedEmployee", null);
map.put("recordMode", "NEW");
Executions.createComponents("EmployeeCRUD.zul", null, map);
}


@GlobalCommand
@NotifyChange("allEmployees")
public void refreshList(@BindingParam("newadded") employee p1)
{
employees.add(p1);
}

}


employee.java


package mydomain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = "emp_master")
public class employee {

@Id
@GeneratedValue
private int ID;
@Column(name = "EMP_NAME")
private String employeeName;

@Column(name = "DOB")
@Temporal(TemporalType.DATE)
private Date dateOfBirth;


public Date getDateOfBirth() {
return dateOfBirth;
}

public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}

public int getID() {
return ID;
}

public void setID(int iD) {
ID = iD;
}

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

}


hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/sampledb</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>

<!-- Mapping Classes -->
<mapping class="mydomain.employee" />

</session-factory>
</hibernate-configuration>


Please change the DB Name, username and password according to your setup.

EmployeeList.zul


<?page title="Listitem MVVM Demo with Hibernate" contentType="text/html;charset=UTF-8"?>
<zk>
<style>
.z-listcell.red .z-listcell-cnt, .z-label.red{ color:red; }

/* Start: Action Images- Edit
---------------------------------------------- */

.fimageedit { width: 25px; background-image:
url('./images/icon-edit.png'); background-repeat: no-repeat;
border: 0 none; cursor: pointer; }

/* End: Action Images - Edit
---------------------------------------------- */


/* Start: Action Images- Delete
---------------------------------------------- */

.fimageDelete { width: 25px; background-image:
url('./images/icon-trash-red.png'); background-repeat:
no-repeat; border: 0 none; cursor: pointer; }

/* End: Action Images - Delete
---------------------------------------------- */


/* Start: Action Images- Active
---------------------------------------------- */

.fimageActive { width: 25px; background-image:
url('./images/icon-enable.png'); background-repeat: no-repeat;
border: 0 none; cursor: pointer; }

/* End: Action Images - Active
---------------------------------------------- */

/* Start: Action Images- Inactive' ]

---------------------------------------------- */

.fimageInactive { width: 25px; background-image:
url('./images/icon-disable.png'); background-repeat: no-repeat;
border: 0 none; cursor: pointer; }

/* End: Action Images - InActive
---------------------------------------------- */

.z-listcell.highlightcell .z-listcell-cnt,
.z-label.highlightcell { color:blue; cursor: pointer; }


</style>
<window title="Listitem MVVM Demo with Hibernate" border="normal"
apply="org.zkoss.bind.BindComposer"
viewModel="@id('myvm') @init('domainVMS.EmployeeListVM')">
<div>
<button label="Add Employee"
onClick="@command('addNewEmployee')" />
</div>
<separator />

<listbox id="test" model="@load(myvm.allEmployees)"
selectedItem="@bind(myvm.curSelectedEmployee)">
<listhead sizable="true">
<listheader label="Name" width="400px"
sort="auto(employeeName)" />
<listheader label="Date of Birth" />
<listheader label="Action" />
</listhead>
<template name="model" var="p1">
<listitem>
<listcell label="@load(p1.employeeName)"
onClick="@command('openAsReadOnly')" sclass="highlightcell" />
<listcell label="@load(p1.dateOfBirth) @converter('component.MyDateFormatConverter')" />
<listcell>
<hbox spacing="20px">
<image sclass="fimageDelete" />
<image sclass="fimageedit"
onClick="@command('editThisEmployee')" />
</hbox>
</listcell>
</listitem>
</template>
</listbox>
</window>
</zk>





EmployeeCRUD.zul

<zk>
<window id="win" title="Employee" width="520px" height="220px"
border="normal" minimizable="false" mode="modal" maximizable="false"
closable="true" action="show: slideDown;hide: slideUp"
apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('domainVMS.EmployeeCRUDVM')">
<separator />
<label value="Employee information" />
<separator />
<panel width="100%">
<panelchildren>
<separator />
<grid width="99.5%">
<columns>
<column label="" width="150px" />
<column label="" />
</columns>
<rows>
<row>
<hbox>
<label value="Name" />
<label value="*" />
</hbox>
<textbox name="name"
readonly="@load(vm.makeAsReadOnly)"
value="@bind(vm.selectedEmployee.employeeName)" cols="50" />
</row>
<row>
<hbox>
<label value="DOB" />
<label value="*" />
</hbox>
<fdatebox id="txtDOB" name="txtDOB"
readonly="@load(vm.makeAsReadOnly)"
value="@bind(vm.selectedEmployee.dateOfBirth) @converter('component.MyDateFormatConverter')" />
</row>
</rows>
</grid>
</panelchildren>
</panel>
<separator />
<div align="center">
<button id="submit" label="Submit"
onClick="@command('save')" visible="@load(not vm.makeAsReadOnly)" />
<button id="cancel"
label="@load(vm.makeAsReadOnly ?'Ok':'Cancel')"
onClick="@command('closeThis')" />
</div>
</window>
</zk>




my-addon.xml

<?xml version="1.0" encoding="UTF-8"?>
<language-addon>
<addon-name>anyname</addon-name>
<language-name>xul/html</language-name>

<javascript src="/js/jquery.maskedinput-1.3.js" />
<javascript src="/js/watermarkinput.js" />

<component>
<component-name>fdatebox</component-name>
<component-class>component.Datebox
</component-class>
<extends>textbox</extends>
</component>


</language-addon>

 

zk.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--
Created by ZK Studio
-->

<zk>
<device-config>
<device-type>ajax</device-type>
<timeout-uri>/timeout.zul</timeout-uri><!-- An empty URL can cause the browser to reload the same URL -->
</device-config>

<language-config>
<addon-uri>/my-addon.xml</addon-uri>
</language-config>


</zk>




Now you can run EmployeeList.zul  file
Output:

image

image


You can download the source code here.


 





 

Read More
Posted in ZK extended Components | No comments

Tuesday, 10 July 2012

Tech Links

Posted on 01:04 by Unknown

Hibernate

  • Hibernate validator perform validation using general Utility Class

Spring Security

  • Spring Security Part 1 – Simple Login application with database
  • quick-spring-security tutorial in eclipse step by step

Spring  + Hibernate + JPA + Entity Manager

  • Integrate with spring and JPA and ZK
  • JPA basic example with EntityManager , Spring and Maven
  • Step by step configuration of Spring , Hibernate and JPA
  • http://www.springbyexample.org/examples/one-to-many-jpa-hibernate-config-reference.html

Spring Service and DAO Layer

  • Developing A Simple Java Application With Spring using Service and DAO Layers
  • http://www.mkyong.com/spring/maven-spring-hibernate-annotation-mysql-example/
  • http://vrtoonjava.wordpress.com/2012/06/17/part-3-dao-and-service-layer/
  • http://www.techferry.com/articles/spring-annotations.html

 

HibernateTemplate or EntityManager

  • http://forum.springsource.org/showthread.php?73629-EntityManager-versus-getHibernateTemplate()
  • http://blog.michaelscepaniak.com/differences-between-hibernate-and-jpa
  • http://blog.springsource.com/2007/06/26/so-should-you-still-use-springs-hibernatetemplate-andor-jpatemplate/
  • http://www.coderanch.com/t/442507/oa/EntityManager-getHibernateTemplate
  • http://stackoverflow.com/questions/12555055/jpas-entitymanager-or-hibernates-hibernatetemplate-with-spring
  • http://www.baeldung.com/2011/12/13/the-persistence-layer-with-spring-3-1-and-jpa/

Generic DAO

  • http://www.bejug.org/confluenceBeJUG/display/BeJUG/Generic+DAO+example
  • http://hop2croft.wordpress.com/2011/06/23/dont-repeat-the-dao-no-repitas-el-dao/
  • http://www.codeproject.com/Articles/251166/The-Generic-DAO-pattern-in-Java-with-Spring-3-and
  • http://www.ibm.com/developerworks/java/library/j-genericdao/index.html

 

Spring and Hibernate ORM Framework Integration.
1.
http://www.javabeat.net/2007/10/integrating-spring-framework-with-hibernate-orm-framework/
2. http://static.springsource.org/spring/docs/2.5.x/reference/orm.html
3. http://blog.springsource.org/2012/04/06/migrating-to-spring-3-1-and-hibernate-4-1/
4. http://javaprogrammingtips4u.blogspot.in/2010/04/spring-integration-with-hibernate_23.html

Read More
Posted in Tech Links | No comments

Friday, 6 July 2012

ZK Hibernate one to one annotation mapping bidirectional CRUD example using MVVM

Posted on 10:36 by Unknown

In this post, we will see how we can implement hibernate one to one mapping bidirectional using ZK Components

In bi-directional mapping, the parent table can be retrieved by the child table and the child table can be retrieved by the parent table. Means retrieval can be done in both direction or bi-directional. In this example, we have two tables caller persona and users. We will create CRUD operation for users which also takes care of inserting record in the person tabke.

ZK Version 6
Project Name : HibernateOneToOneMap
Project Structure

image

Step 1:  ZK + Hibernate Setup
Please
follow this post to setup the Project and related jar files needed for this example

Mysql

image

CREATE  TABLE IF NOT EXISTS `sampledb`.`person` (
  `ID` BIGINT(20) NOT NULL AUTO_INCREMENT ,
  `FirstName` VARCHAR(100) NULL DEFAULT NULL ,
  `LastName` VARCHAR(100) NULL DEFAULT NULL ,
  `Email` VARCHAR(100) NULL DEFAULT NULL ,
  PRIMARY KEY (`ID`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1

CREATE  TABLE IF NOT EXISTS `sampledb`.`userlogin` (
  `ID` BIGINT(20) NOT NULL AUTO_INCREMENT ,
  `LoginID` VARCHAR(100) NULL DEFAULT NULL ,
  `Password` VARCHAR(100) NULL DEFAULT NULL ,
  `PersonID` BIGINT(20) NULL DEFAULT NULL ,
  PRIMARY KEY (`ID`) ,
  INDEX `FK_userlogin` (`PersonID` ASC) ,
  CONSTRAINT `FK_userlogin`
    FOREIGN KEY (`PersonID` )
    REFERENCES `sampledb`.`person` (`ID` ))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1

person.java

package domain;

import javax.persistence.Column;
import javax.persistence.OneToOne;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;


@Entity
@Table(name = "person")
public class person {

@Id
@GeneratedValue
private int ID;

@Column(name = "FirstName")
private String FirstName;

@Column(name = "LastName")
private String LastName;

@Column(name = "Email")
private String Email;

@OneToOne(mappedBy = "person")
@Cascade(CascadeType.ALL)
private userlogin userlogin;


public userlogin getUserlogin() {
return userlogin;
}

public void setUserlogin(userlogin userlogin) {
this.userlogin = userlogin;
}

public int getID() {
return ID;
}

public void setID(int iD) {
ID = iD;
}

public String getFirstName() {
return FirstName;
}

public void setFirstName(String firstName) {
FirstName = firstName;
}

public String getLastName() {
return LastName;
}

public void setLastName(String lastName) {
LastName = lastName;
}

public String getEmail() {
return Email;
}

public void setEmail(String email) {
Email = email;
}

}

userlogin.java


package domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@Entity
@Table(name = "userlogin")
public class userlogin implements Serializable, Cloneable {

@Id
@GeneratedValue
private int ID;

@Column(name = "LoginID")
private String LoginID;

@Column(name = "Password")
private String Password;


@OneToOne(targetEntity = person.class)
@Cascade(CascadeType.ALL)
@JoinColumn(name = "personid")
private person person;


public person getPerson() {
return person;
}

public void setPerson(person person) {
this.person = person;
}

public int getID() {
return ID;
}

public void setID(int iD) {
ID = iD;
}

public String getLoginID() {
return LoginID;
}

public void setLoginID(String loginID) {
LoginID = loginID;
}

public String getPassword() {
return Password;
}

public void setPassword(String password) {
Password = password;
}




public Object clone() throws CloneNotSupportedException {
/*
* Employee copyObj = new Employee();
* copyObj.setDesignation(this.designation); copyObj.setName(this.name);
* return copyObj;
*/
return super.clone();
}

}

HibernateUtil.java

package HibernateUtilities;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {

private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static Configuration getInitConfiguration() {
Configuration config = new Configuration();
config.configure();
return config;
}

public static Session getSession() {
if (factory == null) {
Configuration config = HibernateUtil.getInitConfiguration();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
config.getProperties()).buildServiceRegistry();
factory = config.buildSessionFactory(serviceRegistry);
}
Session hibernateSession = factory.getCurrentSession();
return hibernateSession;
}

public static Session beginTransaction() {
Session hibernateSession;
hibernateSession = HibernateUtil.getSession();
hibernateSession.beginTransaction();
return hibernateSession;
}

public static void CommitTransaction() {
HibernateUtil.getSession().getTransaction().commit();
}

public static void closeSession() {
HibernateUtil.getSession().close();
}

public static void rollbackTransaction() {
HibernateUtil.getSession().getTransaction().rollback();
}

}

 

hibernate.cfg.xml



<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/sampledb</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>

<!-- Mapping Classes -->
<mapping class="domain.person" />
<mapping class="domain.userlogin" />

</session-factory>
</hibernate-configuration>



UserCRUDVM.java


package domainVM;

import java.util.HashMap;
import java.util.Map;

import domain.person;
import domain.userlogin;

import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.ExecutionArgParam;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Window;

import DAO.userDAO;

public class UserCRUDVM {

private userlogin selectedItem;
private userlogin selectedItemOrg;
private boolean makeAsReadOnly;

@Wire("#win")
private Window win;

public boolean isMakeAsReadOnly() {
return makeAsReadOnly;
}

public void setMakeAsReadOnly(boolean makeAsReadOnly) {
this.makeAsReadOnly = makeAsReadOnly;
}


public userlogin getSelectedItem() {
return selectedItem;
}

public void setSelectedItem(userlogin s1) {
this.selectedItem = s1;
}

@Init
@NotifyChange("selectedItem")
public void initSetup(@ContextParam(ContextType.VIEW) Component view,
@ExecutionArgParam("selectedItem") userlogin s1,
@ExecutionArgParam("recordMode") String recordMode)
throws CloneNotSupportedException {
Selectors.wireComponents(view, this, false);


if (recordMode == "NEW") {
this.selectedItem = new userlogin();
this.selectedItemOrg = new userlogin();
this.selectedItem.setPerson(new person());
}

if (recordMode == "EDIT") {
this.selectedItemOrg = s1;
this.selectedItem = (userlogin) s1.clone();
}

if (recordMode == "READ") {
this.selectedItemOrg = s1;
this.selectedItem = (userlogin) s1.clone();
setMakeAsReadOnly(true);
win.setTitle(win.getTitle() + " (Readonly)");
}

}

@Command
public void save() {

// userlogin u1 = new userlogin();
// u1.setLoginID("sen4");
// u1.setPassword("sen4");
//
// person p1 = new person();
// p1.setEmail("senth4il@mail.com");
// p1.setFirstName("sen4thil");
// p1.setLastName("muth4iah");
// u1.setPerson(p1);
new userDAO().saveOrUpdate(this.selectedItem );
Map args = new HashMap();
args.put("newadded", this.selectedItem);
BindUtils.postGlobalCommand(null, null, "refreshList", args);
win.detach();
}
@Command
public void closeThis() {
win.detach();
}
}

userVM.java

package domainVM;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import DAO.userDAO;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.GlobalCommand;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Executions;

import domain.userlogin;

public class userVM {

private List<userlogin> users = null;
private userlogin selectedItem;

public userlogin getSelectedItem() {
return selectedItem;
}

public void setSelectedItem(userlogin selectedItem) {
this.selectedItem = selectedItem;
}

public List<userlogin> getallUsers() {
if (users == null) {
users = new ArrayList<userlogin>();
users = new userDAO().getAllUsersFromDB();
}
return users;
}

@Command
public void addNewUser() {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("selectedItem", null);
map.put("recordMode", "NEW");
Executions.createComponents("AddUser.zul", null, map);
}

@Command
@NotifyChange("selectedItem")
public void editThisUser() {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("recordMode", "EDIT");
map.put("selectedItem", this.selectedItem);
Executions.createComponents("AddUser.zul", null, map);
}

@Command
public void openAsReadOnly() {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("recordMode", "READ");
map.put("selectedItem", this.selectedItem);
Executions.createComponents("AddUser.zul", null, map);
}

@GlobalCommand
@NotifyChange("allUsers")
public void refreshList(@BindingParam("newadded") userlogin p1) {
users = null;
}
}







demo.zul

<?page title="Listitem MVVM Demo with Hibernate" contentType="text/html;charset=UTF-8"?>
<zk>

<style>

/* Start: Action Images- Edit
---------------------------------------------- */

.fimageedit { width: 25px; background-image:
url('./images/icon-edit.png'); background-repeat: no-repeat;
border: 0 none; cursor: pointer; }

/* End: Action Images - Edit
---------------------------------------------- */


/* Start: Action Images- Delete
---------------------------------------------- */

.fimageDelete { width: 25px; background-image:
url('./images/icon-trash-red.png'); background-repeat:
no-repeat; border: 0 none; cursor: pointer; }

/* End: Action Images - Delete
---------------------------------------------- */
.z-listcell.highlightcell .z-listcell-cnt,
.z-label.highlightcell { color:blue; cursor: pointer; }


</style>

<window title="Hibernate one to one Mapping bidirectional "
border="normal" apply="org.zkoss.bind.BindComposer"
viewModel="@id('myvm') @init('domainVM.userVM')">
<div>
<button label="Add User" onClick="@command('addNewUser')" />
</div>
<separator />

<listbox id="test" selectedItem="@bind(myvm.selectedItem)"
model="@load(myvm.allUsers)">
<listhead sizable="true">
<listheader label="Login ID" width="200px" />
<listheader label="Password" width="200px" />
<listheader label="First Name" width="200px" />
<listheader label="Last Name" width="285px" />
<listheader label="email" width="285px" />
<listheader label="Action" />
</listhead>
<template name="model" var="p1">
<listitem>
<listcell label="@load(p1.loginID)" />
<listcell label="@load(p1.password)" />
<listcell label="@load(p1.person.firstName)" />
<listcell label="@load(p1.person.lastName)" />
<listcell label="@load(p1.person.email)" />
<listcell>
<hbox spacing="20px">
<image sclass="fimageDelete" />
<image sclass="fimageedit"
onClick="@command('editThisUser')" />
</hbox>
</listcell>
</listitem>
</template>
</listbox>
</window>
</zk>


AddUser.zul

<zk>
<window id="win" title="User" width="520px" height="280px"
border="normal" minimizable="false" mode="modal" maximizable="false"
closable="true" action="show: slideDown;hide: slideUp"
apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('domainVM.UserCRUDVM')">
<separator />
<label value="User information" />
<separator />
<panel width="100%">
<panelchildren>
<separator />
<grid width="99.5%">
<columns>
<column label="" width="150px" />
<column label="" />
</columns>
<rows>
<row>
<hbox>
<label value="Login" />
<label value="*" />
</hbox>
<textbox name="Login ID" cols="50"
value="@bind(vm.selectedItem.loginID)" />
</row>
<row>
<hbox>
<label value="Password" />
<label value="*" />
</hbox>
<textbox name="Password" cols="50"
value="@bind(vm.selectedItem.password)" />
</row>

<row>
<hbox>
<label value="First Name" />
<label value="*" />
</hbox>
<textbox name="firstName" cols="50"
value="@bind(vm.selectedItem.person.firstName)" />
</row>
<row>
<hbox>
<label value="Last Name" />
<label value="*" />
</hbox>
<textbox name="firstName" cols="50"
value="@bind(vm.selectedItem.person.lastName)" />
</row>
<row>
<hbox>
<label value="email" />
<label value="*" />
</hbox>
<textbox name="email" cols="50"
value="@bind(vm.selectedItem.person.email)" />
</row>
</rows>
</grid>
</panelchildren>
</panel>
<separator />
<div align="center">
<button id="submit" label="Submit"
onClick="@command('save')" />
<button id="cancel" label="Cancel"
onClick="@command('closeThis')" />
</div>
</window>
</zk>



Now you can run demo.zul and add/edit the users

You can download source here


 

Read More
Posted in ZK Hibernate | No comments

ZK Component extend

Posted on 09:28 by Unknown

In this post, we will see how we can create our component by extending ZK Component. All the jquery plugin can be used in ZK. The following example will explain how to create Phonebox, Zip Code and Tax ID.

For your further reference, you can see the following http://www.zkoss.org/zkdemo/effects/form_effect
You can download the jquery plugin from http://digitalbush.com/projects/masked-input-plugin/

ZK Version 6
Project Name : MyComponents
Project Structure:

image

Download the jquery plugin and Add in webcontent/js folder.

Here is the source for other files

Demo.jul

<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
<window id="myWin" title="new page title" border="normal" >
<label value="Phone :" />
<phonebox id="phone" width='150px' />
<label value="Extension :" />
<Extension id="txtPhoneExt" />
<label value="zipCode :" />
<ZipCode id="txtZipCode" />
<label value="Tax ID:" />
<EIN id="txtEIN" />
<label value="Alpha Numeric :" />
<AlphaNumeric />
</window>
</zk>


AlphaNumeric.java


package components;

import org.zkoss.zul.Textbox;

public class AlphaNumeric extends Textbox {
private static final long serialVersionUID = 1L;

public AlphaNumeric() {
setWidgetListener("onBind", "jq(this).mask('******');");
}
}


EIN.java

package components;
import org.zkoss.zul.Textbox;

public class EIN extends Textbox {
private static final long serialVersionUID = 1L;
public EIN() {
setWidgetListener("onBind", "jq(this).mask('99-9999999');");
}
}

Extension.java

package components;

import org.zkoss.zul.Textbox;

public class Extension extends Textbox {
private static final long serialVersionUID = 1L;

public Extension() {
setWidgetListener("onBind", "jq(this).mask('99999');");
}
}

NPI.java

package components;

import org.zkoss.zul.Textbox;

public class NPI extends Textbox {
private static final long serialVersionUID = 1L;
public NPI() {
setWidgetListener("onBind", "jq(this).mask('9999999999');");
}
}

Phonebox.java

package components;
import org.zkoss.zul.Textbox;

public class Phonebox extends Textbox {
private static final long serialVersionUID = 1L;
public Phonebox() {
setWidgetListener("onBind", "jq(this).mask('(999) 999-9999');");
}
}

ZipCode.java

package components;

import org.zkoss.zul.Textbox;

public class ZipCode extends Textbox {
private static final long serialVersionUID = 1L;

public ZipCode() {
setWidgetListener("onBind", "jq(this).mask('99999-9999');");
}
}


In the webcontent folder, create a file in the name of my-addon.xml (you can keep any file name)


<?xml version="1.0" encoding="UTF-8"?>
<language-addon>
<addon-name>ecosmos</addon-name>
<language-name>xul/html</language-name>

<component>
<component-name>phonebox</component-name>
<component-class>components.Phonebox
</component-class>
<extends>textbox</extends>
</component>

<component>
<component-name>EIN</component-name>
<component-class>components.EIN</component-class>
<extends>textbox</extends>
</component>

<component>
<component-name>NPI</component-name>
<component-class>components.NPI</component-class>
<extends>textbox</extends>
</component>

<component>
<component-name>Extension</component-name>
<component-class>components.Extension
</component-class>
<extends>textbox</extends>
</component>


<component>
<component-name>ZipCode</component-name>
<component-class>components.ZipCode
</component-class>
<extends>textbox</extends>
</component>

<component>
<component-name>AlphaNumeric</component-name>
<component-class>components.AlphaNumeric
</component-class>
<extends>textbox</extends>
</component>





<addon-name>my.extension</addon-name><!-- any name you like -->
<javascript src="js/jquery.maskedinput-1.3.js" /> <!-- assume you package it as /myjs/foo.js -->

</language-addon>


And in the ZK.Xml , add the reference for the above file as follows


<?xml version="1.0" encoding="UTF-8"?>

<!-- Created by ZK Studio -->

<zk>
<device-config>
<device-type>ajax</device-type>
<timeout-uri>/timeout.zul</timeout-uri><!-- An empty URL can cause the
browser to reload the same URL -->
</device-config>


<language-config>
<addon-uri>/WEB-INF/my-addon.xml</addon-uri>
</language-config>

</zk>


Now you can run the demo.zul and check the output


image


You can download source here

Read More
Posted in ZK extended Components | No comments
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)

Popular Posts

  • ZK Example for inline Editing with Add New and Delete
    I am quite impressed on this demo from ZK . But adding new record and delete existing record is missing as part of typical CRUD. So i thoug...
  • EDI 5010 Documentation 837 Professional - Loop 2010BB Payer Name
    2010BB Payer Name          In this loop, all the information will be taken from Insurance master screen. Take a look of our sample screen...
  • EDI 5010 Documentation–837 - BHT - Beginning of Hierarchical Transaction
    BHT – Beginning of Hierarchical Transaction Loop Seg ID Segment Name Format Length Ref# Req Value   BHT Beginning of Hier...
  • Hibernate Validator Example 2
    In this example, we will see some more validation constraints such as @email, @past, @length, etc. And also we will also define custom error...
  • ZK Passing Parameter between two files using MVVM–Part 1
    Overview This is the first series of articles about Passing parameter between two zul files using MVVM Design pattern .This article will fo...
  • MVVM Command annotation and Notify change example
    Here is an example, how to pass parameter on a zul through MVVM Command binding annotation. ZK URL http://books.zkoss.org/wiki/ZK%20Develo...
  • History of Present Illness
    HPI - One of the main component of Clinical History. What is an HPI ? The history of present illness (HPI) is a chronological description...
  • Patient Demographics
    Patient browse (search) is the key element for any EMR / PMS Software. In my past 15 years experience, i involved more than 5 times in desig...
  • ViewModel Class Java Annotation @Init, @NotifyChange, @Command
    In following sections we'll list all syntaxes that can be used in implementing a ViewModel and applying ZK bind annotation. The ZK binde...
  • Good Website Design Links
    Form Design Label Placement in Forms International Address Fields in Web Forms 40 Eye-Catching Registration Pages blog-comment-form-...

Categories

  • Billing Process
  • C Workbook
  • C++ Workbook
  • Eclipse Tips
  • EDI 5010
  • EMR Appointment Features
  • EMR Labs Stuff
  • EMR PMS Links
  • EMR Use cases
  • EMR Vital Sign
  • Good Website Design
  • Hibernate Criteria Queries
  • Hibernate Introduction
  • Hibernate Introduction Setup
  • Hibernate Mapping
  • Hibernate POC
  • Hibernate Validator
  • Hibernate–Java Environment setup
  • HPI
  • Java
  • Maven
  • MU Certification
  • NPI
  • PQRS
  • Practice Management System
  • Spring Security
  • Tech Links
  • Today Tech Stuff
  • zk
  • ZK Hibernate
  • ZK 5 Databinding
  • ZK Application
  • ZK Calling Another ZUL
  • ZK CheckBox
  • ZK CreateComponents
  • ZK CSS
  • ZK extended Components
  • ZK Foreach
  • ZK Forum Posts
  • ZK Framework
  • ZK Hibernate Setup
  • ZK ID Space
  • ZK Include
  • ZK Installation
  • ZK iReport
  • ZK Layout
  • ZK Listitem Pagination
  • ZK Message Box
  • ZK MVC
  • ZK MVC Combox Box
  • ZK MVC CRUD Examples
  • ZK MVC Listbox
  • ZK MVVM
  • ZK MVVM Combo
  • ZK MVVM CRUD
  • ZK MVVM ListBox
  • ZK Spring
  • ZK TextBox

Blog Archive

  • ►  2013 (105)
    • ►  December (3)
    • ►  September (7)
    • ►  August (13)
    • ►  July (1)
    • ►  June (11)
    • ►  May (3)
    • ►  April (14)
    • ►  March (19)
    • ►  February (21)
    • ►  January (13)
  • ▼  2012 (177)
    • ►  December (1)
    • ►  November (13)
    • ►  October (19)
    • ►  September (24)
    • ►  August (26)
    • ▼  July (6)
      • My date box Component
      • Tech Links
      • ZK Hibernate one to one annotation mapping bidirec...
      • ZK Component extend
      • ZK Messagebox Styling
      • EDI 5010 Documentation 837 Professional - Loop 230...
    • ►  June (37)
    • ►  May (30)
    • ►  April (16)
    • ►  March (1)
    • ►  January (4)
  • ►  2011 (5)
    • ►  December (1)
    • ►  November (1)
    • ►  July (1)
    • ►  June (1)
    • ►  April (1)
  • ►  2010 (1)
    • ►  September (1)
Powered by Blogger.

About Me

Unknown
View my complete profile