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
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials

7019 Articles
article-image-managing-image-content-joomla
Packt
23 Feb 2010
3 min read
Save for later

Managing Image Content in Joomla!

Packt
23 Feb 2010
3 min read
Creating image galleries and slideshows Joomla! is a Content Management System designed primarily for organizing and managing website content. It contains numerous multimedia features built into it, but its main focus is providing two roles: Powerful CMS features, and a well-designed framework which allows additional features to be added to the system, thus creating powerful functionality. These additional features are called Extensions and are designed to plug in to the core Joomla! Framework and extend the functionality of it. With regards to the core Joomla! CMS, we have already looked at how images can be included into content items and modules. However, image galleries and slideshows are asking a bit more than just simple image management, and so require the power of extensions to provide these features: The number of multimedia extensions now available for Joomla! is staggering. We have extensions which can create complex galleries, stream in videos, and compile jukebox type audio features. Having considered at great length the best approach has resulted in one option. That is to highlight some of the most popular and useful image gallery and slideshow extensions, and hope that these will provide understanding as to the complex image management capability that can be achieved by using Joomla! Extensions. Image management extensions, and how to install them Before proceeding with covering third-party extension functionality, let's quickly cover how image extensions are added to your Joomla! site. As with most things in Joomla!, the process of installing extensions has had careful consideration from the development team, and is a very easy to perform. Most Joomla! Extensions come with their own installation instructions, and these general guidelines will help you get them installed on your site. Before installing anything, make sure you copy your file set and backup your site database. For the purpose of this example, I am going to install one of my favorite Joomla! Multimedia Extensions—the RokBox extension by RocketTheme. RokBox is a MooTools powered slideshow plugin that enables you to display numerous media formats with a professional pop-up screen lightbox effect: The installation steps are as follows: Download the required extension and save this download on your computer. The file will be in a .zip format, or possibly a .gzip or .tgz format which may require unzipping before installation: Log into your Joomla! Administrator's Control Panel, and navigate to the Extensions menu, then to Extension Manager. The page will default to the Install screen: Browse your computer for the extension .zip file using the Choose File button on this page and once the file is located, use the Upload File & Install button. The Joomla! Installation Manager will perform all of the work and if your extension has been built correctly, the installer will place all files and documents into their correct directories: An installation success message will show to inform you that the extension has been successfully installed. Some extensions success text may contain additional links to configuration pages for the extension.
Read more
  • 0
  • 0
  • 6073

article-image-ajax-and-connection-manager-yahoo-user-interface-yui
Packt
22 Feb 2010
9 min read
Save for later

AJAX and Connection Manager with Yahoo User Interface (YUI)

Packt
22 Feb 2010
9 min read
As far as web interface design techniques are concerned, AJAX is definitely the way to go. The term AJAX has been part of the mainstream development community's vocabulary since early 2005, yet AJAX reinvented existing technologies as something new and exciting, and paved the way to a better, more attractive, and interactive web (sometimes referred to loosely as web 2.0) where web applications feel much more like desktop applications. The very first JavaScript libraries sprang into existence as a means of abstracting away the differences in AJAX implementation between platforms, thereby allowing developers to focus on the important things in web design instead of worrying about compatibility issues. The result in many cases is a quick and easy way for developers to cut down on the amount of code they are required to produce, and a better more interactive experience for end users and website visitors. The Connection Manager—A Special Introduction The Connection Manager utility is by no means the smallest, most light-weight component included with the YUI, but it's certainly not the largest either, yet it packs so much functionality into just 12Kb (for the –min version). Connection Manager provides a fast and reliable means of accessing server-side resources, such as PHP or ASP scripts and handling the response. A series of supporting objects manage the different stages of any asynchronous transactions, whilst providing additional functionality where necessary. Connection is one of just a few of the utilities that are supported by a single class; this makes looking up its methods nice and straight-forward. It also doesn't have any properties at all (although the objects that it creates all have their own members which hold various pieces of information), which makes using it even easier! This utility is what is known as a singleton utility, which means that there can only be one live instance of the utility at any one time, differing from many of the other components of the library. Don't worry though, this doesn't restrict you to only making one request; Connection will manage as many separate requests as you need. Because this utility is a singleton, there are important considerations that advanced coders may want to take note of. Unlike some of the other library components, Connection cannot be subclassed—all of its class's members are static, meaning that they won't be picked up when using the YAHOO global .extend() method. It wraps up the cross-browser creation of the XMLHttpRequest (XHR) object, as well as a simple to use object-based method of accessing the server response and any associated data, into a simple package which handles the request from start to finish. This requires minimal input from you, the developer, saving time as well as effort. Another object created by Connection is the response object, which is created once the transaction has completed. The response object gives you access via its members to a rich set of data including the id of the transaction, the HTTP status code and status message, and either the responseText and responseXML members depending on the format of the data returned. Like most of the other library components, Connection Manager provides a series of global custom events that can be used to hook into key moments during any transaction. We'll look at these events in more detail later on in the article but rest assured, there are events marking the start and completion of transactions, as well as success, failure, and abort events. The Connection utility has been a part of the YUI since its second public release (the 0.9.0 release) and has seen considerable bug fixing and refinement since this time. This makes it one of the more reliable and better documented utilities available. Connection is such a useful utility that it's used by several other library components in order to obtain data from remote sources. Other components that make use of Connection Manager include the AutoComplete control, DataTable, DataSource, and Tabview. It is one of the only library components not dependant on the DOM utility. All it requires are the YAHOO global utility and the Event utility. That doesn't mean that you can't include a reference to the DOM utility, however, to make use of its excellent DOM manipulation convenience methods. The XMLHttpRequest Object Interface When working with the Connection utility you'll never be required to manually create or access an XHR object directly. Instead, you talk to the utility and this works with the object for you using whichever code is appropriate for the browser in use. This means that you don't need separate methods of creating an XHR object in order to keep each browser happy. A transaction describes the complete process of making a request to the server and receiving and processing the response. Connection Manager handles transactions from beginning to end, providing different services at different points during a request. Transactions are initiated using the .asyncRequest() method which acts as a constructor for the connection object. The method takes several arguments: the first specifies the HTTP method that the transaction should use, the second specifies the URL of your server-side script while the third allows you to add a reference to a callback object. A fourth, optional, argument can also be used to specify a POST message if the HTTP method is set to use POST giving you an easy means of sending data to the server as well as retrieving it. This is rarely required however, even when using the POST method, as we shall see later in the article. It's also very easy to build in query string parameters if these are required to obtain the data that you are making the request for. It can be hard coded into a variable and then passed in as the second argument of the Connection constructor instead of setting the second argument manually within the constructor. Connection Manager takes these arguments and uses them to set up the XHR object that will be used for the transaction on your behalf. Once this has been done, and Connection has made the request, you then need to define a new object yourself that will allow you to react to a range of responses from the server. A Closer Look at the Response Object I briefly mentioned the response object that is created by the utility automatically once a transaction has completed, let's now take a slightly more in-depth view at this object. It will be created after any transaction, whether or not it was considered a success. The callback functions you define to handle successful or failed transactions (which we'll examine in more detail very shortly) are automatically passed to the response object as an argument. Accessing it is extremely easy and requires no additional intervention from yourself. If the transaction fails, this object gives you access to the HTTP failure code and HTTP status message which are received from the server. Examining these two members of the response object can highlight what happened to make the request fail, making it integral to any Connection implementation. If the transaction was a success, these two members will still be populated but with a success code and status message, and additional members such as responseText or responseXML will also contain data for you to manipulate. If you need to obtain the HTTP response headers sent by the server as part of the response, these can be obtained using either the getResponseHeader collection, or the getAllResponseHeaders member. In the case of file uploads, some of these members will not be available via the response object. File uploads are the one type of transaction that do not make use of the XHR object at all, so the HTTP code and status message members cannot be used. Similarly, there will not be either a textual or XML-based response when uploading files. Managing the Response with a Callback Object In order to successfully negotiate the response from the server, a literal callback object should be defined which allows you to deal quickly and easily with the information returned whether it is a success, failure, or another category of response. Each member of this object invokes a callback function or performs some other action relevant to your implementation. These members can be one of several types including another object, a function call or even a string or integer depending on the requirements of your application. The most common members you would use in your callback object would usually be based upon success and failure function calls to handle these basic response types, with each member calling its associated function when a particular HTTP response code is received by the response object. It's also very easy to add an additional member to this object which allows you to include data which may be useful when processing the response form the server. In this situation, the argument object member can be used and can take a string, a number, an object, or an array. Other optional members include a customevents handler to deal with custom, per-transaction events as opposed to the global events that are available to any and all transactions, a scope object used to set the scope of your handler functions, and a timeout count used to set the wait time before Connection aborts the transaction and assumes failure. The remaining member of the callback object is the upload handler which is of course a special handler to deal specifically with file uploads. As I already mentioned, the response object will be missing success of failure details when dealing with file uploads, however, you can still define a callback function to be executed once the upload transaction has completed.
Read more
  • 0
  • 0
  • 2364

article-image-introduction-php-nuke
Packt
22 Feb 2010
6 min read
Save for later

An Introduction to PHP-Nuke

Packt
22 Feb 2010
6 min read
This is the first article of the series in which we will cover the introduction to PHP-Nuke. PHP-Nuke is a free tool to manage the content of dynamic websites. To be more specific, PHP-Nuke is an open-source content management system. In fact, you could say it is 'the' open-source content management system. Since it is vastly popular, a number of other similar systems have sprung from it, and even similar systems based around very different technologies that owe nothing to it in terms of code have added 'Nuke' to their name as homage. Although the first paragraph conveys something of the history and grandeur of PHP-Nuke, it doesn't answer the basic question of what it can actually do for you. PHP-Nuke allows you to create a dynamic, community-driven website with minimum effort and programming knowledge. To get the most out of PHP-Nuke, a knowledge of web development will prove to be useful, but even then, PHP-Nuke is written in the PHP scripting language (as can be deduced from the name), which is probably the most popular and straightforward language for creating websites and web applications. The first PHP-Nuke release in June 2000 was created by a developer named Francisco Burzi to power his site, Linux Preview. Since then, PHP-Nuke has evolved under his guidance to the system it is today. PHP-Nuke is truly one of the Internet's legendary applications. In this article, we will take our first look at PHP-Nuke, understand what it can do, find out where to go for further resources, and briefly discuss the site we will create in this article series. What PHP-Nuke Can Do for You PHP-Nuke is ideal for creating community-driven websites. The 'community' part of 'community-driven' means that the site is geared towards a particular group of people with similar interests. Maybe this community is concerned with wine making, flowers, programming, zombie films, or even dinosaurs. Maybe the community is actually a group of customers of a particular product. Of course, we are talking about an online community here. Whatever the community is into, the site can be structured to hold information relevant to the members; maybe it will be news stories about a forthcoming zombie film, links to other zombie sites, reviews, or synopses of other zombie films. The 'driven' part of 'community-driven' suggests that the information available on this site can be extended or enhanced by the members of the community. Members of the community may be able to shape what is on the site by posting comments, contributing or rating stories, and participating in discussions. After all, communities are made up of people, and people have views and opinions, and often like to express them! This is exactly what PHP-Nuke enables. More than being just a website, a PHP-Nuke site provides a rich and interactive environment for its visitors. The best bit is, you don't have to be an expert programmer to achieve all this. With only rudimentary knowledge of HTML, you can engineer a unique-looking PHP-Nuke website. The Visitor Experience The standard installation of PHP-Nuke provides many features for its visitors. Some of them are: Searchable news articles, organized into topics Ability of visitors to create an account on the site, and log in to their own personal area Ability of visitors to rate articles, and create discussions about them Straw polls and surveys Ability of visitors to submit their own stories to be published on the site An encyclopedia, in other words, a collection of entries organized alphabetically A catalog of web links or downloadable files Discussion forums Ability of visitors to select their own look for the site from a list of different 'themes' RSS syndication of your articles to share your content with other sites This is not a complete list either. And these are only some of the features that come with the standard installation. PHP-Nuke is a modular system; it can be customized and extended, and there is a huge range of third-party customizations and extensions to be found on the Internet. Any of these can add to the range of features your site provides. The Management Experience As a potential 'manager' of a PHP-Nuke site, as you read through the list of features above you may think they sound rather attractive, but you might also wonder how you will handle all of that. PHP-Nuke provides a web-based management interface. You, as the manager of the site, visit the site and log in with a special super user, or site administrator, account. After this, from the comfort of your web browser, you run the show: You can add new information, and edit, delete, or move existing pieces of information. You can approve articles submitted by the user to be shown on the site. You can decide the features of the site. You can control what is displayed on the pages. You can control who is able to see what. What Exactly is PHP-Nuke? PHP-Nuke is a collection of PHP scripts that run on a web server, connect to a database, and display the retrieved data in a systematic way. In other words, PHP-Nuke is a data-driven PHP web application. PHP-Nuke can be downloaded for free, and then installed to your local machine for testing and development. The files and the database can be uploaded to a web hosting service, so that your site will be available to anyone on the Internet. There are even web hosting services that offer PHP-Nuke installation at the click of a button. Modular Structure PHP-Nuke is built around a 'core' set of functions, which perform mundane tasks such as selecting what part of the application the user should be shown, checking who the user is, and what they can do on the site. The thing that makes PHP-Nuke exciting to the world is the set of modules that comes with it. These modules provide the real functionality of the site, and include ones for news and article management, downloads, and forums, among others. The modules can be switched on and off with ease, and other modules can be added to the system. There is no shortage of third-party modules on the Internet, and you can find a PHP-Nuke module for almost any imaginable purpose. Themed Interface The look of a PHP-Nuke site is controlled by a theme. This is a collection of images, colors, and other resources, and instructions that determine the layout of the page. A new theme can be selected, and your site will be transformed immediately. Visitors with a user account on the site are able to select their own personal theme. Multi-Lingual Interface PHP-Nuke comes with many language files. These contain translations of standard elements on the site interface. The availability of these translations reflects the international nature of the PHP-Nuke community. PHP-Nuke as an Open-Source Content Management System We used the expression 'open-source content management system' earlier in the article to describe PHP-Nuke. Let's take a closer a look at this term.
Read more
  • 0
  • 24
  • 14122

article-image-installing-php-nuke
Packt
22 Feb 2010
10 min read
Save for later

Installing PHP-Nuke

Packt
22 Feb 2010
10 min read
The steps to install and configure PHP-Nuke are simple: Download and extract the PHP-Nuke files. Download and apply ChatServ's patches. Create the database for PHP-Nuke. Create a database user, and fill the database with data. Make some simple changes to the PHP-Nuke configuration file. Copy the PHP-Nuke files to the document root of the web server. Test it out! Let's get started. Downloading PHP-Nuke The latest version of PHP-Nuke can be downloaded at phpnuke.org downloads page: http://www.phpnuke.org/modules.php?name=Downloads&d_op=viewdownload&cid=1 You can also obtain older versions of PHP-Nuke, including version 1.0, from SourceForge: http://sourceforge.net/project/showfiles.php?group_id=7511&package_id=7622 SourceForge is the world's largest home of open-source projects. Many projects use SourceForge's facilities to host and maintain their projects. You can find almost anything you want on SourceForge—whether it is in a usable state or has been updated recently is another matter. Extracting PHP-Nuke Once you have downloaded PHP-Nuke, you should extract the contents of the PHP-Nuke ZIP archive to the root of your c: drive. You will have to create a folder called PHP-Nuke-7.8 in the root of your c: drive. (If you extract the files elsewhere, create the folder PHP-Nuke-7.8 and copy the contents of the main unzipped folder to this new folder). If you don't have a tool for extracting the files, you can download an evaluation edition (or buy a full edition) of WinZip from www.winzip.com. There are also free, powerful, extracting tools such as ZipGenius (http://www.zipgenius.it/index_eng.htm) and 7-Zip (http://sourceforge.net/projects/sevenzip/) among others. In the PHP-Nuke-7.8 folder, you will find three subfolders called html, sql, and upgrades. The upgrades folder contains scripts that handle upgrading the database between different versions, the sql folder contains the definition of the PHP-Nuke database that we will be working with, and the html folder contains the guts of your PHP-Nuke installation. The html folder contains all the PHP scripts, HTML files, images, CSS stylesheets, and so on that drive PHP-Nuke. Within the html folder are further subfolders; some of these include: modules: Contains the modules that make up your PHP-Nuke site. Modules are the essence of PHP-Nuke's operation; we look at them from article Your First Page onwards. blocks: Contains PHP-Nuke's blocks. Blocks are 'mini-functionality' units and usually provide snippet views of modules. We will look at blocks in article Managing the Site. language: Contains PHP-Nuke language files. These allow the language of PHP-Nuke's interface to be changed. images: Contains images used in the display of the PHP-Nuke site. themes: Contains the themes for PHP-Nuke. The use of themes allows you to completely change the look of a PHP-Nuke site with a click of a button. includes, db: Contain code to support the running of PHP-Nuke. The db folder, for example, contains database access code. admin: Contains code to power the administration area of your site. Downloading the Patches No software is without its flaws, and PHP-Nuke is no exception. After a release, the large user community invariably finds problems and potential security holes. Furthermore, PHP-Nuke also contains features such as its forum, which is in fact the phpBB application specially modified to work with PHP-Nuke. phpBB itself is updated on a regular basis to correct critical security vulnerabilities or to fix other problems, and consequently the corresponding part of PHP-Nuke also needs to be updated. Rather than releasing a new version of PHP-Nuke for these situations, patches for its various parts are released. ChatServ's patches from www.nukeresources.com are mostly concerned with variable validation, in other words, making sure that the variables used in the application are of the right type for storing in the database. This has been an area of weakness with many earlier versions of PHP-Nuke. The patches are often incorporated into subsequent versions of PHP-Nuke so that each new version becomes more robust. Note that you don't have to apply the patches, and PHP-Nuke will still work without them. However, by applying them you will have taken a good step towards improving the security of your site. If you navigate to http://www.nukeresources.com, there is a handy menu on the front page to access the patches: To obtain the patch corresponding to your version, click the link and you will be taken to the relevant file (of course, www.nukeresources is a PHP-Nuke powered site!). Click on the Nuke 7.8 link to go to the Downloads page of www.nukeresources.com. On this page, clicking the Download this file Now! link will download the patches for PHP-Nuke 7.8. The name of this file will be of the form 78patched.tar.gz. This is a GZIP compressed file that contains all the patches that we are about to apply. The GZIP file can be extracted with WinZip, or any of the other utilities we discussed earlier. The patches are simply modified versions of the original PHP-Nuke files. The original files have been modified to address various security issues that may have been identified since the initial release, or maybe since the last version of the patch. Applying the Patches To apply the patches, first we need to extract the 78patched.tar.gz file. We will extract the files into a folder called patches that we will create in the PHP-Nuke-7.8 folder. After extracting the files, copy the contents of the patches folder to your html folder. Do not copy the patches folder, copy its contents. The patches folder contains files that replace the files in the default installation, and you get a Confirm File Replace window. Select Yes for all the files, and when the copying is complete, your installation is ready to go. We have performed this patching immediately after installing PHP-Nuke, but we could have done this at any time. Doing it at this point is more sensible as it means that we are working on the most secure version of PHP-Nuke. Also, the patch process we have described here overwrites existing PHP-Nuke installation files. If you have modified these files, then the changes will be lost on applying the patch. Thus applying the patches later without disturbing any of your changes becomes more demanding. There is one further thing to watch for after applying the patches. You may find that the patched files have had their permissions set to read-only, and that you are unable to modify the files. To modify the files (and we do have to modify at least the config.php file in this article) you will need to remove this setting. You can do this on Windows by right-clicking on the file, selecting Properties from the menu, unchecking the Read-only setting, and clicking the OK button: We've done almost all the work with the files that we need to; now we turn our attention to creating and populating PHP-Nuke's database. Preparing the PHP-Nuke Database We'll be using the phpMyAdmin tool to do our database work. phpMyAdmin is part of the XAMPP installation (detailed in Appendix A), or can be downloaded from www.phpmyadmin.net, if you don't already have it. phpMyAdmin provides a powerful web interface for working with your MySQL databases. First of all, open your browser and navigate to http://localhost/phpmyadmin/, or whatever the location of your phpMyAdmin installation is: Creating the Database We need to create an empty database for PHP-Nuke to hold all the data about our site. To do this, we simply enter a name for our database into the Create new database textbox: We will call our database nuke. Enter this, and click the Create button. The name you give doesn't particularly matter, as long as it is not the name of some already existing database. If you try to use the same name as an already existing database, phpMyAdmin will inform you of this, and no action will be taken. The exact name isn't particularly important at this point because there is another configuration step coming up, which requires us to tell PHP-Nuke the name of the database we've created for it. After clicking Create, the screen will reload and you will be notified of the successful creation of your database: Creating a Database User Before we start populating the database, we will create a database user that can access only the PHP-Nuke database. This user is not a human, but will be used by PHP-Nuke to connect to the database while it performs its data-handling activities. The advantage of creating a database user is that it adds an extra level of security to our installation. PHP-Nuke will be able to work with data only in this database of the MySQL server, and no other. Also, PHP-Nuke will be restricted in the operations it can perform on the tables in the database. We will need to create a username for this boxed-in user to access the nuke database. Let's call our user nuker and go with the password nukepassword. However, in order to add an extra level of security we will introduce some digits into nukepassword, and some other slight twists, to strengthen it, and so use the word No0kPassv0rd as our database user password. To create the database user, click the SQL tab, and enter the following into the Run SQL query/queries on database textbox: GRANT ALL PRIVILEGES ON nuke.* TO nuker@localhost IDENTIFIED BY 'No0kPassv0rd' WITH GRANT OPTION Your screen should look like this: Click the Go button, and the database user will be created: Populating the Database Now we are ready to fill our database with data for PHP-Nuke. This doesn't mean we start typing the data in ourselves; the data comes with the PHP-Nuke installation. This data is found in a file called nuke.sql in the sql folder of the PHP-Nuke installation. This file contains a number of SQL statements that define the tables within the database and also fill them with 'raw' data for the site. However, before we fill the database with the tables from this file, we need to make a modification to this file. By default, the name of each database table in PHP-Nuke begins with nuke_. For example, there is a table with the name nuke_stories that holds information about stories, and a table called nuke_topics that holds information about story topics. These are just two of the tables; there are more than 90 in the standard installation. The word nuke_ is a 'table prefix', and is used to ensure that there are no clashes between the names of PHP-Nuke's tables and tables from another application in the same database, since the rest of the table name is descriptive of the data stored in the table, and other applications may have similarly named tables. What this does mean is that unless this table prefix is changed, the table names in your PHP-Nuke database will be known to anyone attempting to hack your site. Many of the typical attacks used to damage PHP-Nuke are based around the fact that the names of the tables in the database powering a PHP-Nuke site are known. By changing the table prefix to something less obvious, you have taken another step to making your site more secure.
Read more
  • 0
  • 8
  • 41236

article-image-jquery-14-dom-manipulation-methods-replacement-copying-and-removal
Packt
19 Feb 2010
5 min read
Save for later

jQuery 1.4 DOM Manipulation Methods for Replacement, Copying and Removal

Packt
19 Feb 2010
5 min read
DOM replacement These methods are used to remove content from the DOM and replace it with new content. .html() (getter) Get the HTML contents of the first element in the set of matched elements. .html() Parameters None Return value A string containing the HTML representation of the element. Description This method is not available on XML documents. In an HTML document, we can use .html() to get the contents of any element. If our selector expression matches more than one element, only the first one's HTML content is returned. Consider the following code: $('div.demo-container').html(); In order for the content of the following <div> to be retrieved, it would have to be the first one in the document. <div class="demo-container"> <div class="demo-box">Demonstration Box</div></div> The result would look like this: <div class="demo-box">Demonstration Box</div> .html() (setter) Set the HTML contents of each element in the set of matched elements. .html(htmlString).html(function) Parameters (first version) htmlString: A string of HTML to set as the content of each matched element Parameters (second version) function: A function returning the HTML content to set Return value The jQuery object, for chaining purposes. Description The .html() method is not available in XML documents. When we use .html() to set the content of elements, any content that was in those elements is completely replaced by the new content. Consider the following HTML code: <div class="demo-container"> <div class="demo-box">Demonstration Box</div></div> We can set the HTML contents of <div class="demo-conta iner"> as follows: $('div.demo-container').html('<p>All new content. <em>You bet!</em></p>'); That line of code will replace everything inside <div class="demo-container">. <div class="demo-container"> <p>All new content. <em>You bet!</em></p></div> As of jQuery 1.4, the .html() method allows us to set the HTML content by passing in a function. $('div.demo-container').html(function() { var emph = '<em>' + $('p').length + ' paragraphs!</em>'; return '<p>All new content for ' + emph + '</p>';}); Given a document with six paragraphs, this example will set the HTML of <div class="demo-container"> to <p>All new content for <em>6 paragraphs!</em></p>. .text() (getter) Get the combined text contents of each element in the set of matched elements, including their descendants. .text() Parameters None Return value A string containing the combined text contents of the matched elements. Description Unlike the .html() method, .text() can be used in both XML and HTML documents. The result of the .text() method is a string containing the combined text of all matched elements. Consider the following HTML code: <div class="demo-container"> <div class="demo-box">Demonstration Box</div> <ul> <li>list item 1</li> <li>list <strong>item</strong> 2</li> </ul></div> The code $('div.demo-container').text() would produce the following result: Demonstration Box list item 1 list item 2 .text() (setter) Set the content of each element in the set of matched elements to the specified text. .text(textString).text(function) Parameters (first version) textString: A string of text to set as the content of each matched element Parameters (second version) function: A function returning the text to set as the content Return value The jQuery object, for chaining purposes. Description Unlike the .html() method, .text() can be used in both XML and HTML documents. We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents (such as &lt; for <). Consider the following HTML code: <div class="demo-container"> <div class="demo-box">Demonstration Box</div> <ul> <li>list item 1</li> <li>list <strong>item</strong> 2</li> </ul></div> The code $('div.demo-container').text('<p>This is a test.</p>'); will produce the following DOM output: <div class="demo-container"> &lt;p&gt;This is a test.&lt;/p&gt;</div> It will appear on a rendered page as though the tags were exposed as follows: <p>This is a test</p> As of jQuery 1.4, the .text() method allows us to set the text content by passing in a function. $('ul li').text(function() {return 'item number ' + ($(this).index() + 1);}); Given an unordered list with three <li> elements, this example will produce the following DOM output: <ul><li>item number 1</li><li>item number 2</li><li>item number 3</li></ul>
Read more
  • 0
  • 0
  • 2063

article-image-build-your-own-application-access-twitter-using-java-and-netbeans-part-2
Packt
19 Feb 2010
17 min read
Save for later

Build your own Application to access Twitter using Java and NetBeans: Part 2

Packt
19 Feb 2010
17 min read
In this tutorial, we’ll develop the simple Java application further to add some more functions. Now that we can connect to our Twitter account via the Twitter4J API, it would be nice to use a login dialog instead of hard-coding our Twitter username and password in the Java application. But before we start to build our enhanced SwingAndTweet application, let me show you how it will look like once we finish all the exercises in this part of the tutorial: And now, let the show begin… Creating a Login dialog for our SwingAndTweet application Open your NetBeans IDE along with your SwingAndTweet project, and make sure you’re in the Design View. Go to the Palette window and locate the Dialog component under the Swing Windows section; then drag and drop it anywhere inside the SwingAndTweetUI JFrame component: A JDialog will be added automatically to your SwingAndTweet application, and it will show up in the Component Inspector tab located at the lower-left part of the screen, under Other Components: Right-click on the jDialog1 component in the Inspector tab and select Change Variable Name… from the pop-up menu. The Rename dialog will show up next. Type twitterLogin in the New Name field and press Enter to change the dialog’s name. Now you can start adding text fields, labels and buttons to your twitterLogin dialog. Double-click on the twitterLogin component under the Inspector tab. The twitterLogin dialog will show up empty in the Design Editor window. Use the Palette window to add two JLabels, one JTextField, one JPasswordField and two JButtons to the twitterLogin dialog. Arrange these controls as shown below: Now let’s change the names of the JTextField control, the JPasswordField control and the two JButton controls, so we can easily identify them within your SwingAndTweet application’s code. Right-click on the first text field (jLabel2), select Change Variable Name… from the pop-up menu and replace the text field’s name with txtUsername. Do the same with the other fields; use txtPassword for the JPasswordField control, btnLogin for the Login button and btnExit for the Exit button. And now the last touch. Right-click anywhere inside the twitterLogin dialog, being careful not to right-click inside any of the controls, and select the Properties option from the pop-up menu. The twitterLogin [JDialog] – Properties dialog will appear next. Locate the title property, double-click on the null value and type Twitter Login to replace it. Next, scroll down the properties list until you find the modal property; click on its checkbox to enable it and then click on Close to save your changes. Basically, in the previous exercise we added all the Swing controls you’re going to need to type your username and password, so you can connect to your Twitter account. The twitterLogin dialog is going to take care of the login process for your SwingAndTweet application. We replaced the default names for the JTextField, the JPasswordField and the two JButton controls because it will be easier to identify them during the coding process of the application. On step 8 we used the Properties window of the twitterLogin dialog to change the title property and give your dialog a decent title. We also enabled the modal property on step 9, so you can’t just close the dialog and jump right to the SwingAndTweetUI main window; you’ll have to enter a valid Twitter username and password combination for that. Invoking the Login dialog Ok, now we have a good-looking dialog called twitterLogin. The next step is to invoke it before our main SwingAndTweet JFrame component shows up, so we need to insert some code inside the SwingAndTweetUI() constructor method. Click on the Source button of the Editor window to change to the Source View: Now locate the SwingAndTweetUI() constructor, and type the following lines right after the initComponents(); line: int loginWidth = twitterLogin.getPreferredSize().width; int loginHeight = twitterLogin.getPreferredSize().height; twitterLogin.setBounds(0,0,loginWidth,loginHeight); twitterLogin.setVisible(true); The code inside the SwingAndTweetUI() constructor method shall now look like this: To see your new twitterLogin dialog in action, press F6 or select Run | Run Project to run your SwingAndTweetUI application. The twitterLogin dialog will pop right up. You’ll be able to type in your username and password, but since we haven’t added any functionality yet, the buttons won’t do anything right now. Click on the Close (X) button to close the dialog window and the SwingAndTweetUI main window will appear next. Click on its Close (X) button to exit your Twitter Java application. Now let’s take a look at the code we added to your twitterLogin dialog. On the first line, int loginWidth = twitterLogin.getPreferredSize().width; we declare an integer variable named loginWidth, and assign to it the preferred width of the twitterLogin dialog. The getPreferredSize method retrieves the value of the preferredSize property from the twitterLogin dialog through the .width field. On the second line, int loginHeight = twitterLogin.getPreferredSize().height; we declare another integer variable named loginHeight, and assign to it the preferred height of the twitterLogin dialog. This time, the getPreferredSize() method retrieves the value of the preferredWidth property from the twitterLogin dialog through the .height field. On the next line, twitterLogin.setBounds(0,0,loginWidth,loginHeight); we use the setBounds method to set the x,y coordinates where the dialog should appear on the screen, along with its corresponding width and height. The first two parameters are for the x,y coordinates; in this case, x=0 and y=0, which means the twitterLogin dialog will show up at the upper-left part of the screen. The last two parameters receive the value of the loginWidth and loginHeight variables to establish the twitterLogin dialog’s width and height, respectively. The last line, twitterLogin.setVisible(true); makes the twitterLogin dialog appear on the screen. And since the modal property of this dialog is enabled, once it shows up on the screen it won’t let you do anything else with your SwingAndTweet1 application until you close it up or enter a valid Twitter username and password, as we’ll see in the next exercise. Adding functionality to the twitterLogin dialog Now your twitterLogin dialog is ready to roll! Basically, it won’t let you go to the SwingAndTweet main window until you’ve entered a valid Twitter username and password. And for doing that, we’re going to use the same login code from Build your own Application to access Twitter using Java and NetBeans: Part 1 of this article series. Go to the end of your SwingAndTweetUI application source code and locate the // Variables declaration – do not modify line. Below this line, you’ll see all the variables used in your application: the btnExit and btnLogin buttons, the text fields from your twitterLogin dialog and your SwingAndTweetUI main window, etc. Add the following line just below the // End of variables declaration line:     Twitter twitter; Now click on the Design button to change to the Design View: You’ll see the twitterLogin dialog again –in case you don’t, double-click on the twitterLogin component under the Inspector tab. Now double-click on the Login button to go back to the Code View. The btnLoginActionPerformed method will show up next. Add the following code inside this method: try { twitter = new Twitter(txtUsername.getText(), String.valueOf(txtPassword.getPassword())); twitter.verifyCredentials(); JOptionPane.showMessageDialog(null, "You're logged in!"); twitterLogin.dispose(); } catch (TwitterException e) { JOptionPane.showMessageDialog (null, "Login failed"); } Make sure you write each line on its own, to avoid errors. The btnLoginActionPerformed method shall look like this: Now you’re ready to test your twitterLogin dialog. Press F6 to run your application. The Twitter Login dialog will show up next. Type your Twitter username and password, and then click on the OK button. If the username and password are correct, the You’re logged in! dialog will show up and you’ll be able to go to the SwingAndTweetUI main window. If they’re not correct, the Login failed dialog will appear instead and, after you click on the OK button, you’ll return to the twitterLogin dialog until you type a correct Twitter username and password combination. To exit your SwingAndTweetUI application, click on the Close(X) button of the twitterLogin dialog and then on the Close(X) button of the SwingAndTweetUI window. You’ll be taken back to the NetBeans IDE. Click on the Design button to go back to the Design View, and double-click on the Exit button to open the btnExitActionPerformed method. Type System.exit(0); inside the btnExitActionPerformed method, as shown below: Now go back to the Design View again, right-click anywhere inside the twitterLogin dialog (just be careful not to right-click over any of the dialog’s controls) and select the Events | Window | windowClosing option from the pop-up menu: NetBeans will change to Code View automatically and you’ll be inside the twitterLoginWindowClosing method. Type System.exit(0); inside this method, as shown below: Now run your application to test the new functionality in your loginTwitter dialog. You’ll be able to exit the SwingAndTweet application when clicking on the Exit or Close(X) buttons, and you’ll be able to go to your application’s main window if you type a correct Twitter username and password combination. You can close your SwingAndTweet application now. And now, let’s examine what we just accomplished. First you added the Twitter twitter; line to your application code. With this line we’re declaring a Twitter object named twitter, and it will be available throughout all the application code. On step 4, you added some lines of code to the btnLoginActionPerformed method; this code will be executed every time you click on the Login button from the twitterLogin dialog. All the code is enclosed in a try block, so that if an error occurs during the login process, a TwitterException will be thrown and the code inside the catch block will execute. The first line inside the try block is twitter = new Twitter(txtUsername.getText(),String.valueOf(txtPassword.getPassword())); This code creates the twitter object that we’re going to use throughout the application. It uses the text value you entered in the txtUsername and txtPassword fields to log into your Twitter account. The next line, twitter.verifyCredentials(); checks to see if the username and password provided to the twitter object are correct; if that’s true, a message dialog box shows up in the screen with the You’re logged in! message and the rest of the code executes once you click on the OK button of this message dialog; otherwise, the code in the catch block executes and a message dialog shows up in the screen with the Login failed message, and the twitterLogin dialog keeps waiting for you to type a correct username and password combination. The next line in the sequence, JOptionPane.showMessageDialog(null, "You're logged in!"); shows the message dialog that we talked about before, and the last line inside the try block, twitterLogin.dispose(); makes the twitterLogin dialog disappear from the screen once you’ve logged into your Twitter account successfully. The only line of code inside the catch block is JOptionPane.showMessageDialog (null, "Login failed"); This line executes when there’s an error in the Twitter login process; it shows the Login failed message in the screen and waits for you to press the OK button. On step 9 we added one line of code to the btnExitActionPerformed method: System.exit(0); This line closes your SwingAndTweet application whenever you click on the Exit button. Finally, on steps 10-12 we added another System.exit(0); line to the twitterLoginWindowClosing method, to close your SwingAndTweet application whenever you click on the Close(X) button of the twitterLogin dialog. Showing your Twitter timeline right after logging in Now let’s see some real Twitter action! The following exercise will show you how to show your most recent tweets inside a text area. Click on the Design button to go to the Design View; then double-click on the [JFrame] component under the Inspector tab to show the SwingAndTweetUI dialog in the Design View window: The SwingAndTweet frame will show the three controls we created during Build your own Application to access Twitter using Java and NetBeans: Part 1. Replace the My Last Tweet text in the JLabel control with the What’s happening text. Then right-click on the JTextField control and select the Change Variable Name… option from the pop-up menu, to change its name from jTextField1 to txtUpdateStatus. Now do the same with the JButton control. Right-click on it and select the Change Variable Name… option from the pop-up menu to change its name from jButton1 to btnUpdateStatus. Right-click on the same button again, but this time select the Edit Text option from the pop-up menu and replace the Login text with Update. Rearrange the three controls as per the following screenshot (you’ll need to make the SwingAndTweet container wider): Now drag a JTextArea control from the Palette window and drop it inside the SwingAndTweetUI container. Resize the text area so it fills up the rest of the container, as shown below: Double-click on the Update button to open the btnUpdateStatusActionPerformed method. The first thing you’ll notice is that it’s not empty; this is because this used to be the old Login button, remember? Now just replace all the code inside this method, as shown below: private void btnUpdateStatusActionPerformed(java.awt.event.ActionEvent evt) { try { if (txtUpdateStatus.getText().isEmpty()) JOptionPane.showMessageDialog (null, "You must write something!"); else { twitter.updateStatus(txtUpdateStatus.getText()); jTextArea1.setText(null); java.util.List<Status> statusList = twitter.getUserTimeline(); for (int i=0; i<statusList.size(); i++) { jTextArea1.append(String.valueOf(statusList.get(i).getText())+"n"); jTextArea1.append("-----------------------------n"); } } } catch (TwitterException e) { JOptionPane.showMessageDialog (null, "A Twitter Error ocurred!"); } txtUpdateStatus.setText(""); jTextArea1.updateUI(); The next step is to modify your btnLoginActionPerformed method; we need to add several lines of code to show your Twitter timeline. The complete method is shown below (the lines you need to add are shown in bold): private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) { try { twitter = new Twitter(txtUsername.getText(), String.valueOf(txtPassword.getPassword())); twitter.verifyCredentials(); // JOptionPane.showMessageDialog(null, "You're logged in!"); java.util.List<Status> statusList = twitter.getUserTimeline(); for (int i=0; i<statusList.size(); i++) { jTextArea1.append(String.valueOf(statusList.get(i).getText())+"n"); jTextArea1.append("-----------------------------n"); } twitterLogin.dispose(); } catch (TwitterException e) { JOptionPane.showMessageDialog (null, "Login failed"); } jTextArea1.updateUI(); } Once you have added all the necessary code in each button’s actionPerformed method, press F6 to run the SwingAndTweet application and check if all things work as intended. If you type a message in the txtUpdateStatus text field and then click on the Update button, the timeline information inside the JTextArea1 control will change to reflect your new Twitter status: You can close your SwingAndTweet application now. That was cool, right? Now you have a much better-looking Twitter client! And you can update your status, too! Let’s examine the code we added in this last exercise… private void btnUpdateStatusActionPerformed(java.awt.event.ActionEvent evt) { try { if (txtUpdateStatus.getText().isEmpty()) JOptionPane.showMessageDialog (null, "You must write something!"); else { twitter.updateStatus(txtUpdateStatus.getText()); jTextArea1.setText(null); java.util.List<Status> statusList = twitter.getUserTimeline(); for (int i=0; i<statusList.size(); i++) { jTextArea1.append(String.valueOf(statusList.get(i).getText())+"n"); jTextArea1.append("-----------------------------n"); } } } catch (TwitterException e) { JOptionPane.showMessageDialog (null, "A Twitter Error ocurred!"); } txtUpdateStatus.setText(""); jTextArea1.updateUI(); On step 7 we added some code to the btnUpdateStatusActionPerformed method. This code will execute whenever you click on the Update button to update your Twitter status. First, let’s look at the code inside the try block. The first two lines, if (txtUpdateStatus.getText().isEmpty()) JOptionPane.showMessageDialog (null, "You must write something!"); are the first part of a simple if-else statement that checks to see if you’ve written something inside the txtUpdateStatus text field; if it’s empty, a message dialog will show the You must write something! message on the screen, and then it will wait for you to click on the OK button. If the txtUpdateStatus text field is not empty, the code inside the else block will execute instead of showing up the message dialog. The next part of the code is the else block. The first line inside this block, twitter.updateStatus(txtUpdateStatus.getText()); updates your twitter status with the text you wrote in the txtUpdateStatus text field; if an error occurs at this point, a TwitterException is thrown and the program execution will jump to the catch block. If your Twitter status was updated correctly, the next line to execute is jTextArea1.setText(null); This line erases all the information inside the jTextArea1 control. And the next line, java.util.List<Status> statusList = twitter.getUserTimeline(); gets the 20 most recent tweets from your timeline and assigns them to the statusList variable. The next line is the beginning of a for statement: for (int i=0; i<statusList.size(); i++) { Basically, what this for block does is iterate through all the 20 most recent tweets in your timeline, one at a time, executing the two statements inside this block on each iteration: jTextArea1.append(String.valueOf(statusList.get(i).getText())+"n"); jTextArea1.append("-----------------------------n"); Although the getUserTimeline() function retrieves the 20 most recent tweets, we need to use the statusList.size() statement as the loop continuation condition inside the for block to get the real number of tweets obtained, because they can be less than 20, and we can’t iterate through something that maybe doesn’t exist, right? The first line appends the text of each individual tweet to the jTextArea1 control, along with a new-line character ("n") so each tweet is shown in one individual line, and the second line appends the "-----------------------------n" text as a separator between each individual tweet, along with a new-line character. The final result is a list of the 20 most recent tweets inside the jTextArea1 control. The only line of code inside the catch block displays the A Twitter Error occurred! message in case something goes wrong when trying to update your Twitter status. The next line of code right after the catch block is txtUpdateStatus.setText(""); This line just clears the content inside the txtUpdateStatus control, so you don’t accidentally insert the same message two times in a row. And finally, the last line of code in the btnUpdateStatusActionPerformed method is jTextArea1.updateUI(); This line updates the jTextArea1 control, so you can see the list of your 20 most recent tweets after updating your status. private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) { try { twitter = new Twitter(txtUsername.getText(), String.valueOf(txtPassword.getPassword())); twitter.verifyCredentials(); // JOptionPane.showMessageDialog(null, "You're logged in!"); java.util.List<Status> statusList = twitter.getUserTimeline(); for (int i=0; i<statusList.size(); i++) { jTextArea1.append(String.valueOf(statusList.get(i).getText())+"n"); jTextArea1.append("-----------------------------n"); } twitterLogin.dispose(); } catch (TwitterException e) { JOptionPane.showMessageDialog (null, "Login failed"); } jTextArea1.updateUI(); And now let’s have a look at the code we added inside the btnLoginActionPerformed method. The first thing you’ll notice is that we’ve added the '//' characters to the // JOptionPane.showMessageDialog(null, "You're logged in!"); line; this means it’s commented out and it won’t be executed, because it’s safe to go directly to the SwingAndTweet main window right after typing your Twitter username and password. The next lines are identical to the ones inside the btnUpdateStatusActionPerformed method we saw before; the first line retrieves your 20 most recent tweets, and the for block displays the list of tweets inside the jTextArea1 control.  And the last line of code, jTextArea1.updateUI(); updates the jTextArea1 control so you can see the most recent information regarding your latest tweets. Summary Well, now your SwingAndTweet application looks better, don’t you think so? In this article, we enhanced the SwingAndTweet application which we build in the first part of the tutorials series. In short, we: Created a twitterLogin dialog to take care of the login process Added functionality to show your 20 most recent tweets right after logging in Added the functionality to update your Twitter status
Read more
  • 0
  • 0
  • 4291
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 $19.99/month. Cancel anytime
article-image-building-calender-application-joomla-using-fabrik
Packt
19 Feb 2010
3 min read
Save for later

Building a Calender Application in Joomla! using Fabrik

Packt
19 Feb 2010
3 min read
Getting ready You need a working installation of Joomla! 1.5.x. For exercise purpose, you can install that on your local computer. The web server should have PHP5 installed. Then you need to install Fabrik component. This component is available for free from http://fabrikar.com/download. Download the latest version of the component and install it from Extensions | Install/Uninstall screen in Joomla! administration panel. Also plan for the application you want to develop. For example, we are developing an event calender. This event calender will contain the following information: Event Category Event Name Venue Start Date & Time End Date & Time Event Description Attached Document Created by This is a very simple list of information we need. Based on the we will create two database tables: categories and events. The table structure is shown in the following diagram. The above table diagrams show that categories table is linked to events table by foreign key category_id. Similarly, we have added user_id field in events table, so that we can link it to jos_users table. Whenever a user creates an event, his or her user ID will be added to this field. For creating the tables in Joomla! database, connect to that database using phpMyadmin or some other interface, and run the following SQL command: CREATE TABLE `categories` (`id` INTEGER AUTO_INCREMENT DEFAULT NULL ,`name` VARCHAR(200) DEFAULT NULL ,PRIMARY KEY (`id`)) COMMENT 'contains categories of events';CREATE TABLE `events` (`id` INTEGER AUTO_INCREMENT DEFAULT NULL ,`category_id` INTEGER DEFAULT NULL ,`event_name` MEDIUMTEXT DEFAULT NULL ,`venue` VARCHAR(100) DEFAULT NULL ,`start` DATETIME DEFAULT NULL ,`end` DATETIME DEFAULT NULL ,`description` MEDIUMTEXT DEFAULT NULL ,`attachment` VARCHAR(250) DEFAULT NULL ,`user_id` INTEGER DEFAULT NULL ,PRIMARY KEY (`id`)) COMMENT 'list of events';ALTER TABLE `events` ADD FOREIGN KEY (category_id) REFERENCES `categories` (`id`); Successful execution of the above code block will create two tables and add a foreign key to events table linking it to categories table. With creation of these two table we are set to create our event calendar application. How to do it... Follow the steps below: From Joomla! Administration panel, click Components | Fabrik |  Connections. That shows existing database connections. By default, connection to Joomla! database is created. You can create  new database connection by clicking New button and filling in the form. Click on Tables link in this screen. That shows existing tables created in Fabrik. In Table screen, click on New button to add a new table. That shows Table: [New] screen. In Label field type Categories, and in Introduction field, type Event Categories. Then select Yes in Published radio box to the right side. Accept default values for other fields. Then click Access tab. That shows Access Rights. Accept the default values in Access tab. Now click Data tab. From here you have to configure which data table you want to use. From Connection drop down list, select site database. Then click on Link to Table drop down list and select categories table. In Order By drop down list, select name. There are some other options in this tab, but those cannot be configured until you save the table. Now click Save button to save the table.
Read more
  • 0
  • 0
  • 3776

article-image-building-simple-address-book-application-jquery-and-php
Packt
19 Feb 2010
14 min read
Save for later

Building a Simple Address Book Application with jQuery and PHP

Packt
19 Feb 2010
14 min read
Let's get along. The application folder will be made up of five files: addressbook.css addressbook.html addressbook.php addressbook.js jquery.js Addressbook.css will contain the css for the interface styling, addressbook.html will contain the html source, addressbook.js contains  javascript codes, addressbook.php will mostly contain the server side code that will store the contacts to database, delete the contacts, provide updates and fetch the list of the contacts. Let's look through the HTML We include the scripts and the css file in the head tag in addressbook.html file. <title>sample address book</title> <link rel="stylesheet" type="text/css" href="addressbook.css"> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="addressbook.js"></script> The code above includes the css for styling the application, jquery library for cross browser javascript and easy DOM access, and the addressbook.js contains functions that help user actions translated via javascript and ajax calls. The Body tag should contain this: <div id="Layer1"> <h1>Simple Address Book</h1> <div id="addContact">               <a href="#add-contact" id="add-contact-btn">Add Contact</a>               <table id="add-contact-form">               <tr>               <td>Names:</td><td><input type="text" name="names" id="names"  /></td>               </tr>               <tr>               <td>Phone Number:</td><td><input type="text" name="phone" id="phone"  /></td>               </tr>               <tr>               <td>&nbsp;</td><td>               <a href="#save-contact" id="save-contact-btn">Save Contact</a>               <a href="#cancel" id="cancel-btn">Cancel</a>               </td>               </tr>               </table> </div> <div id="notice">               notice box </div> <div id="list-title">My Contact List</div> <ul id="contacts-lists">         <li>mambe nanje [+23777545907] - <a href="#delete-id" class="deletebtn" contactid='1'> delete contact </a></li>         <li>mambe nanje [+23777545907] - <a href="#delete-id" class="deletebtn" contactid='2'> delete contact</a></li>         <li>mambe nanje [+23777545907] - <a  href="#delete-id" class="deletebtn" contactid='3'> delete contact</a></li> </ul> </div> The above code creates an html form that provides input fields to insert new address book entries. It also displays a button to make it appear via javascript functions. It also creates a notification div and goes to display the contact list with delete button on each entry. With the above code, the application will now look like this:   /* CSS Document */   body {               background-color: #000000; } #Layer1 {               margin:auto;               width:484px;               height:308px;               z-index:1; } #add-contact-form{               color:#FF9900;               font-weight:bold;               font-family:Verdana, Arial, Helvetica, sans-serif;               background-color:#333333;               margin-top:5px;               padding:10px; } #add-contact-btn{               background-color:#FF9900;               font-weight:bold;               font-family:Verdana, Arial, Helvetica, sans-serif;               border:1px solid #666666;               color:#000;               text-decoration:none;               padding:2px;               font-weight:bold; } #save-contact-btn{               background-color:#FF9900;               font-weight:bold;               font-family:Verdana, Arial, Helvetica, sans-serif;               border:1px solid #666666;               color:#000;               text-decoration:none;               padding:2px;               font-weight:bold; } #cancel-btn{               background-color:#FF9900;               font-weight:bold;               font-family:Verdana, Arial, Helvetica, sans-serif;               border:1px solid #666666;               color:#000;               text-decoration:none;               padding:2px;               font-weight:bold; } h1{               color:#FFFFFF;               font-family:Arial, Helvetica, sans-serif; } #list-title{               color:#FFFFFF;               font-weight:bold;               font-size:14px;               font-family:Arial, Helvetica, sans-serif;               margin-top:10px; } #contacts-lists{               color:#FF6600;               font-weight:bold;               font-family:Verdana, Arial, Helvetica, sans-serif;               font-size:12px; } #contacts-lists a{               background-color:#FF9900;               text-decoration:none;                            padding:2px;               color:#000;               margin-bottom:2px; } #contacts-lists li{               list-style:none;               border-bottom:1px dashed #666666;               margin-bottom:10px;               padding-bottom:5px; } #notice{               width:400px;               margin:auto;               background-color:#FFFF99;               border:1px solid #FFCC99;               font-weight:bold;               font-family:verdana;               margin-top:10px;               padding:4px; } The CSS code styles the HTML above and it ends up looking like this: Now that we have our html and css perfectly working, we need to setup the database and the PHP server codes that will handle the AJAX requests from the jquery functions. Create a MySQL database and executing the following SQL code will create the contacts table. This is the only table this application needs. CREATE TABLE `contacts` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `names` VARCHAR( 200 ) NOT NULL , `phone` VARCHAR( 100 ) NOT NULL ); Let's analyse the php codes. Remember, this code will be located in addressbook.php. The database connection code # FileName="Connection_php_mysql.htm" # Type="MYSQL" # HTTP="true" //configure the database paramaters $hostname_packpub_addressbook = "YOUR-DATABASE-HOST"; $database_packpub_addressbook = "YOUR-DATABASE-NAME"; $username_packpub_addressbook = "YOUR-DATABASE-USERNAME"; $password_packpub_addressbook = "YOUR-DATABASE-PASSWORD"; //connect to the database server $packpub_addressbook = mysql_pconnect($hostname_packpub_addressbook, $username_packpub_addressbook,  $password_packpub_addressbook) or trigger_error(mysql_error(),E_USER_ERROR); //selete the database mysql_select_db($database_packpub_addressbook); the above code sets the parameters required for the database connection, then establishes a connection to the server and selects your database. The PHP codes will then contain functions SAVECONTACTS, DELETECONTACTS, GETCONTACTS. These functions will do exactly as their name implies. Save the contact from AJAX call to the database, delete contact via AJAX request or get the contacts. The functions are as show below: //function to save new contact /** * @param <string> $name //name of the contact * @param <string> $phone //the telephone number of the contact */ function saveContact($name,$phone){               $sql="INSERT INTO contacts (names , phone ) VALUES ('".$name."','".$phone."');";               $result=mysql_query($sql)or die(mysql_error()); } //lets write a function to delete contact /** * @param <int> id //the contact id in database we wish to delete */ function deleteContact($id){               $sql="DELETE FROM contacts where id=".$id;               $result=mysql_query($sql); }   //lets get all the contacts function getContacts(){               //execute the sql to get all the contacts in db               $sql="SELECT * FROM contacts";               $result=mysql_query($sql);               //store the contacts in an array of objects               $contacts=array();               while($record=mysql_fetch_object($result)){                             array_push($contacts,$record);               }               //return the contacts               return $contacts; } The codes above creates the functions but the functions are not called till the following code executes: //lets handle the Ajax calls now $action=$_POST['action']; //the action for now is either add or delete if($action=="add"){               //get the post variables for the new contact               $name=$_POST['name'];               $phone=$_POST['phone'];               //save the new contact               saveContact($name,$phone);               $output['msg']=$name." has been saved successfully";               //reload the contacts               $output['contacts']=getContacts();               echo json_encode($output); }else if($action=="delete"){               //collect the id we wish to delete               $id=$_POST['id'];               //delete the contact with that id               deleteContact($id);               $output['msg']="one entry has been deleted successfully";               //reload the contacts               $output['contacts']=getContacts();               echo json_encode($output); }else{               $output['contacts']=getContacts();               $output['msg']="list of all contacts";               echo json_encode($output); } The above code is the heart of the addressbook.php codes. It gets the action from post variables sent via AJAX call in addressbook.js file, interprets the action and executes the appropriate function for either add, delete or nothing which will just get the list of contacts. json_encode() function is used to encode the data in to Javascript Object Notation format; it will be easily interpreted by the javascript codes.
Read more
  • 0
  • 0
  • 12718

article-image-drupal-6-performance-optimization-using-views-and-panels-caching
Packt
19 Feb 2010
5 min read
Save for later

Drupal 6 Performance Optimization Using Views and Panels Caching

Packt
19 Feb 2010
5 min read
Views caching The Views 2 module allows you to cache your Views data and content. You can cache Views data per View. We're going to enable caching on one of our existing Views, and also create a brand new View and set caching for that as well using the test content we just generated. This will show you a nice integration of the Devel functionality with the Views module and then how caching works with Views. Go to your Site building | Views configuration page and you'll see many of your default and custom views listed. We have a view on this site for our main photo gallery. The view is named photo_gallery in our View listing. Go ahead and click on one of your Views edit links to get into edit mode for a View. In our Views 2 interface mode, we'll see our tabs for default, Page, and/or Block View display. I'm going to click on my Page tab to see my View's page settings. Under my Basic settings configuration, I'll see a link for Caching. Currently, our Caching link states None, meaning that no caching has been configured for this view. Click on the None link. Select the Time-based radio button. This will enable Time-based caching for our View page. Click the Update default display button. The next caching options configuration screen will ask you to set the amount of time for both, your View Query results and for your View Rendered output. Query results refer to the amount of time raw queries should be cached. Rendered output is the amount of time the View HTML output should be cached. So basically, you can cache both your data and your frontend HTML output. Set them both to the default of 1 hour. You can also set one to a specific time and the other to None. Go ahead and tweak these settings to your own requirements. I'm leaving both set to the default of 1 hour. Click on the Update button to save your caching options settings. You are now caching your View. Save your View by clicking on the Save button. The next time you look at your View interface you should see the caching time notation listed under your Basic settings. It will say 1 hour/1 hour for this setting. Once you enable Views caching, if you make a change to your View settings and configuration, the results and output of the View may not update while you have caching enabled. So, while in Views development you may want to disable caching and set it to None. Otherwise, this next section will show you how to disable your Views cache while you are in development. To see the performance results of this, you can use the Devel module's functionality again. When you load your View after you enable caching, you should see a decrease in the amount of ms (milliseconds) needed to build your Views plugin, data, and handlers. So, if your Views plugin build loaded in 27.1 ms before you enabled caching, you may notice that it changes to something less—for example, in my case it now shows that it loads in 2.8 ms. You can immediately see a slight performance increase with your View build. Let's go ahead and build a brand new View using the test content that we generated with the Devel module and then enable caching for this View as well. Go to your Views admin and follow these steps: Add a new View. Name the View, add a description and a tag if applicable. Click on Next. I'm going to create a View that filters my blog entries and lists the new blog entries in post date order using the Devel content I generated. Add a Page display to your new View. Name the page View. Give the page View a title. Give your View an HTML list style. Set the View to display 5 posts and to use a full pager. Set your caching to Time-based (following instructions above in the first view we edited). Give the view a path. Add a Node: Title field and set the field to be linked to its node. Add a filter in order to filter by Node:Type and then select Blog entry. Set your Sort criteria to sort by Node:Post date in ascending order by hour. Your settings should look similar to this: Save your View by clicking on the Save button. Your new View will be visible at the Page path you gave it and it will also be caching the content and data it presents. Again, if you refresh your View page each time you should notice that the plugins, data, and handlers build times decrease or stay very similar and consistent in load times. You should also notice that the Devel database queries status is telling you that it's using the cached results and cached output for the View build times and the MySQL statements. You should see the following code sitting below your page content on the View page you are looking at. It will resemble this: Views plugins build time: 23.509979248 msViews data build time: 55.7069778442 msViews handlers build time: 1.95503234863 msSELECT node.nid AS nid,node_data_field_photo_gallery_photo.field_photo_gallery_photo_fidAS node_data_field_photo_gallery_photo_field_photo_gallery_photo_fid,node_data_field_photo_gallery_photo.field_photo_gallery_photo_listAS node_data_field_photo_gallery_photo_field_photo_gallery_photo_list,node_data_field_photo_gallery_photo.field_photo_gallery_photo_dataAS node_data_field_photo_gallery_photo_field_photo_gallery_photo_data,node.type AS node_type,node.vid AS node_vid,node.title AS node_title,node.created AS node_createdFROM {node} nodeLEFT JOIN {content_type_photo} node_data_field_photo_gallery_photo ONnode.vid = node_data_field_photo_gallery_photo.vidWHERE (node.status <> 0) AND (node.type in ('%s'))ORDER BY node_created ASCUsed cached resultsUsed cached output
Read more
  • 0
  • 0
  • 3182

article-image-video-editing-blender-using-video-sequence-editor-part-2
Packt
19 Feb 2010
7 min read
Save for later

Video Editing in Blender using Video Sequence Editor: Part 2

Packt
19 Feb 2010
7 min read
Video Sequence Editor (The Main Dish) Since we’ve been always using Blender’s default screen for modeling, setting up materials, or node compositing, let’s try to deviate for a moment and make use of Blender’s screen features to jump from one preset to another, which is a very useful tool in my opinion. Moving your attention over to Blender’s main menu (located at the very top of the window, below the header), you’ll notice the drop-down menu with a prefix of SR: at the beginning. This is Blender’s screen system which can come in handy anytime you want to switch to any preset view or customized view, quickly! You can click on the box itself with the text to edit the name of the screen you currently have, or you can use the dropdown button to either add a new screen or to choose between the selection. Right now we don’t have the diligence to create a new and customized screen since the presets are already of best use. Clicking the drop-down button, you’ll be presented with different screen names, of which, we will be selecting the fourth one labeled 4-Sequence. Instantaneously, after confirming your selection, your Blender screen will be warped to yet another spaceship-like interface, don’t worry though, we’ll get used to it pretty much soon. Changing Screen Layouts On the upper left hand corner, we have our IPO window which is used to add refined and custom controls over the behavior of our strips/inputs, on its right is the preview window, on the middle part is the VSE editor, below it is the Timeline, and lastly at the bottom part is the buttons window. Sequence Screen Layout For this part of the article, we’ll only be delving into some of these parts, namely the Preview, VSE Editor, Timeline, and the Buttons Window. I could’ve just said “except the IPO Window. So before we actually try and add in our videos, there are things we need to do: hover your mouse pointer over to the Timeline Window and press SHIFT+T to bring up the Time Value option and choose Seconds. This will help us later on to recognize our video lengths with seconds as the unit and not frames, which can become clearer as we go on. And next is to click the Sequencer button under the Scene(F10) menu. This will enable us to see options for our video later on. Timeline and Button Options Next thing we need to do is to add our videos (at long last) into the VSE Editor and finally to editing on them.  To do this, move your mouse pointer over to the VSE Editor and press spacebar > Movie or Movie + Audio (HD) or you can click Add > Movie or Movie + Audio (HD) on the menu header. This will then lead you into Blender’s file browser where you can locate your videos. If you want to load your videos simultaneously, you can right click, hold, and drag on the videos to select them, and click the load button. They will then be automatically concatenated, each having its own individual video strip. But right now, I only want to load them one at a time so we could focus on editing them separately and not worry about the other strips floating around and messing around with our view. Once the video/s are loaded into the VSE window and are selected, you’ll notice the Sequencer Buttons Window populated with options.  Normally, we will see four (4) tabs, namely: Edit, Input, Filter, and Proxy. Let’s leave the default settings now as they work great as they are (but you can always doodle around the buttons and settings and see how they work, try to experiment!) Basically, I will introduce you to some of Blender’s video editing capabilities such as: cutting, duplicating, transition effects, artistic glows, and speed controls. Discussing the extents and features of this editor might take me a whole new set of article or two so right now, I’ll only lead you to the basic concepts and have you and your imagination with a lot of experimentation lead you to where you want. First off, Cutting video strips. Often, you want to delete parts of your video or move a section of it on a certain time on your collection, this is where cutting comes in handy. In Blender VSE world, you can cut a video by clicking over or scrubbing on the frame where you want to start your cut and press K for hard-cut, SHIFT+K for soft-cut. Once this operation is successful, you’ll notice your strip change appearance as a result of the cut, and depending on the number of cuts you made, that’s how much sub-strips you have which can individually be moved (G) or deleted X or delete key. Cutting, Moving, and Deleting Strips Once you have made the necessary cuts, you can always arrange your strips by moving them beside each other or with gaps, depending on what you want to achieve. Additionally, you can scrub your videos by click and dragging your mouse over to the VSE window (with the green vertical line as your current frame marker) or you could also click and drag over to the Timeline Window. As you scrub your videos, you’ll notice a live preview of what’s happening on the Preview Window on the upper right hand corner of your screen. Another cool trick with the VSE is adding markers to label parts of your animation or videos. Markers are also a way of identifying events in your timeline as they happen so you won’t lose track of what has occurred on that frame in time. You can add markers to your VSE Window where your current frame marker (vertical green line) by pressing CTRL+ALT+M or by clicking Marker > Add Marker on the menu, and add a label to it by pressing CTRL+M or by clicking Marker > (Re)Name Marker. These markers would also appear on your Timeline Window. Adding and (Re)Naming Markers Next is duplicating strips. Sometimes in your video editing endeavors, you wanted to repeat parts of the video for more emphasis or even just for artistic purposes. Luckily, duplicating strips in Blender’s VSE is just as easy as selecting the strips(s) you wish to duplicate and press SHIFT+D or clicking Strip > Duplicate in the menu. Duplicating Strips Now we discuss transition effects, which are one of the nicest things video editing has ever offered. In this part, we’ll try adding some simple transition effects from within the VSE to add subtlety and variation to our strips. Like any other video editing application, it requires you to have at least two strips of video/image to create the transition. We do this in Blender by selecting two strips by first selecting the first strip with right click, then adding to it a second strip by shift right clicking. This way you’re telling Blender from what video to what will the transition occur. Say, you have selected video A first then shift selected video B next, if we’ll now try to add the transition effect, it will happen from video A to video B and not vice versa. The simplest transition that we could add now is the Gamma Cross which simply takes the first strip and fades it into the second one and so on. Do this by selecting two strips and press spacebar then click Gamma Cross or click Add > Effect > Gamma Cross.  With its default settings, when you now scrub your strips or use the timeline, you’ll notice that in between the two strips is a blend of both. Moving any of the video strips will update automatically the length of the Gamma Cross that’s present.
Read more
  • 0
  • 0
  • 6043
article-image-video-editing-blender-using-video-sequence-editor-part-1
Packt
19 Feb 2010
6 min read
Save for later

Video Editing in Blender using Video Sequence Editor: Part 1

Packt
19 Feb 2010
6 min read
Blender, the open-source 3D creation suite, as we all know, has been on great heights lately, and with the astounding amount of work and dedication that is being put into the current development, there’s no doubt it is already a state-of-the-art software. From the time I was introduced to Blender, I was pretty amazed at the amount of features it has and the myriad of possibilities you can achieve with it. Features like modeling, shading, texturing, rendering are already a given fact, but what’s much more impressive with Blender is it’s “side features” that come along with it, one great example would be the “Video Sequence Editor”, popularly called VSE is the Blender universe. From the name alone, you can already figure out what it is used for, yup – video editing! Pretty cool, eh? With the right amount of knowledge, strategy, and workarounds, there’s much more leeway than it is really used for. I’ll share with you some tips and guidelines as to how you could start along and begin using Blender itself for editing your videos and not keep jumping from application to application, which can become really troublesome at times. Without further ado, let’s get on with it! Requirements Before we begin, there are a couple of things we need to have: Blender 2.49b Clips/Videos/Movies Skill level: Beginner to Intermediate a little bit of patience lots of coffee to keep you awake (and a comfortable couch?)! Post-processing This might sound odd to you as this came first before anything else in the article. The reason for this is that we don’t want to mess up with a lot of things, and create more trouble later (you’ll see that shortly during the process). But if you already are satisfied with the way your videos look and feel, then you can skip this step and move on to the main one. Partly, we will deal on how to enhance your videos, making them look better than they were originally shot. This part could also dictate how you want the mood of your videos to be (depending on the way you shot it). Just like how we post-process and add more feel to our still images, the same thing goes with our videos, thus using the Composite Nodes to achieve this. And later, use these processed videos into the sequence editor for final editing. To begin with, open up Blender and depending on your default layout, you will see something like this (see screenshot below): Blender Window Let’s change our current 3D viewport into the Node Editor window and under the Scene Button(F10), set the render size to 100%, enable Do Composite under the Anim panel, set the Size/Resolution and the video format under the Format panel, and lastly set your output path under the Output panel on the same window. That was quite a lengthy instruction to pack into one paragraph though, so check out the screenshot below for a clearer picture. Settings Now that we’re already in the Node Editor window, by default, we see nothing but grid and a new header (which apparently gives us a clue what to do next). Since we’re not dealing with Material Nodes and Texture Nodes, we’re safe to ignore some other things that comprise the node editor for now and instead, we’ll use the Composite Nodes, which is represented by a face icon on the header. Click and enable that button. But then, you’ll notice that nothing has happened yet, that’s because we still have to indicate to Blender that, it’s actually going to be using the nodes. So, go ahead and click the Use Nodes and you’ll notice something came up on your node editor window, being the Render Layer Node and the Composite Node respectively.The render layer node is an input node which takes data from our current Blender scene as specified through of render layer options under the scene window, which is often useful in general purpose node compositing direct from our 3d scene or if you wanted to layer your renders into passes. But since, we are not doing that now, we won’t be needing this node right now, go ahead and select the Render Layer Node by right clicking on it and press X or Delete on your keyboard and automatically, without any popups shown, the render layer node is now gone from our composite window. Next step is to load our videos into the node compositor and actually begin the process. To load the videos into our compositor, we use the Image Input Node to call our videos from wherever it is stored. To do this, press spacebar on your keyboard while your mouse cursor is on the node editor window, choose Add < Input > Image. With our Image Node loaded in the compositor, click the Load New button and browse to the directory where the file is loaded. Loading the Video via the Image Input Node After successfully loading the video, you’ll notice the Image Input Node change its appearance, now having a thumbnail preview and some buttons and inputs we can experiment with. The most important setting we have to specify here is the number of frames our video has or else Blender wouldn’t know which ranges to composite. Specifying the Number of Frames in the Image Node Often, this can be a difficult task to deal with and I’ve had so much trouble with this before as I wanted the exact frame count that would precisely match that of my original video without even missing a single glitch. There are a couple of ways to do this, and if you’re smart enough to calculate the number of frames based on the time your video consumes, that’s fair enough, or you could open up a separate application to see how many frames it got, but if you’re like me who likes to make it simple and still within Blender’s grasp, then there’s still hope to this. Right now, we’re off to a tiny part of the main course here which is Blender’s VSE, but this time we’ll only use it to know how many frames our video has. But don’t worry because it’s the main dish and we’ll get to that shortly.
Read more
  • 0
  • 0
  • 3863

article-image-jboss-richfaces-33-supplemental-installation
Packt
19 Feb 2010
6 min read
Save for later

JBoss RichFaces 3.3 Supplemental Installation

Packt
19 Feb 2010
6 min read
This installation guide is for the Windows platform. JBoss Server Installation In order to run any web application, an application server is needed. JBoss server is an industry standard and is ideal for running Seam and RichFaces applications.  Downloading the server is a very simple task. First go to the JBoss download page and download the 4.2.2.GA version of the JBoss server. Save it to a directory for downloads such as c:downloads. Unzip the file to the c: directory.  After unzipping, you should have a folder named c: jboss-4.2.2.GA. Test the server installation by going into c:jboss-4.2.2.GAbin and running the file run.bat. A command window should run with server logs. At completion, the logs will indicate that the server has started. Starting JBoss Server Within Eclipse Although you can start JBoss server from the run.bat file, for the purposes of development and learning RichFaces, it is more valuable to start the JBoss server within Eclipse. The Eclipse IDE provides support to run, shutdown and adjust settings for servers. In Eclipse, we will work from the Java Perspective. Change Eclipse to be in the Java Perspective. Go to Window->Open Perspective->Java. We need to have a tab for Server. Go To Window->Show View->Other->Servers->Server. In the Server tab, right click and go to New->Server. Here we are defining a server to launch within Eclipse. Choose JBoss->JBoss v4.2->Next. Choose the JRE, which will typically be the path to where Java is installed. For the Application Server Directory, choose c:jboss-4.2.2.GA then Next. Accept the defaults for Address, Port, JNDI Port and Server Configuration. Click Next->Finish. Next the server settings need to be adjusted. Double click on the JBOSS 4.2 entry in the server tab to bring up the settings menu in eclipse. Click on the edit menu on the right hand side. Figure 1 - JBoss Server settings Uncheck all check boxes and Server Timeout Delay to be Unlimited. The server is ready to run. In the Server tab, right click on the JBOSS 4.2 entry and choose Start. Go to the Console tab and you will see the server logs. At completion, the logs should indicate that the server has started. MySql Installation MySql is the database used to store information in the example applications. Once MySql is installed, the example applications can connect to a persistent store and the developer will be able to see data saved as the application is exercised. Go to the MySql download page and retrieve the installation file. Look for MSI file labeled mysql-essential-5.1.42-winx64.msi (or a similar version). The MSI file is easiest to install as it gives a wizard to guide you through the process. Once the file is saved, double click on it to initiate installation. Choose all the default options. When the id and password is requested, choose root as both the id and password. This is easy to remember for development purposes. Verify installation of MySql by looking for the shortcuts placed Windows Programs Menu. Also verify that MySql has been installed as a Windows service. The easiest way to do this is to go to Start-> Run in Windows and type services.msc. The services dialogue box should have a MySql entry. Make sure the MySql service is started. Run MySql Command Client In order to operate the MySql database, you can use the provided command line client. The client enables the user to look up tables, execute operational commands, and run sql statements.  In the Windows Start menu, go to Start->Programs0->MySql->MySql Server 5.x->MySql Command Line Client. Type in root for the password. A mysql prompt will appear. The command line tool is used for creating the database for the example applications. In order to import a sql script, use the command source <path>. For example: source c:adv_contact_manager_create.sql For a full list of commands for MySql, see the online manual: http://dev.mysql.com/doc/refman/5.1/en/index.html. Download and Install MySql JDBC Connector In order for Java applications to connect to MySql through JDBC, a connector jar is needed. MySql provides connectivity for client applications developed in the Java programming language via a JDBC driver, which is called MySql Connector/J. Go to the connector download page and retrieve the zip file. Unzip the file to a directory. Identify the file mysql-connector-java-5.1.10-bin.jar. Copy this file to the default server lib directory so that it is accessible by all applications: C:jboss-4.2.2.GAserverdefaultlib Build and Deploy Example Applications In order to see the application that is being developed, it is necessary to build and deploy the application onto the server. Applications generated by the seam-gen tool come built with a script armed with many build tasks. Eclipse provides Ant support so we can use it to operate the build file provided within the example application. In Eclipse with the application loaded as a project, open the Ant view. Go to Window-> Show View-> Ant. The Ant view will be displayed. Now load the build.xml in order to operate the Ant targets. Right click in the Ant view and select Add Buildfiles->Choose build.xml for the application. A list of Ant targets will be loaded. In order to execute a task, simply double click on the task. The Console window will display the executed statements. Seam-gen offers several tasks, but a notable few are very useful. deploy – builds and deploys the application to the server undeploy – deletes the application from the server purge – deletes temporary server files associated with the application clean – deletes package application files from the local distribution directory If the deploy task fails, simply go to the JBoss deployment directory and delete the installed application. C:jboss-4.2.2.GAserverdefaultdeploy Applications can also be directly copied into this directory for deployment. Inversely, applications can be directly deleted from this directory for un-deployment. With these basics installations complete, running the example applications should be simple and you will be on your way to mastering RichFaces 3.3. Summary In this article, we discussed the following: JBoss Server Installation Starting JBoss Server within Eclipse MySql Installation Build and Deploy Example applications
Read more
  • 0
  • 0
  • 2066

article-image-spring-mvc-configuring-and-deploying-application
Packt
19 Feb 2010
5 min read
Save for later

Spring MVC - Configuring and Deploying the Application

Packt
19 Feb 2010
5 min read
The first section will focus on configuring the application and its components so that the application can be deployed. The focus of the second section will be a real world application that will be developed using the steps described in the article on Developing the MVC components and in this article. That sets the agenda for this discussion. Using Spring MVC – Configuring the Application There are four main steps in configuring of the application. They are: Configure the DispatcherServlet Configure the Controller Configure the View Configure the Build Script The first step will be same for any application that is built using Spring MVC. The other three steps change according to the components that have been developed for the application. Here are the details. Configure the DispatcherServlet The first step is to tell the Application server that all the requests for this (Spring MVC based) application need to be routed to Spring MVC. This is done by setting up the DispatcherServlet. The reason for setting up DispatcherServlet is that it acts as the entry point to the Spring MVC and thus to the application.  Since the DispatcherServlet interacts with the application as a whole (instead of individual components), its configuration or setting up at application level. And any setup that needs to be done at the application level is done by making the required entries in the web.xml. The entries required  in the web.xml can be divided into the following: Servlet mapping URL mapping The former specifies the details of the servlet and the latter specifies how the servlet is related to a URL. Here are the details. Servlet mapping Servlet mapping is akin to declaring a variable. It is through servlet mapping that Application Server knows which servlets of the application it needs to support.  Servlet mapping, in essence, assigns a name to a servlet class that can be reference throughout web.xml. To set up the DispatcherServlet, first it has to be mapped to a name. that can be done using <servlet-name> and <servlet-class> tags that are the child nodes of the <servlet> tag. The following statement maps the DispatcherServlet to the name "dispatcher". <servlet> <servlet-name> dispatcher </servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> </servlet> Since the DispatcherServlet needs to be loaded on the startup of the Application Server instead of the loading when a request arrives, the optional node <load-on-startup> with value of 1 is also required. The modified <servlet> tag will be: <servlet> <servlet-name> dispatcher </servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> Next step is to map the URL to the servlet name so that the requests can be routed to the DispatcherServlet. URL mapping Once the servlet has been mapped, the next step is to map the servlet name with a URL so that the requests for that particular URL can be passed on to the application via the DispatcherServlet. That can be done using the <servlet-name> and <url-pattern> nodes of the <servlet-mapping> node. The <servlet-name> is used to refer the name that was mapped with the DispatcherServlet class. The <url-pattern> is used to map a URL pattern with a servlet name so that when a request arrives matching the URL pattern, Application Server can redirect it to the mapped servlet. To map the DispatcherServlet with a URL pattern the <servlet-mapping> tag will be: <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> With this configuration/setting up of DispatcherServlet is complete. One point to keep in mind is that the URL pattern can be any pattern of one’s choice. However, it’s a common practice to use *.html for DispatcherServlet and *do for ActionServlet (Struts 1.x). Next step is to configure the View and Controller components of the application. Mapping the Controller By setting up the DispatcherServlet, the routing of requests to the application will be taken care of by the Application Server. However, unless the individual controllers of the application are setup/configured, the Framework would not know which controller to be called once the DispatcherServlet receives the request. The configuration of the Controller as well as the View components is done in the Spring MVC configuration file. The name of the configuration file is dependent on the name of the DispatcherServlet in web.xml, which is of the form <DispatcherServlet_name-servlet>.xml. So if the DispacherServlet is mapped to the name dispatcher, then the name of the configuration file will be dispatcher-servlet.xml. The file will reside in WEB-INF folder of the application. Everything in Spring Framework is a bean. Controllers are no exceptions. Controllers are configured as beans using the <bean> child tag of <beans> tag. A Controller is mapped by providing the URL of the request as the name attribute and complete qualified name of the Controller class as the value of the class attribute. For example, if the request URL is say, http://localhost/test/hello.html, then the name attribute will have /hello.html and the value attribute will have the fully qualified class name say, org.me.HelloWorldController. The following statements depicts the same: <bean name="/hello.html" class=" org.me.HelloWorldController "/> One point to keep in mind is that the "/" in the bean name represents the relative path. In other words, /hello.html means that hello.html is directly under http://localhost/test. If hello.html was under another directory say, jsp which, in turn was directly under the application, then the name attribute will be /jsp/hello.html. Let us move onto configuring the Views.
Read more
  • 0
  • 0
  • 3432
article-image-jquery-14-dom-manipulation-methods-style-properties-and-class-attributes
Packt
19 Feb 2010
3 min read
Save for later

jQuery 1.4 DOM Manipulation Methods for Style Properties and Class Attributes

Packt
19 Feb 2010
3 min read
General attributes These methods get and set DOM attributes of elements. .attr() (getter) Get the value of an attribute for the first element in the set of matched elements. .attr(attributeName) Parameters attributeName: The name of the attribute to get Return value A string containing the attribute value. Description It's important to note that the .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, we need to rely on a looping construct such as jQuery's .each() method. Using jQuery's .attr() method to get the value of an element's attribute has two main benefits: Convenience: It can be called directly on a jQuery object and chained to other jQuery methods. Cross-browser consistency: Some attributes have inconsistent naming from browser to browser. Furthermore, the values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The .attr() method reduces such inconsistencies. .attr() (setter) Set one or more attributes for the set of matched elements. .attr(attributeName, value).attr(map).attr(attributeName, function) Parameters (first version) attributeName: The name of the attribute to set value: A value to set for the attribute Parameters (second version) map: A map of attribute-value pairs to set Parameters (third version) attributeName: The name of the attribute to set function: A function returning the value to set Return value The jQuery object, for chaining purposes. Description The .attr() method is a convenient and powerful way to set the value of attributes, especially when setting multiple attributes or using values returned by a function. Let's consider the following image: <img id="greatphoto" src="brush-seller.jpg" alt="brush seller" /> Setting a simple attribute We can change the alt attribute by simply passing the name of the attribute and its new value to the .attr() method. $('#greatphoto').attr('alt', 'Beijing Brush Seller'); We can add an attribute the same way. $('#greatphoto').attr('title', 'Photo by Kelly Clark'); Setting several attributes at once To change the alt attribute and add the title attribute at the same time, we can pass both sets of names and values into the method at once using a map (JavaScript object literal). Each key-value pair in the map adds or modifies an attribute: $('#greatphoto').attr({alt: 'Beijing Brush Seller',title: 'photo by Kelly Clark'}); When setting multiple attributes, the quotation marks around attribute names are optional. Computed attribute values By using a function to set attributes, we can compute the value based on other properties of the element. For example, we could concatenate a new value with an existing value as follows: $('#greatphoto').attr('title', function() { return this.alt + ' – photo by Kelly Clark'}); This use of a function to compute attribute values can be particularly useful when we modify the attributes of multiple elements at once. .removeAttr() Remove an attribute from each element in the set of matched elements. .removeAttr(attributeName).removeAttr(function) Parameters (first version) attributeName: An attribute to remove Parameters (second version) function: A function returning the attribute to remove Return value The jQuery object, for chaining purposes. Description The .removeAttr() method uses the JavaScript removeAttribute() function, but it has the advantage of being able to be called directly on a jQuery object and it accounts for different attribute naming across browsers. As of jQuery 1.4, the .removeAttr() function allows us to indicate the attribute to be removed by passing in a function.
Read more
  • 0
  • 0
  • 3462

article-image-melody-other-movable-type
Packt
19 Feb 2010
5 min read
Save for later

Melody: The Other Movable Type

Packt
19 Feb 2010
5 min read
If there’s one golden rule of open source, it’s this: Major projects can and will be forked. Multiple versions of just about every open source app of repute have been spun off from the original. These splits happen for reasons that are more often political than technical. Look at the clamor building around MySQL, where people concerned about the future of the project under Oracle’s stewardship want its code copied out into another, separately managed project that won’t (as they see it) end up as a corporate lapdog. The blogging system Movable Type, now in its fifth major revision, is also undergoing a code schism of sorts. A number of Movable Type developers and contributors became frustrated with what they felt was an emphasis by MT’s corporate owners on the wrong features, as well as a lack of transparency in the development process for the product. Rather than attack Six Apart (Movable Type’s parent company) directly, they chose instead to do an end run—to take the now open-source code base for Movable Type and create a new product from it: Melody. The theme behind Melody Melody extends on Movable Type’s legacy in four basic ways. Take what already exists in Movable Type, keep what’s best about it, remove from the core product features which make things substantially more complex but which are only used by a minority of users anyway, and move Melody forward in ways that show the developers are directly attuned to the needs of the new user (and developer) base. How these things manifest in Melody can be summed up in a few key points as shown below. Backwards compatibility Since most of the initial user base for Melody will consist of Movable Type users and developers, it only makes sense for Melody to be heavily backwards-compatible with MT. This doesn’t just mean that a MT database can be imported into a Melody installation as-is. This also means things like plugins and transformation filters will still work correctly. Both are crucial, since so much of MT’s appeal is in how it can be bent and shaped to fit user’s needs—and those same needs will carry directly over into Melody. (If anything, they’ll have to be satisfied all the better in Melody, since Melody’s being written specifically from the perspective of allowing such customization to be all the easier and more powerful to implement.) The exact degree and scope of Melody’s backwards compatibility with Movable Type is still being wrangled out, but it’s likely to be as friendly as possible to existing MT developers as a way to gain their immediate support. One thing that has become clearer is that people looking to make a straight upgrade from MT to Melody will at this point be best served by an upgrade from the 4.x branch of MT than the current 5.x branch. This is probably due to Melody being more derived from the former than the latter, but there’s nothing that says in time a clean 5.x migration path can’t be created. A more developer-friendly culture "Developer" doesn’t just mean people who write Melody or Movable Type’s own code. It means people who create the above-mentioned add-ons, and—in some ways the most visible type of third-party development—people who create themes and templates for the system. A better culture for those people to thrive in means more. Another concrete way for developer-friendliness to manifest is with better use of existing CPAN (for Perl) and jQuery (for JavaScript) libraries and community-developed code. A lot of what was written for earlier versions of Movable Type duplicated functions that were available in those repositories. Not only did this mean MT’s code had to be maintained separately, but it also meant Movable Type didn’t leverage what was available in CPAN and jQuery as effectively as it could. Indirect contribution to Movable Type itself What Melody’s developers hope to create is a project that doesn’t so much steal marketshare from Movable Type as it does give Movable Type itself a chance to become a better project, too. Melody could become a model for how MT itself might evolve, and since Melody’s licensed under the same terms as MT itself (GPLv2), there’s nothing preventing significant chunks of Melody—or even the whole project—from being back-adopted into MT. Even the Melody developers themselves don’t see everyone ditching Movable Type. For one, the enterprise-level editions of Movable Type have a bevy of features (not least among which is paid support) that won’t show up in Melody any time soon. That and Melody’s developers don’t see it as being part of their project’s focus to try and eclipse MT’s high-end, paying-customers features. (Melody’s own FAQ discourages using the paid-support add-ons for MT with Melody, because of the licensing and support-contract restrictions involved.) Melody’s current interface is based on the 4.x branch of Movable Type, and so most closely resembles that program with only minimal changes.
Read more
  • 0
  • 0
  • 2864
Modal Close icon
Modal Close icon