Table of Contents Presentation of GWT Hello World Application - - PowerPoint PPT Presentation

table of contents
SMART_READER_LITE
LIVE PREVIEW

Table of Contents Presentation of GWT Hello World Application - - PowerPoint PPT Presentation

Table of Contents Presentation of GWT Hello World Application Advanced Web Technology Widgets 5) Google Web Toolkits - Hello World GWT, Client Side Event Handling Applying Style Sheets Emmanuel Benoist Deployment


slide-1
SLIDE 1

Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side

Emmanuel Benoist

Spring Term 2020

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 1

Table of Contents

  • Presentation of GWT
  • Hello World Application
  • Widgets

Hello World

  • Event Handling
  • Applying Style Sheets
  • Deployment
  • Internationalization

Static String i18n

  • Remote Procedure Code
  • JSON

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 2

Presentation of GWT

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 3

Motivation

What is GWT?

A development environment in pure Java for rich web applications Provides Java for programming both client and server sides

Advantages of GWT

Homogenous environment Testing of a web application (using JUnit)

Not integrated in JSF

Concurent system developed by google

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 4

slide-2
SLIDE 2

Principle

Write Java code

Use Java on Server Side But also on a Client Side Communication is handeled conveniently

Tests in a JVM

Testing is done using JUnit Plugin in the browser Tests are conducted inside one JVM (based on Java Code)

Compile into Javascript

Creates different versions for different browsers Each browser receives only the “right” version Can be deployed on Java Servers Or any other server (if the server part is not Java)

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 5

Hello World Application

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 6

Hello World Application

Download the GWT

From Google Code Web site http://code.google.com

Create an application

Execute ./webAppCreator -out /home/bie1/test/ ch.bfh.awt.Hello A default application is created Includes ant and Eclipse project files

Test the Application

Go to the directory execute ant devmode Install the plugin in your browser Test the application

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 7

Directories created

Source files: /src/

Package for client side application : /src/ch/bfh/awt/client Server side classes : /src/ch/bfh/awt/server The file /src/ch/bfh/awt/Hello.gwt.xml contains the configurations for the GWT application

Web Application: /war/

Contains html, css, javascript, gifs, and the like Contains the WEB-INF/ directory (where the server classes are automatically compiled The directory /war/ will receive the JavaScript files compiled from the client application At the end the content of this directory is copied to the server

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 8

slide-3
SLIDE 3

Widgets

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 9

Hello World

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 10

Hello World

Hello.html: contains a real HTML

Containing layout, References to images, JavaScript, CSS

Reference to the script loading the files <script type="text/javascript" language="javascript" src="ց

→hello/hello.nocache.js"></script>

And it contains place-holders that will be manipulated from “Java”. <div id="nameFieldContainer"></div> <div id="sendButtonContainer"></div> <div style="color:blue;" id="responseContainer"ց

→></div> Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 11

HTML FIle

<!doctype html> <html> <head> <meta http−equiv="content−type" content="text/html;␣charset=UTFց

→−8">

<link type="text/css" rel="stylesheet" href="Hello.css"> <title>Web Application Starter Project</title> <script type="text/javascript" language="javascript" src="hello/hello.ց

→nocache.js"></script>

</head> <body> ... <h1>Web Application Starter Project</h1> Please enter your name: <div id="nameFieldContainer"></div> <div id="sendButtonContainer"></div> <div style="color:blue;" id="responseContainer"></div> </body> </html>

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 12

slide-4
SLIDE 4

Java File

Contains the definition of the user interface

Definition of the Widgets used, Panels, Text fields, buttons

Extends the EntryPoint class

Defines the onModuleLoad() function.

Defines the Event Handling

Defines functions to be executed when an Event is fired.

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 13

Hello.java

package ch.bfh.awt.client; import .......... /∗∗ Entry point classes define <code>onModuleLoad()</code>.ց

→ ∗/

public class Hello implements EntryPoint { public void onModuleLoad() { final Button sendButton = new Button("Send"); final TextBox nameField = new TextBox(); final Label responseLabel = new Label(); RootPanel.get("nameFieldContainer").add(nameField); RootPanel.get("sendButtonContainer").add(sendButton); RootPanel.get("responseContainer").add(responseLabel); nameField.setFocus(true); ... // Event Handling } }

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 14

Widgets

List of default widgets

Buttons: Button, PushButton, RadioButton,CheckBox,,, Calendar: DatePicker Lists : ListBox , CellList, Trees: MenuBar, Tree with CellTree, Panels: PopoupPanel, StackPanel, HorizontalPanel, VerticalPanel, http://code.google.com/intl/fr-FR/webtoolkit/doc/ latest/RefWidgetGallery.html

Possibility to write your own widgets:

http://code.google.com/intl/en/webtoolkit/doc/ latest/DevGuideUiCustomWidgets.html Composite components (composition of existing components)

  • r from scratch in Java code

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 15

Example: StockWatcher1

An interface to watch stock values

Presentation (when deployed on localhost) localhost:8080/stockWatcherGWT

User Interface: One page

One page A list containing the stocks A field to type the stock into A button to add a new stock

Back-office

No back-office today Communications with the servers are seen in the next course Communication available:

◮ Remote Procedure Call (RPC) in Java ◮ Call to JSON data on the same server (PHP for instance) ◮ Call to JSON data on another server (against the same origin

policy).

1Source:http:

//code.google.com/intl/fr-FR/webtoolkit/doc/latest/tutorial/

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 16

slide-5
SLIDE 5

The HTML Page 2

<body> <img src="images/bfh.jpg" /> <h1>Stock Watcher testing project</h1> <div id="stockList"></div> <iframe src="javascript:’’" id="__gwt_historyFrame" tabIndex=’ց

→−1’ style="position:absolute;width:0;height:0;border:0"></iframe>

<noscript> <div style="width:␣22em;␣position:␣absolute;␣left:␣50%;␣margin−leftց

→:␣−11em;␣color:␣red;␣background−color:␣white;␣border:␣1px␣solid␣ց →red;␣padding:␣4px;␣font−family:␣sans−serif">

Your web browser must have JavaScript enabled in order for this application to display correctly. </div> </noscript> </body>

2/war/StockWatcher.html Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 17

Java Files 3

Contains Widgets

mainPanel a vertical panel containing components addPanel an horizontal panel containing a textbox and a button stocksFlexTable a fexible table containing lines and columns newSymbolTextBox a text box to enter text into addStockButton a button that generates an event when clicked on lastUpdatedLabel a label contains a text

private VerticalPanel mainPanel = new VerticalPanel(); private FlexTable stocksFlexTable = new FlexTable(); private HorizontalPanel addPanel = new HorizontalPanel(); private TextBox newSymbolTextBox = new TextBox(); private Button addStockButton = new Button("Add"); private Label lastUpdatedLabel = new Label();

3/src/ch/bfh/awt/client/StockWatcher.java Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 18

The Java File

public void onModuleLoad() { // Create table for stock data. stocksFlexTable.setText(0, 0, "Symbol"); stocksFlexTable.setText(0, 1, "Price"); stocksFlexTable.setText(0, 2, "Change"); stocksFlexTable.setText(0, 3, "Remove"); // Assemble Add Stock panel. addPanel.add(newSymbolTextBox); addPanel.add(addStockButton); // Assemble Main panel. mainPanel.add(stocksFlexTable); mainPanel.add(addPanel); mainPanel.add(lastUpdatedLabel); // Associate the Main panel with the HTML host page. RootPanel.get("stockList").add(mainPanel); // Move cursor focus to the input box. newSymbolTextBox.setFocus(true); }

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 19

Event Handling

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 20

slide-6
SLIDE 6

Event Handling

Events Handlers are attached to widgets

Events in GWT use the event handler interface model similar to other user interface frameworks. To subscribe to an event, you pass a particular event handler interface to the appropriate widget. An event handler interface defines one or more methods that the widget then calls to announce (publish) an event.

Example: Hello World

Add an event handler for a click on the button Add an event handler when a user types on the Enter key

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 21

Event Handlers for Hello World 4

class MyHandler implements ClickHandler, KeyUpHandler { public void onClick(ClickEvent event) { copyName(); } public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { copyName(); } } private void copyName() { String textToCopy = nameField.getText(); responseLabel.setText(textToCopy); } } MyHandler handler = new MyHandler(); sendButton.addClickHandler(handler); nameField.addKeyUpHandler(handler);

4Inside the definition of the class Hello Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 22

Event Handling by Stock Watcher

// Listen for mouse events on the Add button. addStockButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { addStock(); } }); // Listen for keyboard events in the input box. newSymbolTextBox.addKeyPressHandler(new KeyPressHandler() { public void onKeyPress(KeyPressEvent event) { if (event.getCharCode() == KeyCodes.KEY_ENTER) { addStock(); } } }); } private void addStock() { // TODO Auto−generated method stub }

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 23

Manipulate the content of the Widgets

Java can generate an alert(). Window.alert("’" + symbol + "’␣is␣not␣a␣valid␣symbol."); One can manipulate elements in a list int removedIndex = stocks.indexOf(symbol); stocks.remove(removedIndex); stocksFlexTable.removeRow(removedIndex + 1); Or change the text of a label or a text box private void copyName() { // First, we validate the input. String textToCopy = nameField.getText(); responseLabel.setText(textToCopy); }

  • r

// Display timestamp showing last refresh.

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 24

slide-7
SLIDE 7

Applying Style Sheets

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 25

Applying Style Sheets

Configure the standard theme

standard.css : contains the GWT default styles (themes) In GWT config file : Hello.gwt.xml Defines the theme: <inherits name=’com.google.gwt.user.theme.standard.ց

→Standard’/>

<!−− <inherits name="com.google.gwt.user.theme.ց

→chrome.Chrome"/> −−>

<!−− <inherits name="com.google.gwt.user.theme.dark.ց

→Dark"/> −−>

Associate a CSS file

Hello.css : contains the project specific classes Linked inside the Hello.html <link type="text/css" rel="stylesheet" href="Hello.css">

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 26

Add Style to the elements

Suppose we have the following style: /∗ stock list header row ∗/ .watchListHeader { background−color: #2062B8; color: white; font−style: italic; } /∗ stock list flex table ∗/ .watchList { border: 1px solid silver; padding: 2px; margin−bottom:6px; }

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 27

Add Style to the elements (Cont.)

We add style to the elements of the first row of the table // Add styles to elements in the stock list table. stocksFlexTable.getRowFormatter().addStyleName(0, "ց

→watchListHeader");

Format all the elements of a table stocksFlexTable.addStyleName("watchList"); Or format only one cell stocksFlexTable.getCellFormatter().addStyleName(0, 1, "ց

→watchListNumericColumn");

Or even a panel addPanel.addStyleName("addPanel");

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 28

slide-8
SLIDE 8

Deployment

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 29

Deployment

Compile the application into JavaScript

Using GWT Compile Project button in Eclipse Or executing ant build

Compilation writes all the required files in the War directory

Uses the definition files and all the existing files in the war/ (html, gif, images, css, . . . )

Copy the content of the directory

To a servlet engine if you use the server side functionality To any server if using only the client side

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 30

Internationalization

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 31

Internationalization : I18N Module

Core types related to internationalization: LocaleInfo Provides information about the current locale. Constants Useful for localizing typed constant values Messages Useful for localizing messages requiring arguments ConstantsWithLookup Like Constants but with extra lookup flexibility for highly data-driven applications Dictionary Useful when adding a GWT module to existing localized web pages Localizable Useful for localizing algorithms encapsulated in a class or when the classes above don’t provide sufficient control DateTimeFormat Formatting dates as strings. See the section

  • n date and number formatting.

NumberFormat Formatting numbers as strings. See the section on date and number formatting.

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 32

slide-9
SLIDE 9

Static String i18n

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 33

Interantionalizing Strings

Implement the Constant Interface

Contains only static strings Very efficient and compiled once.

Implement the Messages Interface

Allows to insert values in the string For instance numbers or dates Equivalent to the resource bundle in applications.

Dynamic String Internationalization

The Dictionary class lets your GWT application consume strings supplied by the host HTML page. Convenient if your existing web server has a localization system that you do not wish to integrate with the static string internationalization methods.

Implement the Localizable Interface

The most powerful technique allows you to go beyond simple string substitution create localized versions of custom types.

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 34

Implement the Constants Interface

Create the StockWatcherConstants interface

Uses annotations for the default translation Implements the Constant interface (GWT) Bound automatically to the StockWatcherConstants*.properties files

The java file must contain one method for each of the constants in the properties files

The right value is found at runtime, corresponding to the locale

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 35

Example: the Constants file

package com.google.gwt.sample.stockwatcher.client; import com.google.gwt.i18n.client.Constants; public interface StockWatcherConstants extends Constants { @DefaultStringValue("StockWatcher") String stockWatcher(); @DefaultStringValue("Symbol") String symbol(); @DefaultStringValue("Price") String price(); @DefaultStringValue("Change") String change(); @DefaultStringValue("Remove") String remove(); @DefaultStringValue("Add") String add(); }

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 36

slide-10
SLIDE 10

Translate it to German

Create a file StockWatcherConstants_de.properties stockWatcher = Aktienbeobachter symbol = Symbol price = Kurs change = Änderung remove = Entfernen add = Hinzufügen

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 37

Implement the Messages interface

For Strings containing information

Similar to resource bundles in Java Can contain strings with parameters ’’{0}’’ ist kein gültiges Aktiensymbol. The number is a place holder myString = First parm is {0}, second parm is {1}, third ց

→parm is {2}.

Usefull for integrating dates, prices, internationalized results

◮ Usefull but less efficient. The strings must be produced at

runtime

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 38

Messages file

package com.google.gwt.sample.stockwatcher.client; import com.google.gwt.i18n.client.Messages; import java.util.Date; public interface StockWatcherMessages extends Messages { @DefaultMessage("’’{0}’’␣is␣not␣a␣valid␣symbol.") String invalidSymbol(String symbol); @DefaultMessage("Last␣update:␣{0,date,medium}␣{0,time,ց

→medium}")

String lastUpdate(Date timestamp); }

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 39

The corresponding properties file

StockWatcherMessages_de.properties file. lastUpdate = Letzte Aktualisierung: {0,date,medium} {0,time,ց

→medium}

invalidSymbol = ’’{0}’’ ist kein gültiges Aktiensymbol.

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 40

slide-11
SLIDE 11

Replace content

Replace the texts with place holders <body> <img src="images/GoogleCode.png"/> <h1 id="appTitle"></h1> Replacing strings set programmatically Create the instances of the classes (internationalized) private ArrayList<String> stocks = new ArrayList<String>(); private StockWatcherConstants constants = GWT.create(ց

→StockWatcherConstants.class);

private StockWatcherMessages messages = GWT.create(ց

→StockWatcherMessages.class); Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 41

Replace content (Cont)

Set the content: // Set the window title, the header text, and the Add button ց

→text.

Window.setTitle(constants.stockWatcher()); RootPanel.get("appTitle").add(new Label(constants.ց

→stockWatcher()));

addStockButton = new Button(constants.add()); // Create table for stock data. stocksFlexTable.setText(0, 0, constants.symbol()); stocksFlexTable.setText(0, 1, constants.price()); stocksFlexTable.setText(0, 2, constants.change()); stocksFlexTable.setText(0, 3, constants.remove());

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 42

Add a supported locale:

Inside StockWatcher.gwt.xml add the property <entry−point class=’com.google.gwt.sample.stockwatcherց

→.client.StockWatcher’/>

<extend−property name="locale" values="de"/> </module> Load the german version by adding &locale=de

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 43

Client Server Communication

Remote Procedure Code

From Java To Java Supported by the language Optimized and easy to test

JSON

For communicating with the same server

JSONP

For cross server communication Overgoes the Same Origin Policy

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 44

slide-12
SLIDE 12

Remote Procedure Code

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 45

GWT Remote Procedure Call

RPC contains: the service that runs on the server

the method you are calling

the client code that invokes the service the Java data objects that pass between the client and server

Both (client and server) must serialize and deserialize the

  • bjects

You need to write three components

Define the interface StockPriceService that extends RemoteService and lists all your RPC methods Create a class StockPriceServiceImpl that extends RemoteServiceServlet and implements the interface you created above. Define an asynchronous interface StockPriceServiceAsync to your service to be called from the client-side code.

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 46

GWT Remote Procedure Call5

5Source: code.google.com Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 47

StockPriceService interface

In the package com.google.gwt.sample.stockwatcher.client package com.google.gwt.sample.stockwatcher.client; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePathց

→;

@RemoteServiceRelativePath("stockPrices") public interface StockPriceService extends RemoteService { StockPrice[] getPrices(String[] symbols); }

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 48

slide-13
SLIDE 13

StockPriceServiceImpl class

package com.google.gwt.sample.stockwatcher.server; import com.google.gwt.sample.stockwatcher.client.StockPrice; import com.google.gwt.sample.stockwatcher.client.StockPriceService; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import java.util.Random; public class StockPriceServiceImpl extends RemoteServiceServlet implementsց

→ StockPriceService {

private static final double MAX_PRICE = 100.0; // $100.00 private static final double MAX_PRICE_CHANGE = 0.02; // +/− 2% public StockPrice[] getPrices(String[] symbols) { Random rnd = new Random(); StockPrice[] prices = new StockPrice[symbols.length]; for (int i=0; i<symbols.length; i++) { double price = rnd.nextDouble() ∗ MAX_PRICE; double change = price ∗ MAX_PRICE_CHANGE ∗ (rnd.nextDoubleց

→() ∗ 2f − 1f);

prices[i] = new StockPrice(symbols[i], price, change); } return prices; } }

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 49

Include the server-side code in the GWT module

Define new servlets in the web.xml <web−app> <welcome−file−list> <welcome−file>StockWatcher.html</welcome−file> </welcome−file−list> <servlet> <servlet−name>stockPriceServiceImpl</servlet−name> <servlet−class>com.google.gwt.sample.stockwatcher.server.ց

→StockPriceServiceImpl</servlet−class>

</servlet> <servlet−mapping> <servlet−name>stockPriceServiceImpl</servlet−name> <url−pattern>/stockwatcher/stockPrices</url−pattern> </servlet−mapping> </web−app>

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 50

Invoking the service from the client

Making asynchronous calls to the server package com.google.gwt.sample.stockwatcher.client; import com.google.gwt.user.client.rpc.AsyncCallback; public interface StockPriceServiceAsync { void getPrices(String[] symbols, AsyncCallback<StockPrice[]> ց

→callback);

}

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 51

Making the remote procedure call

private void refreshWatchList() { // Initialize the service proxy. if (stockPriceSvc == null) { stockPriceSvc = GWT.create(StockPriceService.class); } // Set up the callback object. AsyncCallback<StockPrice[]> callback = new AsyncCallback<ց

→StockPrice[]>() {

public void onFailure(Throwable caught) { // TODO: Do something with errors. } public void onSuccess(StockPrice[] result) { updateTable(result); } }; // Make the call to the stock price service. stockPriceSvc.getPrices(stocks.toArray(new String[0]), callback); }

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 52

slide-14
SLIDE 14

Serializing Java objects

GWT RPC requires that all service method parameters and return types be serializable. package com.google.gwt.sample.stockwatcher.client; import java.io.Serializable; public class StockPrice implements Serializable { private String symbol; private double price; private double change; ...

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 53

JSON

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 54

Retrieving JSON Data

JSON stands for JavaScript Object Notation

Language independant format Very light

Example [ { "symbol": "ABC", "price": 87.86, "change": −0.41 }, { "symbol": "DEF", "price": 62.79, "change": 0.49 } ]

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 55

Server part

JSON can be generated by a servlet

  • ut.println("␣␣{");
  • ut.print("␣␣␣␣\"symbol\":␣\"");
  • ut.print(stockSymbol);
  • ut.println("\",");
  • ut.print("␣␣␣␣\"price\":␣");
  • ut.print(price);
  • ut.println(’,’);
  • ut.print("␣␣␣␣\"change\":␣");
  • ut.println(change);
  • ut.println("␣␣},");

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 56

slide-15
SLIDE 15

JSON generated by PHP

<?php header(’Content−Type:␣text/javascript’); define("MAX_PRICE", 100.0); // $100.00 define("MAX_PRICE_CHANGE", 0.02); // +/− 2% echo ’[’; $q = trim($_GET[’q’]); if ($q) { $symbols = explode(’␣’, $q); for ($i=0; $i<count($symbols); $i++) { $price = lcg_value() ∗ MAX_PRICE; $change = $price ∗ MAX_PRICE_CHANGE ∗ (lcg_value() ∗ 2.0 − ց

→1.0);

echo ’{’; echo "\"symbol\":\"$symbols[$i]\","; echo "\"price\":$price,"; echo "\"change\":$change"; echo ’}’; if ($i < (count($symbols) − 1)) { echo ’,’; } } }

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 57

Transform JSON object into JavaScript

use the built in JavaScript function eval

The function will receive a response.getText() as a parameter

private final native JsArray<StockData> asArrayOfStockData(ց

→String json) /∗−{

return eval(json); }−∗/;

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 58

Manipulate JSON objects

Create a JavaScriptObject StockData to manipulate the data input in Java package com.google.gwt.sample.stockwatcher.client; import com.google.gwt.core.client.JavaScriptObject; class StockData extends JavaScriptObject { // Overlay types always have protected, zero argument constructors. protected StockData() {} // JSNI methods to get stock data. public final native String getSymbol() /∗−{ return this.symbol; }−∗/; public final native double getPrice() /∗−{ return this.price; }−∗/; public final native double getChange() /∗−{ return this.change; }−∗/; // Non−JSNI method to return change percentage. public final double getChangePercent() { return 100.0 ∗ getChange() / getPrice(); } }

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 59

Connect the Web server

Prepare the list of stocks private void refreshWatchList() { if (stocks.size() == 0) { return; } String url = JSON_URL; // Append watch list stock symbols to query URL. Iterator iter = stocks.iterator(); while (iter.hasNext()) { url += iter.next(); if (iter.hasNext()) { url += "+"; } } url = URL.encode(url); // TODO Send request to server and handle errors. }

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 60

slide-16
SLIDE 16

Connect the Web Server (Cont.)

// Send request to server and catch any errors. RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url); try { Request request = builder.sendRequest(null, new RequestCallback() { public void onError(Request request, Throwable exception) { displayError("Couldn’t␣retrieve␣JSON"); } public void onResponseReceived(Request request, Response responseց

→) {

if (200 == response.getStatusCode()) { updateTable(asArrayOfStockData(response.getText())); } else { displayError("Couldn’t␣retrieve␣JSON␣(" + response.ց

→getStatusText()

+ ")"); } } }); } catch (RequestException e) { displayError("Couldn’t␣retrieve␣JSON"); }

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 61

Conclusion

GWT: pure Java Web Application

Client and Server share one language

Testing made easy

Testing of Web Application is often a nightmare JUnit testing is possible Debugging inside one JVM : In Eclipse or in devmode

Security?

What is executed where? What is transfered and can be manipulated? What is tested where?

Useful features

I18N Client Server Communication Remote Procedure Call JSON

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 62

References

Tutorial by Google Code http://code.google.com/intl/ fr-FR/webtoolkit/overview.html http://code.google.com/intl/fr-FR/webtoolkit/doc/ latest/tutorial/gettingstarted.html Developer Guide by Google Code http://code.google.com/intl/fr-FR/webtoolkit/doc/ latest/DevGuide.html Hello World Example

Obtained by executing the create application script.

Tutorial for Client Server communication http://code.google.com/intl/fr-FR/webtoolkit/doc/ latest/tutorial/clientserver.html

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 63