Adding function to an existing application is arguably one of the most challenging efforts in software development. You have to be careful not to alter existing code and also ensure that your change satisfies any ease-of-use and performance requirements. In this article, learn how to introduce new functions at the later stages of a Web project and how to seamlessly integrate your changes with the existing project.
The method in this article is especially useful during the following stages in the software development life cycle.
- Development stage. A client asks the development team to integrate new functions that would improve the usability of the product. (As projects start using iterative and agile methods of development, this is becoming more common.) A quick analysis and integration of new functions is required, with short turnaround time, without compromising the robustness and standards of the application.
- Maintenance stage. Frequently involves the addition and removal of functions. The development team might also be required to plug out or plug in certain functions for a particular client. Other customizations are often required.
After reviewing the problem statement, the team should develop a flexible architecture that allows additions and removals without changing the code that deals with the core functions of the product or application. Ideally, code pertaining to core functions should not change at all because of the time already invested in testing and stabilizing that portion of code. The use case in this article shows how you can develop such an application and outlines some of the challenges.
A blogging application is up and running. The client has a new requirement to add a mailing function to the blogging system. The client has a mailing server in place and wants to somehow integrate the two applications. The client wants:
- To provide users with a window whenever they click over a valid URL.
- The window to include all the options provided by a mailing widget.
- The mailing window to post messages to the mailing server.
The development team cannot risk changing the core functions of the blogging system to add the mailing function. The situation was aggravated when the team, when developing core functions, used third-party software that does not allow them to make changes in the source code. In addition, management is resistant to altering the existing presentation and business layers.
There are two approaches available to the development team. Figure 1 shows the approach where core and new functions are not tightly integrated; the architecture has new functions loosely coupled with the core functions:
Figure 1. Core and new functions not tightly integrated
Figure 2 shows the approach with core and new functions tightly integrated; in this architecture, new functions become an inherent part of the core functions.
Figure 2. Core and new functions tightly integrated
The development team decides to adopt the first approach, in Figure 1. It has all the benefits related to loosely coupled architecture, such as code reusability, and it also limits the testing effort required.
They will use the Dojo toolkit to develop widgets and integrate them with the main application in a loosely coupled fashion. They chose Dojo because:
- It's a JavaScript based toolkit that meets the requirement for ease of integration. Just by including the JavaScript, they have the benefit of a rich API that should suffice for most of the development efforts. It allows the team to develop wonderfully rich and great-looking widgets with little or no effort to integrate them within the application.
- Dojo supports Ajax, which makes the application more responsive and improves the overall efficiency. More importantly, it allows very fast interaction with the main application.
If you are new to Ajax, it is a Web development technique used for creating interactive Web applications. It makes Web pages seem more responsive by exchanging small amounts of data with the server, behind the scenes, so the entire Web page doesn't have to reload each time the user requests a change. This is intended to increase the Web page's interactivity, speed, function, and usability. See Resources for more about Ajax.
First, you need to set up Dojo (see Resources for help with setup). After setting up Dojo:
- You need to create a .js file that will include most of the coding effort. To plug in the required functions, just include this .js file in the presentation layer (jsp, HTML, and so on).
-
To avoid including Dojo libraries in the presentation layer, include them in the .js
file created in Step 1. Listing 1 shows sample code to enable the inclusion of
dojo.js:
Listing 1. Enabling inclusion of dojo.jsfunction addOnJsFiles(file) { var scriptTag= document.createElement('script'); scriptTag.src = file; scriptTag.type = 'text/javascript'; scriptTag.defer = true; document.getElementsByTagName('head').item(0).appendChild(scriptTag); } /*Take special care that you have not included the dojo.js in the jsp also, as this is known to cause problem in IE though it works fine with Firefox. If you have included both dojo.js and the .js file in which this function is to implemented, you should remove inclusion of dojo.js from jsp file.*/
Depending on the directory structure, you might have to make a call to Listing 1, as shown in Listing 2:
Listing 2. Call to function in Listing 1addOnJsFiles('js/dojo/dojo.js'); /* Take care of the directory structure */
-
A parsing mechanism lets you find any e-mail addresses on the screen being visualized by
the user. You can use JavaScript's regular expression to do this, as shown in Listing
3:
Listing 3. Searching all valid e-mail patternsvar email = /(([a-zA-Z0-9_\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+)/g
-
Write the code snippet that allows you to wrap up the e-mail address in a label tag, as
shown in Listing 4:
Listing 4. Replacing all the valid e-mail patternsvar htmlContent = document.body.innerHTML; htmlContent=htmlContent.replace(email, "<label onclick= "sendmail('$1')\">$1</label>"); document.body.innerHTML=htmlContent;
-
Use the sendmail function to include the primary business logic and the code for creating and displaying Dojo widgets.
Include the files that you need for your widgets, depending on which widgets and APIs
you use. Listing 5 shows an example:
Listing 5. Include necessary packagesdojo.require("dojo.widget.*"); dojo.require("dojo.event.*"); dojo.require("dojo.widget.Button"); dojo.require("dojo.widget.Editor2"); dojo.require("dojo.widget.Textbox");
You'll have to include packages such as dojo.widget.* even though you include specific widget libraries (like dojo.widget.Button). This behavior is unlike Java and other languages. The method
dojo.requirewill dynamically retrieve the JavaScript code and load them in the page. If you don't include dojo.widget.* and dojo.widget.Button, you'll get a run time exception because the common widget libraries wouldn't have been loaded. -
Dojo provides two approaches for creating widgets:
-
Pass the parent id of the widget in the constructor (showin in Listing 6). "Parent" here means the DOM element to which our widget will be connected.
Listing 6. Creation of Dojo widgetsvar tmpDiv = document.getElementById(divid); var FloatingPaneWidget = dojo.widget.createWidget("FloatingPane", { id:"pane1",windowState:"minimized", title:"Send Email", hasShadow: "true", resizable:"true",displayMinimizeAction:"true", toggle:"explode",constrainToContainer: "false" }, tmpDiv);
-
Create widgets programmatically and insert them back into the DOM structure, as shown
in Listing 7:
Listing 7. Creation of Dojo widgetsvar newEditor = dojo.widget.createWidget('Editor2'); var layoutWinEd2 = dojo.widget.createWidget("LayoutContainer", {layoutAlign:"top"}); layoutWinEd2.addChild(newEditor);
Listing 7 adds the editor to the layout container. To connect to our mailing widget, you can include the following code:
FloatingPaneWidget.addChild(layoutWinEd2);
For adding the business logic (actual code for sending e-mails), Dojo gives you the ability to attach their methods along with the primitive ones provided by the toolkit. Attaching a customized method is done with:
dojo.event.connect(SubmitButtonId,"onClick", "codeForSendingMail");
Write the function for handling the onclick event, shown in Listing 8:
Listing 8. Sample code for handling events.function codeForSendingMail () { alert("Special handling for onclick ..."); ...Your logic goes here }
dojo.widget.byId('pane1').show();
-
Pass the parent id of the widget in the constructor (showin in Listing 6). "Parent" here means the DOM element to which our widget will be connected.
-
To submit data asynchronously, use the library dojo.io. This library provides a fairly
simple interface for submitting the forms data asynchronously through the
bindmethod. Listing 9 shows an example:
Listing 9. Handling eventsvar myform = dojo.byId("myform"); dojo.io.bind({ url: xyz.com, /* This is not required if the form has an action element defined */ formNode: myform, method: myform.method, /* Get or Post */ load: myCallBackFuntion, error: function(type, error) { alert("Error: " + type + "n" + error); } });
-
Dojo provides support for cross domain communication. Because the application requires
communication across different domains (application server, mailing server), use Dojo's
XhrIframeProxy library. Add the code in Listing 10 to the .js that you developed earlier.
Include the dojo.io.XhrIframeProxy, which does all the Iframe work, to Dojo's
bindfunction:dojo.require("dojo.io.XhrIframeProxy");
Listing 10. Dojo's bind calldojo.io.bind({ IframeProxyUrl: http://externalDomain/myhtml.html, url:http://externalDomain/path/myservlet.do, content: { To:toVal, From: fromVal, CC: ccVal, BCC:bccVal, Subject: subVal, Message: messageText }, load: showSucessMessage, error: showErrorMessage, method: 'POST', mimetype: "text/html" });
IframeProxyUrlis the location of the HTML file on the external domain, which includes a .js to implement the authorization (isAllowedRequest) function.The HTML file myhtml.html, on the domain externalDomain, should implement the function in Listing 11 by including a .js file or directly in script tags:
Listing 11. Remote html should includefunction isAllowedRequest(request){ /* Return true if you want to allow cross domain interaction, else return false */ }
In this article, you learned how to add a floating pane (Dojo widget) and integrate it back into the main application without altering the original code base. Advantages of this development strategy include:
- Various teams can work on isolated parts of the project, allowing you to develop different modules in parallel. The framework of the methodologies allows for development and integration of independent and redistributable code.
- Testing and acceptance efforts are reduced dramatically. Testers can focus only on new functions being integrated, rather than retesting an entire application.
- Flexible customization according to business requirements. Add-on functions can be added or removed at any time.
Learn
- Get a demo and learn all about
Dojo.
- Check out a collection of Dojo FAQs.
- "Develop HTML
widgets with Dojo" (Igor Kusakov, developerWorks, February 2007) shows the basics of developing HTML widgets using Dojo, including how to refer an image, how to add an event handler to an HTML page, and how to handle composite widgets.
- Use the case study "Develop a Web
application using Ajax with Dojo and DB2" (Leons Petrazickis, developerWorks, February 2007) to learn to quickly creating an elegant, responsive Web application using IBM DB2 9 for Linux, UNIX, and Windows, XQuery, PHP, and the Dojo JavaScript Framework.
-
"Build apps
using Asynchronous JavaScript with XML (Ajax)" (Naveen Balani and Rajeev Hathi,
developerWorks, November 2005) explains how to build Ajax-based Web applications
— complete with real time validation and without page refreshes — by following the construction of a sample book order application.
- Browse the
technology bookstore
for books on these and other technical topics.
Get products and technologies
- Download
IBM product evaluation versions
and get your hands on application development tools and middleware products from
DB2®, Lotus®, Rational®, Tivoli®, and
WebSphere®.
Discuss
- Check out
developerWorks blogs and get involved in the
developerWorks community.
Comments (Undergoing maintenance)






