Thursday, 11 April 2013

ZK MVVM Form Binding CRUD with Spring and Hibernate - Part 8

ZK Theme customization for each user.

        


Well, now we can create users and login using the newly created users. How about changing the look and feel for each user ?.
Yes this can be done using “Packaging Themes Inside Folders in ZK 6.5.2”

ZK Reference
1. Packaging Themes Inside Folders in ZK 6.5.2
2. Providing Theme Resources
3. Switch different themes dynamically

So what we are going to do now ?
1. For each user, we will ask what is their preferred theme while creating their information. In this example, I am going to have 5 different of colors such as red,blue,green,purple and brown.
2. After user is created and set their preferred theme, then after user is logged in, then we will change the theme.

Let’s start.

Step 1:
First let us organize our images folder. As per the previous article, the images folder structure as shown.
[image%255B20%255D.png]

You can see, we have been using low_bkg.gif, side_bkg.gif, side_mid.gif, side_top.gif,top_bkg.gif. All these images are in blue color. So we should have the same set of images with green, purple, brown and red. Where we can get this images. Either you can get from the source provided at the bottom or you can get it from here.

Now let us change our images folder structure such as each color will have folder and the folder have the corresponding images as shown.
image

Step 2:
Next we will modify our CSS Folder. As per previous article, the CSS Folder will look as follows
image
If you look the code on the above css file, you can observe that style.css does not contain any color related CSS Property. But the themestyle.css contains all color (blue) related property.

So we have already have the blue color css ? what about for other colors such as purple, red, brown and green. Well, just take a copy of the themestyle.css and paste 4 times and change to corresponding color. Finally rename the themeStyle.css to blueTheme.css. So the modified structure will look as follows
image
You can get the code from the source provided at the bottom of this post. Finally, modify the zkAddon.xml as follows

<?xml version="1.0" encoding="UTF-8"?>
<language-addon>
<addon-name>myaddon</addon-name>
<language-name>xul/html</language-name>
<stylesheet href="/css/login.css" type="text/css" />
<stylesheet href="/css/style.css" type="text/css" />
<stylesheet href="/css/blueTheme.css" type="text/css" />

</language-addon>

At the bottom of each file, we have three css classes such as .theme, .theme:hover and .theme:active. Even though class names are same, but the background color is different. We will use this class for our buttons.

Step 3:
In the UserCRUD.zul and userList.zul, change the button sclass from “mybutton button blue small” to “mybutton button theme small”.

Step 4:
Next we will create all 5 theme using folder structure. For zk documentation, please refer here. Follow the steps to create theme folders.

1. Download ZK 6.5.2 CE Bin Zip file
2. Create a folder zk_jars in your drive. For example c:\zk_jars.
3. Extract all the files from zk-bin-6.5.2\zk-bin-6.5.2\dist\lib  and copy to c:\zk_jars
4. Download the ztx.bat and copy in c:\zk_jars.
5. In the command line, goto to the folder c:\zk_jars and run the command ztx.bat C:\zk_jars bluetheme
6. Now, ztx batch file will create a jar file in the name of bluetheme.jar
7. Extract the bluetheme.jar and will contain two root folders such as js and zul.
7. Now come to eclipse and under the webapp folder , create a folder called “theme”.
8. In the theme folder, copy the bluetheme folder.
9. Similarly, create 4 more jars in the name of browntheme, greentheme, purpletheme and redtheme.
10. Now the folder structure will look as follows
image
Then, in the web.xml, include the following lines


<servlet>
    <servlet-name>dspLoader</servlet-name>
    <servlet-class>org.zkoss.web.servlet.dsp.InterpreterServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>dspLoader</servlet-name>
    <url-pattern>*.dsp</url-pattern>
</servlet-mapping>

Step 5:
Next we will add one more column in the table userprofile such as theme varchar(300) Null. We will update our domain object as follows


package zkexample.domain;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.NamedQuery;

@Entity
@Table(name = "userprofile")
@NamedQuery(name = "UserProfile.findUserByUserID", query = "SELECT usr FROM UserProfile as usr WHERE usr.userLoginID = ?")
public class UserProfile implements Serializable {

*********Other Code**************
private String theme;

*********Other Code**************

public String getTheme() {
return theme;

}


public void setTheme(String theme) {
this.theme = theme;
}

}

Step 6:
As we said in the introduction, while creating user, we will load all the theme and ask the user to set their preference. So we will add one more component next to password field such as combo box. Here is the code snipped to include combo box.


	<rows>
<row>
<vlayout>
<label value="Login ID"
sclass="flabel" />
<textbox id="loginid" hflex="1"
readonly="@load(vm.makeAsReadOnly)" mold="rounded"
value="@bind(fx.userLoginID)" />
</vlayout>
<vlayout>
<label value="Password"
sclass="flabel" />
<textbox id="password" width="80%"
readonly="@load(vm.makeAsReadOnly)" mold="rounded"
value="@bind(fx.password)" />
</vlayout>
<vlayout>
<label value="Theme"
sclass="flabel" />
<combobox model="@load(vm.themes)"
width="30%" mold="rounded"
selectedItem="@bind(fx.theme)"
value="@bind(fx.theme)" />
</vlayout>
</row>

Next we have to register the new themes and we will load all the theme in the above combo box. So we need to modify zkexample.zkoss.UserCRUDVM


package zkexample.zkoss;

import java.util.Arrays;
import java.util.HashMap;

import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.AfterCompose;
import org.zkoss.bind.annotation.BindingParam;
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.NotifyChange;
import org.zkoss.web.theme.StandardTheme.ThemeOrigin;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.Center;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.theme.Themes;

import zkexample.domain.UserProfile;
import zkexample.service.CRUDService;

public class UserCRUDVM {

private Center centerArea;

@WireVariable
private CRUDService CRUDService;

private UserProfile selectedRecord;
private String recordMode;
private boolean makeAsReadOnly;
private DataFilter dataFilter = new DataFilter();

// Available themes
private ListModel<String> _themes = null;
// Current theme name
private String currentTheme = null;

public ListModel<String> getThemes() {
return _themes;
}

public String getCurrentTheme() {
return currentTheme;
}

@NotifyChange("currentTheme")
public void setCurrentTheme(String currentTheme) {
this.currentTheme = currentTheme;
}

public DataFilter getDataFilter() {
return dataFilter;
}

public void setDataFilter(DataFilter dataFilter) {
this.dataFilter = dataFilter;
}

public UserProfile getSelectedRecord() {
return selectedRecord;
}

public void setSelectedRecord(UserProfile selectedRecord) {
this.selectedRecord = selectedRecord;
}

public String getRecordMode() {
return recordMode;
}

public void setRecordMode(String recordMode) {
this.recordMode = recordMode;
}

public boolean isMakeAsReadOnly() {
return makeAsReadOnly;
}

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

@AfterCompose
public void initSetup(@ContextParam(ContextType.VIEW) Component view,
@ExecutionArgParam("selectedRecord") UserProfile userProfile,
@ExecutionArgParam("recordMode") String recordMode,
@ExecutionArgParam("centerArea") Center centerArea) {

Selectors.wireComponents(view, this, false);
setRecordMode(recordMode);
CRUDService = (CRUDService) SpringUtil.getBean("CRUDService");
this.centerArea = centerArea;

Themes.register("bluetheme", ThemeOrigin.FOLDER);
Themes.register("greentheme", ThemeOrigin.FOLDER);
Themes.register("browntheme", ThemeOrigin.FOLDER);
Themes.register("purpletheme", ThemeOrigin.FOLDER);
Themes.register("redtheme", ThemeOrigin.FOLDER);

String[] themes = Themes.getThemes();
themes = Arrays.copyOf(themes, themes.length + 1);

// Attempting to switch to a theme that is not registered
// will switch to the default theme (i.e. breeze)
themes[themes.length - 1] = "unknown";
_themes = new ListModelList<String>(themes);

currentTheme = Themes.getCurrentTheme();

if (recordMode.equals("NEW")) {
this.selectedRecord = new UserProfile();
this.selectedRecord.setSystem(0);
}

if (recordMode.equals("EDIT")) {
this.selectedRecord = userProfile;
}

if (recordMode == "READ") {
setMakeAsReadOnly(true);
this.selectedRecord = userProfile;
}
}

@Command
public void saveThis(@BindingParam("action") Integer action) {
CRUDService.Save(this.selectedRecord);
if (action == 0) {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("centerArea", centerArea);
centerArea.getChildren().clear();
Executions.createComponents("userList.zul", centerArea, map);
}
if (action == 1) {
this.selectedRecord = new UserProfile();
BindUtils.postNotifyChange(null, null, UserCRUDVM.this,
"selectedRecord");

}
}

@Command
public void cancel() {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("centerArea", centerArea);
centerArea.getChildren().clear();
Executions.createComponents("userList.zul", centerArea, map);
}

}

Step 7:
Next we have inject our theme(color) css file into zk theme provider. For zk documentation, please refer here.
Create a new class called MyThemeProvider.java under the zkoss package as shown.
image



package zkexample.zkoss;

import java.util.Collection;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.util.ThemeProvider;

public class MyThemeProvider implements ThemeProvider {

public Collection<Object> getThemeURIs(Execution exec, List<Object> uris) {

if ("greentheme".equals(getSkinCookie(exec))) {
uris.add("/css/greenTheme.css");
}
if ("bluetheme".equals(getSkinCookie(exec))) {
uris.add("/css/blueTheme.css");
}
if ("browntheme".equals(getSkinCookie(exec))) {
uris.add("/css/brownTheme.css");
}
if ("purpletheme".equals(getSkinCookie(exec))) {
uris.add("/css/purpleTheme.css");
}
if ("redtheme".equals(getSkinCookie(exec))) {
uris.add("/css/redTheme.css");
}

return uris;
}

public int getWCSCacheControl(Execution exec, String uri) {
return -1;
}

public String beforeWCS(Execution exec, String uri) {
return uri;
}

public String beforeWidgetCSS(Execution exec, String uri) {
return uri;
}

/** Returns the skin specified in cookie. */
private static String getSkinCookie(Execution exec) {
Cookie[] cookies = ((HttpServletRequest) exec.getNativeRequest())
.getCookies();
if (cookies != null)

for (int i = 0; i < cookies.length; i++) {

if ("zktheme".equals(cookies[i].getName()))
return cookies[i].getValue();
}
return "";
}

}

Then, you configure WEB-INF/zk.xml by adding the following lines.


<desktop-config>
<theme-provider-class>zkexample.zkoss.MyThemeProvider</theme-provider-class>
</desktop-config>

Step 8:
Next we need dynamically switch the theme after user logged in. We will do this in MainVM as follows


package zkexample.zkoss;

import java.util.HashMap;

import org.zkoss.bind.annotation.AfterCompose;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.Init;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Borderlayout;
import org.zkoss.zul.Center;
import org.zkoss.zul.theme.Themes;

public class MainVM {

@Wire("#mainlayout")
private Borderlayout borderLayout;

@WireVariable
private Session _sess;

/**
* This method will be called after host component composition has been done
* (AfterCompose)
*
* @param view
* Root Component of the ZUL File.
*/

@AfterCompose
public void initSetup(@ContextParam(ContextType.VIEW) Component view) {

if (_sess.getAttribute("theme") == null) {
Themes.setTheme(Executions.getCurrent(), FHSessionUtil.getCurrentUser().getTheme());
_sess.setAttribute("theme", 1);
Executions.sendRedirect(null);
}

final HashMap<String, Object> map = new HashMap<String, Object>();

Selectors.wireComponents(view, this, false);

/* get an instance of the searched CENTER layout area */
Center c1 = borderLayout.getCenter();

/* clear the center child */
c1.getChildren().clear();

map.put("centerArea", c1);
/* Load the left navigation menu for patient cases */
Executions.createComponents("userList.zul", c1, map);

}


}


After successful login, store the user object in the MyUserDetailsService.java as follows


FHSessionUtil.setCurrentUser(dbUser);

In the next part 9, we will fix some bugs in this project.

You can download the source from here
For online demo, click here.

Use the following user id and password to check out different theme for each user
a) For blue theme, user id : lee and password : lee.
b) For brown theme, user id : wing and password : wing
c) for Green theme, user id : dennis and password : dennis
d) For purple theme, user id : senthil and password : senthil
e) For red theme, user id : zkoss and password : zkoss


        




 

1 comment: