How to create a Captcha in zk ce version?

Creating an own Captcha component while it’s not in the zk community version.

As i work on the ‘forgotten password?’ module in openTruuls™ i would use a Captcha component for the user verification and i’m wondering that such a component is not in the zk community version. So openTruuls™ will be opensourced i need a Captcha component that developers can using without registering for a personal or commercial zk version.

After a few searching in the zk forum and the WWW i became a hint from Maik, the developer behind the jease cms ( www.jease.org ) to using the simpleCaptcha framework.

Argh, the biggest problem was to find a repository where a not corupted  version is downloading via the maven2 build system. And let me talk that i’m do it at last by a manual downloading in the linux shell on our web server because i don’t find a runing version.

Okay, after done this, the result is a little Captcha Controller who creates the Captcha which we can call in a static way. In the forgottenPassword Controller we use this Captcha and get the image from it which we assign to a zk image.

pieces of the zul-template


    .  .  .
								<!-- Captcha / Captcha -->
								<row>
									<space width="0" />
									<hbox>

										<image id="img_Captcha" />

										<toolbarbutton id="btnReCaptcha"
											image="/images/icons/sync_16x16.gif"
											tooltiptext="${c:l('common.ReCaptcha')}" />
									</hbox>
								</row>
   . . .

The complete dialog should looks like in this picture:

ForgottenPasswordController
ForgottenPasswordController

the FDCaptchaUtils.java



/**
 * EN: Utility class for creating a CAPTCHA.<br>
 * Captcha can be direct loaded into a org.zkoss.zul.Image<br>
 * DE: Hilfsklasse zur Erzeugung eines CAPTCHA.<br>
 * Captcha kann direkt in ein org.zkoss.zul.Image eingelesen werden.
 *
 * <pre>
 * Image img = new org.zkoss.zul.Image();
 * img.setContent(CaptchaUtils.getCaptcha().getImage());
 *
 * String verifyStr = captcha.getAnswer();
 * </pre>
 *
 * @author Stephan Gerth
 */
public class FDCaptchaUtils {

	public FDCaptchaUtils() {
	}

	/**
	 * Create a 5 digits captcha.
	 *
	 * @return
	 */
	public static Captcha getCaptcha() {

		Captcha captcha = new Captcha.Builder(170, 50).addText(new ColoredEdgesWordRenderer()).addNoise().addBackground(new GradiatedBackgroundProducer()).addBorder().build();

		return captcha;
	}

}

In the forgotten password controller we create the Captcha and insert it in the zk Image and handles the verify logic.

The needed methods in the controller code looks like this:

pieces of the ForgottenPassword controller


   . . .
   private Captcha captcha; // + getter/setter
   . . .

/**
 * Do a re-Captcha.<br>
 *
 * @param event
 */
private void doReCaptcha(Event event) {
	// init: disable the send password button
	btnReset.setDisabled(true);

	setCaptcha(FDCaptchaUtils.getCaptcha());
	img_Captcha.setContent(getCaptcha().getImage());
}

/**
 * 1. Checks if the email address is entered.<br>
 * 2. Verify the created captcha digits against the users input from a textbox.<br>
 * 3. Enable/disable the 'reset password' button.<br>
 *
 * @param event
 */
private void doVerifyCaptcha(Event event) {

     // init: disable the reset password button
     btnReset.setDisabled(true);

     // check if the tenant ID is entered
     if (StringUtils.isEmpty(longb_TenantID.getValue().toString().trim())) {
       	 throw new WrongValueException(longb_TenantID, Labels.getLabel("message.Error.CannotBeEmpty"));
     }

     // check if the email address is entered
	if (StringUtils.isEmpty(txtb_EmailAddress.getValue())) {
	    throw new WrongValueException(txtb_EmailAddress, Labels.getLabel("message.Error.CannotBeEmpty"));
	}

	// check if the captcha is verified correctly
	if (StringUtils.equals(txtb_VerifyCaptcha.getValue(), getCaptcha().getAnswer())) {
            btnReset.setDisabled(false);
	}
     }

Have fun with it.

Stephan Gerth

Dipl.rer.pol.


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

openTruuls™ will become Business Process Management from jBoss

The opening of the sources of openTruuls™  ( . powered ) will delayed a little bit because we will integrate jBPM5 (Business Process Management) Drools (Business Rules) and the Guvnor repository from jBoss.

In fact, we will prevent that there comes many needed code modifications/adaptions in future for special industries so we do early our best and take therefore the big step by integrating a professional BPM system where the developer can modify most of such things separate in a workflow. jBPM5 works BPMN 2.0 standard compliant.

In this case i will speak a welcome to Anton from Hannover(Germany) who joins the core developer team.

Interested people/partners write us under zk(at)forsthaus(dot)de

best

Stephan Gerth

Only a few weeks until we open the sources for openTruuls™

At time we work hard on the codes for our new child called openTruuls™. It’s a business solution in the big field of the erp/crm software market. The multi-tenancy web-application is easy to extend for third party developers. It’s build to run in a clustered environment. For higher scaling the tenant/user/security database are separated from the tenants work data.  So our goal is to offer this solution for smaller and middle sized firms as SaaS (Software as a Service) in a hosted environment. For using this system by in house servers in the customers firm we can offer the install, modify or extending of the solution and support them. openTruuls™ openTruuls™ is an open source business application. It comes as a community edition or an enterprise edition with support.  The application self is build on the MVC (model-view-controller) pattern on a stable stack of open source JAVA frameworks. For the frontend that runs in all common used browsers we select the great java AJAX web framework from Potix corp. the zk framework  .. Spring, hibernate, hibernate-generic-dao are working in the middle layer. Out of the box the app will run against a PostgreSQL database. Running against mySQL,  DB2, Informix, Sybase, SQL Server, Oracle or other Hibernate supported databases are doing by modifying the mapping files. For the reporting we use at time JasperReports with DynamicJasper. openTruuls have a full customizable rights management build on top of the spring security framework. Customers can define own access levels for their users and third party developers can easy extend their new written or modified modules with additional rights. In the case of financial accounting we have at first adopt a DATEV compatible accounting module for the german market with pre-defined charts of accounts for the SKR 03 and SKR 04.

Dashboard

Dashboard

System Manager

System Manager

openTruuls™ openTruuls™ SaaS Manager

Interested people/partners write us under zk(at)forsthaus(dot)de

be part of it
best

Stephan Gerth
Dipl.rer.pol.


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

10. Web Monday in Magdeburg (11.10.2010)

WebMonday in Magdeburg

10. WebMonday in Magdeburg

On Monday i was speeking in Magdeburg on the WebMonday event about the zk framework.

It’s a nice event that take place every second monday in a month in many bigger cities worldwide. Here you can follow the speeches and meet some other guys who are interesting in Web Development.

This monday we have about 4 lectures and all speakers have only 15 minutes time for presenting their lecture and 15 minutes for questions and answers about their theme. I failed. It’s not possible to talk about zk in 15 minutes. I need 10 minutes more and i have luck. No one shoot me.

10. Web Monday

nice living room atmosphere

    Themes

1. Suggy ( all guys from suggy )
2. InfoVis & OpenData ( Gregor Aisch )
3. Template Toolkit 2 ( Alexander Dahl )
4. ZK Ajax Web Framework ( Stephan Gerth )

For all visitors who wants to know more about the webMondays in Magdeburg follow these link.

How to create a MessageSystem with the zk framework ?

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

In this article we will create a messaging system which is visually placed in the statusBar. We will call it messageBar and we add it as a Window component left before the statusBar window component as we explained in this previous post.

The ready implemented component are looks like this picture with only two icons in it. The red mail icon is for showing the message. This icon is blinking if there comes new messages in and the message reader is not opened (or if you uncomment a few lines in code it will popUp if a new message come in) . The right next icon is for opening a little window for writing a message text who can be send to all users.

Message Bar component

Message Bar component

pieces of the zul-template

.  .  .
		<!-- STATUS BAR AREA -->
			<south id="south" border="none" height="22px"
				splittable="false">

				<div id="divSouth" align="left"
					style="float: left; padding: 0px" width="100%">

					<borderlayout width="100%" height="22px">

						<west border="none" width="50px">
							<!-- The MessageBar. Comps are created in the Controller -->
							<window id="winMessageBar"
								apply="${messageBarCtrl}" border="none" width="50px"
								height="22px" />
						</west>

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

					</borderlayout>

				</div>

			</south>
.  .  .

The messageBar controller creates the two icons with their event Listeners and the global Listener for the messaging system. If you whish that an incoming message will popup self than you can uncomment the involved lines in the afterCompose method.

MessageBarCtrl.java

/**
 * =======================================================================<br>
 * MessageBarController. <br>
 * =======================================================================<br>
 * Works with the EventQueues mechanism of zk 5.x. ALl needed components are
 * created in this class. In the zul-template declare only this controller with
 * 'apply' to a winMessageBar window component.<br>
 * This MessageBarController is for sending and receiving messages from other
 * users.<br>
 *
 * The message text we do input with a special helper window that is called
 * InputMessageTextBox.java
 *
 * <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 MessageBar. Comps are created in the Controller -- >
 *          < window id="winMessageBar" apply="${messageBarCtrl}"
 *                   border="none" width="100%" height="100%" />
 *          < !-- The StatusBar. Comps are created in the Controller -- >
 *          < window id="winStatusBar" apply="${statusBarCtrl}"
 *                   border="none" width="100%" height="100%" />
 *        < /div >
 *    < /south >
 *  < /borderlayout >
 * </pre>
 *
 * call for the message system:
 *
 * <pre>
 * EventQueues.lookup(&quot;userNameEventQueue&quot;, EventQueues.APPLICATION, true).publish(new Event(&quot;onChangeSelectedObject&quot;, null, &quot;new Value&quot;));
 * </pre>
 *
 *
 * Spring bean declaration:
 *
 * <pre>
 * < !-- MessageBarCtrl -->
 * < bean id="messageBarCtrl" class="de.forsthaus.webui.util.MessageBarCtrl"
 *    scope="prototype">
 * < /bean>
 * </pre>
 *
 * since: zk 5.0.0
 *
 * @author sgerth
 *
 */
public class MessageBarCtrl extends GenericForwardComposer implements Serializable {

	private static final long serialVersionUID = 1L;
	/*
	 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	 * All the components that are defined here and have a corresponding
	 * component with the same 'id' in the zul-file are getting autowired by our
	 * 'extends GFCBaseCtrl' GenericForwardComposer.
	 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	 */
	protected Window winMessageBar; // autowired

	// Indicator column for message buttons
	private Column statusBarMessageIndicator;
	private Toolbarbutton btnOpenMsg;
	private Toolbarbutton btnSendMsg;

	private Window msgWindow = null;
	private String msg = "";
	private String userName;

	/**
	 * Default constructor.
	 */
	public MessageBarCtrl() {
		super();
	}

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

		try {
			userName = ((UserImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
		} catch (Exception e) {
			e.printStackTrace();
		}

		// Listener for incoming messages ( scope=APPLICATION )
		EventQueues.lookup("testEventQueue", EventQueues.APPLICATION, true).subscribe(new EventListener() {

			@Override
			public void onEvent(Event event) throws Exception {
				final String msg = (String) event.getData();

				// Check if empty, than do not show incoming message
				if (StringUtils.isEmpty(msg)) {
					return;
				}

				setMsg(msg);

				if (msgWindow == null) {

					/**
					 * If you whish to popup the incoming message than uncomment
					 * these lines.
					 */
					// getMsgWindow();
					// ((Textbox)
					// getMsgWindow().getFellow("tb")).setValue(getMsg());
					MessageBarCtrl.this.btnOpenMsg.setImage("/images/icons/incoming_message1_16x16.gif");
				} else {
					((Textbox) getMsgWindow().getFellow("tb")).setValue(getMsg());
				}
			}
		});

	}

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

		final Grid grid = new Grid();
		grid.setHeight("100%");
		grid.setWidth("50px");
		grid.setParent(this.winMessageBar);

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

		// Column for the Message buttons
		this.statusBarMessageIndicator = new Column();
		this.statusBarMessageIndicator.setWidth("50px");
		this.statusBarMessageIndicator.setStyle("background-color: #D6DCDE; padding: 0px");
		this.statusBarMessageIndicator.setParent(columns);
		Div div = new Div();
		div.setStyle("padding: 1px;");
		div.setParent(statusBarMessageIndicator);

		// open message button
		this.btnOpenMsg = new Toolbarbutton();
		this.btnOpenMsg.setWidth("20px");
		this.btnOpenMsg.setHeight("20px");
		this.btnOpenMsg.setImage("/images/icons/message2_16x16.gif");
		this.btnOpenMsg.setTooltiptext(Labels.getLabel("common.Message.Open"));
		this.btnOpenMsg.setParent(div);
		this.btnOpenMsg.addEventListener("onClick", new EventListener() {

			@Override
			public void onEvent(Event event) throws Exception {
				// 1. Reset to normal image
				btnOpenMsg.setImage("/images/icons/message2_16x16.gif");
				// 2. open the message window
				Window win = getMsgWindow();
				Textbox t = (Textbox) win.getFellow("tb");
				t.setText(getMsg());
				// Clients.scrollIntoView(t);

			}
		});

		// send message button
		this.btnSendMsg = new Toolbarbutton();
		this.btnSendMsg.setWidth("20px");
		this.btnSendMsg.setHeight("20px");
		this.btnSendMsg.setImage("/images/icons/message1_16x16.gif");
		this.btnSendMsg.setTooltiptext(Labels.getLabel("common.Message.Send"));
		this.btnSendMsg.setParent(div);
		this.btnSendMsg.addEventListener("onClick", new EventListener() {

			@Override
			public void onEvent(Event event) throws Exception {
				// open a box for inserting the message
				Window win = (Window) Path.getComponent("/outerIndexWindow");
				final String str = InputMessageTextBox.show(win);
				EventQueues.lookup("testEventQueue", EventQueues.APPLICATION, true).publish(new Event("onTestEventQueue", null, str));
			}
		});

	}

	// +++++++++++++++++++++++++++++++++++++++++++++++++ //
	// ++++++++++++++++ Setter/Getter ++++++++++++++++++ //
	// +++++++++++++++++++++++++++++++++++++++++++++++++ //

	public void setMsg(String msg) {
		this.msg = this.msg + "\n" + msg;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsgWindow(Window msgWindow) {
		this.msgWindow = msgWindow;
	}

	public Window getMsgWindow() {

		if (msgWindow == null) {
			msgWindow = new Window();
			msgWindow.setId("msgWindow");
			msgWindow.setTitle("Messages");
			msgWindow.setSizable(true);
			msgWindow.setClosable(true);
			msgWindow.setWidth("400px");
			msgWindow.setHeight("250px");
			msgWindow.setParent(winMessageBar);
			msgWindow.addEventListener("onClose", new EventListener() {

				@Override
				public void onEvent(Event event) throws Exception {
					msgWindow.detach();
					msgWindow = null;
				}
			});
			msgWindow.setPosition("bottom, left");
			Textbox tb = new Textbox();
			tb.setId("tb");
			tb.setMultiline(true);
			tb.setRows(10);
			tb.setReadonly(true);
			tb.setHeight("100%");
			tb.setWidth("98%");
			tb.setParent(msgWindow);

			msgWindow.doOverlapped();

		}

		return msgWindow;
	}
}

If you click on the left mail icon a little window comes up and shows all messages that comes in since the user was logged in.

window for showing the messages

window for showing the messages

After clicking on the right icon there comes a window up for inserting the message text to send.

window for writing and sending a message

window for showing the messages

The code for the InputMessageTextBox looks like this:

InputMessageTextBox.java

/**
 * This class creates a modal window as a dialog in which the user <br>
 * can input some text. By onClosing with <RETURN> or Button <send> this
 * InputConfirmBox can return the message as a String value if not empty. <br>
 * In this case the returnValue is the same as the inputValue.<br>
 *
 * @author bbruhns
 * @author sgerth
 */
public class InputMessageTextBox extends Window {

	private static final long serialVersionUID = 8109634704496621100L;
	private static final Logger logger = Logger.getLogger(InputMessageTextBox.class);

	private final Textbox textbox;
	private String msg = "";
	private String userName;

	/**
	 * The Call method.
	 *
	 * @param parent
	 *            The parent component
	 * @param anQuestion
	 *            The question that's to be confirmed.
	 * @return String from the input textbox.
	 */
	public static String show(Component parent) {
		return new InputMessageTextBox(parent).getMsg();
	}

	/**
	 * private constructor. So it can only be created with the static show()
	 * method.
	 *
	 * @param parent
	 * @param anQuestion
	 */
	private InputMessageTextBox(Component parent) {
		super();

		textbox = new Textbox();

		setParent(parent);

		try {
			userName = ((UserImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
		} catch (Exception e) {
			e.printStackTrace();
		}

		createBox();
	}

	private void createBox() {

		setWidth("350px");
		setHeight("150px");
		setTitle(Labels.getLabel("message.Information.PleaseInsertText"));
		setId("confBox");
		setVisible(true);
		setClosable(true);
		addEventListener("onOK", new OnCloseListener());

		// Hbox hbox = new Hbox();
		// hbox.setWidth("100%");
		// hbox.setParent(this);
		// Checkbox cb = new Checkbox();
		// cb.setLabel(Labels.getLabel("common.All"));
		// cb.setChecked(true);

		Separator sp = new Separator();
		sp.setParent(this);

		textbox.setWidth("98%");
		textbox.setHeight("80px");
		textbox.setMultiline(true);
		textbox.setRows(5);
		textbox.setParent(this);

		Separator sp2 = new Separator();
		sp2.setBar(true);
		sp2.setParent(this);

		Button btnSend = new Button();
		btnSend.setLabel(Labels.getLabel("common.Send"));
		btnSend.setParent(this);
		btnSend.addEventListener("onClick", new EventListener() {

			@Override
			public void onEvent(Event event) throws Exception {

				// Check if empty, than do not send
				if (StringUtils.isEmpty(StringUtils.trim(textbox.getText()))) {
					onClose();
					return;
				}

				msg = msg + ZksampleDateFormat.getDateTimeLongFormater().format(new Date()) + " / " + Labels.getLabel("common.Message.From") + " " + userName + ":" + "\n";
				msg = msg + textbox.getText();
				msg = msg + "\n" + "_____________________________________________________" + "\n";

				onClose();
			}
		});

		try {
			doModal();
		} catch (SuspendNotAllowedException e) {
			logger.fatal("", e);
		} catch (InterruptedException e) {
			logger.fatal("", e);
		}
	}

	final class OnCloseListener implements EventListener {
		@Override
		public void onEvent(Event event) throws Exception {
			onClose();
		}
	}

	// +++++++++++++++++++++++++++++++++++++++++++++++++ //
	// ++++++++++++++++ Setter/Getter ++++++++++++++++++ //
	// +++++++++++++++++++++++++++++++++++++++++++++++++ //

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getMsg() {
		return msg;
	}

}

It’s now at your hands to implement the logic for sending a message to a selected user or user groups in the InputMessageTextBox and the logic for listening only to the user’s account who is the receiver of the message in the MessageBarCtrl.

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 5

Coming soon…

Samples are hostet in the Zksample2 project on

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