google web toolkit web conference presenation

107
Google Web Toolkit http://code.google.com/webtoolkit/

Upload: stephen-erdman

Post on 03-Dec-2014

159 views

Category:

Technology


0 download

DESCRIPTION

The slides from my presentation on my 3 hour Google Web Toolkit presentation from the Wharton Web Conference in 2012.

TRANSCRIPT

  • 1. Google Web Toolkit http://code.google.com/webtoolkit/

2. What do we all want? The Simpsons show us the way. 3. The wonder of abstraction Machine code -> assembly -> modern programming languages Music example 4. What gets done for us? Code handling UI implementation details AJAX communication 5. How does it get done? Java Code In Magic ElvesI mean Compiler HTML + Javascript out 6. Code Handling 7. Code Handling Compiler is upgradeable and customizable Deployed app detects browser and locale and serves appropriate code Speed Incorporating other JavaScript libraries 8. Compiler There are periodic updates to GWT that generally add on features, but can also alter underlying implementation details You can customize the compiler yourself, but thats far outside the scope of this talk 9. Browser and Locale detection Compiles separate files for browser/locale combination Detects combos on initial communication and serves up only appropriate file Works for all major browsers and iOS and Android agents Allows user configuration 10. Overriding detection and serving XML in module file Example from TextBox.gwt.xml 11. If the web page drops below 50 mph, it will explode!!! 12. Speed Code pruning Compression and inlining Caching (*cache.js files) Reduces number of js files Bundling (Advanced topic) 13. Other JavaScript libraries JavaScript Native Interface (JSNI) Wrappers Extensions Google APIs 14. JSNI: Create the call Create the wrapper methods: Wrap JavaScript in Java native methods Access window with $wnd, document with $doc Example: public static native void hide(String selector) /*-{ $wnd.jQuery(selector).hide(); }-*/; 15. JSNI: Use the call Just make a normal Java call to the method Example: hide("#" + element.getId()); 16. Wrappers Deeper integration than JSNI Adds Java -> wrapped JS compilation instructions jQuery wrapper: jQuery4GWT (http://code.google.com/p/jquery4gwt/) 17. Extensions Near full replacement of standard GWT 3 options for full extensions o Ext GWT (http://www.sencha.com/products/extgwt/) o GWT-Ext (http://gwt-ext.com/) o SmartGWT (http://www.smartclient.com/product/sgwtOverview.jsp) gwtQuery (http://code.google.com/p/gwtquery/) 18. Google APIs Tightly integrated wrappers to Google libraries (http://code.google.com/p/gwt-google-apis/) Gears Gadgets AJAX search Maps Chart Tools (Visualization) Language AJAX loader Many more 19. UI Implementation Details 20. UI Implementation Details Widgets CSS Styles Events Animations Back/Forward handling 21. Widgets Work like blue prints set up spaces and the things to put into those spaces, magic elves actually construct it Types of widgets: Panels Static Components Form Components Complex Componets 22. Panels Act like the rooms in the blue print set up the spaces and how they relate to each other Types of panels: Simple Layout Complex Layout Containers FormPanel Popups 23. Layout Panels Do the main work of setting up how every thing is laid out Exist in quirks and standards mode o Standards requires HTML files to start with o Quirks class Panel, Standards LayoutPanel Often nested to get full layout Widgets are generally added with examplePanel.add(aWidget); 24. Simple Layouts RootPanel FlowPanel HorizontalPanel and VerticalPanel SplitPanels (Horizontal and Vertical) DockPanel DeckPanel HTMLPanel Tables (Grid and FlexTable) 25. RootPanel This is a special panel is used to load your layouts into the HTML page. It can be used either to insert at the document root or inside a div tag. To use it, you just call the static get method on the RootPanel class, like this: RootPanel docRootPanel = RootPanel.get(); or RootPanel divPanel = RootPanel(div-id); 26. Flow Panel Lays out the widgets to it linearly (by default from left to right) until it reaches the end of line and then wraps around to the next line 27. Horizontal and Vertical Panels Lays out the widgets added to it linearly, either horizontally or vertically, without wrapping 28. Split Panels A panel that is split into two sections with a moveable divider between them. It can be either a HorizontalSplitPanel or VerticalSplitPanel. Widgets are added with setTopWidget(aWidget), setBottomWidget(aWidget), setLeftWidget(aWidget), or setRightWidget(aWidget) 29. DockPanel Splits its area into 5 sections: North, South, East, West, and Center Widgets are added with exampleDockPanel.add(aWidget, DockPanel.NORTH); with the appropriate section name If no widget is added to a section, the other sections take over its area 30. DeckPanel Deck as in a deck of cards Can have any number of widgets added to it, but only shows one at a time TabPanel is a specialize case of this panel Visible widget is set using exampleDeckPanel.showWidget(index); where index is the order (starting at 0) that the widget was added Widgets can be inserted at specific index with exampleDeckPanel.insert(aWidget, insertIndex); 31. HTMLPanel Used to mix HTML with widgets Youre generally not going to be using this 32. Table Panels: Grid and FlexTable Uses the html table tag to lay out widgets in rows and columns ultimately cells Grid has fixed number of rows and columns (set on creation) and no spanning FlexTable can add and remove rows and columns and can span A cells contents can be a Widget, HTML, or Text and is set by the set(row, column, ); method 33. Complex Layout Panels StackPanel TabPanel Really, theyre not that complex 34. StackPanel Often known as an accordian Lays out widgets in vertical sections, with one section showing at a time by default 35. TabPanel I think we all pretty much know what a Tab Panel is, right? 36. Container Panels These are panels that contain widgets so as to add some behavior to them Types: Composite and Simple ScrollPanel DisclosurePanel 37. Composite and Simple Panels These are used to create your own reusable widgets. This is an advanced topic that well cover later. 38. ScrollPanel Adds scrollbars to the widget it contains to allow scrolling 39. DisclosurePanel Allows quick hiding/showing of the widget it contains 40. FormPanel Sort of what you would expect in that it encapsulates an HTML form, but there are a few automatic enhancements It submits the form and handles the return using AJAX It uses a FormHandler (well get to handlers) to run code right before the form is submitted to the server, including cancelling submission. This is great for form validation. The FormHandler also runs code when the server responds to the form submission 41. Popups: PopupPanel and DialogBox Pops up a panel DialogBox differs from PopupPanel in that it has a draggable caption bar PopupPanels are used for things like tooltips, drop down lists, pull down menus, etc. DialogBoxes are used fordialogs 42. Static Widgets These are like your signs and artwork that are going to be put up in the house youre building. They include what you would expect: o Labels for displaying simple text o HTML o Images 43. Hyperlinks Hyperlinks are generally also considered static widgets, although theyre more like really fast elevators than pieces of information like the others These are not like HTML hyperlinks. They link to things within the GWT application, not to external resources that will cause a page reload o Youd use an HTML widget with an HTML hyperlink in it or an Anchor component to do this, but it will cause the GWT application to be unloaded They work by pushing a new token onto the History stack (more on that later) 44. Form Widgets These are all the widgets which take user input, whether they are used in a form or not It includes all the usual suspects: textboxes, checkboxes, radio buttons, etc. It also has some new kids that achieve common tasks 45. RichTextEditor You can add and customize a rich text editor directly, instead of importing a JS library 46. SuggestBox A TextBox that responds to user input by matching against a list and suggesting matching values This is achieved by associating an instance of the SuggestOracle with it well cover this later when we look at coding Suggestions from a defined list of strings have a default MultiWordSuggestOracle that takes a an array of strings Almost all other cases will involve submitting the term to a search service and displaying the results 47. FileUpload Encapsulates an html input with file type to allow people to choose a file from their file system to upload 48. Complex Widgets Trees Menus Cell Widgets 49. Tree For simple display and interaction with hierarchical data Nodes are represented by TreeItem objects You can add text, a widget, or a TreeItem to the tree with the addItem method Calling addItem on the tree will add to the hidden root node, calling it on a TreeItem will place the added item under that TreeItem 50. MenuBar For hierarchically arranged menus Works the same as a Tree, but with MenuItems instead of TreeItems 51. Cell Widgets For complex structured rendering/editing, GWT provides widgets that center around using cells Types of cell widgets: CellTable CellTree CellBrowser 52. Cells Used to display a unit of data Predefined types: Text Number Date Button Image 53. Text Cells TextCell just displays text ClickableTextCell can be clicked on TextInputCell basically a TextBox cell EditTextCell click to edit 54. Number Cell Renders a number based on the passed in NumberFormat object 55. Date Cells DateCell displays a date based on the passed in DateFormat object DatePickerCell DateCell with a popup calendar editor for choosing date 56. Button Cells ButtonCell a cell with a button in it ActionCell a button cell that takes a delegate to perform the action CheckBoxCell a cell with a checkbox in it SelectionCell a cell with a drop down menu 57. Image Cells ImageCell renders an image based on URL ImageResourceCell renders a defined ImageResouce dont worry about what this is right now ImageLoadingCell initially displays a loading indicator until the image is loaded 58. Other Cells A CompositeCell is a container for child cells that are laid out vertically by default An IconCellDecorator adds an icon to another Cell 59. Styling UI Widgets GWT itself doesnt style widgets, instead it relies on CSS styles Widgets are created with default css classes Styles can be set, added, or removed at any point with setStyleName, addStyleName, and removeStyleName, respectively 60. Themes GWT ships with defined themes that use the default widget styles to present a unified look and feel to an application Other open source themes are available Themes can be custom built 61. Animations It is possible to hand code the animations you want, but I recommend using one of the available wrappers for effects libraries. My suggestion would be gwt-fx (http://code.google.com/p/gwt-fx/) In gwt-fx, you create an effect object that takes the DOM element of a widget (retrieved with the getElement method) and then call theEffect.play(); 62. Handling the back button The browser navigation buttons are difficulties when using AJAX applications. The default behavior is to unload the application and load the previous page in the browser history. GWT deals with this by using anchors for internal browsing and the History class to add and remove application states that dont come from Hyperlink navigation 63. History Stack Primary way to navigate the application Tokens get pushed onto the History stack o Automatically with Hyperlink click o Explicitly with a call to History.newItem(tokenString); Handled by ValueChangeHandler Code: History.addValueChangeHandler(new ValueChangeHandler() { public void onValueChange(ValueChangeEvent event) { String historyToken = event.getValue(); set up the state change } }); 64. GWT Widgets Examples GWT Showcase (http://gwt.google.com/samples/Showcase/Showcase.ht ml) Example Mail app (http://gwt.google.com/samples/Mail/Mail.html) 65. AJAX Communication 66. HTTP Module GWT ships with the HTTP Module, which provides a simple way to communicate with asynchronous HTTP requests and responses To use it, you need to include in your module file (will be explained later) 67. RequestBuilder Has direct support for GET and POST requests Syntax to create: RequestBuilder(RequestBuilder., url); to send: senderRequest(queryString, RequestCallBack); 68. RequestCallback Two methods: onError(Request request, Throwable exception) And onResponseReceived(Request request, Response response) 69. PUT and DELETE calls RequestBuilder methods are only GET and POST but if can get PUT and DELETE using the X-HTTP-Method-Override header Example: RequestBuilder builder = RequestBuilder(RequestBuilder.POST, url); builder.setHeader(X-HTTP-Method-Override, PUT); builder.sendRequest(queryString, requestCallback); 70. Reading and Writing XML Reading you use an XMLParser.parse(xmlString); method call to return a Document object that exposes the DOM. There are also XPath modules available, such as jaxen4gwt (http://code.google.com/p/jaxen4gwt/) Writing you can either programmatically create a Document object and add Elements to it or just write out an XML String 71. Reading and Writing JSON The JSON module needs to be explicitly included in your module file with the line: You use JSONParser.parse(jsonString); method call, which returns a JSONObject 72. SmartGWT Much better than StupidGWT 73. Whats so smart about it DataSources o Data Binding! Better Widgets o They help with Data Binding! 74. DataSources These are the central concept of SmartGWT, pretty much everything flows from them Encapsulates three aspects of data o Domain model enhanced with things like validation, etc. o Default UI field aspects like editors, formatting, etc. o Communication with server and/or data source If youre running a Java server, there are options, especially if you choose to go with one of the pay versions, but were going to focusing on the RestDataSource. 75. Enhanced Domain Model Very similar to setting up ORM entity Add typed fields with addField(dataSourceField); method calls On the DataSourceFields: o Set up validation with Validator objects o Set up relationship to another DataSource o Add a list of allowed values or allowed key -> value map 76. UI Details Set up default id, hidden, name, and details fields for automating display of data On fields: o Set up title label to display o Set up editor to use to edit the field o Set up hierarchical relationship with parent or children fields 77. Data Binding DataSources allow automatic data binding with ui compents Can either explicitly set field to component or with some (DynamicForm is most often used), just setDatasource() on the widget and SmartGWT will do the rest + 78. Communicating with the Server and/or Data Store DataSources by default have the four CRUD operators set up as Add, Update, Fetch, and Delete Custom operations can be set up as well RestDataSource is set up to easily work with either XML or JSON in a specific format Other formats are possible through overriding the transformRequest and transformResponse methods Client-only DataSources are very good for prototyping, testing, and local development 79. Expected XML Format 0076546valuevaluevaluevalue ... 75 total records ... 80. Expected JSON Format { response: { status:0, startRow:0, endRow:76, totalRows:546, data:[ {field1:"value", field2:"value"}, {field1:"value", field2:"value"}, ... 75 total records ... ] } } 81. Extracting embedded values There may be times when the DataSource will not directly match the structure of the returned XML or JSON. In that case, there are a couple of ways of using methods on the fields to extract the data. Use setXPath(xPathSelectorString); to specify the data For more complicated or computed situations use a FieldValueExtractor object 82. Better Widgets ListGrid TreeListGrid DynamicForm DetailViewer Calendar Widgets Also, built in cool effects 83. ListGrid and TreeGrid Primarily used with DataSource Can have data loaded into it with Record objects Tree must have hierarchical DataSource (have field that has a foreign key reference to itself) and have the root set Highly recommend setting setLoadDataOnDemand(false); and setAutoFetchData(true); Can control displayed fields either directly by adding ListGridField or TreeGridField, all from DataSource by setUseAllDataSourceFields(true);, or using showXXXFields(true); 84. DynamicForm and DetailViewer CRUD form and display view Usually have DataSource set on them, but can be populated explicitly from Record object Same deal as Grids, can add fields directly, use all of them, or showXXXFields(true); 85. Calendar Widgets A lot of effort was put into these, really need to look at showcase 86. SmartGWT Widget Showcase Can be seen here: http://www.smartclient.com/smartgwt/showcase/ 87. Structure of GWT application project Main division between code and compiled html and JavaScript Code is under src and then the top level package Deployable application of compiled html and JavaScript under war 88. Code Under src/ there are three main important areas o Client folder o Server folder o Module file 89. Client folder/package This contains all the code that is going to be compiled into the interface and supporting classes Basically, this is everything that the client is going to see Other folders can be set to be compiled like the client folder in the module file 90. Server folder/package If you are running Java code on the server and/or setting up resources that they are going to be pulling from the server, this is where it would be put What is put in here shows up in the war deployable application without any compilation or translation Were not going to be using this much, but its very important in other types of applications Server is just to be helpful. Any folder that is not client and not set to be compiled in the module file will behave the same 91. Module File This is the primary file that sets up the GWT application Usually will be called .gwt.xml Sections o Inherits Core Web Toolkit - Theme Module Additional add-ons for using SmartGWT, you would put in o Stylesheets - o Entry Point - o Source paths optional, for when you want to compile other folders like the client on 92. Entry Point One class in the client folder (or a subfolder) must be designated as the Entry Point in the module file Needs to implement the EntryPoint interface o this means it needs to have a onModuleLoad() method which is the initial method that will get called when the module loads. This is where you will do the main setup for the application. 93. Deployable application By default, is put under the war folder Theres a JavaScript folder in here and a web-inf for server settings, but dont worry about them Main important file is the .html file. This needs to call the GWT application JavaScript file and set up any divs that you are going to load into Also has code to allow back handling just leave this alone Can reference any css files you want 94. Actually doing stuff Regrettably, you are going to sometimes have to do some things 95. Tools were going to use Some version of Eclipse. I recommend the SpringToolSuite from SpringSource (http://www.springsource.com/developer/sts). The Google Plugin for Eclipse (http://code.google.com/eclipse/) WindowBuilder Pro (http://code.google.com/javadevtools/download- wbpro.html) SmartGWT (http://www.smartclient.com/product/sgwtOverview.jsp) A web browser (I recommend FireFox with Firebug installed) 96. Create a project Go through File -> New menu or better yet, click on the blue g button Fill in project name and top level package o Top level package can be anything you want, but convention is for it to start with your website backwards and then the project name, so a UPenn one would be edu.upenn. Use Google Web Toolkit should be checked Use Google App Engine should not, unless you are planning on deploying there Yes, you want the sample code included 97. Run/debug with IDE GWT plugin has hosted browser set up and the code will be run as Java Right click on project -> select Run as or Debug as -> Web Application Will start and bring up Development Mode if there are no problems. Double click on URL. To load changes, compile project by clicking on red button next to blue g button When done, click on red square in development mode tab 98. Deploying Copy contents of war folder to web server root + where ever you to call it from 99. GWT Designer To use, right click on the file you want to edit and choose Open With -> GWT Designer If youre working with SmartGWT, it needs to be set up once by right clicking on a file or folder in the src area and choosing Google Web Toolkit -> Configure for using SmartGWT o You will have to then point it to your SmartGWT installation directory so it can find the jar files 100. Things to know about Java 101. Generics Youll see warnings for this, but you can ignore them if you want For type safety, compiler hints are given for classes that work from templates or generic utilities, like Collections 102. Collections Java arrays are set up how you would think, but they are not extensible (cant grow or shrink) and there arent associative arrays You use Collections instead o ArrayList = extensible array o HashMap = associative array 103. Using objects in handlers If an object is defined outside a handler and you want to use it inside, you must declare it final o This does mean that you cant change the value once it has been set Example: final String finalizedString = Hi; String nonFinalizedString = Hello; Button.addClickListener(new ClickListener(){ public void onClick(Widget sender){ String message = finalizedString; //this is fine String message = nonFinalizedString; //this wont work }); 104. Checking for equality For objects, the = operator checks if they are the same object (i.e. exist in the same spot in memory) To check if the values are equal, you have to use the .equals(); method This is most important to remember with Strings Example: String strOne = Hi; String strTwo = Hi; strOne = strTwo; //this will be false strOne.equals(strTwo); // this will be true 105. Follow up reading Google Web Toolkit project on Google code: http://code.google.com/webtoolkit/ Book: Google Web Toolkit Applications: SmartGWT forums: http://forums.smartclient.com/forumdisplay.php?f=14 106. Thanks so much Stephen Erdman Email: [email protected]