<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaBeat &#187; GWT</title>
	<atom:link href="http://www.javabeat.net/category/web-frameworks/gwt/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Fri, 24 May 2013 01:32:07 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>What is Model View Presenter (MVP) in GWT Application?</title>
		<link>http://www.javabeat.net/2011/11/what-is-model-view-presenter-mvp-in-gwt-application/</link>
		<comments>http://www.javabeat.net/2011/11/what-is-model-view-presenter-mvp-in-gwt-application/#comments</comments>
		<pubDate>Mon, 28 Nov 2011 23:50:29 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[GWT]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=2510</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This article is based on GWT IN Action, Second Edition (buy from amazon), published on May 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p><em>This article is based on <a href="http://www.manning.com/tacy/" target="_blank">GWT IN Action, Second Edition</a> (buy from <a href="http://astore.amazon.com/javabeat-20/detail/1933988231" target="_blank">amazon</a>), published on May 2011. It is being reproduced here by permission from <a href="http://www.manning.com" target="_blank">Manning Publications</a>. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information. [ <span style="color: red;"><span style="text-decoration: underline;"><strong>Use promotional code 'java40beat' and get 40% discount on eBooks and pBooks</strong></span> </span>]</em></p>
<h2>Introduction</h2>
<p>One of the main selling points of <strong>GWT</strong> is that it allows you to use an industry-grade language, with an industry-grade set of tools, to build&#8230;well&#8230;industry-grade web apps. But, as with any large scale development project, you can easily paint yourself into a corner. Far too many times when building <strong>GWT</strong>-based apps, we find ourselves slinging code wherever necessary to make the app work, and (sometimes more importantly) look good.</p>
<p>Fortunately, there is a well known solution to this problem: build your applications based on the model-view-presenter (MVP) paradigm.</p>
<p>Architecting your <strong>GWT</strong>-based apps to utilize the <strong>Model View Presenter (MVP)</strong> paradigm provides the foundation and rails necessary to avoid some common pitfalls.</p>
<p>Let&#8217;s see first how the user sees the application and then what we will be doing from the <strong>MVP</strong> perspective.</p>
<h2>From the user&#8217;s perspective</h2>
<p>Figure 1 shows the screens that can be found in our sample photo application.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/159.jpg"><img class="aligncenter size-medium wp-image-2514" title="1" src="http://www.javabeat.net/wp-content/uploads/2012/04/159-300x164.jpg" alt="" width="300" height="164" /></a></p>
<p><center><strong><span style="color: red;">Figure 1 The three views shown by the photo application. The user starts at the WelcomeView, clicks a button to see the PhotoListView, then clicking a photo brings up the PhotoDetailsView.</span></strong></center>When you start the application, you are taken to a welcome screen, where you can request a list of photos by clicking the View Photos button or going through the menu bar options. While the list of photos is being retrieved, a busy message is displayed to the user.</p>
<p>Our photographer seems to have been in one of their abstract moods for this photo set because these are all just blocks of color. You can click on one of the photos, and a larger version is shown on its own, and here you can edit the title through an editable label where the new title is saved back to the server, if requested.</p>
<p>It really is a nice way to see the underlying implementation using <strong>MVP</strong>.</p>
<h2>From the MVP perspective</h2>
<p>At its core, MVP is a design pattern that breaks your app up into the components listed in table 1, the right-hand column of which explains how this is done for PhotoApp.</p>
<p><strong><span style="color: red;">Table 1 Components of the MVP paradigm</span></strong></p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/229.jpg"><img class="aligncenter size-medium wp-image-2517" title="2" src="http://www.javabeat.net/wp-content/uploads/2012/04/229-300x228.jpg" alt="" width="300" height="228" /></a><a href="http://www.javabeat.net/wp-content/uploads/2012/04/327.jpg"><img class="aligncenter size-medium wp-image-2521" title="3" src="http://www.javabeat.net/wp-content/uploads/2012/04/327-300x130.jpg" alt="" width="300" height="130" /></a>The concept is that a presenter creates its associated view and requests the view to be populated with appropriate data from the model. When UI elements in the view are updated, they notify the presenter to change the model. This way, the view doesn&#8217;t need to know about the model, making it easy to swap and maintain.</p>
<p><strong>A quick note on connecting views and presenters</strong></p>
<p>The more contemporary <strong>MVP</strong> setup you may have read about in previous articles, blog posts, and so on, would indicate that presenters register to receive events raised from the view&#8217;s widgets.</p>
<p>However, you will see that we specifically make the presenter register itself in the view, and that the view notifies the presenter by calling appropriate registered presenter methods when events are raised.</p>
<p>Navigation to a new view is performed either by the application updating the URL in the browser as a result of the user doing something, or the user clicking the forward/back buttons. The application will react to changes in the browser&#8217;s URL and creating the appropriate presenter (which then creates the view). We will call this the Application Controller or AppController for short.</p>
<p>We will also make use of an EventBus. We&#8217;ll use this to raise application-wide events. To keep to the <strong>MVP</strong> paradigm, we need to be careful that these events do not cause changes in the model. What is their use then? Well, in our application we will allow various presenters to raise ApplicationBusy and ApplicationFree events, for example, when starting and completing communication with the server. These events will be dropped onto the EventBus by the presenters, and the AppController will listen for them and react by showing and hiding a busy message.</p>
<p><strong>Using a ClientFactory</strong></p>
<p>Throughout the two photo app projects, you will see us use a ClientFactory object. It will provide access to singleton instances to common objects across the application. For example, it provides access to our views as singleton objects, and this improves efficiency because views contain DOM calls, which are expensive.</p>
<p>There&#8217;s no requirement to use a ClientFactory in the <strong>MVP</strong> paradigm, but it is helpful if we are thinking of enterprise-wide development.</p>
<p>Between a presenter and its view, there is a strong connection, but loose coupling. Nice words, but what does it mean? Well, let&#8217;s crack open some of the photo apps code and have a look.</p>
<h2>Creating Views</h2>
<p>Remember that our view should have no application logic in it, at all. It should be just UI components that the presenter can access to set or get values from.</p>
<p>All of our views will be implemented as three separate items: a generic interface, a specific interface and an implementation. The next three sections will look at each of those in turn, starting with the generic interface.</p>
<h2>The root of all views</h2>
<p>Each of our views will be built upon a basic interface that we will call View. This is not a requirement to have, but suits us well as it creates a basic contract that all our views will adhere to, and that other components are aware of and can trust. Here it is:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public interface View extends IsWidget{
		void setPresenter(PhotoDetailsPresenter presenter);
	}</pre></td></tr></table></div>

<p>There are two key things to note about this interface. Any implementation must implement the setPresenter method – which allows the presenter to register itself with this view (this is the topic of section 14.1.3 so we will leave that for now). The other is that all our views will extends the IsWidget interface. This means each view will implement the asWidget method, which we will have to implement so that it returns a representation of the view that is a widget. Luckily, since most views will be made up from a Composite which, from <strong>GWT 2.1</strong> onwards, already implements asWidget, we are good to go with no extra work!</p>
<p>Each specific view needs to be described individually, and for that, we create first a new interface.</p>
<h2>View specific interface</h2>
<p>For each view we will have, we create a new interface that extends View. These view specific interfaces define the methods that a presenter can call to get access to the UI components. As an example, our PhotoDetailsView will have a title that can be changed and so the value of needs to be retrieved. We can make the interface show that by saying it must implement a getPhotoTitle method that returns an object implementing the HasValue&lt;String&gt; interface:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public interface PhotoDetailsView extends View {
		HasValue&lt;String&gt; getPhotoTitle();
	}</pre></td></tr></table></div>

<p>Our application has three views, so you can find the three interfaces in the source code, for example in the com.manning.gwtia.ch14.client.mvp.views package.</p>
<p>With the details of the views now specified in the interfaces, we need to implement them.</p>
<h2>Implementing the views</h2>
<p>Our view specific interfaces detail exactly what can be expected from the view. But without an implementation, they are not going to do much!</p>
<p>It turns out that our implementation of the PhotoDetailsView interface is pretty simple. That should be as expected as the view is dumb and contains no logic. The first two chapter examples are the same, except they differ in how views are implemented. In the first example, the implementations are verbose as we have a lot of boilerplate code; in the second, we have swapped the view implementation for UiBinder versions.</p>
<p>The only difference between the two versions is the use of UiBinder, and therefore how we bind events to actions. The actual actions do not change. Take the detailed view, each implementation implements the setPresenter method to register the parameter as this object&#8217;s presenter:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public void setPresenter(PhotoDetailsPresenter presenter) {
		this.presenter = presenter;
	}</pre></td></tr></table></div>

<p>Each view also implements a reaction to the title being changed. In the UiBinder approach it is neatly described as follows</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">	@UiHandler(&quot;title&quot;)
	public void changeTitle(ValueChangeEvent&lt;String&gt; event) {
		if (presenter != null){
			presenter.onUpdateTitle();
		}
	}</pre></td></tr></table></div>

<p>In other words, if the title widget raises a ValueChangeEvent, then as long as the presenter is not null, call the presenter&#8217;s onUpdateTitle method.</p>
<p>In the non UIBinder project, the same logic is there, but it is implemented by manually creating the title object and then adding a ValueChangeEvent handler to it. By convention, we tend to put all the binding code in a bind() method, if we are not using UIBinder.</p>
<p>So, our view is dumb and contains zero application logic. That is because we agreed that all of that should appear only in the presenter. And this brings us to the discussion of those presenters.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h2>Presenters</h2>
<p>Presenters are where all the application logic sits and will have no UI components. (Those are all in the view, as we&#8217;ve just seen.) In a similar way to views, we provide a generic presenter interface, a specific one, and an implementation for each presenter.</p>
<h2>The root of all presenters</h2>
<p>Just like views, we will create a basic interface that all of our presenters will implement. Again, there is no requirement to do this; it is just good to have. Here&#8217;s our basic interface:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public interface Presenter{
		public void go(final HasWidgets container);
		public void bind();
	}</pre></td></tr></table></div>

<p>The go method takes the widget in which we wish the presenter-associated view associated to be displayed. All we require of that widget is that it implements the HasWidgets interface; in other words, it is a panel of some kind.</p>
<p>A presenter will also implement a bind method. In our design, this is where the presenter will listen to any application-wide events it is interested in (for example, this is where it hooks into the event bus) as well as where it calls the associated views setPresenter method.</p>
<p>Each view will have an associated specific interface.</p>
<h2>Presenter-specific interface</h2>
<p>The specific functionality of the view is given in a new interface that implements Presenter.</p>
<p>In the specific presenter interface we wish to declare those methods that will be called from the view when things happen. Remember that we said the view is responsible for reacting to UI events within itself, but that it will then call methods on the presenter that was registered with it for the actual business logic. Here, we see the PhotoDetailsPresenter interface relating to the title:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public interface PhotoDetailsPresenter implements Presenter{
		public void onUpdateTitle();
	}</pre></td></tr></table></div>

<p>What we are saying here is that we expect the onUpdateTitle method to be called when the title is updated in the view. We would add other methods to the interface based on the other UI components that are of interest.</p>
<p>Now we have the specific presenter interface in place, we should implement it.</p>
<h2>Implementing specific presenters</h2>
<p>Our presenters are just implementations of the specific presenter interfaces. For example, PhotoDetailsPresenterImpl implements the PhotoDetailsPresenter interface.</p>
<p>This means it needs to implement the go and bind method from Presenter as well as the onUpdateTitle from PhotoDetailsPresenter. Listing 1 shows the skeleton of our implementation.</p>
<p><strong><span style="color: red;">Listing 1 PhotoDetailsPresenter</span></strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public class PhotoDetailsPresenterImpl implements PhotoDetailsPresenter {
private ClientFactory clientFactory = GWT.create(ClientFactory.class);
public PhotoDetailsPresenterImpl(final PhotoDetailsView photoDetailsView
, final String id) {
this.rpcService = clientFactory.getPhotoServices(); |#1
this.eventBus = clientFactory.getEventBus(); |#1
this.photoDetailsView = photoDetailsView; |#1
eventBus.fireEvent(new AppBusyEvent()); #2
rpcService.getPhotoDetails(……) #3
bind();
}
public void bind() {
photoDetailsView.setPresenter(this); #4
}
public void go(final HasWidgets container) { |#5
container.clear(); |#5
container.add(photoDetailsView.asWidget()); |#5
} |#5
public void onUpdateTitle() { |#6
rpcService.savePhotoDetails(……); |#6
} |#6
}
#1 Getting shared resources
#2 Firing application wide event
#3 Making a server call
#4 Binding to other items
#5 Implementing the go method
#6 Called from View when title updated</pre></td></tr></table></div>

<p>The first thing that is done in the constructor is to get hold of some common resources from the ClientFactory that we previously mentioned. This is not a requirement but makes our lives easier. For example, we grab resources such as the RPC service and the event bus—we might as well share the RPC service for efficiency, and we have to share the event bus; otherwise, it would not be system wide.</p>
<p>Once we have grabbed our resources from the factory, we make a call to get the details of the photo just after we have fired off a system-wide ApplicationBusy event. The intention here is that some other component will inform the user that the application is busy in some way—we don&#8217;t care at this point how that is done. Not shown in listing 1 is the fact that an ApplicationFree event is fired within the RPC return handling code so that the user is notified the application is no longer busy.</p>
<p>Within the constructor, we also call the bind method from the Presenter interface. For this implementation, that simply calls the view&#8217;s setPresenter method to register this view with that presenter. Other implementations may register on the event bus if it has to handle application wide events.</p>
<p>In #5, we are implementing the Presenter&#8217;s go method. This clears the container widget passed in as the parameter and then adds the associated view as a widget. In the application controller, we will create presenters in the following manner:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">new PhotoDetailsPresenterImpl(clientFactory.getDetailsView()).go(container)</pre></td></tr></table></div>

<p>Where container is the widget that we wish the presenter to present in the view.</p>
<p>That&#8217;s it really for the views and presenters. Just before we jump to the AppController, which is responsible for tying everything together and starting presenters, we want to take a little deeper look at the relationship between presenter and views we have used.</p>
<h2>The two-way presenter/view relationship</h2>
<p>At the heart of the <strong>MVP</strong> pattern is the relationship between your presenters and views. Presenter classes should contain all of your complex application logic, and no widget code/references. Completely inverse to that, your views should contain nothing more than widgets, and should avoid any application logic wherever possible.</p>
<p>Why? For two reasons: 1) fast testing with increased code coverage and 2) maximum code reuse when porting to other Java based platforms, for instance Android (written carefully in the <strong>MVP</strong> paradigm, the application logic of a <strong>GWT application</strong> can be reused and all you need to do is just replace the view component).</p>
<p>If you look at testing, enforcing this split between presenters and views offers another way to save more time/money/development frustration. Whenever you find yourself needing to test functionality within your app that relies on widgets or some Javascript Native Interface (JSNI), you&#8217;re going to need a browser context. This means you&#8217;re going to need to run it within a GWTTestCase, which means—you guessed it—it&#8217;s going to take a long time to run that test. So how do we fix this? Simple. Let&#8217;s not test them at all—if you make the view as dumb as possible, by moving all of your app logic out into the presenter, you should be left with a view that contains nothing more than <strong>GWT</strong> widgets. Given that these are continuously tested by the <strong>GWT</strong> team, doing so in our own tests is simply redundant and not required. And, where you do need to test your views, those tests should be few and far between and, in many instances, simply integration testing being driven by Selenium (or some Selenium-like testing suite).</p>
<p>Now that we agree on moving the app logic out of the view, we have to move the view logic out of the presenter. More specifically, we have to make sure our presenters are solely relying on plain old Java code. This is to ensure that they can be tested using a vanilla JUnit test (which runs in ~1/1000th of the time of a GWTTestCase).</p>
<p>But, we are also making the relationship between view and presenters slightly differently to what you might expect. The more contemporary MVP setup you may have read about in previous articles, blog posts, and so on, would indicate that presenters register to receive events from the view&#8217;s widgets.<br />
However, you can see in the code above, we specifically make the presenter register itself in the bind method with the view via the view&#8217;s setPresenter method, and that the view listens for events and then calls the appropriate method in the presenter.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/427.jpg"><img class="aligncenter size-medium wp-image-2524" title="4" src="http://www.javabeat.net/wp-content/uploads/2012/04/427-300x177.jpg" alt="" width="300" height="177" /></a></p>
<p><center><span style="color: red;">Figure 1 The coupling between presenter and view in our photo application.</span></center>Technically there is no reason not to make the presenter listen for events from the view widgets. But allowing the view to call back into the presenter makes using the UIBinder approach easy, as you can see in figure 1.</p>
<p>Up until now we have views and presenters for our PhotoApp, but we have no way of knowing what presenter to request (so no idea what view to show), or react to the user changing views. For that, we need to control the application.</p>
<h2>Controlling the application</h2>
<p>We need a mechanism to change views in our application. The most common one is to indicate in the browser URL the new view required, usually via a token on the URL, and then to react to that.</p>
<p>In our presenters, if a view change is needed, we will change the history token to an appropriate value. This happens, for example, when selecting a photo in the Photo List view. The click on a photo is registered in PhotoListViewImpl, which then calls back to the presenter saying which photo is selected. In the PhotoListPresenterImpl code, we have:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public void onSelectPhotoClicked(String id) {
History.newItem(Tokens.DETAIL + &quot;&amp;&quot; + id);
}</pre></td></tr></table></div>

<p>All we are doing here is changing the history token to have a value defined in the Tokens class to represent Photo Detail view appended by the photo id the user is interested in. If we&#8217;re interested in photo number 00004, then our development mode URL becomes as shown in figure 2.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2012/04/5.bmp"><img class="aligncenter  wp-image-2513" title="5" src="http://www.javabeat.net/wp-content/uploads/2012/04/5.bmp" alt="" width="442" height="152" /></a></p>
<p><center></center><center><span style="color: red;">Figure 2 Development mode URL after photo 00004 has been selected to be shown in the detailed view</span></center>If we&#8217;re using history to store tokens, then we must set up our <strong><a href="http://www.javabeat.net/articles/238-history-management-in-gwt-1.html">GWT history management</a></strong> to handle history changes and fire up the appropriate presenter. We do that in the AppController class, as shown in listing 2.</p>
<p><strong><span style="color: red;">Listing 2 AppController showing bind() to History and other events</span></strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public class PhotoAlbumApp implements ValueChangeHandler&lt;String&gt; { #1
	private void bind() {
		:
		History.addValueChangeHandler(this); #1
		}
		public void onValueChange(ValueChangeEvent&lt;String&gt; event) { |#2
		String token = event.getValue(); |#2
		if (token != null) { |#2
		if (token.startsWith(&quot;details&quot;)) |#2
		doPhotoDetailsDisplay(token); |#2
		else if(token.startsWith(”list”)) |#2
		: |#2
		} |#2
	} |#2
	private void doPhotoDetailsDisplay(String token){} |#3
	private void doPhotoListDisplay(String token){} |#3
	private void doWelcomeDisplay(String token){} |#3
}
#1 Implementing the History Management
#1 Binding events to actions in the code
#2 Handling history changes
#3 Changing the view</pre></td></tr></table></div>

<p>The AppController binds itself to listen to listen to history events in #1 by implementing the ValueChange interface as well as adding this object as the ValueChangeHandler in the History.</p>
<p>We must implement the onValueChange method (#2), which is called when the history changes by GWT&#8217;s history subsystem. This method we set up to simply parse the history token to determine what view is requested, and then is required, and will call one of the do methods in #3, if the history token is recognized and an action can be determined.</p>
<p>These do methods are responsible for creating the view and the presenter, and then calling the presenter&#8217;s go method. For example, if we have changed to the situation in figure 2, then the onValueChange method determines that the value detail means it needs to call the doPhotoDetailsDisplay method. This action shows the user the new photo details view with the requested image, while the AppController sits there waiting for the next history change.</p>
<h2>Summary</h2>
<p>The <strong>MVP</strong> pattern is extremely useful when building large, web-based applications with <strong>GWT</strong>. Not only does it help make code more readable, and subsequently more maintainable, it also makes it much easier to implement new features, optimizations, and automated testing. Speaking from experience, we can&#8217;t stress the testing benefits enough. It&#8217;s a fundamental part of writing real-world applications, but often times it&#8217;s overlooked because it&#8217;s left until the end, and is too much of a pain to integrate. When your app is developed using the <strong>MVP</strong> pattern, test cases are a piece of cake, so much so that you&#8217;ll want to write them first. Remember, test driven development is your friend.</p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fweb-frameworks%2Fgwt%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/web-frameworks/gwt/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/web-frameworks/gwt/feed/" data-count="vertical" data-text="GWT" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/11/what-is-model-view-presenter-mvp-in-gwt-application/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to create widget in GWT 2.0?</title>
		<link>http://www.javabeat.net/2011/11/how-to-create-widget-in-gwt-2-0/</link>
		<comments>http://www.javabeat.net/2011/11/how-to-create-widget-in-gwt-2-0/#comments</comments>
		<pubDate>Mon, 28 Nov 2011 23:48:24 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[GWT]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=2476</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This article is based on GWT IN Action, Second Edition (buy from amazon), published on May 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><em>This article is based on <a href="http://www.manning.com/tacy/" target="_blank">GWT IN Action, Second Edition</a> (buy from <a href="http://astore.amazon.com/javabeat-20/detail/1933988231" target="_blank">amazon</a>), published on May 2011. It is being reproduced here by permission from <a href="http://www.manning.com" target="_blank">Manning Publications</a>. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information. [ <span style="color: red;"><span style="text-decoration: underline;"><strong>Use promotional code 'java40beat' and get 40% discount on eBooks and pBooks</strong></span> </span>]</em></p>
<h2>Introduction</h2>
<p>With <strong>GWT</strong> v2, it is going to be a rare occasion where you need to create a widget directly from the Document Object Model (DOM). This is because <strong>GWT</strong> 2.0 covers nearly all the widgets we can think of. If you are using a <strong>GWT</strong> version lower than 2.0 then you may find some things missing (such as a widget wrapping the SPAN element—GWT 2.0 provides InlineLabel, which does that).</p>
<p>We will look a little into the future and show how to implement a Canvas widget. (You can tell <strong>GWT</strong> is quite swift moving because <strong>GWT</strong> 2.2 now provides this type of widget, but we will stick to creating it ourselves to explore some of the points related to creating a widget from the DOM.) A canvas element in HTML allows us to draw two- dimensional objects and bitmaps on the browser screen. Figure 1 shows an example of our Canvas widget in action as it draws a square on the screen.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/158.jpg"><img class="aligncenter size-medium wp-image-2495" title="1" src="http://www.javabeat.net/wp-content/uploads/2012/04/158-300x277.jpg" alt="" width="300" height="277" /></a></p>
<p><center><strong><span style="color: red;">Figure 1 Canvas widget in action</span></strong></center>We won&#8217;t include any error checking in our definition and assume you are using a canvas-aware browser such as Chrome, Firefox, Safari, or Opera. If you are using Internet Explorer, then you could use Google&#8217;s ChromeFrame until IE catches up (otherwise, this example will not work). Listing 1 shows our Canvas widget in full.</p>
<p><strong><span style="color: red;">Listing 1 An example Canvas widget</span></strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package org.gwtbook.client;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
public class Canvas extends Widget { #1
public Canvas() { #2
Element element = Document.get().createElement(&quot;canvas&quot;);
setElement(element);
setStyleName(&quot;canvas-style&quot;);
context = getCanvasContext(element);
}
protected Canvas(Element element) { #3
setElement(element);
assert element.getTagName().equalsIgnoreCase(&quot;canvas&quot;);
}
public static Canvas wrap(Element element) { #4
assert Document.get().getBody().isOrHasChild(element);
Canvas canvas = new Canvas(element);
canvas.onAttach();
RootPanel.detachOnWindowClose(canvas);
canvas.context = canvas.getCanvasContext(element);
return canvas;
}
JavaScriptObject context;
public native void fillRect(int top, int left,
int width, int height)/*-{
this.@org.gwtbook.client.Canvas::context.fillRect(top,left,
width,height);
}-*/;
public native void fillStyle(String fillStyle)/*-{
this.@org.gwtbook.client.Canvas::context.fillStyle = fillStyle;
}-*/;
protected native JavaScriptObject getCanvasContext
(Element element)/*-{ #5
return element.getContext('2d');
}-*/;
}
#1 Extending the Widget class
#2 Creating a new Widget
#3 Private constructor
#4 Wrapping an existing canvas element</pre></td></tr></table></div>

<p>Widgets will extend the Widget class (#1). Most <strong>GWT widgets</strong> contain two ways to create them: a public constructor used for creating a new widget (#2) from scratch and a protected constructor that creates a widget from an existing element in the DOM (#3).</p>
<p>When creating a new widget, there are generally three steps. First, we create the DOM element. At #2, we use Document.get().createElement(”canvas”)) to create a canvas element. Then, we call the Widget class&#8217;s setElement method to bind the element to the widget. After this, we set a style name for the widget. For this widget, we chose the base style name canvas-style.</p>
<p>Typically, a widget would now be complete and ready for use. In our case, we need to take an extra step to get the canvas&#8217;s 2D context which is used in later drawing methods. We do that by calling getCanvasContext method, defined at #5 using JSNI.</p>
<p>With everything defined, creating the square in figure 1 in a browser that supports canvas can be created using:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">Canvas c = new Canvas();
	c.setPixelSize(400, 400);
	RootPanel.get().add(c);
	c.fillStyle(&quot;rgb(80,255,80)&quot;);
	c.fillRect(10, 20, 100, 50);</pre></td></tr></table></div>

<p>This code creates a new Canvas widget instance, sets its size, adds it to the RootPanel, and then uses two specific methods we defined in the widget to set the fill style and draw the rectangle.</p>
<p>If we had the following HTML in the body of our application&#8217;s HTML file</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;canvas id=&quot;demo-canvas&quot; width=&quot;400&quot; height=&quot;400&quot;&gt;&lt;/canvas&gt;</pre></td></tr></table></div>

<p>Then we could use the wrap method to create the widget. We get the same result as figure 1 using the following code instead of the code above.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">Canvas c = Canvas.wrap(RootPanel.get(&quot;demo-canvas&quot;).getElement());
	c.fillStyle(&quot;rgb(80,255,80)&quot;);
	c.fillRect(10, 20, 100, 50);</pre></td></tr></table></div>

<p>The wrap method in listing 1 (#4) is copied here.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public static Canvas wrap(Element element) {
		assert Document.get().getBody().isOrHasChild(element); #1
		Canvas canvas = new Canvas(element); #2
		canvas.onAttach(); #3
		RootPanel.detachOnWindowClose(canvas); #3
		return canvas;
	}</pre></td></tr></table></div>

<p>It first asserts the element passed as the argument is attached to the DOM (#1). If it is, then it calls the protected Canvas constructor (#2), which binds the element to the widget and asserts that it is indeed a canvas element. Once the widget is constructed, we need to manually call two housekeeping methods that <strong>GWT</strong> would normally call for us (#3).</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Because the widget is already attached to the DOM, then we need to call the widget&#8217;s onAttach method ourselves to link it into <strong>GWT</strong> cradle. We also need to manually register the widget with the RootPanel&#8217;s detachOnWindowClose method so it is removed safely if the browser window is closed.</p>
<p>Our widget is effectively complete. You could extend it further to implement other canvas functionality, and perhaps use some deferred binding to cope with Internet Explorer&#8217;s lack of canvas implementation. We should, though, look at two other things—the functionality that the widget declared will implement and how events are handled.</p>
<h2>Indicating functionality</h2>
<p>There are a number of Java interfaces that a widget can implement to tell the world it has certain functionality. You don&#8217;t need to make your widget implement any of these interfaces, but it does help to adhere to the <strong>GWT</strong> style, and do so.</p>
<p>The HasText interface indicates the widget has some text, and that we can expect to be able to call the setText method to change that text and the getText method to retrieve the text value.</p>
<p>When you create a new widget, you should consider what interfaces the widget should implement. Some of these are shown in table 1 along with an indication of which package they are in to help you find others.</p>
<p><strong><span style="color: red;">Table 1 An overview of some of the interfaces a widget can implement to provide indication of functionality.</span></strong></p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/226.jpg"><img class="aligncenter size-medium wp-image-2497" title="2" src="http://www.javabeat.net/wp-content/uploads/2012/04/226-300x218.jpg" alt="" width="300" height="218" /></a><a href="http://www.javabeat.net/wp-content/uploads/2012/04/325.jpg"><img class="aligncenter size-medium wp-image-2499" title="3" src="http://www.javabeat.net/wp-content/uploads/2012/04/325-300x220.jpg" alt="" width="300" height="220" /></a><a href="http://www.javabeat.net/wp-content/uploads/2012/04/425.jpg"><img class="aligncenter size-medium wp-image-2501" title="4" src="http://www.javabeat.net/wp-content/uploads/2012/04/425-300x79.jpg" alt="" width="300" height="79" /></a>For our canvas widget, there are no <strong>GWT interfaces</strong> we need to implement but, next, we&#8217;ll hook up an event and so use the HasMouseOverHandler interface.</p>
<h2>Hooking up events</h2>
<p>Hooking up events is simple. We introduce the appropriate HasXXXXXHandler interface, and then provide an addXXXXXHandler method that calls the addDOMHandler method. (Since our widget extends Widget, this is available to us.)</p>
<p>To show this in practice, let&#8217;s add the ability to handle mouse over events to our Canvas widget (see listing 2).</p>
<p><strong><span style="color: red;">Listing 2 An example Canvas widget</span></strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package com.gwtbook.client.ui;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
public class Canvas extends Widget
implements HasMouseOverHandler { #1
public HandlerRegistration |#2
addMouseOverHandler(MouseOverHandler handler){ |#2
return
this.addDomHandler(handler, MouseOverEvent.getType()); #3
}
public Canvas() {
:
See listing 1 for rest of Canvas code
:
}
#1 Creating a new Widget
#2 Defining the BookBar class
#3 Wrapping an existing canvas element
&nbsp;
Now, if we run our example code with a little addition—
&nbsp;
&nbsp;
final Canvas c = new Canvas();
c.setPixelSize(400, 400);
RootPanel.get().add(c);
c.fillStyle(&quot;rgb(80,255,80)&quot;);
c.fillRect(10, 20, 100, 50);
c.addMouseOverHandler(new MouseOverHandler(){
public void onMouseOver(MouseOverEvent event){
c.getElement().getStyle().setBackgroundColor(”lightblue”);
}
});</pre></td></tr></table></div>

<p>And put the mouse over the widget, we get figure 2 as the result.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/523.jpg"><img class="aligncenter size-full wp-image-2492" title="5" src="http://www.javabeat.net/wp-content/uploads/2012/04/523.jpg" alt="" width="255" height="237" /></a></p>
<p><center><strong><span style="color: red;">Figure 2 Result of moving the mouse over the updated canvas widget.</span></strong></center></p>
<h2>Summary</h2>
<p>We created a widget from scratch to represent a DOM element. We mentioned that it is unlikely you will have to do this because GWT already provides widgets for most DOM elements already.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/11/how-to-create-widget-in-gwt-2-0/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Code Splitting in GWT</title>
		<link>http://www.javabeat.net/2011/11/code-splitting-in-gwt/</link>
		<comments>http://www.javabeat.net/2011/11/code-splitting-in-gwt/#comments</comments>
		<pubDate>Mon, 28 Nov 2011 23:45:15 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[GWT]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=2471</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This article is based on GWT IN Action, Second Edition (buy from amazon), published on May 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><em>This article is based on <a href="http://www.manning.com/tacy/" target="_blank">GWT IN Action, Second Edition</a> (buy from <a href="http://astore.amazon.com/javabeat-20/detail/1933988231" target="_blank">amazon</a>), published on May 2011. It is being reproduced here by permission from <a href="http://www.manning.com" target="_blank">Manning Publications</a>. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information. [ <span style="color: red;"><span style="text-decoration: underline;"><strong>Use promotional code 'java40beat' and get 40% discount on eBooks and pBooks</strong></span> </span>]</em></p>
<h2>Introduction</h2>
<p>Back in 2006 when <strong>GWT</strong> was released, it solved a lot of the traditional problems for developing large JavaScript applications. So great was the promise that developers began to develop massive <strong>GWT</strong> applications—so massive, in fact, that they started hitting a wall. The wall they hit had to do with the size of the application.</p>
<p>If you think about your traditional desktop application like Microsoft Word, there are so many features of that application that you don&#8217;t normally use. For instance, the Mail Merge tool within Microsoft Word is extremely useful when you need that functionality, but most users rarely use it if at all. So the first question is how do we load only the functionality that will be used?.</p>
<p>Another common engineering issue was how to decrease the load time of the application. It is common for a feature full <strong>GWT</strong> application to approach a megabyte in size. With broadband, this is generally a fast download, but at the same time users have higher expectations that they did with their 56K modem. Users now judge the speed of your application in hundreds of milliseconds and not seconds. If your application takes a full second to start up, it may be considered as being sluggish. So how can you decrease the start time?.</p>
<p>This is where <strong>code splitting</strong> comes in. If you can cut your code into multiple segments, you can kill two birds with one stone. A smaller initial download means faster startup, and loading less-often accessed code only when it loads means smaller total downloads.</p>
<p>We begin our discussion by explaining the basics of using <strong>code splitting</strong>, then delve deeper and explore a coding pattern that has proven useful for segmenting your application.</p>
<h2>Understanding code splitting basics</h2>
<p><strong>code splitting</strong> in theory is really very simple to understand. You wrap a piece of code in an asynchronous block, much like you would do with an RPC call, and let the compiler handle the rest. Let&#8217;s start with an example, listing 1, so that we can see what we are talking about.</p>
<p><strong><span style="color: red;">Listing 1 An extremely simple example of code splitting</span></strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">RunAsyncCallback callback = new RunAsyncCallback() { |#1
	public void onSuccess () { |#2
	doStuff();
	}
	public void onFailure (Throwable reason) { |#3
	Window.alert(&quot;Error: &quot; + reason.getMessage());
	}
	};
	GWT.runAsync(callback); |#4
	#1 Creates callback
	#2 Defines success handler
	#3 Defines error handler
	#4 Loads and executes</pre></td></tr></table></div>

<p>This example literally covers the entire <strong>code splitting API</strong>. Even though it is extremely simple, let&#8217;s walk through the example and provide some commentary. As shown in the example, we first create a RunAsyncCallback instance (#1). RunAsyncCallback is an interface that is very similar to the asynchronous interfaces used by RPC, like AsyncCallback and RequestCallback, in that it has methods for handling success and errors.</p>
<p>The success handler onSuccess() (#2) is called when the JavaScript fragment, called a split point, is successfully loaded from the server and is ready to be run. This is also where the compiler determines where to split your code. Of course it, isn&#8217;t quite that cut and dry due to dependencies, which we will discuss shortly.</p>
<p>The error handler onFailure() [#3] is called when the split point fails to load. The typical cause of this would be because the network is not available or the site is not reachable. This could occur frequently for mobile users, where they might start using your application from a Wi-Fi hot spot, then trigger a split point after leaving the hot spot. Here, we simply show an alert pop-up, but it is probably a good idea to think about how your application should handle these errors.</p>
<p>Once the callback is defined, all we need to do is call <em>GWT.runAsync()</em> (#4) to trigger the loading and execution of the split point. In addition to loading the split point, there may also be some leftover code that also needs to be loaded. During compiling, there may be some code that doesn&#8217;t fit in a single split point and instead is shared across more than one. This is called leftover code and will be loaded prior to any split point code.</p>
<h3>What is GWT.runAsync()?</h3>
<p>To get your code split, simply insert calls to GWT.runAsync() at the places where you want the program to be able to pause for downloading more code. These locations are called split points.</p>
<p>For example, here is the initial, unsplit Hello sample that comes with GWT:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public class Hello implements EntryPoint {
	  public void onModuleLoad() {
		Button b = new Button(&quot;Click me&quot;, new ClickHandler() {
		  public void onClick(ClickEvent event) {
			Window.alert(&quot;Hello, AJAX&quot;);
		  }
		});
&nbsp;
		RootPanel.get().add(b);
	  }
	}</pre></td></tr></table></div>

<p>To visualize this, add a few split points to a <strong>GWT</strong> application then compile the code and generate a Compile Report. You can turn on generation of the Compile Report add the compiler switch –compileReport.</p>
<p>An example of what you might see on the Compile Report if you had two split points is shown in figure 1.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2012/04/11.bmp"><img class="aligncenter  wp-image-2511" title="1" src="http://www.javabeat.net/wp-content/uploads/2012/04/11.bmp" alt="" width="534" height="265" /></a></p>
<p><center></center><center><strong><span style="color: red;">Figure 1 Here is an example of a Compile Report showing two split points. It shows the size of the initial download, the two split points, and leftover code that is shared between the split points.</span></strong></center>The initial download size for this permutation is only about 24 KB, which, compared to the total code size of 292 KB, is a significant improvement. In addition, you will see that there is 62 KB worth of leftover code. The leftover code is code that is shared by more than one split point and isn&#8217;t needed in the initial download. And, finally, there are two split points, one of 141 KB and another of 64 KB. So there are four total JavaScript files, each containing some portion of the total application.</p>
<p>If you just drop this into one of your own applications, it is likely you won&#8217;t see results quite as good as these. These results are from a simple test application where the initial download has relatively no functionality, and the code within the split points have no dependencies on each other. In fact, what you are more likely to see is something in figure 2.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/228.jpg"><img class="aligncenter size-medium wp-image-2512" title="2" src="http://www.javabeat.net/wp-content/uploads/2012/04/228-300x148.jpg" alt="" width="300" height="148" /></a></p>
<p><center><strong><span style="color: red;">Figure 2 Another example of a Compile Report, but this time interclass dependencies have caused the full application to be included in the initial download.</span></strong></center>Unless you planned ahead you will likely see something closer to figure 2 where essentially the entire application is in the initial download. But why does this happen? You may have guessed that the culprit is interclass dependencies. Most developers don&#8217;t think about interclass and interpackage dependencies so much. Usually the focus is on interlibrary dependencies (aka jars).</p>
<p>Tracking down dependencies can be done using the Compile Report, but there is also a pattern we can rely on, the Async Package pattern.</p>
<h2>Using the Async Package pattern</h2>
<p>The intent of the Async Package pattern is to place collaborating classes within a Java package, then restrict access to classes within that package so that they can only be used asynchronously as a split point.</p>
<p>The motivation is that we want to create a split point that contains a particular segment of our code base, and we want to do so in a way that makes it difficult or impossible to create code dependencies that will cause the segmented code to be required by other segments. This is useful for development teams with multiple programmers, where you want to ensure that one developer can&#8217;t undo the work done by another. This is also useful for a single developer who wants to keep the application easy to maintain, so that enhancements added months from now don&#8217;t cause your split points to become dependent on each other.</p>
<p>If we were to boil this pattern to a recipe, it would consist of these bullet points.</p>
<ul>
<li>Isolate collaborating classes within a package.</li>
<li>Remove all static methods.</li>
<li>Create a single gateway class with a private constructor.</li>
<li>Instantiate the gateway only within a GWT.runAsync() call.</li>
</ul>
<p>The general idea is that all access to that package must first require the creation of the gateway class using <em>GWT.runAsync()</em>. By doing this, you ensure that your split point can&#8217;t be broken from users calling into the package. The first step in implementing this pattern is to isolate classes within a package from the outside world.</p>
<h2>Isolating collaborating classes</h2>
<p>Of course, we do this all the time in Java. We make use of keywords like protected and private to hide methods and fields from unrestricted use. By providing access where it is really needed, our code becomes inherently easier to maintain. A private method can always be renamed with the assurance that it won&#8217;t affect anything outside of the class. And the type of a protected field can be altered knowing that it only affects classes in the same package and subclasses.</p>
<p>The Async Package pattern makes use of Java&#8217;s access tools by restricting access to the set of classes that will become our split point. Locking down the classes in your package should be fairly straightforward for Java developers, so we won&#8217;t say much about that other than that you should make use of protected and default access to prevent outside access.</p>
<p>Ideally, you would plan out your split points ahead of time, but as with many things it isn&#8217;t always predictable ahead of time where it makes sense to split your code. So, if you have an application, you may wish to make use of a tool like JDepend1, which will analyze your application and report on dependencies between packages. If you are using Eclipse for your development, we recommend using JDepend4Eclipse2, which is shown in figure 3.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/326.jpg"><img class="aligncenter size-medium wp-image-2505" title="3" src="http://www.javabeat.net/wp-content/uploads/2012/04/326-300x197.jpg" alt="" width="300" height="197" /></a></p>
<p><center><strong><span style="color: red;">Figure 3 JDepend4Eclipse will analyze your Java code and allows you to review dependencies between packages and classes.</span></strong></center>JDepend4Eclipse makes it very easy to see dependencies, both incoming and outgoing, for both packages and classes. If you aren&#8217;t familiar with JDepend, it will be worth the effort to read the overview on the JDepend website. The overview provides definitions for the terms used in the report; for example, afferent vs. efferent coupling and dependency cycles.</p>
<p>Now, once you have your grouped your collaborating classes in a package, it is time to create the gateway class.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h2>Creating the gateway</h2>
<p>Creating the gateway class involves creating a private constructor, creating an asynchronous factory method, and implementing any methods needed by the world outside of our package.</p>
<p>We present our example gateway class for a package that encapsulated functionality for driving a car in listing 2.</p>
<p><strong><span style="color: red;">Listing 2 An example gateway class for the Async Package pattern</span></strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package com.manning.gwtia.ch18.client.car;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
public class CarGateway {
private CarGateway () { }
public static void createAsync (final Callback callback) { |#1
GWT.runAsync(new RunAsyncCallback() {
public void onSuccess () { |#2
callback.onCreated(new CarGateway());
}
public void onFailure (Throwable reason) { |#3
callback.onCreateFailed(reason);
}
});
}
public interface Callback { |#4
void onCreated (CarGateway gateway);
void onCreateFailed (Throwable reason);
}
public void startEngine () { ... }
public void setSpeed (int mph) { ... }
public int getSpeed () { ... }
}
#1 Factory method
#2 Success handler
#3 Failure handler
#4 Callback interface</pre></td></tr></table></div>

<p>In listing 2, we have made the constructor private, forcing callers to construct the class using the factory method createAsync() (#1). The createAsync() method takes a single callback argument, which is an interface that we will define shortly. In createAsync(), we use GWT.runAsync(), which will create our split point.</p>
<p>In the onSuccess() method (#2), we make use of the callback argument, calling callback.onCreated() and passing back a new instance of CarGateway.</p>
<p>The callback.onFailure() method (#3) simply passes the exception back to the user. As stated before, this would typically be triggered if there was a network error where the split point can&#8217;t be loaded.</p>
<p>The Callback interface (#4), implemented by the parameter passed to our createAsync() method, is defined here as an inner class. We then provide some work methods that can be called, like startEngine() and getSpeed(), once the CarGateway instance has been constructed.</p>
<p>Creating a gateway class in this manner, where we force callers to use a factory method, means that the caller can&#8217;t get it wrong. We will look at some examples of that next.</p>
<h2>Using the gateway class</h2>
<p>From the client side, use of the gateway class is unrestricted now that it can only be created via the factory method createAsync(). Instead of looking at the simplest use case, let&#8217;s look at something you might find in the real world. Imagine that your application is pretty heavy and you want to present a splash screen as early as possible. This is akin to when you open a web application and it says “Loading”, like you might see on GMail.</p>
<p>The reason developers do this is so that user perceives the application as loading quickly. Your typical will perceive the speed of starting the application based on how long it takes you to render those first widgets, so it is useful to display some sort of splash screen while the full application code loads.</p>
<p>For our example, in listing 3, we will display a simple message “Loading car data…” and then replace that message with a button to start the car once the split point is loaded.</p>
<p><center><strong><span style="color: red;">Listing 3 Example client useage of an Async Package gateway</span></strong></center></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package com.manning.gwtia.ch18.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.manning.gwtia.ch18.client.car.CarGateway;
import com.manning.gwtia.ch18.client.car.CarGateway.Callback;
public class Main implements EntryPoint
{
private CarGateway carGateway;
public void onModuleLoad () {
RootPanel.get().add(new Label(&quot;Loading car data...&quot;)); |#1
CarGateway.createAsync(new Callback() { |#2
public void onCreated (CarGateway gateway) {
carGateway = gateway; |#3
initDisplay(); |#3
}
public void onCreateFailed (Throwable reason) {
Window.alert(&quot;Error loading data&quot;);
}
});
}
private void initDisplay () { |#4
RootPanel.get().clear();
Button button = new Button(&quot;Start your engines!&quot;);
RootPanel.get().add(button);
button.addClickHandler(new ClickHandler() {
public void onClick (ClickEvent event) {
carGateway.startEngine();
}
});
}
}
#1 Loading message
#2 Loads split point
#3 Handle loaded
#4 Initializes display</pre></td></tr></table></div>

<p>This example is our module entry point, and the first thing we do is add a loading message to the page in the form of a Label (#1). This is followed up by a call to CarGateway.createAsync() (#2), which will load the split point.</p>
<p>In the onCreated() method of the callback&#8217;s pass to createAsync()(#3), we can initialize the application. We do this by storing a reference to the CarGateway in the class field carGateway and then calling initDisplay().</p>
<p>The initDisplay() (#4) method then uses the carGateway reference to create a “Start your engines” Button and ClickHandler, which are then displayed on the page.</p>
<p>This example is pretty simple, but there are some things worth noting. First is that we can store a reference to the gateway class. When GWT creates a split point for the gateway it will recognize that the reference can only be null until the object is constructed. And because it is only constructed within a <em>GWT.runAsync()</em> call, all of the CarGateway methods can be included in the split point. To be specific, what we are trying to point out is that you can store references to the CarGateway and pass them around without breaking the split point.</p>
<p>Another thing to point out in this example is that, because the loading message is just a Label, it could have probably been hard-coded in the HTML page. Our example is very small, but in a larger application you might expect to find a progress bar instead of a simple text message. A progress bar is useful to the user because they can see that something is actually happening, preventing them from thinking that the application has hung.</p>
<p>If we had several split points, we could initiate the loading of them all at the same time and increment the progress bar as each one is completed. Then, we could use some sort of an event handler in the progress bar to initialize the application once all of the split points were loaded.</p>
<p>One ideal place to add a second split point in this specific application would be where we create the widgets in the initDisplay() method. If we could move this code into a gateway as well it would decrease out initial download size even further, and generally speaking the UI code is a fairly large part of more <strong>GWT</strong> applications.</p>
<p>When the first split point is loaded, so is the leftover code. Depending on how you have split your code, you may have a significant chunk of leftover code. To reduce the size of the leftover code <strong>GWT</strong> has one more trick up its sleeve.</p>
<h2>Reducing leftover code by specifying load order</h2>
<p>The leftover download shown in the Compile Report is any code that is shared across split points. If you have a lot of split points you may find that this chunk of code can be rather large. For example, if you have four split points, with 5 KB of code shared between split points A and B, and a different 5 KB of shared code used by split points C and D. If you were to load split point A, you would also be downloading the shared code for C and D, even though you might never need it.</p>
<p><strong>GWT</strong> provides a mechanism to solve this problem, but, in order to do so, you need to be able to predict the load order of at least some of the split points. To do this you need to first give your split points an identity, and then reference the identity of the split point in the module configuration (listing 4).</p>
<p><center><strong><span style="color: red;">Listing 4 Updated gateway class providing an identity to the split point</span></strong></center></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package com.manning.gwtia.ch18.client.car;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
public class CarGateway
{
private CarGateway () { }
public static void createAsync (final Callback callback) {
GWT.runAsync(CarGateway.class, new RunAsyncCallback() { |#A
public void onSuccess () {
CarGateway gateway = new CarGateway();
callback.onCreated(gateway);
}
public void onFailure (Throwable reason) {
callback.onCreateFailed(reason);
}
});
}
...
}
#A Identity provided</pre></td></tr></table></div>

<p>In listing 4, we omitted most of our sample so that we can focus on the GWT.runAsync() call. Here, you will see that we pass a class literal as the first argument to <em>GWT.runAsync()</em>. This purpose of this is only to provide a unique identity, meaning that we could have used any class literal for this purpose, but typically you would use the class literal that is related to the split point. In our case, it makes the most sense to use CarGateway.class as the identity.</p>
<p>The second part is to identify the order of the initial split points in the module configuration. This is done by extending the configuration property “compiler.splitpoint.initial.sequence”, as in this example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;extend-configuration-property
name=&quot;compiler.splitpoint.initial.sequence&quot;
value=&quot;com.manning.gwtia.ch18.client.car.CarGateway&quot;/&gt;</pre></td></tr></table></div>

<p>The value is where we specify the identity that we gave our split point. By extending this property we are signaling to the compiler that this split point will be the first to load following the initial download. Because of this the compiler can include shared code that that split point uses in this split point, increasing the size of the split point and reducing the size of the leftover code.</p>
<p>If you can provide the order of additional split points beyond the first, you can specify them by adding additional entries in the module configuration.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;extend-configuration-property
name=&quot;compiler.splitpoint.initial.sequence&quot;
value=&quot;com.manning.gwtia.ch18.client.car.UIGateway&quot;/&gt;
&lt;extend-configuration-property
name=&quot;compiler.splitpoint.initial.sequence&quot;
value=&quot;com.manning.gwtia.ch18.client.car.RoadwayGateway&quot;/&gt;</pre></td></tr></table></div>

<p>These will again reduce the size of the leftover code, increasing the code in the split points.</p>
<p>The downside of specifying the load order is that if your code ends up loading a split point out of order it will need to go back and load additional split points. For example, if you declare the load order to be A B C, but, try to load C first, it will also trigger the loading of split points A and B.</p>
<p>So, ordering the split points can reduce your total leftover code, but requires some preplanning in order to use it effectively.</p>
<h2>Summary</h2>
<p>We looked at the Compile Report and <strong>code splitting</strong>. This is a fairly new tool to the GWT stack and is also one of the most anticipated. With <strong>code splitting</strong>, there is now, in theory, no upper limit on the size of your applications. With <strong>code splitting</strong>, you can break out the rarely used parts only to be loaded when they are needed. Just imagine a million-line application running in the browser, with an initial load time of less than one second. That&#8217;s amazing considering that the underlying technology, namely JavaScript, was never meant to do that.</p>
<p>What makes <strong>GWT</strong> such a compelling product in our minds is that it allows us to do all these things without needing to think about the underlying JavaScript all that much. That is a good thing because JavaScript implementations differ and, as a developer, you can either spend your time learning about JavaScript implementation differences, or you can spend your time coding your application. We prefer the later.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/11/code-splitting-in-gwt/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting Response through GWT using Http Protocol</title>
		<link>http://www.javabeat.net/2011/03/getting-response-through-gwt-using-http-protocol/</link>
		<comments>http://www.javabeat.net/2011/03/getting-response-through-gwt-using-http-protocol/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 13:34:57 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[GWT]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=585</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction This article deals with getting the response from the server side using Google Web ToolKit Framework and Ajax. Google Web ToolKit is one of the Ajax frameworks which is mainly aimed at Java Developers.The main advantage of GWT is that it comes with a compiler which will translate the Java code written by the [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p>This article deals with getting the response from the server side using Google Web ToolKit Framework and Ajax. Google Web ToolKit is one of the Ajax frameworks which is mainly aimed at Java Developers.The main advantage of GWT is that it comes with a compiler which will translate the Java code written by the developers to highly optimized , browser independent Java Script, thereby eliminating the need of front-end developers to know Java.</p>
<p>In this article, we will see how to use GWT to send a HTTPRequest to the server and update the response on the client side using Ajax.Please find below the screenshot of the sample output.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/03/17.jpg"><img class="aligncenter" title="1" src="http://www.javabeat.net/wp-content/uploads/2011/03/17-300x66.jpg" alt="" width="300" height="66" /></a>In this example, we have a html file(HttpRequest.html) with a simple button. We shall be coding for the button and the other UI elements using GWT and not HTML.When the user clicks on the button, we shall be sending a httpRequest to &#8220;Response.html&#8221;.We shall also be updating &#8220;HttpRequest.html&#8221; with the content of &#8220;Response.html&#8221; through Ajax. In this article, we shall be seeing how to do all this using GWT.</p>
<h2>Software Requirements</h2>
<ul>
<li>JDK 1.6</li>
<li>Eclipse 3.6 IDE</li>
<li>GWT SDK 1.7</li>
<li>GWT Eclipse Plug-in</li>
</ul>
<h2>File Structure</h2>
<p>Please find below the File Structure of the application. The following are the files that are to be coded:</p>
<ul>
<li>HttpRequest.java</li>
<li>HttpRequest.html</li>
<li>Response.html</li>
<li>HttpRequest.gwt.xml</li>
</ul>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/03/26.jpg"><img class="aligncenter size-medium wp-image-1092" title="2" src="http://www.javabeat.net/wp-content/uploads/2011/03/26-220x300.jpg" alt="" width="220" height="300" /></a></p>
<p>Let&#8217;s try to understand the File Structure. The GWT web application will have src folder which has 3 packages.</p>
<p>In our case, we have</p>
<ul>
<li>com.enr</li>
<li>com.enr.client</li>
<li>com.enr.server</li>
</ul>
<p>com.enr package will have the file &#8220;<strong><em>HttpRequest.gwt.xml </em></strong>&#8220;. This is a configuration file which will be discussed more in detail later.</p>
<p>com.enr.client package will have the client side related files. The files that are to be converted into javascript will have to be placed here.</p>
<p>com.enr.server package will have the server related files, for example the servlet code etc. All the java classes that need not be converted to Java Script will have to be placed here.</p>
<p>An another important folder will be <strong><em>war</em></strong> which has WEB-INF folder. <strong><em>war</em></strong> folder is the one wherein all the GWT-compiler generated files will be placed.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Now let us add in code into <strong>HttpRequest.java</strong></p>
<h2>HttpRequest.java</h2>
<p>This is the file, wherein, we will be coding for the front end. We shall be using GWT packages to generate UI Elements like button , label etc. The code that is present in &#8220;HttpRequest.java&#8221; will be converted to html and JavaScript by the GWT Compiler.The generated javascript code will be encapsulated into a iframe(invisible frame) and will be pasted into &#8220;HttpRequest.html&#8221;. This code will run on the browser.</p>
<p>Soon after the user clicks on the button, as discussed before, we need to generate a HttpRequest and also update the page with the response. Let&#8217;s try to understand how to do the same using GWT.</p>
<p>In order to generate a HttpRequest we need to use RequestBuilder class. <strong><em>RequestBuilder</em></strong> is a builder class which is used to generate HttpRequest Objects .This builder is however limited to build GET or POST requests.We use the method sendRequest to send the request to the specified url.In our case since we are sending the request to &#8220;Response.html&#8221;, the url should be corresponding to &#8220;Response.html&#8221;</p>
<p>We need to use <strong><em>RequestCallback class</em></strong> which will be invoked on recieving the response.</p>
<p>The RequestCallback class has two methods, <strong><em>onError </em></strong> and <strong><em>OnResponseRecieved </em></strong> which will be invoked upon getting the response depending on whether the response is positive or negative.These methods get references of the request and response objects which can be used to update the html page with the response.</p>
<p>In our example, we shall be sending the request on the click of the button.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package com.enr.client;
&nbsp;
	import com.google.gwt.core.client.EntryPoint;
	import com.google.gwt.core.client.GWT;
	import com.google.gwt.event.dom.client.ClickEvent;
	import com.google.gwt.event.dom.client.ClickHandler;
	import com.google.gwt.event.dom.client.KeyCodes;
	import com.google.gwt.event.dom.client.KeyUpEvent;
	import com.google.gwt.event.dom.client.KeyUpHandler;
	import com.google.gwt.http.client.Request;
	import com.google.gwt.http.client.RequestBuilder;
	import com.google.gwt.http.client.RequestCallback;
	import com.google.gwt.http.client.RequestException;
	import com.google.gwt.http.client.RequestTimeoutException;
	import com.google.gwt.user.client.Window;
	import com.google.gwt.user.client.rpc.AsyncCallback;
	import com.google.gwt.user.client.ui.Button;
	import com.google.gwt.user.client.ui.DialogBox;
	import com.google.gwt.user.client.ui.HTML;
	import com.google.gwt.user.client.ui.Label;
	import com.google.gwt.user.client.ui.RootPanel;
	import com.google.gwt.user.client.ui.TextBox;
	import com.google.gwt.user.client.ui.VerticalPanel;
	import com.google.gwt.http.client.Response;
	/**
	 * Entry point classes define onModuleLoad().
	 */
	public class HttpRequest implements EntryPoint {
&nbsp;
		public static final int STATUS_CODE_OK = 200;
&nbsp;
&nbsp;
		public static void doGet(String url) {
			RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
&nbsp;
			try {
				Request response = builder.sendRequest(null, new RequestCallback() {
					public void onError(Request request, Throwable exception) {
						if (exception instanceof RequestTimeoutException) {
							Window.alert(&quot;The request has timed out&quot;);
						} else {
	        			Window.alert(exception.getMessage());
						}
					}
					public void onResponseReceived(Request request, Response response) {
						if (STATUS_CODE_OK == response.getStatusCode()) {
							HTML responseLabel=new HTML(&quot;&lt;h3&gt;Response is gonna be updated here&lt;/H3&gt;&quot;);
							responseLabel.setHTML(response.getText());
							responseLabel.addStyleName(&quot;response&quot;);
							RootPanel.get().add(responseLabel);
						} else {
							Window.alert(&quot;&quot;+response.getStatusCode());
						}
					}
				});
			} catch (RequestException e) {
				// Code omitted for clarity
			}
		}
&nbsp;
		public void onModuleLoad() {
			Button button=new Button(&quot;Get Response&quot;);
			button.addClickHandler(new ClickHandler(){
				@Override
				public void onClick(ClickEvent event) {
					doGet(&quot;Response.html&quot;);
				}
			});
			RootPanel.get(&quot;container&quot;).add(button);
		}	
	}</pre></td></tr></table></div>

<h2>HttpRequest.gwt.xml</h2>
<p>This is a configuration file which has information about the name of the module and entry point class and various GWT java packages that needs to be imported by the web application.</p>
<p>Entry point class is the class that will be executed on running the application.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
	&lt;!DOCTYPE module PUBLIC &quot;-//Google Inc.//DTD Google Web Toolkit 1.7.1//EN&quot; &quot;http://google-web-toolkit.googlecode.com/svn/tags/1.7.1/distro-source/core/src/gwt-module.dtd&quot;&gt;
	&lt;module rename-to='httprequest'&gt;
		&lt;inherits name='com.google.gwt.user.User'/&gt;
		&lt;inherits name='com.google.gwt.user.theme.standard.Standard'/&gt;
		&lt;inherits name=&quot;com.google.gwt.http.HTTP&quot;/&gt;
		&lt;entry-point class='com.enr.client.HttpRequest'/&gt;
	&lt;/module&gt;</pre></td></tr></table></div>

<h2>HttpRequest.html</h2>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;html&gt;
	&lt;head&gt;
		&lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
		&lt;link type=&quot;text/css&quot; rel=&quot;stylesheet&quot; href=&quot;HttpRequest.css&quot;&gt;
		&lt;title&gt;Web Application Starter Project&lt;/title&gt;
		&lt;script type=&quot;text/javascript&quot; language=&quot;javascript&quot; src=&quot;httprequest/httprequest.nocache.js&quot;&gt;&lt;/script&gt;
		&lt;style&gt;
			.response
			{
				background-color: #efefef;
				padding-bottom: 1.5em; 
			}
		&lt;/style&gt;
	&lt;/head&gt;
	&lt;body&gt;
		&lt;iframe src=&quot;javascript:''&quot; id=&quot;__gwt_historyFrame&quot; tabIndex='-1' style=&quot;position:absolute;width:0;height:0;border:0&quot;&gt;&lt;/iframe&gt;
		&lt;h1&gt;Getting the response through Ajax using HTTP Protocol&lt;/h1&gt;
		&lt;center&gt;&lt;div id=&quot;container&quot;&gt;&lt;/div&gt;&lt;/center&gt;
	&lt;/body&gt;
	&lt;/html&gt;</pre></td></tr></table></div>

<h2>Response.html</h2>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;html&gt;
	&lt;head&gt;
		&lt;title&gt;Response&lt;/title&gt;
	&lt;/head&gt;
	&lt;body&gt;
		&lt;h2&gt;This is the response through GWT Http Ajax&lt;/h2&gt;
	&lt;/body&gt;
	&lt;/html&gt;</pre></td></tr></table></div>

<h2>Conclusion</h2>
<p>In this article , we have seen the usage of RequestBuilder Class and RequestCallback class to send in a HttpRequest and update the page with server side response through Ajax.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/03/getting-response-through-gwt-using-http-protocol/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Internationalisation(i18n) in GWT Application</title>
		<link>http://www.javabeat.net/2011/01/internationalisationi18n-in-gwt-application/</link>
		<comments>http://www.javabeat.net/2011/01/internationalisationi18n-in-gwt-application/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 13:01:09 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[GWT]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=538</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Internationalization is the technique of designing the application to be attuned with different regions or countries where the application needs to be run. Internationalization requires separation of the usage data to be internationalized into properties file. In the Java programming language, internationalization is usually implemented by means of Resource Bundles i.e., a .properties file for [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><strong>Internationalization </strong>is the technique of designing the application to be attuned with different regions or countries where the application needs to be run. Internationalization requires separation of the usage data to be internationalized into properties file. In the Java programming language, internationalization is usually implemented by means of Resource Bundles i.e., a <strong>.properties</strong> file for each locale that needs to be supported. <strong>GWT</strong> also uses the same mechanism of implementing internationalization using Resource Bundles.</p>
<p><span style="text-decoration: underline;"><strong>also read:</strong></span></p>
<ul>
<li><a href="http://www.javabeat.net/2011/11/code-splitting-in-gwt/">Code Splitting in GWT</a></li>
<li><a href="http://www.javabeat.net/2011/11/what-is-model-view-presenter-mvp-in-gwt-application/">What is Model View Presenter (MVP) in GWT Application?</a></li>
<li><a href="http://www.javabeat.net/2011/01/history-management-in-gwt/">History Management in GWT</a></li>
</ul>
<h2>GWT&#8217;s I18N support</h2>
<p><strong>GWT</strong> provides a module which contains all the core classes and interfaces related to internationalization in the package named <strong>com.google.gwt.i18n</strong> and the module is <strong>com.google.gwt.i18n.I18N </strong>. <strong>GWT</strong> supports two ways of internationalizing the application. They are :</p>
<ul>
<li><strong>Static String Internationalization</strong></li>
<li><strong>Dynamic String Internationalization</strong></li>
</ul>
<p>In this article we will discuss how to internationalize the application using <strong>Static String Internationalization</strong>. <strong>GWT</strong> provides the <strong>Static String i18n</strong> through<br />
the interfaces like <strong>Constants, ConstantsWithLookup</strong> and <strong>Messages</strong>.</p>
<h2>Sample Application</h2>
<p>The sample application we discuss here demonstrates how to add I18N support to the GWT application. We will create Login application which has support for three locales English, French and Hindi. Let us see the step by step procedure for the same.</p>
<h2>Software Requirements</h2>
<p>Install the following softwares to run the sample application.</p>
<ul>
<li>JDK 1.6</li>
<li>Eclipse 3.6 IDE</li>
<li>GWT SDK 2.0.0</li>
<li>GWT Eclipse Plug-in</li>
<li>GWT plug-in for IE browser. (to run in development mode)</li>
</ul>
<h2>GWT Project Structure</h2>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/01/12.jpg"><img class="aligncenter size-full wp-image-1007" title="1" alt="" src="http://www.javabeat.net/wp-content/uploads/2011/01/12.jpg" width="255" height="269" /></a></p>
<h2>How to Implement I18N in GWT?</h2>
<ol>
<li>
<h3>Inherit the I18N module and add the locale values to the application<br />
module file.</h3>
</li>
</ol>
<ul>
<li>Mention each locale value that the application wants to support by extending the locale value in the Module&#8217;s XML file as shown below.</li>
</ul>
<pre class="brush: java; title: ; notranslate">
&lt;module&gt;

    &lt;inherits name=&quot;com.google.gwt.user.User&quot;/&gt;

   &lt;inherits name=&quot;com.google.gwt.i18n.I18N&quot;/&gt;

    &lt;entry-point/&gt;
    &lt;extend-property name=&quot;locale&quot; values=&quot;fr&quot;/&gt;
    &lt;extend-property name=&quot;locale&quot; values=&quot;hi&quot;/&gt;

    &lt;/module&gt;
</pre>
<p>From the above configuration of the module file , it indicates that our application supports two locales French and Hindi apart from the default locale.</p>
<h3>2. Create .properties file for each locale</h3>
<ul>
<li>All the resource bundles must have same base name and should differ in their suffix which indicates the locale.</li>
<li>The message lookup algorithm considers the base name, current locale and key of the message.</li>
<li>Place all the .properties files in the src package.</li>
</ul>
<p><strong>AppConstants.properties</strong> is for the default locale i.e., english which has the key/value pairs as below.</p>
<pre class="brush: java; title: ; notranslate">username: Username
password: Password
login: Login</pre>
<p><strong>AppConstants_fr.properties</strong> supports French locale. The key/value pairs are as below.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">username: Nom d'utilisateur
password: Mot de passe
login: connexion</pre>
<h3>3.Create an Interface corresponding to the Property Files.</h3>
<ul>
<li>Create an interface that extends GWTs Constants interface. Resource bundles can be used by binding them to this interface.</li>
<li>The base name of the property files and the interface name must be same.</li>
<li>Each method in the interface corresponds to the key in the properties file.</li>
</ul>
<p>Create the interface as shown below:</p>
<pre class="brush: java; title: ; notranslate">public interface AppConstants extends Constants {

String username();
String password();
String login();

}</pre>
<ul>
<li>If the method name is different from the message key in the properties file then annotate the method with @Key annotation<br />
to bind the method name to message key in the resource bundle as below.</li>
</ul>
<p><strong>@Key(&#8220;uname&#8221;)</strong></p>
<p>String username();</p>
<p>Where uname is the message key in the properties file.</p>
<h3>4. Setting up the EntryPoint class.</h3>
<p>The last step of the application is to use the Constants interface and values from the properties file.</p>
<ul>
<li>Create the interface object through the deferred binding mechanism that is by using GWT.create() method.</li>
<li>Assign the text to the labels and buttons by using the interface methods which reads the values from the properties file.</li>
</ul>
<pre class="brush: java; title: ; notranslate">AppConstants constants=(AppConstants)GWT.create(AppConstants.class);// Creating Interface object
	public void onModuleLoad() {
		// Getting the values from resource bundle through interface methods
		Label username=new Label(constants.username());
		Label passsword=new Label(constants.password());
		TextBox ubox=new TextBox();
		PasswordTextBox pbox=new PasswordTextBox();
		Button button = new Button(constants.login());
	}</pre>
<h2>GWT Sample Application</h2>
<pre class="brush: java; title: ; notranslate">public class LoginI18nDemo implements EntryPoint {
	public LoginI18nDemo () {}
	AppConstants constants=(AppConstants)GWT.create(AppConstants.class);
	public void onModuleLoad() {
		Label username=new Label(constants.username());
		Label passsword=new Label(constants.password());
		TextBox ubox=new TextBox();
		PasswordTextBox pbox=new PasswordTextBox();
		Button button = new Button(constants.login());
		Grid g=new Grid(3,2);
		g.setWidget(0,0,username);
		g.setWidget(0,1,ubox);
		g.setWidget(1, 0, passsword);
		g.setWidget(1,1,pbox);
		g.setWidget(2, 1, button);
		HorizontalPanel links=new HorizontalPanel();
		Anchor french=new Anchor(&quot;French&quot;,GWT.getHostPageBaseURL()+&quot;?locale=fr&quot;);
		Anchor hindi=new Anchor(&quot;Hindi&quot;,GWT.getHostPageBaseURL()+&quot;?locale=hi&quot;);
		links.add(french);
		links.add(hindi);
		links.setSpacing(5);
		RootPanel.get().add(g);
		RootPanel.get().add(links);
	}
}</pre>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/01/22.jpg"><img class="aligncenter size-medium wp-image-1008" title="2" alt="" src="http://www.javabeat.net/wp-content/uploads/2011/01/22-300x61.jpg" width="300" height="61" /></a><br />
<a href="http://www.javabeat.net/wp-content/uploads/2011/01/32.jpg"><img class="aligncenter size-medium wp-image-1009" title="3" alt="" src="http://www.javabeat.net/wp-content/uploads/2011/01/32-300x57.jpg" width="300" height="57" /></a><br />
<a href="http://www.javabeat.net/wp-content/uploads/2011/01/41.jpg"><img class="aligncenter size-medium wp-image-1006" title="4" alt="" src="http://www.javabeat.net/wp-content/uploads/2011/01/41-300x51.jpg" width="300" height="51" /></a></p>
<h2>Conclusion</h2>
<p>In this article we learned how to internationalize the <strong>GWT</strong> application using <strong>Static String approach</strong>, allowing the user to select the locale in which the application should be rendered. In the next article we will discuss how to <strong>Internationalize using Dynamic String approach</strong> and how to use <strong>Messages Interface</strong>.</p>
<p><strong>also read:</strong></p>
<ul>
<li><a href="http://www.javabeat.net/2011/11/code-splitting-in-gwt/">Code Splitting in GWT</a></li>
<li><a href="http://www.javabeat.net/2011/11/what-is-model-view-presenter-mvp-in-gwt-application/">What is Model View Presenter (MVP) in GWT Application?</a></li>
<li><a href="http://www.javabeat.net/2011/01/history-management-in-gwt/">History Management in GWT</a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/01/internationalisationi18n-in-gwt-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Google Web Toolkit (GWT) 2.0 Application Development</title>
		<link>http://www.javabeat.net/2011/01/google-web-toolkit-gwt-2-0-application-development/</link>
		<comments>http://www.javabeat.net/2011/01/google-web-toolkit-gwt-2-0-application-development/#comments</comments>
		<pubDate>Tue, 25 Jan 2011 00:16:38 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[GWT]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1583</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Google Web Toolkit 2 Application Development CookbookGWT 2.0 radically improves the web experience for users by using the existing Java tools to build a no-compromise AJAX for any modern browser. It provides a solid platform so that the other great libraries can be built on top of the GWT. Creating web applications efficiently and making [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><center>Google Web Toolkit 2 Application Development Cookbook</center><strong><a href="http://www.javabeat.net/books/gwt/1/">GWT 2.0</a></strong> radically improves the web experience for users by using the existing Java<br />
tools to build a no-compromise AJAX for any modern browser. It provides a solid<br />
platform so that the other great libraries can be built on top of the GWT. Creating<br />
web applications efficiently and making them impressive, however, is not as easy as it<br />
sounds. Writing web applications for multiple browsers can be quite tasking. In addition,<br />
building, reusing, and maintaining large JavaScript code bases and AJAX components<br />
can be difficult.</p>
<p><strong><a href="http://www.javabeat.net/books/gwt/1/">GWT 2.0</a></strong> Application Development Cookbook eases these burdens by allowing the<br />
developers to build and maintain complex, yet highly efficient JavaScript frontend<br />
applications in the Java programming language quickly. It tells you how to make the<br />
web experience all the more thrilling and hassle-free by using various tools along with<br />
the GWT SDK.</p>
<p>This book starts with developing an application from scratch. Right from creating the<br />
layout of the home page to home page elements including left and right sidebars, to<br />
placing a tree-like navigational menu, menu bars, tool bars, banners, and footers are<br />
discussed with examples.</p>
<p>You will see how to create forms using the Ext GWT library widgets and handle different<br />
types of events. Then, you will move on to see how to design a database for sales<br />
processing systems, and learn how to create the database in MySQL with the help of<br />
easy-to-follow recipes.</p>
<p>One of the interesting topics of this book is using the JPA in <strong>GWT</strong>. Using the JPA object<br />
in <strong><a href="http://www.javabeat.net/books/gwt/1/">GWT 2.0</a></strong> is a challenge. To use it perfectly, a mechanism to convert the JPA object into a<br />
plain object and vice versa is required. You will see recipes to use entity classes, entity<br />
managers, and controller classes in the <strong><a href="http://www.javabeat.net/books/gwt/1/">GWT 2.0</a></strong> application. You will efficiently create<br />
reports with parameters, variables, and subreports, and get the report output in both<br />
<strong>HTML</strong> and PDF formats using real-world recipes.</p>
<p>You will then learn how to configure the GlassFish server to deploy a GWT application<br />
with a database. Finally, you will learn how to trace speed and improve performance in<br />
web applications using tracing techniques.</p>
<p>Create impressive web applications with tool bars, menus, multiple windows, and more<br />
with this step-by-step guide.</p>
<h2>GWT Articles &amp; Books</h2>
<ul>
<li><a href="http://www.javabeat.net/articles/28-google-web-toolkitgwt-1.html">Google Web ToolKit(GWT)</a></li>
<li><a href="http://www.javabeat.net/articles/238-history-management-in-gwt-1.html">History Management in GWT </a></li>
<li><a href="http://www.javabeat.net/books/gwt/1/">GWT Books</a></li>
<li><a href="http://code.google.com/webtoolkit/" target="_blank">GWT Official Site</a></li>
</ul>
<h1>What This Book Covers</h1>
<p><em>Chapter 1, Setting up the <strong>GWT</strong> Environment in NetBeans</em> shows which tools and<br />
technologies are required to build a web application using <strong>GWT</strong>, JPA, and iReport<br />
in NetBeans. The required installation and configuration of the tools are shown as<br />
easy-to-follow recipes.</p>
<p><em>Chapter 2, Creating Home Page with Panels and Menus</em> creates the layout of the<br />
application. It shows how to divide the page into the banner, left and right sidebars,<br />
and the center and footer sections.</p>
<p><em>Chapter 3, Forms with Layout and Widgets</em> includes recipes that show how to use<br />
widgets to create forms, sidebars for navigation, tab panel, and so on.</p>
<p><em>Chapter 4, Handling your First Events</em> includes easy-to-follow recipes that show how to<br />
handle the typical <strong>GWT</strong> events such as button event, field event, menu event, focus<br />
event, change event, and so on.</p>
<p><em>Chapter 5, Creating Database for Sales Processing</em> creates a sample database in MySQL<br />
for Sales Processing Systems. To create a database and its tables with the required<br />
constraints, easily the uses of MySQL GUI tools have been shown.</p>
<p><em>Chapter 6, Managing Entities using JPA</em> deals with the Java Persistence API (JPA)<br />
framework. It is a framework that is used to manage relational data in Java EE and Java<br />
SE applications. <strong>JPA</strong> provides a <strong>Plain Old Java Object (POJO)</strong> persistence model for<br />
object relational mapping. This chapter shows how to create a database connection,<br />
persistence unit, entity classes, and controller classes for the database CRUD operations.</p>
<p><em>Chapter 7, Communicating with Server using <strong>GWT</strong> RPC</em> deals with the communication<br />
between the client and the server. The recipes in this chapter describe how to use the JPA in<br />
the server side and <strong>Data Transfer Objects (DTO)<strong> in the client side. It discusses how the<br />
<strong>GWT</strong> RPC mechanism allows the server and the client to pass Java objects back and forth.</strong></strong></p>
<p><em>Chapter 8, Reporting with iReport</em> shows how to use iReport for the reporting solutions<br />
in Java web applications. Parameterized reports, subreports, and reports with variables<br />
are shown in some recipes. Then, the chapter discusses and shows how to show the<br />
created reports as <strong>HTML</strong> or PDF in the <strong>GWT</strong> application.</p>
<p><em>Chapter 9, Deploying a <strong>GWT</strong> Application</em> includes recipes that show how to build the<br />
<strong>GWT</strong> project for the deployment, and before the deployment, how to create JDBC<br />
connection pool and resources in the GlassFish server are given as recipes.</p>
<p><em>Chapter 10, Using Speed Tracer</em> deals with the extension Speed Tracer. Speed Tracer is a<br />
Google Chrome browser extension which is used to identify and fix performance<br />
problems in web applications. Installation and use of Speed Tracer for the created <strong>GWT</strong><br />
applications are shown in this chapter.</p>
<p><center>Creating Home Page with Panels and Menus</center>In this chapter, we will cover:</p>
<ul>
<li>Creating the home page layout class</li>
<li>Adding the banner</li>
<li>Adding menus</li>
<li>Creating the left-hand sidebar</li>
<li>Creating the right-hand sidebar</li>
<li>Creating the main content panel</li>
<li>Creating the footer</li>
<li>Using HomePage instance in EntryPoint</li>
</ul>
<h1>Introduction</h1>
<p>In this chapter, we will learn about creating the home page of our application. The home page<br />
will include a banner at the top, a sidebar for navigation on the left-hand side, another sidebar<br />
on the right-hand side for showing dynamic content, a footer to show copyright and other<br />
information, and the main content at the center.</p>
<p>The layout will be as shown in the diagram below:</p>
<p><center><img src="images/2011/01/WebToolkit2/1.jpg" alt="" /></center></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h1>Creating the home page layout class</h1>
<p>This recipe creates a panel to place the menu bar, banner, sidebars, footer, and the main<br />
application layout. Ext <strong>GWT</strong> provides several options to define the top-level layout of the<br />
application. We will use the BorderLayout function. We will add the actual widgets after<br />
the layout is fully defined. The other recipes add the menu bar, banner, sidebars, and footers<br />
each, one-by-one.</p>
<h2>Getting ready</h2>
<p>Open the <strong>Sales Processing System</strong> project.</p>
<h2>How to do it&#8230;</h2>
<p>Let&#8217;s list the steps required to complete the task.</p>
<ol>
<ol>
<li>Go to <strong>File | New File</strong>.</li>
<li>Select <strong>Java</strong> from <strong>Categories</strong>, and <strong>Java Class</strong> from <strong>File Types</strong>.</li>
</ol>
</ol>
<p><center><img src="images/2011/01/WebToolkit2/2.jpg" alt="" /></center></p>
<ol>
<ol>
<li>Click on <strong>Next</strong>.</li>
<li>Enter <strong>HomePage</strong> as the <strong>Class Name</strong>, and <strong>com.packtpub.client</strong> as <strong>Package</strong>.</li>
</ol>
</ol>
<p><center><img src="images/2011/01/WebToolkit2/3.jpg" alt="" /></center></p>
<ol>
<ol>
<li>Click on <strong>Finish</strong>.</li>
<li>Inherit the cla ss ContentPanel. Press <em>Ctrl + Shift + I</em> to import the package<br />
automatically. Add a default constructor:</li>
</ol>
</ol>
<pre><code>
 package com.packtpub.client;
 import com.extjs.gxt.ui.client.widget.ContentPanel;
 public class HomePage extends ContentPanel
 {
 public HomePage()
 {
 }
 }
 </code></pre>
<p>Write the code of the following steps in this constructor.</p>
<ol>
<ol>
<li>Set the size in pixels for the content panel:</li>
</ol>
</ol>
<pre><code>
 setSize(980,630);
 </code></pre>
<ol>
<ol>
<li>Hide the header:</li>
</ol>
</ol>
<pre><code>
 setHeaderVisible(false);
 </code></pre>
<ol>
<ol>
<li>Create a BorderLayout instance and set it for the content panel:</li>
</ol>
</ol>
<pre><code>
 BorderLayout layout = new BorderLayout();
 setLayout(layout);
 </code></pre>
<ol>
<ol>
<li>Create a BorderLayoutData instance and configure it to be used for the menu bar<br />
and toolba r:</li>
</ol>
</ol>
<pre><code>
 BorderLayoutData menuBarToolBarLayoutData=
 new BorderLayoutData(LayoutRegion.NORTH, 55);
 menuBarToolBarLayoutData.setMargins(new Margins(5));
 </code></pre>
<ol>
<ol>
<li>Create a BorderLayoutData instance and configure it to be used for the left-hand<br />
sideb ar:</li>
</ol>
</ol>
<pre><code>
 BorderLayoutData leftSidebarLayoutData =
 new BorderLayoutData(LayoutRegion.WEST, 150);
 leftSidebarLayoutData.setSplit(true);
 leftSidebarLayoutData.setCollapsible(true);
 leftSidebarLayoutData.setMargins(new Margins(0, 5, 0, 5));
 </code></pre>
<ol>
<ol>
<li>Create a BorderLayoutData instance and configure it to be used for the main<br />
contents, at the cent er:</li>
</ol>
</ol>
<pre><code>
 BorderLayoutData mainContentsLayoutData =
 new BorderLayoutData(LayoutRegion.CENTER);
 mainContentsLayoutData.setMargins(new Margins(0));
 </code></pre>
<ol>
<ol>
<li>Create a BorderLayoutData instance and configure it to be used for the right-hand<br />
sideb ar:</li>
</ol>
</ol>
<pre><code>
 BorderLayoutData rightSidebarLayoutData =
 new BorderLayoutData(LayoutRegion.EAST, 150);
 rightSidebarLayoutData.setSplit(true);
 rightSidebarLayoutData.setCollapsible(true);
 rightSidebarLayoutData.setMargins(new Margins(0, 5, 0, 5));
 </code></pre>
<ol>
<ol>
<li>Create a BorderLayoutData instance and configure it to be used for the foot er:</li>
</ol>
</ol>
<pre><code>
 BorderLayoutData footerLayoutData =
 new BorderLayoutData(LayoutRegion.SOUTH, 20);
 footerLayoutData.setMargins(new Margins(5));
 </code></pre>
<h2>How it works&#8230;</h2>
<p>Let&#8217;s now learn how these steps allow us to complete the task of designing the application<br />
for the home page layout. The full page (home page) is actually a &#8220;content panel&#8221; that covers<br />
the entire area of the host page. The content panel is a container having top and bottom<br />
components along with separate header, footer, and body sections. Therefore, the content<br />
panel is a perfect building block for application-oriented user interfaces.</p>
<p>In this example, we will place the banner at the top of the content panel. The body section<br />
of the content panel is further subdivided into five regions in order to place these—the menu<br />
bar and toolbar at the top, two sidebars on each side, a footer at the bottom, and a large<br />
area at the center to place the contents like forms, reports, and so on. A BorderLayout<br />
instance lays out the container into five regions, namely, north, south, east, west, and center.<br />
By using BorderLayout as the layout of the content panel, we will get five places to add<br />
five components.</p>
<p>BorderLayoutData is used to specify layout parameters of each region of the container that<br />
has BordeLayout as the layout. We have created five instances of BorderLayoutData, to<br />
be used in the five regions of the container.</p>
<h2>There&#8217;s more&#8230;</h2>
<p>Now, let&#8217;s talk about some general information that is relevant to this recipe.</p>
<h3>Setting the size of the panel</h3>
<p>The setSize method is used to set the size for a panel. Any one of the two overloaded<br />
setSize methods can be used. A method has two int parameters, namely, width and<br />
height. The other one takes the same arguments as string.</p>
<h3>Showing or hiding header in the content panel</h3>
<p>Each content panel has built-in headers, which are visible by default. To hide the header, we<br />
can invoke the setHeaderVisible method, giving false as the argument, as shown in the<br />
preceding example.</p>
<h3>BorderLayoutData</h3>
<p>BorderLayoutData is used to set the layout parameters, such as margin, size, maximum<br />
size, minimum size, collapsibility, fl oatability, split bar, and so on for a region in a border panel.</p>
<p>Consider the following line of code in the example we just saw:</p>
<pre><code>
 BorderLayoutData leftSidebarLayoutData =
 new BorderLayoutData(LayoutRegion.WEST, 150)
 </code></pre>
<p>It creates a variable leftSidebarLayoutData, where the size is 150 pixels and the region<br />
is the west of the border panel.</p>
<p>rightSidebarLayoutData.setSplit(true) sets a split bar between this region and its<br />
neighbors. The split bar allows the user to resize the region.</p>
<p>leftSidebarLayoutData.setCollapsible(true) makes the component collapsible,<br />
that is, the user will be able to collapse and expand the region.</p>
<p>leftSidebarLayoutData.setMargins(new Margins(0, 5, 0, 5)) sets a margin<br />
where 0, 5, 0, and 5 are the top, right, bottom, and left margins, respectively.</p>
<h3>Classes and packages</h3>
<p>In the preceding example, some classes are used from Ext <strong>GWT</strong> library, as shown in<br />
the following</p>
<p><center><img src="images/2011/01/WebToolkit2/4.jpg" alt="" /></center></p>
<h2>See also</h2>
<ul>
<li>The <em>Adding the banner</em> recipe</li>
<li>The <em>Adding menus</em> recipe</li>
<li>The <em>Creating the left-hand sidebar</em> recipe</li>
<li>The <em>Creating the right-hand sidebar</em> recipe</li>
<li>The <em>Creating the main content panel</em> recipe</li>
<li>The <em>Creating the footer</em> recipe</li>
<li>The <em>Using the HomePage instance in EntryPoint</em> recipe</li>
</ul>
<h2>GWT Articles &amp; Books</h2>
<ul>
<li><a href="http://www.javabeat.net/articles/28-google-web-toolkitgwt-1.html">Google Web ToolKit(GWT)</a></li>
<li><a href="http://www.javabeat.net/articles/238-history-management-in-gwt-1.html">History Management in GWT </a></li>
<li><a href="http://www.javabeat.net/books/gwt/1/">GWT Books</a></li>
<li><a href="http://code.google.com/webtoolkit/" target="_blank">GWT Official Site</a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/01/google-web-toolkit-gwt-2-0-application-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Google App Engine Java and GWT Application Development</title>
		<link>http://www.javabeat.net/2011/01/google-app-engine-java-and-gwt-application-development/</link>
		<comments>http://www.javabeat.net/2011/01/google-app-engine-java-and-gwt-application-development/#comments</comments>
		<pubDate>Mon, 24 Jan 2011 00:19:55 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[GWT]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1592</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Google App Engine Java and GWT Application DevelopmentThis book is designed to give developers the tools they need to build their own Google App Engine (GAE) with Google Web Toolkit (GWT) applications, with a particular focus on some of the technologies useful for building social-media-oriented applications. The book is centered on a GAE + GWT [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><center>Google App Engine Java and <strong><strong>GWT</strong></strong> Application Development</center>This book is designed to give developers the tools they need to build their own Google<br />
App Engine (GAE) with Google Web Toolkit (<strong><strong>GWT</strong></strong>) applications, with a particular<br />
focus on some of the technologies useful for building social-media-oriented applications.<br />
The book is centered on a GAE + <strong><strong>GWT</strong></strong> Java application called <em>Connectr</em>, which is<br />
developed throughout the chapters and demonstrates, by example, the use of the<br />
technologies described in the book. The application includes social-media information<br />
gathering and aggregation activities and incorporates the use of many App Engine<br />
services and APIs, as well as <strong><strong>GWT</strong></strong> design patterns and widget examples.</p>
<p>Several stages of the <em>Connectr</em> application are used throughout the book as features are<br />
added to the app. Code is included with the book for all application stages, and each<br />
chapter indicates the stage used.</p>
<h2>GWT Articles &amp; Books</h2>
<ul>
<li><a href="http://www.javabeat.net/articles/28-google-web-toolkitgwt-1.html">Google Web ToolKit(GWT)</a></li>
<li><a href="http://www.javabeat.net/books/gwt/1/">GWT Books</a></li>
<li><a href="code.google.com/webtoolkit/">GWT Official Site</a></li>
</ul>
<h1>What This Book Covers</h1>
<p><em>Chapter 1, Introduction</em>, introduces the approaches and technology covered in the book,<br />
and discusses what lies ahead.</p>
<p><em>Chapter 2, Using Eclipse and the Google Plugin</em>, describes the basics of setting up a<br />
project using the Eclipse IDE and Google&#8217;s <strong><strong>GWT</strong></strong>/GAE plugin. Topics include defining,<br />
compiling and running an Eclipse <strong><strong>GWT</strong></strong>/GAE project, and using the <strong><strong>GWT</strong></strong> developer<br />
browser plugin with the interactive debugger. The chapter also covers how to set up an<br />
App Engine account and create applications, and how to deploy an app to App Engine<br />
and access its Admin Console.</p>
<p><em>Chapter 3, Building The Connectr User Interface with <strong><strong>GWT</strong></strong></em>, focuses on <strong><strong>GWT</strong></strong>, and<br />
building the first iteration of the Connectr application&#8217;s frontend. The chapter looks at<br />
how to specify widgets, with a focus on declarative specification using <strong><strong>GWT</strong></strong>&#8216;s UIBinder<br />
and using the <strong><strong>GWT</strong></strong> RPC APifor server-side communication.</p>
<p><em>Chapter 4, Persisting Data: The App Engine Datastore</em>, covers Datastore basics. In the<br />
process, the first iteration of Connectr&#8217;s server-side functionality is built. The chapter<br />
looks at how the Datastore works, and the implications of its design for your data models<br />
and code development. It covers how to use Java Data Objects (JDO) as an interface to<br />
the Datastore and how to persist and retrieve Datastore entities.</p>
<p><em>Chapter 5, JDO Object Relationships and Queries</em>, builds on the topics of <em>Chapter 4</em>. It<br />
describes how to build and manage JDO objects that have relationships to each other,<br />
such as one-to-many and one-to-one parent-child relationships. It also covers how to<br />
query the Datastore, and the important role that Datastore indexes play in this process.</p>
<p><em>Chapter 6, Implementing MVP, an Event Bus and Other <strong>GWT</strong> Patterns</em>, builds on the<br />
client-side code of Chapter 3, and shows how to make the frontend code modular and<br />
extensible. It accomplishes this via use of the MVP (Model-View-Presenter) and Event<br />
Bus design patterns, history/bookmark management, and an RPC abstraction, which<br />
supports call retries and progress indicators.</p>
<p><em>Chapter 7, Background Processing and Feed Management</em>, centers on defining and<br />
running decoupled backend asynchronous tasks. In the process, the chapter introduces<br />
several App Engine services, including URLFetch and Task Queues, shows the use of<br />
Query Cursors to distribute Datastore-related processing across multiple Tasks, and<br />
introduces the use of Java Servlets and the incorporation of third-party libraries in a<br />
deployed application.</p>
<p><em>Chapter 8, Authentication using Twitter and Facebook OAuth and Google Accounts</em>, adds<br />
authentication, login, and account functionality to Connectr, allowing it to support<br />
multiple users. The chapter demonstrates the use of both the Google Accounts APiand<br />
the OAuth protocol for creating user accounts.</p>
<p><em>Chapter 9, Robustness and Scalability: Transactions, Memcache, and Datastore Design</em>,<br />
delves into more advanced Datastore-related topics. The chapter investigates Datastorerelated<br />
means of increasing the robustness, speed, and scalability of an App Engine app,<br />
including several ways to design data classes for scalability and to support efficient joinlike<br />
queries. The chapter also introduces App Engine transactions and Transactional<br />
Tasks and the use of Memcache, App Engine&#8217;s volatile-memory key-value store.</p>
<p><em>Chapter 10, Pushing fresh content to clients with the Channel API</em>, covers the<br />
implementation of a message push system using the App Engine Channel API, used by<br />
Connectr to keep application data streams current. The chapter describes how to open<br />
back-end channels connected to client-side socket listeners, and presents a strategy for<br />
preventing the server from pushing messages to unattended web clients.</p>
<p><em>Chapter 11, Managing and Backing Up Your App Engine Application</em>, focuses on useful<br />
App Engine deployment strategies, and admin and tuning tools. It includes ways to<br />
quickly upload configuration files without redeploying your entire application and<br />
describes how to do bulk uploads and downloads of application data. The chapter also<br />
discusses tools to analyze and tune your application&#8217;s behavior, and the App Engine<br />
billing model.</p>
<p><em>Chapter 12, Asynchronous Processing with Cron, Task Queue, and XMPP</em>, finishes<br />
building the server-side part of the Connectr app. The chapter introduces the use of App<br />
Engine Cron jobs, configuration of customized Task Queues, and App Engine&#8217;s XMPP<br />
service and API, which supports push notifications. The chapter shows the benefits of<br />
proactive and asynchronous updating—the behind-the scenes work that keeps Connectr&#8217;s<br />
data stream fresh—and looks at how App Engine apps can both send and receive XMPP<br />
messages.</p>
<p><em>Chapter 13, Conclusion</em>, summarizes some of the approaches and technology covered in<br />
the book, and discusses what might lie ahead.</p>
<p><center>Robustness and Scalability:Transactions, Memcache, and Datastore Design</center><em>Chapter 4</em> and <em>Chapter 5</em> explored the basics of using the App Engine Datastore. In this<br />
chapter, we&#8217;ll delve deeper to investigate Datastore-related ways to help increase the<br />
robustness, speed, and scalability of an App Engine app, and apply these techniques<br />
to our <em>Connectr</em> app.</p>
<p>First, in the <em>Data modeling and scalability</em> section we look at ways to structure and<br />
access your data objects to make your application faster and more scalable.</p>
<p>Then, the <em>Using transactions</em> section describes the Datastore <strong>transactions</strong>, what they<br />
do, and when and how to use them. Finally, <em>Using Memcache</em> will introduce App<br />
Engine&#8217;s <strong>Memcache</strong> service, which provides a volatile-memory key-value store, and<br />
discuss the use of Memcache to speed up your app.</p>
<p>In this chapter, we will use for our examples the full version of the<br />
<em>Connectr</em> app, ConnectrFinal.</p>
<h1>Data modeling and scalability</h1>
<p>In deciding how to design your application&#8217;s data models, there are a number of<br />
ways in which your approach can increase the app&#8217;s scalability and responsiveness.<br />
In this section, we discuss several such approaches and how they are applied in<br />
the <em>Connectr</em> app. In particular, we describe how the Datastore access latency can<br />
sometimes be reduced; ways to split data models across entities to increase the<br />
efficiency of data object access and use; and how property lists can be used to<br />
support &#8220;join-like&#8221; behavior with Datastore entities.</p>
<h2>Reducing latency—read consistency and Datastore access deadlines</h2>
<p>By default, when an entity is updated in the Datastore, all subsequent reads of that<br />
entity will see the update at the same time; this is called <strong>strong consistency</strong>. To<br />
achieve it, each entity has a primary storage location, and with a strongly consistent<br />
read, the read waits for a machine at that location to become available. Strong<br />
consistency is the default in App Engine.</p>
<p>However, App Engine allows you to change this default and use <strong>eventual<br />
consistency</strong> for a given Datastore read. With eventual consistency, the query<br />
may access a copy of the data from a secondary location if the primary location is<br />
temporarily unavailable. Changes to data will propagate to the secondary locations<br />
fairly quickly, but it is possible that an &#8220;eventually consistent&#8221; read may access a<br />
secondary location before the changes have been incorporated. However, eventually<br />
consistent reads are faster on average, so they trade consistency for availability. In<br />
many contexts, for example, with web apps such as <em>Connectr</em> that display &#8220;activity<br />
stream&#8221; information, this is an acceptable tradeoff—completely up-to-date freshness<br />
of information is not required.</p>
<pre><code>
 This touches on a complex and interesting field beyond the scope of
 this book. See http://googleappengine.blogspot.com/2010/03/
 read-consistency-deadlines-more-control.html,

http://googleappengine.blogspot.com/2009/09/migrationto-

 better-datastore.html, and http://code.google.com/
 events/io/2009/sessions/TransactionsAcrossDatacenters.
 html for more background on this and related topics.
 </code></pre>
<p>In <em>Connectr</em>, we will add the use of eventual consistency to some of our feed object<br />
reads; specifically, those for feed content updates. We are willing to take the small<br />
chance that a feed object is slightly out-of-date in order to have the advantage of<br />
quicker reads on these objects.</p>
<p>The following code shows how to set eventual read consistency for a query, using<br />
server.servlets.FeedUpdateFriendServlet as an example.</p>
<pre><code>
 Query q = pm.newQuery("select from " + FeedInfo.class.getName() +
 "where urlstring == :keys");
 //Use eventual read consistency for this query
 q.addExtension("datanucleus.appengine.datastoreReadConsistency",
 "EVENTUAL");
 </code></pre>
<p>App Engine also allows you to change the default Datastore <em>access deadline</em>. By<br />
default, the Datastore will retry access automatically for up to about 30 seconds.<br />
You can set this deadline to a smaller amount of time. It can often be appropriate to<br />
set a shorter deadline if you are concerned with response latency, and are willing to<br />
use a cached version of the data for which you got the timeout, or are willing to do<br />
without it.</p>
<p>The following code shows how to set an access timeout interval (in milliseconds) for<br />
a given JDO query.</p>
<pre><code>
 Query q = pm.newQuery("…");
 // Set a Datastore access timeout
 q.setTimeoutMillis(10000);
 </code></pre>
<h2>Splitting big data models into multiple entities to make access more efficient</h2>
<p>Often, the fields in a data model can be divided into two groups: main and/or<br />
summary information that you need often/first, and <em>details</em>—the data that you might<br />
not need or tend not to need immediately. If this is the case, then it can be productive<br />
to split the data model into multiple entities and set the <em>details</em> entity to be a child of<br />
the summary entity, for instance, by using JDO owned relationships. The child field<br />
will be fetched lazily, and so the child entity won&#8217;t be pulled in from the Datastore<br />
unless needed.</p>
<p>In our app, the Friend model can be viewed like this: initially, only a certain amount<br />
of summary information about each Friend is sent over RPC to the app&#8217;s frontend<br />
(the Friend&#8217;s name). Only if there is a request to view details of or edit a particular<br />
Friend, is more information needed.</p>
<p>So, we can make retrieval more efficient by defining a parent <em>summary</em> entity, and<br />
a child <em>details</em> entity. We do this by keeping the &#8220;summary&#8221; information in Friend,<br />
and placing &#8220;details&#8221; in a FriendDetails object , which is set as a child of Friend<br />
via a JDO bidirectional, one-to-one owned relationship, as shown in Figure 1. We<br />
store the Friend&#8217;s e-mail address and its list of associated URLs in FriendDetails.<br />
We&#8217;ll keep the name information in Friend. That way, when we construct the initial<br />
&#8216;FriendSummaries&#8217; list displayed on application load, and send it over RPC, we only<br />
need to access the summary object.</p>
<p><center><img src="images/2011/01/GoogleApp/1.jpg" alt="" /></center>A details field of Friend points to the FriendDetails child, which we create when<br />
we create a Friend. In this way, the details will always be transparently available<br />
when we need them, but they will be lazily fetched—the details child object won&#8217;t<br />
be initially retrieved from the database when we query Friend, and won&#8217;t be fetched<br />
unless we need that information.</p>
<p>As you may have noticed, the Friend model is already set up in this manner—this is<br />
the rationale for that design.</p>
<h2>Discussion</h2>
<p>When splitting a data model like this, consider the queries your app will perform<br />
and how the design of the data objects will support those queries. For example,<br />
if your app often needs to query for property1 == x and property2 == y, and<br />
especially if both individual filters can produce large result sets, you are probably<br />
better off keeping both those properties on the same entity (for example, retaining<br />
both fields on the &#8220;main&#8221; entity, rather than moving one to a &#8220;details&#8221; entity).</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>For persistent classes (that is, &#8220;data classes&#8221;) that you often access and update, it is<br />
also worth considering whether any of its fields do not require indexes. This would<br />
be the case if you never perform a query which includes that field. The fewer the<br />
indexed fields of a persistent class, the quicker are the writes of objects of that cl ass.</p>
<h2>Splitting a model by creating an &#8220;index&#8221; and a &#8220;data&#8221; entity</h2>
<p>You can also consider splitting a model if you identify fields that you access only<br />
when performing queries, but don&#8217;t require once you&#8217;ve actually retrieved the object.<br />
Often, this is the case with multi-valued properties. For example, in the <em>Connectr</em> app,<br />
this is the case with the friendKeys list of the server.domain.FeedIndex class (first<br />
encountered in <em>Chapter 7</em>). This multi-valued property is used to find relevant feed<br />
objects but is not used when displaying feed content information.</p>
<p>With App Engine, there is no way for a query to retrieve only the fields that you<br />
need (with the exception of <em>keys-only</em> queries, as introduced in <em>Chapter 5</em>), so the<br />
full object must always be pulled in. If the multi-valued property lists are long,<br />
this is inefficient.</p>
<p>To avoid this inefficiency, we can split up such a model into two parts, and put each<br />
one in a different entity—an index entity and a data entity. The <strong>index entity</strong> holds<br />
only the multi-valued properties (or other data) used only for querying, and the <strong>data<br />
entity</strong> holds the information that we actually want to use once we&#8217;ve identified the<br />
relevant objects. The trick to this new design is that the data entity key is defined to<br />
be the parent of the index entity key.</p>
<p>More specifically, when an entity is created, its key can be defined as a &#8220;child&#8221; of<br />
another entity&#8217;s key, which becomes its parent. The child is then in the same <strong>entity<br />
group</strong> as the parent (we discuss entity groups further in the <em>Using transactions</em><br />
section). Because such a child key is based on the path of its parent key, it is possible<br />
to derive the parent key given only the child key, using the getParent() method of<br />
Key, without requiring the child to be instantiated.</p>
<p>So with this design, we can first do a <em>keys-only</em> query on the index kind (which is<br />
faster than full object retrieval) to get a list of the keys of the relevant index entities.<br />
With that list, even though we&#8217;ve not actually retrieved the index objects themselves,<br />
we can derive the parent data entity keys from the index entity keys. We can then do<br />
a <em>batch fetch</em> with the list of relevant parent keys to grab all the data entities at once.<br />
This lets us retrieve the information we&#8217;re interested in, without having to retrieve<br />
the properties that we do not need.</p>
<pre><code>
 See Brett Slatkin's presenta tion, <em>Building scalable, complex
 apps on App Engine</em> (http://code.google.com/events/
 io/2009/sessions/BuildingScalableComplexApps.
 html) for more on this index/data des ign.
 </code></pre>
<p><center><img src="images/2011/01/GoogleApp/2.jpg" alt="" /></center>Our feed model (which was introduced in <em>Chapter 7</em>) maps well to this design—we<br />
filter on the FeedIndex.friendKeys multi-valued property (which contains the list<br />
of keys of Friends that point to this feed) when we query for the feeds associated<br />
with a given Friend.</p>
<p>But, once we have retrieved those feeds, we don&#8217;t need the friendKeys list further.<br />
So, we would like to avoid retrieving them along with the feed content. With our<br />
app&#8217;s sample data, these property lists will not comprise a lot of data, but they would<br />
be likely to do so if the app was scaled up. For example, many users might have the<br />
same friends, or many different contacts might include the same company blog in<br />
their associated feeds.</p>
<p>So, we split up the feed model into an index part and a parent data part, as shown in<br />
Figure 2. The index class is server.domain.FeedIndex; it contains the friendKeys<br />
list for a feed. The data part, containing the actual feed content, is server.domain.<br />
FeedInfo. When a new FeedIndex object is created, its key will be constructed so<br />
that its corresponding FeedInfo object &#8216;s key is its parent key. This construction must<br />
of course take place at object creation, as Datastore entity keys cannot be changed.</p>
<pre><code>
 For a small-scale app, the payoff from this split model would
 perhaps not be worth it. But for the sake of example, let's
 assume that we expect our app to grow significantly.
 </code></pre>
<p>The FeedInfo persistent class —the parent class—simply uses an app-assigned<br />
String primary key, urlstring (the feed URL string). The server.domain.<br />
FeedIndex constructor, shown in the code below, uses the key of its FeedInfo<br />
parent—the URL string—to construct its key. (The <em>Using transactions</em> section will<br />
describe the key-construction code of the figure in more detail). This places the two<br />
entities into the same <strong>entity group</strong> and allows the parent FeedInfo key to be derived<br />
from the FeedIndex entity&#8217;s key.</p>
<pre><code>
 @PersistenceCapable(identityType = IdentityType.APPLICATION,
 detachable="true")
 public class FeedIndex implements Serializable {
 @PrimaryKey
 @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
 private Key key;
 …</code></pre>
<p>public FeedIndex(String fkey, String url) {<br />
this.friendKeys = new HashSet&lt;String&gt;();<br />
this.friendKeys.add(fkey);<br />
KeyFactory.Builder keyBuilder =<br />
new KeyFactory.Builder(FeedInfo.class.getSimpleName(), url);<br />
keyBuilder.addChild(FeedIndex.class.getSimpleName(), url);<br />
Key ckey = keyBuilder.getKey();<br />
this.key= ckey;<br />
}</p>
<p>The following code, from server.servlets.FeedUpdateFriendServlet, shows<br />
how this model is used to efficiently retrieve the FeedInfo objects associated<br />
with a given Friend. Given a Friend key, a query is performed for the keys of<br />
the FeedIndex entities that contain this Friend key in their friendKeys list.<br />
Because this is a <em>keys-only</em> query, it is much more efficient than returning the actual<br />
objects. Then, each FeedIndex key is used to derive the parent (FeedInfo) key.<br />
Using that list of parent keys, a <em>batch fetch</em> is performed to fetch the FeedInfo objects<br />
associated with the given Friend. We did this without needing to actually fetch the<br />
FeedIndex object s.</p>
<pre><code>
 … imports…
 @SuppressWarnings("serial")
 public class FeedUpdateFriendServlet extends HttpServlet{</code></pre>
<p>private static Logger logger =<br />
Logger.getLogger(FeedUpdateFriendServlet.class.getName());<br />
public void doPost(HttpServletRequest req, HttpServletResponse resp)<br />
throws IOException {<br />
PersistenceManager pm = PMF.get().getPersistenceManager();<br />
Query q = null;<br />
try {<br />
String fkey = req.getParameter(&#8220;fkey&#8221;);<br />
if (fkey != null) {<br />
logger.info(&#8220;in FeedUpdateFriendServlet, updating feeds for:&#8221;<br />
+fkey);<br />
// query for matching FeedIndex keys<br />
q = pm.newQuery(&#8220;select key from &#8220;+FeedIndex.class.getName()+&#8221;<br />
where friendKeys == :id&#8221;);<br />
List ids=(List)q.execute(fkey);<br />
if (ids.size()==0) {<br />
return;<br />
}<br />
// else, get the parent keys of the ids<br />
Key k = null;<br />
List&lt;Key&gt;parent list = new ArrayList&lt;Key&gt;();<br />
for (Object id : ids) {<br />
// cast to key<br />
k = (Key)id;<br />
parentlist.add(k.getParent());<br />
}<br />
// fetch the parents using the keys<br />
Query q2 = pm.newQuery(&#8220;select from +FeedInfo.class.getName()+<br />
&#8220;where urlstring == :keys&#8221;);<br />
// allow eventual consistency on read<br />
q2.addExtension(<br />
&#8220;datanucleus.appengine.datastoreReadConsistency&#8221;,<br />
&#8220;EVENTUAL&#8221;);<br />
List&lt;FeedInfo&gt;results =<br />
(List&lt;FeedInfo&gt;)q2.execute(parentlist);<br />
if(results.iterator().hasNext()){<br />
for(FeedInfo fi: results){<br />
fi.updateRequestedFeed(pm);<br />
}<br />
}<br />
}<br />
}<br />
catch (Exception e) {<br />
logger.warning(e.getMessage());<br />
}<br />
finally {<br />
if q!=null) {<br />
q.closeAll();<br />
}<br />
pm.close();<br />
}<br />
}<br />
}//end class</p>
<h2>Use of property lists to support &#8220;join&#8221; behavior</h2>
<p>Google App Engine does not support joins with the same generality as a relational<br />
database. However, property lists along with accompanying denormalization can<br />
often be used in GAE to support join-like functionality in a very efficient manner.</p>
<pre><code>
 At the time of writing, there is GAE work in progress to support simple
 joins. However, this functionality is not yet officially part of the SDK.
 </code></pre>
<p>Consider the many-to-many relationship between Friend and feed information<br />
in our application. With a relational database, we might support this relationship<br />
by using three tables: one for Friend data, one for Feed data, and a &#8220;join table&#8221;<br />
(sometimes called a &#8220;cross-reference table&#8221;), named, say, FeedFriend, with two<br />
columns—one for the friend ID and one for the feed ID. The rows in the join table<br />
would indicate which feeds were associated with which friends.</p>
<p>In our hypothetical relational database, a query to find the feeds associated with a<br />
given Friend fid would look something like this:</p>
<pre><code>
 select feed.feedname from Feed feed, FeedFriend ff
 where ff.friendid = 'fid' and ff.feedid = feed.id
 </code></pre>
<p>If we wanted to find those feeds that both Friend 1 (fid1) and Friend 2 (fid2) had<br />
listed, the query would look something like this:</p>
<pre><code>
 select feed.feedname from Feed feed, FeedFriend f1, FeedFriend f2
 where f1.friendid = 'fid1' and f1.feedid = feed.id
 and f2.friendid = 'fid2' and f2.feedid = feed.id
 </code></pre>
<p>With Google App Engine, to support this type of query, we can denormalize<br />
the &#8220;join table&#8221; information and use Datastore multi-valued properties to hold<br />
the denormalized information. (Denormalization should not be considered a<br />
second-class citizen in GAE).</p>
<p>In <em>Connectr</em>, feed objects hold a list of the keys of the Friends that list that feed<br />
(friendKeys), and each Friend holds a list of the feed URLs associated with it.<br />
<em>Chapter 7</em> included a figure illustrating this many-to-many relationship.</p>
<p>So, with the first query above, the analogous JDQL query is:</p>
<pre><code>
 select from FeedIndex where friendKeys == 'fid'
 </code></pre>
<p>If we want to find those feeds that are listed by both Friend 1 and Friend 2, the JDQL<br />
query is:</p>
<pre><code>
 select from FeedIndex where friendKeys == 'fid1' and
 friendKeys == 'fid2'
 </code></pre>
<p>Our data model, and its use of multi-valued properties, has allowed these queries to<br />
be very straightforward and efficient in GAE.</p>
<h2>Supporting the semantics of more complex joins</h2>
<p>The semantics of more complex join queries can sometimes be supported in GAE<br />
with multiple synchronously-ordered multi-valued properties.</p>
<p>For example, suppose we decided to categorize the associated feeds of Friends by<br />
whether they were &#8220;Technical&#8221;, &#8220;PR&#8221;, &#8220;Personal&#8221;, &#8220;Photography-related&#8221;, and so on<br />
(and that we had some way of determining this categorization on a feed-by-feed<br />
basis). Then, suppose we wanted to find all the Friends whose feeds include &#8220;PR&#8221;<br />
feed(s), and to list those feed URLs for each Friend.</p>
<p>In a relational database, we might support this by adding a &#8220;Category&#8221; table to hold<br />
category names and IDs, and adding a category ID column to the Feed table. Then,<br />
the query might look like this:</p>
<pre><code>
 select f.lastName, feed.feedname from Friend f, Category c,
 Feed feed, FeedFriend ff
 where c.id = 'PR' and feed.cat_id = c.id and ff.feedid = feed.id
 and ff.friend.id = f.id
 </code></pre>
<p>We might attempt to support this type of query in GAE by adding a<br />
feedCategories multi-valued property list to Friend, which contained all the<br />
categories in which their feeds fell. Every time a feed was added to the Friend, this<br />
list would be updated with the new category as necessary. We could then perform a<br />
JDQL query to find all such Friends:</p>
<pre><code>
 select from Friend where feedCategories == 'PR'
 </code></pre>
<p>However, for each returned Friend we would then need to check each of their<br />
feeds in turn to determine which feed(s) were the PR ones—requiring further<br />
Datastore access.</p>
<p>To address this, we could build a Friend feedCategories multi-valued property list<br />
whose ordering was synchronized with the urls list ordering, with the <em>nth</em> position<br />
in the categories list indicating the category of the <em>nth</em> feed. For exam ple, suppose<br />
that url1 and url3 are of category &#8216;PR&#8217;, and url2 is of category &#8216;Technical&#8217;. The two<br />
lists would then be sorted as follows:</p>
<pre><code>
 urls = [ url1, url2, url3, … ]</code></pre>
<p>feedCategories = [PR, TECHNICAL, PR, …]</p>
<p>(For efficiency, we would probably map the categories to integers). Then, for each<br />
Friend returned from the previous query, we could determine which feed URLs<br />
were the &#8216;PR&#8217; ones by their position in the feed list, without requiring further<br />
Datastore queries. In the previous example, it would be the URLs at positions 0<br />
and 2— url1 and url3.</p>
<p>This technique requires more expense at write time, in exchange for more efficient<br />
queries at read time. The approach is not always applicable—for example, it requires<br />
a one-to-one mapping between the items in the synchronized property lists, but can<br />
be very effective when it does apply.</p>
<h2>GWT Articles &amp; Books</h2>
<ul>
<li><a href="http://www.javabeat.net/articles/28-google-web-toolkitgwt-1.html">Google Web ToolKit(GWT)</a></li>
<li><a href="http://www.javabeat.net/books/gwt/1/">GWT Books</a></li>
<li><a href="code.google.com/webtoolkit/">GWT Official Site</a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/01/google-app-engine-java-and-gwt-application-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>History Management in GWT</title>
		<link>http://www.javabeat.net/2011/01/history-management-in-gwt/</link>
		<comments>http://www.javabeat.net/2011/01/history-management-in-gwt/#comments</comments>
		<pubDate>Sat, 22 Jan 2011 12:58:41 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[GWT]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=536</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction GWT is a toolkit used to write AJAX applications using java language. It comes with Java to JavaScript compiler and a special browser that helps in debugging the GWT applications. GWT Provides lot of user interface widgets that can be utilized to create new applications.There are two modes of running GWT application. They are: [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p><strong>GWT </strong>is a toolkit used to write AJAX applications using java language. It comes with Java to JavaScript compiler and a special browser that helps in debugging the <strong>GWT</strong> applications. <strong>GWT</strong> Provides lot of user interface widgets that can be utilized to create new applications.There are two modes of running <strong>GWT</strong> application. They are: 1.</p>
<p><strong>also read:</strong></p>
<ul>
<li><a href="http://www.javabeat.net/2011/11/code-splitting-in-gwt/">Code Splitting in GWT</a></li>
<li><a href="http://www.javabeat.net/2011/11/what-is-model-view-presenter-mvp-in-gwt-application/">What is Model View Presenter (MVP) in GWT Application?</a></li>
<li><a href="http://www.javabeat.net/2011/01/internationalisationi18n-in-gwt-application/">Internationalisation(i18n) in GWT Application</a></li>
</ul>
<p><strong>Development mode</strong> 2.<strong>Production mode</strong>.</p>
<p>In Development Mode, the application runs java byte code within the JVM.</p>
<p>As it runs within the JVM it takes the advantage of java’s debugging facilities. In Production Mode ,the application run’s as JavaScript and HTML using GWT compiler which converts Java code to JavaScript.</p>
<h2>History Class</h2>
<p>As most other Ajax based applications, <strong>GWT</strong> applications also run in a single page. This approach of work creates the problem of Back Button. The problem is if the user needs to go to previous page or next page then the results will be unpredictable. <strong>GWT</strong> provides a solution for this problem is through the <strong>History</strong> class.</p>
<p>Browser history keeps track of all the URLs that are loaded. It is a dynamic stack of URLs, where the browser displays the top URL of the stack. History class is used to interact with the browser’s history stack. <strong>GWT</strong> maintains the browser history as tokens which hold the state of the application mapped to them by the developer. Token is represented as String which should be associated to a given in the program. All the History class methods are static. Some of the methods of them are <strong>getToken()</strong>, <strong>newItem(String)</strong>, <strong>back()</strong>,<strong> forward()</strong> , <strong>addValueChangeHandler()</strong> and so on.</p>
<h2>Sample Application</h2>
<p>The sample application we discuss here demonstrates how to add history support to the <strong>GWT</strong> application. We will create Login application which has the history support. In this application, we will create two views one is Login view and the other one is Welcome view. Let us see the step by step procedure for the same.</p>
<h2>Software Requirements</h2>
<p>For this Sample application i have used the following software&#8217;s.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<ul>
<li>JDK 1.6</li>
<li>Eclipse 3.6 IDE</li>
<li><strong>GWT</strong> SDK 2.1.1</li>
<li><strong>GWT</strong> Eclipse Plug-in</li>
<li><strong>GWT</strong> plug-in for chrome browser. (to run in development mode)</li>
</ul>
<h2>Project Structure</h2>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/01/11.jpg"><img class="aligncenter size-full wp-image-1003" title="1" alt="" src="http://www.javabeat.net/wp-content/uploads/2011/01/11.jpg" width="263" height="242" /></a></p>
<h2>Steps to add History support</h2>
<ol>
<li>
<h3>Setup the HTML page.</h3>
</li>
</ol>
<ul>
<li>Add the following iframe to the html page(home<br />
page) of the application.</li>
</ul>
<pre class="brush: java; title: ; notranslate">
&lt;iframe src=&quot;javascript:''&quot; id=&quot;__gwt_historyFrame&quot; tabIndex='-1'

           style=&quot;position:absolute;width:0;height:0;border:0&quot;&gt;

          &lt;/iframe&gt;
</pre>
<p>This iframe will be automatically inserted in the html page when creating the Application. This code is required if your application is running in ie6 or ie7 which lack the necessary <strong>onhashchange</strong> event. This script is not required for Firefox, chrome, safari or ie8 browsers. Ie8 browser supports the <strong>onhashchange</strong> event so it works on ie8 without this script.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/01/21.jpg"><img class="aligncenter size-medium wp-image-1005" title="2" alt="" src="http://www.javabeat.net/wp-content/uploads/2011/01/21-300x230.jpg" width="300" height="230" /></a></p>
<h3>2. Add the valueChangeHandler to the application EntryPoint Class.</h3>
<p>The handler will be invoked on every history change event. Below is the code for adding the handler to the application.</p>
<pre class="brush: java; title: ; notranslate">public class LoginHistoryDemo implements EntryPoint, ValueChangeHandler {
private static final String LOGIN_TOKEN = &quot;login&quot;;
private static final String WELCOME_TOKEN = &quot;welcome&quot;;

Label nameError = new Label();
Label pwdError = new Label();
final TextBox nameTextbox = new TextBox();
final PasswordTextBox passwordTextbox = new PasswordTextBox();

public void onModuleLoad() {
setupHistory();
}

private void setupHistory() {
History.addValueChangeHandler(this);
History.newItem(LOGIN_TOKEN, true);
}
}</pre>
<p>When the first time application gets loaded, there will not be any change event. We need to set the initial token for the first load using<br />
<strong>History.newItem(LOGIN_TOKEN,true); </strong>Where in the above code LOGIN_TOKEN and WELCOME_TOKEN are two tokens representing two views of our application. The initial view of application is set to LOGIN_TOKEN.</p>
<h3>3.Create the two views Login and welcome.</h3>
<pre class="brush: java; title: ; notranslate">
private void loadLoginView() {
    final Label loginPrompt = new Label(&quot;Please Log in&quot;);
    final Grid grid = new Grid(3, 3);
    final Label namePrompt = new Label(&quot;Name&quot;);
    final Label passwordPrompt = new Label(&quot;Password&quot;);
    final Button button = new Button(&quot;Login&quot;);
private void loadLoginView() {
final Label loginPrompt = new Label(&quot;Please Log in&quot;);
final Grid grid = new Grid(3, 3);
final Label namePrompt = new Label(&quot;Name&quot;);
final Label passwordPrompt = new Label(&quot;Password&quot;);
final Button button = new Button(&quot;Login&quot;);

button.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if (validateFormInput())
History.newItem(WELCOME_TOKEN);
}
});

loginPrompt.addStyleName(&quot;loginPrompt&quot;);
nameTextbox.addStyleName(&quot;nameField&quot;);
passwordTextbox.addStyleName(&quot;passwordField&quot;);
grid.setWidget(0, 0, namePrompt);
grid.setWidget(0, 1, nameTextbox);
grid.setWidget(0, 2, nameError);
grid.setWidget(1, 0, passwordPrompt);
grid.setWidget(1, 1, passwordTextbox);
grid.setWidget(1, 2, pwdError);
grid.setWidget(2, 1, button);

RootPanel.get().clear();
RootPanel.get().add(loginPrompt);
RootPanel.get().add(grid);
}

private void loadWelcomeView() {
final Label welcomeMsg = new Label(&quot;Welcome to the GWT History Demo&quot;);

welcomeMsg.addStyleName(&quot;welcomeMsg&quot;);

RootPanel.get().clear();
RootPanel.get().add(welcomeMsg);
RootPanel.get().add(new Hyperlink(&quot;Logout&quot;, LOGIN_TOKEN));
}</pre>
<p>Here the username and password fields are validated using the method  <em><strong><code>validateFormInput(). </code></strong></em></p>
<pre class="brush: java; title: ; notranslate">protected boolean validateFormInput() {

// validating the username and password fields
String name = nameTextbox.getText();
boolean nameIsValid = name.length() &gt; 0;
nameError.setText(nameIsValid ? &quot;&quot; : &quot;Please enter the Name&quot;);

String pwd = passwordTextbox.getText();
boolean pwdIsValid = pwd.length() &gt; 0;
pwdError.setText(pwdIsValid ? &quot;&quot; : &quot;Please enter the Password&quot;);

return (name</pre>
<h3>4. Implement the onValueChangeEvent() method of the ValueChangeHandler</h3>
<pre class="brush: java; title: ; notranslate">public void onValueChange(ValueChangeEvent event) {
     String historyToken = event.getValue();
     if (LOGIN_TOKEN.equals(historyToken)) {
        loadLoginView();
     } else if (WELCOME_TOKEN.equals(historyToken)) {
        loadWelcomeView();
     }

   }</pre>
<p>On every History change event the appropriate view gets displayed. This changing of views should be written inside the onValueChange() method of the Handler. When the user clicks the Login button, we call History.newItem() but this time we pass the WELCOME_TOKEN token. Once again, <strong>GWT</strong> invokes our history Handler’s onValueChange method.</p>
<h3>Putting it all Together</h3>
<pre class="brush: java; title: ; notranslate">public class LoginHistoryDemo implements EntryPoint, ValueChangeHandler {
	private static final String LOGIN_TOKEN = &quot;login&quot;;
	private static final String WELCOME_TOKEN = &quot;welcome&quot;;
	Label nameError = new Label();
	Label pwdError = new Label();
	final TextBox nameTextbox = new TextBox();
	final PasswordTextBox passwordTextbox = new PasswordTextBox();

	public void onModuleLoad() {
		setupHistory();
	}

	private void setupHistory() {
		History.addValueChangeHandler(this);
		History.newItem(LOGIN_TOKEN, true);
	}

	private void loadLoginView() {
		final Label loginPrompt = new Label(&quot;Please Log in&quot;);
		final Grid grid = new Grid(3, 3);
		final Label namePrompt = new Label(&quot;Name&quot;);
		final Label passwordPrompt = new Label(&quot;Password&quot;);
		final Button button = new Button(&quot;Login&quot;);
		button.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				if (validateFormInput())
					History.newItem(WELCOME_TOKEN);
			}
		});
		loginPrompt.addStyleName(&quot;loginPrompt&quot;);
		nameTextbox.addStyleName(&quot;nameField&quot;);
		passwordTextbox.addStyleName(&quot;passwordField&quot;);
		grid.setWidget(0, 0, namePrompt);
		grid.setWidget(0, 1, nameTextbox);
		grid.setWidget(0, 2, nameError);
		grid.setWidget(1, 0, passwordPrompt);
		grid.setWidget(1, 1, passwordTextbox);
		grid.setWidget(1, 2, pwdError);
		grid.setWidget(2, 1, button);

		RootPanel.get().clear();
		RootPanel.get().add(loginPrompt);
		RootPanel.get().add(grid);
	}

	private void loadWelcomeView() {
		final Label welcomeMsg = new Label(&quot;Welcome to the GWT History Demo&quot;);

		welcomeMsg.addStyleName(&quot;welcomeMsg&quot;);

		RootPanel.get().clear();
		RootPanel.get().add(welcomeMsg);
		RootPanel.get().add(new Hyperlink(&quot;Logout&quot;, LOGIN_TOKEN));
	}

	protected boolean validateFormInput() {

		// validating the password is not empty
		String name = nameTextbox.getText();
		boolean nameIsValid = name.length() &gt; 0;
		nameError.setText(nameIsValid ? &quot;&quot; : &quot;Please enter the Name&quot;);

		String pwd = passwordTextbox.getText();
		boolean pwdIsValid = pwd.length() &gt; 0;
		pwdError.setText(pwdIsValid ? &quot;&quot; : &quot;Please enter the Password&quot;);

		return (nameIsValid &amp;&amp; pwdIsValid);
	}

	@Override
	public void onValueChange(ValueChangeEvent event) {
		String historyToken = event.getValue();
		if (LOGIN_TOKEN.equals(historyToken)) {
			loadLoginView();
		} else if (WELCOME_TOKEN.equals(historyToken)) {
			loadWelcomeView();
		}

	}

}</pre>
<h2><a href="http://www.javabeat.net/wp-content/uploads/2011/01/31.jpg"><img class="aligncenter size-medium wp-image-1002" title="3" alt="" src="http://www.javabeat.net/wp-content/uploads/2011/01/31-300x164.jpg" width="300" height="164" /></a></h2>
<h2>Conclusion</h2>
<p><strong>also read:</strong></p>
<ul>
<li><a href="http://www.javabeat.net/2011/11/code-splitting-in-gwt/">Code Splitting in GWT</a></li>
<li><a href="http://www.javabeat.net/2011/11/what-is-model-view-presenter-mvp-in-gwt-application/">What is Model View Presenter (MVP) in GWT Application?</a></li>
<li><a href="http://www.javabeat.net/2011/01/internationalisationi18n-in-gwt-application/">Internationalisation(i18n) in GWT Application</a></li>
</ul>
<p>In this article we learned how to add History support to the <strong>GWT</strong> application, allowing the user to use the Back and Forward buttons of the browser at will, leading to a general launcher for any application.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/01/history-management-in-gwt/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>What is Ext GWT 2.0?</title>
		<link>http://www.javabeat.net/2010/12/what-is-ext-gwt-2-0/</link>
		<comments>http://www.javabeat.net/2010/12/what-is-ext-gwt-2-0/#comments</comments>
		<pubDate>Fri, 10 Dec 2010 00:22:17 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[GWT]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1598</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Ext GWT 2.0Ext GWT 2.0: Beginner&#8217;s Guide is a practical book that teaches you how to use the Ext GWT library to its full potential. It provides a thorough, no-nonsense explanation of the Ext GWT library, what it offers, and how to use it through practical examples. This book provides clear, step-by-step instructions for getting [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><center>Ext GWT 2.0</center>Ext <a href="http://astore.amazon.com/javabeat-20?_encoding=UTF8&amp;node=32">GWT 2.0</a>: Beginner&#8217;s Guide is a practical book that teaches you how to use the Ext<br />
GWT library to its full potential. It provides a thorough, no-nonsense explanation of the<br />
Ext GWT library, what it offers, and how to use it through practical examples. This book<br />
provides clear, step-by-step instructions for getting the most out of Ext GWT and offers<br />
practical examples and techniques that can be used for building your own applications in<br />
Ext <a href="http://astore.amazon.com/javabeat-20?_encoding=UTF8&amp;node=32">GWT</a>.</p>
<p>This book gets you up and running instantly to build powerful Rich Internet Applications<br />
(RIA) with Ext GWT. It then takes you through all the interface-building widgets and<br />
components of Ext <a href="http://astore.amazon.com/javabeat-20?_encoding=UTF8&amp;node=32">GWT</a> using practical examples to demonstrate when, where, and how<br />
to use each of them. Layouts, forms, panels, grids, trees, toolbars, menus, and many other<br />
components are covered in the many examples packed in this book. You will also learn to<br />
present your data in a better way with templates and use some of the most sought-after<br />
features of Ext GWT in your web applications such as drag-and-drop and charts.<br />
Throughout the book, a real application is built step-by-step using Ext GWT and<br />
deployed to Google App Engine.</p>
<p>Imagine how great you&#8217;ll feel when you&#8217;re able to create great-looking desktop-style user<br />
interfaces for your web applications with Ext GWT!</p>
<h2>GWT Articles</h2>
<ul>
<li>Buy <a href="http://astore.amazon.com/javabeat-20/detail/1933988231" target="_blank">GWT in Action</a> from <a href="http://astore.amazon.com/javabeat-20?_encoding=UTF8&amp;node=32" target="_blank">GWT Books</a> Store</li>
<li><a href="http://www.javabeat.net/articles/12-comparison-of-ajax-frameworks-prototype-gwt-dwr-and-1.html">Comparison of AJAX Frameworks</a></li>
<li><a href="http://www.javabeat.net/articles/28-google-web-toolkitgwt-1.html">Google Web ToolKit(GWT)</a></li>
</ul>
<h1>What This Book Covers</h1>
<p><em>Chapter 1, Getting Started with Ext <a href="http://astore.amazon.com/javabeat-20?_encoding=UTF8&amp;node=32">GWT</a></em>, introduces Ext GWT and explains where it fits<br />
into GWT. It then moves on to show how to get up and running with Ext GWT by<br />
creating your first project.</p>
<p><em>Chapter 2, The Building Blocks</em>, starts by looking at the explorer demo application. It<br />
then introduces the world of GXT components, beginning with some key concepts, and<br />
quickly moves on to practically working with an example application.</p>
<p><em>Chapter 3, Forms and Windows</em>, explores GXT&#8217;s form features. It looks at the form<br />
components that GXT provides and demonstrates how to put them to use. It also<br />
introduces the GXT Registry and shows how it can be used across the application.</p>
<p><em>Chapter 4, Data-backed Components</em>, explains how GXT facilitates working with data. It<br />
looks at the components available for retrieving, manipulating, and processing data and<br />
then moves on to work with the built-in data-backed display components.</p>
<p><em>Chapter 5, More Components</em>, introduces more advanced data-backed components<br />
and the extensions that build on the components covered in the previous chapter. It<br />
then moves on to cover additional advanced components—specifically menus, toolbars,<br />
and tabs.</p>
<p><em>Chapter 6, Templates</em>, looks at templates and how they can be used to easily format and<br />
display data in a highly customizable way. It also introduces the more powerful features<br />
of XTemplates.</p>
<p><em>Chapter 7, Model View Controller</em>, explains GXT&#8217;s Model View Controller framework<br />
and demonstrates how it can allow components to communicate in larger applications.</p>
<p><em>Chapter 8, Portal and Drag-and-Drop</em>, covers the portal and drag-and-drop features<br />
of GXT. It starts by showing how to turn out existing components into portlets and<br />
then moves on to practically make use of GXT&#8217;s drag-and-drop features to move data<br />
between them.</p>
<p><em>Chapter 9, Charts</em>, covers GXT&#8217;s charting plugin. It explores the wide range of charts<br />
available, shows how to avoid the pitfalls of the plugin, and demonstrates how charts can<br />
be used with existing data.</p>
<p><em>Chapter 10, Putting it all together</em>, shows how to publish the example application to the<br />
world using the Google App Engine. It then moves on to look at how to take<br />
development with GXT further and other resources that can be turned to after this book.</p>
<p><center>Data-backed Components</center></p>
<pre><code><em>
 In this chapter, we introduce how GXT allows us to work with data. We look at
 the components available for retrieving, manipulating, and processing data,
 and then move on to work with the built-in data-backed display components.
 </em></code></pre>
<p>We shall cover the following components:</p>
<p>Data</p>
<ul>
<li>ModelData</li>
<li>BeanModel</li>
<li>BeanModelTag</li>
<li>BeanModelMarker</li>
<li>BeanModelFactory</li>
<li>Stores</li>
</ul>
<p>Remote Data</p>
<ul>
<li>DataProxies</li>
<li>DataReaders</li>
<li>ListLoadResults</li>
<li>ModelType</li>
<li>Loaders</li>
<li>LoadConfigs</li>
</ul>
<p>Data-backed components</p>
<ul>
<li>ListField</li>
<li>ComboBox</li>
<li>Grid</li>
<ul>
<li>ColumnModel</li>
<li>ColumnConfig</li>
<li>GridCellRenderer</li>
</ul>
</ul>
<h1>Working with data</h1>
<p>One of the advantages of AJAX applications, including those built with GXT, is the ability to<br />
manipulate data in the browser. GXT provides useful data-backed visual components that<br />
allow us to work with local data such as lists, combos, and grids. With them we can perform<br />
sorting, filtering, and editing operations on data quickly and efficiently.</p>
<p>There is also another set of components that work in the background allowing us to retrieve<br />
remote data, cache it on the client, and deliver it to the visual components. It is these two<br />
sets of components that we are going to focus on in this chapter.</p>
<p>First of all, we are going to look at how to produce the data that we need for display in the<br />
visual components.</p>
<h1>ModelData interface</h1>
<p>GXT provides us an interface named ModelData. Any data objects we wish to use with GXT<br />
data-backed components must implement this interface. The ModelData interface provides<br />
the ability for property names and values to be retrieved at runtime. As <a href="http://astore.amazon.com/javabeat-20?_encoding=UTF8&amp;node=32">GWT</a> does not<br />
support refl ection, GXT does this using a form of introspection.</p>
<p>In our example application, at present we are using a JavaBean named Feed to store feed<br />
data. However, at the moment, it does not implement the ModelData interface, so we<br />
cannot use it with GXT&#8217;s data-backed components.</p>
<p>We have three methods that will allow us to achieve this:</p>
<ol>
<li>Modify the Feed JavaBean so that it extends BaseModel.</li>
<li>Modify the Feed JavaBean so that it implements BeanModelTag.</li>
<li>Create a BeanModelMarker interface to accompany the Feed JavaBean.<br />
This method allows us to avoid having to modify the Feed JavaBean.</li>
</ol>
<h1>Method 1: Extending BaseModel</h1>
<p>BaseModel is the default implementation of the ModelData interface. Classes that extend<br />
BaseModel make use of a HashMap to store data rather than local fields. Data is added and<br />
retrieved using the set and get methods of the BaseModel respectively. The downside<br />
of this method is that we need to use strings as attribute names and as such it is easier for<br />
errors to creep in.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>The Feed object implemented as a subclass of BaseModel would look like this:</p>
<pre><code>
 public class Feed extends BaseModel {
 public Feed () {
 }
 public Feed (String uuid) {
 set("uuid", uuid);
 }
 public String getDescription() {
 return get("description");
 }
 public String getLink() {
 return get("link");
 }
 public String getTitle() {
 return get("title");
 }
 public String getUuid() {
 return get("uuid");
 }
 public void setDescription(String description) {
 set("description", description);
 }
 public void setLink(String link) {
 set("link", link);
 }
 public void setTitle(String title) {
 set("title", title);
 }
 }
 </code></pre>
<h1>BeanModel class</h1>
<p>If we already have a JavaBean we wish to use instead of creating a new BaseModel, GXT<br />
provides the BeanModel, a class which acts as a wrapper for JavaBeans. BeanModel objects<br />
cannot be created directly; instead they are generated by a BeanModelFactory.</p>
<h1>BeanModelFactory class</h1>
<p>BeanModelFactory is a useful class that allows us to take a JavaBean with a<br />
corresponding BeanModelMarker interface such as a Feed object, and get back<br />
a BeanModel representation.</p>
<p>The remaining two methods of providing a ModelData object involve wrapping a JavaBean<br />
as a BeanModel.</p>
<h1>Method 2: Implementing BeanModelTag</h1>
<p>BeanModelTag is an interface that allows us to tag existing Java objects that meet the<br />
JavaBean specification. This allows BeanModel instances to be generated from the JavaBean<br />
using a BeanModelFactory.</p>
<p>In order to make our existing Feed JavaBean usable as a GXT BeanModel, we simply need to<br />
implement the BeanModelTag interface like this:</p>
<pre><code>
 <strong>public class Feed implements Serializable, BeanModelTag {</strong>
 private String description;
 private String link;
 private String title;
 private String uuid;
 public Feed() {
 }
 public Feed(String uuid) {
 this.uuid = uuid;
 }
 public String getDescription() {
 return description;
 }
 public String getLink() {
 return link;
 }
 public String getTitle() {
 return title;
 }
 public String getUuid() {
 return uuid;
 }
 public void setDescription(String description) {
 this.description = description;
 }
 public void setLink(String link) {
 this.link = link;
 }
 public void setTitle(String title) {
 this.title = title;
 }
 }
 </code></pre>
<p>This still requires a change to the JavaBean, however. There are situations where making<br />
any change to a JavaBean would be unacceptable or at least undesirable. In this case, GXT<br />
provides the BeanModelMarker.</p>
<h1>Method 3: Creating a BeanModelMarker</h1>
<p>BeanModelMarker is an interface, which, as its name suggests, allows us to mark an<br />
existing JavaBean as a BeanModel. This is achieved by creating an interface that extends<br />
BeanModelMarker. It makes use of annotations to define the JavaBean to wrap.</p>
<p>In our example application, we already have a Feed JavaBean, and we will now create a<br />
BeanModelMarker for it so that we can use it with the GXT data-backed controls.</p>
<p>Notice the use of the @BEAN annotation to make a reference to the Feed class. We do not<br />
need to make any changes to the Feed JavaBean itself.</p>
<h2>Time for action – creating a BeanModelMarker for Feed objects</h2>
<ol>
<ol>
<li>Create a new class named FeedBeanModel that implements the<br />
BeanModelMarker interface in a new package named client.model:</p>
<pre>public class FeedBeanModel implements BeanModelMarker {}</pre>
</li>
<li>Add an @BEAN annotation to tell GXT to use the Feed JavaBean class as follows:</li>
</ol>
</ol>
<pre><code><strong>
 @BEAN(com.danielvaughan.rssreader.shared.model.Feed.class)</strong>
 public class FeedBeanModel implements BeanModelMarker {}
 </code></pre>
<h3>What just happened?</h3>
<p>We created a BeanModelMarker for our existing Feed JavaBean. We can now use our Feed<br />
JavaBean with GXT&#8217;s data-backed controls without having to modify the Feed JavaBean class<br />
in any way.</p>
<h1>Stores</h1>
<p>In GXT, a Store is an abstract class used to provide a client-side cache of ModelData objects<br />
of a specified class. Stores are where the data-backed GXT components keep data. There are<br />
two concrete Store classes. The first is TreeStore, which is used with Tree components,<br />
and we will look at these in the next chapter. The second is ListStore, which is used for<br />
storing the lists of data. These are typically used with ListField, ComboBox, and<br />
Grid components.</p>
<p>To create a ListStore to contain Feed objects, we would define it like this:</p>
<pre><code>
 ListStore&lt;BeanModel&gt; feedStore = <strong>new</strong> ListStore&lt;BeanModel&gt;();
 </code></pre>
<p>Note that the ListStore is set to contain BeanModel instances. This is because a Store<br />
can only contain objects that inherit from the ModelData class. If we wanted to add a Feed<br />
JavaBean object, we cannot do it directly. We need to use a BeanModelFactory to convert<br />
the Feed JavaBean object into a BeanModel representation.</p>
<p>We will now modify the example application so that when creating a new Feed<br />
JavaBean object, a BeanModel representation of the Feed object is added into<br />
a client-side ListStore.</p>
<h2>Time for action – creating and populating a ListStore</h2>
<ol>
<ol>
<li>In the RSSReaderConstants class, add a new constant named FEED_STORE for<br />
the feed store:</li>
</ol>
</ol>
<pre><code>
 public static final String FEED_STORE = "feedStore";
 </code></pre>
<ol>
<ol>
<li>In the onModuleLoad method of the RSSReader class, create a new ListStore<br />
and add it to the Registry using the FEED_STORE constant as the key:</li>
</ol>
</ol>
<pre><code>
 public void onModuleLoad() {
 Registry.register(RSSReaderConstants.FEED_SERVICE,
 GWT.create(FeedService.class));
 <strong>Registry.register(RSSReaderConstants.FEED_STORE, new
 ListStore&lt;BeanModel&gt;());</strong>
 …
 }
 </code></pre>
<ol>
<ol>
<li>In the save method of the FeedForm, modify the onSuccess method of the<br />
callback function to retrieve the feed store from the Registry:</li>
</ol>
</ol>
<pre><code>
 public void save(final Feed feed) {
 @Override
 public void onSuccess(Void result) {
 Info.display("RSS Reader", "Feed " + feed.getTitle()
 + " saved successfully");
 <strong>final ListStore&lt;BeanModel&gt; feedStore = Registry
 .get(RSSReaderConstants.FEED_STORE);</strong>
 }
 …
 }
 </code></pre>
<ol>
<ol>
<li>Retrieve a BeanModelFactory for the Feed class:</li>
</ol>
</ol>
<pre><code>
 public void onSuccess(Void result) {
 Info.display("RSS Reader", "Feed " + feed.getTitle() + " saved
 successfully");
 final ListStore&lt;BeanModel&gt; feedStore =
 Registry.get(RSSReaderConstants.FEED_STORE);
 <strong>BeanModelFactory beanModelFactory =
 BeanModelLookup.get().getFactory(feed.getClass());</strong>
 }
 </code></pre>
<ol>
<ol>
<li>Finally, use the BeanModelFactory to create a BeanModel representation of the<br />
Feed object and then add it to the feed store:</li>
</ol>
</ol>
<pre><code>
 public void onSuccess(Void result) {
 Info.display("RSS Reader", "Feed " + feed.getTitle() + " saved
 successfully");
 final ListStore&lt;BeanModel&gt; feedStore =
 Registry.get(RSSReaderConstants.FEED_STORE);
 BeanModelFactory beanModelFactory =
 BeanModelLookup.get().getFactory(feed.getClass());
 <strong>feedStore.add(beanModelFactory.createModel(feed));</strong>
 }
 </code></pre>
<h3>What just happened?</h3>
<p>Feed objects are now stored in a GXT ListStore. The advantage of this is that we can now<br />
simply link the data-backed components to the Store, and the values in the components<br />
will refresh automatically.</p>
<h1>Data-backed ComboBox</h1>
<p>Once we have a ListStore populated with data, we can use it to provide the options in a<br />
ComboBox by binding the ComboBox to the Store. We would take the feed store and create<br />
a ComboBox that uses the title field of each Feed to populate the values of the ComboBox<br />
like this:</p>
<pre><code>
 ComboBox&lt;Feed&gt;combo = new ComboBox&lt;Feed&gt;();
 combo.setDisplayField("title");
 combo.setStore(feeds);
 </code></pre>
<p>Here we use the setDisplayField of the ComboBox to set the title field as the field to use<br />
as the display value.</p>
<p>Once a data-backed component is linked with a Store, it then observes the Store for<br />
changes. If a change to the data in the Store occurs, such as an object being added to the<br />
Store, the content of the data-backed control will be updated automatically. The specific<br />
Store events that can be observed are listed as follows:</p>
<ul>
<li>Add</li>
<li>Clear</li>
<li>Data Changed</li>
<li>Filter</li>
<li>Remove</li>
<li>Sort</li>
<li>Update</li>
</ul>
<h1>Data-backed ListField</h1>
<p>Associating a ListField with a Store is very similar to associating a ComboBox with a<br />
Store. In our example application, we will now add a ListField containing all current<br />
feeds to the left navigation panel.</p>
<h2>Time for action – creating a ListField for feeds</h2>
<ol>
<ol>
<li>Create a new package named client.lists, and in it create a new class named<br />
FeedList that extends LayoutContainer:</li>
</ol>
</ol>
<pre><code>
 public class FeedList extends LayoutContainer {}
 </code></pre>
<ol>
<ol>
<li>In the constructor of the FeedList class, set the layout of the LayoutContainer<br />
to FitLayout:</li>
</ol>
</ol>
<pre><code>
 public FeedList() {
 setLayout(new FitLayout());
 }
 </code></pre>
<ol>
<ol>
<li>Override the onRender method, and in it create a new ListField:</li>
</ol>
</ol>
<pre><code>
 @Override
 protected void onRender(Element parent, int index) {
 super.onRender(parent, index);
 final ListField&lt;BeanModel&gt; feedList = new
 ListField&lt;BeanModel&gt;();
 }
 </code></pre>
<ol>
<ol>
<li>Again in the onRender method, retrieve the feed store from the Registry:</li>
</ol>
</ol>
<pre><code>
 final ListStore&lt;BeanModel&gt; feedStore =
 Registry.get(RSSReaderConstants.FEED_STORE);
 </code></pre>
<ol>
<ol>
<li>Set the feed store as the Store for the feed list ListField:</li>
</ol>
</ol>
<pre><code>
 feedList.setStore(feedStore);
 </code></pre>
<ol>
<ol>
<li>Tell the ListField to use the title field of the Feed object as the value to display in<br />
the ListField:</li>
</ol>
</ol>
<pre><code>
 feedList.setDisplayField("title");
 </code></pre>
<ol>
<ol>
<li>Add the ListField to the underlying container:</li>
</ol>
</ol>
<pre><code>
 add(feedList);
 </code></pre>
<ol>
<ol>
<li>At the end of the constructor of the RssNavigationPanel, set the layout to a new<br />
instance of FitLayout and add a new instance of the FeedList component to<br />
the underlying ContentPanel:</li>
</ol>
</ol>
<pre><code>
 setLayout(new FitLayout());
 add(new FeedList());
 </code></pre>
<ol>
<ol>
<li>Start the application, click on the <strong>Create feed</strong> button, and complete the form as<br />
shown in the screenshot below:</li>
</ol>
</ol>
<p><center><img src="images/2010/12/ExtGWT2.0/1.jpg" alt="" /></center></p>
<ol>
<ol>
<li>On clicking the <strong>Save</strong> button, the new feed&#8217;s title, <strong>Test Feed</strong>, will appear in the list<br />
of feeds on the left:</li>
</ol>
</ol>
<p><center><img src="images/2010/12/ExtGWT2.0/2.jpg" alt="" /></center></p>
<h3>What just happened?</h3>
<p>We added a list of feeds to the RSS Reader application. When we created a new feed, it<br />
automatically appeared in the feed list on the left.</p>
<h2>GWT Articles</h2>
<ul>
<li>Buy <a href="http://astore.amazon.com/javabeat-20/detail/1933988231" target="_blank">GWT in Action</a> from <a href="http://astore.amazon.com/javabeat-20?_encoding=UTF8&amp;node=32" target="_blank">GWT Books</a> Store</li>
<li><a href="http://www.javabeat.net/articles/12-comparison-of-ajax-frameworks-prototype-gwt-dwr-and-1.html">Comparison of AJAX Frameworks</a></li>
<li><a href="http://www.javabeat.net/articles/28-google-web-toolkitgwt-1.html">Google Web ToolKit(GWT)</a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2010/12/what-is-ext-gwt-2-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GWT user interface components</title>
		<link>http://www.javabeat.net/2009/03/gwt-user-interface-components/</link>
		<comments>http://www.javabeat.net/2009/03/gwt-user-interface-components/#comments</comments>
		<pubDate>Mon, 30 Mar 2009 04:45:41 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[GWT]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=509</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>HTML host page A GWT module needs a HTML host page to run. The HTML page includes the GWT project through the script tag. In the HTML page we do not add any HTML code ourselves. It is the responsibility of the developer to programmatically include content into the HTML page through GWT. Lets look [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>HTML host page</h2>
<p>
A <b>GWT</b> module needs a <b>HTML</b> host page to run. The HTML page includes the GWT project through the <b>script</b> tag. In the HTML page we do not add any HTML code ourselves. It is the responsibility of the developer to programmatically include content into the HTML page through GWT. Lets look at a sample HTML host page :
</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;html&gt;
  &lt;head&gt;
    &lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
    &lt;title&gt;Simple GWT Host Page&lt;/title&gt;
    &lt;script type=&quot;text/javascript&quot; language=&quot;javascript&quot; src=&quot;com.google.gwt.sample.tempraturewatch.TempratureWatch.nocache.js&quot;&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id=&quot;tempratureWatchDiv&quot;&gt;&lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre></td></tr></table></div>

<p>
In the above host page we can see that the GWT application is included through the <b>script</b> tag. The <b>nocache.js</b> is an auto generated file created using the <b>applicationcreator</b> command (Refer : <a href="http://www.javabeat.net/tips/188-gwt-installation-and-creating-a-gwt-project.html">GWT installation and creating a GWT Project</a> for information on the <b>applicationcreator</b>). Next, we can see a <b>div</b> tag with the <b>id</b> attribute.<br />
In GWT we can insert content into selective sections of the HTML page. Lets look at an example :
</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">final Button button = new Button(&quot;Submit&quot;);
RootPanel.get(&quot;tempratureWatchDiv&quot;).add(button);</pre></td></tr></table></div>

<p>
In the above code snippet, we can see that usage of the class <b>RootPanel</b>. The RootPanel is the container for all other GWT components. We use the RootPanel class to get a <b>reference</b> of <b>tempratureWatchDiv</b> division. Once we have a reference to it we can add <b>Widgets</b>(controls) to the html page.
</p>
<h2>Widgets</h2>
<p>
Widgets are controls which allow the users to interact with the system. Lets look at the different types of widgets available in GWT:</p>
<ul>
<li><b>Button</b></li>
<p> &#8211; Button enables the user to take a certain action</p>
<li><b>TextBox</b></li>
<p> &#8211; Textbox allows the user to enter data as text</p>
<li><b>Tree</b></li>
<p> &#8211; Tree represents a hierarchy of other widgets</p>
<li><b>RichTextArea</b></li>
<p> &#8211; RichTextArea provides the user to perform editing features on text</p>
<li><b>Checkbox</b></li>
<p> &#8211; Checkbox allows multiple selection of items</p>
<li><b>RadioButton</b></li>
<p> &#8211; RadioButton allows only single selection of items</p>
<li><b>PasswordTextBox</b></li>
<p> &#8211; PasswordTextBox is used to input password. The typed characters are not displayed as it is.</p>
<li><b>TextArea</b></li>
<p> &#8211; TextArea allows the user to enter text over multiple lines</p>
<li><b>Hyperlink</b></li>
<p> &#8211; Hyperlink allows you to link to an URL</p>
<li><b>Listbox</b></li>
<p> &#8211; Listbox allows multiple selection from a list of items</p>
<li><b>MenuBar</b></li>
<p> &#8211; MenuBar allows you to implement a standard menu bar. Menu bar can hold one or more menus.</p>
<li><b>SuggestBox</b></li>
<p> &#8211; SuggestBox is like a textbox but it provides suggestions based on the user input. The suggestions provided are pre-configured.</p>
<li><b>Table</b></li>
<p> &#8211; Table control mimics the HTML table</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<li><b>Dialog Box</b></li>
<p> &#8211; Dialog Box represents a form of popup
</ul>
<p>In addition to these we can also create <b>custom widgets</b>.
</p>
<h3>Panels</h3>
<p>
Panels are used as <b>container</b> for widgets and subpanels. Panels also define how the widgets will be laid out. Lets look at the type of panels in GWT:</p>
<ul>
<li><b>Dock Panel</b></li>
<p> &#8211; Using dock panels the widgets are aligned directionally</p>
<li><b>Horizontal Panel</b></li>
<p> &#8211; Provides horizontal alignment of controls</p>
<li><b>Tab Panel</b></li>
<p> &#8211; Provides tabular arrangement of controls</p>
<li><b>Root Panel</b></li>
<p> &#8211; The Root panel holds the reference to the entire GWT interface.</p>
<li><b>Stack Panel</b></li>
<p> &#8211; The stack panel displays the components vertically by stacking its children.</p>
<li><b>Popup Panel</b></li>
<p> &#8211; The popup panel is a popup which can popup up over other widgets</p>
<li><b>Vertical Panel</b></li>
<p> &#8211; The vertical panel lays out the components in a vertical column</p>
<li><b>Flow Panel</b></li>
<p> &#8211; This panel lays out it components in the same manner as the default HTML layout</p>
<li><b>Vertical Split Panel</b></li>
<p> &#8211; This panels splits the window verticals into two widgets</p>
<li><b>Horizontal Split Panel</b></li>
<p> &#8211; This panels splits the window horizontally into two widgets
</ul>
</p>
<h3>Style Sheets</h3>
<p>
In GWT we can apply style information to content by using <b>Cascading Style Sheets (CSS)</b>. This is very similar to the way we apply style information to HTML pages. Each widget class in GWT has a <b>addStyleName</b> method which takes a string parameter. The string parameter associates a style name with the widget. The same name should be defined in the <b>CSS</b> file. Under the name we can set visual styling information. The reference to the CSS should be made in the GWT module. Let us now look at how we can make use of style sheets in a GWT application.
</p>
<p>
As a first step we have to associate the style attribute in the Java class:
</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">Label nameLabel = new Label();
nameLabel.addStyleName(&quot;LabelStyle&quot;);</pre></td></tr></table></div>

<p>
The next step would be to define the style attribute in the CSS file:
</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">.LabelStyle {
  color: blue;
  font-size: large;
}</pre></td></tr></table></div>

<p>
The final step would be to declare the style sheet file in the XML module. This enables the GWT to know exactly where to look for the styling information.
</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;module&gt;
	&lt;!--Other application level settings--&gt;
	.......
	&lt;stylesheet src='MyStyleSheet.css' /&gt;
&lt;/module&gt;</pre></td></tr></table></div>

<h3>GWT Reference</h3>
<ul>
<li><a href="http://www.javabeat.net/tips/188-gwt-installation-and-creating-a-gwt-project.html">GWT installation and creating a GWT Project</a></li>
<li><a href="http://www.javabeat.net/articles/gwt/1/">GWT Articles</a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/03/gwt-user-interface-components/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
