Upload
saravanan-thangavel
View
219
Download
0
Embed Size (px)
Citation preview
8/2/2019 Rc001-Gwt Style Online Merged
http://slidepdf.com/reader/full/rc001-gwt-style-online-merged 1/12
GWTStyle, Configuration and JSNI Referenc
By Robert Hans
CONTENTS INCLUDE:
n About Google WebToolkit (GWT)
n Ocial GWT Web Sites
n Styling Widgets with CSS
n GWT Module Conguration
n
JavaScript Native Interacen Hot Tips and more...
DZone, Inc. | www.dzone.com
ABOUT GOOGLE WEB TOOLKIT (GWT) STYLING WIDGETS WITH CSS
The Google Web Toolkit is a set o tools or writing JavaScript
applications in Java. The cornerstone o the tool suite is a Java
to JavaScript compiler that can not only compile Java down to
JavaScript, but can also compress and optimize your code as
well. GWT was released to the public in June o 2006 and has
been an overwhelming success, boasting 1 million downloads
in its rst year.
The benet o using GWT over some o the other JavaScript
rameworks like JQuery or Ext-JS is the environment in which
you code. GWT allows a Java developer to use the same tools
they use today like Eclipse, Maven, and JUnit, making the
transition rom Java server-side development to GWT client-
side development nearly seamless.
The GWT toolkit comes ready with its own widget library,
internationalization tools, image bundling tools, tools or
client-server communication, and many others. Since its launch
GWT has become an open-source project, and although led
by the GWT team at Google, many rom the community have
contributed patches to the toolkit. GWT boasts a thriving
community, proving or a multitude o ree widgets, integrationtools, and utilities.
This reerence card is a guide to everything that your IDE
can’t already tell you. Specically, IDEs like Eclipse provide
auto-completion capabilities or perusing a list o methods on
an object, and oten they also provide support or viewing
javadocs in the IDE as well. This recard is meant to supplement
that capability by providing details that are only available in
books and online documentation. Specically this includes a
CSS style or the widgets that ship with GWT, a reerence or
the JavaScript Native Interace, and a complete guide to the
GWT module conguration le.
OFFICIAL GWT WEB SITES
WebSite: http://code.google.com/webtoolkit/
Blog: http://googlewebtoolkit.blogspot.com/
Forum: http://groups.google.com/group/Google-Web-Toolkit
Issue Tracker: http://code.google.com/webtoolkit/issues/
Articles: http://code.google.com/webtoolkit/articles.html
Examples: http://code.google.com/webtoolkit/examples/
Dev Guide: http://code.google.com/webtoolkit/documentation/
Styling widgets is done using Cascading Style Sheets (CSS).
CSS can be applied to the widgets in the application three
dierent ways.
Adding a style element inside the <head> o the HTML page
that is hosting the application.
<style type=”text/css”>
/* CSS style rules*/
</style>
Adding a <link> element to the <head> o the HTML page,
reerencing an external CSS stylesheet.
<link type=”text/css” rel=”stylesheet”
href=”url-to-le.css” />
Adding a <stylesheet> element to the GWT project’s module
conguration, causing the stylesheet to be injected into the
host HTML page.
<stylesheet src=”url-to-le.css”/>
Most o the widgets that come with GWT have been pre-assigne
CSS class names. For example, the Button widget uses theCSS class name gwt-Button. So you could set the width o all
Button widgets in your application by using the ollowing CSS
rule. In order to reerence a CSS class in a CSS rule you prex
the class name with a period “.”.
.gwt-Button {
width: 100px;}
w w
w . d z o n e . c o m
G e t M o r e R e f c a r d z ! v i s i t r e f c a r d z . c o m
G
W T
y
g
a n d
J S N I R e f e r e n c e
n Authoritative contentn Designed for developersn Written by top expertsn Latest tools & technologiesn Hot tips & examplesn Bonus content onlinen New issue every 1-2 weeks
Subscribe Now or FREE!Recardz.com
Get More Recardz(They’re free!)
tech f act sa t your finger
t ips
tech facts at your fingertips
Elemen t Description
<description> Used todescribeaSpringco n textor anindividua l b ean.
<impor t> Importsano ther Spring contex tdefnition.
<description> Documents the bean. Although ignored b y thecontainer,
<descrip tion>can be usedby tools thatd ocument Spring
con texts.
<lookup-method> Enabl esge tter-in jectionby wayo methodreplacement.
Speci fes a methodtha twillb e overridden to returna
specifc bean. Commonl y known as getter-injec tion.
<meta> Allows orme ta-con fgura tiono the bean. Only useul
when there are beans con fgured that interprets and ac ts
on the me ta inormation.
<prop erty> Injectsav alueor a bean reerenceintoa specifcproperty
o the bean. Comm only known as se tter-in jection.
<replaced-me thod> Replacesam ethodothe bean withanewimplemen tation.
Element Descrip tion
<alias> Creates an alias or a bean de fnition.
<bean> Defnes a bean in the Springc ontainer.
<constructor-arg> In jectsa valueo r abeanre erenc ei nto anargumento the
bean’sconstruc tor.Commonlyknownascons tructorinjec tion.
AttributeDescription
abstract I true, the bean is abs tractandw illnot be ins tantia tedb y
the Spri ng container.
au towire Declares how and i a bean should be au towired. Valid
values are byT ype, b yName, constructor, autodetect, or
no orno autowiring.
auto wire-candidate I false, the bean is no t a candida te or auto wiring into
another bean.
class Theully-qualifed classname othe bean.
dependency-check Determines howSpring shouldenorcepropertysetting o nthe
bean.simple indica test ha tallp rimitive typepropertiesshould
beset;ob jects indica tes thatall complexty pe properties
should b eset.O therval uev al uesare de fault, none, or all.
depends-on Identi fes a bean thatshould be instantia tedb y the
containerbe ore this bean is instantiated.
#1
8/2/2019 Rc001-Gwt Style Online Merged
http://slidepdf.com/reader/full/rc001-gwt-style-online-merged 2/12
GWT Style, Conguration and JSNI Reerence2
DZone, Inc. | www.dzone.com
STYLING WIDGETS WITH CSS, continued
Altering Style Names You can programmatically alter the CSS class name used on
a widget by calling any o these methods.
widget.setStylePrimaryName(“styleName”)
In HTML you may provide any number o CSS class names onan element by separating them with spaces, like in the HTML
snippet below.
<div class=”style1 style2 style3”></div>
The primary style name in GWT is dened as the rst style
name in the class attribute. In the example provided, this
would be the style “style1”. Calling setStylePrimaryName()
allows you to alter this rst style.
widget.addStyleDependentName(“styleName”)
When you add a dependent style name, its name in the HTML
is the primary name plus the depende nt name, separated
with a dash (“-“).
Example:
Button button = new Button();
button.setStylePrimaryName(“oo”);
button.addStyleDependentName(“bar”);
Result:
<BUTTON class=”foo foo-bar”></BUTTON>
widget.setStyleName(“styleName”)
Using setStylename() will clear all current style names, including
the primary style name, and adds the one provided.
widget.addStyleName(“styleName”)
Adds an additional style name to any existing style names.Example:
Button button = new Button();
button.setStyleName(“oo”);
button.addStyleName(“bar”);
Result:
<BUTTON class=”foo bar”></BUTTON>
widget.removeStyleName(“styleName”)
Allows you to remove an existing style name on a widget.
Deault GWT Widget Style Names
Most o the widgets provided by the GWT library havepre-dened primary style names. The ollowing is a list o the
deault names or each widget.
tech facts at your fingertips
Widget Deault Name
HorizontalSplitPanel .gwt-HorizontalSplitPanel { the panel }.gwt-HorizontalSplitPanel hsplitter { splitter }
HTML .gwt-HTML { }
Hyperlink .gwt-Hyperlink { }
Image .gwt-Image { }
Note: Transormations between clipped and upclipped
will result in the loss o any CSS style names that wereset or added.
Label .gwt-Label { }
ListBox .gwt-ListBox { }
MenuBar .gwt-MenuBar { the menu bar itsel }.gwt-MenuBar .gwt-MenuItem { menu items }.gwt-MenuBar .gwt-MenuItem-selected { selectedmenu items }
PasswordTextBox .gwt-PasswordTextBox { primary style }.gwt-PasswordTextBox-readonly { dependent styleset when the password text box is read-only }
PushButton .gwt-PushButton-up {}.gwt-PushButton-down {}.gwt-PushButton-up-hovering {}
.gwt-PushButton-down-hovering {}
.gwt-PushButton-up-disabled {}
.gwt-PushButton-down-disabled {}<any o the above> .html-ace {}
RadioButton .gwt-RadioButton { }
RichTextArea .gwt-RichTextArea { }
StackPanel .gwt-StackPanel { the panel itsel }.gwt-StackPanel .gwt-StackPanelItem{ unselected items }.gwt-StackPanel .gwt-StackPanelItem-selected{ selected items }
SuggestBox .gwt-SuggestBox { the suggest box itsel }.gwt-SuggestBoxPopup { the suggestion popup }.gwt-SuggestBoxPopup .item{ an unselected suggestion }
.gwt-SuggestBoxPopup .item-selected{ a selected suggestion }
TabBar .gwt-TabBar { the tab bar itsel }.gwt-TabBar .gwt-TabBarFirst { the let edge o the bar }.gwt-TabBar .gwt-TabBarRest{ the right edge o the bar }.gwt-TabBar .gwt-TabBarItem { unselected tabs }.gwt-TabBar .gwt-TabBarItem-selected{ additional style or selected tabs }
TabPanel .gwt-TabPanel { the tab panel itsel }.gwt-TabPanelBottom { the bottom section o thetab panel (the deck containing the widget) }
TextArea .gwt-TextArea { primary style }.gwt-TextArea-readonly{ dependent style set when the text area is read-only }
TextBox .gwt-TextBox { primary style }
.gwt-TextBox-readonly{ dependent style set when the text box is read-only }
ToggleButton .gwt- ToggleButton-up {}.gwt- ToggleButton-down {}.gwt- ToggleButton-up-hovering {}.gwt- ToggleButton-down-hovering {}.gwt- ToggleButton-up-disabled {}.gwt- ToggleButton-down-disabled {}<any o the above> .html-ace {}
Tree .gwt-Tree { the tree itsel }.gwt-Tree .gwt-TreeItem { a tree item }.gwt-Tree .gwt-TreeItem-selected { a selected treeitem }
VerticalSplitPanel .gwt-VerticalSplitPanel { the panel itsel }.gwt-VerticalSplitPanel vsplitter { the splitter }
Widget Deault Name
Button .gwt-Button { }
Checkbox .gwt-CheckBox { }
DialogBox .gwt-DialogBox { the box container }.gwt-DialogBox .Caption { the box caption }
DisclosurePanel .gwt-DisclosurePanel { primary style }.gwt-DisclosurePanel-open { when open }.gwt-DisclosurePanel-closed { when closed }.header { the panel header area }.content { the panel content area }
8/2/2019 Rc001-Gwt Style Online Merged
http://slidepdf.com/reader/full/rc001-gwt-style-online-merged 3/12
3
DZone, Inc. | www.dzone.com
Simple Module ConfgurationA simple module conguration must inherit the User module
and speciy a single entry point. The entry point is the class that
implements the EntryPoint interace and acts as the starting
point or the application.
<module>
<inherits name=’com.google.gwt.user.User’ />
<entry-point
class=’org.gwtsandbox.demo.client.Demo’ />
</module>
From the basic module conguration you can build on it by
adding additional elements to inherit additional modules,
change the deault source path, add servlet mappings, and
add deerred binding rules.
Inheriting ModulesI your GWT project needs to reerence external GWT modules
you must explicitly inherit them in your module conguration.
The core GWT libraries are split into several modules, each o
which is listed here. You will always need to include the User
module, and optionally one or more o the others.
GWT widgets and core utilities
<inherits name=”com.google.gwt.user.User” />
RequestBuilder and associated classes
<inherits name=”com.google.gwt.http.HTTP” />
Internationalization tools and date/number ormatting
<inherits name=”com.google.gwt.i18n.I18N” />
Tools or using RPC with JavaScript Object Notation
<inherits name=”com.google.gwt.json.JSON” />
XML parser and associated classes
<inherits name=”com.google.gwt.xml.XML” />
Source PathThe source path is a relative path name used to override the
deault location o the client-side Java source destined to
be compiled into JavaScript. The source path you speciy is
appended to the path where the module conguration le
resides, and you may speciy multiple source paths.
<source path=”path”/>
By deault the source path is “client”. So by way o example, i your GWT module conguration le is located at com.example.
MyApp.gwt.xml, then the deault path o “client” will dictate that
your client-side Java source will be located in the Java package
com.example.client.*, as well as all packages below this one.
All source code in the source path(s) must be able to be
compiled to JavaScript with the GWT compiler. This implies
that only classes rom the JRE emulation library and GWT
user library be used. For example, you can not include Java
servlets or use the java.sql.* classes under this path.
Public PathThe public path is used to store non-Java les that need
to be included in the application. This includes HTML les,JavaScript les, images, CSS, and anything else. By deault
this will be the “public” directory below where the module
conguration is stored.
You can overr ide the deault by using the <public> tag in the
module conguration.
<public path=”path”/>
You may speciy multiple public paths i required or your project.
Defning GWT-RPC Servlets You can use the <servlet> tag in the module conguration to
dene your GWT-RPC servlets.
<servlet path=”/path”class=”org.gwtsandbox.demo.server.Demo” />
The path specied should be absolute.
Resource Injection
You can have external JavaScript and CSS les automaticallyinjected into the hosting web page. By injecting the resources
you avoid the need to have the hosting HTML page explicitly
include them with <link> and <script> tags. Resources loaded
in this way will be loaded prior to the executing o the GWT
application.
<script src=”js-url”/>
<stylesheet src=”css-url”/>
To inject a resource you can either place the JavaScript or CSS
le into the public package o the GWT module (see above),
reerencing it with a relative path, or reerence an external CSS
le by using a ull URL.
GWT Style, Conguration and JSNI Reerence
HotTip
These servlet mappings are or the beneft o
hosted-mode use only, and does not imply that
these mappings will be carried over to your
production environment. For that you would set
them up in the deployment descriptor, just as
you would with any other servlet.
A module in GWT is best described as a set o classes that are
bound by a single module conguration le. The module con-
guration denes what classes are a part o the module, what
other modules that the module depends on, as well as rules or
deerred binding, resource injection, and everything else that
the GWT compiler and shell needs to know about your module.
A module conguration le is located in the GWT project, with
an extension o “.gwt.xml”. The location on the classpath and the
module conguration le name determine the ull module name.
Module Name =
Java Package + Module File Name (-gwt.xml)
For example, i you have a module conguration le named
Demo.gwt.xml, in the java package com.gwtsandbox.demo, the
module name would be com.gwtsandbox.demo.Demo.
GWT MODULE CONFIGURATION
HotTip
The module confguration is only used at design
and compile-time, it is not used at run-time. This
is a common mistake or new GWT developers.
tech facts at your fingertips
8/2/2019 Rc001-Gwt Style Online Merged
http://slidepdf.com/reader/full/rc001-gwt-style-online-merged 4/12
4
DZone, Inc. | www.dzone.com
GWT Style, Conguration and JSNI Reerence
GWT MODULE CONFIGURATION, continued
Deerred BindingIn some cases you need to write low-level unctionality that
diers based on the client browser, or you need to trigger
a generator to generate code at compile time. For these
unctions you use deerred binding. Deerred binding allows
you to write code to an interace and have the concrete classdetermined at compile-time.
For example, you may be amiliar with GWT’s RPC mechanism.
You use the GWT.create() method to return a concrete class
that can serialize and send your data to the server.
MyServiceAsync svc =
(MyServiceAsync) GWT.create(MyService.class);
When this code is compiled the compiler examines the
argument passed to the create method, then attempts to
match the target class to a set o rules that reside in the
module conguration.
Using Generate-With to Trigger GeneratorsIn this case the compiler rule is specied in the module com.
google.gwt.user.RemoteService, which is inherited rom your
module when using GWT-RPC.
<generate-with
class=”com.google.gwt.user.rebind.rpc.
ServiceInterfaceProxyGenerator”>
<when-type-assignable
class=”com.google.gwt.user.client.rpc.RemoteSer -
vice”/>
</generate-with>
This rule states that when the target class o the GWT.create()
is assignable to RemoteService, that the generator
ServiceInteraceProxyGenerator is executed. The generator
then creates the code and returns the name o the class thatshould be returned by the create method.
Using Replace-With to Trigger Class ReplacementThe other use o deerred binding is to speciy a alternate class
to be returned by GWT.create() based on available properties.
The most common use o this is to use an alternate class
depending on the client browser. The property that can be
examined to determine this is “user.agent”.
For example, the DOM class in GWT is used to perorm low-level
unctions, where the browser implementations can dier. In order
to allow or dierent browsers the ollowing rule can be ound
in the com.google.gwt.user.DOM module.
<replace-with
class=”com.google.gwt.user.client.impl.DOMImplIE6”>
<when-type-is
class=”com.google.gwt.user.client.impl.DOMImpl”/>
<when-property-is name=”user.agent” value=”ie6”/>
</replace-with>
In the DOM class the ollowing code is used to “create” the
correct implementation o the DOM class.
DOMImpl impl = (DOMImpl) GWT.create(DOMImpl.class);
When the user.agent property is “ie6” the replace-with rule
specied above will return a DOM implementation that is
specically designed or Internet Explorer.
Generate-With and Replace-With ExpressionsThe ollowing expression tags can be used within generate-with
and replace-with tags. When any o the expression tags within
the rule returns a true value, the code generation or class
replacement is perormed.
<when-property-is
name=”prop-name” value=”matched-value” />
Returns true when the value o the property matches thespecied value. For details on setting properties, see the
Setting Properties section.
<when-type-assignable class=”assignable-type” />
The target class is tested to see i it can be assigned to the
specied assignable type.
<when-type-is class=”type” />
Similar to when-type-assignable, except that the class must be
an exact match.
<all>, <any>, <none>
Use these expression tags to group other expression tags.
The <all> tag implies that all o the tags contained within it
must be true. The <any> tag requires only one o the containingexpressions to be true. The <none> tag requires that all contained
expression tags return alse.
Setting PropertiesProperty names and their possible values can be dened in
the module conguration.
<dene-property name=”prop-name” values=”vals” />
Creates a new property and comma separated list o the
possible values. For example, you could use the ollowing
to dene a view property that could be used to dene three
unique view types or the application.
<extend-property name=”prop-name” values=”vals” />
Extends the possible values or a property that has alreadybeen dened.
<set-property name=”prop-name” value=”value” />
Sets the value o a dened property. The value must be one o the
possible values as dened by the <dene-property> tag or one o
the extended values as dened by the <extended-property> tag.
<property-provider name=”prop-name”>
Property values can be set at run-time by supplying a property
provider. The contents o the <property-provider> tag is a block
o JavaScript that returns the property value. The JavaScript
code must be placed in a CDATA block to avoid parsing errors.
<property-provider name=”view”><![CDATA[
var view = __gwt_getMetaProperty(“view”);
if (!__gwt_isKnownPropertyValue(“view”, view)) {
view = ‘basic’;
}
return view;
]]></property-provider>
The JavaScript block can utilize the __gwt_getMetaProperty()
method to get the value o GWT property dened in a <meta>
tag in the HTML page, and can use __gwt_isKnownProperty-
Value() to test that it is an allowed value. Here’s an example o
using the HTML <meta> tag to set the view as “extended”.
<meta name=”gwt:property” content=”view=extended” />
tech facts at your fingertips
8/2/2019 Rc001-Gwt Style Online Merged
http://slidepdf.com/reader/full/rc001-gwt-style-online-merged 5/12
5
DZone, Inc. | www.dzone.com
GWT Style, Conguration and JSNI Reerence tech facts at your fingertips
JSNI VariablesDue to the way GWT applications load, the “window” and
“document” JavaScript objects point to the wrong objects.
GWT provides these special variables or use in JSNI methods.
public native void doStu () /*-{
$wnd.alert(‘Hello World’);
}-*/;
Passing Values Between Java and JavaScript You can pass both Java primitives and objects into a JSNI
method. The ollowing rules dene how Java values are
available in JSNI methods and visa versa.
Calling Java Methods rom JavaScript, continued
The instance expression is the name o the variable passed
into the method, or “this” to reer to the class instance, or
blank or calling static methods.
The class name is the ully qualied name, ollowed by
double colons and the method name.
The parameter signature is a list o the parameter types in
the method that you are calling. This is needed in order todistinguish between two Java methods that have the same
name but dierent sets or parameters. The ollowing table
denes the codes used to speciy the parameter type.
Types are listed one ater the other without spaces. For example,
“ZLjava/lang/String;[F” denes the method signature (boolean,
String, foat[]).
The argument list is exactly that, a list o the arguments being
passed to the method.
Below are examples o calling methods rom JavaScript on well
known Java types.
Calling instance method with no arguments:
public native long extractTime (Date date) /*-{
return [email protected]::getTime()();
}-*/;
Calling instance method with a single argument:
public native void appendText (StringBuer sb, String txt)
/*-{
[email protected]::append(Ljava/lang/String;)
(txt);
}-*/;
Calling static method with multiple arguments:
public native int maxValue (int x, int y) /*-{
return @java.lang.Math::max(II)(x, y);
}-*/;
Accessing Java properties rom JavaScriptAccessing properties o a Java object rom JavaScript is similar
to calling a Java method.
[instance-expr.]@class-name::eld-name
The same value rules apply as calling methods (see Calling Java
Methods rom JavaScript). The instance expression is the variable
name passed into the JSNI method, “this” or the instance o the
class, or let o to access a static property. The class name is the
ully qualied package and class, and is separated rom the feld
name with two colons. On the ollowing page are some examples.
JSNI methods that have Java objects passed to them may use
a special syntax in order to call methods and access properties
o the object.
Calling Java Methods rom JavaScriptThe ollowing syntax is used to call a Java method rom a
JSNI method.
[instance-expr.]@class-name::method-name(param-signature)(arguments)
Variable Purpose
$wnd Alias or the JavaScript “window” object
$doc Alias or the JavaScript “document” object
Type Code Java Type
Z Boolean
B Byte
C Char
S Short
I Int
J Long
F Float
D Double
L ully-qualifed-class ; Java objects. Uses “/” to delimit parts o the packagename, e.g. “Ljava/lang/String;”
[ type Int
Java type Where created JavaScript type
numeric primitive (byte,short, char, int, long, foat,double)
Both numeric value
boolean primitive Both boolean value
String Both string value
JavaScriptObject Must be created inJSNI method
An object
Java array Must be created in Java Not directly usable,
can be passed backinto Java code
All other Java objects Must be created in Java Special, see below
The JSNI interace is used as a gateway between your Java
and JavaScript code. It allows you to create Java methods
that have JavaScript code in the body, and then to have the
JavaScript code call Java methods.
JSNI MethodsMethods containing JavaScript must use the native modier
so that a Java compiler will not validate its contents. Methods
in Java marked as native may not have a method body.
public native void doStu ();
GWT introduces a special comment syntax that ollows the
Java native rule o having no method body, while allowing
you to provide JavaScript code that can be picked up by the
GWT compiler.
public native void doStu () /*-{
// JavaScript code goes here
}-*/;
JAVASCRIPT NATIVE INTERFACE
8/2/2019 Rc001-Gwt Style Online Merged
http://slidepdf.com/reader/full/rc001-gwt-style-online-merged 6/12
6
GWT Style, Conguration and JSNI Reerence
ABOUT THE AUTHOR RECOMMENDED BOOK
BUY NOWbooks.dzone.com/books/gwt-in-acti
GWT in Action shows you
how to set up your develop
ment environment, use and
create widgets, communica
with the server, and much
more. Readers will ollow a
example running througho
the book and quickly mast
the basics o GWT: widget
panels, and event handling.
Robert Hanson
Robert Hanson is an Applications Manager or Quality Technology Services, a company
providing hosting, managed services, and application development. He is passionate
about programming and architecture, and has developed opensource sotware
or both the Perl and Java communities. His latest venture is the GWT Widget Library,
a set o tools or use with the Google Web Toolkit, a toolkit allowing you to write
JavaScript applications in Java. In 2007 Robert co-authored the book GWT in Action with Adam Tacy,
providing instruction on using the Google toolkit. Robert provides tutorials and random thoughts about
the crat on his blog ound at roberthanson.blogspot.com.
Publications n GWT in Action with Adam Tacy
Blog Roberthanson.blogspot.com
tech facts at your fingertips
Accessing Java properties rom JavaScript, continued
Reading and writing to feld on “this”
// int currentIndex;
var cur = [email protected]::currentIndex;
[email protected]::currentIndex = 0;
Reading and writing to feld on object
// String welcomeMessage;
var msg = [email protected]::welcomeMessage;
[email protected]::welcomeMessage = “Hello”;
Reading and writing to a static feld
// boolean lastResult;
var last = @org.example.Demo::lastResult;
@org.example.Demo::lastResult = true;
JAVASCRIPT NATIVE INTERFACE, continued You can use JSNI to dynamically create JavaScriptmethods that can be used by external JavaScriptcode to make calls into your application. Theollowing code creates a JavaScript method
jsMethod(string) on startup in the browser that can be used
to call the javaMethod(String) in the GWT application.
public void onModuleLoad () {
createJsMethod(this);}
private native void createJsMethod (Main obj) /*-{
$wnd.jsMethod = function (s) {
return
[email protected]::javaMethod(Ljava/lang/
String;)(s);
};
}-*/;
public String javaMethod (String in) {
return “I got your message: “ + in;
}
<button onclick=”alert(jsMethod(‘Hello’))”>Say Hello</button>
HotTip
DZone, Inc.
1251 NW Maynard
Cary, NC 27513
888.678.0399
919.678.0300
Recardz Feedback Welcome
Sponsorship Opportunities
Copyright © 2008 DZone, Inc. All rights reserved. No part o this publication may be reproduced, stored in a retrieval system, or transmitted, in any orm or by means electronic,
mechanical, photocopying, or otherwise, without prior written permission o the publisher.
Version 1.
ISBN-13: 978-1-934238-07-3
ISBN-10: 1-934238-07-4
9 781934 238073
5 0 7 9 5
DZone communities deliver over 4 million pages each month to
more than 1.7 million software developers, architects and decision
makers. DZone offers something for everyone, including news,
tutorials, cheatsheets, blogs, feature articles, source code and more.
“DZone is a developer’s dream,” says PC Magazine.
Get More FREE Recardz. Vis it recardz.com now!
Upcoming Refcardz:Core Seam
Core CSS: Part III
Hibernate Search
Equinox
EMF
XML
JSP Expression Language
ALM Best Practices
Available:Essential Ruby
Essential MySQL
JUnit and EasyMock
Getting Started with MyEclipse
Spring Annotations
Core Java
Core CSS: Part II
PHP
Getting Started with JPA
JavaServer Faces
Core CSS: Part I
Struts2
Core .NET
Very Firs t Steps in Flex
C#
Groovy
NetBeans IDE 6.1 Java Editor
RSS and Atom
Visit recardz.com or a complete listing o available Recardz.Design Patterns
Published June 2008
FREE
8/2/2019 Rc001-Gwt Style Online Merged
http://slidepdf.com/reader/full/rc001-gwt-style-online-merged 7/12
DZone, Inc. | www.dzone.com
By Daniel Rub
ABOUT CLOUD COMPUTING
G
e t t i n g
S t a r t e d
w i t h
C l o u d C o m p u t i n g
w
w w . d z o n e . c o m
G e t M o r e R e f c a r d z ! V i
s i t r e f c a r d z . c o m
82
Getting Started with
Cloud Computing
CONTENTS INCLUDE:
n About Cloud Computingn Usage Scenariosn Underlying Conceptsn Costn Data Tier Technologiesn Platform Management and more...
Web applications have always been deployed on servers
connected to what is now deemed the ‘cloud’.
However, the demands and technology used on such servers
has changed substantially in recent years, especially with
the entrance of service providers like Amazon, Google and
Microsoft.
These companies have long deployed web applications
that adapt and scale to large user bases, making them
knowledgeable in many aspects related to cloud computing.
This Refcard will introduce to you to cloud computing, with an
emphasis on these providers, so you can better understand
what it is a cloud computing platform can offer your web
applications.
Get over 70 DZone Refcardz
FREE from Refcardz.com!
USAGE SCENARIOS
Pay only what you consumeWeb application deployment until a few years ago was similar
to most phone services: plans with alloted resources, with an
incurred cost whether such resources were consumed or not.
Cloud computing as it’s known today has changed this.
The various resources consumed by web applications (e.g.
bandwidth, memory, CPU) are tallied on a per-unit basis
(starting from zero) by all major cloud computing platforms.
This can be benecial for web applications that have
disproportionate resource requirements (e.g. bandwidth
intensive vs. memory intensive), since only consumed resources
incur in cost.
One time event provisioning
Web applications are often subject to trafc spikes due to onetime events (e.g. National broadcast exposure, SuperBowl
commercial). Not only can this type of provisioning be
expensive, but often times difcult to achieve.
By using a cloud computing platform, provisioning of this sort
can be greatly simplied.
Cloud computing platforms allow web applications “on tap”
access to resources without an application owner (i.e. you)
footing the bill for stand-by equipment.
Additionally, since the underlying architecture of a web
application is built around a cloud computing platform, this
also minimizes the need to make design changes to support
one time events.
Automated growth & scalable technologiesHaving the capability to support one time events, cloud
computing platforms also facilitate the gradual growth curves
faced by web applications.
Large scale growth scenarios involving specialized equipmen
(e.g. load balancers and clusters) are all but abstracted away
relying on a cloud computing platform’s technology.
In addition, several cloud computing platforms support data
tier technologies that exceed the precedent set by Relationa
Database Systems (RDBMS): Map Reduce, web service APIs,
etc. Some platforms support large scale RDBMS deployment
CLOUD COMPUTING PLATFORMS AND
UNDERLYING CONCEPTS
Amazon EC2: Industry standard software and virtualizatio
Amazon’s cloud computing platform is heavily based on
industry standard software and vi rtualization technology.
Virtualization allows a physical piece of hardware to be
utilized by multiple operating systems. This allows resources
(e.g. bandwidth, memory, CPU) to be allocated exclusively to
individual operating system instances.
As a user of Amazon’s EC2 cloud computing platform, you
are assigned an operating system in the same way as on all
hosting providers that preceded cloud computing platforms.
8/2/2019 Rc001-Gwt Style Online Merged
http://slidepdf.com/reader/full/rc001-gwt-style-online-merged 8/12DZone, Inc. | www.dzone.com
2Getting Started with Cloud Computing
The primary difference is that such an instance is highly
customizable, in addition to having its resources tallied on a
per unit basis, as well as being equipped to scale to larger
loads on a case by case basis.
Key characteristics of Amazon EC2
• Choice of industry standard server operating system
(e.g. Windows, Linux, Solaris)
• Deployment building block consists of an Amazon
Machine Image(AMI). An AMI is a standard server
operating system image with pre-selected applications.
AMI’s can be found at: http://developer.amazonwebservices.com/
connect/kbcategory.jspa?categoryID=171
• Application development open to any server-side
development tool, compatible with industry standard
server operating system.
Google App Engine: Google infrastrcture & SDK Google’s cloud computing platform is heavi ly based on
Google’s own server infrastructure.
As a user of Google’s App Engine, your web applications are
built on the same principles as Google applications.
Key Characteristics of Google App Engine
• Built on Google infrastructure (i.e. No commercially
available server operating system).
• Choice of either Python or Java run-time for running web
applications. Other pre-selected applications are available
via services (e.g. Mail, Memcache).
• Application development tightly pegged to Google’s
Software Development Kit (SDK). (http://code.google.com/
appengine/downloads.html#Download_the_Google_App_Engine_SDK)
• Tightly integrated with Google’s web services APIs (e.g.
For authenticating users and sending email).
• Free quotas for applications limited to: 500MB of
persistent storage and CPU & bandwidth for
approximately 5 million page views a month.
Microsoft Azure: Azure & Visual StudioMicrosoft’s cloud computing platform is tightly integrated with
Microsoft’s product line.
As a user of Microsoft Azure’s cloud computing platform,
you can expect your web applications to have streamlinedintegration with Microsoft’s product line.
Key Characteristics of Microsoft Azure
• Operates on Microsoft’s virtualized 64-bit Windows
Server 2008 operating system.
• Support for .NET applications, as well as other third party
applications available for the same OS running on a
standard server (i.e. unmanaged code apps).
• Support for .NET services: .NET Access Control Service &
.NET Service Bus. Originally known as BizTalk services,
focused on enterprise application scenarios.
• Application development tightly integrated with
Microsoft’s Visual Studio, in addition to having its
own Software Development Kit (SDK)
http://go.microsoft.com/fwlink/?LinkID=128752
• Free usage under CTP (Community Technology Preview),
but limited to 2000 hours, 50 GB of persistent storage and
20GB/day bandwidth.
Selection Grid by Web Application Language
Web applicationlanguage
Amazon EC2 Google App Engine Microsoft Azure
PHP
.NET
Java
Python
Ruby
Resources (Bandwidth, CPU, I/O)Cloud computing providers keep track of consumed resources
on a more granular basis than traditional service providers. Thefollowing list illustrates a series of consumption units:
• Server – Per Hour
• Bandwidth – Per Gigabyte
• Storage – Per Gigabyte
• CPU/Memory – Per unit
• Emails – Per recipient
This approach gives an application owner (i.e. you) greater
leverage and cost effectiveness. The next section on ‘Costs’
illustrates case scenarios with side by side comparisons for the
various cloud computing platforms.
Other cloud computing providersIn addition to Amazon’s EC2 , Google’s App Engine and
Microsoft’s Azure cloud computing platforms, other providers
in this space have also emerged.
Some of these providers include:
• Slice Host - http://www.slicehost.com/
• Linode - http://www.linode.com/
• Prgmr - http://prgmr.com/
• Heroku - http://heroku.com/
• Rackspace - http://www.rackspacecloud.com/
• GoGrid - http://www.gogrid.com/
Many of these providers rely on industry standard virtualization
and operating system technology, making them closecompetitors to Amazon’s EC2 cloud computing platform.
Comparing these other providers to Google’s App Engine
or Microsoft’s Azure cloud computing platforms can be more
difcult. This in light of the greater proprietary nature of both
Google’s and Microsoft’s platforms.
Still, with the brand recognition and breadth of companies like
Amazon, Google and Microsoft, these other cloud computing
providers can often fall short of being deemed ‘platforms’.
This can be due to a lack of end-to-end integration (e.g.
application development, tools and application deployment),
8/2/2019 Rc001-Gwt Style Online Merged
http://slidepdf.com/reader/full/rc001-gwt-style-online-merged 9/12DZone, Inc. | www.dzone.com
3Getting Started with Cloud Computing
Assuming the data for a mailing list or report batch is already
stored on a cloud computing platform: A conservative estimate
of 1 day (24 hours) for processing and 5GB of outgoing
bandwidth, would equal approximately $3.00 in cost from each
of the previous cloud computing providers.
As you can surely attest, at this price point it’s only such cloud
computing providers that are able to offer dedicated resources
at such competitive rates, especially compared to leasing your
own hardware or using one of the many commercial hosting
providers.
Spot pricing on Amazon EC2Providing what can potentially be the most competitive rates
among cloud computing platforms, Amazon EC2 offers what it
calls ‘spot instances’.
A spot instance allows you to make a bid for unused Amazon
EC2 capacity and run applications for as long as your bid
exceeds the current spot price.
For web application tasks that are not time sensitive (e.g.
long-running scientic calculations or historical reports) this
approach can substantially reduce a web application’s runningcosts.
Since spot prices change based on supply and demand, this
allows you to obtain the most competitive rates at any given
time, without exceeding your maximum bid.
CLOUD COMPUTING PLATFORMS & DATA TIER
TECHNOLOGIES
Scaling a web application’s data tier entails a different
approach than scaling its business logic and web tier. This is
due to limitations and features pertaining to specic data tier
technologies.
Most web applications are underpinned by Relational Database
Management Systems (RDBMS) that use Structured Query
Language (SQL) as their access mechanism.
Though a series of c loud computing platforms now offer
RDBMS/SQL data tier support, many cloud computing
platforms grew to address data tier demands for which
RDBMS/SQL technology had limiting factors. Namely those
pertaining to data mining and the complexities involved
in providing fault-tolerant & high-availability RDBMS/SQL
solutions.
COSTS
Cloud computing platform costs are fairly competitive.
However, some metrics used by providers are sufciently
different from others to make holistic cost comparisons
difcult.
For example, stored data can have added costs related to the
number of Input/Output operations or transactions. Other
aspects, like CPU consumption, can also vary in the formthey are tallied by provider. The following table illustrates
comparable resources and their associated costs in each cloud
computing platform.
Resources Amazon EC2 (Smallinstance)
Google App Engine Microsoft Azure
Outgoing bandwidth(Gigabyte)
$0.10 (Over 150 TB)~$0.17(First 10 TB)
$0.12 $0.15
Incomingbandwidth (Gigabyte)
$0.10 $0.10 $0.10
CPU time (hours) $0.085 (Unix/Linux)~ 0.12(Windows)
$0.10 $0.12
Stored data(Gigabytes per
month)
$0.10(+ $0.10 per 1 million I/Orequests
$0.15 $0.15( +$0.01 for 10Ktransactions)
Recipients emailed(Recipients)
N/A $0.0001 N/A
Cost CalculatorsFor an accurate cost estimate pertaining to each cloud
computing platform, I recommend you use the following
calculators offered by each provider:
• Amazon EC2 -
http://calculator.s3.amazonaws.com/calc5.html
• Google App Engine -
http://code.google.com/appengine/docs/billing.html
(ONLY budgeting resources – No calculator)
• Microsoft Azure -
http://www.microsoft.com/windowsazure/tco/
Cost case scenarios: Mailing list or report processingTo give added cost context to the use of c loud computing
platforms in web applications, let’s take the case of common
one-time events in web applications.
Mailing list or end of month report processing can consume
substantial resources from a web application’s main
environment, in addition to being short-lived tasks.
Instead of leasing a stand-alone server for such tasks or
hampering the performance level of a web application’s
main environment, a cloud computing platform can be a cost
effective solution.
lack of scalable data tier technology options, to service level
agreements (e.g. uptime and indemnity) that can only be
offered by large corporations the size of Amazon, Google and
Microsoft.
Nevertheless, some of these other cloud computing providers
have carved out niche markets in the cloud computing market.
Some do so by adopting more aggressive pricing structures,
catering to the specic needs of certain communities(e.g. Ruby/Rails, or Linux), or providing better customer service
than their larger rivals.
Figure - Amazon EC2 spot pricing behavior
More information on Amazon EC2 Spot instances can be found
at: http://aws.amazon.com/ec2/spot-instances/
8/2/2019 Rc001-Gwt Style Online Merged
http://slidepdf.com/reader/full/rc001-gwt-style-online-merged 10/12DZone, Inc. | www.dzone.com
4Getting Started with Cloud Computing
Microsoft Azure Data TierMicrosoft’s cloud computing platform offers similar data tier
solutions to the previous cloud computing platforms, based on
Microsoft technology.
Windows Azure Storage Service
• Storage and retrieval based on .NET API: ADO.NET or
LINQ, as well as web services (e.g. REST).
• Schema-less; requiring no up-front data modeling tasks.
• Built on Microsoft infrastructure, including storage
replication.
Windows SQL Azure
• Out-of-the-box RDBMS/SQL capabilities built on
Microsoft SQL Server.
• Minimal operational management
(e.g. Disk usage, log les)
• Synchronization availability between various RDBMS
instances (a.k.a ‘Huron Data Sync’)
HotTip
NoSQL movement
The industry has blossomed healthy debates over
the suitability of RDBMS/SQL vs. alternate data
tier technologies for developing large scale web
applications. Now often cataloged as the NoSQL
movement http://en.wikipedia.org/wiki/nosql
Amazon EC2 Data TierAmazon’s cloud computing platform offers the largest array of
data tier technologies.
Amazon SimpleDB
SimpleDB technology has the following characteristics:
• Storage and retrieval based on Amazon API; available via
web service.
• Low administrative overhead compared to RDBMS (e.g.
No index maintenance and performance tuning required)
• Schema-less; requiring no up-front data modeling tasks.
• Provides the building block for querying Amazon S3 data.
Amazon Simple Storage Service (S3)
Whereas Amazon SimpleDB provides the foundations for
querying data in Amazon’s EC2 cloud computing platform,
Amazon’s Simple Storage Service (S3) is used for the actual
storage of data.
Simple Storage Service (S3) has the following characteristics:
• Storage of objects between 1 byte and 5 gigabytes.
• REST and SOAP interfaces, as well as authentication
mechanisms.
• Objects are assigned a unique ID, with meta-data
assignment done in Amazon SimpleDB for querying
purposes.
• Built on Amazon infrastructure.
Amazon Simple Queue Service
Provides data tier capabilities similar to those of message
orientated middleware ( http://en.wikipedia.org/wiki/Message-oriented_
middleware ) for web applications.
Amazon Simple Queue Service has the following
characteristics:
• Messages can contain up to 8 KB of text in any format.
• Messages can be sent and read simultaneously.
• Access is supported through standard SOAP web services.Amazon Elastic MapReduce
Provides data tier capabilities based on Google’s MapReduce
framework (http://en.wikipedia.org/wiki/MapReduce ) built on Amazon’s
EC2 cloud computing platform.
Amazon Elastic MapReduce has the following characteristics:
• Out-of-the-box MapReduce capabilities built on Apache’s
MapReduce implementation Hadoop.
• Depends on Amazon Simple Storage Service (S3).
• Support for third party MapReduce tools
(e.g. Karmasphere)
Figure - Google App Engine Data Tier Advantages
Amazon Relational Database Service
Provides data tier capabilities for deploying RDBMS/SQL web
applications.
Amazon Relational Database Service has the following
characteristics:
• Out-of-the-box RDBMS/SQL capabilities built on MySQL.
• Scale and compute capacity managed through Amazon
APIs.
• Automated backup and patch management.
Google App Engine Data TierGoogle’s cloud computing platform is built enti rely on Google’s
data tier technology stack.
Google’s App Engine data tier has the following characteristics:
• Storage and retrieval based on either Java – available via
Java Data Objects (JDO), Java Persistence API (JPA) or
low-level datastore API – as well as Python – available via
a data modeling API and a SQL-like query language called
GQL.
• Schema-less; requiring no up-front data modeling tasks.
• Built on Google infrastructure (i.e. BigTable, Google File
System).
8/2/2019 Rc001-Gwt Style Online Merged
http://slidepdf.com/reader/full/rc001-gwt-style-online-merged 11/12DZone, Inc. | www.dzone.com
5Getting Started with Cloud Computing
• Google App Engine Administrative console: Basic web
console for managing Google App Engine.
https://appengine.google.com/
• Google App Engine API: Google’s App Engine
development kit (SDK) includes an API to communicate
remotely with Google App Engine servers.
Python - http://code.google.com/appengine/docs/python/tools/
Java - http://code.google.com/appengine/docs/java/tools/ )
Microsoft Azure
Microsoft’s Azure computing platform can be managed
through the following means:
• Microsoft Azure Administrative console: Basic web
console for managing Windows Azure instances.
https://windows.azure.com/Cloud/Provisioning/Default.aspx
• Windows Azure API: Windows Azure development kit
(SDK) includes an API to communicate remotely with
Windows Azure servers.
http://msdn.microsoft.com/en-us/library/dd179367.aspx
• Windows Azure Management Tool: Provides a desktop
(i.e. fat-client) to communicate remotely with Windows
Azure servers. http://code.msdn.microsoft.com/windowsazuremmc
CLOUD COMPUTING PLATFORM SECURITY
Generally speaking, security for web applications running
on cloud computing platforms is no different than security
pertaining to any web application accesible to the public at
large.
Issues such as code injection ( http://en.wikipedia.org/wiki/Code_injection )
or cross-site scripting ( http://en.wikipedia.org/wiki/Cross_site_scripting ) can
just as easily present themselves in web applications running oncloud computing platforms, given they are issues entirely under
the control of an application’s designer.
As a user of a cloud computing platform, your security
concerns should span to contemplate the security
vulnerabilities and security limitations inherent to a provider’s
services, in addition to those of web applications in general.
The following sections enumerate key security characteristics
to take into account when choosing a cloud computing
platform.
Amazon EC2 security characteristics
• Full access to host operating system instance. Vulnerability and ‘hardening’ policies are the responsibili ty
of a user, as with any other public operating system.
• Amazon Security groups to facilitate and limit access to
instances by port, protocol and or incoming IP.
• Optional multi-factor authentication, to limit access
through a six-digit, single-use code from an authentication
device in your physical possession ( http://aws.amazon.com/mfa/ )
Google App Engine security characteristics
• Access to underlying host provided entirely through a
Google account. Limiting a user ’s security accountability
(e.g. no operating system to ‘harden’)
CLOUD COMPUTING PLATFORM MANAGEMENT
For all the benets of cloud computing platforms, the term
‘cloud’ often comes with the connotation of loosing control
over one’s web applications and being at the mercy of a serv ice
provider.
While it’s true that some cloud computing platforms have
certain proprietary elements that can lock-in your applications
to their service offerings, cloud computing management and
security concerns are often unfounded.
Cloud computing platform managementManagement of cloud computing platforms – which is to say
provisioning or modifying (e.g. starting, stopping or deleting)
an underlying environment – is achieved by either a provider’s
administrative web console, through APIs or other third party
tools.
Administrative web consoles provide practical access to
standard cloud computing tasks. APIs on the other hand
allow the execution of more sophisticated cloud managementchores, such as the integration of tasks into custom
applications or automation of tasks altogether. Third party
tools can range from browser plug-ins to open source libraries.
Amazon EC2 management
Amazon’s cloud computing platform can be managed through
the following means:
• Amazon EC2 Administrative console: Basic web console
for managing EC2 instances, Elastic Block Store volumes
and modifying conguration settings (e.g. I.P addresses).
http://aws.amazon.com/console/
• Amazon CloudWatch: Advanced web console – billed
separately – for determining resource utilization,
operational performance, and demand metrics (e.g. CPU
utilization, disk reads and writes, and network trafc).
http://aws.amazon.com/cloudwatch/
• Amazon EC2 API: Web services API for inspecting and
modifying EC2 instances from remote/custom
applications.
http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/
• Libcloud API: Python API for inspecting and modifying
EC2 instances from remote/custom applications.
http://incubator.apache.org/libcloud/
• Elasticfox & S3Fox browser plug-ins: Firefox plug-ins formanaging EC2 instances & EC3 data.
Elasticfox - http://developer.amazonwebservices.com/connect/entry.
jspa?externalID=609
S3Fox - http://developer.amazonwebservices.com/connect/entry.
jspa?externa lID=771
• Lifeguard: provides an automatic, Spring based monitoring
solution to dynamically scale EC2 resources based on load.
http://code.google.com/p/lifeguard/issues/list
Google App Engine
Google’s App Engine computing platform can be managed
through the following means:
8/2/2019 Rc001-Gwt Style Online Merged
http://slidepdf.com/reader/full/rc001-gwt-style-online-merged 12/12