advanced web technology 13) google web toolkits 2 - gwt ... · advanced web technology 13) google...
TRANSCRIPT
Advanced Web Technology13) Google Web Toolkits 2 -GWT, Communication
Emmanuel BenoistFall Term 2016-17
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 1
Table of Contents
� InternationalizationStatic String i18n
� Remote Procedure Code
� JSON
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 2
Internationalization
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 3
Internationalization : I18N ModuleCore 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 lookupflexibility for highly data-driven applications
Dictionary Useful when adding a GWT module to existinglocalized web pages
Localizable Useful for localizing algorithms encapsulated ina class or when the classes above don’t provide sufficientcontrol
DateTimeFormat Formatting dates as strings. See the sectionon date and number formatting.
NumberFormat Formatting numbers as strings. See thesection on date and number formatting.
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 4
Static String i18n
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 5
Interantionalizing StringsImplement the Constant Interface
Contains only static stringsVery efficient and compiled once.
Implement the Messages InterfaceAllows to insert values in the stringFor instance numbers or datesEquivalent to the resource bundle in applications.
Dynamic String InternationalizationThe Dictionary class lets your GWT application consumestrings supplied by the host HTML page.Convenient if your existing web server has a localizationsystem that you do not wish to integrate with the static stringinternationalization methods.
Implement the Localizable InterfaceThe most powerful techniqueallows you to go beyond simple string substitutioncreate localized versions of custom types.
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 6
Implement the Constants Interface
Create the StockWatcherConstants interfaceUses annotations for the default translationImplements the Constant interface (GWT)Bound automatically to theStockWatcherConstants*.properties files
The java file must contain one method for each of theconstants in the properties files
The right value is found at runtime, corresponding to the locale
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 7
Example: the Constants filepackage 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 spcialise bernoise | Berne University of Applied Sciences 8
Translate it to German
Create a file StockWatcherConstants de.properties
stockWatcher = Aktienbeobachtersymbol = Symbolprice = Kurs
change = Anderungremove = Entfernenadd = Hinzufugen
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 9
Implement the Messages interface
For Strings containing informationSimilar to resource bundles in JavaCan contain strings with parameters
’’{0}’’ ist kein gultiges 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, internationalizedresults
I Usefull but less efficient. The strings must be produced atruntime
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 10
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 spcialise bernoise | Berne University of Applied Sciences 11
The corresponding properties file
StockWatcherMessages de.properties file.
lastUpdate = Letzte Aktualisierung: {0,date,medium} {0,time,↘→medium}invalidSymbol = ’’{0}’’ ist kein gultiges Aktiensymbol.
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 12
Replace content
Replace the texts with place holders
<body><img src=”images/GoogleCode.png”/><h1 id=”appTitle”></h1>
Replacing strings set programmaticallyCreate 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 spcialise bernoise | Berne University of Applied Sciences 13
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 spcialise bernoise | Berne University of Applied Sciences 14
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 spcialise bernoise | Berne University of Applied Sciences 15
Client Server Communication
Remote Procedure CodeFrom Java To JavaSupported by the languageOptimized and easy to test
JSONFor communicating with the same server
JSONPFor cross server communicationOvergoes the Same Origin Policy
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 16
Remote Procedure Code
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 17
GWT Remote Procedure CallRPC contains:
the service that runs on the serverthe method you are calling
the client code that invokes the service
the Java data objects that pass between the client andserver
Both (client and server) must serialize and deserialize theobjects
You need to write three componentsDefine the interface StockPriceService that extendsRemoteService and lists all your RPC methodsCreate a class StockPriceServiceImpl that extendsRemoteServiceServlet and implements the interface youcreated above.Define an asynchronous interface StockPriceServiceAsync
to your service to be called from the client-side code.
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 18
GWT Remote Procedure Call1
1Source: code.google.comBerner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 19
StockPriceService interface
In the packagecom.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 spcialise bernoise | Berne University of Applied Sciences 20
StockPriceServiceImpl classpackage 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.00private 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 spcialise bernoise | Berne University of Applied Sciences 21
Include the server-side code in theGWT moduleDefine 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 spcialise bernoise | Berne University of Applied Sciences 22
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 spcialise bernoise | Berne University of Applied Sciences 23
Making the remote procedure callprivate 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 spcialise bernoise | Berne University of Applied Sciences 24
Serializing Java objects
GWT RPC requires that all service method parametersand 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 spcialise bernoise | Berne University of Applied Sciences 25
JSON
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 26
Retrieving JSON DataJSON stands for JavaScript Object Notation
Language independant formatVery light
Example
[{
”symbol”: ”ABC”,”price”: 87.86,”change”: −0.41},{
”symbol”: ”DEF”,”price”: 62.79,”change”: 0.49}
]Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 27
Server part
JSON can be generated by a servlet
out.println(” {”);out.print(” \”symbol\”: \””);out.print(stockSymbol);out.println(”\”,”);out.print(” \”price\”: ”);out.print(price);out.println(’,’);out.print(” \”change\”: ”);out.println(change);out.println(” },”);
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 28
JSON generated by PHP<?php
header(’Content−Type: text/javascript’);define(”MAX PRICE”, 100.0); // $100.00define(”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 ’,’;}}}echo ’]’;
?>
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 29
Transform JSON object intoJavaScript
use the built in JavaScript function eval
The function will receive a response.getText() as aparameter
private final native JsArray<StockData> asArrayOfStockData(↘→String json) /∗−{
return eval(json);}−∗/;
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 30
Manipulate JSON objects
Create a JavaScriptObject StockData to manipulate the data inputin 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 spcialise bernoise | Berne University of Applied Sciences 31
Connect the Web serverPrepare 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 spcialise bernoise | Berne University of Applied Sciences 32
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 spcialise bernoise | Berne University of Applied Sciences 33
Conclusion GWT
Google Web ToolkitsOne Application = one languageDevelopment in JavaScript is made easyClient Server Communication is hidden
Security IssuesCommunication is bluredWhat is tested where?Who does what?
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 34
Conclusion AWTJava on a Server
Servlet : for small programms (alternative to PHP)Java Server Faces : For large programms with a huge Middletier
Web SecurityVery important to test and validate inputsEncode outputsVerify everythingDo not allow access to your intern kitchen to attackersRemove error messages
GWTOnly one language from the client to the server
Quality Management
Can you please fill out the given questionnairePurely informative, for my use only
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 35
References
Google Codehttp://code.google.com/intl/fr-FR/webtoolkit/
overview.html
Tutorial for Client Server communicationhttp://code.google.com/intl/fr-FR/webtoolkit/doc/
latest/tutorial/clientserver.html
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 36