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-quality-assurance-asterisk-16
Packt
18 Nov 2009
10 min read
Save for later

Quality Assurance in Asterisk 1.6

Packt
18 Nov 2009
10 min read
The world has changed quite a bit in the last 150 years. Over this time, the telephone system has been invented, improved, and automated. Telephone switches no longer refer to people sitting in a large room connecting wires between the appropriate jacks. Flexible and powerful telephone service has moved from a dream to an expectation in large businesses, and for most of us it is a necessity. Today, telephone systems are the lifeblood of business. They are how we take orders, acquire supplies, and even call for emergency assistance. With the increase in prominence of telephones, the expectations of telephone users have increased proportionally. Not only have the technological expectations for telephone systems increased dramatically, but consumers are expecting more and more out of the businesses they call. Customers expect to be helped quickly and professionally. They want to know everything in a matter of minutes. Roads do not hold the only rage our society is facing today. As a business we have a variety of questions relating to our telephone system such as: How are our personnel handling angry callers? Are our employees answering the calls in a reasonable amount of time? Do we have any workers using the phone system for personal calls when they should be doing their job? We will never be able to make sure everybody does what they are supposed to do all of the time. What we will be able to do at the end of this article is perform spot-checks on how we are doing on customer service, and make sure our phone service isn't being used for unauthorized purposes. Ultimately, it comes down to a matter of trust; however, some people do not know better because they haven't been fully trained. Most will always act honorably; however, some just cannot and should not be trusted. We will try to find out who is who. Call Detail Records When we talk about security, what images come to mind? May be a big, burly guard? Perhaps a bunch of guys in green, carrying machine guns? Do we imagine a person with a metal-detecting wand? Or do we think of thick glass window panes? All of these are security features. It is just that some are a little more intrusive than others. Each time we increase security, we become a little bit less friendly. We all have to decide how far we are willing (and able) to go. In the continuum of security, Call Detail Records are the least intrusive. No special usernames or passwords have to be remembered. No fear of big brother breathing down your customers' and users' necks need be felt. We are simply doing the same thing telephone companies do—tracking what calls were made, when they were made, how long they lasted, where they came from, and a few other bits of information. This information is then available for us to review at our leisure. Asterisk gives us a few options on how we track this information. The two major choices are flat-file logging and database logging. Flat-file CDR logging By default, Asterisk includes a module called cdr_csv. Right out of the box, Asterisk logs all calls coming in and going out. The information for these calls is placed in a Comma Separated Value (CSV) file. This CSV file is located in var/log/asterisk/cdr-csv. All information is available in Master.csv, and some channels can be configured to send some information to other files as well. The benefit of using a CSV file is the simplicity. Right after compiling and installing Asterisk, this method will work. No additional configuration is required. Also, no additional network traffic is generated, and no additional services have to be installed on our server. When using the CSV form of CDR, we will see lists and lists of values. They are not very easy to parse, so here is the format, in the order in which they appear: account code: As determined by the channel (for DAHDI) or the user (for IAX and SIP) source: The source of the call destination: The destination of the call destination context caller ID channel: The channel of the source destination channel: If applicable last application: The last application run on the channel last application argument: The last argument to the last application on the channel start time: The time the call commenced answer time: The time the call was answered end time: The time the call ended duration: The difference between start time and end time billable seconds: The difference between answer time and end time, which must be less than the duration disposition: Either ANSWERED, NO ANSWER, or BUSY amaflags: As set for the channel or user, like account code uniqueid: A unique call identifier userfield: A user field set by the SetCDRUserField command We see that there are many items of information logged for each and every call. We can compare the billable seconds with our phone bill at the end of the month to make sure they're close. We can look at the destination and figure out if the calls were authorized. This gives us enough information to answer most questions we may have about a phone call. While we have enough information to answer questions, finding that answer is not very easy. We would have to scan through the entire file to try to find anything. If we are going to use an accounting package or reporting software, CSV may be exactly what we need. However, if we wish to use it in a more ad hoc sort of way, it is not very readable. Database CDR logging If we wish to read our CDR logs, it is most easily accomplished when the records are sortable. The easiest way to do this is to store our CDR records in a database. Even in this, Asterisk gives us choices. Included with Asterisk is support for PostgreSQL databases. In order to be able to install this, we must first have the postgresql-devel package installed on our system. If you have to install this package, you'll need to reinstall Asterisk. The automake system will automatically detect that we have the capability to use PostgreSQL and compile that module for us. Aside from the development packages we have installed, we will also need a PostgreSQL server somewhere in our network. It can be the same machine as the Asterisk server, but it doesn't necessarily need to be. In fact, it probably makes sense to have only one such database server on our network, and we don't want to tie up too much of our PBX's resources with database maintenance and storage. There is a script in /usr/src/asterisk/contrib/scripts/ called postgres_cdr.sql, which creates the correct table structure for us. This script should be run from the database server. If we get an error message while rebuilding that says something like "cannot find-lz", then we need to install zlib-devel. Now that we have set up our database and installed the CDR module, we must configure Asterisk to use the correct database. In order to do this, we need to edit /etc/asterisk/cdr_pgsql.conf. All of the configuration variables are in the global section. Our file should look like the following: [global]hostname=dbserver.mydomain.tldport=5432dbname=asteriskpassword=supersecretuser=asteriskuser Once we have these variables set, the next time we restart Asterisk, all CDR records will be logged in the database. If PostgreSQL is not our database of choice, we can use MySQL. This is not a part of the normal distribution of Asterisk. But as we have already installed asterisk-addons, we should already have the ability to use MySQL for CDR logging. Before we compile, we need to make sure that we have mysql-devel installed. First, we need to decide which version we're going to use. Because of some license quibbles, MySQL version 4.0 and later is not in the automatic package distribution chain. Instead, if we do need to download it, we will have to get it directly from www.mysql.com. However, the older version (3.x) will work with Asterisk and hence, you may wish to take a look at the differences between what version 3 offered and what later versions give us. Other than the development package mentioned, we will also need a MySQL server somewhere in our network. Just as with PostgreSQL, we can choose to have it on the same server as Asterisk, but for the same reasons, we probably shouldn't. Next, on the database server, we need to create the database with a user and a table for the CDR data. We do this by running the following code: # mysqladmin create database asteriskcdrdb # mysqlmysql> GRANT ALL PRIVILEGES   -> ON asteriskcdrdb.*   -> TO asteriskcdruser   -> IDENTIFIED BY 'changethis2yourpassword';mysql> USE asteriskcdrdb;mysql> CREATE TABLE cdr (   -> uniqueid varchar(32) NOT NULL default '',   -> userfield varchar(255) NOT NULL default '',   -> accountcode varchar(20) NOT NULL default '',   -> src varchar(80) NOT NULL default '',   -> dst varchar(80) NOT NULL default '',   -> dcontext varchar(80) NOT NULL default '',   -> clid varchar(80) NOT NULL default '',   -> channel varchar(80) NOT NULL default '',   -> dstchannel varchar(80) NOT NULL default '',   -> lastapp varchar(80) NOT NULL default '',   -> lastdata varchar(80) NOT NULL default '',   -> calldate datetime NOT NULL default '0000-00-00 00:00:00',   -> duration int(11) NOT NULL default '0',   -> billsec int(11) NOT NULL default '0',   -> disposition varchar(45) NOT NULL default '',   -> amaflags int(11) NOT NULL default '0'-> ); That's all there is to it! We only have to do this once, so it's really not so bad. Next, we have to modify the /etc/asterisk/cdr_mysql.conf file to correctly reflect our choices. [global]hostname=ourdbserver.ourdomain.tlddbname=asteriskcdrdbpassword=changethis2yourpassworduser=asteriskcdruserport=3306userfield=1 The next time we restart Asterisk, our CDR information will be stored in the MySQL database. What does that give us? We now have the ability to use a number of very powerful tools to search our CDR records to find trends and patterns.
Read more
  • 0
  • 0
  • 1680

article-image-applying-special-effects-3d-game-development-microsoft-silverlight-3-part-1
Packt
18 Nov 2009
7 min read
Save for later

Applying Special Effects in 3D Game Development with Microsoft Silverlight 3: Part 1

Packt
18 Nov 2009
7 min read
  A 3D game must be attractive. It has to offer amazing effects for the main characters and in the background. A spaceship has to fly through a meteor shower. An asteroid belt has to draw waves while a UFO pursues a spaceship. A missile should make a plane explode. The real world shows us things moving everywhere. Most of these scenes, however, aren't repetitive sequences. Hence, we have to combine great designs, artificial intelligence (AI), and advanced physics to create special effects. Working with 3D characters in the background So far, we have added physics, collision detection capabilities, life, and action to our 3D scenes. We were able to simulate real-life effects for the collision of two 3D characters by adding some artificial intelligence. However, we need to combine this action with additional effects to create a realistic 3D world. Players want to move the camera while playing so that they can watch amazing effects. They want to be part of each 3D scene as if it were a real life situation. How can we create complex and realistic backgrounds capable of adding realistic behavior to the game? We can do this combining everything we have learned so far with a good object-oriented design. We have to create random situations combined with more advanced physics. We have to add more 3D characters with movement to the scenes. We must add complexity to the backgrounds. We can work with many independent physics engines to work with parallel worlds. In real-life, there are concurrent and parallel words. We have to reproduce this behavior in our 3D scenes. Time for action – adding a transition to start the game Your project manager does not want the game to start immediately. He wants you to add a butt on in order to allow the player to start the game by clicking on it. As you are using Balder, adding a butt on is not as simple as expected. We are going to add a butt on to the main page, and we are going to change Balder's default game initialization: Stay in the 3DInvadersSilverlight project. Expand App.xaml in the Solution Explorer and open App.xaml.cs––the C# code for App.xaml. Comment the following line of code (we are not going to use Balder's services in this class):  //using Balder.Silverlight.Services; Comment the following line of code in the event handler for the Application_Startup event, after the line this.RootVisual = new MainPage();: //TargetDevice.Initialize<InvadersGame>(); Open the XAML code for MainPage.xaml and add the following lines of code after the line (You will see a butt on with the ti tle Start the game.): <!-- A button to start the game --><Button x_Name="btnStartGame" Content="Start the game!" Canvas.Left="200" Canvas.Top="20" Width="200" Height="30" Click="btnStartGame_Click"></Button> Now, expand MainPage.xaml in the Solution Explorer and open MainPage.xaml.cs––the C# code for MainPage.xaml. Add the following line of code at the beginning (As we are going to use many of Balder's classes and interfaces.): using Balder.Silverlight.Services; Add the following lines of code to program the event handler for the button's Click event (this code will initialize the game using Balder's services): private void btnStartGame_Click(object sender, RoutedEventArgs e){ btnStartGame.Visibility = Visibility.Collapsed; TargetDevice.Initialize<InvadersGame>();} Build and run the solution. Click on the Start the game! butt on and the UFOs will begin their chase game. The butt on will make a transition to start the game, as shown in the following screenshots:   What just happened? You could use a Start the game! butt on to start a game using Balder's services. Now, you will be able to offer the player more control over some parameters before starting the game. We commented the code that started the game during the application start-up. Then, we added a button on the main page (MainPage). The code programmed in its Click event handler initializes the desired Balder.Core.Game subclass (InvadersGame) using just one line: TargetDevice.Initialize<InvadersGame>(); This initialization adds a new specific Canvas as another layout root's child, controlled by Balder to render the 3D scenes. Thus, we had to make some changes to add a simple butt on to control this initialization. Time for action – creating a low polygon count meteor model The 3D digital artists are creating models for many aliens. They do not have the time to create simple models. Hence, they teach you to use Blender and 3D Studio Max to create simple models with low polygon count. Your project manager wants you to add dozens of meteors, to the existing chase game. A gravitational force must attract these meteors and they have to appear in random initial positions in the 3D world. First, we are going to create a low polygon count meteor using 3D Studio Max. Then, we are going to add a texture based on a PNG image and export the 3D model to the ASE format, compatible with Balder. As previously explained, we have to do this in order to export the ASE format with a bitmap texture definition enveloping the meshes. We can also use Blender or any other 3D DCC tool to create this model. We have already learned how to export an ASE format from Blender. Thus, this time, we are going to learn the necessary steps to do it using 3D Studio Max. Start 3D Studio Max and create a new scene. Add a sphere with six segments. Locate the sphere in the scene's center. Use the Uniform Scale tool to resize the low polygon count sphere to 11.329 in the three axis, as shown in the following screenshot: Click on the Material Editor button. Click on the first material sphere, on the Material Editor window's upper-left corner. Click on the small square at the right side of the Diffuse color rectangle, as shown in the following screenshot: Select Bitmap from the list shown in the Material/Map Browser window that pops up and click on OK. Select the PNG file to be used as a texture to envelope the sphere. You can use Bricks.PNG, previously downloaded from http://www.freefoto.com/. You just need to add a reference to a bitmap file. Then, click on Open. The Material Editor preview panel will show a small sphere thumbnail enveloped by the selected bitmap, as shown in the following screenshot: Drag the new material and drop it on the sphere. If you are facing problems, remember that the 3D digital artist created a similar sphere a few days ago and he left the meteor.max file in the following folder (C:Silverlight3DInvaders3D3DModelsMETEOR). Save the file using the name meteor.max in the previously mentioned folder. Now, you have to export the model to the ASE format with the reference to the texture. Therefore, select File | Export and choose ASCII Scene Export (*.ASE) on the Type combo box. Select the aforementioned folder, enter the file name meteor.ase and click on Save. Check the following options in the ASCII Export dialog box. (They are unchecked by default): Mesh Normals Mapping Coordinates Vertex Colors The dialog box should be similar to the one shown in the following screenshot: Click on OK. Now, the model is available as an ASE 3D model with reference to the texture. You will have to change the absolute path for the bitmap that defines the texture in order to allow Balder to load the model in a Silverlight application.
Read more
  • 0
  • 0
  • 2844

article-image-version-management-upk-35-part-1
Packt
18 Nov 2009
12 min read
Save for later

Version Management with UPK 3.5: Part 1

Packt
18 Nov 2009
12 min read
Though this implies multi-user environment client/server setup, this article could still be of use to a single user. If you are a lone developer working in a stand-alone environment (sometimes referred to as a single-user environment), you may want to just skip straight to the section Exporting and importing content, at the end of this article. Sorry, but version management in a stand-alone environment is almost nonexistent, so you're largely on your own. In a client/server environment, all content objects are stored on a central server. Developers create and edit content on their own workstation (typically, a PC), and then send this content to a database on the central server for storage when they have finished with it. This is referred to as checking in a content object. If they subsequently want to change a content object that is on the server, they need to check out the content object, change it, and then check it back in. Checking in a content object When you create a content object in a client/server environment, the content object is stored in your local repository (that is, on the client side of the client/server set-up). It is important to understand that your local repository is located on your local workstation. This means that if you have a content object in your local repository, and then move to another workstation, you will not see your local version of this content object on the new workstation. This is because they are located on the workstation on which you created them or checked them out. You should, therefore, always use the same workstation, or check in all of your content objects before moving to a new workstation. Version Difference In UPK 3.5.1 client/server edition, it is possible to choose a specific location for your local repository. Documents that are checked out to your local repository are identified by a green check-mark () to the left of the object details in the Library. You will need to check these objects in if you want them to be stored in the central library so they will be accessible to other developers. Generally, you should do this whenever you have finished working on a content object. However, there are good reasons for checking in objects more frequently. Your local repository is (typically) in the C: drive of your computer, whereas the central library is on a central server. Unless you are very fastidious about backing up your PC, the chances are that the server is backed up more often than your PC, and is usually backed up automatically. Placing your files in the central library will, therefore, provide greater security in terms of having a backup that you can revert to in the event of a disaster. In addition to this, whenever you check in a content object, a back-up of the previous version is taken. Should you need to back out your changes, you can simply revert to a back-up version of the content object. Related to this, content objects are never really deleted from the server library. Actually, they can be deleted, but only by an Administrator, and typically as part of a cleanup. However, if you delete an object (that has never been checked in to the central server) from your local repository, it is gone. Forever! Finally, it is not unheard of that for a local repository to simply disappear when UPK crashes (which thankfully doesn't happen that often, but it has been known to happen). If this does happen to you, then you may again lose all of the content that you currently have checked out even though the Lost documents view, introduced in UPK 3.5, may save you. For all of these reasons, and more, it is recommended that you check in all of the content that is stored in your local repository to the server at least at the end of each work day. Fortunately, UPK provides a quick way of doing this. If you click the Check In All button (), then all of the content objects that you currently have checked out will be checked in again. The downside of this is that if you do check in all of the documents that you are currently working on at the end of the day, you need to remember which objects these are so that you can check them out again the next day. Before checking the documents in, you can use the All Checked Out view to identify all of the documents that you currently have checked out. You can then print this list, and will know which files you need to check out again the next day. There is one further thing to bear in mind when deciding how often you are going to check in your content objects. As mentioned above, UPK retains every version of a content that has been checked in. These are accessible via the Document History, as we will see later. This means that if you check in a content object ten times, then UPK will retain ten versions of it. This can also make it difficult to identify the "released" versions of the content object in the Document History, should you subsequently need to roll back to the last-released version. The Administrator can clean up the database periodically, but the only way of differentiating between versioned drafts and versioned released content objects is by using the check-in comments. These are explained in the section Step 2: Confirming the scope of the check-in, ahead. UPK Workflow The down-side to checking in content objects that you may not have finished working on is that these objects could be mis-perceived as being final, and actually used or published. In some cases, you may have checked some of them out not because you want to change them, but specifically to stop anyone else from changing them. UPK does not provide you with a simple, automatic solution to these shortcomings, but there is a manual workaround that you can use. This is to use the Workflow properties of the objects. UPK does not have a "real" workflow, it does not have "routing" of content objects based on their status, or automatic email notification of content objects that are due for review, or any of the things that you'd expect from workflow functionality. Of course users can use a Custom View to display content objects according to their Workflow properties, but this is still not really "workflow". If you display the Properties for a content object, by clicking on the Properties button (), the last category of properties (at the end of the Properties list) is the Workflow category. Within this, there are two properties: Assigned To: This property allows you to select (from a drop-down list) the user ID of any developer who is authorized to access the content object. If you select your own user ID in this field, then this is an indication to the other developers that they should not work on this content object themselves. State: This property can be used to specify the current status of a content object. The default values are (blank), Not Started, Draft, In Review, and Final. If you select a status of Draft, then this is an indication that you have not finished with the object. An example of the Properties pane, showing the Workflow category, is in the following screenshot: Of course, these Properties do not provide "hard checks". You still rely on people seeing, and then paying attention to, these Properties but it is a start. Some strong guidance from your Project Manager or Team Leader would help, here. Administrators can add, remove, or rename statuses. It is recommended that a suitable set of statuses are established and defined prior to any development work starting, and that these statuses and their meaning are communicated to all developers. Step 1: Selecting the content objects To select content objects for checking in, carry out the steps described below: In the Library, select the content objects that you want to check in. Normally, you will want to check in specific content objects, so you would only select these. As always, you click on a content object to select it. You can Ctrl-click to select multiple objects, or Shift-click to select a series of objects. You can also select a folder in the Library to check in all of the content objects in that folder. Do not worry if some of the objects that are included in your selection are not checked out; UPK will simply ignore these objects during check-in (it will not "error-out"). You can also check in content objects by selecting them in an Outline Element. Once you have selected all of the content objects that you want to check in, click the Check In button (). Step 2: Confirming the scope of the check-in When you check in one or more specific content objects and have not selected a folder in the Library to check in, UPK will automatically check for any content objects that are related to the object that you are checking in. You will be prompted to check these in, as well. An example of this prompt is shown in the following screenshot: What are related documents? In general, they are Web Pages and Packages used by the content object that you are checking in. For example: If you have created, or changed, an Outline Element (Module or Section) then UPK will automatically select all of the content objects (Modules, Lessons, and Topics) included in this Outline Element, along with any Web Pages used by any of these content objects will be selected as well. If you are checking in a Topic for which you have also created a Web Page that is linked to the Concepts pane, then UPK will automatically select this Web Page as a related document during check-in. If you have created a Glossary and are checking this in, the related documents will be all of the Web Pages for the content definitions used by the Glossary. An example of the Related Documents dialog box is shown in the following screenshot: This list of related documents can be confusing, as it does not match the list that you see in the Related Documents pane for the content object that you are checking in. The list will include Web Pages that have been explicitly linked to from the content object that you are checking, but will not include Glossaries, Templates, Packages, or icons, all of which are listed in the Related Documents pane. This limitation is important to understand. If you checked out, and updated, a Glossary and as a result UPK checked out several content objects during the glossary link regeneration, UPK will not identify all of the Glossary elements (Web Pages) as "related documents". You will need to locate these and check them in separately using custom views. Adding to the confusion, the list of related documents will include all of the explicitly-linked content objects, and not only those objects that are currently checked out to you. Do not worry about this – UPK will only physically check in the content objects that you do have checked out (these are the ones that have your User ID in the Checked Out To column of the Related Documents dialog box). In the example above, we are checking in an Outline Element that contains one Topic, which in turn contains a Web Page. The Topic is checked out, but the Web Page is not. Step 3: Specifying a reason for the change When you check in one or more content objects, you will be prompted to enter a short description of the change, as shown in the following screenshot: The title of the content object that you are checking in is shown above the comment text box. If you are checking in multiple content objects, then this will initially specify the first object and (assuming that you deselect the Apply same comments to all documents option) will specify the next object when you click OK. It then moves on to the next object. In this way, you can provide separate comments for each content object, even though you are checking them all in at the same time. Although it is entirely optional, it is a very good practice to always enter a comment. This comment will appear in the object History, and therefore serves as a useful audit log. Specify a reason for the change by carrying out the steps described below: Enter a suitable comment in the space provided. Note that you do not need to specify the date and time of the change, or your user ID. These are captured automatically by UPK. If you are checking in multiple objects, then UPK will initially suggest applying the same comments to all of the objects. You will see that the Apply same comments to all documents checkbox toward the bottom of the dialog box is selected. If you do not want to use the same comment for all objects that you are checking in, then deselect this checkbox. Now, when you click on OK, the Check In Comment dialog box for the next content object in the check-in selection will be displayed. You can repeat the above processing from Step 3. Once you have entered your description of the change (or reason for the change), click on OK. Once you have specified a comment, and clicked on OK for the last time, then the content objects are checked in, and the Library screen is redisplayed.  
Read more
  • 0
  • 0
  • 1800

article-image-datagrid-api-ibm-websphere-extreme-scale-6-part-1
Packt
18 Nov 2009
19 min read
Save for later

The DataGrid API with IBM WebSphere eXtreme Scale 6: Part 1

Packt
18 Nov 2009
19 min read
In a client-server ObjectGrid interaction, local ObjectGrid instances run in the same memory process as the business application. Access to objects stored in the grid is extremely fast, and there are no network hops or routing done on ObjectGrid operations. The disadvantage with a local ObjectGrid instance is that all objects stored in the grid must fit into the heap space of one JVM. The client-server distributed ObjectGrid instances overcomes that single heap space disadvantage by combining the resources of multiple JVMs on multiple servers. These combined resources hide behind the façade of an ObjectGrid instance. The ObjectGrid instance has far more CPU, memory, and network I/O available to it than the resources available to any single client. In this article, we'll learn how to use those resources held by the ObjectGrid instance to co-locate data and business logic on a single JVM. The client-server model relies on a client pulling objects across a network from an ObjectGrid shard. The client performs some operations on those objects. Any object whose state has changed must be sent back across the network to the appropriate shard. The client-server programming model co-locates data and code by moving data to the code. The data grid programming model does the opposite by moving code to the data. Rather than dragging megabytes of objects from an ObjectGrid shard to a client, only to send it right back to the ObjectGrid, we instead send our much smaller application code to an ObjectGrid shard to operate on the data in place. The end result is the same: code and data are co-located. We now have the resources of an entire data grid available to run that code instead of one client process. What does DataGrid do for me? The DataGrid API provides encapsulation to send application-specific methods into the grid and operate directly on the objects in shards. The API consists of only five public classes. These five classes provide us with several patterns to make an ObjectGrid instance do the heavy lifting for a client application. The client application did a lot of work by operating on the objects in the grid. The client requires a network hop to get an object from the grid and performs an operation on it, persisting that the object requires another network hop to the grid. In a single client environment, the probable bottlenecks in dealing with ObjectGrid are all on the client side. A single client will not stress the resources in the ObjectGrid deployment. The client application is most likely the bottleneck. With all computers in a deployment being equal, one client application on one computer will not stress the combined resources of the grid. In a naïve application that performs single object get and put operations, our application will first notice a bottleneck due to data starvation. This is where a client cannot get the data it needs fast enough, caused by network latency. Single object get and put operations (and the corresponding Entity API calls) won't saturate a gigabit ethernet connection by any means, but the latency in making the RPC is higher than what the CPU can handle. The application works, but it's slow. A smarter application would use the ObjectMap#getAll method. This would go out to the grid and get an object for every key in the list. Instead of waiting for each individual object, the client application waits for the entire list to come over the network. While the cost of network RPC is amortized over the size of the list, the client still incurs that cost. In addition to these network latency concerns, we may not want a near-cache that eats up client-side memory. Turning off the near-cache means that every get operation is an RPC. Turning it on means that some of our JVM heap space is used to store objects, which we may not need after the first use. The fundamental problem is that our objects and client application are architecturally separated. For our application to do anything, it needs to operate on objects that exist in the grid. In the client-server model, we copy data from the server to the client. At this point, our data and code are co-located, and the application can perform some business logic with that data. This model breaks down when there are huge data sets copied between boxes. Databases co-locate data and code with stored procedures. The processing power of the stored procedure is a product of the CPU and memory resources of the computer running the database. The stored procedure is code compiled into a module and executed by the database. Within that process, the stored procedure accesses data available in the same process. ObjectGrid gives us the ability to run code in the same process that gives an object access via the DataGrid API. Unlike the database example, where the throughput and latency of getting the store procedure result is limited to the power of the server it's on, ObjectGrid's power is limited by the number of CPUs in the deployment, and it can scale out at any time. ObjectGrid co-locates our code and objects by sending serialized classes with our application code methods to primary partitions in the grid. There are two ways to do this. The first way sends the code to every primary partition in the grid. The code executes and returns a result to the client. In the second way, we supply a collection of keys to the DataGrid API. With a list of keys, ObjectGrid only sends the application code to the partitions that contain at least one object with a key in the list. This reduces the amount of container processes doing the work for our client application, and is preferred instead of making the entire grid service on one client request. Let's look at finding an object by key in the client-server distributed model. The client has a key for an object. Calling the ObjectMap#get(key) method creates some work for the client. It first needs to determine to which partition the key belongs. The partition is important because the ClientClusterContext, already obtained by the client, knows how to get to the container that holds the primary shard in one hop. We find out the partition ID (pID) for a key with the PartitionManager class: BackingMap bMap = grid.getMap("Payment");PartitionManager pm = bMap.getPartitionManager();int pId = pm.getPartition(key); After obtaining the partition ID and the host running the container process, the client performs a network hop to request the object. The object is serialized and sent back to the client, where the client performs some operation with the object. Persisting an updated object requires one more network hop to put it back in the primary shard. We can now repeat that process for every object in our multi-million object collection. On second thought, that may not be such a great idea. Instead, we'll create an agent that we send to the grid. The agent encapsulates the logic we want to perform. An AgentManager serializes the agent and sends it to each primary shard in the deployment. Once on a primary shard, the agent executes and produces a result which is sent back to the client.   Borrowing from functional programming The DataGrid API borrows the "map" and "reduce" concepts from the world of functional programming. Just so we're all on the same page, let's go over the concepts behind these two functions. Functional programming focuses more on what a program does, instead of how it does it. This is in contrast to the most imperative programming we do in the C family of languages. That's not to say we can't follow a functional programming model, it's just that we don't. Other languages, like Lisp and its descendants, make functional programming the natural thing to do. Map and reduce are commonly found in functional programming. They are known as higher-order functions because they take functions as arguments. This is similar to how we would use a function pointer in C, or an anonymous inner class in Java, to implement callbacks. Though the focus is on what to do, at some point, we need to tell our program how to do it. We do this with the function passed as an argument to map or reduce. Let's look at a simple example in Ruby, which has both functional and imperative programming influences: >> numbers = [0,1,2,3,4,5,6,7,8,9]>> numbers.map { |number| number * 2 }=> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] We assign an array of numbers 0-9 to the variable numbers. The array has a method called map that we call in the second line. Map is a higher-order function and accepts a function as its argument. The Array#map method calls the passed-in function for each element in the array. It passes the element in the variable numbers. In this way, we return a new array that contains the results of each call to our function which performs number * 2. Let's look at the reduce method. In Ruby, reduce is called inject but the concept is the same: >> numbers = [0,1,2,3,4,5,6,7,8,9]>> numbers.inject(0) { |sum, number| sum = sum + number }=> 45 The inject (read as reduce) method takes a function that performs a running total on the numbers in the array. Instead of an array as our return type, we only get one number. The reduce operation returns a single result for an entire data set. The map operation returns a new set based on running the original set through a given function. These concepts are relevant in the data grid environment because we work with large data sets where we frequently need to work with large segments of data. Pulling raw data across the network, and operating over the data set on one client, are both too slow. Map and reduce helps us by using the remote CPU resources of the grid to cut down on the data sent across the network and the CPU power required on the client. This help comes from writing methods that work like map and reduce and sending them to our objects in the grid. java.util.M  ap, BackingMaps, ObjectMaps, HashMaps, like we need one more use for the word "map". We just saw the functional origin of the map concept. Let's take a look at a Java implementation. Map implements an algorithm that performs an operation on each element in a collection and returns a new collection of results: public Collection doubleOddInts(Collection c) {Collection results = new HashSet();Iterator iter = c.iterator();while (iter.hasNext()) {int i = (Integer)iter.next();if (i % 2 == 0) {[ 172 ]results.add(i);} else {results.add(i*2);}}return results;} Our needs go beyond performing a map function over an array. In order to be useful in a DataGrid environment, the map function must operate on a distributed collection of objects in an ObjectGrid instance. The DataGrid API supports this by giving us the MapGridAgent interface. A business logic class implements the two methods in MapGridAgent to encapsulate the code we intend to run in the grid. Classes that implement MapGridAgent must implement two methods, namely, MapGridAgent#process(Session session, ObjectMap map, Object key) and MapGridAgent#processAllEntries(Session session, ObjectMap map). Let's implement the doubleOddInts algorithm with MapGridAgent. We first create a class that implements the MapGridAgent interface. We give this class a meaningful name that describes the map operation implemented in the process methods: public class DoubleOddIntsMapAgent implements Serializable,MapGridAgent {public Object process(Session session, ObjectMap map, Object key){int i = (Integer)map.get(key);if (i % 2 == 0) {return i;} else {return i*2;}}public Map processAllEntries(Session session, ObjectMap map) {// nothing to do here for now!}} The map function itself is called by our client code. The process (session, map, key) method performs the how in the map function. Because ObjectGrid gives us the what for free (the map function), we only need to implement the how part. Like the Ruby example, this process (session, map, key) method is performed for each element in a collection. The Session and ObjectMap arguments are supplied by the AgentManager based on the current session and ObjectMap that starts the map function. The key is the crucial object for a given value in the collection, and that collection is supplied by us when we run the DoubleOddIntsMapAgent. After implementing the MapGridAgent#process(session, map, key) method, the DoubleOddIntsMapAgent is ready to run. We want it to run on each shard in an ObjectGrid instance that has a key in the collection we pass to it. We do this with an instance of the AgentManager class. The AgentManager class has two methods to send a MapGridAgent to the grid: AgentManager#callMapAgent(MapGridAgent agent, Collection keys) and AgentManager#callMapAgent(MapGridAgent agent). The first method provides a set of keys for our agent to use when run on each partition. Using this method is preferable to the non-keyed version because the non-keyed version runs the code on every primary shard in the grid. The Agent Manager#callMapAgent(agent, keys) method only runs the code on primary partitions that contain at least one key in the key collection. Whenever we have the choice to use part of the grid instead of the entire grid, we should take the choice that uses only part of the grid. Whenever we use the entire grid for one operation, we limit scalability and throughput. The AgentManager serializes the DoubleOddIntsMapAgent agent and sends it to each partition that has a key in the keys collection. Once on the primary partition, the process (session, map, key) method is called for each key in the keys collection supplied to AgentManager#callMapAgent(agent, keys). This set of keys is a subset of all of the keys in the BackingMap, and likely a subset of keys in each partition. Let's create an instance of this agent and submit it to the grid: Collection numbers = new ArrayList();for(int i = 0; i < 10000; i++) {numbers.add(i);}MapGridAgent agent = new DoubleOddIntsAgent();AgentManager am = session.getMap("Integer").getAgentManager();am.callMapAgent(agent, numbers); This example assumes that we have a BackingMap of Integer for both the key and value objects. The numbers collection is a list of keys to use. Once we create the agent, we submit it to the grid with the 10,000 keys to operate on. Before running the agent, the AgentManager sorts the keys by partition. The agent only runs on partitions that have a list of keys that hash to that partition. The agent runs on each partition that has a list of keys that hash to it. In each primary partition, the DoubleOddIntsMapAgent#process(session, map, key) method is called only for the keys that map to that partition. GridAgent and Entity GridAgent works with Entity classes as well. We don't directly use key objects when working with Entity objects. The Entity API hides the key/value implementation from us to make working with Entity objects easier than working with the ObjectMap API. The method definition for MapGridAgent#process(session, map, key) normally expects an object to be used as a key for an ObjectMap. We can still find the value object by converting key and value objects to their Tuple representations, but the DataGrid API makes it much easier for us. Instead of passing a key to the process method, we can convince the primary shard to pass us the Entity object itself, rather than a key using the EntityAgentMixin interface. EntityAgentMixin has one method, namely, EntityAgentMixin#getClassForEntity(). The implementation of this method should return the class object of the Entity. DataGrid needs this method defined in the grid agent implementation so it can provide the Entity object itself, rather than its key to the MapGridAgent#process(session, map, key) method. Let's assume that we have an Entity MyInteger that acts as a wrapper for Integer: public class DoubleOddIntsMapAgent implements Serializable,MapGridAgent, EntityAgentMixin {public Object process(Session session, ObjectMap map, Object key){MyInteger myInt = (MyInteger)key;if (myInt.mod(2) == 0) {return myInt;} else {return myInt.multiplyBy(2);}}public Map processAllEntries(Session session, ObjectMap map) {// nothing to do here for now!}public Class getClassForEntity() {return MyInteger.class;}} Our agent now implements the EntityAgentMixin interface and the getClassForEntity() method. The key is converted to the correct class before the MapGridAgent#process(session, map, key) method is called. Instead of the Tuple key for an Entity, the process method is passed a reference to the Entity itself. Because it is passed as an object, we must cast the Entity to its defined class. There is no need to look up for the Entity in its BackingMap because it's already the Entity we want to work with. This means the collection of keys passed to AgentManager#callMapAgent(agent, keys) is a collection with all elements of the c lass returned by getClassForEntity(). GridAgent with an unknown key set We may not always know the keys for each object we want to submit to an agent. In this situation, we send an agent into the grid without a key set. The grid agent cannot call the process (session, map, key) method because we don't know which keys to use. Instead, our grid agent method relies on the Query API to narrow the number of objects in each partition we work with. The MapGridAgent interface gives us the MapGridAgent#processAllEntries(Session session, ObjectMap map) method for this situation. The MapGridAgent#processAllEntries(session, map) method lets us specify what to do when we potentially need to work with all objects in a partition. Particularly, it lets us narrow the field with a query. In the past, we used a query to find card and address objects in a local ObjectGrid instance. This was fine for local instances with only one partition. The real power of the Query API is revealed when used with the DataGrid API. Query does not work across partitions when called from an ObjectGrid client in a distributed environment. It works with just one partition. In a distributed deployment, where we use the DataGrid API, a grid agent instance runs on one partition. Each partition has an instance of the grid agent running in it and each agent can see the objects in its partition. If we have 20 partitions, then we have 20 grid agents running, one in each partition. Because we're working with a single partition in each grid agent, we use the Query API to determine which objects are of interest to the business logic. Now that we know how to run code in the grid, the Query API is suddenly much more useful. Now, we want a query to run against just one partition. Using a query in a GridAgent is a natural fit. Each agent runs on one partition, and each query runs on that partition in the primary shard container process: public class DoubleOddIntsMapAgent implements Serializable,MapGridAgent, EntityAgentMixin {public Object process(Session session, ObjectMap map, Object key){MyInteger myInt = (MyInteger)key;if (myInt.mod(2) == 0) {return myInt;} else {return myInt.multiplyBy(2);}}public Map processAllEntries(Session session, ObjectMap map) {EntityManager em = session.getEntityManager();Query q = em.createQuery("select m from MyInteger m " +"where m.integer > 0 " +"and m.integer < 10000");Iterator iter = q.getResultIterator();Map<MyInteger, Integer> results =new HashMap<MyInteger, Integer)();while (iter.hasNext()) {MyInteger mi = (MyInteger)iter.next();results.put(mi, (Integer)process(session, map, mi));}return results;}public Class getClassForEntity() {return MyInteger.class;}} The MapGridAgent#processAllEntries(session, map) method generally follows the same pattern when implemented: Narrow the scope of objects in the partition. This is important in the MapGridAgent because it returns a result for every object it processes. This can result in hundreds of megabytes of objects sent back to a client from every partition for an indiscriminate query. Create a map to hold the results of each process operation. This map is keyed with the key object, or the value object, when using ObjectMap. The client application can perform its own gets if the keys are returned. Otherwise, it works directly with the value objects. We can also return a map of key/value objects. The map is keyed with the Entity class itself when using Entity. Iterate over the query results calling MapGridAgent#process(session, map, key) for each result. Calling the process method is required here since we didn't pass a collection of keys to the AgentManager#callMapAgent(agent) method. The key set is unknown before the agent runs. The agent finds all objects in a partition that meet our criteria for processing, and then we call process to get each result. Return the results. This map contains an entry for each object that meets our processing criteria in this partition. This map is merged, client-side, with the maps from every other partition where the agent ran. The merged map is the final result, and it is the return value to the AgentManager#callMapAgent(agent) method. Following the call to AgentManager#callMapAgent(agent), we have a Map that contains the combined agent results from every partition. We also split the workload between N partitions rather than performing all of the processing on the client. The ObjectGrid deployment performed our business logic because we passed the business logic to the grid rather than pulling objects out of the grid. One of the great things about this pattern is that our task on many partitions completes in about 1/Nth the amount of time it would take for one huge partition containing the same objects running on one computer. Of course, there is the overhead of the merge operation and network connections, but this is amortized over the number of primary partitions used by the agent. This is distinctly different than scaling up a database server when it needs more CPU speed for stored procedures. Instead of incurred downtime for database server migration, we simply add more containers on additional computers. The power of our grid increases as easily as starting a few more JVMs. >> Continue Reading: The DataGrid API with IBM WebSphere eXtreme Scale 6: Part 2
Read more
  • 0
  • 0
  • 1388

article-image-build-advanced-contact-manager-using-jboss-richfaces-33-part-3
Packt
18 Nov 2009
11 min read
Save for later

Build an Advanced Contact Manager using JBoss RichFaces 3.3: Part 3

Packt
18 Nov 2009
11 min read
  The ajaxSingle and the process attributes The ajaxSingle property is very useful to control the form submission when ajaxSingle is set to true—the form is not submitted and, just the Ajax component data is sent. This attribute is available in every Ajax action component and we can use it to call an action from a button, skipping the form validation (like the JSF immediate property does), or to send the value of just an input into a form without validation and submitting the other ones. The second use case can be used, for example, when we need an input menu that dynamically changes the value of other inputs without submitting the entire form: <h:form> <!-- other input controls --> <h:selectOneMenu id="country" value="#{myBean.selectedCountry}"> <f:selectItems value="#{myBean.myCountries}"> <a:support event="onchange" ajaxSingle="true" reRender="city" /> </h:selectOneMenu> <h:selectOneMenu id="city" value="#{myBean.selectedCity}"> <f:selectItems value="#{myBean.myCities}"> </h:selectOneMenu> <!-- other input controls --></h:form> In this example, every time the user selects a new country, the value is submitted to the bean that recalculates the myCities property for the new country, after that the city menu will be re-rendered to show the new cities. All that without submitting the form or blocking the changes because of some validation problem. What if you would like to send more than one value, but still not the entire form? We can use Ajax regions (we will see in the next sections), or we can use the process attribute. It contains a list of components to process while submitting the Ajax action: <h:form> <!-- other input controls --> <h:inputText id="input1" ... /> <h:selectOneMenu id="country" value="#{myBean.selectedCountry}"> <f:selectItems value="#{myBean.myCountries}"> <a:support event="onchange" ajaxSingle="true" process="input2, input3" reRender="city" /> </h:selectOneMenu> <h:inputText id="input2" ... /> <h:inputText id="input3" ... /> <h:selectOneMenu id="city" value="#{myBean.selectedCity}"> <f:selectItems value="#{myBean.myCities}"> </h:selectOneMenu> <!-- other input controls --></h:form> In this example, we also wanted to submit the input2 and the input3 values together with the new country, because they are useful for retrieving the new cities list—just by setting the process attribute with the id list and during the submission, they will be processed. Thus input1 will not be sent. Also, for action components such as buttons, you can decide what to send using the ajaxSingle and process attributes. Form submission and processingWe speak about form "submission" to simplify the concept and make things more understandable. In reality, for every request, all of the form is submitted, but only the selected components (using ajaxSingle and/or process attributes) will be "processed". By "processed" we mean "pass through" the JSF phases (decoding, conversion, validation, and model updating). More Ajax! For every contact, we would like to add more customizable fields, so let's use the ContactField entity connected to every Contact instance. First of all, let's create a support bean called HomeSelectedContactOtherFieldsHelper inside the book.richfaces.advcm.modules.main package. It might look like this: @Name("homeSelectedContactOtherFieldsHelper")@Scope(ScopeType.CONVERSATION)public class HomeSelectedContactOtherFieldsHelper { @In(create = true) EntityManager entityManager; @In(required = true) Contact loggedUser; @In FacesMessages facesMessages; @In(required = true) HomeSelectedContactHelper homeSelectedContactHelper; // my code} A notable thing is highlighted—we injected the homeSelectedContactHelper component, because to get the list of the customized fields from the database, we need the contact owner. We also set the required attribute to true, because this bean can't live without the existence of homeSelectedContactHelper in the context. Now, let's add the property containing the list of personalized fields for the selected contact: private List<ContactField> contactFieldsList;public List<ContactField> getContactFieldsList() { if (contactFieldsList == null) { // Getting the list of all the contact fields String query = "from ContactField cf where cf.contact.id=:idContactOwner order by cf.id"; contactFieldsList = (List<ContactField>) entityManager.createQuery(query) .setParameter("idContactOwner", homeSelectedContactHelper.getSelectedContact() .getId()).getResultList(); } return contactFieldsList;}public void setContactFieldsList(List<ContactField> contactFieldsList) { this.contactFieldsList = contactFieldsList;} As you can see, it is a normal property lazy initialized using the getter. This queries the database to retrieve the list of customized fields for the selected contact. We have to put into the bean some other method useful to manage the customized field (adding and deleting field to and from the database), let's add those methods: public void createNewContactFieldInstance() { // Adding the new instance as last field (for inserting a new field) getContactFieldsList().add(new ContactField());}public void persistNewContactField(ContactField field) { // Attaching the owner of the contact field.setContact(homeSelectedContactHelper.getSelectedContact()); entityManager.persist(field);}public void deleteContactField(ContactField field) { // If it is in the database, delete it if (isContactFieldManaged(field)) { entityManager.remove(field); } // Removing the field from the list getContactFieldsList().remove(field);}public boolean isContactFieldManaged(ContactField field) { return field != null && entityManager.contains(field);} The createNewContactFieldInstance() method will just add a new (not yet persisted), empty instance of the ContactField class into the list. After the user has filled the values in, he/she will press a button that calls the persistNewContactField() method to save the new data into the database. In order to delete it, we are going to use the deleteContactField() method, and to determine if an instance is persisted into the database or not, we are going to use the isContactFieldManaged() method. Now, let's open the /view/main/contactView.xhtml file and add the code to show the personalized fields after h:panelGrid— i shows the standard ones: <a:repeat value="#{homeSelectedContactOtherFieldsHelper.contactFieldsList}" var="field"> <h:panelGrid columns="2" rowClasses="prop" columnClasses="name,value"> <h:outputText value="#{field.type} (#{field.label}):"/> <h:outputText value="#{field.value}"/> </h:panelGrid></a:repeat> We are using a new RichFaces data iteration component that permits us to iterate over a collection and put the data we want (the rich:dataTable component would instead create a table for the elements list). In our case, the h:panelGrid block will be repeated for every element of the collection (so for every customized field). Now, let's open the /view/main/contactEdit.xhtml file and add the code for editing the customized fields into the list: <a:region> <a:outputPanel id="otherFieldsList"> <a:repeat value="#{homeSelectedContactOtherFieldsHelper. contactFieldsList}" var="field"> <h:panelGrid columns="3" rowClasses="prop" columnClasses="name,value,validatormsg"> <h:panelGroup> <h:inputText id="scOtherFieldType" value="#{field.type}" required="true" size="5"> <a:support event="onblur" ajaxSingle="true"/> </h:inputText> <h:outputText value=" ("/> <h:inputText id="scOtherFieldLabel" value="#{field.label}" size="5"> <a:support event="onblur" ajaxSingle="true"/> </h:inputText> <h:outputText value=")"/><br/> <rich:message for="scOtherFieldType" styleClass="messagesingle" errorClass="errormsg" infoClass="infomsg" warnClass="warnmsg"/> </h:panelGroup> <h:panelGroup> <h:inputText id="scOtherFieldValue" value="#{field.value}" required="true"> <a:support event="onblur" ajaxSingle="true"/> </h:inputText><br/> <rich:message for="scOtherFieldValue" styleClass="messagesingle" errorClass="errormsg" infoClass="infomsg" warnClass="warnmsg"/> </h:panelGroup> <h:panelGroup> <a:commandButton image="/img/add.png" reRender="otherFieldsList" action="#{homeSelectedContactOtherFieldsHelper. persistNewContactField(field)}" rendered="#{!homeSelectedContactOtherFieldsHelper. isContactFieldManaged(field)}"> </a:commandButton> <a:commandButton image="/img/remove.png" reRender="otherFieldsList" ajaxSingle="true" action="#{homeSelectedContactOtherFieldsHelper. deleteContactField(field)}"> </a:commandButton> </h:panelGroup> </h:panelGrid> </a:repeat> <a:commandLink reRender="otherFieldsList" ajaxSingle="true" action="#{homeSelectedContactOtherFieldsHelper. createNewContactFieldInstance}" rendered="#{homeSelectedContactHelper. selectedContactManaged}" styleClass="image-command-link"> <h:graphicImage value="/img/add.png"/> <h:outputText value="#{messages['addNewField']}"/> </a:commandLink> </a:outputPanel></a:region> The code looks very similar to the one in the view box, except for the action buttons (to add a new instance, persist, save, or delete) and, for the presence of the surrounding tag a:region (highlighted). This is very important in order to make sure the form works correctly; we will see why in the next section. Also, notice that every input component has the a:support tag as a child that will update the bean with the edited value at the onblur event (which means that every time you switch the focus to another component, the value of the last one is submitted). So, if you delete or add a field, you will now loose the edited values for other fields. It is also used for Ajax validation, as the user is informed that the value is not valid when it moves the cursor to another input. Here is a screenshot with the new feature in the edit box: Using a:support only for Ajax validation If you want to use the a:support tag only for validation purpose, remember to set its bypassUpdates attribute to true, so the process would be faster as the JSF Update Model and Invoke Application phases will not be invoked. Ajax containers While developing a web application with RichFaces, it's very useful to know how to use Ajax containers (such as the a:region component) in order to optimize Ajax requests. In this section, we'll discuss about the a:region component. It is a very important component of the framework—it can define Ajax areas to limit the part of the component tree to be processed during an Ajax request. Regions can be nested during an Ajax request and the closest one will be used. By setting to true the a:region attribute called regionRenderOnly, you can use this component to limit the elements' update—In this way, in fact, only the components inside the region can be updated. Another important attribute is selfRendered; setting this to true tells the framework to render the response basing on component tree without referring to the page code—it is faster, but all of the transient elements that are not saved in the tree (such as f:verbatim or HTML code written directly without using JSF components) will be lost at the first refresh, so you can't use them in this case. To summarize, it is very useful to control the rendering process and optimize it, in order to limit the elements of a form to send during an Ajax request without validation problems, to show different indicators for Ajax status. Example of using a:region: <h:form> <a:region> <h:inputText id="it1" value="#{aBean.text1}"> <a:support event="onkeyup" reRender="text1" /> </h:inputText> <h:inputText id="it2" value="#{aBean.text2}" /> </a:region> <h:inputText id="it3" value="#{aBean.text3}" /> <a:commandButton action="#{aBean.saveTexts}" reRender="text1,text2" /></h:form><h:outputText id="text1" value="#{aBean.text1}" /><h:outputText id="text2" value="#{aBean.text2}" /> In this example, while the user is typing in the text1 value of inputText, a:support sends an Ajax request containing only the it1 and it2 values of inputText. In this case, in fact, a:region limits the components sent by every Ajax request originated from inside the region. So, the Ajax request will only update aBean.text1 and aBean.text2. Wrapping only a component inside an Ajax region is the equivalent of using the ajaxSingle property set to true. If the user clicks on the a:commandButton aBean.text1, the aBean.text2 and aBean.text3 values will be updated by the Ajax request. Coming back to our application, as all the customized fields are inside the same form component, we surround each one with the a:region tag. In this way, the single field is submitted regardless of the other ones. For example, without using a:region, if the user empties the name input value and then tries to insert a new customized field, the process will fail because the name input is not validated. If we use the a:region component, the name field will not be processed and a new field will be inserted. Now that we know how to use the a:region tag, we can combine it with ajaxSingle and process in order to decide what to send at every request, and to better optimize Ajax interactions into the application.
Read more
  • 0
  • 0
  • 1402

article-image-joomla-flash-showing-maps-using-yos-ammap
Packt
18 Nov 2009
12 min read
Save for later

Joomla! with Flash: Showing maps using YOS amMap

Packt
18 Nov 2009
12 min read
Showing maps using YOS amMap Adding a map to your site may be a necessity in some cases. For example, you want to show the population of countries, or you want to show a world map to your students for teaching geography. Flash maps are always interesting as you can interact with them and can view them as you like. amMap provides tools for showing Flash maps. The amMap tool is ported as a Joomla! component by yOpensource, and the component is released with the name YOS amMap. This component has two versions—free and commercial. The commercial or pro version has some advanced features that are not available in the free version. The YOS amMap component, together with its module, allows you to display a map of the world, a region, or a country. You can choose the map to be displayed, which areas or countries are to be highlighted, and the way in which the viewers can control the map. Generally, maps displayed through the YOS amMap component can be zoomed, centered, or scrolled to left, right, top, or bottom. You can also specify a color in which a region or a country should be displayed. Installing and configuring YOS amMap To use YOS amMap with your Joomla! website, you must first download it from http://yopensource.com/en/component/remository/?func=fileinfo&id=3. After downloading and extracting the compressed package, you get the component and module packages. Install the component and module from the Extensions | Install/Uninstall screen. Once installed, you can administer the YOS amMap component from Components | YOS amMap. This shows the YOS amMap Control Panel, as shown in the following screenshot: YOS amMap Control Panel displays several icons through which you can configure and publish maps. The first thing you should do is to configure the global settings for amMap. In order to do this, click on the Parameters icon in the toolbar. Doing so brings up the dialog box, as shown in the following screenshot: In the Global Configuration section, you can enter a license key if you have purchased the commercial or the pro version of this component. For the free version, this is not needed. In this section, you can also configure the legal extensions of files that can be uploaded through this component, the maximum file size for uploads, the legal image extensions, and the allowed MIME types of all uploads. You can also specify whether the Flash uploader will be used or not. Once you have configured these fields, click on the Save button and return to YOS amMap Control Panel. Adding map files You can see the list of available maps by clicking on the Maps icon on the YOS amMap Control Panel screen or by clicking on Components | amMap | Maps. This shows the Maps Manager screen, as shown in the next screenshot. As you can see, the Maps Manager screen displays the list of available maps. By default, you find the world.swf, continents.swf, and world_with_antartica.swf map files. You will find some extra maps with the amMap bundle. You can also download the original amMap package from http://www.ammap.com/download. After downloading the ZIP package, extract it, and you will find many maps in the maps subfolder. Any map from this folder can be uploaded to the Joomla! site from the Maps Manager screen. Creating a map There are several steps for creating a map using YOS amMap. First we need to upload the package for the map. For example, if we want to display the map of the United States of America, then we need to upload the map template, the map data file, and the map settings file for the United States of America. To do this first upload the map template from the Maps Manager screen. You will find the map template for USA in the ammap/maps folder. Then we need to upload the data and the settings files. For doing so, click on the Upload link on the YOS amMap Control Panel screen. Then, in the Upload amMap screen, which is shown in the next screenshot, type the map's title (United States) in the Title field. Before clicking on the Browse button besides the Package File field, you first add the ammap_data.xml and the ammap_settings.xml files to a single ZIP file, unitedstates.zip. Now, click on the Browse button, and select this unitedstates.zip file. Then click on the Upload File & Install button. Once uploaded successfully, you see this map listed in the YOS amMap Manager screen, as shown in the next screenshot. You get this screen by clicking on the amMaps link on the toolbar. As you can see, the map that we have added is now listed in the YOS amMap Manager screen. However, the map is yet in an unpublished state, and we need to configure the map before publishing it. We need to configure its data and settings files, which are discussed in the following sections. Map data file The different regions of a map are identified by the map data file. This is an XML file and it defines the areas to be displayed on the map. The typical structure of a map data file can be understood by examining ammap_data.xml. The file has many comments that explain its structure. This file looks like as follows: <?xml version="1.0" encoding="UTF-8"?><map map_file="maps/world.swf" tl_long="-168.49" tl_lat="83.63" br_long="190.3" br_lat="-55.58" zoom_x="0%" zoom_y="0%" zoom="100%"><areas> <area title="AFGHANISTAN" mc_name="AF"></area> <area title="ALAND ISLANDS" mc_name="AX"></area> <area title="BANGLADESH" mc_name="BD"></area> <area title="BHUTAN" mc_name="BT"></area> <area title="CANADA" mc_name="CA"></area> <area title="UNITED ARAB EMIRATES" mc_name="AE"></area> <area title="UNITED KINGDOM" mc_name="GB"></area> <area title="UNITED STATES" mc_name="US"></area> <area title="borders" mc_name="borders" color="#FFFFFF" balloon="false"></area></areas><movies> <movie lat="51.3025" long="-0.0739" file="target" width="10" height="10" color="#CC0000" fixed_size="true" title="build-in movie usage example"></movie> <movie x="59.6667%" y="77.5%" file="icons/pin.swf" title="loaded movie usage example" text_box_width="250" text_box_height="140"> <description> <![CDATA[You can add description text here. This text will appear the user clicks on the movie. this description text can be html-formatted (for a list which html tags are supported, visit <u><a href="http://livedocs.adobe.com/flash/8/main/00001459.html">this page</a></u>. You can add descriptions to areas and labels too.]]> </description> </movie></movies><labels> <label x="0" y="50" width="100%" align="center" text_size="16" color="#FFFFFF"> <text><![CDATA[<b>World Map]]></text> <description><![CDATA[]]></description></label></labels><lines> <line long="-0.0739, -74" lat="51.3025, 40.43" arrow="end" width="1" alpha="40"></line> </lines></map> This code is a stripped-down version of the default ammap_data.xml file. Let us examine its structure and try to understand the meaning of each markup: <map> </map>: You define the map's structure using this markup. First, by using the map_file attribute, we declare the map file that should be used to display this map. This markup has some other attributes through which we declare the top and the left offset in longitude and latitude. We can also specify the zooming level using the zoom_x, zoom_y, and zoom attributes. <areas> </areas>: Areas are the regions or countries on a map. These are defined in the map. We only need to define the areas that we want to display. For example, in the sample, we have defined eight countries to be displayed and one straight line. Each area element has several attributes, among which you need to mention mc_name and title. You specify the area's name in mc_name, which is predefined in the map template. The title element will be displayed as the title of that map area. For example, <area mc_name="BD" title="Bangladesh"></area> means the areas marked as BD in the map template will be displayed with the title Bangladesh. In order to specify the mc_name element, you need to follow the map template designer's instructions. <movies> </movies>: Movies are some extra clips that can be displayed as a separate layer on the map. For example, to display the capital of each country, a movie clip could be displayed in the specified latitude and longitude. You can also display some other animations or text using a movie definition. <labels> </labels>: The <labels> markup contains the text to be displayed on the map. You can add any text on a map by defining a label element. To view and edit the map data file, ammap_data.xml, click on the map name on the YOS amMap Manager screen. This opens-up the amMap: [Edit] screen, as shown in the following screenshot: The amMap: [Edit] screen displays several configurations for the map. From the Details section you can change the map name, publish the map, and enable security. From the Design section you can view and edit the data and the settings files. Clicking on Data will show the data file. You can edit the data file from the online editor. As we want to display the map of USA, we will make the following changes on this screen: Select usa.swf in the Maps list. Change the data file as follows: <?xml version="1.0" encoding="UTF-8"?><map map_file="maps/usa.swf" zoom="100%" zoom_x="7.8%"zoom_y="0.18%"><areas> <area mc_name="AL" title="Alabama"/> <area mc_name="AK" title="Alaska"/> <area mc_name="AZ" title="Arizona"/> <area mc_name="AR" title="Arkansas"/> <area mc_name="CA" title="California"/> <area mc_name="CO" title="Colorado"/> <area mc_name="CT" title="Connecticut"/> <area mc_name="DE" title="Delaware"/> <area mc_name="DC" title="District of Columbia"/> <area mc_name="FL" title="Florida"/> <area mc_name="GA" title="Georgia"/> <area mc_name="HI" title="Hawaii"/> <area mc_name="ID" title="Idaho"/> <area mc_name="IL" title="Illinois"/> <area mc_name="IN" title="Indiana"/> <area mc_name="IA" title="Iowa"/> <area mc_name="KS" title="Kansas"/> <area mc_name="KY" title="Kentucky"/> <area mc_name="LA" title="Louisiana"/> <area mc_name="ME" title="Maine"/> <area mc_name="MD" title="Maryland"/> <area mc_name="MA" title="Massachusetts"/> <area mc_name="MI" title="Michigan"/> <area mc_name="MN" title="Minnesota"/> <area mc_name="MS" title="Mississippi"/> <area mc_name="MO" title="Missouri"/> <area mc_name="MT" title="Montana"/> <area mc_name="NE" title="Nebraska"/> <area mc_name="NV" title="Nevada"/> <area mc_name="NH" title="New Hampshire"/> <area mc_name="NJ" title="New Jersey"/> <area mc_name="NM" title="New Mexico"/> <area mc_name="NY" title="New York"/> <area mc_name="NC" title="North Carolina"/> <area mc_name="ND" title="North Dakota"/> <area mc_name="OH" title="Ohio"/> <area mc_name="OK" title="Oklahoma"/> <area mc_name="OR" title="Oregon"/> <area mc_name="PA" title="Pennsylvania"/> <area mc_name="RI" title="Rhode Island"/> <area mc_name="SC" title="South Carolina"/> <area mc_name="SD" title="South Dakota"/> <area mc_name="TN" title="Tennessee"/> <area mc_name="TX" title="Texas"/> <area mc_name="UT" title="Utah"/> <area mc_name="VT" title="Vermont"/> <area mc_name="VA" title="Virginia"/> <area mc_name="WA" title="Washington"/> <area mc_name="WV" title="West Virginia"/> <area mc_name="WI" title="Wisconsin"/><area mc_name="WY" title="Wyoming"/></areas><labels> <label x="0" y="60" width="100%" color="#FFFFFF" text_size="18"> <text>Map of the United States of America</text> </label></labels></map> As you can see, we have defined regions (states) on the map of USA, and towards the end of the file, we have added a label for the map. Select Yes for the Published field in the Details section. When you are done making these changes click on the Save button to save these changes. Now we will look into the map settings file. Map data files for countries are available with the amMap package. Thus, if you download amMap 2.5.1, you will get the map settings files for different countries. For example, the map data file for USA will be in the amMap_2.5.1/examples/_countries/usa folder.  
Read more
  • 0
  • 0
  • 4599
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 €18.99/month. Cancel anytime
article-image-unity-game-development-interactions-part-2
Packt
18 Nov 2009
14 min read
Save for later

Unity Game Development: Interactions (Part 2)

Packt
18 Nov 2009
14 min read
Opening the outpost In this section, we will look at the two differing approaches for triggering the animation giving you an overview of the two techniques that will both become useful in many other game development situations. In the first approach, we'll use collision detection—a crucial concept to get to grips with as you begin to work on games in Unity. In the second approach, we'll implement a simple ray cast forward from the player. Approach 1—Collision detection To begin writing the script that will trigger the door-opening animation and thereby grant access to the outpost, we need to consider which object to write a script for. In game development, it is often more efficient to write a single script for an object that will interact with many other objects, rather than writing many individual scripts that check for a single object. With this in mind, when writing scripts for a game such as this, we will write a script to be applied to the player character in order to check for collisions with many objects in our environment, rather than a script made for each object the player may interact with, which checks for the player. Creating new assets Before we introduce any new kind of asset into our project, it is good practice to create a folder in which we will keep assets of that type. In the Project panel, click on the Create button, and choose Folder from the drop-down menu that appears. Rename this folder Scripts by selecting it and pressing Return (Mac) or by pressing F2 (PC). Next, create a new JavaScript file within this folder simply by leaving the Scripts folder selected and clicking on the Project panel's Create button again, this time choosing JavaScript. By selecting the folder, you want a newly created asset to be in before you create them, you will not have to create and then relocate your asset, as the new asset will be made within the selected folder. Rename the newly created script from the default—NewBehaviourScript—to PlayerCollisions. JavaScript files have the file extension of .js but the Unity Project panel hides file extensions, so there is no need to attempt to add it when renaming your assets. You can also spot the file type of a script by looking at its icon in the Project panel. JavaScript files have a 'JS' written on them, C# files simply have 'C#' and Boo files have an image of a Pacman ghost, a nice little informative pun from the guys at Unity Technologies! Scripting for character collision detection To start editing the script, double-click on its icon in the Project panel to launch it in the script editor for your platform—Unitron on Mac, or Uniscite on PC. Working with OnControllerColliderHit By default, all new JavaScripts include the Update() function, and this is why you'll find it present when you open the script for the first time. Let's kick off by declaring variables we can utilise throughout the script. Our script begins with the definition of four variables, public member variables and two private variables. Their purposes are as follows: doorIsOpen: a private true/false (boolean) type variable acting as a switch for the script to check if the door is currently open. doorTimer: a private floating-point (decimal-placed) number variable, which is used as a timer so that once our door is open, the script can count a defined amount of time before self-closing the door. currentDoor: a private GameObject storing variable used to store the specific currently opened door. Should you wish to add more than one outpost to the game at a later date, then this will ensure that opening one of the doors does not open them all, which it does by remembering the most recent door hit. doorOpenTime: a floating-point (potentially decimal) numeric public member variable, which will be used to allow us to set the amount of time we wish the door to stay open in the Inspector. doorOpenSound/doorShutSound: Two public member variables of data type AudioClip, for allowing sound clip drag-and-drop assignment in the Inspector panel. Define the variables above by writing the following at the top of the PlayerCollisions script you are editing: private var doorIsOpen : boolean = false;private var doorTimer : float = 0.0;private var currentDoor : GameObject;var doorOpenTime : float = 3.0;var doorOpenSound : AudioClip;var doorShutSound : AudioClip; Next, we'll leave the Update() function briefly while we establish the collision detection function itself. Move down two lines from: function Update(){} And write in the following function: function OnControllerColliderHit(hit : ControllerColliderHit){} This establishes a new function called OnControllerColliderHit. This collision detection function is specifically for use with player characters such as ours, which use the CharacterController component. Its only parameter hit is a variable that stores information on any collision that occurs. By addressing the hit variable, we can query information on the collision, including—for starters—the specific game object our player has collided with. We will do this by adding an if statement to our function. So within the function's braces, add the following if statement: function OnControllerColliderHit(hit: ControllerColliderHit){ if(hit.gameObject.tag == "outpostDoor" && doorIsOpen == false){ }} In this if statement, we are checking two conditions, firstly that the object we hit is tagged with the tag outpostDoor and secondly that the variable doorOpen is currently set to false. Remember here that two equals symbols (==) are used as a comparative, and the two ampersand symbols (&&) simply say 'and also'. The end result means that if we hit the door's collider that we have tagged and if we have not already opened the door, then it may carry out a set of instructions. We have utilized the dot syntax to address the object we are checking for collisions with by narrowing down from hit (our variable storing information on collisions) to gameObject (the object hit) to the tag on that object. If this if statement is valid, then we need to carry out a set of instructions to open the door. This will involve playing a sound, playing one of the animation clips on the model, and setting our boolean variable doorOpen to true. As we are to call multiple instructions—and may need to call these instructions as a result of a different condition later when we implement the ray casting approach—we will place them into our own custom function called OpenDoor. We will write this function shortly, but first, we'll call the function in the if statement we have, by adding: OpenDoor(); So your full collision function should now look like this: function OnControllerColliderHit(hit: ControllerColliderHit){ if(hit.gameObject.tag == "outpostDoor" && doorIsOpen == false){ OpenDoor(); }} Writing custom functions Storing sets of instructions you may wish to call at any time should be done by writing your own functions. Instead of having to write out a set of instructions or "commands" many times within a script, writing your own functions containing the instructions means that you can simply call that function at any time to run that set of instructions again. This also makes tracking mistakes in code—known as Debugging—a lot simpler, as there are fewer places to check for errors. In our collision detection function, we have written a call to a function named OpenDoor. The brackets after OpenDoor are used to store parameters we may wish to send to the function—using a function's brackets, you may set additional behavior to pass to the instructions inside the function. We'll take a look at this in more depth later in this article under the heading Function Efficiency. Our brackets are empty here, as we do not wish to pass any behavior to the function yet. Declaring the function To write the function we need to call, we simply begin by writing: function OpenDoor(){} In between the braces of the function, much in the same way as the instructions of an if statement, we place any instructions to be carried out when this function is called. Playing audio Our first instruction is to play the audio clip assigned to the variable called doorOpenSound. To do this, add the following line to your function by placing it within the curly braces after { "and before" }: audio.PlayOneShot(doorOpenSound); To be certain, it should look like this: function OpenDoor(){ audio.PlayOneShot(doorOpenSound);} Here we are addressing the Audio Source component attached to the game object this script is applied to (our player character object, First Person Controller), and as such, we'll need to ensure later that we have this component attached; otherwise, this command will cause an error. Addressing the audio source using the term audio gives us access to four functions, Play(), Stop(), Pause(), and PlayOneShot(). We are using PlayOneShot because it is the best way to play a single instance of a sound, as opposed to playing a sound and then switching clips, which would be more appropriate for continuous music than sound effects. In the brackets of the PlayOneShot command, we pass the variable doorOpenSound, which will cause whatever sound file is assigned to that variable in the Inspector to play. We will download and assign this and the clip for closing the door after writing the script. Checking door status One condition of our if statement within our collision detection function was that our boolean variable doorIsOpen must be set to false. As a result, the second command inside our OpenDoor() function is to set this variable to true. This is because the player character may collide with the door several times when bumping into it, and without this boolean, they could potentially trigger the OpenDoor() function many times, causing sound and animation to recur and restart with each collision. By adding in a variable that when false allows the OpenDoor() function to run and then disallows it by setting the doorIsOpen variable to true immediately, any further collisions will not re-trigger the OpenDoor() function. Add the line: doorOpen = true; to your OpenDoor() function now by placing it between the curly braces after the previous command you just added. Playing animation We have already imported the outpost asset package and looked at various settings on the asset before introducing it to the game in this article. One of the tasks performed in the import process was the setting up of animation clips using the Inspector. By selecting the asset in the Project panel, we specified in the Inspector that it would feature three clips: idle (a 'do nothing' state) dooropen doorshut In our openDoor() function, we'll call upon a named clip using a String of text to refer to it. However, first we'll need to state which object in our scene contains the animation we wish to play. Because the script we are writing is to be attached to the player, we must refer to another object before referring to the animation component. We do this by stating the line: var myOutpost : GameObject = GameObject.Find("outpost"); Here we are declaring a new variable called myOutpost by setting its type to be a GameObject and then selecting a game object with the name outpost by using GameObject.Find. The Find command selects an object in the current scene by its name in the Hierarchy and can be used as an alternative to using tags. Now that we have a variable representing our outpost game object, we can use this variable with dot syntax to call animation attached to it by stating: myOutpost.animation.Play("dooropen"); This simply finds the animation component attached to the outpost object and plays the animation called dooropen. The play() command can be passed any string of text characters, but this will only work if the animation clips have been set up on the object in question. Your finished OpenDoor() custom function should now look like this: function OpenDoor(){ audio.PlayOneShot(doorOpenSound); doorIsOpen = true; var myOutpost : GameObject = GameObject.Find("outpost"); myOutpost.animation.Play("dooropen");} Reversing the procedure Now that we have created a set of instructions that will open the door, how will we close it once it is open? To aid playability, we will not force the player to actively close the door but instead establish some code that will cause it to shut after a defined time period. This is where our doorTimer variable comes into play. We will begin counting as soon as the door becomes open by adding a value of time to this variable, and then check when this variable has reached a particular value by using an if statement. Because we will be dealing with time, we need to utilize a function that will constantly update such as the Update() function we had awaiting us when we created the script earlier. Create some empty lines inside the Update() function by moving its closing curly brace } a few lines down. Firstly, we should check if the door has been opened, as there is no point in incrementing our timer variable if the door is not currently open. Write in the following if statement to increment the timer variable with time if the doorIsOpen variable is set to true: if(doorIsOpen){ doorTimer += Time.deltaTime;} Here we check if the door is open — this is a variable that by default is set to false, and will only become true as a result of a collision between the player object and the door. If the doorIsOpen variable is true, then we add the value of Time.deltaTime to the doorTimer variable. Bear in mind that simply writing the variable name as we have done in our if statement's condition is the same as writing doorIsOpen == true. Time.deltaTime is a Time class that will run independent of the game's frame rate. This is important because your game may be run on varying hardware when deployed, and it would be odd if time slowed down on slower computers and was faster when better computers ran it. As a result, when adding time, we can use Time.deltaTime to calculate the time taken to complete the last frame and with this information, we can automatically correct real-time counting. Next, we need to check whether our timer variable, doorTimer, has reached a certain value, which means that a certain amount of time has passed. We will do this by nesting an if statement inside the one we just added—this will mean that the if statement we are about to add will only be checked if the doorIsOpen if condition is valid. Add the following code below the time incrementing line inside the existing if statement: if(doorTimer > doorOpenTime){shutDoor();doorTimer = 0.0;} This addition to our code will be constantly checked as soon as the doorIsOpen variable becomes true and waits until the value of doorTimer exceeds the value of the doorOpenTime variable, which, because we are using Time.deltaTime as an incremental value, will mean three real-time seconds have passed. This is of course unless you change the value of this variable from its default of 3 in the Inspector. Once the doorTimer has exceeded a value of 3, a function called shutDoor() is called, and the doorTimer variable is reset to zero so that it can be used again the next time the door is triggered. If this is not included, then the doorTimer will get stuck above a value of 3, and as soon as the door was opened it would close as a result. Your completed Update() function should now look like this: function Update(){ if(doorIsOpen){ doorTimer += Time.deltaTime; if(doorTimer > 3){ shutDoor(); doorTimer = 0.0; } }} Now, add the following function called shutDoor() to the bottom of your script. Because it performs largely the same function as openDoor(), we will not discuss it in depth. Simply observe that a different animation is called on the outpost and that our doorIsOpen variable gets reset to false so that the entire procedure may start over: function shutDoor(){audio.PlayOneShot(doorShutSound);doorIsOpen = false;var myOutpost : GameObject = GameObject.Find("outpost");myOutpost.animation.Play("doorshut");}
Read more
  • 0
  • 0
  • 3019

article-image-applying-special-effects-3d-game-development-microsoft-silverlight-3-part-2
Packt
18 Nov 2009
6 min read
Save for later

Applying Special Effects in 3D Game Development with Microsoft Silverlight 3: Part 2

Packt
18 Nov 2009
6 min read
Time for action – simulating fluids with movement Your project manager is amazed with the shower of dozens of meteors in the background. However, he wants to add a more realistic background. He shows you a water simulation sample using Farseer Physics Engine. He wants you to use the wave simulation capabilities offered by this powerful physics simulator to create an asteroids belt. First, we are going to create a new class to define a fluid model capable of setting the initial parameters and updating a wave controller provided by the physics simulator. We will use Farseer Physics Engine's wave controller to add real-time fluids with movement for our games. The following code is based on the Silverlight water sample offered with the physics simulator. However, in this case, we are not interested in collision detection capabilities because we are going to create an asteroid belt in the background. Stay in the 3DInvadersSilverlight project. Create a new class—FluidModel. Replace the default using declarations with the following lines of code (we are going to use many classes and interfaces from Farseer Physics Engine): using System;using FarseerGames.FarseerPhysics;using FarseerGames.FarseerPhysics.Controllers;using FarseerGames.FarseerPhysics.Mathematics; Add the following public property to hold the WaveController instance: public WaveController WaveController { get; private set; } Add the following public properties to define the wave generator parameters: public float WaveGeneratorMax { get; set; }public float WaveGeneratorMin { get; set; }public float WaveGeneratorStep { get; set; } Add the following constructor without parameters: public FluidModel(){ // Assign the initial values for the wave generator parameters WaveGeneratorMax = 0.20f; WaveGeneratorMin = -0.15f; WaveGeneratorStep = 0.025f;} Add the Initialize method to create and configure the WaveController instance using the PhysicsSimulator instance received as a parameter: public void Initialize(PhysicsSimulator physicsSimulator){ // The wave controller controls how the waves move // It defines how big and how fast is the wave // It is represented as set of points equally spaced horizontally along the width of the wave. WaveController = new WaveController(); WaveController.Position = ConvertUnits.ToSimUnits(-20, 5); WaveController.Width = ConvertUnits.ToSimUnits(30); WaveController.Height = ConvertUnits.ToSimUnits(3); // The number of vertices that make up the surface of the wave WaveController.NodeCount = 40; // Determines how quickly the wave will dissipate WaveController.DampingCoefficient = .95f; // Establishes how fast the wave algorithm runs (in seconds) WaveController.Frequency = .16f; //The wave generator parameters simply move an end-point of the WaveController.WaveGeneratorMax = WaveGeneratorMax; WaveController.WaveGeneratorMin = WaveGeneratorMin; WaveController.WaveGeneratorStep = WaveGeneratorStep; WaveController.Initialize();} Add the Update method to update the wave controller and update the points that draw the waves shapes: public void Update(TimeSpan elapsedTime){ WaveController.Update((float) elapsedTime.TotalSeconds);} What just happened? We now have a FluidModel class that creates, configures, and updates a WaveController instance according to an associated physics simulator. As we are going to work with different gravitational forces, we are going to use another independent physics simulator to work with the FluidModel instance in our game. Simulating waves The wave controller offers many parameters to represent a set of points equally spaced horizontally along the width of one or many waves. The waves can be: Big or small Fast or slow Tall or short The wave controller's parameters allow us to determine the number of vertices that make up the surface of the wave assigning a value to its NodeCount property. In this case, we are going to create waves with 40 nodes and each point is going to be represented by an asteroid: WaveController.NodeCount = 40; The Initialize method defines the position, width, height and other parameters for the wave controller. We have to convert our position values to the simulator values. Thus, we use the ConvertUnits.ToSimUnits method. For example, this line defines the 2D Vector for the wave's upper left corner (X = -20 and Y = 5): WaveController.Position = ConvertUnits.ToSimUnits(-20, 5); The best way to understand each parameter is changing its values and running the example using these new values. Using a wave controller we can create amazing fluids with movement.   Time for action – creating a subclass for a complex asteroid belt Now, we are going to create a specialized subclass of Actor (Balder.Core.Runtime. Actor) to load, create an update a fluid with waves. This class will enable us to encapsulate an independent asteroid belt and add it to the game. In this case, it is a 3D character composed of many models (many instances of Mesh). Stay in the 3DInvadersSilverlight project. Create a new class, FluidWithWaves (a subclass of Actor) using the following declaration: public class FluidWithWaves : Actor Replace the default using declarations with the following lines of code (we are going to use many classes and interfaces from Balder, Farseer Physics Engine and lists): using System.Windows;using System.Windows.Controls;using System.Windows.Media;using System.Windows.Shapes;// BALDERusing Balder.Core;using Balder.Core.Geometries;using Balder.Core.Math;using Balder.Core.Runtime;// FARSEER PHYSICSusing FarseerGames.FarseerPhysics;using FarseerGames.FarseerPhysics.Collisions;using FarseerGames.FarseerPhysics.Dynamics;using FarseerGames.FarseerPhysics.Factories;using FarseerGames.FarseerPhysics.Mathematics;// LISTSusing System.Collections.Generic; Add the following protected variables to hold references for the RealTimeGame and the Scene instances: protected RealTimeGame _game;protected Scene _scene; Add the following private variables to hold the associated FluidModel instance, the collection of points that define the wave and the list of meshes (asteroids): private FluidModel _fluidModel;private PointCollection _points;private List<Mesh> _meshList; Add the following constructor with three parameters—the RealTimeGame, the Scene, and the PhysicsSimulator instances: public FluidWithWaves(RealTimeGame game, Scene scene, PhysicsSimulator physicsSimulator){ _game = game; _scene = scene; _fluidModel = new FluidModel(); _fluidModel.Initialize(physicsSimulator); int count = _fluidModel.WaveController.NodeCount; _points = new PointCollection(); for (int i = 0; i < count; i++) { _points.Add(new Point(ConvertUnits.ToDisplayUnits (_fluidModel.WaveController.XPosition[i]), ConvertUnits.ToDisplayUnits (_fluidModel.WaveController.CurrentWave[i]))); }} Override the LoadContent method to load the meteors' meshes and set their initial positions according to the points that define the wave: public override void LoadContent(){ base.LoadContent(); _meshList = new List<Mesh>(_points.Count); for (int i = 0; i < _points.Count; i++) { Mesh mesh = _game.ContentManager.Load<Mesh>("meteor.ase"); _meshList.Add(mesh); _scene.AddNode(mesh); mesh.Position.X = (float) _points[i].X; mesh.Position.Y = (float) _points[i].Y; mesh.Position.Z = 0; }} Override the Update method to update the fluid model and then change the meteors' positions taking into account the points that define the wave according to the elapsed time: public override void Update(){ base.Update(); // Update the fluid model with the real-time game elapsed time _fluidModel.Update(_game.ElapsedTime); _points.Clear(); for (int i = 0; i < _fluidModel.WaveController.NodeCount; i++) { Point p = new Point(ConvertUnits.ToDisplayUnits (_fluidModel.WaveController.XPosition[i]), ConvertUnits.ToDisplayUnits (_fluidModel.WaveController.CurrentWave[i]) +ConvertUnits.ToDisplayUnits (_fluidModel.WaveController.Position.Y)); _points.Add(p); }// Update the positions for the meshes that define the wave's points for (int i = 0; i < _points.Count; i++) { _meshList[i].Position.X = (float)_points[i].X; _meshList[i].Position.Y = (float)_points[i].Y; }}
Read more
  • 0
  • 0
  • 3020

article-image-formatting-and-enhancing-your-moodle-materials-part-2
Packt
18 Nov 2009
8 min read
Save for later

Formatting and Enhancing Your Moodle Materials: Part 2

Packt
18 Nov 2009
8 min read
Images If you've taken digital images, or scanned images onto your computer, it's likely that they'll be high resolution images, ready for printing. We don't need high resolution images on our computer screens for two good reasons: screen resolutions can't show so much detail and they take up a lot of storage space. There's a process called optimization which you can use to make your images more usable for your language learning activities. You can either use a program like Photoshop Elements (commercial), or Google's Picasa, which is free from http://picasa.google.com. These will enable you to edit your pictures and get the best quality with the smallest storage size. Let's look at a few things you can do to enhance your images using Picasa. Cropping Imagine we've taken this picture, but we're only interested in using the picture of the mug for a vocabulary exercise. Open up Picasa. Click on the photo we want to edit. Click on Basic Fixes and then on Crop. Click on Manual in the drop-down menu, then select the bit of the image we want to crop (cut out). Then click on Apply. The result will be: Color balance As it stands, the picture is too dark. There is too little contrast. Picasa will also allow us to create a stronger contrast, just by clicking on Tuning and Fill light and then moving the button across to brighten up the picture. The final picture looks like this: It's smaller and brighter than the original and more appropriate for our Moodle page. Optimization and image size The picture above is 340 kb in storage size, which is pretty big. The reason it's so big in storage size is that its real size is 837 px in width and 960 px in height. In case you're new to image measurement, px stands for pixels, which are the dots on your screen. So we have an unnecessarily large image. We can reduce the image size when we insert an image, but it's a much better idea to reduce the dimensions to what we actually need before we import the image into Moodle. That will reduce the storage size at the same time. Another reason for resizing images is that if you're using several photos on the same page, you'll achieve a much greater sense of balance and therefore effectiveness if all your images are the same size. If we reduce the mug to 100 px in width, the final version is only 92 kb in size. We can resize images in Picasa by exporting, emailing, or uploading our photos to Picasa Web Albums. When we select File | Export, we can select what size we want. Videos One exciting way of enhancing your web pages in Moodle is to use video. You can either upload videos to your own Moodle site or upload them to a site like YouTube, or TeacherTube. Mashable at http://mashable.com/category/video is an excellent source of ideas and resources for editing, uploading, and sharing your videos. If you decide to upload your videos onto your Moodle site, you'll need to check their size and the upload limits on your Moodle site. The default limits are usually quite low, but you can get your administrator to change them. You can also get round this problem by uploading your videos direct to the server using an FTP program. You will need to ask your Moodle administrator for help with that. Embedding videos will save your server's storage space and traffic. Adding subtitles to your videos One way of making video content more accessible for language learners is to add same-language subtitles. This would work well as an extension to the read and listen activity. Alternatively, you could get students to produce the subtitles, a rather glamorous type of dictation. If you want to add subtitles to your own videos, this is quite straightforward in free programs like Movie Maker (for Windows) or iMovie (for Macs). Look up "subtitles" in the help files. If you want to add subtitles to a YouTube video, http://www.overstream.net/ allows you to do just that. You can then embed the final product in your website. Here's what a video with added subtitles could look like: Sound If you're not happy with the quality of sound, there are various things you can do to improve it. The six examples below are created with the audio program called Audacity, but most audio editing programs will offer the same tools. The first four edits are in the Effect menu. Remove noise Effect | Noise removal If there is an unwelcome background noise on your recording, Audacity has a tool for reducing it. Open Audacity. Open your recording. Select the whole sound track or part of the track that has too much noise by highlighting it with your mouse cursor. Select click on Effect | Noise removal to get to the noise removal tool. On-screen instructions will guide you through the rest of the process. Be careful not to reduce the noise too much, as this sometimes creates distortion. Fade in and fade out Effect | Fade in/out If you want the sound to fade in and out, use your mouse to select the part of the sound track where you want the effect. Then select Effect | Fade in/out to create the effect. This could be useful for a presentation to avoid having a burst of sound at the beginning of the recording. Change tempo without changing pitch Effect | Change tempo This can be very useful, particularly for lower-level learners. It's useful to create two versions of your recordings: one fast and one slow. You can upload both and give students the choice of which one they listen to. The great thing about this tool is that the pitch doesn't change. Change pitch without changing tempo Effect | Change pitch Sometimes you might want to lower or raise the pitch of a voice to make it more audible. This tool lets you do that without the speed changing. It can even be used to simulate a dialog, with you speaking both parts, keeping one at your normal pitch and the other one at a higher or lower pitch. You'll find the next two settings in the Preferences menu. Sample rate This helps determine the quality of your recording. You can think of it as the number of times per second you capture a snapshot of sound while you're recording. Higher sample rates give you more detail. In other words, it's a fuller sound. 8 KHz is the lowest sampling rate you should select for voice recordings. 16 KHz is more likely to produce an acceptable sound. If you have music as well, you'll need a higher sample rate, like 44 KHz. Bit rate This is the number of bits (digital 1s and 0s) that are used each second to represent the sound signal. The bit-rate for digital audio is represented in thousands of bits per second (kbps). The higher the bit-rate is, the larger the file size and the better the sound quality. Lower bit rates result in smaller files but poorer sound quality. A good bit rate for recording in Audacity is 32. Audacity offers many more possibilities, and it's well worth exploring it in detail. Go to http://audacity.sourceforge.net/help/ for more help. Navigation Most of the navigation work—that is, menus and links—is done for you in Moodle. However, there are things you can do to improve it. Here's a list of tips: Font size and color Make consistent use of font size and color with headings so that users recognize the relative importance of different sections. For example, make topics big and bold so that they stand out. Remember that the default font and color is the same as for all other text. You have to make the difference yourself. For example: User control Allow users to move ahead if necessary, so that they feel in control. You can do this by providing explicit headings in your course topics. Don't call an activity "activity". Give it a more specific name, like "Second prepositions grammar exercise". Here are some options for navigation maps: Use the Topics view on your course pages Use Book to organize a syllabus. There's an example of this in the introduction to this article. Use a flowchart program to create a plan. Then import it into your Moodle web page. For example:   Many flowchart programs allow you to include hyperlinks to the actual activities. To do that, first copy and paste the target web page address from the address bar. Then paste that address into the hyperlink in your flowchart program. Here's an example using gliffy: Create a web page with a menu on it, as in the following screenshots. To make your new web page appear with blocks to the left and right, click on Show the course blocks on the set-up page—it's at the bottom of the next screenshot. The final page would look like this. Students will see all the other navigation blocks in the left and right-hand columns.
Read more
  • 0
  • 0
  • 1545

article-image-customizing-document-joomla-15-part-1
Packt
18 Nov 2009
3 min read
Save for later

Customizing the Document with Joomla! 1.5: Part 1

Packt
18 Nov 2009
3 min read
Introduction The classes that extend JDocument are intended for different response formats. The following table describes the classes and their purposes: Class Format Default MIME type Purpose JDocumentError error text/html Display a fatal error JDocumentFeed feed application/rss+xml   or application/atom+xml Syndication feed, RSS, or Atom JDocumentHTML html text/html Default document used for all typical Joomla! responses JDocumentPDF pdf application/pdf Adobe PDF representation JDocumentRAW raw* text/html All other circumstances   So what exactly does the format column represent? When a request is made, Joomla! uses the value of the request variable format to determine which document type to use. We really see this only when we retrieve something other than an HTML document, because this always defaults to html. For example, when we request an article as a PDF, we use a URI similar to this: http://example.org/index.php?option=com_content&view=article&id=5&format=pdf The JDocumentError class is slightly different from the others. We should never really need to interact directly with this. We can, of course, invoke this document indirectly by raising a fatal error. For more information, refer to Error handling and reporting. The Joomla! document object and views in Joomla! MVC components are closely related. For each format that we provide a view, we create a new JView subclass. For example, when we examine the content component, we can see that the article view supports HTML and PDF simply by the presence of the view.html.php and view.pdf.php files. This article also deals with the static JResponse class. This class is used to define the HTTP response, including the HTTP headers. The separation between JResponse and the JDocument object is not always as clear as one would hope. However, this is somewhat inevitable because the two are inextricably linked—the response describes and includes the document output. For example, outputting an HTML response will require the response Content-Type header field to be set accordingly, that is, as text/html. Setting the document title This recipe explains how to set the title of the current document. The exact meaning of title will depend on the type of document. For example, in an HTML document, this is the value encapsulated in the <head> tag. Getting ready Before we do anything, we need the global document object. $document =& JFactory::getDocument(); How to do it... To set the title of the document, we use the JDocument::setTitle() method $document->setTitle('My Unique Title'); If we are outputting an HTML document, this should generate something like this: <title>My Unique Title</title> There's more... Menu items can also define page titles. Thus, the actual title we use should not necessarily be the title of whatever we are viewing. To deal with this, we should use something along these lines: // get the component and page parameters$application =& JFactory::getApplication();$params =& $application->getParams();// get the page title$pageTitle = $params->get('page_title', $defaultTitle);// set the document title$document->setTitle($pageTitle); Setting the document generator This recipe explains how to set the name of the piece of software that generated the page. The exact meaning of generator will depend on the type of document. For example, in an HTML document, this value is used in a tag. Getting ready Before we do anything, we need the global document object. $document =& JFactory::getDocument();
Read more
  • 0
  • 0
  • 2299
article-image-create-quick-application-cakephp-part-2
Packt
18 Nov 2009
7 min read
Save for later

Create a Quick Application in CakePHP: Part 2

Packt
18 Nov 2009
7 min read
Editing a Task Now that we can add tasks to CakeTooDoo, the next thing that we will be doing is to have the ability to edit tasks. This is necessary because the users should be able to tick on a task when it has been completed. Also, if the users are not happy with the title of the task, they can change it. To have these features in CakeTooDoo, we will need to add another action to our Tasks Controller and also add a view for this action. Time for Action: Creating the Edit Task Form Open the file tasks_controller.php and add a new action named edit as shown in the following code: function edit($id = null) { if (!$id) { $this->Session->setFlash('Invalid Task'); $this->redirect(array('action'=>'index'), null, true); } if (empty($this->data)) { $this->data = $this->Task->find(array('id' => $id)); } else { if ($this->Task->save($this->data)) { $this->Session->setFlash('The Task has been saved'); $this->redirect(array('action'=>'index'), null, true); } else { $this->Session->setFlash('The Task could not be saved. Please, try again.'); } } } Inside the directory /CakeTooDoo/app/views/tasks, create a new file named edit.ctp and add the following code to it: <?php echo $form->create('Task');?> <fieldset> <legend>Edit Task</legend> <?php echo $form->hidden('id'); echo $form->input('title'); echo $form->input('done'); ?> </fieldset> <?php echo $form->end('Save');?> We will be accessing the Task Edit Form from the List All Task page. So, let's add a link from the List All Tasks page to the Edit Task page. Open the index.ctp file in /CakeTooDoo/app/views directory, and replace the HTML comment <!-- different actions on tasks will be added here later --> with the following code: <?php echo $html->link('Edit', array('action'=>'edit', $task['Task']['id'])); ?> Now open the List All Tasks page in the browser by pointing it to http://localhost/CakeTooDoo/tasks/index and we will see an edit link beside all the tasks. Click on the edit link of the task you want to edit, and this will take you to do the Edit Task form, as shown below: Now let us add links in the Edit Task Form page to the List All Tasks and Add New Task page. Add the following code to the end of edit.ctp in /CakeTooDoo/app/views: <?php echo $html->link('List All Tasks', array('action'=>'index')); ?><br /> <?php echo $html->link('Add Task', array('action'=>'add')); ?> What Just Happened? We added a new action named edit in the Tasks controller. Then we went on to add the view file edit.ctp for this action. Lastly, we linked the other pages to the Edit Task page using the HTML helper. When accessing this page, we need to tell the action which task we are interested to edit. This is done by passing the task id in the URL. So, if we want to edit the task with the id of 2, we need to point our browser to http://localhost/CakeTooDoo/tasks/edit/2. When such a request is made, Cake forwards this request to the Tasks controller's edit action, and passes the value of the id to the first parameter of the edit action. If we check the edit action, we will notice that it accepts a parameter named $id. The task id passed in the URL is stored in this parameter. When a request is made to the edit action, the first thing that it does is to check if any id has been supplied or not. To let users edit a task, it needs to know which task the user wants to edit. It cannot continue if there is no id supplied. So, if $id is undefined, it stores an error message to the session and redirects to the index action that will show the list of current tasks along with the error message. If $id is defined, the edit action then checks whether there is any data stored in $this->data. If no data is stored in $this->data, it means that the user has not yet edited. And so, the desired task is fetched from the Task model, and stored in $this->data in the line: $this->data = $this->Task->find(array('id' => $id)); Once that is done, the view of the edit action is then rendered, displaying the task information. The view fetches the task information to be displayed from $this->data. The view of the edit action is very similar to that of the add action with a single difference. It has an extra line with echo $form->hidden('id');. This creates an HTML hidden input with the value of the task id that is being edited. Once the user edits the task and clicks on the Save button, the edited data is resent to the edit action and saved in $this->data. Having data in $this->data confirms that the user has edited and submitted the changed data. Thus, if $this->data is not empty, the edit action then tries to save the data by calling the Task Model's save() function: $this->Task->save($this->data). This is the same function that we used to add a new task in the add action. You may ask how does the save() function of model knows when to add a new record and when to edit an existing one? If the form data has a hidden id field, the function knows that it needs to edit an existing record with that id. If no id field is found, the function adds a new record. Once the data has been successfully updated, a success message is stored in the session and it redirects to the index action. Of course the index page will show the success message. Adding Data Validation If you have come this far, by now you should have a working CakeTooDoo. It has the ability to add a task, list all the tasks with their statuses, and edit a task to change its status and title. But, we are still not happy with it. We want the CakeTooDoo to be a quality application, and making a quality application with CakePHP is as easy as eating a cake. A very important aspect of any web application (or software in general), is to make sure that the users do not enter inputs that are invalid. For example, suppose a user mistakenly adds a task with an empty title, this is not desirable because without a title we cannot identify a task. We would want our application to check whether the user enters title. If they do not enter a title, CakeTooDoo should not allow the user to add or edit a task, and should show the user a message stating the problem. Adding these checks is what we call Data Validation. No matter how big or small our applications are, it is very important that we have proper data validation in place. But adding data validation can be a painful and time consuming task. This is especially true, if we have a complex application with lots of forms. Thankfully, CakePHP comes with a built-in data validation feature that can really make our lives much easier. Time for Action: Adding Data Validation to Check for Empty Title In the Task model that we created in /CakeTooDoo/app/models, add the following code inside the Task Model class. The Task Model will look like this: <?php class Task extends AppModel { var $name = 'Task'; var $validate = array( 'title' => array( 'rule' => VALID_NOT_EMPTY, 'message' => 'Title of a task cannot be empty' ) ); } ?> Now open the Add Task form in the browser by pointing it to http://localhost/CakeTooDoo/tasks/add, and try to add a task with an empty title. It will show the following error message:
Read more
  • 0
  • 0
  • 2328

article-image-build-advanced-contact-manager-using-jboss-richfaces-33-part-2
Packt
18 Nov 2009
10 min read
Save for later

Build an Advanced Contact Manager using JBoss RichFaces 3.3: Part 2

Packt
18 Nov 2009
10 min read
The contact detail For the third column, we would like to show three different statuses: The "No contact selected" message when no contact is selected (so the property is null) A view-only box when we are not in the edit mode (the property selectedContactEditing is set to false) An edit box when we are in the edit mode (the property selectedContactEditing is set to true) So, let's open the home.xhtml page and insert the third column inside the panel grid with the three statuses: <a:outputPanel id="contactDetail"> <a:outputPanel rendered="#{homeSelectedContactHelper. selectedContact==null}"> <rich:panel> <h:outputText value="#{messages['noContactSelected']}"/> </rich:panel></a:outputPanel> <a:outputPanel rendered="#{homeSelectedContactHelper. selectedContact!=null and homeSelectedContactHelper. selectedContactEditing==false}"> <ui:include src="main/contactView.xhtml"/> </a:outputPanel> <a:outputPanel rendered="#{homeSelectedContactHelper. selectedContact!=null and homeSelectedContactHelper. selectedContactEditing==true}"> <ui:include src="main/contactEdit.xhtml"/> </a:outputPanel></a:outputPanel> Here, we have put the main a:outputPanel as the main placeholder, and inside it we put three more instances of a:outputPanel (one for every state) with the rendered attribute in order to decide which one to show. The first one just shows a message when homeSelectedContactHelper.selectedContact is set to null: The second instance of a:outputPanel will include the main/contactView.xhtml file only if homeSelectedContactHelper.selectedContact is not null, and we are not in editing mode (so homeSelectedContactHelper.selectedContactEditing is set to false); the third one will be shown only if homeSelectedContactHelper.selectedContact is not null, and we are in the edit mode (that is homeSelectedContactHelper.selectedContactEditing is equal to true). Before starting to write the include sections, let's see how the main bean for the selected contact would look, and connect it with the data table for selecting the contact from it. The support bean Let's create a new class called HomeSelectedContactHelper inside the book.richfaces.advcm.modules.main package; the class might look like this: @Name("homeSelectedContactHelper")@Scope(ScopeType.CONVERSATION)public class HomeSelectedContactHelper { @In(create = true) EntityManager entityManager; @In(required = true) Contact loggedUser; @In FacesMessages facesMessages; // My code here} This is a standard JBoss Seam component and  now let's add the properties. The bean that we are going to use for view and edit features is very simple to understand—it just contains two properties (namely selectedContact and selectedContactEditing) and some action methods to manage them. Let's add the properties to our class: private Contact selectedContact;private Boolean selectedContactEditing;public Contact getSelectedContact() { return selectedContact;}public void setSelectedContact(Contact selectedContact) { this.selectedContact = selectedContact;}public Boolean getSelectedContactEditing() { return selectedContactEditing;}public void setSelectedContactEditing(Boolean selectedContactEditing) { this.selectedContactEditing = selectedContactEditing;} As you can see, we just added two properties with standard the getter and setter. Let's now see the action methods: public void createNewEmptyContactInstance() { setSelectedContact(new Contact());}public void insertNewContact() { // Attaching the owner of the contact getSelectedContact().setContact(loggedUser); entityManager.persist(getSelectedContact()); facesMessages.addFromResourceBundle(StatusMessage.Severity.INFO,  "contactAdded");}public void saveContactData() { entityManager.merge(getSelectedContact()); facesMessages.addFromResourceBundle(StatusMessage.Severity.INFO, "contactSaved");}public void deleteSelectedContact() { entityManager.remove(getSelectedContact()); // De-selecting the current contact setSelectedContact(null); setSelectedContactEditing(null); facesMessages.addFromResourceBundle(StatusMessage.Severity.INFO, "contactDeleted");}public boolean isSelectedContactManaged() { return getSelectedContact() != null && entityManager.contains (getSelectedContact());} It's not difficult to understand what they do, however, in order to be clear, we are going to describe what each method does. The method createNewEmptyContactInstance() simply sets the selectedContact property with a new instance of the Contact class—it will be called by the "add contact" button. After the user has clicked on the "add contact" button and inserted the contact data, he/she has to persist this new instance of data into the database. It is done by the insertNewContact() method, called when he/she clicks on the Insert button. If the user edits a contact and clicks on the "Save" button, the saveContactData() method will be called, in order to store the modifications into the database. As for saving, the deleteSelectedContact() method will be called by the "Delete" button, in order to remove the instance from the database. A special mention for the isSelectedContactManaged() method—it is used to determine if the selectedContact property contains a bean that exists in the database (so, I'm editing it), or a new instance not yet persisted to the database. We use it especially in rendered properties, in order to determine which component to show (you will see this in the next section). Selecting the contact from the contacts list We will use the contacts list in order to decide which contact must be shown in the detail view. The simple way is to add a new column into the dataTable, and put a command button (or link) to select the bean in order to visualize the detail view. Let's open the contactsList.xhtml file and add another column as follows: <rich:column width="10%" style="text-align: center"> <a:commandButton image="/img/view.png" reRender="contactDetail"> <f:setPropertyActionListener value="#{contact}" target="#{homeSelectedContactHelper.selectedContact}"/> <f:setPropertyActionListener value="#{false}" target="#{homeSelectedContactHelper.selectedContactEditing}"/> </a:commandButton></rich:column> Inside the column, we added the a:commandButton component (that shows an image instead of the standard text) that doesn't call any action—it uses the f:setPropertyAction method to set the homeSelectedContactHelper.selectedContact value to contact (the row value of the dataTable), and to tell to show the view box and not the edit one (setting homeSelectedContactHelper.selectedContactEditing to false). After the Ajax call, it will re-render the contactDetail box in order to reflect the change. Also, the header must be changed to reflect the column add: <rich:dataTable ... > <f:facet name="header"> <rich:columnGroup> <rich:column colspan="3"> <h:outputText value="Contacts"/> </rich:column> <rich:column breakBefore="true"> <h:outputText value="Name"/> </rich:column> <rich:column> <h:outputText value="Surname"/> </rich:column> <rich:column> <rich:spacer/> </rich:column> </rich:columnGroup> </f:facet> ... We incremented the colspan attribute value and added a new (empty) column header. The new contacts list will look like the following screenshot: Adding a new contact Another feature we would like to add to the contacts list is the "Add contact" button. In order to do that, we are going to use the empty toolbar. Let's add a new action button into the rich:toolbar component: <a:commandButton image="/img/addcontact.png" reRender="contactDetail"action="#{homeSelectedContactHelper.createNewEmptyContactInstance}"> <f:setPropertyActionListener value="#{true}"target="#{homeSelectedContactHelper.selectedContactEditing}"/></a:commandButton> This button will call the homeSelectedContactHelper.createNewEmptyContactInstance() action method in order to create and select an empty instance and will set homeSelectedContactHelper.selectedContactEditing to true in order to start the editing; after those Ajax calls, it will re-render the contactDetail box to reflect the changes. Viewing contact detail We are ready to implement the view contact detail box; just open the /view/main/contactView.xhtml file and add the following code: <h:form> <rich:panel> <f:facet name="header"> <h:outputText value="#{homeSelectedContactHelper.selectedContact.name} #{homeSelectedContactHelper.selectedContact.surname}"/> </f:facet> <h:panelGrid columns="2" rowClasses="prop" columnClasses="name,value"> <h:outputText value="#{messages['name']}:"/> <h:outputText value="#{homeSelectedContactHelper.selectedContact.name}"/> <h:outputText value="#{messages['surname']}:"/> <h:outputText value="#{homeSelectedContactHelper.selectedContact.surname}"/> <h:outputText value="#{messages['company']}:"/> <h:outputText value="#{homeSelectedContactHelper.selectedContact.company}"/> <h:outputText value="#{messages['email']}:"/> <h:outputText value="#{homeSelectedContactHelper.selectedContact.email}"/> </h:panelGrid> </rich:panel> <rich:toolBar> <rich:toolBarGroup> <a:commandLink ajaxSingle="true" reRender="contactDetail" styleClass="image-command-link"> <f:setPropertyActionListener value="#{true}" target="#{homeSelectedContactHelper.selectedContactEditing}"/> <h:graphicImage value="/img/edit.png" /> <h:outputText value="#{messages['edit']}" /> </a:commandLink> </rich:toolBarGroup> </rich:toolBar></h:form> The first part is just rich:panel containing h:panelGrid with the fields' detail. In the second part of the code, we put rich:toolBar containing a command link (with an image and a text) that activates the edit mode—it, in fact, just sets the homeSelectedContactHelper.selectedContactEditing property to true and re-renders contactDetail in order to make it appear in the edit box. We also added a new CSS class into the /view/stylesheet/theme.css file to manage the layout of command links with images: .image-command-link { text-decoration: none;}.image-command-link img { vertical-align: middle; padding-right: 3px;} The view box looks like: We are now ready to develop the edit box. Editing contact detail When in the edit mode, the content of the /view/main/contactEdit.xhtml file will be shown in the contact detail box—let's open it for editing. Let's add the code for creating the main panel: <h:form> <rich:panel> <f:facet name="header"> <h:panelGroup> <h:outputText value="#{homeSelectedContactHelper.selectedContact.name} #{homeSelectedContactHelper.selectedContact.surname}"rendered="#{homeSelectedContactHelper.selectedContactManaged}"/> <h:outputText value="#{messages['newContact']}"rendered="#{!homeSelectedContactHelper.selectedContactManaged}"/> </h:panelGroup> </f:facet> <!-- my code here --> </rich:panel><!-- my code here --></h:form> This is a standard rich:panel with a customized header—it has two h:outputText components that will be shown depending on the rendered attribute (whether it's a new contact or not). More than one component inside f:facetRemember that f:facet must have only one child, so, to put more than one component, you have to use a surrounding one like h:panelGroup or something similar. Inside the panel, we are going to put h:panelGrid containing the components for data editing: <rich:graphValidator> <h:panelGrid columns="3" rowClasses="prop" columnClasses="name,value,validatormsg"> <h:outputLabel for="scName" value="#{messages['name']}:"/> <h:inputText id="scName" value="#{homeSelectedContactHelper.selectedContact.name}"/> <rich:message for="scName" styleClass="messagesingle" errorClass="errormsg" infoClass="infomsg" warnClass="warnmsg"/> <h:outputLabel for="scSurname" value="#{messages['surname']}:"/> <h:inputText id="scSurname" value="#{homeSelectedContactHelper.selectedContact.surname}"/> <rich:message for="scSurname" styleClass="messagesingle" errorClass="errormsg" infoClass="infomsg" warnClass="warnmsg"/> <h:outputLabel for="scCompany" value="#{messages['company']}:"/> <h:inputText id="scCompany" value="#{homeSelectedContactHelper.selectedContact.company}"/> <rich:message for="scCompany" styleClass="messagesingle" errorClass="errormsg" infoClass="infomsg" warnClass="warnmsg"/> <h:outputLabel for="scEmail" value="#{messages['email']}:"/> <h:inputText id="scEmail" value="#{homeSelectedContactHelper.selectedContact.email}"/> <rich:message for="scEmail" styleClass="messagesingle" errorClass="errormsg" infoClass="infomsg" warnClass="warnmsg"/> </h:panelGrid><rich:graphValidator> Nothing complicated here, we've just used h:outputLabel, h:inputText, and rich:message for every Contact property to be edited; it appears as follows:
Read more
  • 0
  • 0
  • 1330

article-image-most-wanted-apache-myfaces-trinidad-12-tags-and-tag-attributes
Packt
18 Nov 2009
6 min read
Save for later

Most Wanted Apache MyFaces Trinidad 1.2 Tags and Tag Attributes

Packt
18 Nov 2009
6 min read
Component library structure Trinidad's approach to web technology is comprehensive: Aimed at full control of all the bits and pieces that make up a web application, little should be left that needs to be added. So based on such a closed world, Trinidad presents itself with a wealth of components and tags that even include very basic XHTML tags as replacements for the real XHTML originals. This is no radical replacement approach, rather it enables Trinidad to remain in full control of mechanisms such as partial-page rendering (PPR, also generally known as Ajax) that otherwise would need to deal with potentially incompatible libraries externally. The following image provides an outline of Trinidad's structural package design: Trinidad is divided into the following two namespaces: tr: It is the usual tag library id that references Trinidad's core library tags. It's a large library of over 100 components ranging from layout components and navigational components, to special viewer components that all implicitly support skinning, partial-page rendering, popup dialogs, error or info messaging, and so on. trh: It is the usual tag library id that references Trinidad's XHTML support library tags, a small companion that offers alternatives for those XHTML tags that are usually applied to build XHTML structures, for example, XHTML tables. Let us take a closer look at both namespaces. The upcoming image shows the core API's hierarchical structure. The tags are backed by two types of Trinidad classes—UIX* classes that deal with the JSF component requirements to implement specific JSF lifecycle processing methods, and Core* classes that deal with the specific properties (getters or setters). Trinidad’s XHTML tag library namespace (trh) Two groups can be distinguished from the trh namespace. The first one deals with the definition of an XHTML page and provides the developer with the following tags: <trh:html>: It is used to define the whole XHTML page, analogous to <html> <trh:head>: It is used to define the header, analogous to <head> <trh:body>: It is used to define the main contents, analogous to <body> <trh:script>: It is used to define a JavaScript to be executed, analogous to <script> <trh:tableLayout>: It is used to define an XHTML table. <trh:rowLayout>: It is used to define an XHTML table line, analogous to <tr>; note that it can also be used to display an arbitrary line, particularly when elements need to be kept in one and the same line. Alternatively, it is particularly interesting to look at the tr namespace as it provides some less heavy structures free from table constructions, for instance panelGroupLayout with a layout set to vertical or a panelBorderLayout, both generating div structures instead. <trh:cellFormat>: It is used to define an XHTML table cell as part of an XHTML table. The attributes of each tag are defined in a most consistent, and thus recognizable way. By the way, there are also tags for the construction of framesets such as trh:frame in case anyone still wants to make use of framesets. However, before we deal with the attributes let us conclude this structural overview by a look at the organization of the functionality of the core tag library. Trinidad’s core tag library namespace (tr) The following groups can be functionally distinguished which is also reflected in the packages structure of Trinidad's API (all beginning with org.apache.myfaces.trinidad.component; which has been left out here to avoid repetition). Note that, for completeness, we will also include information on the pure Java side as well as information on the few components that stem from the trh namespace: Basic document composition tags from the core API: document, stylesheet, form, subform. poll also appears here although it is not a composition tag. Form input and display tags, components from the core.input API: inputText, inputDate, inputListOfValues, and so on. Command or navigation tags from core.nav that includes two tag types: One that is focused on command tags that assumes a given form, presupposing the use of form and display tags from the foregoing group—commandButton, commandLink, goButton, goLink, and so on. The other deals exclusively with navigation: navigationTree, navigationPane, breadCrumbs, and so on. Large input and output component tags from core.data, for example, table, tree, and treeTable components. Layout component tags from core.layout, for example, all the swing-like panel tags, such as panelBorderLayout, panelHorizontalLayout, panelAccordion, showDetail, showDetailItem, and so on. Basic output components from core.output that are almost always used in a web application, for example, messages, outputText, outputLabel, spacer, statusIndicator, and so on. Model objects from core.model devised for various tags ; they provide the corresponding view models for their tag viewer counterparts, for example, SortableModel, CollectionModel and RowKeySet for tr:table, ChildPropertyTreeModel for tr:tree and ChartModel for tr:chart. A couple of converter components from trinidad.convert equip JSF and Trinidad input components with powerful JSF conversion, that is, convertNumber and convertDateTime. Validator components from trinidad.validator equip JSF and Trinidad input components with powerful JSF validation such as range validation (validateDateTimeRange) and validation by regular expression match (validateRegExp). Events and event listeners from trinidad.event add new event types and listeners specific for Trinidad components such as those that support Trinidad's dialog framework, for example, commandButton to launch a popup dialogue using LaunchEvent, ReturnEvent, and ReturnListener. It provides only a few tags, but these can be very utile, for example, fileDownloadActionListener, resetActionListener, returnActionListener, and setActionListener. There is a lot more to be found on the pure Java API side that either surfaces indirectly on the tag library as attributes, or is used implicitly by the tags themselves. Furthermore, there are utility classes and context support classes—RequestContext being probably the most prominent one because it offers a lot of functionality, for example, PPR from the server side. The following figure illustrates the Java side of things (it shows what the structure of some of the classes behind core.input look like): The preceding figure is an outline of the core.input API hierarchy. Again, we can see the typical UIX* and Core* structure. Finally, let us take a closer look at the tag attributes.
Read more
  • 0
  • 0
  • 1913
article-image-joomla-15-blogging-and-rss-feeds
Packt
18 Nov 2009
7 min read
Save for later

Joomla! 1.5 Blogging and RSS Feeds

Packt
18 Nov 2009
7 min read
  Blogging is a great way to get more traffic to your site and communicate with the community interested in the same topics as you. Search engines such as Yahoo! and Google love blogs because of the fact that articles written in blogs are mostly up-to-date and they get the information about the update of a blog really fast using RSS Feeds and Pings. Articles posted on a blog with these two options in place can get into the search engine indexes within hours, sometimes even minutes. How is blogging good for SEO? Using a blog has some advantages that fair really well if you want to have more visibility in the search engines. We will be looking at some of those advantages and how they can affect your search engine rankings. I am not saying blogging is easy, but it is very rewarding. Creating fresh content Creating short articles about your favorite topic and publishing them on a regular basis is the best way to get into the search engine results pages faster. The number one thing about blogging is that you can write long articles or short articles. The combination of the two different formats won't break the flow of your site, unlike a normal web site, where you mostly write articles that are built with a certain length. You can also state an opinion about things that are going on in your community and write news items. All that in one web site without worrying too much about how to structure all the information. A structure is needed for SEO and Joomla! will force you to use the structure you have chosen for your site. Using Joomla! as a blog will make it easier for you as you will be using the categories created in advance to hold that information for you. Google and blog indexing If you set up a blog and start using the sites and services we will be looking at, like FeedBurner and Technorati, you will notice that the major search engines also use these services to index blog sites and find new posts really fast. Now Google even owns FeedBurner! You will not only syndicate your articles using options such as RSS Feeds, but you will also push your articles through Technorati, the number one site to show your blog to bloggers. Google has a special tool with some basic categorization in place for searching blogs; you can find it at http://blogsearch.google.com. One good thing about this blog search tools is that it will show you how "old" a blog post is. For example, under the title you will see a statement such as 10 hours ago just to prove how fast you can get an article indexed from a blog. Setting up Joomla! as a blog Joomla! was not built to be a blog in its basic form, unlike WordPress. However, Joomla! has a built-in layout function called Blog layout that can be used for sections and categories. RSS Feeds are also built in, but we need to put an extra component in place to get a commenting system. First things first, let's set up the basic structure of your Joomla! based blog. How to structure your blog section The first thing you need to do is to come up with a section name for your blog. You already have an extended keywords list, so it should not be difficult to set up a blog. In my example site I have set up a Section called Garden Pools Blog and the Alias I want to use is garden-pools. This alias is going to be included in the SEF URL and contains some of the keywords I want to target with the blog. Once that is ready, you need to create the main categories, which of course will be the main topics of your blog section. Choosing your blog categories Again you need to find the right keywords to put into your category names. The best thing you can do now is to focus on the topic you want to blog about. It is really essential that you think about these categories and name them the right way, or you will get into trouble later on. Once you know about the SEF URLs, you might find yourself in trouble if you have the same category names as in the main site. In my category for this blog I have used the category name Water Gardens, depending on my choice of URL construction in the sh404SEF component. It is possible that I may not use the same category name for the main topics of my site. If I were to use the same category name they both would get the URL http://www.cblandscapegardening/water-gardens/, leaving one of the categories not reachable. One workaround would be to change the alias of one of the categories, but that would still leave a duplicate title on your site which you would need to change. Google would show it as a possible duplicate title in its webmaster content analysis. You can prevent this by choosing your categories wisely. Therefore, it is important to think about these URL structures, when you start naming and creating the blog categories. Stay focused and limit yourself If you start naming the categories make sure you stay on the same blog topic and keep the terms as relevant as possible. Don't create too many categories as you are going to create a separate menu for the blog. Too many categories will fill your menu with a long list of topics, and the visitors will not be able to choose from this long list. It is also not a pretty sight to have such a long list in your sidebar. Limiting yourself to a smaller section of categories, which you want to connect your articles to, will help you to stay more relevant to the topic of your choice. Creating a blog menu Once you have set up your categories, it's time to create your blog menu. Start with creating a new menu and call it whatever you want to, give it a title like The Garden Blog as in my example site. To set this feature go to your administrator panel and choose Menus | Main Menu from the menu bar at the top. After that choose New. Make it short and to the point so that it is really easy to find it on your site. Go to the Extensions menu, choose Module Manager, and Publish the module in the location you want it to show on your site. The first thing you should do is create a link to the section in which you are going to put your blog posts, and change the Parameters(Basic) to match the layout you want:   #Leading is set to 1, which means one full length article to start with   #Intro is set the 6, so you have the introduction text (that is the text before the "read more" link) from six articles, getting a total of seven on the blog page   Columns is set to 1 to get a complete overview of the articles in a listing that is not broken into two columns after the first Intro article   #Links this is the number of links with the title of older articles that don't show on the blog page anymore After setting the Parameters(Basic) you need to set the Parameters(Advanced) as well:   Change the Category Order to Order and the Primary Order to Most recent first.   Make sure you have the Show a Feed Link set to Yes—only for this menu item. This option is set so that we can get a full RSS Feed over all the blog categories For a blog, you need to change some of the settings in the Parameters(Component):     For a blog you need to Show the Author Name, the Created Date and Time, the Show Navigation, and the Read more... Link   The Article Rating/Voting depends on you, for me its set to off, as I don't like the dotted rating icons. The commenting system will give your visitors the ability to share their thoughts about your article, rather than just rate them, unlike the rating system. You will learn more about such a commenting system later in this article.
Read more
  • 0
  • 0
  • 1869

article-image-microsoft-chart-xml-data
Packt
18 Nov 2009
4 min read
Save for later

Microsoft Chart with XML Data

Packt
18 Nov 2009
4 min read
Introduction SQL 2000 Server provided T-SQL language extensions to operate bi-directionally with relational and XML sources. It also provided two system stored procedures, sp_XML_preparedocument and sp_XML_removedocument, that assist the XML to Relational transformation. This support for returning XML data from relational data using the For XML clause is continued in SQL Server 2005 and SQL Server 2008 although the support for XML is lot more extensive. The shape of the data returned by the For XML clause is further modified by choosing the following modes, raw, auto, explicit, or path. As a preparation for this article we will be creating an XML document starting from the PrincetonTemp table used in a previous article, Binding MS Chart Control to LINQ Data Source Control, on this site. Creating an XML document from an SQL Table Open the SQL Server Management and create a new query [SELECT * from PrincetonTemp for XML auto]. You can use the For XML Auto clause to create a XML document (actually what you create is a fragment - a root-less XML without a processing directive) as shown in Figure 01. Figure 01: For XML Auto clause of a SELECT statement The result shown in a table has essentially two columns with the second column containing the document fragment shown in the next listing. Listing 01: <PrincetonTemp Id="1" Month="Jan " Temperature="4.000000000000000e+001" RecordHigh="6.000000000000000e+001"/> <PrincetonTemp Id="2" Month="Feb " Temperature="3.200000000000000e+001" RecordHigh="5.000000000000000e+001"/> <PrincetonTemp Id="3"Month="Mar " Temperature="4.300000000000000e+001" RecordHigh="6.500000000000000e+001"/> <PrincetonTemp Id="4" Month="Apr " Temperature="5.000000000000000e+001" RecordHigh="7.000000000000000e+001"/> <PrincetonTemp Id="5" Month="May " Temperature="5.300000000000000e+001" RecordHigh="7.400000000000000e+001"/> <PrincetonTemp Id="6" Month="Jun " Temperature="6.000000000000000e+001" RecordHigh="7.800000000000000e+001"/> <PrincetonTemp Id="7" Month="Jul " Temperature="6.800000000000000e+001" RecordHigh="7.000000000000000e+001"/> <PrincetonTemp Id="8" Month="Aug " Temperature="7.100000000000000e+001" RecordHigh="7.000000000000000e+001"/> <PrincetonTemp Id="9" Month="Sep " Temperature="6.000000000000000e+001" RecordHigh="8.200000000000000e+001"/> <PrincetonTemp Id="10" Month="Oct " Temperature="5.500000000000000e+001" RecordHigh="6.700000000000000e+001"/> <PrincetonTemp Id="11" Month="Nov " Temperature="4.500000000000000e+001" RecordHigh="5.500000000000000e+001"/> <PrincetonTemp Id="12" Month="Dec " Temperature="4.000000000000000e+001" RecordHigh="6.200000000000000e+001"/> This result is attribute-centric as each row of data corresponds to a row in the relational table with each column represented as an XML attribute. The same data can be extracted in an element centric manner by using the directive elements in the SELECT statement as shown in the next figure. Figure 02: For XML auto, Elements clause of a Select statement This would still give us an XML fragment but now it is displayed with element nodes as shown in the next listing (only two nodes 1 and 12 are shown). Listing 02: <PrincetonTemp><Id>1</Id><Month>Jan </Month><Temperature>4.000000000000000e+001</Temperature> <RecordHigh>6.000000000000000e+001</RecordHigh> </PrincetonTemp> ... <PrincetonTemp><Id>12</Id><Month>Dec </Month><Temperature>4.000000000000000e+001</Temperature> <RecordHigh>6.200000000000000e+001 </RecordHigh></PrincetonTemp> To make a clear distinction between the results returned by the two select statements the first row of data is shown in blue. This has returned elements and not attributes. As you can see the returned XML still lacks a root element as well as the XML processing directive. To continue with displaying this data in MS Chart Save Listing 2 as PrincetonXMLDOC.xml to a location of your choice. Create a Framework 3.5 Web Site project Let us create a web site project and display the chart on the Default.aspx page. Open Visual Studio 2008 from its shortcut on the desktop. Click File  New | Web Site...|(or Shift+Alt+N) to open the New Web Site window. Change the default name of the site to a name of your choice (herein Chart_XMLWeb) as shown. Make sure you are creating a .NET Framework 3.5 web site as shown here. Figure 03: New Framework 3.5 Web Site Project Click on APP_Data folder in the solution explorer as shown in the next figure and click on Add Existing Item… menu item. Figure 04: Add an existing item to the web site folder In the interactive window that gets displayed browse to the location where you saved the PrincetonXMLDOC.xml file and click Add button. This will add the XML file to the ADD_Data folder of the web site project. Double click PrincetonXMLDOC.xml in the web site project folder to display and verify its contents as shown in the next figure. Only nodes 1 and 12 are shown expanded. As mentioned previously this is an XML fragment. Figure 05: Imported PrincetonXMLDOC.xml Modify this document by adding the <root/> as well as the XML processing instruction as shown in the next figure. Build the project. Figure 06: Modified PrincetonXMLDOX.xml (valid XML document)
Read more
  • 0
  • 0
  • 14701
Modal Close icon
Modal Close icon