How to create a StatusBarController with the zk framework ?

A simple statusBarController that works with the new zk5 EventQueues mechanism.

In this article we will create a statusBar that lay in the south area from a borderlayout and access it in a pretty simple way that the zk 5.x version will give us. Exactly the new EventQueues mechanism.

The statusBar should have 5 columns for UserName, OfficeId, selectedRecordObject (That we can see which i.e. customer is selected if we change the tab from listView to detailView).

One way is to create the columns of the statusBar in a zul-template like this:

pieces of the zul-template

            .  .  .
			<south id="south" border="none" margins="1,0,0,0"
				height="20px" splittable="false" flex="true">
				<div id="divSouth">

					<grid id="statusBarGrid" fixedLayout="true"
						height="20px" width="100%">
						<columns sizable="false">

							<column label="User:" width="10%"
								style="background-color: #D6DCDE;" />

							<column id="statusBarColUser" label=""
								width="10%" style="background-color: #D6DCDE;" />

							<column label="Office-No.:" width="10%"
								style="background-color: #D6DCDE;" />

							<column id="statusBarSelectedObject"
								width="30%" style="color: blue; background-color: #D6DCDE;" />

							<column id="statusBarAppVersion"
								style="color: #FF0000; background-color: #D6DCDE;" width="20%" />

							<column id="statusBarTableSchema"
								width="20%" style="color: blue; background-color: #D6DCDE;"
								align="left" />

						</columns>
					</grid>
				</div>

			</south>
		</borderlayout>

It should looks like in this picture:

StatusBarController

StatusBarController

As before zk 5.x we can do actualizing such statusBar columns in the old way by getting the needed objects with a chain of getFellow()’s or a little smaller with autowireing the components with a GenericForwardComposer.

pieces of the old java controller code

            .  .  .
		// show the selected Customers data in the statusBar column 'statusBarSelectedObject'
		if (aCustomer != null) {
			Column aColumn = (Column) event.getPage().getFirstRoot().getFellowIfAny("statusBarSelectedObject");

			if (aColumn != null) {
				aColumn.setLabel("--> " + aCustomer.getName1() + ", " + aCustomer.getName2() + "; " + aCustomer.getZip() + "-" + aCustomer.getCity());
			}
		}

With the EventQueues mechanism ships with zk 5.x it’s easy to do such things in a more elegant way. Jump over namespaces or different controllers away. It works like a global installed listener that if once declared you can reach them from any piece in your application. For that fine way we will spend a little more time for coding the controller. In it we create a grid and the 5 localized columns. In the afterCompose() method we setup the EventQueues ‘Listeners’ for the 5 columns. Like ‘the same procedure as every year, James?’ we create all inside a window container component so we need only one line of code in the zul-template for declaring our statusBarController.

The controller code looks like this:

StatusBarCtrl.java


package de.forsthaus.webui.util;

import java.io.Serializable;

import org.apache.log4j.Logger;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.EventQueues;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Column;
import org.zkoss.zul.Columns;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Window;

/**
 * =======================================================================<br>
 * StatusBarController. <br>
 * =======================================================================<br>
 * Works with the EventQueues mechanism of zk. ALl needed components are created
 * in this class. In the zul-template declare only this controller with
 * 'apply' to a window component.<br>
 * 
 * Declaration in the zul-file:<br>
 * 
 * <pre>
 * < borderlayout >
 *   . . .
 *    < !-- STATUS BAR AREA -- >
 *    < south id="south" border="none" margins="1,0,0,0"
 * 		height="20px" splittable="false" flex="true" >
 * 	      < div id="divSouth" >
 * 
 *          < !-- The StatusBar. Comps are created in the Controller -- >
 *          < window id="winStatusBar" apply="${statusBarCtrl}"
 *                   border="none" width="100%" height="100%" />
 * 
 *        < /div >
 *    < /south >
 *  < /borderlayout >
 * </pre>
 * 
 * call in java to actualize a columns label:
 * 
 * <pre>
 * EventQueues.lookup(&quot;userNameEventQueue&quot;, EventQueues.DESKTOP, true).publish(new Event(&quot;onChangeSelectedObject&quot;, null, &quot;new Value&quot;));
 * </pre>
 * 
 * Spring bean declaration:
 * 
 * <pre>
 * < !-- StatusBarController -->
 * < bean id="statusBarCtrl" class="de.forsthaus.webui.util.StatusBarCtrl"
 *    scope="prototype">
 * < /bean>
 * </pre>
 * 
 * since: zk 5.0.0
 * 
 * @author sgerth
 * 
 */
public class StatusBarCtrl extends GenericForwardComposer implements Serializable {

	private static final long serialVersionUID = 1L;
	private transient final static Logger logger = Logger.getLogger(StatusBarCtrl.class);

	protected Window winStatusBar; // autowired

	// Used Columns
	private Column statusBarColUser;
	private Column statusBarOfficeId; 
	private Column statusBarSelectedObject;
	private Column statusBarAppVersion;
	private Column statusBarTableSchema;

	// Localized labels for the columns
	private String _labelUser = Labels.getLabel("common.User") + ": ";
	private String _labelOfficeId = Labels.getLabel("common.OfficeId") + ": ";
	private String _labelSelectedObject = Labels.getLabel("common.SelectedSign") + ": ";
	private String _labelAppVersion = Labels.getLabel("common.Version") + ": ";
	private String _labelTableSchema = Labels.getLabel("common.TableSchema") + ": ";

	/**
	 * Default constructor.
	 */
	public StatusBarCtrl() {
		super();

		if (logger.isDebugEnabled()) {
			logger.debug("--> super()");
		}
	}

	@Override
	public void doAfterCompose(Component window) throws Exception {
		super.doAfterCompose(window);

		// Listener for Username
		EventQueues.lookup("userNameEventQueue", EventQueues.DESKTOP, true).subscribe(new EventListener() {
			public void onEvent(Event event) throws Exception {
				String msg = (String) event.getData();
				statusBarColUser.setLabel(_labelUser + msg);
			}
		});

		// Listener for OfficeId
		EventQueues.lookup("officeIdEventQueue", EventQueues.DESKTOP, true).subscribe(new EventListener() {
			public void onEvent(Event event) throws Exception {
				String msg = (String) event.getData();
				statusBarOfficeId.setLabel(_labelOfficeId + msg);
			}
		});

		// Listener for selected Record
		EventQueues.lookup("selectedObjectEventQueue", EventQueues.DESKTOP, true).subscribe(new EventListener() {
			public void onEvent(Event event) throws Exception {
				String msg = (String) event.getData();
				statusBarSelectedObject.setLabel(_labelSelectedObject + msg);
			}
		});

		// Listener for applicationVersion
		EventQueues.lookup("appVersionEventQueue", EventQueues.DESKTOP, true).subscribe(new EventListener() {
			public void onEvent(Event event) throws Exception {
				String msg = (String) event.getData();
				statusBarAppVersion.setLabel(_labelAppVersion + msg);
			}
		});

		// Listener for TableSchemaName
		EventQueues.lookup("tableSchemaEventQueue", EventQueues.DESKTOP, true).subscribe(new EventListener() {
			public void onEvent(Event event) throws Exception {
				String msg = (String) event.getData();
				statusBarTableSchema.setLabel(_labelTableSchema + msg);
			}
		});

	}

	/**
	 * Automatically called method from zk.
	 * 
	 * @param event
	 */
	public void onCreate$winStatusBar(Event event) {

		Grid grid = new Grid();
		grid.setHeight("100%");
		grid.setWidth("100%");
		grid.setParent(winStatusBar);

		Columns columns = new Columns();
		columns.setSizable(false);
		columns.setParent(grid);

		statusBarColUser = new Column();
		statusBarColUser.setLabel(_labelUser);
		statusBarColUser.setWidth("10%");
		statusBarColUser.setStyle("background-color: #D6DCDE;");
		statusBarColUser.setParent(columns);

		statusBarOfficeId = new Column();
		statusBarOfficeId.setLabel(_labelOfficeId);
		statusBarOfficeId.setWidth("10%");
		statusBarOfficeId.setStyle("background-color: #D6DCDE;");
		statusBarOfficeId.setParent(columns);

		statusBarSelectedObject = new Column();
		statusBarSelectedObject.setLabel(_labelSelectedObject);
		statusBarSelectedObject.setWidth("30%");
		statusBarSelectedObject.setStyle("background-color: #D6DCDE; color: blue;");
		statusBarSelectedObject.setParent(columns);

		statusBarAppVersion = new Column();
		statusBarAppVersion.setLabel(_labelAppVersion);
		statusBarAppVersion.setWidth("20%");
		statusBarAppVersion.setStyle("background-color: #D6DCDE; color: #FF0000;");
		statusBarAppVersion.setParent(columns);

		statusBarTableSchema = new Column();
		statusBarTableSchema.setLabel(_labelTableSchema);
		statusBarTableSchema.setWidth("10%");
		statusBarTableSchema.setStyle("background-color: #D6DCDE; color: blue;");
		statusBarTableSchema.setParent(columns);

	}
}

We can now add the statusBar in our zul-template with a single line of code:

As we mentioned we would have it in the south area of our borderlayout we moved it to there. Now the pieces of the zul-file looks like this:

pieces of the zul-template

   .  .  .
		    <!-- STATUS BAR AREA -->
			<south id="south" border="none" margins="1,0,0,0"
				height="20px" splittable="false" flex="true">
				<div id="divSouth">

					<!-- The StatusBar. Comps are created in the Controller -->
					<window id="winStatusBar" apply="${statusBarCtrl}" border="none" width="100%" height="100%" />

				</div>
			</south>
		</borderlayout>
   .  .  .

At last we have a look on how we call such a ‘listener’ . Therefore we imagine we have a listbox with an onSelect() event. By selecting an listItem we call the corresponding method an get the selected Item. In our case we get it from the DataBinder so we must not casting it to the right object. The .publish() method will send the events data to the EventQueues listener and there’s the code running that we have defined in the onEvent() method. The final code looks like here:

calling the EventQueue


	public void onSelect$listBoxCustomer(Event event) {

		Customer aCustomer = getSelectedCustomer();

		if (aCustomer != null) {
	        	
         		// show the objects data in the statusBar
		        EventQueues.lookup("selectedObjectEventQueue", EventQueues.DESKTOP, true).publish(new Event("onChangeSelectedObject", null, aCustomer.getName1()));
		}
	}

Samples are hostet in the Zksample2 project on

Have fun with it.

Stephan Gerth

Dipl.rer.pol.


PS: Help to prevent the global warming by writing cool software

How to customize a spring-security form-login. Part 4

An article from my zk integration series.

part 1
part 2
part 3
part 5

AuthenticationSuccessHandler.java
Handles the workflow after a successful authentication. It extends from SimpleUrlAuthenticationSuccessHandler in which we can configure a default URL. There the successful authenticated users can be sent to.

AuthenticationSuccessHandler.java

public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

	private transient static final Logger logger = Logger.getLogger(MyAuthenticationSuccessHandler.class);

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

		if (logger.isDebugEnabled()) {
			logger.debug("MyAuthenticationSuccessHandler");
			logger.debug(request.getContextPath());
			logger.debug(getDefaultTargetUrl());
			logger.debug(request.getContextPath() + getDefaultTargetUrl());
			logger.debug("getPrincipal() : " + authentication.getPrincipal().toString());
			logger.debug("getName() : " + authentication.getName());
			logger.debug("getCredentials() : " + authentication.getCredentials());

			Collection<GrantedAuthority> col = authentication.getAuthorities();

			logger.debug("getAuthorities() COUNT : " + col.size());
			int i = 0;
			for (GrantedAuthority grantedAuthority : col) {
				++i;
				logger.debug("getAuthorities()" + i + " : " + grantedAuthority.getAuthority().toString());
			}
			logger.debug("isAuthenticated : " + authentication.isAuthenticated());
		}

		// redirect the user to the configured URL
		response.sendRedirect(request.getContextPath() + getDefaultTargetUrl());
	}
}

Part 5 of this article you can read here.

Samples are hostet in the Zksample2 project on

Have fun with it.

Stephan Gerth

Dipl.rer.pol.


PS: Help to prevent the global warming by writing cool software

How to customize a spring-security form-login. Part 3

An article from my zk integration series.

part 1
part 2
part 4
part 5

AbstractUserDetailsAuthenticationProvider.java
The method additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordTenantAuthenticationToken authentication) allow us additional checks for a returned UserDetails. We adapt it only to our UsernamePasswordTenantAuthenticationToken.

AbstractUserDetailsAuthenticationProvider.java

public abstract class MyAbstractUserDetailsAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
	// ~ Instance fields
	// ================================================================================================

	protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
	private UserCache userCache = new NullUserCache();
	private boolean forcePrincipalAsString = false;
	protected boolean hideUserNotFoundExceptions = true;
	private UserDetailsChecker preAuthenticationChecks = new DefaultPreAuthenticationChecks();
	private UserDetailsChecker postAuthenticationChecks = new DefaultPostAuthenticationChecks();

	// ~ Methods
	// ========================================================================================================

	/**
	 * Allows subclasses to perform any additional checks of a returned (or
	 * cached) <code>UserDetails</code> for a given authentication request.
	 * Generally a subclass will at least compare the
	 * {@link Authentication#getCredentials()} with a
	 * {@link UserDetails#getPassword()}. If custom logic is needed to compare
	 * additional properties of <code>UserDetails</code> and/or
	 * <code>UsernamePasswordAuthenticationToken</code>, these should also
	 * appear in this method.
	 * 
	 * @param userDetails
	 *            as retrieved from the
	 *            {@link #retrieveUser(String, UsernamePasswordAuthenticationToken)}
	 *            or <code>UserCache</code>
	 * @param authentication
	 *            the current request that needs to be authenticated
	 * 
	 * @throws AuthenticationException
	 *             AuthenticationException if the credentials could not be
	 *             validated (generally a <code>BadCredentialsException</code>,
	 *             an <code>AuthenticationServiceException</code>)
	 */
	protected abstract void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordTenantAuthenticationToken authentication) throws AuthenticationException;

	public final void afterPropertiesSet() throws Exception {
		Assert.notNull(this.userCache, "A user cache must be set");
		Assert.notNull(this.messages, "A message source must be set");
		doAfterPropertiesSet();
	}

	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		Assert.isInstanceOf(UsernamePasswordTenantAuthenticationToken.class, authentication, messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
				"Only UsernamePasswordTenantAuthenticationToken is supported"));

		// Determine username
		String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();

		boolean cacheWasUsed = true;
		UserDetails user = this.userCache.getUserFromCache(username);

		if (user == null) {
			cacheWasUsed = false;

			try {
				user = retrieveUser(username, (UsernamePasswordTenantAuthenticationToken) authentication);
			} catch (UsernameNotFoundException notFound) {
				if (hideUserNotFoundExceptions) {
					throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
				} else {
					throw notFound;
				}
			}

			Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
		}

		try {
			preAuthenticationChecks.check(user);
			additionalAuthenticationChecks(user, (UsernamePasswordTenantAuthenticationToken) authentication);
		} catch (AuthenticationException exception) {
			if (cacheWasUsed) {
				// There was a problem, so try again after checking
				// we're using latest data (i.e. not from the cache)
				cacheWasUsed = false;
				user = retrieveUser(username, (UsernamePasswordTenantAuthenticationToken) authentication);
				preAuthenticationChecks.check(user);
				additionalAuthenticationChecks(user, (UsernamePasswordTenantAuthenticationToken) authentication);
			} else {
				throw exception;
			}
		}

		postAuthenticationChecks.check(user);

		if (!cacheWasUsed) {
			this.userCache.putUserInCache(user);
		}

		Object principalToReturn = user;

		if (forcePrincipalAsString) {
			principalToReturn = user.getUsername();
		}

		return createSuccessAuthentication(principalToReturn, authentication, user);
	}

	/**
	 * Creates a successful {@link Authentication} object.
	 * <p>
	 * Protected so subclasses can override.
	 * </p>
	 * <p>
	 * Subclasses will usually store the original credentials the user supplied
	 * (not salted or encoded passwords) in the returned
	 * <code>Authentication</code> object.
	 * </p>
	 * 
	 * @param principal
	 *            that should be the principal in the returned object (defined
	 *            by the {@link #isForcePrincipalAsString()} method)
	 * @param authentication
	 *            that was presented to the provider for validation
	 * @param user
	 *            that was loaded by the implementation
	 * 
	 * @return the successful authentication token
	 */
	protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
		// Ensure we return the original credentials the user supplied,
		// so subsequent attempts are successful even with encoded passwords.
		// Also ensure we return the original getDetails(), so that future
		// authentication events after cache expiry contain the details

		// OLD
		// UsernamePasswordTenantAuthenticationToken result = new
		// UsernamePasswordTenantAuthenticationToken(principal,
		// authentication.getCredentials(), user.getAuthorities());
		UsernamePasswordTenantAuthenticationToken result = new UsernamePasswordTenantAuthenticationToken(principal, authentication.getCredentials(), user.getAuthorities(),
				((UsernamePasswordTenantAuthenticationToken) authentication).getTenantId());
		result.setDetails(authentication.getDetails());

		return result;
	}

	protected void doAfterPropertiesSet() throws Exception {
	}

	public UserCache getUserCache() {
		return userCache;
	}

	public boolean isForcePrincipalAsString() {
		return forcePrincipalAsString;
	}

	public boolean isHideUserNotFoundExceptions() {
		return hideUserNotFoundExceptions;
	}

	/**
	 * Allows subclasses to actually retrieve the <code>UserDetails</code> from
	 * an implementation-specific location, with the option of throwing an
	 * <code>AuthenticationException</code> immediately if the presented
	 * credentials are incorrect (this is especially useful if it is necessary
	 * to bind to a resource as the user in order to obtain or generate a
	 * <code>UserDetails</code>).
	 * <p>
	 * Subclasses are not required to perform any caching, as the
	 * <code>AbstractUserDetailsAuthenticationProvider</code> will by default
	 * cache the <code>UserDetails</code>. The caching of
	 * <code>UserDetails</code> does present additional complexity as this means
	 * subsequent requests that rely on the cache will need to still have their
	 * credentials validated, even if the correctness of credentials was assured
	 * by subclasses adopting a binding-based strategy in this method.
	 * Accordingly it is important that subclasses either disable caching (if
	 * they want to ensure that this method is the only method that is capable
	 * of authenticating a request, as no <code>UserDetails</code> will ever be
	 * cached) or ensure subclasses implement
	 * {@link #additionalAuthenticationChecks(UserDetails, UsernamePasswordAuthenticationToken)}
	 * to compare the credentials of a cached <code>UserDetails</code> with
	 * subsequent authentication requests.
	 * </p>
	 * <p>
	 * Most of the time subclasses will not perform credentials inspection in
	 * this method, instead performing it in
	 * {@link #additionalAuthenticationChecks(UserDetails, UsernamePasswordAuthenticationToken)}
	 * so that code related to credentials validation need not be duplicated
	 * across two methods.
	 * </p>
	 * 
	 * @param username
	 *            The username to retrieve
	 * @param authentication
	 *            The authentication request, which subclasses <em>may</em> need
	 *            to perform a binding-based retrieval of the
	 *            <code>UserDetails</code>
	 * 
	 * @return the user information (never <code>null</code> - instead an
	 *         exception should the thrown)
	 * 
	 * @throws AuthenticationException
	 *             if the credentials could not be validated (generally a
	 *             <code>BadCredentialsException</code>, an
	 *             <code>AuthenticationServiceException</code> or
	 *             <code>UsernameNotFoundException</code>)
	 */
	protected abstract UserDetails retrieveUser(String username, UsernamePasswordTenantAuthenticationToken authentication) throws AuthenticationException;

	public void setForcePrincipalAsString(boolean forcePrincipalAsString) {
		this.forcePrincipalAsString = forcePrincipalAsString;
	}

	/**
	 * By default the <code>AbstractUserDetailsAuthenticationProvider</code>
	 * throws a <code>BadCredentialsException</code> if a username is not found
	 * or the password is incorrect. Setting this property to <code>false</code>
	 * will cause <code>UsernameNotFoundException</code>s to be thrown instead
	 * for the former. Note this is considered less secure than throwing
	 * <code>BadCredentialsException</code> for both exceptions.
	 * 
	 * @param hideUserNotFoundExceptions
	 *            set to <code>false</code> if you wish
	 *            <code>UsernameNotFoundException</code>s to be thrown instead
	 *            of the non-specific <code>BadCredentialsException</code>
	 *            (defaults to <code>true</code>)
	 */
	public void setHideUserNotFoundExceptions(boolean hideUserNotFoundExceptions) {
		this.hideUserNotFoundExceptions = hideUserNotFoundExceptions;
	}

	public void setMessageSource(MessageSource messageSource) {
		this.messages = new MessageSourceAccessor(messageSource);
	}

	public void setUserCache(UserCache userCache) {
		this.userCache = userCache;
	}

	public boolean supports(Class<? extends Object> authentication) {
		return (UsernamePasswordTenantAuthenticationToken.class.isAssignableFrom(authentication));
	}

	protected UserDetailsChecker getPreAuthenticationChecks() {
		return preAuthenticationChecks;
	}

	/**
	 * Sets the policy will be used to verify the status of the loaded
	 * <tt>UserDetails</tt> <em>before</em> validation of the credentials takes
	 * place.
	 * 
	 * @param preAuthenticationChecks
	 *            strategy to be invoked prior to authentication.
	 */
	public void setPreAuthenticationChecks(UserDetailsChecker preAuthenticationChecks) {
		this.preAuthenticationChecks = preAuthenticationChecks;
	}

	protected UserDetailsChecker getPostAuthenticationChecks() {
		return postAuthenticationChecks;
	}

	public void setPostAuthenticationChecks(UserDetailsChecker postAuthenticationChecks) {
		this.postAuthenticationChecks = postAuthenticationChecks;
	}

	private class DefaultPreAuthenticationChecks implements UserDetailsChecker {
		public void check(UserDetails user) {
			if (!user.isAccountNonLocked()) {
				throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked"), user);
			}

			if (!user.isEnabled()) {
				throw new DisabledException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"), user);
			}

			if (!user.isAccountNonExpired()) {
				throw new AccountExpiredException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"), user);
			}
		}
	}

	private class DefaultPostAuthenticationChecks implements UserDetailsChecker {
		public void check(UserDetails user) {
			if (!user.isCredentialsNonExpired()) {
				throw new CredentialsExpiredException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired", "User credentials have expired"), user);
			}
		}
	}
}

MyDaoAuthenticationProvider.java
An implementation of an AuthenticationProvider that retrieves the user details from an UserDetailsService.

MyDaoAuthenticationProvider .java

public class MyDaoAuthenticationProvider extends MyAbstractUserDetailsAuthenticationProvider {

	// ~ Instance fields
	// ================================================================================================

	private PasswordEncoder passwordEncoder = new PlaintextPasswordEncoder();

	private SaltSource saltSource;

	private UserDetailsService userDetailsService;

	private boolean includeDetailsObject = true;

	// ~ Methods
	// ========================================================================================================

	protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordTenantAuthenticationToken authentication) throws AuthenticationException {
		Object salt = null;

		if (this.saltSource != null) {
			salt = this.saltSource.getSalt(userDetails);
		}

		if (authentication.getCredentials() == null) {
			throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), includeDetailsObject ? userDetails : null);
		}

		String presentedPassword = authentication.getCredentials().toString();

		if (!passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) {
			throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), includeDetailsObject ? userDetails : null);
		}
	}

	protected void doAfterPropertiesSet() throws Exception {
		Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");
	}

	protected final UserDetails retrieveUser(String username, UsernamePasswordTenantAuthenticationToken authentication) throws AuthenticationException {
		UserDetails loadedUser;

		try {
			loadedUser = this.getUserDetailsService().loadUserByUsername(username + "/" + authentication.getTenantId());
		} catch (DataAccessException repositoryProblem) {
			throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
		}

		if (loadedUser == null) {
			throw new AuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
		}
		return loadedUser;
	}

	/**
	 * Sets the PasswordEncoder instance to be used to encode and validate
	 * passwords. If not set, {@link PlaintextPasswordEncoder} will be used by
	 * default.
	 * 
	 * @param passwordEncoder
	 *            The passwordEncoder to use
	 */
	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	protected PasswordEncoder getPasswordEncoder() {
		return passwordEncoder;
	}

	/**
	 * The source of salts to use when decoding passwords. <code>null</code> is
	 * a valid value, meaning the <code>DaoAuthenticationProvider</code> will
	 * present <code>null</code> to the relevant <code>PasswordEncoder</code>.
	 * 
	 * @param saltSource
	 *            to use when attempting to decode passwords via the
	 *            <code>PasswordEncoder</code>
	 */
	public void setSaltSource(SaltSource saltSource) {
		this.saltSource = saltSource;
	}

	protected SaltSource getSaltSource() {
		return saltSource;
	}

	public void setUserDetailsService(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	protected UserDetailsService getUserDetailsService() {
		return userDetailsService;
	}

	protected boolean isIncludeDetailsObject() {
		return includeDetailsObject;
	}

	/**
	 * Determines whether the UserDetails will be included in the
	 * <tt>extraInformation</tt> field of a thrown BadCredentialsException.
	 * Defaults to true, but can be set to false if the exception will be used
	 * with a remoting protocol, for example.
	 * 
	 * @deprecated use
	 *             {@link org.springframework.security.authentication.ProviderManager#setClearExtraInformation(boolean)}
	 */
	public void setIncludeDetailsObject(boolean includeDetailsObject) {
		this.includeDetailsObject = includeDetailsObject;
	}
}

Part 4 of this article you can read here.

Samples are hostet in the Zksample2 project on

Have fun with it.

Stephan Gerth

Dipl.rer.pol.


PS: Help to prevent the global warming by writing cool software

How to customize a spring-security form-login. Part 2

An article from my zk integration series.

part 1
part 3
part 4
part 5

Bellow are the used main classes for a spring-security form-login:

UsernamePasswordAuthenticationToken.java:
This class is an authentication implementation that represents a simple username and password. We modifiy it for the TenantId and change the name to UsernamePasswordTenantAuthenticationToken.java

UsernamePasswordTenantAuthenticationToken.java

@SuppressWarnings("serial")
public class UsernamePasswordTenantAuthenticationToken extends AbstractAuthenticationToken {
	// ~ Instance fields
	// ================================================================================================

	private final Object credentials;
	private final Object principal;
	private final Object tenantId;

	// ~ Constructors
	// ===================================================================================================

	/**
	 * This constructor can be safely used by any code that wishes to create a
	 * <code>UsernamePasswordAuthenticationToken</code>, as the
	 * {@link #isAuthenticated()} will return <code>false</code>.
	 * 
	 */
	public UsernamePasswordTenantAuthenticationToken(Object principal, Object credentials, Object tenantId) {
		super(null);
		this.principal = principal;
		this.credentials = credentials;
		this.tenantId = tenantId;
		setAuthenticated(false);
	}

	/**
	 * @deprecated use the list of authorities version
	 */
	public UsernamePasswordTenantAuthenticationToken(Object principal, Object credentials, GrantedAuthority[] authorities) {
		this(principal, credentials, Arrays.asList(authorities));
	}

	/**
	 * This constructor should only be used by
	 * <code>AuthenticationManager</code> or <code>AuthenticationProvider</code>
	 * implementations that are satisfied with producing a trusted (i.e.
	 * {@link #isAuthenticated()} = <code>true</code>) authentication token.
	 * 
	 * @param principal
	 * @param credentials
	 * @param authorities
	 */
	public UsernamePasswordTenantAuthenticationToken(Object principal, Object credentials, Collection<GrantedAuthority> authorities, Object tenantId) {
		super(authorities);
		this.principal = principal;
		this.credentials = credentials;
		this.tenantId = tenantId;
		super.setAuthenticated(true); // must use super, as we override
	}

	// ~ Methods
	// ========================================================================================================

	public Object getCredentials() {
		return this.credentials;
	}

	public Object getPrincipal() {
		return this.principal;
	}

	public Object getTenantId() {
		return this.tenantId;
	}

	public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
		if (isAuthenticated) {
			throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
		}

		super.setAuthenticated(false);
	}
}

UserPasswordAuthenticationFilter.java
This class processes the submission of an authentication form, means our ZKLoginDialog . This filter responds per default to the /j_spring_security_check URL.

UserPasswordAuthenticationFilter.java

public class UserPasswordTenantAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

	// ~ Static fields/initializers
	// =====================================================================================

	public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "j_username";
	public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "j_password";
	public static final String SPRING_SECURITY_FORM_TENANTID_KEY = "j_tenantid";
	public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "SPRING_SECURITY_LAST_USERNAME";

	private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
	private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
	private String tenantParameter = SPRING_SECURITY_FORM_TENANTID_KEY;
	private boolean postOnly = true;

	// ~ Constructors
	// ===================================================================================================

	public UserPasswordTenantAuthenticationFilter() {
		super("/j_spring_security_check");
	}

	// ~ Methods
	// ========================================================================================================

	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
		if (postOnly && !request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}

		String username = obtainUsername(request);
		String password = obtainPassword(request);
		String tenantId = obtainTenantId(request);

		if (username == null) {
			username = "";
		}

		if (password == null) {
			password = "";
		}

		if (tenantId == null) {
			tenantId = "";
		}

		username = username.trim();
		tenantId = tenantId.trim();

		UsernamePasswordTenantAuthenticationToken authRequest = new UsernamePasswordTenantAuthenticationToken(username, password, null, tenantId);

		// Place the last username attempted into HttpSession for views
		HttpSession session = request.getSession(false);

		if (session != null || getAllowSessionCreation()) {
			request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY, TextEscapeUtils.escapeEntities(username));
		}

		// Allow subclasses to set the "details" property
		setDetails(request, authRequest);

		return this.getAuthenticationManager().authenticate(authRequest);
	}

	/**
	 * Enables subclasses to override the composition of the password, such as
	 * by including additional values and a separator.
	 * <p>
	 * This might be used for example if a postcode/zipcode was required in
	 * addition to the password. A delimiter such as a pipe (|) should be used
	 * to separate the password and extended value(s). The
	 * <code>AuthenticationDao</code> will need to generate the expected
	 * password in a corresponding manner.
	 * </p>
	 * 
	 * @param request
	 *            so that request attributes can be retrieved
	 * 
	 * @return the password that will be presented in the
	 *         <code>Authentication</code> request token to the
	 *         <code>AuthenticationManager</code>
	 */
	protected String obtainPassword(HttpServletRequest request) {
		return request.getParameter(passwordParameter);
	}

	/**
	 * Enables subclasses to override the composition of the username, such as
	 * by including additional values and a separator.
	 * 
	 * @param request
	 *            so that request attributes can be retrieved
	 * 
	 * @return the username that will be presented in the
	 *         <code>Authentication</code> request token to the
	 *         <code>AuthenticationManager</code>
	 */
	protected String obtainUsername(HttpServletRequest request) {
		return request.getParameter(usernameParameter);
	}

	/**
	 * Enables subclasses to override the composition of the tenantID, such as
	 * by including additional values and a separator.
	 * 
	 * @param request
	 *            so that request attributes can be retrieved
	 * 
	 * @return the tenantID that will be presented in the
	 *         <code>Authentication</code> request token to the
	 *         <code>AuthenticationManager</code>
	 */
	protected String obtainTenantId(HttpServletRequest request) {
		return request.getParameter(tenantParameter);
	}

	/**
	 * Provided so that subclasses may configure what is put into the
	 * authentication request's details property.
	 * 
	 * @param request
	 *            that an authentication request is being created for
	 * @param authRequest
	 *            the authentication request object that should have its details
	 *            set
	 */
	protected void setDetails(HttpServletRequest request, UsernamePasswordTenantAuthenticationToken authRequest) {
		authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
	}

	/**
	 * Sets the parameter name which will be used to obtain the username from
	 * the login request.
	 * 
	 * @param usernameParameter
	 *            the parameter name. Defaults to "j_username".
	 */
	public void setUsernameParameter(String usernameParameter) {
		Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
		this.usernameParameter = usernameParameter;
	}

	/**
	 * Sets the parameter name which will be used to obtain the password from
	 * the login request..
	 * 
	 * @param passwordParameter
	 *            the parameter name. Defaults to "j_password".
	 */
	public void setPasswordParameter(String passwordParameter) {
		Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
		this.passwordParameter = passwordParameter;
	}

	/**
	 * Sets the parameter name which will be used to obtain the password from
	 * the login request..
	 * 
	 * @param passwordParameter
	 *            the parameter name. Defaults to "j_password".
	 */
	public void setTenantIdParameter(String tenantParameter) {
		Assert.hasText(tenantParameter, "Tenant ID parameter must not be empty or null");
		this.tenantParameter = tenantParameter;
	}

	/**
	 * Defines whether only HTTP POST requests will be allowed by this filter.
	 * If set to true, and an authentication request is received which is not a
	 * POST request, an exception will be raised immediately and authentication
	 * will not be attempted. The <tt>unsuccessfulAuthentication()</tt> method
	 * will be called as if handling a failed authentication.
	 * <p>
	 * Defaults to <tt>true</tt> but may be overridden by subclasses.
	 */
	public void setPostOnly(boolean postOnly) {
		this.postOnly = postOnly;
	}

	public final String getUsernameParameter() {
		return usernameParameter;
	}

	public final String getPasswordParameter() {
		return passwordParameter;
	}

	public final String getTenantParameter() {
		return tenantParameter;
	}
}

Part 3 of this article you can read here.

Samples are hostet in the Zksample2 project on

Have fun with it.

Stephan Gerth

Dipl.rer.pol.


PS: Help to prevent the global warming by writing cool software

How to customize a spring-security form-login. Part 1

An article from my zk integration series.

part 2
part 3
part 4
part 5

For a spring-security 3.0.2 managed project i need a third parameter in the login dialog. This third parameter should represent a tenant id for a multi-tenant application. The logic should lookup in the tenant administrations database for the used table schema name in which the tenants data are stored. Let me early say that the best practice not only for multi-tenant database applications is the way to separate completely the user/tenant and right data from the applications data. This separation is a basic necessity for high scaling applications. In doing so it’s equal if the users data are stored in a LDAP or relational database server. Mostly an LDAP server is prefered because it’s optimized for fast reading, means 1000’s of user entries in a second.

Here’s an picture on how the login dialog should looks like:

ZKLoginDialog

customized spring-security form-login dialog with zk framework

zkloginDialog.zul

<?page id="ZKLoginDialog" title="LOGIN"?>
<?taglib uri="http://www.zkoss.org/dsp/web/core" prefix="c"?>
<?variable-resolver class="org.zkoss.zkplus.spring.DelegatingVariableResolver"?>

<zk xmlns="http://www.zkoss.org/2005/zul"
	xmlns:h="http://www.w3.org/1999/xhtml"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.zkoss.org/2005/zul http://www.zkoss.org/2005/zul/zul.xsd">

	<style>
		body { padding: 0 0; /* 0 padding on top and bottom and 0
		padding on right and left */

		<!-- background image -->
		background-image:
		url(${c:encodeURL('/images/templates/test/Grey_T_R.jpg')});
		background-repeat:repeat-x; }

		<!-- cut the vertical borders in the rows -->
		tr.z-row td.z-row-inner { border-right: 0px #CCC; }

		<!-- nicer looking -->
		.z-window-modal-cnt-noborder {background: none}
		.z-window-modal-cl-noborder {background: none}

		.outerGroupBox .z-groupbox-cnt {padding: 0px;}

		<!-- Make Plain Grid -->
		.GridLayoutNoBorder tr.z-row td.z-row-inner, tr.z-row
		.z-cell,div.z-grid { border: none; overflow: hidden; zoom: 1;
		background: white; border-top: none; border-left: none;
		border-right: none; border-bottom: none; }
	</style>

	<window id="loginwin" border="none" width="390px"
		apply="de.forsthaus.webui.login.ZkLoginDialogCtrl">

		<groupbox mold="3d" closable="false" sclass="outerGroupBox"
			contentStyle="background-color : white">
			<caption label="Login" image="/images/earth2.gif"
				style="font-weight: bold;">

				<button id="button_ZKLoginDialog_Close"
					image="/images/icons/stop.gif"
					tooltiptext="${c:l('button_ZKLoginDialog_Close.tooltiptext')}" />
			</caption>

			<columnlayout
				style="background-image:url(${c:encodeURL('/images/login_151x222.jpg')}); ">
				<columnchildren width="30%" />

				<columnchildren width="70%">
					<panel border="none">
						<panelchildren>
							<separator />
							<groupbox
								if="${not empty param.login_error}">
								<label style="color:red"
									value="Login failed. Please try again." />
								<h:br />
								<label style="color:red"
									value="Reason: ${sessionScope.SPRING_SECURITY_LAST_EXCEPTION.message}" />
								<h:br />
							</groupbox>

							<groupbox
								style="padding-top: 5px; padding-left: 5px; ">
								<caption label="Login" />

								<div>
									<!-- ### Spring Security action-url = j_spring_security_check  ### -->
									<h:form id="f" name="f"
										action="j_spring_security_check" method="POST">

										<grid fixedLayout="true"
											sclass="GridLayoutNoBorder" style="border:0px">
											<columns>
												<column width="40%" />
												<column width="60%" />
											</columns>
											<rows>

												<!-- TenantID -->
												<row>
													<label
														id="label_ZKLoginDialog_tenant"
														value="${c:l('label_ZKLoginDialogTenant')}" />
													<textbox
														id="txtb_TenantId" name="j_tenantid" width="98%" />
												</row>

												<!-- Username -->
												<row>
													<label
														id="label_ZKLoginDialog_user"
														value="${c:l('label_ZKLoginDialogUser')}" />
													<textbox
														id="txtb_Username" name="j_username" width="98%" />
												</row>

												<!-- Password -->
												<row>
													<label
														id="label_ZKLoginDialog_pwd"
														value="${c:l('label_ZKLoginDialogPwd')}" />
													<textbox
														id="txtb_Password" type="password" name="j_password"
														width="98%" />
												</row>

												<row spans="2">
													<hbox>
														<h:input
															type="submit" value="Login" />
														<!-- 
															<button id="btnReset" 
															height="22px" label="Reset" />
														-->
													</hbox>
												</row>
											</rows>
										</grid>
									</h:form>
								</div>

							</groupbox>

						</panelchildren>
					</panel>
				</columnchildren>
			</columnlayout>

		</groupbox>

	</window>
</zk>

The interesting part of this file are the three variable names: j_tenantid, j_username, j_password . These are submitting to the server when pressing the OK button .

  • ZKLoginDialogCtrl.java

    /**
     * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<br>
     * Controller for the /WEB-INF/zkloginDialog.zul file.<br>
     * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<br>
     * 
     * @author bbruhns
     * @author sgerth
     */
    public class ZkLoginDialogCtrl extends GenericForwardComposer implements Serializable {
    
    	private transient final static Logger logger = Logger.getLogger(ZkLoginDialogCtrl.class);
    	private static final long serialVersionUID = -71422545405325060L;
    
    	/*
    	 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    	 * All the components that are defined here and have a corresponding
    	 * component with the same 'id' in the zul-file are getting autowired 
         * by the 'GenericForwardComposer'.
    	 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    	 */
    	protected Window loginwin; // autowired
    	protected Textbox txtb_Username; // autowired
    	protected Textbox txtb_Password; // autowired
    	protected Textbox txtb_TenantId; // autowired
    
    	/**
    	 * default constructor. <br>
    	 */
    	public ZkLoginDialogCtrl() {
    		super();
    
    		if (logger.isDebugEnabled()) {
    			logger.debug("--> super() ");
    		}
    	}
    
    	/**
    	 * Automatically called method from zk.
    	 * 
    	 * @param event
    	 * @throws Exception
    	 */
    	public void onCreate$loginwin(Event event) throws Exception {
    
    		if (logger.isDebugEnabled()) {
    			logger.debug("--> " + event.toString());
    		}
    
    		txtb_Username.focus(); // set the focus on UserName
    
    		loginwin.setShadow(false);
    		loginwin.doModal();
    	}
    
    	/**
    	 * when the "close" button is clicked. <br>
    	 * 
    	 * @throws IOException
    	 */
    	public void onClick$button_ZKLoginDialog_Close() throws IOException {
    
    		if (logger.isDebugEnabled()) {
    			logger.debug("-->");
    		}
    
    		Executions.sendRedirect("/j_spring_logout");
    	}
    
    }
    

    Ok. Back to the customizing. In this article i will not explain how spring-security works therefore’s the documentation. I will concentrate on the classes for the needed purpose. At first we have a look which classes are involved in the case of spring-security’s form-login.

    This we will done in part 2 of this article.

    Samples are hostet in the Zksample2 project on

    Have fun with it.

    Stephan Gerth

    Dipl.rer.pol.


    PS: Help to prevent the global warming by writing cool software

    Modal search dialogs. Part 3: ExtendedSearchListBox skeleton.

    An extended modal searchBox/selectionList with paging and data limiting features which returns an object.

    As we see in part 1 and part 2 of the modal search dialogs story we build all search/selection components in a modal window component and by closing these window we can get back the selected object from the list.

    Database Paging is necessary if the application should be fast. Over all we need a functionality with which we can limit the amount of possible list results by manipulating the value of a table field for the sql where clause. For our ExtendedSearchListBox we do this by adding a textbox component and a search button. The textbox receives signs that must be occur with the data of the table field. We search in our backend method with the ‘like’ keyword, so that every record comes back where in their field ‘Description’ i.e. the signs ‘ar‘ exists. We start the retrieving of the records by pressing the search button right next the textbox. If we want get all records that we must clear the textbox and press the search button again.

    From the backend we get back a helper class called: ResultObject() . This class holds only two things. First a generic list that we must cast them back and second an int value that represents the totalSize of possible records (not the paged one’s size).

    calling in code:

         Bean bean = ExtendedSearchListBox.show(parentComponent);
    
         if ( bean != null ) {
           // do something
           }
    

    This is a very simple call. We get back the selected object from the list by selecting it and click the OK button or by double clicking on a listItem. Otherwise by closing without selecting we get back null.

  • The classfile:

    /**
     * Copyright 2010 the original author or authors.
     * 
     * This file is part of Zksample2. http://zksample2.sourceforge.net/
     *
     * Zksample2 is free software: you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation, either version 3 of the License, or
     * (at your option) any later version.
     * 
     * Zksample2 is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with Zksample2.  If not, see <http://www.gnu.org/licenses/gpl.html>.
     */
    package de.forsthaus.webui.util.searchdialogs;
    
    import java.io.Serializable;
    import java.util.List;
    
    import org.apache.log4j.Logger;
    import org.zkoss.spring.SpringUtil;
    import org.zkoss.util.resource.Labels;
    import org.zkoss.zk.ui.Component;
    import org.zkoss.zk.ui.SuspendNotAllowedException;
    import org.zkoss.zk.ui.event.Event;
    import org.zkoss.zk.ui.event.EventListener;
    import org.zkoss.zk.ui.sys.ComponentsCtrl;
    import org.zkoss.zkex.zul.Borderlayout;
    import org.zkoss.zkex.zul.Center;
    import org.zkoss.zkex.zul.North;
    import org.zkoss.zkex.zul.South;
    import org.zkoss.zul.Button;
    import org.zkoss.zul.Div;
    import org.zkoss.zul.Hbox;
    import org.zkoss.zul.ListModelList;
    import org.zkoss.zul.Listbox;
    import org.zkoss.zul.Listcell;
    import org.zkoss.zul.Listhead;
    import org.zkoss.zul.Listheader;
    import org.zkoss.zul.Listitem;
    import org.zkoss.zul.ListitemRenderer;
    import org.zkoss.zul.Paging;
    import org.zkoss.zul.Separator;
    import org.zkoss.zul.Textbox;
    import org.zkoss.zul.Window;
    import org.zkoss.zul.event.PagingEvent;
    
    import de.forsthaus.backend.bean.ResultObject;
    import de.forsthaus.backend.model.Branche;
    import de.forsthaus.backend.service.BrancheService;
    
    /**
     * This class creates a modal window as a dialog in which the user <br>
     * can search and select a branch object. By onClosing this box <b>returns</b>
     * an object or null. <br>
     * The object can returned by selecting and clicking the OK button or by
     * DoubleClicking on an item from the list.<br>
     * Further the count of results can limited by manipulating the value of a table
     * field for the sql where clause.<br>
     * <br>
     * This is a basic skeleton which is extended for database paging and an
     * additionally textbox for inserting a searchparameter.<br>
     * <br>
     * 
     * <pre>
     * call: Branch branch = BranchExtendedSearchListBox.show(parentComponent);
     * </pre>
     * 
     * @author bbruhns
     * @author sgerth
     */
    public class BranchExtendedSearchListBox extends Window implements Serializable {
    
    	private static final long serialVersionUID = 1L;
    	private static final Logger logger = Logger.getLogger(BranchExtendedSearchListBox.class);
    
    	// the textbox for inserting the searchparameter
    	private Textbox _textbox;
    
    	// button for sending the ServiceMethod if searchParameters are used
    	private Button _searchButton;
    
    	// the paging component
    	private Paging _paging;
    
    	// pageSize
    	private int pageSize = 18;
    
    	// the data listbox
    	private Listbox listbox;
    
    	// the model for the listbox
    	private ListModelList listModelList;
    
    	// the windows title
    	private String _title = Labels.getLabel("message.Information.ExtendedSearch") + " / " + Labels.getLabel("common.Branch");
    
    	// 1. Listheader
    	private String _listHeader1 = Labels.getLabel("common.Description");
    
    	// the windows height
    	private int _height = 410;
    
    	// the windows width
    	private int _width = 300;
    
    	// the returned bean object
    	private Branche branche = null;
    
    	// The service from which we get the data
    	private BrancheService brancheService;
    
    	/**
    	 * The Call method.
    	 * 
    	 * @param parent
    	 *            The parent component
    	 * @return a BeanObject from the listBox or null.
    	 */
    	public static Branche show(Component parent) {
    		return new BranchExtendedSearchListBox(parent).getBranche();
    	}
    
    	/**
    	 * Private Constructor. So it can only be created with the static show()
    	 * method.<br>
    	 * 
    	 * @param parent
    	 */
    	private BranchExtendedSearchListBox(Component parent) {
    		super();
    
    		setParent(parent);
    
    		createBox();
    	}
    
    	/**
    	 * Creates the components, sets the model and show the window as modal.<br>
    	 */
    	@SuppressWarnings("unchecked")
    	private void createBox() {
    
    		// Window
    		this.setWidth(String.valueOf(_width) + "px");
    		this.setHeight(String.valueOf(_height) + "px");
    		this.setTitle(_title);
    		this.setVisible(true);
    		this.setClosable(true);
    
    		// Borderlayout
    		Borderlayout bl = new Borderlayout();
    		bl.setHeight("100%");
    		bl.setWidth("100%");
    		bl.setParent(this);
    
    		Center center = new Center();
    		center.setBorder("none");
    		center.setFlex(true);
    		center.setParent(bl);
    
    		// Borderlayout
    		Borderlayout bl2 = new Borderlayout();
    		bl2.setHeight("100%");
    		bl2.setWidth("100%");
    		bl2.setParent(center);
    
    		North north2 = new North();
    		north2.setBorder("none");
    		north2.setHeight("26px");
    		north2.setParent(bl2);
    		// Paging
    		_paging = new Paging();
    		_paging.setDetailed(true);
    		_paging.addEventListener("onPaging", new OnPagingEventListener());
    		_paging.setPageSize(getPageSize());
    		_paging.setParent(north2);
    
    		Center center2 = new Center();
    		center2.setBorder("none");
    		center2.setFlex(true);
    		center2.setParent(bl2);
    		// Div Center area
    		Div divCenter2 = new Div();
    		divCenter2.setWidth("100%");
    		divCenter2.setHeight("100%");
    		divCenter2.setParent(center2);
    
    		// Listbox
    		listbox = new Listbox();
    		// listbox.setStyle("border: none;");
    		listbox.setHeight("290px");
    		listbox.setVisible(true);
    		listbox.setParent(divCenter2);
    		listbox.setItemRenderer(new SearchBoxItemRenderer());
    	
    		Listhead listhead = new Listhead();
    		listhead.setParent(listbox);
    		Listheader listheader = new Listheader();
    		listheader.setParent(listhead);
    		listheader.setLabel(_listHeader1);
    
    		South south2 = new South();
    		south2.setBorder("none");
    		south2.setHeight("26px");
    		south2.setParent(bl2);
    		// hbox for holding the Textbox + SearchButton
    		Hbox hbox = new Hbox();
    		hbox.setPack("stretch");
    		hbox.setStyle("padding-left: 5px");
    		hbox.setWidth("100%");
    		hbox.setHeight("27px");
    		hbox.setParent(south2);
    		// textbox for inserting the search parameter
    		_textbox = new Textbox();
    		_textbox.setWidth("100%");
    		_textbox.setMaxlength(20);
    		_textbox.setParent(hbox);
    		// serachButton
    		_searchButton = new Button();
    		_searchButton.setImage("/images/icons/search.gif");
    		_searchButton.addEventListener("onClick", new OnSearchListener());
    		_searchButton.setParent(hbox);
    
    		South south = new South();
    		south.setBorder("none");
    		south.setHeight("30px");
    		south.setParent(bl);
    
    		Div divSouth = new Div();
    		divSouth.setWidth("100%");
    		divSouth.setHeight("100%");
    		divSouth.setParent(south);
    
    		Separator sep = new Separator();
    		sep.setBar(true);
    		sep.setOrient("horizontal");
    		sep.setParent(divSouth);
    
    		// Button
    		Button btnOK = new Button();
    		btnOK.setStyle("padding-left: 5px");
    		btnOK.setLabel("OK");
    		btnOK.addEventListener("onClick", new OnCloseListener());
    		btnOK.setParent(divSouth);
    
    		/**
    		 * init the model.<br>
    		 * The ResultObject is a helper class that holds the generic list and
    		 * the totalRecord count as int value.
    		 */
    		ResultObject ro = getBrancheService().getAllBranchesLikeText("", 0, getPageSize());
    		List<Branche> resultList = (List<Branche>) ro.getList();
    		_paging.setTotalSize(ro.getTotalCount());
    
    		// set the model
    		setListModelList(new ListModelList(resultList));
    		listbox.setModel(getListModelList());
    
    		try {
    			doModal();
    		} catch (SuspendNotAllowedException e) {
    			logger.fatal("", e);
    			this.detach();
    		} catch (InterruptedException e) {
    			logger.fatal("", e);
    			this.detach();
    		}
    	}
    
    	/**
    	 * Inner ListItemRenderer class.<br>
    	 */
    	final class SearchBoxItemRenderer implements ListitemRenderer {
    
    		@Override
    		public void render(Listitem item, Object data) throws Exception {
    
    			Branche branche = (Branche) data;
    
    			Listcell lc = new Listcell(branche.getBraBezeichnung());
    			lc.setParent(item);
    
    			item.setAttribute("data", data);
    			ComponentsCtrl.applyForward(item, "onDoubleClick=onDoubleClicked");
    		}
    	}
    
    	/**
    	 * If a DoubleClick appears on a listItem. <br>
    	 * This method is forwarded in the renderer.<br>
    	 * 
    	 * @param event
    	 */
    	public void onDoubleClicked(Event event) {
    
    		if (listbox.getSelectedItem() != null) {
    			Listitem li = listbox.getSelectedItem();
    			Branche branche = (Branche) li.getAttribute("data");
    
    			setBranche(branche);
    			this.onClose();
    		}
    	}
    
    	/**
    	 * "onPaging" EventListener for the paging component. <br>
    	 * <br>
    	 * Calculates the next page by currentPage and pageSize values. <br>
    	 * Calls the method for refreshing the data with the new rowStart and
    	 * pageSize. <br>
    	 */
    	public final class OnPagingEventListener implements EventListener {
    		@Override
    		public void onEvent(Event event) throws Exception {
    
    			PagingEvent pe = (PagingEvent) event;
    			int pageNo = pe.getActivePage();
    			int start = pageNo * getPageSize();
    
    			if (logger.isDebugEnabled()) {
    				logger.debug("--> : " + start + "/" + getPageSize());
    			}
    
    			String searchText = _textbox.getValue();
    			// refresh the list
    			refreshModel(searchText, start);
    		}
    	}
    
    	/**
    	 * Refreshes the list by calling the DAO methode with the modified search
    	 * object. <br>
    	 * 
    	 * @param so
    	 *            SearchObject, holds the entity and properties to search. <br>
    	 * @param start
    	 *            Row to start. <br>
    	 */
    	@SuppressWarnings("unchecked")
    	void refreshModel(String searchText, int start) {
    
    		// clear old data
    		getListModelList().clear();
    
    		// init the model
    		ResultObject ro = getBrancheService().getAllBranchesLikeText(searchText, start, getPageSize());
    		List<Branche> resultList = (List<Branche>) ro.getList();
    		_paging.setTotalSize(ro.getTotalCount());
    
    		// set the model
    		setListModelList(new ListModelList(resultList));
    		listbox.setModel(getListModelList());
    	}
    
    	/**
    	 * Inner OnSearchListener class.<br>
    	 */
    	final class OnSearchListener implements EventListener {
    		@Override
    		public void onEvent(Event event) throws Exception {
    
    			String searchText = _textbox.getValue();
    
    			// we start new
    			refreshModel(searchText, 0);
    		}
    	}
    
    	/**
    	 * Inner OnCloseListener class.<br>
    	 */
    	final class OnCloseListener implements EventListener {
    		@Override
    		public void onEvent(Event event) throws Exception {
    
    			if (listbox.getSelectedItem() != null) {
    				Listitem li = listbox.getSelectedItem();
    				Branche branche = (Branche) li.getAttribute("data");
    
    				setBranche(branche);
    			}
    			onClose();
    		}
    	}
    
    	// +++++++++++++++++++++++++++++++++++++++++++++++++ //
    	// ++++++++++++++++ Setter/Getter ++++++++++++++++++ //
    	// +++++++++++++++++++++++++++++++++++++++++++++++++ //
    
    	public Branche getBranche() {
    		return branche;
    	}
    
    	private void setBranche(Branche branche) {
    		this.branche = branche;
    	}
    
    	public BrancheService getBrancheService() {
    		if (brancheService == null) {
    			brancheService = (BrancheService) SpringUtil.getBean("brancheService");
    		}
    		return brancheService;
    	}
    
    	public void setBrancheService(BrancheService brancheService) {
    		this.brancheService = brancheService;
    	}
    
    	public void setPageSize(int pageSize) {
    		this.pageSize = pageSize;
    	}
    
    	public int getPageSize() {
    		return pageSize;
    	}
    
    	public void setListModelList(ListModelList listModelList) {
    		this.listModelList = listModelList;
    	}
    
    	public ListModelList getListModelList() {
    		return listModelList;
    	}
    
    }
    
    

    The helper classfile:

    /**
     * A helper class that can hold a generic list and an int value. Used as the
     * totalSize value of possible records for paging components.<br>
     * 
     * @author sgerth
     * 
     */
    public class ResultObject implements Serializable {
    
    	private static final long serialVersionUID = 1L;
    
    	// holds a generic List
    	private List<?> list;
    
    	// holds an int
    	private int totalCount;
    
    	public ResultObject() {
    	}
    
    	public ResultObject(List<?> list, int totalCount) {
    		super();
    		setList(list);
    		setTotalCount(totalCount);
    	}
    
    	public List<?> getList() {
    		return list;
    	}
    
    	public void setList(List<?> list) {
    		this.list = list;
    	}
    
    	public int getTotalCount() {
    		return totalCount;
    	}
    
    	public void setTotalCount(int totalCount) {
    		this.totalCount = totalCount;
    	}
    }
    
    

    The backend method uses Spring/Hibernate:

    	@SuppressWarnings("unchecked")
    	@Override
    	public ResultObject getAllBranchesLikeText(String text, int start, int pageSize) {
    		DetachedCriteria criteria = DetachedCriteria.forClass(Branche.class);
    
    		if (!StringUtils.isEmpty(text)) {
    			criteria.add(Restrictions.ilike("braBezeichnung", text, MatchMode.ANYWHERE));
    		}
    
    		criteria.addOrder(Order.asc("braBezeichnung"));
    
    		int totalCount = getHibernateTemplate().findByCriteria(criteria).size();
    
    		List<Branche> list = getHibernateTemplate().findByCriteria(criteria, start, pageSize);
    
    		return new ResultObject(list, totalCount);
    	}
    
    

    Samples are hostet in the Zksample2 project on

    Have fun with it.

    Stephan Gerth

    Dipl.rer.pol.


    PS: Help to prevent the global warming by writing cool software

    Modal search dialogs. Part 2: AdvancedSearchListBox skeleton.

    An advanced modal searchBox/selectionList with database paging which returns an object.

    part 1 SimpleSearchListBox
    part 3 ExtendedSearchListBox

    As we see in part 1 of the modal search dialogs story we build all search/selection components in a modal window component and by closing these window we can get back the selected object from the list.

    You’ll discover that these searchDialog is not really recommended for handling huge data amounts. In fact the underlying zk ListModelList will handle the data paging on the server and send back to the clients listbox only such count of records that are defined in the pageSize but holds all of the loaded records on the server. So the memory usage can increase rapidly.

    As a Webui framework the involved zk component cannot and need not know what backend technology we use. So we can catch the onPaging() event from the paging component to manipulate the outgoing database call for the needed records. In this case we get a real database paging where only the needed records for presenting in the listbox are loaded from the db.

    calling in code:

         Bean bean = AdvancedSearchListBox.show(parentComponent);
    
         if ( bean != null ) {
           // do something
           }
    

    The classfile:

    /**
     * Copyright 2010 the original author or authors.
     * 
     * This file is part of Zksample2. http://zksample2.sourceforge.net/
     *
     * Zksample2 is free software: you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation, either version 3 of the License, or
     * (at your option) any later version.
     * 
     * Zksample2 is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with Zksample2.  If not, see <http://www.gnu.org/licenses/gpl.html>.
     */
    package de.forsthaus.webui.util.searchdialogs;
    
    import java.io.Serializable;
    import java.util.List;
    
    import org.apache.log4j.Logger;
    import org.zkoss.spring.SpringUtil;
    import org.zkoss.util.resource.Labels;
    import org.zkoss.zk.ui.Component;
    import org.zkoss.zk.ui.SuspendNotAllowedException;
    import org.zkoss.zk.ui.event.Event;
    import org.zkoss.zk.ui.event.EventListener;
    import org.zkoss.zk.ui.sys.ComponentsCtrl;
    import org.zkoss.zkex.zul.Borderlayout;
    import org.zkoss.zkex.zul.Center;
    import org.zkoss.zkex.zul.South;
    import org.zkoss.zul.Button;
    import org.zkoss.zul.Div;
    import org.zkoss.zul.ListModelList;
    import org.zkoss.zul.Listbox;
    import org.zkoss.zul.Listcell;
    import org.zkoss.zul.Listhead;
    import org.zkoss.zul.Listheader;
    import org.zkoss.zul.Listitem;
    import org.zkoss.zul.ListitemRenderer;
    import org.zkoss.zul.Paging;
    import org.zkoss.zul.Window;
    import org.zkoss.zul.event.PagingEvent;
    
    import de.forsthaus.backend.bean.ResultObject;
    import de.forsthaus.backend.model.Branche;
    import de.forsthaus.backend.service.BrancheService;
    
    /**
     * This class creates a modal window as a dialog in which the user <br>
     * can search and select a branch object. By onClosing this box <b>returns</b>
     * an object or null. <br>
     * The object can returned by selecting and clicking the OK button or by
     * DoubleClicking on an item from the list.<br>
     * 
     * <br>
     * This is a basic skeleton which is extended for database paging.<br>
     * <br>
     * 
     * <pre>
     * call: Branch branch = BranchAdvancedSearchListBox.show(parentComponent);
     * </pre>
     * 
     * @author bbruhns
     * @author sgerth
     */
    public class BranchAdvancedSearchListBox extends Window implements Serializable {
    
    	private static final long serialVersionUID = 1L;
    	private static final Logger logger = Logger.getLogger(BranchAdvancedSearchListBox.class);
    
    	// the paging component
    	private Paging _paging;
    
    	// pageSize
    	private int pageSize = 19;
    
    	// the data listbox
    	private Listbox listbox;
    
    	// the model for the listbox
    	private ListModelList listModelList;
    
    	// the windows title
    	private String _title = Labels.getLabel("message.Information.AdvancedSearch") + " / " + Labels.getLabel("common.Branch");
    
    	// 1. Listheader
    	private String _listHeader1 = Labels.getLabel("common.Description");
    
    	// the windows height
    	private int _height = 400;
    
    	// the windows width
    	private int _width = 300;
    
    	// the returned bean object
    	private Branche branche = null;
    
    	// The service from which we get the data
    	private BrancheService brancheService;
    
    	/**
    	 * The Call method.
    	 * 
    	 * @param parent
    	 *            The parent component
    	 * @return a BeanObject from the listBox or null.
    	 */
    	public static Branche show(Component parent) {
    		return new BranchAdvancedSearchListBox(parent).getBranche();
    	}
    
    	/**
    	 * Private Constructor. So it can only be created with the static show()
    	 * method.<br>
    	 * 
    	 * @param parent
    	 */
    	private BranchAdvancedSearchListBox(Component parent) {
    		super();
    
    		setParent(parent);
    
    		createBox();
    	}
    
    	/**
    	 * Creates the components, sets the model and show the window as modal.<br>
    	 */
    	@SuppressWarnings("unchecked")
    	private void createBox() {
    
    		// Window
    		this.setWidth(String.valueOf(_width) + "px");
    		this.setHeight(String.valueOf(_height) + "px");
    		this.setTitle(_title);
    		this.setVisible(true);
    		this.setClosable(true);
    
    		// Borderlayout
    		Borderlayout bl = new Borderlayout();
    		bl.setHeight("100%");
    		bl.setWidth("100%");
    		bl.setParent(this);
    
    		Center center = new Center();
    		center.setFlex(true);
    		center.setParent(bl);
    
    		South south = new South();
    		south.setHeight("26px");
    		south.setParent(bl);
    
    		// Button
    		Button btnOK = new Button();
    		btnOK.setLabel("OK");
    		btnOK.addEventListener("onClick", new OnCloseListener());
    		btnOK.setParent(south);
    
    		Div divCenter = new Div();
    		divCenter.setWidth("100%");
    		divCenter.setHeight("100%");
    		divCenter.setParent(center);
    
    		// Paging
    		_paging = new Paging();
    		_paging.addEventListener("onPaging", new OnPagingEventListener());
    		_paging.setPageSize(getPageSize());
    		_paging.setParent(divCenter);
    
    		// Listbox
    		listbox = new Listbox();
    		listbox.setStyle("border: none;");
    		listbox.setHeight("100%");
    		listbox.setVisible(true);
    		listbox.setParent(divCenter);
    		listbox.setItemRenderer(new SearchBoxItemRenderer());
    
    		Listhead listhead = new Listhead();
    		listhead.setParent(listbox);
    		Listheader listheader = new Listheader();
    		listheader.setParent(listhead);
    		listheader.setLabel(_listHeader1);
    
    		/**
    		 * init the model.<br>
    		 * The ResultObject is a helper class that holds the generic list and
    		 * the totalRecord count as int value.
    		 */
    		ResultObject ro = getBrancheService().getAllBranches(0, getPageSize());
    		List<Branche> resultList = (List<Branche>) ro.getList();
    		_paging.setTotalSize(ro.getTotalCount());
    
    		// set the model
    		setListModelList(new ListModelList(resultList));
    		listbox.setModel(getListModelList());
    
    		try {
    			doModal();
    		} catch (SuspendNotAllowedException e) {
    			logger.fatal("", e);
    			this.detach();
    		} catch (InterruptedException e) {
    			logger.fatal("", e);
    			this.detach();
    		}
    	}
    
    	/**
    	 * Inner ListItemRenderer class.<br>
    	 */
    	final class SearchBoxItemRenderer implements ListitemRenderer {
    
    		@Override
    		public void render(Listitem item, Object data) throws Exception {
    
    			Branche branche = (Branche) data;
    
    			Listcell lc = new Listcell(branche.getBraBezeichnung());
    			lc.setParent(item);
    
    			item.setAttribute("data", data);
    			ComponentsCtrl.applyForward(item, "onDoubleClick=onDoubleClicked");
    		}
    	}
    
    	/**
    	 * If a DoubleClick appears on a listItem. <br>
    	 * This method is forwarded in the renderer.<br>
    	 * 
    	 * @param event
    	 */
    	public void onDoubleClicked(Event event) {
    
    		if (listbox.getSelectedItem() != null) {
    			Listitem li = listbox.getSelectedItem();
    			Branche branche = (Branche) li.getAttribute("data");
    
    			setBranche(branche);
    			this.onClose();
    		}
    	}
    
    	/**
    	 * "onPaging" EventListener for the paging component. <br>
    	 * <br>
    	 * Calculates the next page by currentPage and pageSize values. <br>
    	 * Calls the method for refreshing the data with the new rowStart and
    	 * pageSize. <br>
    	 */
    	public final class OnPagingEventListener implements EventListener {
    		@Override
    		public void onEvent(Event event) throws Exception {
    
    			PagingEvent pe = (PagingEvent) event;
    			int pageNo = pe.getActivePage();
    			int start = pageNo * getPageSize();
    
    			if (logger.isDebugEnabled()) {
    				logger.debug("--> : " + start + "/" + getPageSize());
    			}
    
    			// refresh the list
    			refreshModel(start);
    		}
    	}
    
    	/**
    	 * Refreshes the list by calling the DAO methode with the modified search
    	 * object. <br>
    	 * 
    	 * @param so
    	 *            SearchObject, holds the entity and properties to search. <br>
    	 * @param start
    	 *            Row to start. <br>
    	 */
    	@SuppressWarnings("unchecked")
    	void refreshModel(int start) {
    
    		// clear old data
    		getListModelList().clear();
    
    		// init the model
    		ResultObject ro = getBrancheService().getAllBranches(start, getPageSize());
    		List<Branche> resultList = (List<Branche>) ro.getList();
    		_paging.setTotalSize(ro.getTotalCount());
    
    		// set the model
    		setListModelList(new ListModelList(resultList));
    		listbox.setModel(getListModelList());
    	}
    
    	/**
    	 * Inner OnCloseListener class.<br>
    	 */
    	final class OnCloseListener implements EventListener {
    		@Override
    		public void onEvent(Event event) throws Exception {
    
    			if (listbox.getSelectedItem() != null) {
    				Listitem li = listbox.getSelectedItem();
    				Branche branche = (Branche) li.getAttribute("data");
    
    				setBranche(branche);
    			}
    			onClose();
    		}
    	}
    
    	// +++++++++++++++++++++++++++++++++++++++++++++++++ //
    	// ++++++++++++++++ Setter/Getter ++++++++++++++++++ //
    	// +++++++++++++++++++++++++++++++++++++++++++++++++ //
    
    	public Branche getBranche() {
    		return branche;
    	}
    
    	private void setBranche(Branche branche) {
    		this.branche = branche;
    	}
    
    	public BrancheService getBrancheService() {
    		if (brancheService == null) {
    			brancheService = (BrancheService) SpringUtil.getBean("brancheService");
    		}
    		return brancheService;
    	}
    
    	public void setBrancheService(BrancheService brancheService) {
    		this.brancheService = brancheService;
    	}
    
    	public void setPageSize(int pageSize) {
    		this.pageSize = pageSize;
    	}
    
    	public int getPageSize() {
    		return pageSize;
    	}
    
    	public void setListModelList(ListModelList listModelList) {
    		this.listModelList = listModelList;
    	}
    
    	public ListModelList getListModelList() {
    		return listModelList;
    	}
    
    }
    
    
    

    For the backend helper class ResultObject() and the backend method please read part 3 of this article.

    Samples are hostet in the Zksample2 project on

    Have fun with it.

    Stephan Gerth

    Dipl.rer.pol.


    PS: Help to prevent the global warming by writing cool software

    Modal search dialogs. Part 1: SimpleSearchListBox skeleton.

    A modal searchBox/selectionList which returns an object.

    part 2 AdvancedSearchListBox
    part 3 ExtendedSearchListBox

    Imagine you have a form with several data fields and one or more of it will get their data by selecting it from a list. Such a list is often called as a DropDownList. With the zk framework you can solve this by using a listbox with mold=”select” and rows=”1″. The outstanding feature of such a component is that the ‘starter’ is in most cases a little button direct at the end of the input field and eveybody knows that he must click on this button to drop down the list. If you need some more options for limiting the count of records when the list appears you need an other way to solve this issue.

    One possibility is to take a so called bandbox component and place all needed data limiting functionality with the listbox on it.


    The second way we will shown in this article is to build a searchBox class with a modal window. For having the same behaviour we place a little starter button right next the input field that we whish to fill with a selected item from our SearchListBox. The advantage of our solution is that we can easily extended the SearchListBox for needed limitation components and logic features and get back an object of the needed bean from a window in a modal state.

    For this requirement we let our SimpleSearchListBox class created by a private constructor that we called in a static way.

  • calling in code:

         Bean bean = SimpleSearchListBox.show(parentComponent);
    
         if ( bean != null ) {
           // do something
           }
    

    The classfile:

    /**
    * Copyright 2010 the original author or authors.
    *
    * This file is part of Zksample2. http://zksample2.sourceforge.net/
    *
    * Zksample2 is free software: you can redistribute it and/or modify
    * it under the terms of the GNU General Public License as published by
    * the Free Software Foundation, either version 3 of the License, or
    * (at your option) any later version.
    *
    * Zksample2 is distributed in the hope that it will be useful,
    * but WITHOUT ANY WARRANTY; without even the implied warranty of
    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    * GNU General Public License for more details.
    *
    * You should have received a copy of the GNU General Public License
    * along with Zksample2.  If not, see .
    */
    package de.forsthaus.webui.util.searchdialogs;
    
    import org.apache.log4j.Logger;
    import org.zkoss.spring.SpringUtil;
    import org.zkoss.util.resource.Labels;
    import org.zkoss.zk.ui.Component;
    import org.zkoss.zk.ui.SuspendNotAllowedException;
    import org.zkoss.zk.ui.event.Event;
    import org.zkoss.zk.ui.event.EventListener;
    import org.zkoss.zk.ui.sys.ComponentsCtrl;
    import org.zkoss.zkex.zul.Borderlayout;
    import org.zkoss.zkex.zul.Center;
    import org.zkoss.zkex.zul.South;
    import org.zkoss.zul.Button;
    import org.zkoss.zul.ListModelList;
    import org.zkoss.zul.Listbox;
    import org.zkoss.zul.Listcell;
    import org.zkoss.zul.Listhead;
    import org.zkoss.zul.Listheader;
    import org.zkoss.zul.Listitem;
    import org.zkoss.zul.ListitemRenderer;
    import org.zkoss.zul.Window;
    
    import de.forsthaus.backend.model.Branche;
    import de.forsthaus.backend.service.BrancheService;
    
    /**
    * This class creates a modal window as a dialog in which the user
    * can search and select a branch object. By onClosing this box <strong>returns</strong>
    * an object or null.
    * The object can returned by selecting and clicking the OK button or by
    * DoubleClicking on an item from the list.
    *
    * This is a basic skeleton which can be extended for paging or additionally
    * textboxes for inserting searchparameters.
    *
    *
    * call: Branch branch = BranchSimpleSearchBox.show(parentComponent);
    *
    * @author bbruhns
    * @author sgerth
    */
    public class BranchSimpleSearchListBox extends Window {
    
    private static final long serialVersionUID = 8109634704496621100L;
    private static final Logger logger = Logger.getLogger(BranchSimpleSearchListBox.class);
    
    private Listbox listbox;
    // the windows title
    private String _title = Labels.getLabel("message.Information.Search") + " " + Labels.getLabel("common.Branch");
    // 1. Listheader
    private String _listHeader1 = Labels.getLabel("common.Description");
    // the windows height
    private int _height = 400;
    // the windows width
    private int _width = 300;
    
    // the returned bean object
    private Branche branche = null;
    
    // The service from which we get the data
    private BrancheService brancheService;
    
    /**
    * The Call method.
    *
    * @param parent
    *            The parent component
    * @return a BeanObject from the listBox or null.
    */
    public static Branche show(Component parent) {
    return new BranchSimpleSearchListBox(parent).getBranche();
    }
    
    /**
    * Private Constructor. So it can only be created with the static show() method.
    *
    * @param parent
    */
    private BranchSimpleSearchListBox(Component parent) {
    super();
    
    setParent(parent);
    
    createBox();
    }
    
    /**
    * Creates the components, sets the model and show the window as modal.
    */
    private void createBox() {
    
    // Window
    this.setWidth(String.valueOf(_width) + "px");
    this.setHeight(String.valueOf(_height) + "px");
    this.setTitle(_title);
    this.setVisible(true);
    this.setClosable(true);
    
    // Borderlayout
    Borderlayout bl = new Borderlayout();
    bl.setHeight("100%");
    bl.setWidth("100%");
    bl.setParent(this);
    
    Center center = new Center();
    center.setFlex(true);
    center.setParent(bl);
    
    South south = new South();
    south.setHeight("26px");
    south.setParent(bl);
    
    // Button
    Button btnOK = new Button();
    btnOK.setLabel("OK");
    btnOK.addEventListener("onClick", new OnCloseListener());
    btnOK.setParent(south);
    
    // Listbox
    listbox = new Listbox();
    listbox.setStyle("border: none;");
    listbox.setHeight("100%");
    listbox.setVisible(true);
    listbox.setParent(center);
    listbox.setItemRenderer(new SearchBoxItemRenderer());
    
    Listhead listhead = new Listhead();
    listhead.setParent(listbox);
    Listheader listheader = new Listheader();
    listheader.setParent(listhead);
    listheader.setLabel(_listHeader1);
    
    // Model
    listbox.setModel(new ListModelList(getBrancheService().getAlleBranche()));
    
    try {
    doModal();
    } catch (SuspendNotAllowedException e) {
    logger.fatal("", e);
    this.detach();
    } catch (InterruptedException e) {
    logger.fatal("", e);
    this.detach();
    }
    }
    
    /**
    * Inner ListItemRenderer class.
    */
    final class SearchBoxItemRenderer implements ListitemRenderer {
    
    @Override
    public void render(Listitem item, Object data) throws Exception {
    
    Branche branche = (Branche) data;
    
    Listcell lc = new Listcell(branche.getBraBezeichnung());
    lc.setParent(item);
    
    item.setAttribute("data", data);
    ComponentsCtrl.applyForward(item, "onDoubleClick=onDoubleClicked");
    }
    }
    
    /**
    * If a DoubleClick appears on a listItem.
    * This method is forwarded in the renderer.
    *
    * @param event
    */
    public void onDoubleClicked(Event event) {
    
    if (listbox.getSelectedItem() != null) {
    Listitem li = listbox.getSelectedItem();
    Branche branche = (Branche) li.getAttribute("data");
    
    setBranche(branche);
    this.onClose();
    }
    }
    
    /**
    * Inner OnCloseListener class.
    */
    final class OnCloseListener implements EventListener {
    
    @Override
    public void onEvent(Event event) throws Exception {
    
    if (listbox.getSelectedItem() != null) {
    Listitem li = listbox.getSelectedItem();
    Branche branche = (Branche) li.getAttribute("data");
    
    setBranche(branche);
    }
    onClose();
    }
    }
    
    // +++++++++++++++++++++++++++++++++++++++++++++++++ //
    // ++++++++++++++++ Setter/Getter ++++++++++++++++++ //
    // +++++++++++++++++++++++++++++++++++++++++++++++++ //
    
    public Branche getBranche() {
    return branche;
    }
    
    private void setBranche(Branche branche) {
    this.branche = branche;
    }
    
    public BrancheService getBrancheService() {
    if (brancheService == null) {
    brancheService = (BrancheService) SpringUtil.getBean("brancheService");
    }
    return brancheService;
    }
    
    public void setBrancheService(BrancheService brancheService) {
    this.brancheService = brancheService;
    }
    
    

    Samples are hostet in the Zksample2 project on

    Have fun with it.

    Stephan Gerth

    Dipl.rer.pol.


    PS: Help to prevent the global warming by writing cool software

    New ZK sample application sources available

    Yesterday we have checked in our new Zksample2 application as maven2 projects on sourceforge.net.
    It’s shows how you can build a robust and scalable enterprise web application by integrating commonly used frameworks like Hibernate, Spring, Spring-AOP, Spring-Security, JasperReports with the ZK Java web framework.
    You can reach the project homepage under the link here .

    You will find there 3 eclipse maven subprojects and the folder for the documentation.

    1. KeyGenZkoss = one-time-password generator
    2. spring-hibernate-backend = backend
    3. zkoss = frontend
    4. zksample2_doc = documentation

    The Documentation you can download seperately as a pdf-file from here .

    The documentation is a work in progress so be sure to check sometimes for the newest file.

    For checkout and evaluate or work with the application please download and read first the documentation.

    Mainly changes to the first sample app are:
    – change project structure as maven2 projects
    – spring managed frontend
    – securing methods with annotations @Secured() with our own implementation
    – login statistic
    – several integration options of ipToCountry
    – one-time-password sources are opened
    – Refactoring all Domain/DAO/Service Classes to english names
    – many many code changes
    – Revised PagedListWrapper
    – documentation

    We whish all fun with it and hope that it can be usefull for others.


    Authors: Stephan Gerth & Björn Bruhns

    Samples are hostet in the Zksample2 project on


    PS: Help to prevent the global warming by writing cool software

    Direct RIA: Die Zukunft von RIA

    Artikel: Direct RIA: Future of RIA / Author:  Robbie Cheng /  ZK Framework.

    Erschienen auf CodeGuru.com http://www.codeguru.com/java/article.php/c16445__1/

    Direkt RIA = Ansatz von Client + Server Verschmelzung

    Mehr Auswahl, schwierigere Entscheidung

    Obwohl Unternehmen von Rich-Internet-Anwendungen profitieren können, so kann die Einführung neuer Technologien auch Risiken beherbergen. Das erste Problem ist, das richtige Werkzeug für die gewünschte Lösung zu wählen. Hier kann es leicht zu einer falschen Entscheidung kommen aufgrund zu großer Auswahl, unklarer Kriterien, und komplexen Anforderungen.

    Produktivität oder Kontrollierbarkeit

    RIA (Rich Internet Application) Lösungen können in der Regel in zwei Kategorien eingestuft werden. Client- oder Server-seitig arbeitend.

    Client-seitige Frameworks sind wie manuelle Schaltgetriebe im  Auto, sie bieten mehr Kontrolle, erfordern aber auch mehr Aufwand. Im Gegensatz dazu verhalten sich Server-seitige Frameworks wie Automatik- Getriebe, die einfacher zu handhaben sind. Entwickler können durch AJAX-Technologie die Produktivität erhöhen und  transparenter gestalten.

    Die zu treffende Auswahl zwischen beiden Lösungsansätzen verursacht weiterhin Kopfschmerzen. Komplette Kontrolle oder Produktivität? Können wir von beiden Ansätzen zur gleichen Zeit profitieren? Der beste Fall wäre, dass unterschiedliche Anforderungen wie ein manuell schaltbares Automatik-Getriebe behandelt werden können.

    Direct RIA ermöglicht einen revolutionäre Ansatz von Client + Server Verschmelzung, der die Vorteile von Produktivität und Kontrollierbarkeit bei der Programmierung zur gleichen Zeit nutzt, je nach dem ob vollständige Anpassung oder Reaktionsfähigkeit benötigt wird.

    Übersicht über die Architektur von Direct RIA

    Direct RIA ist eine Server-seitige Lösung plus optionale Client-seitige Programmierung. Wenn Sie einen Blick auf die folgende Grafik nehmen, können Sie sehen, dass das Server-seitige Programmiermodell  dem Entwickler erlaubt die Web-Anwendung unter Verwendung von reinem Server-seitigen Code zu bauen.

    Der Server-seitige Code Generator erzeugt den benötigten HTML- und JavaScript-Code automatisch. Danach  wird der Client-seitige Code Generator mit dem DOM-Baum interagieren, um den Inhalt zu aktualisieren. Darüber hinaus ist die Synchronisation zwischen dem Browser und dem Server durch das  Zusammenspiel  des Client-seitigen und Server-seitigen AJAX Generators automatisiert. Entwickler können sich so auf das Erstellen der Anwendung konzentrieren als auf die komplexen AJAX-Technologien.

    Allerdings ist einer der größten Nachteile des reinen Server-seitigen Programmiermodells, dass die Entwickler nicht vollständig die Darstellung der Benutzeroberfläche kontrollieren können. Um dieses Problem zu überwinden, ermöglicht Direct RIA ein zusätzliches Client-seitiges Programmiermodell, das es Entwicklern ermöglicht Client-Code zu schreiben um, wenn nötig, die Benutzeroberfläche direkt zu kontrollieren.

    Direkter Oberflächen Zugriff

    Da die Anwendung auf dem Server läuft  kann sie auf Widgets direkt zugreifen. Nehmen wir das ZK Framework als ein Beispiel und erstellen ein Java-2D-Objekt auf dem Server, und geben dieses Objekt einfach in das Widget. Die Nutzer werden das Bild auf dem Browser  sehen, sobald sie auf die Schaltfläche klicken.


    <image id="image">
    <button onClick='draw(10,10,10,10)'/>
    <zscript>
    void draw( int x1, int y1, int x2, int y2) {
    LiveImage li = new LiveImage(400, 300, LiveImage.TYPE_INT_RGB);
    Graphics2D g2d = li.createGraphics();
    Line2D line = new Line2D.Double(x1, y1, x2, y2); g2d.draw(line);
    image.setContent(Images.encode("test.png", li));
    }
    </zscript>
    

    Mit Direct RIA, müssen sich Entwicklern nicht mehr um Client-seitige Programmierung kümmern. Sie können also sehr schnell ein Projekt beginnen ohne die vielen Client-seitigen Technologien zu erlernen.

    - Keine Client-seitige Programmierung.


    Direkter Datenzugriff

    Darüber hinaus kann die Applikation leicht und direkt auf Server-Ressourcen zugreifen, einschließlich Datenbank- und Web-Services, da beide sowohl das Frontend als auch das Backend auf der Server-Seite laufen. Das folgende Beispiel zeigt ein einfaches Szenario, um Daten aus der Datenbank zu lesen, und zeigt sie dem Anwender mithilfe des ZK Frameworks. Sobald der Benutzer auf die Schaltfläche klickt, erscheint eine Willkommens Nachricht.

    
    Hi. <label id="name"/>
    
    <button>
    
    <attribute name="onClick">
    
    User usr = Database.getUserById(1);
    
    name.setValue(usr.getName());
    
    </attribute>
    
    </button>
    
    

    Eine der schwierigsten Herausforderungen bei der Erstellung von Web-Anwendungen liegt in im asynchronen Programmiermodell, welches die verschiedenen Schritte enthält, um Daten vom Server zu bekommen und entsprechend den DOM-Baum zu aktualisieren. Mit Direct RIA jedoch können Frontend und Backend nahtlos integriert werden.

    - Keine asynchrone Kommunikation mehr.


    Direkte Live Daten

    Mit Live-Daten können Entwickler die Daten von der View trennen. Entwickler können die Daten durch die Implementierung des ListModel Interfaces anbieten. Das ZK Framework ermöglicht diesen Weg anstatt der direkte Manipulation der Daten.

    
    <zscript>
    
    String[] data = new  String[1000]; for ( int  j=0; j < data.length; ++j) {
    
    data[j] = "option "+j;
    
    }
    
    ListModel strset = new  SimpleListModel(data);
    
    </zscript>
    
    <grid width="100px" height="100px" model="${strset}">
    
    <columns>
    
    <column label="options"/>
    
    </columns>
    
    </grid>
    
    

    Das Grid sendet die Daten nur dann an den Client, wenn es sichtbar ist. Es spart so eine Menge des Netzwerkverkehrs, wenn die Datenmenge sehr groß ist.

    -Kein Problem mehr mit der Skalierbarkeit.


    Direkte Klienten Kontrolle

    Mit Direct Client Control kann der Entwickler Widgets entweder in Java-Script oder einer Markup-Sprache entwickeln und die Funktionen im Klienten implementieren um so das Verhalten der Antwortzeiten zu verbessern. Im folgenden Beispiel zeigen wir eine einfache Funktion zur Anzeige einer User-Eingabe mittels reiner Client-Programmierung. Diese wird  mit der Markup-Sprache von ZK umgesetzt.

    <page id="main">
    <textbox id="searchBox"/>
    <label id="value">
    </page>
    <script>
    zk.zuml.Parser.createAt( '#main', null, null, function (page) {
    page.$f('searchBox').listen({onChanging: function (event) {
    page.$f( 'value').setValue(event.data.value);}});
    </script>
    

    Entwicklern steht es frei, eine Funktion auf dem Client-Seite anpassen, um ihre unterschiedlichen Anforderungen gerecht zu werden.

    - Keine Anpassung Probleme mehr.


    Direct RIA ist die Zukunft der RIA

    Es ist nie eine leichte Aufgabe eine Enterprise-Anwendung zu erstellen, ganz zu schweigen die Benutzer-Schnittstelle zur selben Zeit zu erzeugen. Darüber hinaus ist es nicht leicht, die richtige Lösung zu wählen bei über 200 Lösungen für die verschiedensten Anforderungen. Direct RIA bietet den Ansatz für eine Client-Server Verschmelzung so dass Entwickler ihre Produktivität steigern können. Mit Hilfe des Direct RIA Programmiermodells kann sowohl auf Frontend und Backend direkt zugreifen werden, außerdem steht es Entwicklern frei, wenn nötig Funktion auf der Client-Seite zu erstellen. Direct RIA weist darauf hin, eine Komplettlösung für Entwickler zu sein, die die  Vorteile der gleichzeitigen Nutzung  von Produktivität und Kontrollierbarkeit zur Verfügung stellt.

    Über den Autor

    Robbie Cheng ist ein Evangelist des ZK Frameworks. Er ist der Hauptentwickler von ZK Mobile für Android und ZK Forum. Er ist der Co-Autor des Buches “ZK: Ajax ohne Javascript Framework” und hat zahlreiche Artikel im AJAXWorld Mgazine, TheServerSide und Javalobby veröffentlicht. Weiterhin ist Robbie auch bei verschiedenen Veranstaltungen wie, Google Developer Day, Mobile Monday, und OSDC 2009 als Redner aufgetreten.

    Übersetzt aus dem englischen von Stephan Gerth.