Affichage des articles dont le libellé est Wicket. Afficher tous les articles
Affichage des articles dont le libellé est Wicket. Afficher tous les articles

samedi 12 juillet 2014

Custom lazy loading indicator for ajax processing with WICKET APACHE


One of the things we must take care of when we use AJAX is to notify user when an AJAX request is already in progress. This is usually done displaying an animated picture as activity indicator while the AJAX request is running.

Wicket comes with a variant of components that display a default activity indicator during AJAX request processing.These components are respectively IndicatingAjaxButton, IndicatingAjaxLink and
IndicatingAjaxFallbackLink. you can check the official documentation for more details.

Here i will show you my prefered way of making ajax lazy loading indicator : first i want to make global ajax indicator that will be displayed when any component in that page make an ajax process, then i want to display a specific ajax indicator for specific component like submit button, of course with custom indicator picture and styling.

Global AJAX indicator

if you want to show an ajax indicator when any component in a page does an ajax process just make the wicket page implement the interface IAjaxIndicatorAware then override the method getAjaxIndicatorMarkupId(), this method should return the markup id of div panel which contain the custom loading picture.

JAVA code

public class pageWithAjaxProcess extends WebPage implements IAjaxIndicatorAware { 
...
       @Override
public String getAjaxIndicatorMarkupId() {
              return "loadingIndicator_id";
}
....

HTML code

<div id="loadingIndicator_id" style="display:none;">
<img src="assets/lazyLoading.gif" width="48" height="48" alt="loading"/>
</div>

like this you can make your custom loading indicator, it is just a question of css styling.

Specific Ajax indicator

Sometimes we want to display a loading picture only  for submit button which has a long processing time, so we can use IndicatingAjaxButton component and we override its getAjaxIndicatorMarkupId() method for customizing its loading panel.




lundi 2 décembre 2013

Tuckey URL Rewrite


How can we make the web application URL cleaner and prettier instead of showing plenty of URL parameters? Is there a way  for a simple easy solution to do that without configuring the application server like Tomcat? after spending a long time of research and test, i found a tool named  Tuckey URL Rewrite that do exactly what i want.
My needs are the following, i have a java wicket web application with Tomcat 7 as webapp server and want to resolve two problems :

  1. First i would make pretty friend profile link as facebook or Google+, for example applicationName/Firstname.lastname , 
  2. Second, i want to implicitly add a dynamic parameter depending on the requested domain name for example :  SuchCustomer.domineName.com should be implicitly transformed to SuchCustomer.domineName.com?CustomertName=SuchCustomer

STEP ONE :

install Tuckey URL Rewrite by adding Maven dependency :
<dependency>
    <groupId>org.tuckey</groupId>
    <artifactId>urlrewritefilter</artifactId>
    <version>4.0.3</version>
</dependency>

STEP TWO :

To WEB-INF/web.xml add :
<filter>
    <filter-name>UrlRewriteFilter</filter-name>
    <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

STEP THREE :

Add urlrewrite.xml in WEB-INF (src/main/webapp/WEB-INF/ for Maven users)  , this file will contain all our rules. so to meet my needs, i write  this two rules:
<rule>
<note>Clean Friend profile URL</note>
<from>^/([a-z0-9]+)\.([a-z0-9]{1,10})$</from>
<to>/FriendProfile?friendLoginID=$1</to>
</rule>

<rule>
<name>Add parameter to URL</name>
<condition name="host" operator="equal">SuchCustomer.DomainName.com</condition>
<from>^/$</from>
<to>?CustomerName=SuchCustomer</to>
</rule>    

 For more information about this tool, take a look at the official documentation.

mercredi 27 novembre 2013

Event based communication between wicket components


when we have a page structured with multiple panels, we need some times to update a component into a one panel following an event into another different panel in the same page, so how can we fix this type of scenario?
Starting from version 1.5 Wicket offers an event-based infrastructure for inter-component
communication. The infrastructure is based on two simple interfaces (both in package org.
apache.wicket.event) : IEventSource and IEventSink.

FIRST sending an event:

The first interface must be implemented by those entities that want to broadcast en event while the
second interface must be implemented by those entities that want to receive a broadcast event.
The following entities already implement both these two interfaces (i.e. they can be either sender or
receiver): Component, Session, RequestCycle and Application.
IEventSource exposes a single method named send which takes in input three parameters:
  1. sink: an implementation of IEventSink that will be the receiver of the event.
  2. broadcast: a Broadcast enum which defines the broadcast method used to dispatch the event to the sink and to other entities such as sink children, sink containers, session object,application object and the current request cycle. It has four possible values:
    1. BREADTH: The event is sent first to the specified sink and then to all its children components following a breadth-first order.
    2. DEPTH: The event is sent to the specified sink only after it has been dispatched to all its children components following a depth-first order.
    3. BUBBLE: The event is sent first to the specified sink and then to its parent containers.
    4. EXACT: The event is sent only to the specified sink.
  3. payload: a generic object representing the data sent with the event.
Each broadcast mode has its own traversal order for Session, RequestCycle and Application.
The below example shows an event sending. This method can be used from any other component: First you need to create one class to encapsulate the notification and the AjaxRequestTarget and pass them using the events infrastructure.
 
private class Notification {
    private String message;
    private AjaxRequestTarget target;
    ... constructor, getters, setters...
}
 
 send(getSession(), Broadcast.BREADTH, new Notification(message, target));

NEXT Receiving the event : 

Interface IEventSink exposes callback method onEvent(IEvent<?> event) which is triggered
when a sink receives an event. The interface IEvent represents the received event and provides getter
methods to retrieve the event broadcast type, the source of the event and its payload. Typically the
received event is used checking the type of its payload object :
 
@Override
public void onEvent(IEvent event) {
    if (event.getPayload() instanceof Notification) {
        Notification notification = (Notification) event.getPayload();
        ... do whatever you want before updating the panel ...
        // Update the panel 
        notification.getTarget().add(this);
    }
}
 You find in this link a project named InterComponetsEventsExample provides a concrete example of sending an event to a component (named 'container in the middle') using all the available broadcast methods:

samedi 29 juin 2013

Change Wicket component behavior

Behaviors are kind of plug-ins for Components. They allow functionality to be added to a component and get essential events forwarded by the component. They can be bound to a concrete component (using the bind method which is called when the behavior is attached), but they don't need to. They can modify the components markup by changing the rendered ComponentTag. These are some of them : 
  1. AbstractAjaxTimerBehavior

  2. A behavior that generates an AJAX update callback at a regular interval. java doc

    WicketComponenet.add(new AbstractAjaxTimerBehavior(Duration.milliseconds(300)){
    @Override
    protected void onTimer(AjaxRequestTarget target) {
    // TODO Auto-generated method stub
    System.out.println("ajax here!");
    target.add(ComponentToModify);
    }});
    



  3. AjaxEventBehavior

  4. An ajax behavior that is attached to a certain client-side (usually javascript) event, such as onClick, onChange, onKeyDown, etc. Example:
    WebMarkupContainer div=new WebMarkupContainer(...);
             div.setOutputMarkupId(true);
             div.add(new AjaxEventBehavior("onclick") {
                 protected void onEvent(AjaxRequestTarget target) {
                     System.out.println("ajax here!");
                 }
             }
    
    This behavior will be linked to the onclick javascript event of the div WebMarkupContainer represents, and so anytime a user clicks this div the onEvent(AjaxRequestTarget) of the behavior is invoked. Java doc

  5. AjaxFormComponentUpdatingBehavior

  6. If you have a form component in wicket with some components and you want to change using ajax some things in that form before submit (when you click or edit on one of the components), then you have to use AjaxFormComponentUpdatingBehavior. This is a behavior that updates the hosting FormComponent via ajax when an event it is attached to is triggered.

    WicketComponenet.add(new AjaxFormComponentUpdatingBehavior("onchange"){ 
    @Override
    protected void onUpdate(AjaxRequestTarget target){
    // TODO 
    System.out.println("ajax here!"); 
    target.add(ComponentToModify);
    }}.setThrottleDelay(Duration.seconds(1))
    );
    ComponentToModify.setOutputMarkupId( true );
    

    The key is that your component must be a FormComponent, otherwise the event won't be triggered. Simple components like CheckBox, TextField, DropDownChoice are all FormComponents. Java Doc
    you should be careful to set setOutputMarkupId(true) of the component that will be modified after defining the behavior !

mardi 25 juin 2013

Wicket: Get Request Parameter from URL

In case you want to retrieve a value from the URL  , you can simply do it with Wicket 1.5  with one line of code :

StringValue game = RequestCycle.get().getRequest().getRequestParameters().getParameterValue("game");

there is also a several  paramters you can retrieve from URL like : 
  1. getClientUrl()
  2. getOriginalUrl()
  3. getUrl()
keep it simple,keep it clean  :)

Wicket PageParameters example

In Wicket 1.5 , you can use “PageParameters” class to store parameters values and pass it to another page. this is how you can do it :
first you should set your page parameters before redirection to be able then to receipt them in destination page

  @Override
  protected void onClick() {
 
   PageParameters pageParameters = new PageParameters();
   pageParameters.add("game", "Tombe Raider");
   setResponsePage(game.class, pageParameters);
 
  }

the next step is to capture these parameters into a method of destination page as follow :
String gameValue = pageParameters.get("game").toString();

that all :) !

jeudi 20 juin 2013

Get Request parameters with Wicket 1.5.x




To get the current request parameters (for example in Ajax behavior processing) in Apache Wicket 1.4:
    String parameterValue = RequestCycle.get().getRequest().getParameter(parameterName);
In 1.5 you have a better control where the parameter comes from:
   // GET request
   StringValue parameterValue = RequestCycle.get().getRequest().getQueryParameters().getParameterValue(parameterName);

   // POST request
   StringValue parameterValue = RequestCycle.get().getRequest().getPostParameters().getParameterValue(parameterName);

Or if you don't care about the method:
   StringValue parameterValue = RequestCycle.get().getRequest().getRequestParameters().getParameterValue(parameterName);

mardi 18 juin 2013

Wicket Motivations


Motivations :

Most existing web frameworks provide weak to non-existent support in managing server-side state

This normally means lots of ad-hoc code in web applications dealing with the gory mechanics of state management. While Wicket will not allow you to stop thinking about server state, it goes a long ways towards making it easy and often transparent to manage that state.
In Wicket, all server side state is automatically managed. You will never directly use an HttpSession object or similar wrapper to store state. Instead, state is associated with components. Each server-side page component holds a nested hierarchy of stateful components, where each component’s model is, in the end, a POJO (Plain Old Java Object). Wicket maintains a map of these pages in each user’s session. One purpose of this page map (and the component hierarchy on each page) is to allow the framework to hide all details of how your components and models are accessed. You deal with simple, familiar Java objects and Wicket deals with things like URLs, session ids and GET/POST requests.
You will also find that this well-structured server state makes it very easy to deal with the dreaded “back button problem”. In fact, Wicket has a generic and robust solution which can identify and expire browser-cached pages that have become stale due to structural changes to the model of a component on the page.
Finally, Wicket has been designed to work with POJO persistence frameworks such as JDO or Hibernate. This can make database driven web applications quite easy to write.
For many applications, it will be worth trading off the increased server load of extra server-side state for decreased development costs, lower maintenance costs, quicker time-to-market and generally higher quality software. The basic observation here is that software is expensive and complex while servers from companies like E-machines and Dell are relatively dirt cheap.
In terms of efficiency versus productivity, perhaps Wicket is to JSP as Java is to C. You can accomplish anything in Wicket in JSP. You may even do it more efficiently in terms of memory or processor consumption. But it may take you weeks or months longer to develop your application. And in the end, since state management in JSP is ad-hoc, you are likely find security problems and bugs popping up everywhere. Most of the other frameworks above will do only a little more to help you.

Most existing frameworks require special HTML code

JSP is by far the worst offender, allowing the embedding of Java code directly in web pages, but to some degree almost all of the frameworks from the list (except Tapestry) above introduce some kind of special syntax to your HTML code.
Special syntax is highly undesirable because it changes the nature of HTML from the kind of pure-and-simple HTML markup that web designers are familiar with, to some kind of special HTML. This special HTML can be more difficult to preview, edit and understand.
Wicket does not introduce any special syntax to HTML. Instead, it extends HTML in a standards-compliant way via a Wicket namespace that is fully compliant with the XHTML standard. This means that you can use Macromedia Dreamweaver, Microsoft Front Page, Word, Adobe Go Live, or any other existing HTML editor to work on your web pages and Wicket components. To accomplish this, Wicket consistently uses a single id attribute in the Wicket namespace (“wicket:id”) to mark HTML tags that should receive special treatment by the toolkit. If you prefer not to render Wicket namespaced tags and attributes to your end-users, Wicket has a simple setting to strip them all out, resulting in ordinary, standards-compliant HTML.
No “special sauce” in your HTML means designers can mock up pages that you can use directly in development. Adding Java components to the HTML is as simple as setting the component name attribute. And you can then give the HTML back to your web designers knowing that they can change it with confidence.
Wicket, more than any other framework gives you a separation of concerns. Web designers can work on the HTML with very little knowledge of the application code (they cannot remove the component name tags and they cannot arbitrarily change the nesting of components, but anything else goes). Likewise, coders can work on the Java components that attach to the HTML without concerning themselves with what a given page looks like. By not stepping on each other’s toes, everyone can get more work done.

Existing frameworks are not easy

Most of the existing toolkits have poorly defined or non-existent object models. In some cases, the model is defined using special XML syntaxes. The syntaxes may be so cumbersome that special tools are required to manipulate all the configuration information. Since these toolkits are not simple Java libraries you may or may not be able to use your favorite IDE tools such as editors, debuggers and compilers.
Wicket is all about simplicity. There are no configuration files to learn in Wicket. Wicket is a simple class library with a consistent approach to component structure. In Wicket, your web applications will more closely resemble a Swing application than a JSP application. If you know Java (and especially if you know Swing), you already know a lot about Wicket.

Existing frameworks inhibit reusability

Tapestry and JSF at least have component models that allow reuse, but you are likely to find that it is not particularly trivial to do, at least when compared with Wicket. Wicket has been explicitly designed to make it very, very easy to create reusable components. It’s surprisingly simple to extend existing components and to make compound components such as a SignInPanel or AddressForm. It is also relatively easy to create components that exploit new features of browsers. Components in Wicket can be packaged up in JAR files and reused by simply dropping them in your lib folder - no configuration necessary!

Web programming should be fun!

This is my most personal goal for writing Wicket . None of the existing frameworks are appealing to me in terms of intuitiveness, quickness, ease of development, etc. It is my hope that Wicket represents a significant step in the direction of making web applications easy and fun to write.




For more informations : Official wicket site

Introduction to Wicket



Why Wicket?


If you are looking to do web application programming in Java, you have a very large number of choices these days. In fact, there are so many web application frameworks now that it has become somewhat of a joke. One blog site on the Internet poses the question: How many Java web frameworks can you name? The answer they show looks like this:

Frameworks, Frameworks Everywhere

EchoCocoonMillstoneOXF
StrutsSOFIATapestryWebWork
RIFESpring MVCCanyamoMaverick
JPublishJATOFoliumJucas
VergeNiggleBishopBarracuda
Action FrameworkShocksTeaServletwingS
ExpressoBentojStatemachinejZonic
OpenEmceeTurbineScopeWarfare
JWAAJaffaJacquardMacaw
SmileMyFacesChibaJBanana
JeeniusJWarpGenieMelati
DovetailCameleonJFormularXoplon
JappleHelmaDinamicaWebOnSwing
NachoCassandraBaritusStripes
ClickGWT


Why “Reinvent the Wheel”?

In light of this, you may be wondering “What good is another web application framework?” Indeed. Why “re-invent the wheel?” One snappy comeback to that old saw is: because this time we could make it rounder!
But it was not simply a desire for higher quality that drove the creation of Wicket. Even with so many options, there really is no web toolkit which fills exactly the niche that Wicket fills. In fact, Wicket is quite unlike each of the frameworks above.
Wicket’s closest cousins are probably Tapestry and Echo, but even there the likeness is very shallow. Like Tapestry, Wicket uses a special HTML attribute to denote components, enabling easy editing with ordinary HTML editors. Like Echo, Wicket has a first-class component model. But Wicket applications are not like applications written in either Tapestry or Echo, because in Wicket you get the best of both worlds. You get the benefits of a first-class component model and a non-intrusive approach to HTML. In many situations, this combination may prove to be a significant development advantage.
To understand why Wicket is so different, it may help to understand the motivations that created it.