ptg 292 Chapter 12 Client-Side Programming with the Dojo Toolkit Figure 12.13 Database schema tree listing The second process started when a data source is selected fetches the database schema. The schema service returns a ItemFileReadStore-formatted JSON data, which contains a hierar- chical structure that is perfect for representing in a tree widget. The process flow should be pre- dictable at this point. We define a new DataStore, fetch the data, and when received, the createSchemaTree function is called to generate the Tree widget. This function checks to see if there is already a tree defined from a previous data source and, if so, destroys it. Then it creates a new Tree instance, passing in the backing DataStore, and setting up a handler for when a leaf node on the tree is clicked. Back in the load schema function, the accordion container is advanced to show the schema tree to the user, as seen in Figure 12.13, as well as updating the contents of the SQL editor area with an informative message. Notice the use of the onError function to report any errors that occur during this process. One common mistake would be to place a try/catch around the entire fetch function. This typi- cally does not do what you would think, as the fetch is asynchronous and effectively returns Figure 12.12 Database driver details Download from www.wowebook.com ptg Tab le S elec tio n and R un ning SQL 293 Figure 12.14 Tabl e colu mns a nd va l ue s immediately. Any errors that occur happened within the context of the Deferred and therefore must be handled in the error path. Always use the appropriate error path (also known as the errback path) when dealing with Deferreds. Otherwise, errors can occur that will otherwise go unreported, even if there are try/catch blocks surrounding the asynchronous function calls. Table Select ion and Running SQL The rest of the application flows are essentially variations of what we have described already. When the user clicks on an entry in the schema tree, the dba.tableSelected function is called. This function creates another DataStore containing the table columns and types, which are then shown in a DataGrid widget, as seen in Figure 12.14. These table details are also used to define a sample SQL query statement that is then placed into the editor. The SQL editor allows freeform queries or update statements. When the user clicks the Execute SQL button, the dba.executeSql function is called. This function uses a regular expression to strip embedded HTML tags from the editor’s value, and then makes an xhrPost call to send the query to the host for processing. The results of the query are then passed on to the dba.processSqlResults function. This function destroys any existing results grid, defines a DataStore based on the results, builds up a new layout, and creates a new results grid. Some update SQL statements return only a message indicating the number of rows updated, or even an error message may be returned. This functions handles and displays them appropriately as well. Download from www.wowebook.com ptg 294 Chapter 12 Client-Side Programming with the Dojo Toolkit Figure 12.15 Final application Final Product We have covered the entire DBA application flow. It took us only a few days to write and debug, and with WebSphere sMash, the deployment was quick and painless. You presented the applica- tion as seen in Figure 12.15, and the business couldn’t be happier with the results. Your boss, basking in the glory that is your success, has offered to take you out to lunch and let you have Fri- day off! WebSphere sMash and the Dojo Toolkit have turned you into a good-looking, geek super-hero. Enjoy your long weekend. This DBA application was originally written as a WebSphere sMash proof of concept a while ago and has real-world value to examine and easily access your databases. Although the number of lines of code is a poor metric for any project, this application comes in at under 750 lines of client-side code (HTML, CSS, and JavaScript) and under 500 lines of code on the server. Even so, it provides an incredibly rich and useful user experience. Please, keep this application user protected and behind a firewall. Otherwise, all sorts of bad things could happen to your data. Remember that disgruntled DBAs eventually become evil clowns, which means that they know how to use computers and have a deep-rooted hatred of relational data. Consider yourself warned. Creating Custom Dojo Builds for Performance This section is somewhat advanced, but if you are deploying a WebSphere sMash application into a production environment, or simply want your application to load quickly, it is strongly Download from www.wowebook.com ptg Using Non-Supplied Versions of Dojo 295 recommended that you create a custom build of Dojo specific to your application. You can bundle this custom build as part of your WebSphere sMash application. You ma y b e as ki ng i f a cu sto m D ojo bui ld i s n ec ess ar y. In a s ing le wor d—y es . A c us tom Dojo build can actually reduce noncached page loading time by 70% or more. A typical complex web application can go from a 30–40 second load time, down to under 5 seconds just by employ- ing a custom Dojo build. It’s hard to argue with that. The reason for this radical load difference is tied directly to Dojo’s module loading scheme. In the Dojo world, you load only what you are going to use. But this comes at the cost of having to discreetly load dozens, if not hundreds, of classes. CSS and HTML template files are also modularized in the same fashion. When you create a custom build, you tell Dojo which modules your application uses, and the build process bundles them all into a single custom dojo.js file. HTML templates are inlined into their class files, and CSS imports are merged together. Comments and console statements are removed, and the result- ing JavaScript file is safely shrunken down to minimize code size. We do not attempt to go into the minutia of the Dojo build process itself. That is all well documented on the Dojo site, and in the Dojo books. The version of Dojo that comes bundled with WebSphere sMash does not include the build tools required to create a custom Dojo build. This is due to licensing issues with the Rhino JavaScript interpreter. To get around this, you need to download and create a local Dojo project to replace, or overlay, the standard WebSphere sMash Dojo dependency. The steps to perform this are shown in the next section. Using Non-Supplied Versions of Dojo There are times when the versions of Dojo supplied in the WebSphere sMash repositories are insuf- ficient for your needs. It may be that you want to perform a custom build as described previously, or the latest and greatest version of Dojo has a killer new dijit that you must have in your next applica- tion. It’s easy to add in a new version of Dojo into your project. Just as the Dojo dependencies that come with WebSphere sMash are external to your actual project, your custom Dojo additions should also be established within their own project. Then you just add the new Dojo project as a depend- ency to your main application. Source versions of Dojo enable you to explore the code and read the internal comments, which is a great way to learn the internal workings of various Dojo components. Follow these steps to set up a Dojo source project: 1. Download a Source version of Dojo. a. Go to www.dojotoolkit.org. b. Locate the main Download link, select “All Download”, and click on the latest version (or any version you want); then locate and download the source distribution. As an example, at the time of this writing, the latest released version of Dojo is 1.4.3, so down- load the file http://download.dojotoolkit.org/release-1.4.3/dojo-release-1.4.3-src.zip. Download from www.wowebook.com ptg 296 Chapter 12 Client-Side Programming with the Dojo Toolkit Figure 12.16 Resulting Dojo source tree under /public 2. Create a new WebSphere sMash Project to hold the Dojo source. a. Call this new project something like Dojo.Source.143 (match the suffix to the version you downloaded). b. Edit the ivy.xml file and set the organization to dojo, and set the version to match the Dojo version you downloaded. 3. Go to a command prompt and extract the dojo zip into the /public directory. a. The zip extracts with an extra directory level, so you need to move some things around. Move the directories under dojo-release-1.4.3-src up one level, and then remove the base extraction directory. You should end up with four directories under /public containing: dojo, dojox, dijit, and utils, as shown in Figure 12.16. You n ow h av e a n ew D ojo p roj ec t th at y ou c an a dd t o any p ro jec t as a d ir ect d ep end en cy. I t is common to have several different versions of Dojo in your workspace using this naming con- vention. It makes it easy to swap versions just by changing your project’s dependency. An important note to discuss here for development environments: WebSphere sMash per- mits any peer projects to the main application to be dependencies. Unfortunately, the current ver- sion of AppBuilder does not recognize local projects as available modules in the dependencies tab. Therefore, to add a local project dependency, you need to edit the ivy.xml file and manually enter the dependency information. But, after you make this change, your project is flagged as not runnable. You then need to select the dependent project(s), and package them. At this point, your application is then ready to run. The WebSphere sMash plugin for Eclipse does not suffer this limitation; you can just add the local project dependencies using the module selector, and every- thing resolves properly. Debugging and Best Practices in Dojo Development If there is one thing that all JavaScript developers can agree on, it’s that debugging can be a source of major frustration. Things break, and it can be hair-pulling difficult to determine where the problem lies. By using a quality debugger, and heavy console logging, you can greatly Download from www.wowebook.com ptg Code Validation with JSLint 297 enhance your ability to resolve problems in JavaScript code. The situation has gotten a lot better in the past few years, with the adoption of better browsers, great debuggers, and tools to validate your code. We will go ahead and state that Internet Explorer, especially version 6, which is still in heavy use around the world, is pure evil. If you don’t agree, fine, but most JavaScript developers are nodding their heads reading this. Do all of your primary development and debugging in Fire- fox and Firebug, and once things are working, test it out in IE and other browsers. Although most of the content in this section has nothing to do with WebSphere sMash, or even Dojo, it’s being including because it’s critical to know these nuggets of knowledge to be able to create solid JavaScript-based applications. Debugging and Logging with Firebug In the early days, the browser would simply state There is an Error on This Page. Developers would then typically insert dozens of I Am Here alert statements and narrow things down until eventually they located the source bug in their JavaScript. These were dark days indeed. Eventu- ally, the Mozilla Venkman debugger became available. And when you spent the time to learn how to make it work, and then relearned it every few months, as you forgot, and needed to use it again, you could step through and properly debug your JavaScript. It was quicker and more definitive than alerts, but not by any great shakes. But, it was the only thing available, so you went for it. This could be compared to the cusp of the industrial revolution for JavaScript developers. Then, in early 2007, Joe Hewitt released the Firebug debugger (http://getfirebug.com), and the JavaScript world was changed forever. Finally, there was a fast, intuitive, cool-as-all-get-out tool to debug your applications. Not only can it debug your code with the expected step in, step over, breakpoints, and the like, it also provides an easy way to profile performance, monitor net- work activity, examine the DOM, identify CSS elements, and provide console output. Read the documentation provided on the website, and soon you will be a master at JavaScript debugging. It should also be noted that Chromium and other WebKit-based browsers also have good debuggers available. Now, if we could only get a good debugger for Internet Explorer. Code Validation with JSLint JSLint (http://jslint.com), written by Douglas Crawford, should be at the top of your JavaScript development bookmarks.You should make it a habit to run your code through JSLint anytime you make significant changes. As the site says, it will hurt your feelings, but it will also make you a much better JavaScript programmer. Spend the time to read through the documentation and under- stand why it flags things as errors. When you have corrected all the reported errors, look through the rest of the report and verify that things look right. For instance, we know that we want to mini- mize global variables, so make sure that the reported globals are valid and not due to missing var qualifiers in your function variables, which is a common omission. JSLint also does a fairly good job at validating HTML and JSON data. JSLint may be that friend that says, “Yes, you do look fat in that dress,” but, soon enough, it will be one of your closest and most trusted friends as well. Download from www.wowebook.com ptg 298 Chapter 12 Client-Side Programming with the Dojo Toolkit Data Validation with JSONLint Along the same lines as JSLint, JSONLint (www.jsonlint.com) checks JSON data for validity. JSON is a data format widely used in Web 2.0 applications. But, just as bad JavaScript code can cause problems, so can malformed JSON data. A quick check of JSON data can verify your data, and notify you of improper quoting, trailing commas on nested lists, or any other common data issues. This site not only validates your JSON data, but also goes a step further and formats it nicely. This is especially handy if you have received a system-generated block of JSON that is compressed into a single line. This is great for minimizing bandwidth and computer parsing, but terrible for viewing by humans. This site instantly provides you with the results intended to show the data structures. Dojo References As we said before, Dojo is a highly capable toolkit for developing amazing applications. How- ever, all the functionality comes at the price of a fairly steep learning curve. There are several good books available that can help you learn to become a Dojo master. Although we can’t vouch for all of them, we can say that Mastering Dojo by Gill, Riecke, and Russel (Pragmatic Program- mers, ISBN: 978-1-934356-11-1) and Dojo, The Definitive Guide by Matthew Russell (O’Reilly, ISBN: 978-0-596-51648-2) both should sit right next to this book and within easy reach on your bookshelf. There are also several websites that you should bookmark, as they are invaluable when working with JavaScript and Dojo. Here are some of our top Dojo development links: • Dojo Toolkit Home (http://dojotoolkit.org) • Dojo API (http://api.dojotoolkit.org/) • Dojo API Cheatsheet (http://download.dojotoolkit.org/release-1.3.2/cheat.html) • Dojo Campus (http://dojocampus.org) • Dojo Campus Docs (http://docs.dojocampus.org) • Dojo API from Uxebu (http://dojodocs.uxebu.com/) Here are some of our top JavaScript development links: • JSLint (http://jslint.com/) • Firebug (http://getfirebug.com) • W3 Schools—JavaScript (http://www.w3schools.com/js/default.asp) • Mozilla Development Center—Core JavaScript Reference (https://developer.mozilla. org/en/Core_JavaScript_1.5_Reference) Download from www.wowebook.com ptg Conclusion 299 • Mozilla Development Center—Core JavaScript Guide (https://developer.mozilla.org/ en/Core_JavaScript_1.5_Guide) • JSONLint (http://jsonlint.com/) Conclusion We have covered a great deal in this chapter, and hopefully have exposed a whole new world of possibilities for client-side application development within WebSphere sMash using the Dojo Toolkit. By leveraging the power of the Dojo Toolkit on the client browser, you can easily con- sume your enterprises data in a RESTful manner. Dojo and WebSphere sMash can put a nice face on your SOA infrastructure. There are many quality JavaScript toolkits out there. IBM and WebSphere sMash have chosen to endorse the Dojo Foundation based on the quality, extensive capabilities, forward- looking APIs, and enterprise features. The time spent learning Dojo will pay off for you, as a developer, as well as for your company. Remember, for most users, the website is the company. Make sure you provide your customers with an engaging, feature-rich, state-of-the-art, and responsive experience. You will be a hero, and your customers will remain loyal. Download from www.wowebook.com ptg This page intentionally left blank Download from www.wowebook.com ptg 301 Why Develop in PHP Using sMash? WebSphere sMash’s PHP implementation was developed using Java SE. This means that you get the best of several environments for application development. You have the ease of use tradition- ally associated with the PHP core libraries and a wealth of available PHP extensions, but you also get the power of Java and its libraries, plus the WebSphere sMash APIs for HTTP access, REST, event, and database access. That’s a lot of power at your fingertips. WebSphere sMash provides a key benefit over normal PHP development in other environ- ments. PHP has a large following because of its ease of use and short time-to-market; however, it has not been good at providing integration with enterprise resource access programs written in other languages. By utilizing the PHP to Java Bridge provided by WebSphere sMash, you can easily extend the reach of PHP to access Message Queuing (MQ) systems, Java Messaging Sys- tems (JMS), and Web Services. This chapter exposes the various ways to use PHP and still seam- lessly work with Java and Groovy resources. These resources can be native code embedded within the application, or more commonly, JAR files or other dependent projects that your PHP application consumes. Adding PHP to Your Application To use PHP in your application, you must add the zero.php module as a dependency. After you create an application, select the Dependencies tab and then click Add. Type in zero:zero.php into the input box, and the filter should show you the desired dependency, as shown in Figure 13.1. After you have enabled this module, you are ready to begin writing WebSphere sMash applica- tion with PHP. C H A P T E R 13 PHP in WebSphere sMash Download from www.wowebook.com . dependent projects that your PHP application consumes. Adding PHP to Your Application To use PHP in your application, you must add the zero.php module as a dependency. After you create an application,. libraries, plus the WebSphere sMash APIs for HTTP access, REST, event, and database access. That’s a lot of power at your fingertips. WebSphere sMash provides a key benefit over normal PHP development. easy to swap versions just by changing your project’s dependency. An important note to discuss here for development environments: WebSphere sMash per- mits any peer projects to the main application