Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - Front-End Web Development

341 Articles
article-image-modx-20-web-development-basics
Packt
24 Feb 2011
7 min read
Save for later

MODx 2.0: Web Development Basics

Packt
24 Feb 2011
7 min read
  MODx Web Development - Second Edition Site configuration When you first log in to the MODx Manager interface, you will see the site configuration page in the rightmost panel. Here, you can customize some basic configurations of the site. You can reach this page from anywhere in the MODx Manager by clicking on the Configuration sub-menu in the Tools menu. All of the options that can be configured from this Configuration page are settings that are global to the entire site. After changing the configurations, you have to let MODx store them by clicking on the Save button. The following is the screenshot of the Configuration page: (Move the mouse over the image to enlarge it) The configurations are grouped into five categories: Site—mostly, settings that are used to personalize the site Friendly URLs—settings to help make the site search-engine optimized User—settings related to user logins Interface & Features—mostly, Manager interface customizations File Manager—settings defining what can be uploaded and where Configuring the site In this section, we are going to make a few changes to get you familiar with the various configurations available. Most configurations have tooltips that describe them in a little pop-up when you move the mouse over them. After making changes in the site configuration and saving it, you will be redirected to another page. This page is available by clicking on the Home link on the Site tab. This page is also the default Manager interface page. This means that every time you log in using the Manager login screen, you will reach this page by default. This page has seven tabs, which are briefly explained below: My MODx Site: Provides quick access to certain features in MODx. Configuration: Displays information on the current status of the site. MODx News: Shows updates on what is happening with MODx. Security Notices: Shows updates on what is happening with MODx that is specific to security. Recent Resources: Shows a list with hyperlinks of the recently created or edited resources. Info: Shows information about your login status. Online: Lists all of the active users. Noticing and fixing errors and warnings The Configuration tab of the default Manager interface page displays errors and warnings about issues in the installation, if any. Generally, it also has instructions on how to fix them. Most of the time, the warnings are for security issues or suggestions for improving performance. Hence, although the site will continue to work when there are warnings listed on this page, it is good practice to fix the issues that have caused these warnings. Here we discuss three such warnings that occur commonly, and also show how to fix them. config file still writable: This is shown when the config file is still writable. It can be fixed by changing the properties of the configuration file to read only. register_globals is set to ON in your php.ini configuration file: This is a setting in the PHP configuration file. This should be set to OFF. Having it ON makes the site more vulnerable to what is known as cross site scripting (XSS). Configuration warning—GD and/or Zip PHP extensions not found: This is shown when you do not have the specified packages installed with PHP. MAMP doesn't come with the ZIP extension and you can ignore this configuration if you are not using it in production. Both XAMPP and MAMP come with the GD extension by default. Changing the name of the site In the previous section, we listed the groups of configuration options that are available. Let us change one option—the name of the site—now. Click on the Tools menu in the top navigational panel Click on the Configuration Menu item Change the text field labeled Site Name to Learning MODx Click on the Save button The basic element of MODx: Resources Resources are the basic building blocks in MODx. They are the elements that make up the content of the site. Every web page in MODx corresponds to a Resource page. In early versions of MODx, Resources were called Documents. Thinking of them as documents may make it easier for you to understand. Every resource has a unique ID. This ID can be passed along in the URL, and MODx will display the page for the resource with the same ID. In the simplest case, a resource contains plain text. As can be seen from the previous screenshot, the ID referred to here is 2, and the content displayed on the screen is from resource ID 9. It is also possible to refer to a resource by an alias name instead of an ID. An alias is a friendly name that can be used instead of having to use numbers. Containers Resources can be contained within other resources called containers. Containers in MODx are like folders in filesystems, but with the difference that a container is also a resource. This means that every container also has a resource ID, and a corresponding page is shown when such an ID is referenced in the URL. MODx Manager interface MODx is administered and customized by using the provided Manager interface. From the Manager interface, you can edit resources, place them within containers, and change their properties. You can log in to the Manager interface by using the Manager login screen http://sitename/manager, by using the username and password that you supplied when installing MODx. The Manager interface is divided into two panes. The leftmost pane always displays the resources in a resource tree, and the rightmost pane displays the content relevant to your last action. The two preceding panes you see are the menu and the corresponding menu items. Each of these leads to the different functionalities of MODx. In the leftmost pane, you will see the site name followed by a hierarchically-grouped resource list. There is a + near every unexpanded container that has other resources. When you click on the + symbol, the container expands to show the children and the + symbol changes to a – symbol. Clicking on the – symbol hides the children of the respective container. The resource's ID is displayed in parentheses after the resource's title in the resource tree. The top of leftmost pane consists of a few icons, referred to as the Resource Toolbar, which help to control the visibility of the resource tree. Expand Site Tree—expand all of the containers to show their children and siblings. Collapse Site Tree—collapse all of the containers to hide their children and siblings. New Resource—open a new resource page in the rightmost pane. New Weblink—open a new weblink page in the rightmost pane. Refresh Site Tree—refresh the tree of containers and resources to make available any changes that are not yet reflected in the tree. Sort the Site Tree—open a pop-up page where you can select from the various criteria available to sort the tree. Purge—when you delete a resource, it stays in the recycle bin. The resources are struck out with a red line. The resources can be completely removed from the system by clicking on the Purge icon. Hide Site Tree—this icon slides the leftmost pane out of view, giving more space for the rightmost pane. Right-clicking on a resource brings up a context menu from where you can perform various actions on the resource. Clicking on Edit will open the page for editing in the rightmost pane. The context menu provides interesting shortcuts that are very handy.
Read more
  • 0
  • 0
  • 1356

article-image-faqs-yui
Packt
18 Feb 2011
7 min read
Save for later

FAQs on YUI

Packt
18 Feb 2011
7 min read
  YUI 2.8: Learning the Library Develop your next-generation web applications with the YUI JavaScript development library Improve your coding and productivity with the YUI Library Gain a thorough understanding of the YUI tools Learn from detailed examples for common tasks         Read more about this book       (For more resources on Yui, see here.) Q: What is the YUI?A: The Yahoo! User Interface (YUI) Library is a toolkit packed full of powerful objects that enables rapid frontend GUI design for richly interactive web-based applications. The utilities provide an advanced layer of functionality and logic to your applications, while the controls are attractive pre-packed objects that we can drop onto a page and begin using with little customization. Q: Who is it for and who will it benefit the most?A: The YUI is aimed at and can be used by just about anyone and everyone, from single site hobbyists to creators of the biggest and best web applications around. Developers of any caliber can use as much or as little of it as they like to improve their site and to help with debugging. It's simple enough to use for those of you that have just a rudimentary working knowledge of JavaScript and the associated web design technologies, but powerful and robust enough to satisfy the needs of the most aspiring and demanding developers amongst you. Q: How do I install it?A: The simple answer is that you don’t. Both you, while developing and your users can load the components needed both from Yahoo! CDN and even from Google CDN across the world. The CDN (Content Delivery Network) is what the press nowadays calls ‘the cloud’ thus, your users are more likely to get a better performance loading the library from the CDN than from your own servers. However, if you wish, you can download the whole package either to take a deep look into it or serve it to your users from within your own network. You have to serve the library files yourself if you use SSL. Q: From where can one download the YUI Library?A: The YUI Library can be downloaded from the YUI homepage. The link can be found at http://developer.yahoo.com/yui/. Q: Are there any licensing restrictions for YUI?A: All of the utilities, controls, and CSS resources that make up the YUI have been publicly released, completely for free, under the open source BSD (Berkeley Software Distribution) license. This is a very unrestrictive license in general and is popular amongst the open source community. Q: Which version should I use?A: The YUI Library is currently provided in two versions, YUI2 and YUI3. YUI2 is the most stable version and there are no plans to discontinue it. In fact, the YUI Team is working on the 2.9 version, which will be the last major revision of the YUI2 code line and is to be released in the second half of 2011. The rest of this article will mostly refer to the YUI 2.8 release, which is the current one. The YUI3 code line is the newest and is much faster and flexible. It has been redesigned from the ground up with all the experience accumulated over 5 years of development of the YUI2 code line. At this point, it does not have such a complete set of components as the YUI2 version and many of those that do exist are in ‘beta’ status. If your target release date is towards the end of 2011, YUI3 is a better choice since by then, more components should be out of ‘beta’. The YUI team has also opened the YUI Gallery to allow for external contributions. YUI3, being more flexible, allows for better integration of third-party components thus, what you might not yet find in the main distribution might be already available from the YUI Gallery. Q: Does Yahoo! use the YUI Library? Do I get the same one?A: They certainly do! The YUI Library you get is the very same that Yahoo! uses to power their own web applications and it is all released at the same time. Moreover, if you are in a rush, you can also stay ahead of the releases (at your own risk) by looking at GitHub, which is the main life repository for both YUI versions. You can follow YUI’s development day by day. Q: How do I get support?A: The YUI Library has always been one of the best documented libraries available with good users guide and plenty of well explained examples besides the automated API docs. If that is not enough, you can reach the forums, which currently have over 7000 members with many very knowledgeable people amongst them, both from the YUI team and many power users. Q: What does the core of the YUI library do?A: What was then known as the ‘browser wars’, with several companies releasing their own set of features on the browsers, left the programming community with a set of incompatible features which made front-end programming a nightmare. The core utilities try to fix these incompatibilities by providing a single standard and predictable API and deal with each browser as needed. The core of the library consists of the following three files: YAHOO Global Object: The Global Object sets up the Global YUI namespace and provides other core services to the rest of the utilities and controls. It's the foundational base of the library and is a dependency for all other library components (except for the CSS tools). Dom utilities: The Dom utilities provide a series of convenient methods that make working with the Document Object Model much easier and quicker. It adds useful selection tools, such as those for obtaining elements based on their class instead of an ID, and smoothes out the inconsistencies between different browsers to make interacting with the DOM programmatically a much more agreeable experience. Event Utility: The Event Utility provides a unified event model that co-exists peacefully with all of the A-grade browsers in use today and offers a consistent method of accessing the event object. Most of the other utilities and controls also rely heavily upon the Event Utility to function correctly. Q: What are A-grade browsers?A: For each release, the YUI Library is thoroughly tested on a variety of browsers. This list of browsers is taken from Yahoo!’s own statistics of visitors to their sites. The YUI Library must work on all browsers with a significant number of users. The A-grade browsers are those that make up the largest share of users. Fortunately browsers come in ‘families’ (for example, Google’s Chrome and Apple’s Safari both use the WebKit rendering engine) thus, a positive result in one of them is likely to apply to all of them. Testing in Safari for Mac provides valid results for the Safari on Windows version, which is rarely seen. Those browsers are considered X-Grade, meaning, they haven’t been tested but they are likely to work fine. Finally, we have the C-grade browsers which are known to be obsolete and nor YUI nor any other library can really be expected to work on them. This policy is called Graded Browser Support and it is updated quarterly. It does not depend on the age of the browser but on its popularity, for example, IE6 is still in the A-grade list because it still has a significant share.
Read more
  • 0
  • 0
  • 1355

article-image-yearly-holiday-list-calendar-developed-using-jquery-ajax-xml-and-css3
Packt
01 Feb 2011
5 min read
Save for later

Yearly Holiday List Calendar Developed using jQuery, AJAX, XML and CSS3

Packt
01 Feb 2011
5 min read
  PHP jQuery Cookbook Over 60 simple but highly effective recipes to create interactive web applications using PHP with jQuery Create rich and interactive web applications with PHP and jQuery Debug and execute jQuery code on a live site Design interactive forms and menus Another title in the Packt Cookbook range, which will help you get to grips with PHP as well as jQuery About Holiday List Calendar This widget will help you in knowing the list of holidays in various countries. Here in this example, I have listed holidays pertaining to only two counties, namely India and US. You can make use of this widget on your websites or blogs to tell your readers about holidays and their importance if necessary. Adding jQuery to your page Download the latest version of jQuery from the jQuery site. This site can be added as a reference to your web pages accordingly. You can reference a local copy of jQuery after downloading <script> tag in the page. You can also directly reference the remote copy from jQuery or Google Ajax API. Pre-requisite Knowledge In order to understand the code, one should have some knowledge of AJAX concepts and XML Structure, basic knowledge of HTML, advance knowledge of CSS3 and lastly and mostly important one should know advance level of jQuery coding. Ingredients Used jQuery [Advance Level] CSS3 HTML XML Photoshop [Used for coming up with UI Design] HTML Code <div id="calendar-container"> <div class="nav-container"> <span>Year<br/><select id="selectYear"></select></span> <span class="last">Month<br /><a href="#" id="prevBtn" class="button gray"><</a> <select id="selectMonth"></select> <a href="#" id="nextBtn" class="button gray">></a></span> </div> <div class="data-container"></div> </div> XML Structure <?xml version="1.0" encoding="ISO-8859-1"?> <calendar> <year whichyear="2010" id="1"> <month name="January" id="1"> <country name="India"> <holidayList date="Jan 01st" day="Friday"><![CDATA[Sample Data]]></holidayList> <holidayList date="Jan 14th" day="Friday"><![CDATA[Sample Data]]></holidayList> <holidayList date="Jan 26th" day="Wednesday"><![CDATA[Sample Data]]></holidayList> </country> <country name="US"> <holidayList date="Jan 01st" day="Saturday"><![CDATA[Sample Data]]></holidayList> <holidayList date="Jan 17th" day="Monday"><![CDATA[Sample Data]]></holidayList> </country> </month> <month name="January" id="1"> --------------------- --------------------- --------------------- </month> </year> </calendar> CSS Code body{ margin: 0; padding: 0; font-family: "Lucida Grande", "Lucida Sans", sans-serif; font-size: 100%; background: #333333; } #calendar-container{ width:370px; padding:5px; border:1px solid #bcbcbc; margin:0 auto; background-color:#cccccc; -webkit-border-radius: .5em; -moz-border-radius: .5em; border-radius: .5em; -webkit-box-shadow: 0 1px 4px rgba(0,0,0,.2); -moz-box-shadow: 0 1px 4px rgba(0,0,0,.2); box-shadow: 0 1px 4px rgba(0,0,0,.2); } .nav-container{ padding:5px; } .nav-container span{display:inline-block; text-align::left; padding-right:15px; border-right:1px solid #828282; margin-right:12px; text-shadow: 1px 1px 1px #ffffff; font-weight:bold;} .nav-container span.last{padding-right:0px; border-right:none; margin-right:0px;} .data-container{ font-family:Arial, Helvetica, sans-serif; font-size:14px; } #selectMonth{width:120px;} .data-container ul{margin:0px; padding:0px;} .data-container ul li{ list-style:none; padding:5px;} .data-container ul li.list-header{border-bottom:1px solid #bebebe; border-right:1px solid #bebebe; background-color:#eae9e9; -webkit-border-radius: .2em .2em 0 0; -moz-border-radius: .2em .2em 0 0; border-radius: .3em .3em 0 0; background:-moz-linear-gradient(center top , #eae9e9, #d0d0d0) repeat scroll 0 0 transparent; margin-top:5px; text-shadow: 1px 1px 1px #ffffff;} .data-container ul li.padding-left-10px {background-color:#EEEEEE; border-bottom:1px solid #BEBEBE; border-right:1px solid #BEBEBE; font-size:12px;} /* button ---------------------------------------------- */ .button { font-size: 25px; font-weight: 700; display: inline-block; zoom: 1; /* zoom and *display = ie7 hack for display:inline-block */ *display: inline; vertical-align: bottom; margin: 0 2px; outline: none; cursor: pointer; text-align: center; text-decoration: none; text-shadow: 1px 1px 1px #555555; padding: 0px 10px 3px 10px; -webkit-border-radius: .2em; -moz-border-radius: .2em; border-radius: .2em; -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.2); -moz-box-shadow: 0 1px 2px rgba(0,0,0,.2); box-shadow: 0 1px 2px rgba(0,0,0,.2); } .button:hover { text-decoration: none; } .button:active { position: relative; top: 1px; } select{ -webkit-border-radius: .2em .2em .2em .2em; -moz-border-radius: .2em .2em .2em .2em; border-radius: .2em; -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.2); -moz-box-shadow: 0 1px 2px rgba(0,0,0,.2); box-shadow: 0 1px 2px rgba(0,0,0,.2); padding:5px; font-size:16px; border:1px solid #4b4b4b; } /* color styles ---------------------------------------------- */ .gray { color: #e9e9e9; border: solid 1px #555; background: #6e6e6e; background: -webkit-gradient(linear, left top, left bottom, from(#888), to(#575757)); background: -moz-linear-gradient(top, #888, #575757); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#888888', endColorstr='#575757'); } .gray:hover { background: #616161; background: -webkit-gradient(linear, left top, left bottom, from(#757575), to(#4b4b4b)); background: -moz-linear-gradient(top, #757575, #4b4b4b); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#757575', endColorstr='#4b4b4b'); } .gray:active { color: #afafaf; background: -webkit-gradient(linear, left top, left bottom, from(#575757), to(#888)); background: -moz-linear-gradient(top, #575757, #888); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#575757', endColorstr='#888888'); } .grayDis{ color: #999999; background: -webkit-gradient(linear, left top, left bottom, from(#575757), to(#888)); background: -moz-linear-gradient(top, #575757, #888); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#575757', endColorstr='#888888'); } h2{ color:#ffffff; text-align:center; margin:10px 0px;} #header{ text-align:center; font-size: 1em; font-family: "Helvetica Neue", Helvetica, sans-serif; padding:1px; margin:10px 0px 80px 0px; background-color:#575757; } .ad{ width: 728px; height: 90px; margin: 50px auto 10px; } #footer{ width: 340px; margin: 0 auto; } #footer p{ color: #ffffff; font-size: .70em; margin: 0; } #footer a{ color: #15ADD1; }  
Read more
  • 0
  • 0
  • 2376
Banner background image

article-image-communicating-server-using-google-web-toolkit-rpc
Packt
19 Jan 2011
5 min read
Save for later

Communicating with Server using Google Web Toolkit RPC

Packt
19 Jan 2011
5 min read
  Google Web Toolkit 2 Application Development Cookbook Over 70 simple but incredibly effective practical recipes to develop web applications using GWT with JPA , MySQL and i Report Create impressive, complex browser-based web applications with GWT 2 Learn the most effective ways to create reports with parameters, variables, and subreports using iReport Create Swing-like web-based GUIs using the Ext GWT class library Develop applications using browser quirks, Javascript,HTML scriplets from scratch Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible  The Graphical User Interface (GUI) resides in the client side of the application. This article introduces the communication between the server and the client, where the client (GUI) will send a request to the server, and the server will respond accordingly. In GWT, the interaction between the server and the client is made through the RPC mechanism. RPC stands for Remote Procedure Call. The concept is that there are some methods in the server side, which are called by the client at a remote location. The client calls the methods by passing the necessary arguments, and the server processes them, and then returns back the result to the client. GWT RPC allows the server and the client to pass Java objects back and forth. RPC has the following steps: Defining the GWTService interface: Not all the methods of the server are called by the client. The methods which are called remotely by the client are defined in an interface, which is called GWTService. Defining the GWTServiceAsync interface: Based on the GWTService interface, another interface is defined, which is actually an asynchronous version of the GWTService interface. By calling the asynchronous method, the caller (the client) is not blocked until the method completes the operation. Implementing the GWTService interface: A class is created where the abstract method of the GWTService interface is overridden. Calling the methods: The client calls the remote method to get the server response. Creating DTO classes In this application, the server and the client will pass Java objects back and forth for the operation. For example, the BranchForm will request the server to persist a Branch object, where the Branch object is created and passed to server by the client, and the server persists the object in the server database. In another example, the client will pass the Branch ID (as an int), the server will find the particular Branch information, and then send the Branch object to the client to be displayed in the branch form. So, both the server and client need to send or receive Java objects. We have already created the JPA entity classes and the JPA controller classes to manage the entity using the Entity Manager. But the JPA class objects are not transferable over the network using the RPC. JPA classes will just be used by the server on the server side. For the client side (to send and receive objects), DTO classes are used. DTO stands for Data Transfer Object. DTO is simply a transfer object which encapsulates the business data and transfers it across the network. Getting ready Create a package com.packtpub.client.dto, and create all the DTO classes in this package. How to do it... The steps required to complete the task are as follows: Create a class BranchDTO that implements the Serializable interface: public class BranchDTO implements Serializable Declare the attributes. You can copy the attribute declaration from the entity classes. But in this case, do not include the annotations: private Integer branchId; private String name; private String location Define the constructors, as shown in the following code: public BranchDTO(Integer branchId, String name, String location) { this.branchId = branchId; this.name = name; this.location = location; } public BranchDTO(Integer branchId, String name) { this.branchId = branchId; this.name = name; } public BranchDTO(Integer branchId) { this.branchId = branchId; } public BranchDTO() { } To generate the constructors automatically in NetBeans, right-click on the code, select Insert Code | Constructor, and then click on Generate after selecting the attribute(s). Define the getter and setter: public Integer getBranchId() { return branchId; } public void setBranchId(Integer branchId) { this.branchId = branchId; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } To generate the setter and getter automatically in NetBeans, right-click on the code, select Insert Code | Getter and Setter…, and then click on Generate after selecting the attribute(s). Mapping entity classes and DTOs In RPC, the client will send and receive DTOs, but the server needs pure JPA objects to be used by the Entity Manager. That's why, we need to transform from DTO to JPA entity class and vice versa. In this recipe, we will learn how to map the entity class and DTO. Getting ready Create the entity and DTO classes. How to do it... Open the Branch entity class and define a constructor with a parameter of type BranchDTO. The constructor gets the properties from the DTO and sets them in its own properties: public Branch(BranchDTO branchDTO) { setBranchId(branchDTO.getBranchId()); setName(branchDTO.getName()); setLocation(branchDTO.getLocation()); } This constructor will be used to create the Branch entity class object from the BranchDTO object. In the same way, the BranchDTO object is constructed from the entity class object, but in this case, the constructor is not defined. Instead, it is done where it is required to construct DTO from the entity class. There's more... Some third-party libraries are available for automatically mapping entity class and DTO, such as Dozer and Gilead. For details, you may visit http://dozer.sourceforge.net/ and http://noon.gilead.free.fr/gilead/. Creating the GWT RPC Service In this recipe, we are going to create the GWTService interface, which will contain an abstract method to add a Branch object to the database. Getting ready Create the Branch entity class and the DTO class.  
Read more
  • 0
  • 0
  • 1689

article-image-working-entities-google-web-toolkit-2
Packt
19 Jan 2011
9 min read
Save for later

Working with Entities in Google Web Toolkit 2

Packt
19 Jan 2011
9 min read
  Google Web Toolkit 2 Application Development Cookbook Over 70 simple but incredibly effective practical recipes to develop web applications using GWT with JPA , MySQL and i Report Create impressive, complex browser-based web applications with GWT 2 Learn the most effective ways to create reports with parameters, variables, and subreports using iReport Create Swing-like web-based GUIs using the Ext GWT class library Develop applications using browser quirks, Javascript,HTML scriplets from scratch Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible         Read more about this book       (For more resources on GWT, see here.) Finding an entity In this recipe, we are going to write the code to find an entity. From the client side, the ID of the entity will be passed to the server; the server will find the entity in the database using the JPA controller class, and then return the entity to the client in order to display it. How to do it... Declare the following method in the GWTService interface: public BranchDTO findBranch(int branchId); Declare the asynchronous version of the above method in GWTServiceAsync interface public void findBranch(int branchId, AsyncCallback<BranchDTO> asyncCallback); Implement this method in GWTServiceImpl class @Override public BranchDTO findBranch(int branchId) { Branch branch=branchJpaController.findBranch(branchId); BranchDTO branchDTO=null; if(branch!=null) { branchDTO=new BranchDTO(); branchDTO.setBranchId(branch.getBranchId()); branchDTO.setName(branch.getName()); branchDTO.setLocation(branch.getLocation()); } return branchDTO; } Create a callback instance in client side (BranchForm in this case) to call this method as shown in the following code: final AsyncCallback<BranchDTO> callbackFind = new AsyncCallback<BranchDTO>() { @Override public void onFailure(Throwable caught) { MessageBox messageBox = new MessageBox(); messageBox.setMessage("An error occured! Cannot complete the operation"); messageBox.show(); clear(); } @Override public void onSuccess(BranchDTO result) { branchDTO=result; if(result!=null) { branchIdField.setValue(""+branchDTO.getBranchId()); nameField.setValue(branchDTO.getName()); locationField.setValue(branchDTO.getLocation()); } else { MessageBox messageBox = new MessageBox(); messageBox.setMessage("No such Branch found"); messageBox.show(); clear(); } } }; Write the event-handling code for the find button as follows: findButton.addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { MessageBox inputBox = MessageBox.prompt("Input", "Enter the Branch ID"); inputBox.addCallback(new Listener<MessageBoxEvent>() { public void handleEvent(MessageBoxEvent be) { int branchId = Integer.parseInt(be.getValue()); ((GWTServiceAsync)GWT.create(GWTService.class)). findBranch(branchId,callbackFind); } }); } }); How it works... Here, the steps for calling the RPC method are the same as we had done for the add/save operation. The only difference is the type of the result we have received from the server. We have passed the int branch ID and have received the complete BrachDTO object, from which the values are shown in the branch form. Updating an entity In this recipe, we are going to write the code to update an entity. The client will transfer the DTO of updated object, and the server will update the entity in the database using the JPA controller class. How to do it... Declare the following method in the GWTService interface: public boolean updateBranch(BranchDTO branchDTO); Declare the asynchronous version of this method in the GWTServiceAsync interface: public void updateBranch(BranchDTO branchDTO, AsyncCallback<java.lang.Boolean> asyncCallback); Implement the method in the GWTServiceImpl class: @Override public boolean updateBranch(BranchDTO branchDTO) { boolean updated=false; try { branchJpaController.edit(new Branch(branchDTO)); updated=true; } catch (IllegalOrphanException ex) { Logger.getLogger(GWTServiceImpl.class.getName()). log(Level.SEVERE, null, ex); } catch (NonexistentEntityException ex) { Logger.getLogger(GWTServiceImpl.class.getName()). log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(GWTServiceImpl.class.getName()). log(Level.SEVERE, null, ex); } return updated; } Create a callback instance for this method in the client side (BranchForm in this case, if it is not created yet): final AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() { MessageBox messageBox = new MessageBox(); @Override public void onFailure(Throwable caught) { messageBox.setMessage("An error occured! Cannot complete the operation"); messageBox.show(); } @Override public void onSuccess(Boolean result) { if (result) { messageBox.setMessage("Operation completed successfully"); } else { messageBox.setMessage("An error occured! Cannot complete the operation"); } messageBox.show(); } }; Write the event handle code for the update button: updateButton.addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { branchDTO.setName(nameField.getValue()); branchDTO.setLocation(locationField.getValue()); ((GWTServiceAsync)GWT.create(GWTService.class)). updateBranch(branchDTO,callback); clear(); } }); How it works... This operation is also almost the same as the add operation shown previously. The difference here is the method of controller class. The method edit of the controller class is used to update an entity. Deleting an entity In this recipe, we are going to write the code to delete an entity. The client will transfer the ID of the object, and the server will delete the entity from the database using the JPA controller class. How to do it... Declare the following method in the GWTService interface public boolean deleteBranch(int branchId); Declare the asynchronous version of this method in GWTServiceAsync interface public void deleteBranch(int branchId, AsyncCallback<java.lang.Boolean> asyncCallback); Implement the method in GWTServiceImpl class @Override public boolean deleteBranch(int branchId) { boolean deleted=false; try { branchJpaController.destroy(branchId); deleted=true; } catch (IllegalOrphanException ex) { Logger.getLogger(GWTServiceImpl.class.getName()). log(Level.SEVERE, null, ex); } catch (NonexistentEntityException ex) { Logger.getLogger(GWTServiceImpl.class.getName()). log(Level.SEVERE, null, ex); } return deleted; } Create a callback instance for this method in the client side (BranchForm in this case, if it is not created yet): final AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() { MessageBox messageBox = new MessageBox(); @Override public void onFailure(Throwable caught) { messageBox.setMessage("An error occured! Cannot complete the operation"); messageBox.show(); } @Override public void onSuccess(Boolean result) { if (result) { messageBox.setMessage("Operation completed successfully"); } else { messageBox.setMessage("An error occured! Cannot complete the operation"); } messageBox.show(); } }; Write the event handling code for the delete button: deleteButton.addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { ((GWTServiceAsync)GWT.create(GWTService.class)). deleteBranch(branchDTO.getBranchId(),callback); clear(); } }); Managing a list for RPC Sometimes, we need to transfer a list of objects as java.util.List (or a collection) back and forth between the server and the client. We already know from the preceding recipes that the JPA entity class objects are not transferable directly using RPC. Because of the same reason, any list of the JPA entity class is not transferable directly. To transfer java.util.List using RPC, the list must contain objects from DTO classes only. In this recipe, we will see how we can manage a list for RPC. In our scenario, we can consider two classes—Customer and Sales. The association between these two classes is that one customer makes zero or more sales and one sale is made by one customer. Because of such an association, the customer class contains a list of sales, and the sales class contains a single instance of customer class. For example, we want to transfer the full customer object with the list of sales made by this customer. Let's see how we can make that possible. How to do it... Create DTO classes for Customer and Sales (CustomerDTO and SalesDTO, respectively). In the following table, the required changes in data types are shown for the entity and DTO class attributes. The list in the DTO class contains objects of only the DTO class; on the other hand, the list of the entity class contains objects of entity class. Define the following constructor in the Customer entity class: public Customer(CustomerDTO customerDTO) { setCustomerNo(customerDTO.getCustomerNo()); setName(customerDTO.getName()); setAddress(customerDTO.getAddress()); setContactNo(customerDTO.getContactNo()); List<SalesDTO> salesDTOList=customerDTO.getSalesList(); salesList = new ArrayList<Sales>(); for(int i=0;i<salesDTOList.size();i++) { SalesDTO salesDTO=salesDTOList.get(i); Sales sales=new Sales(salesDTO); salesList.add(sales); } } Define the following constructor in the Sales entity class: public Sales(SalesDTO salesDTO) { setSalesNo(salesDTO.getSalesNo()); setSalesDate(salesDTO.getSalesDate()); setCustomer(new Customer(salesDTO.getCustomer())); // there's more but not relevant for this recipe } How it works... Now in the server side, the entity classes, Customer and Sales, will be used, and in the client side, CustomerDTO and SalesDTO, will be used. Constructors with DTO class type argument are defined for the mapping between entity class and DTO class. But here, the addition is the loop used for creating the list. From the CustomerDTO class, we get a list of SalesDTO. The loop gets one SalesDTO from the list, converts it to Sales, and adds it in the Sales list—that's all. Authenticating a user through username and password In this recipe, we are going to create the necessary methods to authenticate a user through a login process. Getting ready Create the DTO class for the entity class Users. How to do it... Declare the following method in the GWTService interface: public UsersDTO login(String username,String password); Declare the following method in the GWTServiceAsync interface: public void login(String username, String password, AsyncCallback<UsersDTO> asyncCallback); Implement the method in the GWTServiceImpl class: @Override public UsersDTO login(String username, String password) { UsersDTO userDTO = null; UsersJpaController usersJpaController = new UsersJpaController(); Users user = (Users) usersJpaController.findUsers(username); if (user != null) { if (user.getPassword().equals(password)) { userDTO=new UsersDTO(); userDTO.setUserName(user.getUserName()); userDTO.setPassword(user.getPassword()); EmployeeDTO employeeDTO= new EmployeeDTO(user.getEmployee().getEmployeeId()); employeeDTO.setName(user.getEmployee().getName()); userDTO.setEmployeeDTO(employeeDTO); } } return userDTO; } How it works... A username and password are passed to the method. An object of the UsersJpaController class is created to find the Users object based on the given username. If the find method returns null, it means that no such user exists. Otherwise, the password of the Users object is compared with the given password. If both the passwords match, a UsersDTO object is constructed and returned. The client will call this method during the login process. If the client gets null, the client should handle it accordingly, as the username/password is not correct. If it is not null, the user is authenticated. Summary In this article we how we can manage entities in GWT RPC. Specifically, we covered the following: Finding an entity Updating an entity Deleting an entity Managing a list for RPC Authenticating a user through username and password Further resources on this subject: Google Web Toolkit 2: Creating Page Layout [Article] Communicating with Server using Google Web Toolkit RPC [Article] Password Strength Checker in Google Web Toolkit and AJAX [Article] Google Web Toolkit GWT Java AJAX Programming [Book] Google Web Toolkit 2 Application Development Cookbook [Book]
Read more
  • 0
  • 0
  • 1149

article-image-making-ajax-requests-yui
Packt
10 Jan 2011
5 min read
Save for later

Making Ajax Requests with YUI

Packt
10 Jan 2011
5 min read
In this Ajax tutorial, you will learn the YUI way of making Asynchronous JavaScript and XML (AJAX) requests. Although, all modern browsers support sending asynchronous requests to the server, not all browsers work the same way. Additionally, you are not required to return XML; your AJAX requests may return JSON, text, or some other format if you prefer. The Connection component provides a simple, cross-browser safe way to send and retrieve information from the server. How to make your first AJAX request This recipe will show you how to make a simple AJAX request using YUI. Getting ready To use the Connection component, you must include the YUI object, the Event component, and the core of the Connection component: <script src="pathToBuild/yahoo/yahoo-min.js" type="text/javascript"></script> <script src="pathToBuild/event/event-min.js" type="text/javascript"></script> <script src="pathToBuild/connection/connection_core-min.js" type="text/javascript"></script> If you plan on using the form serialization example, or other advanced features, you will need to include the whole component, instead of only the core features: <script src="pathToBuild/connection/connection-min.js" type="text/javascript"></script> How to do it... Make an asynchronous GET request: var url = "/myUrl.php?param1=asdf&param2=1234"; var myCallback = { success: function(o) {/* success handler code */}, failure: function(o) {/* failure handler code */}, /* ... */ }; var transaction = YAHOO.util.Connect.asyncRequest('GET', url, myCallback); Make an asynchronous POST request: var url = "/myUrl.php"; var params = "param1=asdf&param2=1234"; var myCallback = { success: function(o) {/* success handler code */}, failure: function(o) {/* failure handler code */}, /* ... */ }; var transaction = YAHOO.util.Connect.asyncRequest( 'POST', url, myCallback, params); Make an asynchronous POST request using a form element to generate the post data: var url = "/myUrl.php"; var myCallback = { success: function(o) {/* success handler code */}, failure: function(o) {/* failure handler code */}, /* ... */ }; YAHOO.util.Connect.setForm('myFormEelementId'); var transaction = YAHOO.util.Connect.asyncRequest('POST', url, myCallback); How it works... All modern browsers have supported AJAX natively since the early 2000. However, IE implemented a proprietary version using the ActiveXObject object , while other browsers implemented the standard compliant XMLHttpRequest (XHR) object . Each object has its own implementation and quirks, which YUI silently handles for you. Both objects make an HTTP request to the provided URL, passing any parameters you specified. The server should handle AJAX requests like any normal URL request. When making a GET request , the parameters should be added to the URL directly (as in the example above). When making a POST request, the parameters should be a serialized form string (&key=value pairs) and provided as the fourth argument. Connection Manager also allows you to provide the parameters for a GET request as the fourth argument, if you prefer. Using the setForm function attaches a form element for serialization with the next call to the asyncRequest function . The element must be a form element or it will throw an exception. YUI polls the browser XHR object until a response is detected, then it examines the response code and the response data to see if it is valid. If it is valid, the success event fires, and if it is not, the failure event fires. YUI wraps the XHR response with its own connection object, thereby masking browser variations, and passes the wrapper object as the first argument of all the AJAX callback functions. There's more... Beside POST and GET, you may also use PUT, HEAD, and DELETE requests, but these may not be supported by all browsers or servers. It is possible to send synchronous request through the native XHR objects, however Connection Manager does not support this. The asyncRequest function returns an object known as the transaction object . This is the same object that YUI uses internally to manage the XHR request. It has the following properties: See also Exploring the callback object properties recipe, to learn what properties you can set on the callback object. Exploring the response object recipe, to learn what properties are available on the YUI object passed into your callback functions. Exploring the callback object properties The third argument you can provide to the asyncRequest function defines your callback functions and other related response/request properties. This recipe explains what those properties are and how to use them. How to do it... The properties available on the callback object are: var callback = { argument: {/* ... */}, abort: function(o) {/* ... */}, cache: false, failure: function(o) {/* ... */}, scope: {/* ... */}, success: function(o) {/* ... */}, timeout: 10000, // 10 seconds upload: function(o) {/* ... */}, }; How it works... The various callback functions attached to the connection object use the CustomEvent.FLAT callback function signature. This way the response object is the first argument of the callback functions. Each of the callback functions is subscribed to the appropriate custom event by the asyncRequest function. When the Connection Manager component detects the corresponding event conditions, it fires the related custom event. The upload callback function is special because an iframe is used to make this request. Consequently, YUI cannot reasonably discern success or failure, nor can it determine the HTTP headers. This callback will be executed both when an upload is successful and when it fails, instead of the success and failure callback functions. The argument property is stored on the response object and passed through to the callback functions. You can set the argument to anything that evaluates as true. When the cache property is true, YUI maps the responses to the URLs, so if the same URL is requested a second time, Connection Manager can simply execute the proper callback function immediately. The timeout property uses the native browser setTimeout function to call the abort function when the timeout expires. The timeout is cleared when an AJAX response is detected for a transaction. See also Exploring the response object properties recipe, to learn what properties are available on the YUI object passed into your callback functions. Using event callback functions recipe, to learn common practices for handling failure and success callback functions.
Read more
  • 0
  • 0
  • 3010
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €14.99/month. Cancel anytime
article-image-getting-started-ext-gwt
Packt
28 Dec 2010
8 min read
Save for later

Getting Started with Ext GWT

Packt
28 Dec 2010
8 min read
  Ext GWT 2.0: Beginner's Guide Take the user experience of your website to a new level with Ext GWT Explore the full range of features of the Ext GWT library through practical, step-by-step examples Discover how to combine simple building blocks into powerful components Create powerful Rich Internet Applications with features normally only found in desktop applications Learn how to structure applications using MVC for maximum reliability and maintainability      What is GWT missing? GWT is a toolkit as opposed to a full development framework, and for most projects, it forms the part of a solution rather than the whole solution. Out-of-the-box GWT comes with only a basic set of widgets and lacks a framework to enable the developers to structure larger applications. Fortunately, GWT is both open and extensible and as a result, a range of complementary projects have grown up around it. Ext GWT is one of those projects. What does Ext GWT offer? Ext GWT sets out to build upon the strengths of GWT by enabling the developers to give their users an experience more akin to that of a desktop application. Ext GWT provides the GWT developer with a comprehensive component library similar to that used when developing for desktop environments. In addition to being a component library, powerful features for working with local and remote data are provided. It also features a model view controller framework, which can be used to structure larger applications. How is Ext GWT licensed? Licensing is always an important consideration when choosing technology to use in a project. At the time of writing, Ext GWT is offered with a dual license. The first license is an open source license compatible with the GNU GPL license v3. If you wish to use this license, you do not have to pay a fee for using Ext GWT, but in return you have to make your source code available under an open source license. This means you have to contribute all the source code of your project to the open source community and give everyone the right to modify or redistribute it. If you cannot meet the obligations of the open source license, for example, you are producing a commercial product or simply do not want to share your source code, you have to purchase a commercial license for Ext GWT. It is a good idea to check the current licensing requirements on the Sencha website, http://www.sencha.com, and take that into account when planning your project. Alternatives to Ext GWT Ext GWT is one of the many products produced by the company Sencha. Sencha was previously named Ext JS and started off developing a JavaScript library by the same name. Ext GWT is closely related to the Ext JS product in terms of functionality. Both Ext GWT and Ext JS also share the same look and feel as well as a similar API structure. However, Ext GWT is a native GWT implementation, written almost entirely in Java rather than a wrapper, the JavaScript-based Ext JS. GWT-Ext Before Ext GWT, there was GWT-Ext: http://code.google.com/p/gwt-ext/. This library was developed by Sanjiv Jeevan as a GWT wrapper around an earlier, 2.0.2 version of Ext JS. Being based on Ext JS, it has a very similar look and feel to Ext GWT. However, after the license of Ext JS changed from LGPL to GPL in 2008, active development came to an end. Apart from no longer being developed or supported, developing with GWT-Ext is more difficult than with Ext GWT. This is because the library is a wrapper around JavaScript and the Java debugger cannot help when there is a problem in the JavaScript code. Manual debugging is required. Smart GWT When development of GWT-Ext came to an end, Sanjiv Jeevan started a new project named Smart GWT: http://www.smartclient.com/smartgwt/. This is a LGPL framework that wraps the Smart Client JavaScript library in a similar way that GWT-Ext wraps Ext JS. Smart GWT has the advantage that it is still being actively developed. Being LGPL-licensed, it also can be used commercially without the need to pay the license fee that is required for Ext GWT. Smart GWT still has the debugging problems of GWT-Ext and the components are often regarded not as visually pleasing as Ext GWT. This could be down to personal taste of course. Vaadin Vaadin, http://vaadin.com, is a third alternative to Ext GWT. Vaadin is a server-side framework that uses a set of precompiled GWT components. Although you can write your own components if required, Vaadin is really designed so that you can build applications by combining the ready-made components. In Vaadin the browser client is just a dumb view of the server components and any user interaction is sent to the server for processing much like traditional Java web frameworks. This can be slow depending on the speed of the connection between the client and the server. The main disadvantage of Vaadin is the dependency on the server. GWT or Ext GWT's JavaScript can run in a browser without needing to communicate with a server. This is not possible in Vaadin. Ext GWT or GXT? To avoid confusion with GWT-Ext and to make it easier to write, Ext GWT is commonly abbreviated to GXT. We will use GXT synonymously with Ext GWT throughout the rest of this article. Working with GXT: A different type of web development If you are a web developer coming to GXT or GWT for the first time, it is very important to realize that working with this toolset is not like traditional web development. In traditional web development, most of the work is done on the server and the part the browser plays is li?? le more than a view-making request and receiving responses. When using GWT, especially GXT, at times it is easier if you suspend your web development thinking and think more like a desktop-rich client developer. Java Swing developers, for example, may find themselves at home. How GXT fits into GWT GXT is simply a library that plugs into any GWT project. If we have an existing GWT project setup, all we need to do to use it is: Download the GXT SDK from the Sencha website Add the library to the project and reference it in the GWT configuration Copy a set of resource files to the project If you haven't got a GWT project setup, don't worry. We will now work through getting GXT running from the beginning. Downloading what you need Before we can start working with GXT, we first need to download the toolkit and set up our development environment. Here is the list of what you need to download for running the examples.     Recommended Notes Download from Sun JDK 6 The Java development kit http://java.sun.com/javase/downloads/widget/jdk6.jsp Eclipse IDE for Java EE Developers 3.6 The Eclipse IDE for Java developers, which also includes some useful web development tools http://www.eclipse.org/downloads/ Ext GWT 2.2.0 SDK for GWT 2.0 The GXT SDK itself http://www.sencha.com/products/gwt/download.php Google supplies a useful plugin that integrates GWT into Eclipse. However, there is no reason that you cannot use an alternative development environment, if you prefer. Eclipse setup There are different versions of Eclipse, and although Eclipse for Java EE developers is not strictly required, it contains some useful tools for editing web-specific files such as CSS. These tools will be useful for GXT development, so it is strongly recommended. We will not cover the details of installing Eclipse here, as this is covered more than adequately on the Eclipse website. For that reason, we make the assumption that you already have a fresh installation of Eclipse ready to go. GWT setup You may have noticed that GWT is not included in the list of downloads. This is because since version 2.0.0, GWT has been available within an Eclipse plugin, which we will now set up. Time for action – setting up GWT In Eclipse, select Help Install New Software|. The installation dialog will appear. Click on the Add button to add a new site. Enter the name and location in the respective fields, as shown in the following screenshot, and click on the OK button. Move the mouse over the image to enlarge it. Select Google Plugin for Eclipse from the plugin section and Google Web Toolkit SDK from the SDKs section. Click on Next. The following dialog will appear. Click on Next to proceed. Click on the radio button to accept the license. Click on Finish. Eclipse will now download the Google Web Toolkit and configure the plugin. Restart when prompted. On restarting, if GWT and the Google Eclipse Plugin are installed successfully, you will notice the following three new icons in your toolbar. What just happened? You have now set up GWT in your Eclipse IDE. You are now ready to create GWT applications. However, before we can create GXT applications, there is a bit more work to do.
Read more
  • 0
  • 0
  • 4598

article-image-oracle-apex-plug-ins
Packt
16 Dec 2010
6 min read
Save for later

Oracle APEX Plug-ins

Packt
16 Dec 2010
6 min read
Oracle APEX 4.0 Cookbook Over 80 great recipes to develop and deploy fast, secure, and modern web applications with Oracle Application Express 4.0 Create feature-rich web applications in APEX 4.0 Integrate third-party applications like Google Maps into APEX by using web services Enhance APEX applications by using stylesheets, Plug-ins, Dynamic Actions, AJAX, JavaScript, BI Publisher, and jQuery Hands-on examples to make the most out of the possibilities that APEX has to offer Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible   Introduction In APEX 4.0, Oracle introduced the plug-in. A plug-in is an extension to the existing functionality of APEX. The idea behind plug-ins is to make life easier for developers. Plug-ins are reusable and can be exported and imported. In this way, it is possible to create functionality which is available to all APEX developers. It is also possible to install and use them without having knowledge of what is inside the plug-in. APEX is actually a program that converts your settings from the APEX builder to HTML and JavaScript. For example, if you created a text item in the APEX builder, APEX converts this to the following code (simplified): <input type="text" id="P12_NAME" name="P12_NAME" value="your name"> When you create an item type plug-in, you actually take over this conversion task of APEX and you generate the HTML and JavaScript code yourself by using PL/SQL procedures. That offers a lot of flexibility because now you can make this code generic so that it can be used for more items. The same goes for region type plug-ins. A region is a container for forms, reports, and such. The region can be a div or a HTML table. By creating a region type plug-in, you create a region yourself with the possibility to add more functionality to the region. There are four types of plug-in: Item type plug-ins Region type plug-ins Dynamic action plug-ins Process type plug-ins In this article, we will discuss all four types of plug-in. Creating an item type plug-in In an item type plug-in you create an item with the possibility of extending its functionality. To demonstrate this, we will make a text field with a tooltip. This functionality is already available in APEX 4.0 by adding the following code to the HTML form element attributes text field in the Element section of the text field: onmouseover="toolTip_enable(event,this,'A tooltip')" But you have to do this for every item that should contain a tooltip. This can be made more easy by creating an item type plug-in with a built-in tooltip. And if you create an item of type plug-in, you will be asked to enter some text for the tooltip. Getting ready For this recipe, you can use an existing page with a region where you can put some text items on. How to do it... Go to Shared Components | User Interface | Plug-ins. Click on the Create button. In the name section, enter a name in the name text field. In this case, we enter tooltip. In the internal name text field, enter an internal name. It is advised to use your company's domain address reversed to ensure the name is unique when you decide to share this plug-in. So, for example, you can use com.packtpub.apex.tooltip. In the source section, enter the following code to the PL/SQL code textarea: function render_simple_tooltip ( p_item in apex_plugin.t_page_item , p_plugin in apex_plugin.t_plugin , p_value in varchar2 , p_is_readonly in boolean , p_is_printer_friendly in boolean ) return apex_plugin.t_page_item_render_result is l_result apex_plugin.t_page_item_render_result; begin if apex_application.g_debug then apex_plugin_util.debug_page_item ( p_plugin => p_plugin , p_page_item => p_item , p_value => p_value , p_is_readonly => p_is_readonly , p_is_printer_friendly => p_is_printer_friendly); end if; -- sys.htp.p('<input type="text" id="'||p_item.name||'" name="'||p_item.name||'" class="text_field" onmouseover="toolTip_enable(event,this,'||''''||p_item.attribute_01||''''||')">'); -- return l_result; end render_simple_tooltip; This function uses the sys.htp.p function to put a text item on the screen. On the text item, the onmouseover event calls the function tooltip_enable(). This function is an APEX function and can be used to put a tooltip on an item. The arguments of the function are mandatory. The function starts with the option to show debug information. This can be very useful when you have created a plug-in and it doesn't work. After the debug information the htp.p function puts the text item on the screen, including the call to tooltip_enable. You can also see that the call to tooltip_enable uses p_item.attribute_01. This is a parameter that you can use to pass a value to the plug-in. That is the following step in this recipe. The function ends with the return of l_result. This variable is of type apex_plugin.t_page_item_render_result. For the other types of plug-in there are also dedicated return types, for example, t_region_render_result. Click on the Create button. The next step is to define the parameter (attribute) for this plug-in. In the Custom Attributes section, click the Add Attribute button. In the name section, enter a name in the label text field, for example tooltip. Ensure that the attribute text field contains the value 1. In the settings section, set the type to text. Click on the Create button. In the callbacks section, enter render_simple_tooltip into the render function name text field. Click on the Apply changes button. The plug-in is ready now. The next step is to create an item of type tooltip plug-in. Go to a page with a region where you want to use an item with a tooltip. In the items section, click on the add icon to create a new item. Select Plug-ins. Now you will get a list of available plug-ins. Select the one we just created, tooltip. Click on Next. In the item name text field, enter a name for the item, for example tt_item. In the region select list, select the region you want to put the item in. Click Next. In the next step, you will get a new option. It's the attribute you created with the plug-in. Enter the tooltip text here. Click Next. In the last step, leave everything as it is and click the Create item button. You are ready now. Run the page. When you move your mouse pointer over the new item, you will see the tooltip.
Read more
  • 0
  • 0
  • 3644

article-image-creating-skeleton-apps-coily-spring-python
Packt
16 Dec 2010
3 min read
Save for later

Creating Skeleton Apps with Coily in Spring Python

Packt
16 Dec 2010
3 min read
  Spring Python 1.1 Create powerful and versatile Spring Python applications using pragmatic libraries and useful abstractions   Maximize the use of Spring features in Python and develop impressive Spring Python applications Explore the versatility of Spring Python by integrating it with frameworks, libraries, and tools Discover the non-intrusive Spring way of wiring together Python components Packed with hands-on-examples, case studies, and clear explanations for better understanding          Read more about this book       (For more resources on this subject, see here.) Plugin approach of Coily coily is a Python script designed from the beginning to provide a plugin based platform for building Spring Python apps. Another important feature is version control of the plugins. Developers should not have to worry about installing an out-of-date plugin that was designed for an older version of Spring Python. coily allows different users on a system to have different sets of plugins installed. It also requires no administrative privileges to install a plugin. Key functions of coily coily is included in the standard installation of Spring Python. To see the available commands, just ask for help. The following table elaborates these commands. Required parts of a plugin A coily plugin closely resembles a Python package with some slight tweaks. This doesn't mean that a plugin is meant to be installed as a Python package. It is only a description of the folder structure. Let's look at the layout of the gen-cherrypy-app plugin as an example. Some parts of this layout are required, and other parts are not. The top folder is the name of the plugin. A plugin requires a __init__.py file inside the top directory. __init__.py must include a __description__ variable. This description is shown when we run the coily --help command. __init__.py must include a command function, which is either a create or apply function. create is used when the plugin needs one argument from the user. apply is used when no argument is needed from the user. Let's look at how gen-cherrypy-app meets each of these requirements. We can already see from the diagram that the top level folder has the same name as our plugin. Inside __init__.py, we can see the following help message defined. __description__ = "plugin to create skeleton CherryPy applications" gen-cherrypy-app is used to create a skeleton application. It needs the user to supply the name of the application it will create. Again, looking inside __init__.py, the following method signature can be found. def create(plugin_path, name) plugin_path is an argument provided to gen-cherrypy-app by coily, which points at the base directory of gen-cherrypy-app. This argument is also provided for plug-ins that use the apply command function. name is the name of the application provided by the user.
Read more
  • 0
  • 0
  • 1136

article-image-yui-2x-using-event-component
Packt
14 Dec 2010
7 min read
Save for later

YUI 2.X: Using Event Component

Packt
14 Dec 2010
7 min read
Yahoo! User Interface Library 2.x Cookbook Over 70 simple incredibly effective recipes for taking control of Yahoo! User Interface Library like a Pro Easily develop feature-rich internet applications to interact with the user using various built-in components of YUI library Simple and powerful recipes explaining how to use and implement YUI 2.x components Gain a thorough understanding of the YUI tools Plenty of example code to help you improve your coding and productivity with the YUI Library Hands-on solutions that take a practical approach to recipes In this article, you will learn how to use YUI to handle JavaScript events, what special events YUI has to improve the functionality of some JavaScript events, and how to write custom events for your own application. Using YUI to attach JavaScript event listeners When attaching events in JavaScript most browsers use the addEventListener function , but the developers of IE use a function called attachEvent. Legacy browsers do not support either function, but instead require developers to attach functions directly to element objects using the 'on' + eventName property (for example myElement.onclick=function(){...}). Additionally, the execution context of event callback functions varies depending on how the event listener is attached. The Event component normalizes all the cross-browser issues, fixes the execution context of the callback function, and provides additional event improvements. This recipe will show how to attach JavaScript event listeners, using YUI. How to do it... Attach a click event to an element: var myElement = YAHOO.util.Dom.get('myElementId'); var fnCallback = function(e) { alert("myElementId was clicked"); }; YAHOO.util.Event.addListener(myElement, 'click', fnCallback); Attach a click event to an element by its ID: var fnCallback = function(e) { alert("myElementId was clicked"); }; YAHOO.util.Event.addListener('myElementId','click',fnCallback) Attach a click event to several elements at once: var ids = ["myElementId1", "myElementId2", "myElementId3"]; var fnCallback = function(e) { var targ = YAHOO.util.Event.getTarget(e); alert(targ.id + " was clicked"); }; YAHOO.util.Event.addListener(ids, 'click', fnCallback); When attaching event listeners, you can provide an object as the optional fourth argument, to be passed through as the second argument to the callback function: var myElem = YAHOO.util.Dom.get('myElementId'); var fnCallback = function(e, obj) { alert(obj); }; var obj = "I was passed through."; YAHOO.util.Event.addListener(myElem,'click',fnCallback,obj); When attaching event listeners, you can change the execution context of the callback function to the fourth argument, by passing true as the optional fifth argument: var myElement = YAHOO.util.Dom.get('myElementId'); var fnCallback = function(e) { alert('My execution context was changed.'); }; var ctx = { /* some object to be the execution context of callback */ }; YAHOO.util.Event.addListener( myElement, 'click', fnCallback, ctx, true); How it works... The addListener function wraps the native event handling functions, normalizing the cross- browser differences. When attaching events, YUI calls the correct browser specific function, or defaults to legacy event handlers. Before executing the callback function, the Event component must (in some browsers) find the event object and adjust the execution context of the callback function. The callback function is normalized by wrapping it in a closure function that executes when the browser event fires, thereby allowing YUI to correct the event, before actually executing the callback function. In legacy browsers, which can only have one callback function per event type, YUI attaches a callback function that iterates through the listeners attached by the addListener function There's more... The addListener function returns true if the event listener is attached successfully and false otherwise. If the element to listen on is not available when the addListener function is called, the function will poll the DOM and wait to attach the listener when the element becomes available. Additionally, the Event component also keeps a list of all events that it has attached. This list is maintained to simplify removing events listeners, and so that all event listeners can be removed when the end-user leaves the page. Find all events attached to an element: var listeners = YAHOO.util.Event.getListeners('myElementId'); for (var i=0,j=listeners.length; i<j; i+=1) { var listener = listeners[i]; alert(listener.type); // event type alert(listener.fn); // callback function alert(listener.obj); // second argument of callback alert(listener.adjust); // execution context } Find all events of a certain type attached to an element: // only click listeners var listeners = YAHOO.util.Event.getListeners('myElementId', 'click'); The garbage collector in JavaScript does not always do a good job cleaning up event handlers. When removing nodes from the DOM, remember to remove events you may have added as well. More on YAHOO.util.Event.addListener The addListener function has been aliased by the shorter on function: var myElement = YAHOO.util.Dom.get('myElementId'); var fnCallback = function(e) { alert("myElementId was clicked"); }; YAHOO.util.Event.on(myElement, 'click', fnCallback); By passing an object in as the optional fifth argument of addListener, instead of a Boolean, you can change the execution context of the callback to that object, while still passing in an another object as the optional fourth argument: var myElement = YAHOO.util.Dom.get('myElementId'); var fnCallback = function(e, obj) { // this executes in the context of 'ctx' alert(obj); }; var obj = "I was passed through."; var ctx = { /* some object to be the execution context of callback */ }; YAHOO.util.Event.addListener( myElement,'click',fnCallback,obj, ctx); Lastly, there is an optional Boolean value that can be provided as the sixth argument of addListener, which causes the callback to execute in the event capture phase, instead of the event bubbling phase. You probably won't ever need to set this value to true, but if you want to learn more about JavaScript event phases see: http://www.quirksmode.org/js/events_order.html Event normalization functions The event object, provided as the first argument of the callback function, contains a variety of values that you may need to use (such as the target element, character code, etc.). YUI provides a collection of static functions that normalizes the cross-browser variations of these values. Before trying to use these properties, you should read this recipe, as it walks you through each of those functions. How to do it... Fetch the normalized target element of an event: var fnCallback = function(e) { var targetElement = YAHOO.util.Event.getTarget(e); alert(targetElement.id); }; YAHOO.util.Event.on('myElementId', 'click', fnCallback); Fetch the character code of a key event (also known as the key code): var fnCallback = function(e) { var charCode = YAHOO.util.Event.getCharCode(e); alert(charCode); }; YAHOO.util.Event.on('myElementId', 'keypress', fnCallback); Fetch the x and y coordinates of a mouse event: var fnCallback = function(e) { var x = YAHOO.util.Event.getPageX(e); var y = YAHOO.util.Event.getPageY(e); alert("x-position=" + x + " and x-position= " + y); }; YAHOO.util.Event.on('myElementId', 'click', fnCallback); Fetch both the x and y coordinates of a mouse event, using: var fnCallback = function(e) { var point = YAHOO.util.Event.getXY(e); alert("x-position="+point[0]+" and x-position= "+point[1]); }; YAHOO.util.Event.on('myElementId', 'click', fnCallback); Fetch the normalized related target element of an event: var fnCallback = function(e) { var targetElement = YAHOO.util.Event.getRelatedTarget(e); alert(targetElement.id); }; YAHOO.util.Event.on('myElementId', 'click', fnCallback); Fetch the normalized time of an event: var fnCallback = function(e) { var time = YAHOO.util.Event.getTime(e); alert(time); }; YAHOO.util.Event.on('myElementId', 'click', fnCallback); Stop the default behavior, propagation (bubbling) of an event, or both: var fnCallback = function(e) { // prevents the event from bubbling up to ancestors YAHOO.util.Event.stopPropagation(e); // prevents the event's default YAHOO.util.Event.preventDefault(e); // prevents the event's default behavior and bubbling YAHOO.util.Event.stopEvent(e); }; YAHOO.util.Event.on('myElementId', 'click', fnCallback); How it works... All of these functions test to see if a value exists on the event for each cross-browser variation of a property. The functions then normalize those values and return them. The stopPropogation and preventDefault functions actually modify the equivalent cross-browser property of the event, and delegate the behavior to the browsers.
Read more
  • 0
  • 0
  • 1822
article-image-getting-started-spring-python
Packt
10 Dec 2010
12 min read
Save for later

Getting started with Spring Python

Packt
10 Dec 2010
12 min read
Spring Python for Python developers You have already picked one of the most popular and technically powerful dynamic languages to develop software, Python. Spring Python makes it even easier to solve common problems encountered by Python developers every day. Exploring Spring Python's non-invasive nature Spring Python has a non-invasive nature, which means it is easy to adopt the parts that meet your needs, without rewriting huge blocks of code. For example, Pyro (http://pyro.sourceforge.net) is a 3rd party library that provides an easy way to make remote procedure calls. In order to demonstrate the Spring way of non-invasiveness, let's code a simple service, publish it as a web service using Pyro's API, and then publish it using Spring Python's wrapper around Pyro. This will show the difference in how Spring Python simplifies API access for us, and how it makes the 3rd party library easier to use without as much rework to our own code. First, let's write a simple service that parses out the parameters from a web request string: class ParamParser(object): def parse_web_parms(self, parm): return [tuple(p.split("=")) for p in parm.split("&")] Now we can write a simple, functional piece of code that uses our service in order to have a working version. parser = ParamParser() parser.parse_web_parms("pages=5&article=Spring_Python") This is just instantiating the ParamParser and accessing the function. To make this a useful internet service, it needs to be instantiated on a central server and should be configured to listen for calls from clients. The next step is to advertise it as a web service using the API of Pyro. This will make it reachable by multiple Pyro clients. To do this, we define a daemon which will host our service on port 9000 and initialize it. daemon = Pyro.core.Daemon(host="localhost", port="9000") Pyro.core.initServer() Next, we create a Pyro object instance to act as proxy to our service as well as an instance of our ParamParser. We configure the proxy to delegate all method calls to our service. pyro_proxy = Pyro.core.ObjBase() parser = ParamParser() pyro_proxy.delegateTo(parser) Finally, we register the pyro_proxy object with the daemon, and startup a listen-dispatch loop so that it's ready to handle requests: daemon.connect(pyro_proxy, "mywebservice") daemon.requestLoop(True) When we run this server code, an instance of our ParamParser will be created and advertised at PYROLOC://localhost:9000/mywebservice. To make this service complete, we need to create a Pyro client that will call into our service. The proxy seamlessly transfers Python objects over the wire using the Pyro library, in this case the tuple of request parameters. url_base = "PYROLOC://localhost:9000" client_proxy = Pyro.core.getProxyForURI( url_base + "/mywebservice") print client_proxy.parse_web_parms( "pages=5&article=Spring_Python") The Pyro library is easy to use. One key factor is how our ParamParser never gets tightly coupled to the Pyro machinery used to serve it to remote clients. However, it's very invasive. What if we had already developed a simple application on a single machine with lots of methods making use of our utility? In order to convert our application into a client-server application, we would have to rewrite it to use the Pyro client proxy pattern everywhere that it was called. If we miss any instances, we will have bugs that need to be cleaned up. If we had written automated tests, they would also have to be rewritten as well. Converting a simple, one-machine application into a multi-node application can quickly generate a lot of work. That is where Spring Python comes in. It provides a different way of creating objects which makes it easy for us to replace a local object with a remoting mechanism such as Pyro. Let's utilize Spring Python's container to create our parser and also to serve it up with Pyro. from springpython.config import PythonConfig from springpython.config import Object from springpython.remoting.pyro import PyroServiceExporter from springpython.remoting.pyro import PyroProxyFactory class WebServiceContainer(PythonConfig): def __init__(self): super(WebServiceContainer, self).__init__() @Object(lazy_init=True) def my_web_server(self): return PyroServiceExporter(service=ParamParser(), service_name="mywebservice", service_port=9000) @Object(lazy_init=True) def my_web_client(self): myService = PyroProxyFactory() myService.service_url="PYROLOC://localhost:9000/mywebservice" return myService With this container definition, it is easy to write both a server application as well as a client application. To spin up one instance of our Pyro server, we use the following code: from springpython.context import ApplicationContext container = ApplicationContext(WebServiceContainer()) container.get_object("my_web_server") The client application looks very similar. from springpython.context import ApplicationContext container = ApplicationContext(WebServiceContainer()) myService = container.get_object("my_web_client") myService.parse_web_parms("pages=5&article=Spring_Python") The Spring Python container works by containing all the definitions for creating key objects. We create an instance of the container, ask it for a specific object, and then use it. This easily looks like just as much (if not more) code than using the Pyro API directly. So why is it considered less invasive? Looking at the last block of code, we can see that we are no longer creating the parser or the Pyro proxy. Instead, we are relying on the container to create it for us. The Spring Python container decouples the creation of our parser, whether its for a local application, or if it uses Pyro to join them remotely. The server application doesn't know that it is being exported as a Pyro service, because all that information is stored in the WebServiceContainer. Any changes made to the container definition aren't seen by the server application code. The same can be said for the client. By putting creation of the client inside the container, we don't have to know whether we are getting an instance of our service or a proxy. This means that additional changes can be made inside the definition of the container of Spring Python, without impacting our client and server apps. This makes it easy to split the server and client calls into separate scripts to be run in separate instances of Python or on separate nodes in our enterprise. This demonstrates how it is possible to mix in remoting to our existing application. By using this pattern of delegating creation of key objects to the container, it is easy to start with simple object creation, and then layer on useful services such as remoting. Later in this book, we will also see how this makes it easy to add other services like transactions and security. Due to Spring Python's open ended design, we can easily create new services and add them on without having to alter the original framework. Adding in some useful templates In addition to the non-invasive ability to mix in services, Spring Python has several utilities that ease the usage of low level APIs through a template pattern. The template pattern involves capturing a logical flow of steps. What occurs at each step is customizable by the developer, while still maintaining the same overall sequence. One example where a template would be useful is for writing a SQL query. Coding SQL queries by hand using Python's database API (http://www.python.org/dev/peps/pep-0249) is very tedious. We must properly handle errors and harvest the results. The extra code involved with connecting things together and handling issues is commonly referred to as plumbing code. Let's look at the following code to see how Python's database API functions. The more plumbing code we have to maintain, the higher the cost. Having an application with dozens or hundreds of queries can become unwieldy, even cost prohibitive to maintain. Using Python's database API, we only have to write the following code once for setup. ### One time setup import MySQLdb conn = MySQLdb.connection(username="me", password"secret", hostname="localhost", db="springpython") Now let's use Python's database API to perform a single query. ### Repeated for every query cursor = conn.cursor() results = [] try: cursor.execute("""select title, air_date, episode_number, writer from tv_shows where name = %s""", ("Monty Python",)) for row in cursor.fetchall(): tvShow = TvShow(title=row[0], airDate=row[1], episodeNumber=row[2], writer=row[3]) results.append(tvShow) finally: try: cursor.close() except Exception: pass conn.close() return results   The specialized code we wrote to look up TV shows is contained in the execute statement and also the part that creates an instance of TvShow. The rest is just plumbing code needed to handle errors, manage the database cursor, and iterate over the results.   This may not look like much, but have you ever developed an application with just one SQL query? We could have dozens or even hundreds of queries, and having to repeatedly code these steps can become overwhelming. Spring Python's DatabaseTemplate lets us just inject the query string and and a row mapper to reduce the total amount of code that we need to write. We need a slightly different setup than before. """One time setup""" from springpython.database.core import * from springpython.database.factory import * connectionFactory = MySQLConnectionFactory(username="me", password="secret", hostname="localhost", db="springpython") We also need to define a mapping to generate our TvShow objects. class TvShowMapper(RowMapper): def map_row(self, row, metadata=None): return TvShow(title=row[0], airDate=row[1], episodeNumber=row[2], writer=row[3]) With all this setup, we can now create an instance of DatabaseTemplate and use it to execute the same query with a much lower footprint. dt = DatabaseTemplate(connectionFactory) """Repeated for each query""" results = dt.query("""select title, air_date, episode_number, writer from tv_shows where name = %s""", ("Monty Python",), TvShowMapper()) This example shows how we can replace 19 lines of code with a single statement using Spring Python's template solution. Object Relational Mappers (ORMs) have sprung up in response to the low level nature of ANSI SQL's protocol. Many applications have simple object persistence requirements and many of us would prefer working on code, and not database design. By having a tool to help do the schema management work, these ORMs have been a great productivity boost. But they are not necessarily the answer for every use case. Some queries are very complex and involve looking up information spread between many tables, or involve making complex calculations and involve decoding specific values. Also, many legacy systems are denormalized and don't fit the paradigm that ORMs were originally designed to handle. The complexity of these queries can require working around, or even against, the ORM-based solutions, making them not worth the effort. To alleviate the frustration of working with SQL, Spring Python's DatabaseTemplate greatly simplifies writing SQL, while giving you complete freedom in mapping the results into objects, dictionaries, and tuples. DatabaseTemplate can easily augment your application, whether or not you are already using an ORM. That way, simple object persistence can be managed with ORM, while complex queries can be handed over to Spring Python's DatabaseTemplate, resulting in a nice blend of productive, functional code. Other templates, such as TransactionTemplate, relieve you of the burden of dealing with the low level idioms needed to code transactions that makes them challenging to incorporate correctly. Later in this book, we will learn how easy it is to add transactions to our code both programmatically and declaratively. Applying the services you need and abstracting away low level APIs is a key part of the Spring way and lets us focus our time and effort on our customer's business requirements instead of our own technical ones. By using the various components we just looked at, it isn't too hard to develop a simple Pyro service that serves up TV shows from a relational database. from springpython.database.factory import * from springpython.config import * from springpython.remoting.pyro import * class TvShowMapper(RowMapper): def map_row(self, row, metadata=None): return (title=row[0], airDate=row[1], episodeNumber=row[2], writer=row[3]) class TvShowService(object): def __init__(self): self.connFactory = MySQLConnectionFactory(username="me", password="secret", hostname="localhost", db="springpython") self.dt = DatabaseTemplate(connFactory) def get_tv_shows(self): return dt.query("""select title, air_date, episode_number, writer from tv_shows where name = %s""", ("Monty Python",), TvShowMapper()) class TvShowContainer(PythonConfig): def __init__(self): super(TvShowContainer, self).__init__() @Object(lazy_init=True) def web_server(self): return PyroServiceExporter(service=TvShowService(), service_name="tvshows", service_port=9000) @Object(lazy_init=True) def web_client(self): myService = PyroProxyFactory() myService.service_url="PYROLOC://localhost:9000/tvshows" return myService if __name__ == "__main__": container = ApplicationContext(TvShowContainer()) container.get_object("web_server") By querying the database for TV shows and serving it up through Pyro, this block of code demonstrates how easy it is to use these powerful modules without mixing them together. It is much easier to maintain software over time when things are kept simple and separated. We just took a quick walk through SQL and Pyro and examined their low level APIs. Many low level APIs require a certain sequence of steps to properly utilize them. We just looked at a SQL query. The need for templates also exists with database transactions and LDAP calls. By capturing the flow of the API in a Spring Python template and allowing you to insert your custom code, you can get out of writing plumbing code and instead work on your application's business logic.
Read more
  • 0
  • 0
  • 5366

article-image-tips-tricks-ext-js-3x
Packt
30 Nov 2010
3 min read
Save for later

Tips & Tricks for Ext JS 3.x

Packt
30 Nov 2010
3 min read
  Learning Ext JS 3.2 Build dynamic, desktop-style user interfaces for your data-driven web applications using Ext JS Learn to build consistent, attractive web interfaces with the framework components Integrate your existing data and web services with Ext JS data support Enhance your JavaScript skills by using Ext's DOM and AJAX helpers Extend Ext JS through custom components An interactive tutorial packed with loads of example code and illustrative screenshots           Read more about this book       (For more resources on Ext JS, see here.) Objective: Button focus and tab orders are built in. Tip: Button focus and tab orders are built into Ext JS Components. For the MessageBox Component, the OK or Yes button will be the default action, so pressing Enter on our keyboard when a MessageBox appears will trigger that button, and pressing Tab will move us through the buttons and other items in the MessageBox. Windows have the ESC key mapped to the Close tool. When using button bars in other Componenets, tabbing through the buttons is enabled by default and in Toolbars like the PagingToolbar tabbing is also built in. Objective: Duplicate Component ID's must be avoided. Tip: Having duplicate IDs in our document can lead to strange behavior, such as a widgets always showing up in the upper-left corner of the browser, and must therefore be avoided. Objective: Other uses of Button config on a MessageBox. Tip: The buttons config for a MessageBox can also specify the text to display on the button. Instead of passing a Boolean value, just pass it the desired text to display, for example, {yes: 'Maybe'}. Objective: Ext does not require any pre-existing markup. Tip: Ext does not require any pre-existing markup for it to function, this is because it generates everything it needs on its own. This let's us start with a very simple HTML document containing an empty body. Objective: Avoid using the built in JavaScript alert messages. Tip: Standard JavaScript alert messages pause code execution, which can cause unexpected results. You should not be using the built in JavaScript alert messages, and instead use Ext's MessageBox widget or console messages (when available), which does not pause that code execution. Objective: Creating form Field validation types (vType). Tip: A search of the Ext JS forum is likely to come back with a vType that someone else has created with exactly what you need, or close enough to use as a starting point for your own requirements, so search the Ext JS Forums before trying to write your own. Objective: Simple and quick static options for a ComboBox. Tip:; A quick way to specify a few static options for a ComboBox is to pass an array to the store config, which will auto-create the store for you. So if we wanted a ComboBox that had 'Yes' and 'No' as options, we would provide ['Yes','No'] as the store config value.
Read more
  • 0
  • 0
  • 1811

article-image-portal-and-drag-and-drop-features-ext-gwt
Packt
29 Nov 2010
5 min read
Save for later

Portal and Drag-and-Drop Features of Ext GWT

Packt
29 Nov 2010
5 min read
  Ext GWT 2.0: Beginner's Guide Portlet class The Portlet class extends ContentPanel to provide a special type of panel that can be repositioned in the Viewport by the user with a Portal container. It may appear similar to a window in a desktop application. Creating a Portlet is similar to creating other containers. This code: Portlet portlet = new Portlet(); portlet.setHeight(150); portlet.setHeading("Example Portlet"); creates a Portlet like this: A Portlet can be excluded from being repositioned by pinning it using: portal.setPinned(true); Apart from that, a Portlet inherits all the features of a standard ContentPanel. The Portal class A Portal is a special container for Portlet components. In fact, it is a Container containing a collection of LayoutContainer components arranged using ColumnLayout. Each of those LayoutContainer components in turn is able to contain Portlet components, arranged using a RowLayout. Portal also supports dragging and dropping of Portlet components, both in terms of changing the row it is in within a column and the column within the Portal. When creating a Portal, we need to set the number of columns the Portal should create in the constructor. We also need to set the widths of each column before using the setColumnWidth method of the Portal. So to create a Portal with two columns, (one using 30 percent of the width and the second 70 percent) we would define it as follows: Portal portal = new Portal(2); portal.setColumnWidth(0, 0.3); portal.setColumnWidth(1, 0.7); We can then add a Portlet to each column like this: Portlet portlet1 = new Portlet(); portlet1.setHeight(150); portlet1.setHeading("Example Portlet 1"); portal.add(portlet1, 0); Portlet portlet2 = new Portlet(); portlet2.setHeight(150); portlet2.setHeading("Example Portlet 2"); portal.add(portlet2, 1); This will produce the following output: Both Portlet components can be dragged and dropped into different positions. The Portlet turns into a blue box while being dragged as shown in the following screenshot: A Portlet will automatically resize and ft into the column in which it is dropped, as seen in the next screenshot: ToolButton Like ContentPanel that Portlet extends, we can add ToolButton components to the header. These can be very useful for making a Portlet look and behave even more like windows in a desktop application. portlet.getHeader().addTool(new ToolButton("x-tool-minimize")); portlet.getHeader().addTool(new ToolButton("x-tool-maximize")); portlet.getHeader().addTool(new ToolButton("x-tool-close")); The output can be seen as shown in the following screenshot: At the moment, we are using ContentPanel components in our example application and laying them out using a BorderLayout. We shall now see that it does not take much to change the ContentPanel components into Portlet components and manage them using a Portal. Portlet components are ideally suited to being independent, self-contained user interface elements that respond to the data passed to them. Rather than tying them into a Portal directly, we can use the MVC components to cause the Portal to respond to the creation of a new Portlet to preserve that independence. Time for action – creating a Portal Controller and a Portlet View The first thing we need to do is add a new EventType to the existing AppEvents class named NewPortletCreated. We will fire this when we create a new Portlet. public static final EventType NewPortletCreated = new EventType(); Create a new class named PortalController that extends Controller. public class PortalController extends Controller { Create a new class named PortalView that extends View. public class PortalView extends View { Create a constructor that sets the Controller of the PortalView. public PortalView(PortalController portalController) { super(portalController); } Returning to PortalController, create a variable to hold the PortalView and override the initialize method to set the view. private PortalView portalView; @Override public void initialize() { super.initialize(); portalView = new PortalView(this); } Create a constructor that registers each EventType the PortalController should observe, specifically NewPortletCreated creation and Error. public PortalController() { registerEventTypes(AppEvents.NewPortletCreated ); registerEventTypes(AppEvents.Error); } Override the handleEvent method to forward any events to the View apart from errors which for the time being we will just log to the GWT log. @Override public void handleEvent(AppEvent event) { EventType eventType = event.getType(); if (eventType.equals(AppEvents.error)) { GWT.log("Error", (Throwable) event.getData()); } else { forwardToView(portalView, event); } } Returning to PortalView, create a new portal field consisting of a Portal component with two columns. private final Portal portal = new Portal(2); Override the initialize method to set the width of the two columns, the first to 30 percent of the width of the Portal and the second to 70 percent. @Override protected void initialize() { portal.setColumnWidth(0, 0.3); portal.setColumnWidth(1, 0.7); } Now create a Viewport, set the layout to FitLayout, add the Portal, and then add the Viewport to GWT's RootPanel. @Override protected void initialize() { portal.setColumnWidth(0, 0.3); portal.setColumnWidth(1, 0.7); final Viewport viewport = new Viewport(); viewport.setLayout(new FitLayout()); viewport.add(portal); RootPanel.get().add(viewport); } We also need to implement the handleEvent method of the View. For now, we will catch the NewPortletCreated event, but we will not do anything with it yet. @Override protected void handleEvent(AppEvent event) { EventType eventType = event.getType(); if (eventType.equals(AppEvents.NewPortletCreated )) { } } Finally, go to the onModuleLoad method of the EntryPoint RSSReader class and instead of creating an AppController, create a PortalController, and remove the line that forwards an Init AppEvent, as we will not be using it. The onModuleLoad method will now look like this: public void onModuleLoad() { final FeedServiceAsync feedService = GWT.create(FeedService.class); Registry.register(RSSReaderConstants.FEED_SERVICE, feedService); Dispatcher dispatcher = Dispatcher.get(); dispatcher.addController(new PortalController()); } What just happened? We created the basic framework for a Portal layout of our application. However, if we started it now, we would just get a blank screen. What we need to do is add Portlet components. The actual Portlet components are not too complicated. They will just act as wrappers.
Read more
  • 0
  • 0
  • 1432
article-image-google-web-toolkit-2-creating-page-layout
Packt
24 Nov 2010
7 min read
Save for later

Google Web Toolkit 2: Creating Page Layout

Packt
24 Nov 2010
7 min read
Google Web Toolkit 2 Application Development Cookbook Over 70 simple but incredibly effective practical recipes to develop web applications using GWT with JPA , MySQL and i Report Create impressive, complex browser-based web applications with GWT 2 Learn the most effective ways to create reports with parameters, variables, and subreports using iReport Create Swing-like web-based GUIs using the Ext GWT class library Develop applications using browser quirks, Javascript,HTML scriplets from scratch Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible   The layout will be as shown in the diagram below: Creating the home page layout class This recipe creates a panel to place the menu bar, banner, sidebars, footer, and the main application layout. Ext GWT provides several options to define the top-level layout of the application. We will use the BorderLayout function. We will add the actual widgets after the layout is fully defined. The other recipes add the menu bar, banner, sidebars, and footers each, one-by-one. Getting ready Open the Sales Processing System project. How to do it... Let's list the steps required to complete the task. Go to File | New File. Select Java from Categories, and Java Class from File Types. Click on Next. Enter HomePage as the Class Name, and com.packtpub.client as Package. Click on Finish. Inherit the class ContentPanel. Press Ctrl + Shift + I to import the package automatically. Add a default constructor: package com.packtpub.client; import com.extjs.gxt.ui.client.widget.ContentPanel; public class HomePage extends ContentPanel { public HomePage() { } } Write the code of the following steps in this constructor. Set the size in pixels for the content panel: setSize(980,630); Hide the header: setHeaderVisible(false); Create a BorderLayout instance and set it for the content panel: BorderLayout layout = new BorderLayout(); setLayout(layout); Create a BorderLayoutData instance and configure it to be used for the menu bar and toolbar: BorderLayoutData menuBarToolBarLayoutData= new BorderLayoutData(LayoutRegion.NORTH, 55); menuBarToolBarLayoutData.setMargins(new Margins(5)); Create a BorderLayoutData instance and configure it to be used for the left-hand sidebar: BorderLayoutData leftSidebarLayoutData = new BorderLayoutData(LayoutRegion.WEST, 150); leftSidebarLayoutData.setSplit(true); leftSidebarLayoutData.setCollapsible(true); leftSidebarLayoutData.setMargins(new Margins(0, 5, 0, 5)); Create a BorderLayoutData instance and configure it to be used for the main contents, at the center: BorderLayoutData mainContentsLayoutData = new BorderLayoutData(LayoutRegion.CENTER); mainContentsLayoutData.setMargins(new Margins(0)); Create a BorderLayoutData instance and configure it to be used for the right-hand sidebar: BorderLayoutData rightSidebarLayoutData = new BorderLayoutData(LayoutRegion.EAST, 150); rightSidebarLayoutData.setSplit(true); rightSidebarLayoutData.setCollapsible(true); rightSidebarLayoutData.setMargins(new Margins(0, 5, 0, 5)); Create a BorderLayoutData instance and configure it to be used for the footer: BorderLayoutData footerLayoutData = new BorderLayoutData(LayoutRegion.SOUTH, 20); footerLayoutData.setMargins(new Margins(5)); How it works... Let's now learn how these steps allow us to complete the task of designing the application for the home page layout. The full page (home page) is actually a "content panel" that covers the entire area of the host page. The content panel is a container having top and bottom components along with separate header, footer, and body sections. Therefore, the content panel is a perfect building block for application-oriented user interfaces. In this example, we will place the banner at the top of the content panel. The body section of the content panel is further subdivided into five regions in order to place these—the menu bar and toolbar at the top, two sidebars on each side, a footer at the bottom, and a large area at the center to place the contents like forms, reports, and so on. A BorderLayout instance lays out the container into five regions, namely, north, south, east, west, and center. By using BorderLayout as the layout of the content panel, we will get five places to add five components. BorderLayoutData is used to specify layout parameters of each region of the container that has BorderLayout as the layout. We have created five instances of BorderLayoutData, to be used in the five regions of the container. There's more... Now, let's talk about some general information that is relevant to this recipe. Setting the size of the panel The setSize method is used to set the size for a panel. Any one of the two overloaded setSize methods can be used. A method has two int parameters, namely, width and height. The other one takes the same arguments as string. Showing or hiding header in the content panel Each content panel has built-in headers, which are visible by default. To hide the header, we can invoke the setHeaderVisible method, giving false as the argument, as shown in the preceding example. BorderLayoutData BorderLayoutData is used to set the layout parameters, such as margin, size, maximum size, minimum size, collapsibility, floatability, split bar, and so on for a region in a border panel. Consider the following line of code in the example we just saw: BorderLayoutData leftSidebarLayoutData = new BorderLayoutData(LayoutRegion.WEST, 150) It creates a variable leftSidebarLayoutData, where the size is 150 pixels and the region is the west of the border panel. rightSidebarLayoutData.setSplit(true) sets a split bar between this region and its neighbors. The split bar allows the user to resize the region. leftSidebarLayoutData.setCollapsible(true) makes the component collapsible, that is, the user will be able to collapse and expand the region. leftSidebarLayoutData.setMargins(new Margins(0, 5, 0, 5)) sets a margin where 0, 5, 0, and 5 are the top, right, bottom, and left margins, respectively. Classes and packages In the preceding example, some classes are used from Ext GWT library, as shown in the following table: ClassPackageBorderLayoutcom.extjs.gxt.ui.client.widget.layoutBorderLayoutDatacom.extjs.gxt.ui.client.widget.layoutContentPanelcom.extjs.gxt.ui.client.widgetMarginscom.extjs.gxt.ui.client.utilStylecom.extjs.gxt.ui.client See also The Adding the banner recipe The Adding menus recipe The Creating the left-hand sidebar recipe The Creating the right-hand sidebar recipe The Creating main content panel recipe The Creating the footer recipe The Using HomePage instance in EntryPoint recipe Adding the banner This recipe will create a method that we will use to add a banner in the content panel. Getting ready Place the banner image banner.png at the location webresourcesimages. You can use your own image or get it from the code sample provided on the Packt Publishing website (www.packtpub.com). How to do it... Create the method getBanner: public ContentPanel getBanner() { ContentPanel bannerPanel = new ContentPanel(); bannerPanel.setHeaderVisible(false); bannerPanel.add(new Image("resources/images/banner.png")); Image("resources/images/banner.png")); return bannerPanel; } Call the method setTopComponent of the ContentPanel class in the following constructor: setTopComponent(getBanner()); How it works... The method getBanner() creates an instance bannerPanel of type ContentPanel. The bannerPanel will just show the image from the location resources/images/banner.png. That's why, the header is made invisible by invoking setHeaderVisible(false). Instance of the com.google.gwt.user.client.ui.Image class, which represents the banner image, is added in the bannerPanel. In the default constructor of the HomePage class, the method setTopComponent(getBanner()) is called to set the image as the top component of the content panel. See also The Creating the home page layout class recipe The Adding menus recipe The Creating the left-hand sidebar recipe The Creating the right-hand sidebar recipe The Creating main content panel recipe The Creating the footer recipe The Using HomePage instance in EntryPoint recipe  
Read more
  • 0
  • 0
  • 1930

article-image-jquery-user-interface-plugins-tooltip-plugins
Packt
27 Oct 2010
6 min read
Save for later

jQuery User Interface Plugins: Tooltip Plugins

Packt
27 Oct 2010
6 min read
  jQuery Plugin Development Beginner's Guide Build powerful, interactive plugins to implement jQuery in the best way possible Utilize jQuery's plugin framework to create a wide range of useful jQuery plugins from scratch Understand development patterns and best practices and move up the ladder to master plugin development Discover the ins and outs of some of the most popular jQuery plugins in action A Beginner's Guide packed with examples and step-by-step instructions to quickly get your hands dirty in developing high quality jQuery plugins         Read more about this book       (For more resources on jQuery, see here.) Before we get started, there is another little thing worth mentioning: provide many different opportunities to introduce new concepts and ideas, even while keeping the complexity of the whole plugin at a minimum. We can now go on to create our plugin, starting with basic functionalities, and subsequently adjusting its goals. We will add new, improved functionalities that, however, do not make the whole code look too difficult to understand—even after some time or for someone who's just starting out with jQuery. Tooltip plugins in general A lot has been said about tooltip plugins, but it's worth repeating the most important points with particular regard to the way tooltips are supposed to work, and how we want our tooltip to behave. First of all, we might want to get an idea of what tooltips look like and a sample of what we will accomplish by the end of this article. Here is an example: Also, with some more work and proper application of effects, images, and other relatively advanced techniques, we can also obtain something more complex and nicer looking, thus giving the user the chance to specify the style and behavior for the tooltip, as follows: The idea is actually very simple. The elements we have selected will trigger an event every time we hover the mouse pointer over them. The tooltip will then pop out, right at the mouse cursor position, retrieving the text portion from the title attribute of the said element. Finally, whenever we move the mouse over the same element, the plugin will move and follow the mouse cursor until it goes off the boundaries of the element. Positioning the tooltip The first problem we have to face is, of course, how to make the tooltip appear in the right position. It would be no trouble at all if we just had to make some text, image, or anything else show up. We've done it many times and it's no problem at all—just make their positioning absolute and set the right top and side distances. However, we need to take into account the fact that we don't know exactly where the mouse cursor might be and, as such, we need to calculate distances based upon the mouse cursor position itself. So, how can we do it? It's simple enough; we can use some of the JavaScript event properties to obtain the position. Unfortunately, Internet Explorer always tries to put a spoke in our wheel. In fact, the magnificent browser does not (according to this table, which is quite accurate: http://www.quirksmode.org/dom/w3c_cssom.html#mousepos) support pageX and pageY, which would normally return the mouse coordinates relative to the document. So we need to think about a workaround for Internet Explorer, as jQuery (from version 1.0.4 onwards) does not normalize some of the event properties according to W3C standards (http://api.jquery.com/category/events/event-object/). The following diagram (also provided in the " target="_blank">code bundle) should clarify what the visible viewport is (that is, the browser window—the red box): Whenever we scroll down, different parts of the document (blue) are shown through the browser window and hidden due to space constraints. The scroll height (green) is the part of the document currently not displayed. Custom jQuery selectors Suppose we have a page with some text written in, which also contains a few links to both internal pages (that is, pages on the same server) and external websites. We are presented with different choices in terms of which elements to apply the tooltip to (referring to links as an example, but they apply to any kind of element as well), as follows: All the links All the links with a specific class (for example, tooltip) All the links with the title attribute not empty All the links pointing to internal pages All the links pointing to external websites Combinations of the above We can easily combine the first three conditions with the others (and with themselves) using CSS selectors appropriately. For example: $("a"), all the links $("a.tooltip"), links having a tooltip class $("a[title]"), links with a title attribute (still have to check if empty) $("a.tooltip[title]"), links with a tooltip class and a title attribute As for internal and external pages, we have to work with jQuery selectors instead. Time for action – creating custom jQuery selectors Although jQuery makes it easy to select elements using standard CSS selectors, as well as some other selectors, jQuery's own selectors are the ones that help the developer to write and read code. Examples of custom selectors are :odd, :animated, and so on. jQuery also lets you create your own selectors! The syntax is as follows: // definition$.expr[':'].customselector = function(object, index,properties, list) { // code goes here};// call$("a:customselector") The parameters are all optional except for the first one (of course!), which is required to perform some basic stuff on the selected object: object: Reference to current HTML DOM element (not jQuery, beware!) index: Zero-based loop index within array properties: Array of metadata about the selector (the 4th argument contains the string passed to the jQuery selector) list: Array of DOM elements to loop through The return value can be either: true: Include current element false: Exclude current element Our selector (for external links detection) will then look, very simply, like the following code: $.expr[':'].external = function(object) { if(object.hostname) // is defined return(object.hostname != location.hostname); else return false;}; Also note that, to access the jQuery object, we have to use the following (since object refers to the DOM element only!): $.expr[':'].sample = function(object) { alert('$(obj).attr(): ' + $(object).attr("href") + 'obj.href: ' + object.href);}; Merging pieces together We have slowly created different parts of the plugin, which we need to merge in order to create a working piece of code that actually makes tooltips visible. So far we have understood how positioning works and how we can easily place an element in a determined position. Also, we have found out we can create our own jQuery selectors, and have developed a simple yet useful custom selector with which we are able to select links pointing to either internal or external pages. It needs to be placed at the top of the code, inside the closure, as we will make use of the dollar symbol ($) and it may conflict with other software.
Read more
  • 0
  • 0
  • 1835