Table of Contents Advanced Web Technology Internationalization - - PowerPoint PPT Presentation

table of contents advanced web technology
SMART_READER_LITE
LIVE PREVIEW

Table of Contents Advanced Web Technology Internationalization - - PowerPoint PPT Presentation

Table of Contents Advanced Web Technology Internationalization 13) Google Web Toolkits 2 - Static String i18n GWT, Communication Remote Procedure Code Emmanuel Benoist Fall Term 2016-17 JSON Berner Fachhochschule | Haute cole


slide-1
SLIDE 1

Advanced Web Technology 13) Google Web Toolkits 2 - GWT, Communication

Emmanuel Benoist

Fall Term 2016-17

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 1

Table of Contents

  • Internationalization

Static 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 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 spcialise bernoise | Berne University of Applied Sciences 4

slide-2
SLIDE 2

Static String i18n

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 5

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 spcialise bernoise | Berne University of Applied Sciences 6

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 spcialise bernoise | Berne University of Applied Sciences 7

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 spcialise bernoise | Berne University of Applied Sciences 8

slide-3
SLIDE 3

Translate it to German

Create a file StockWatcherConstants de.properties stockWatcher = Aktienbeobachter symbol = Symbol price = Kurs change = ¨ Anderung remove = Entfernen add = Hinzuf¨ ugen

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 9

Implement the Messages interface

For Strings containing information

Similar to resource bundles in Java Can contain strings with parameters ’’{0}’’ ist kein g¨ ultiges 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 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 g¨ ultiges Aktiensymbol.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 12

slide-4
SLIDE 4

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 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 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 spcialise bernoise | Berne University of Applied Sciences 16

slide-5
SLIDE 5

Remote Procedure Code

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 17

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 spcialise bernoise | Berne University of Applied Sciences 18

GWT Remote Procedure Call1

1Source: code.google.com Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 19

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 spcialise bernoise | Berne University of Applied Sciences 20

slide-6
SLIDE 6

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 spcialise bernoise | Berne University of Applied Sciences 21

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 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 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 spcialise bernoise | Berne University of Applied Sciences 24

slide-7
SLIDE 7

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 spcialise bernoise | Berne University of Applied Sciences 25

JSON

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 26

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 spcialise bernoise | Berne University of Applied Sciences 27

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 spcialise bernoise | Berne University of Applied Sciences 28

slide-8
SLIDE 8

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 spcialise bernoise | Berne University of Applied Sciences 29

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 spcialise bernoise | Berne University of Applied Sciences 30

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 spcialise bernoise | Berne University of Applied Sciences 31

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 spcialise bernoise | Berne University of Applied Sciences 32

slide-9
SLIDE 9

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 Toolkits

One Application = one language Development in JavaScript is made easy Client Server Communication is hidden

Security Issues

Communication is blured What is tested where? Who does what?

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 34

Conclusion AWT

Java on a Server

Servlet : for small programms (alternative to PHP) Java Server Faces : For large programms with a huge Middle tier

Web Security

Very important to test and validate inputs Encode outputs Verify everything Do not allow access to your intern kitchen to attackers Remove error messages

GWT

Only one language from the client to the server

Quality Management

Can you please fill out the given questionnaire Purely informative, for my use only

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 35

References

Google Code http://code.google.com/intl/fr-FR/webtoolkit/

  • verview.html

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

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 36