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

7018 Articles
article-image-working-microsoft-dynamics-ax-and-net-part-2
Packt
30 Dec 2009
4 min read
Save for later

Working with Microsoft Dynamics AX and .NET: Part 2

Packt
30 Dec 2009
4 min read
Add a reference to .NET Business Connector In the next example, we create a new project in Visual Studio and add the reference to the project. You can skip this step if you already have a project where you would like to use the .NET Business Connector. Open Visual Studio and create a new project as shown in the next screenshot: When you click on OK, you will have a new C# file called Program.cs. Before we start writing any code in the file, we have to add the .NET Business Connector as a reference. In the Solution Explorer right-click on the References node and select Add Reference. In the form that opens select Microsoft.Dynamics.BusinessConnectorNet.dll under the Browse tab. The file is found in the ClientBin catalog of your AX installation. The default path is: C:Program FilesMicrosoft Dynamics Ax50ClientBin Click on OK and note that the reference has now been added under the References node in the Solution Explorer. Using the .NET Business Connector in .NET classes In the next sections of this article we will look at some examples that show how we can use methods in the .NET Business Connector to call AX methods, insert data into AX tables, and read data from AX tables. Calling a static class method in AX You now have to go back to AX, open the AOT and find the Global class. Add the following method to the Global class: static str AxHelloWorld(){ return "HelloWorld!";} In the Visual Studio project we open the Program.cs file again and enter the following code that will create a connection to AX through the .NET Business Connector. We then call the method we created in the Global class before it prints the result to the console: using System;using Microsoft.Dynamics.BusinessConnectorNet;namespace GetAxInfo1{ class Program { /// <summary> /// This class connects to AX throught the /// .NET Business Connector and call the static method /// AxHelloWorld in the Global class in AX. /// The result is sent to the console (command prompt). /// </summary> /// <param name="args"></param> static void Main(string[] args) { Axapta ax; Object axObject; try { // Create a new Axapta object. ax = new Axapta(); // Logon using the default settings // in the AX configuration for the .NET // Business Connector ax.Logon(null, null, null, null); // Call the static method and return the // result to the axObject variable axObject = ax.CallStaticClassMethod("Global", "AxHelloWorld"); // Print the result to the console Console.WriteLine("The message from AX is {0}", axObject.ToString()); ax.Logoff(); } catch (Exception e) { Console.WriteLine(e.Message); } Console.ReadKey(); } }} Execute the program by pressing Ctrl + F5. You should now see the following result in the console (command prompt) that opens up: If you get a different result it might be because you haven't set up the .NET Business Connector correctly. If so, please refer to the installation guide to set it up properly. Also, check the Windows Event Viewer to see if there are any error messages that can lead you in the right direction. Insert data into an AX table As mentioned earlier in this article, you can use the methods in some of the marshaled classes in the .NET Business Connector to manipulate data. However, it is better to avoid this and instead have AX handle all data selection and manipulation. It would be even better to have your .NET application call a method in AX that does the job and returns the results back to the .NET application again. However, this is not always feasible, for instance, when you would like to insert records from your .NET application to an AX table. The next section will guide you through the steps needed to achieve this. First, you should create a new project in Visual Studio as we did earlier in this article. In this example, we will call the new project "InsertAxRecord". Then you have to add a reference to the .NET Business Connector. In the Program.cs file (or whatever you call your file), you write something like this: using System;using Microsoft.Dynamics.BusinessConnectorNet;namespace InsertAxRecord{ class Program { static void Main(string[] args) { Axapta ax; AxaptaRecord record; try { // Create AX object and logon to AX ax = new Axapta(); ax.Logon(null, null, null, null); // Create a new AxaptaRecord object with // the name of the table as input parameter using (record = ax.CreateAxaptaRecord("CarTable")) { // Remember to clear the tablebuffer if // you are inserting inside a loop record.Clear(); record.InitValue(); // Set the fields in the table record.set_Field("CARID", "XXX1"); record.set_Field("MODELYEAR", 1998); record.set_Field("CARBRAND", "FORD"); record.set_Field("MODEL", "F1"); record.set_Field("MILEAGE", 89378); // Insert the record record.Insert(); } // End the AX session ax.Logoff(); } catch (Exception e) { Console.WriteLine(e.Message); } } }}
Read more
  • 0
  • 0
  • 4576

article-image-working-microsoft-dynamics-ax-and-net-part-1
Packt
30 Dec 2009
4 min read
Save for later

Working with Microsoft Dynamics AX and .NET: Part 1

Packt
30 Dec 2009
4 min read
When you are done with this article, you should be able to use .NET classes as reference classes in AX through the Common Language Runtime (CLR). The article will also guide you through the process of creating a .NET class in Visual Studio, and how to use it in AX. You will also learn how to use AX logic from external applications by using the .NET Business Connector. All the Visual Studio examples in this article are written in C#. Common Language Runtime You might have done some .NET development before looking into X++ right? Maybe you're even a .NET expert? If so, you must have heard of CLR before. The CLR is a component of .NET that enables objects written in different languages to communicate with each other. CLR can be used in AX to combine functionality from .NET classes and libraries, including the ones you have yourself created in .NET. However, you cannot consume AX objects in .NET by using the CLR. Instead, you will then have to use the .NET Business Connector. To learn more about the CLR, check out the following link: http://msdn.microsoft.com/en-us/library/ddk909ch(VS.71).aspx One very useful feature in AX when dealing with integration between AX and .NET is the way AX implicitly converts the most common data types. For the data types listed in the next table you do not need to convert the data manually. For all other data types, you will have to convert them manually. .NET Common Language Runtime X++ System.String str System.Int32 int System.Int64 int64 System.Single real System.Double real System.Boolean Boolean System.DateTime date System.Guid guid Enums are stored as integers in AX and are treated as integers when they are implicitly converted between .NET and AX.     We prove this by executing the next example that shows the conversion between System.String and str. The same can be done for any of the other data types in the above table. static void ImplicitDataConversion(Args _args){ System.String netString; str xppString; ; // Converting from System.String to str netString = "Hello AX!"; xppString = netString; info(xppString); // Converting from str to System.String xppString = "Hello .NET!"; netString = xppString; info(netString);} X++ is case insensitive, except when dealing with CLR. This means that writing System.string in the previous example will result in     a compile error, whereas writing Str instead of str will not. The result will look like this: Adding a reference to a .NET class in AX To be able to use .NET classes in AX you have to make sure that the .NET assembly that you would like to use in AX exists under the References node in the AOT. If you can't find it there, you have to add it by adding a reference to the DLL file that contains the assembly in the AOT under References. When adding a reference node in the AOT you have to make sure that the DLL exists on all client computers. If there is a client computer in which the DLL does not exist, it will result in compile errors when compiling code on that client computer. Assembly exist in the Global Assembly Cache Follow these steps to add a reference that exists in the Global Assembly Cache: If the DLL has been added to the Global Assembly Cache, you can right-click on the Reference node in the AOT and select Add Reference. In the form that opens (see next screenshot), you should be able to find the desired DLL. Add it by clicking on the Select button. When you have selected the desired reference, click on the OK button. The assembly has now been added to the AOT, and can be used when writing X++ code.          Assembly not in Global Assembly Cache If the file does not exist in the Global Assembly Cache follow these steps: Click on the Browse button in the Add Reference form shown above and find the DLL file. Click on Open. If the DLL is a valid assembly it will be added to the AOT under References. Another option is to add the DLL to the Global Assembly Cache first and select it as described in the previous section, Assembly exist in the Global Assembly Cache.
Read more
  • 0
  • 0
  • 6549

article-image-implementing-security-adempiere-34-part-2
Packt
30 Dec 2009
8 min read
Save for later

Implementing Security in ADempiere 3.4: Part 2

Packt
30 Dec 2009
8 min read
Recording access security rules Currently, with our configuration, there are two warehouses available in the Dress organization. These are: 1st Dress W/h 2nd Dress W/h By default, all users that have access rights to the Dress organization will be free to access these warehouses. Do we have a requirement that allows just user Moses to access 2nd Dress W/h only? Is that possible? ADempiere has a feature to block users from accessing information in certain records. With this feature, the locking process is applied based on a Role, and not on a certain user ID. Enabling Personal Lock There are some prerequisite activities required in order to be able to block access to certain records. This activity defines which Role has the rights to block access. In our example, we will give the default Sistematika Fashion, Ltd Admin role this right. Log in with user ID admin, select Sistematika Fashion, Ltd Admin as the role. Open the Role window, and access the Role tab. Point your active records to Sistematika Fashion, Ltd Admin, and then find and select the Personal Lock checkbox, as shown in the following screenshot: On enabling the personal lock, if you are logged in as user ID admin have Sistematika Fashion, Ltd Admin as an active Role, on opening all of the ADempiere windows, there will be an additional special Private Record Lock toolbar available, as shown in the following screenshot: Blocking access to certain records With the previous requirement, we will block the user ID (which connects with the Restricted Access role) from accessing the 1st Dress W/h warehouse. This be done by using the following procedure: Open the Menu  Material Management | Material Management Rules | Warehouse & Locators window. In the Warehouse tab, find your 1st Dress W/h record. Press the Ctrl key, and then click on the Private Record Lock button at the same time. In the upcoming Record Access Dialog confirmation window, set the following information: Set the Role field to Restricted Access (pick from the options available) Select the Active checkbox Select the Exclude checkbox The following screenshot shows the completed window: Finalize the process by clicking on the OK button. Log in with user ID Moses and password 123456, using Restricted Access as the role, and Dress as the organization. Open the Purchase Order window, and try to create a new document. Take a closer look at the available options in the Warehouse field. Now, it will only list 2nd Dress W/h, as shown in the following screenshot: Restoring access to certain blocked records There are two way to restore user rights to certain blocked records. First, if you know the blocked records and the Role to which these records are blocked (in our case, 1st Dress W/h with Restricted Access), then you can open the Warehouse & Locators window, find your 1st Dress W/h record, press the Ctrl key, and then click on the Private Record Lock button. In the upcoming Record Access Dialog confirmation window, make sure that you set the Role to Restricted Access, and then click on the Delete record button. The Delete record button is a green recycle button on the right-hand side of the Dependent Entities checkbox. Second, you can open the Menu  System Admin | General Rules | Security | Role Data Access window. Select the role that needs to be maintained in the Role tab. In our case, this is the Restricted Access role. Navigate to the Record Access tab. This tab will contain all of the record restriction configuration. This is a sample record format, which contains blocking information for certain records, as shown in the following screenshot: Click on the Record ID button, to check what kind of record information is currently blocked. On confirmation, you can press the F3 key to delete this record, and the access rights to this information will be restored. Using Dependent Entities With the previous record access lock activity, the user who was connected to the ADempiere system using Restricted Access role could not use the 1st Dress W/h as their target warehouse when working with a new document (such as, Purchase Order, Material Receipt, and so on). They will still be able to access any existing document that uses 1st Dress W/h as part of their warehouse information references. If you need to hide or restrict access to any document that has 1st Dress W/h as part of its document information, you can select the Dependent Entities checkbox. Working with Role Data Access in detail In the Menu  System Admin | General Rules | Security | Role Data Access window, we can define an access right on both the ADempiere database table and column, which is registered in the ADempiere Application Dictionary. We will elaborate on a sample use of this data access in the subsequent sections. Restricting Table access Suppose that you need to grant access to a role that can only read or view the Material Receipt window and cannot add or alter any information in this window. With User ID admin and using Sistematika Fashion, Ltd Admin as the role, you need to perform the following steps: Find the document's target table. You can get this information by opening the Material Receipt window and clicking on Record Info. In this case, the table name is M_InOut. Open the Role Data Access window, set your target role (for example, Restricted Access) in the Role tab, and then navigate to the Table Access tab. Enter and then save the following information: Set the Table field to M_InOut (on the screen, it will show as M_InOut_Shipment/Receipt) Select the Exclude checkbox Set the Access Type field to Accessing Select the Read Only checkbox With this configuration, if the user is connected to the ADempiere system using the Restricted Access role, on opening their Material Receipt window they will have read-only access and will not be able to alter or add any information. Restricting Report access In this section, the option was to be able to create a report, and unfortunately, this configuration applies to all of the available windows. With the combination of the Can Report option and restricting report access, we have the option to give report access by first authorizing access to all of the available reports, and then restricting access to certain selected reports. We will use this approach. Here, we will show you an example wherein a user ID connected using the Restricted Access role will not be able to access only the Material Receipt report. For this requirement, using user ID admin and Sistematika Fashion, Ltd Admin as the role you need to: Access the Role tab in the Role Data Access window. Ensure that your active record is Restricted Access. On the Role tab, select the Can Report option. Navigate to the Table Access tab, add and then enter and save the following information: Set the Table field to M_InOut (on the screen, it will show M_InOut_Shipment/Receipt) Select the Exclude checkbox Set the Access Type field to Reporting Deselect the Can Report checkbox (this option will be available if the Access Type is set to Reporting) Restricting Export access So far, if user ID Moses is connected using the Restricted Access role, he can process a report, print preview, or print the Purchase Order data. "Okay, this role has rights to create a report, print preview, or print Purchase Order data through the Purchase Order window. For security reasons, could we ensure that the user ID connected to the system using the Restricted Access role cannot export this report?"                           Yes, this is possible with ADempiere. You can achieve this by carrying out the following steps: Access the Role tab in the Role Data Access window. Ensure that your active record is Restricted Access. In the Role tab, select the Can Export option. Navigate to the Table Access tab, and then enter and save the following information: Set the Table field to C_Order (on the screen, it will show as C_Order_Order) Select the Exclude checkbox Set the Access Type field to Exporting Deselect the Can Export checkbox (this option will be available if the Access Type is set to Exporting) If the user is connected to the ADempiere system using the Restricted Access role, when making a report and print previewing the document in the Purchase Order window, the Export button will not be available.
Read more
  • 0
  • 0
  • 1559

article-image-spicing-your-blog-uploading-files-and-images-your-weblog-using-apache-roller
Packt
30 Dec 2009
5 min read
Save for later

Spicing Up Your Blog: Uploading Files and Images to your Weblog using Apache Roller

Packt
30 Dec 2009
5 min read
This article gives you insight on weblogs and how they can be used to create a worldwide presence through the blogosphere. It also teaches you the difference between a blog and a CMS, the basics about newsfeeds and the important role they play for blogs, and how you can use them to spread information on the blogosphere. Before the action begins Before starting with this article's exercises, you need to download the support files (screenshots, videos, sounds, and so on) from http://www.packtpub.com/files/code/9508_Code.zip, and then unzip them into a folder—C:ApacheRollerBook, for example—on your hard drive. All these files are zipped in a file named chapter05.zip. Inside this file, there's an image file (chapter05_01.jpg), a sound file (seaontherocks.mp3), and several files for the video example (showvbox.mp4, showvbox_controller.swf, and FirstFrame.png). Uploading files to your weblog Now that you have the basic knowledge about how to manage your weblog, it's time to make things more interesting for you and your future visitors. So, how can we do that? Well, multimedia files (audio or video) are always a good addition to a web page, because they can express much more than using text-only posts. Imagine what you could offer to your clients, if you had an online specialty store. You could show your new items in your Roller weblog with full color photos, and you could also embed videos of your items in your posts, to give visitors a complete virtual tour of your store! To top that, you could show them a custom Google Map, where they could get directions from their location to your store! What else could you ask for? Using images on your posts An image can say a thousand words and if you include some of them in your posts, imagine the space you can save. Roller has a very friendly interface to help you upload and include images in your posts, and now you're about to learn how to do it! Time for action – uploading images into Roller In this exercise, I'll show you how to use Roller's file upload interface, so that you can add an image to an entry (post) in your blog:                                                                Open your web browser and log into Roller. The New Entry page will appear. Then click on the File Uploads link, under the Create & Edit tab: The File Uploads page will appear next, as shown in the following screenshot:      Click on the Browse... button of the first text field, and the File Upload dialog will appear. Go to the folder where you downloaded this article's support files, and double-click on the chapter5_01.png image to select it. The name of the file you selected will show up in the first textbox of the File Uploads page: Click on the Upload button to upload the image to your blog. Roller will respond with a success message as shown in the next screenshot: Take note of the URL shown in the previous message, because you'll use it when inserting the image inside a post in your blog. Now click on the New Entry link from the Create & Edit tab, and use the following screenshot as an example for your new post: Press Enter after the last line of text (Here's a screenshot of the official Website:) and click on the text editor's Insert/Modify Image button: The Insert Image dialog will show up. Type the URL of the image you uploaded to Roller (http://localhost/roller/main/resource/chapter5_01.png) inside the Image URL field, and click on the Preview button to see a small preview of the image. Then, type VirtualBox Web site in the Alternate text field and click on the OK button to insert the image in your post: You'll be taken back to the New Entry page again. To see the image, click on the Maximize/Minimize Editor button: The editor will fill up your web browser's entire workspace area and you will be able to see the image, as shown in the following screenshot: Click on the image to select it and change its size by dragging the little white square at the upper-right corner: Click on the Maximize/Minimize Editor button again to change the text editor to its original size. The image will now fit inside the text editor, as shown in the following screenshot: Use the down and right arrow keys to position the text cursor at the end of the post, press Enter and type the text shown in the following screenshot: Exit the text editor and scroll down the New Entry page until you locate the Post to Weblog button, and click on it to publish the post to the blog. Roller will show the Changes saved message inside a green box. Now click on the Front Page link in Roller's menu bar, at the upper-right corner of the screen, to go to your blog's front page: Your new post will appear on your weblog's front page, as shown in the following screenshot: You can logout from Roller and close your web browser now.
Read more
  • 0
  • 0
  • 2270

article-image-uploading-videos-and-sound-files-your-posts-using-apache-roller-40
Packt
30 Dec 2009
6 min read
Save for later

Uploading Videos and Sound Files on Your Posts Using Apache Roller 4.0

Packt
30 Dec 2009
6 min read
Using videos in your posts It's time to learn how to insert video files in your posts. You can just insert one as an HTML link, but who does that anymore? It's a good way to drive your prospective readers away! In today's world, you need to offer your spectators the easiest, quickest, and most attractive way to see what you have to offer. My job is to show you how to do that with your Roller weblog, so let's get to it! Time for action – uploading and inserting videos on your posts In this exercise, I'll show you how to upload a video file to your blog server and then insert it into a post using Apache Roller: Open your web browser and log into Roller. The New Entry page will appear. Click on the File Uploads link from the Create & Edit tab. Scroll down the File Uploads page until you locate the Manage Uploaded Files section. Type video in the New Directory field and click on the Create button, as shown in the following screenshot:  Roller will show the following success message: Scroll down the page again until you locate the video folder in the Manage Uploaded Files section, and click on it: Roller will take you to the same File Uploads page, but this time you'll be inside the video directory. Now click on the first Browse... button of the Upload files for use in weblog main section. On the File Upload dialog, go to the folder where you downloaded the support files for this article, and double-click on the FirstFrame.png image to select it. The name of this file will show up on the first textbox of the File Uploads page. Now click on the second Browse... button and double-click on the showvbox.mp4 file, so that its name appears in the second textbox of the File Uploads page. Repeat the process with the third Browse... button and the showvbox_controller.swf file. Your File Uploads page must look like the following screenshot: Click on the Upload button to upload the three files to the video directory in your blog server. Roller will return the following success page: Don't forget to write down the three URLs from the previous Roller message; you'll need them when inserting the video into an entry (post). Click on the New Entry link from the Create & Edit tab to go to the New Entry page and create a new post for your blog. Type Ubuntu Linux Virtual Machine Inside a Windows XP PC in the Title field, select Open Source in the Category field, type virtualbox windows xp linux ubuntu in the Tags field. In the Content field, and type Here's a sample video of my Ubuntu Linux Virtual Machine, running inside a Windows XP PC with VirtualBox: as shown in the following screenshot:   Click on the Toggle HTML Source button from the HTML editor and write the following code below the text you typed in step 8 (the text in bold must correspond to the URLs from step 7's screenshot): <object height="498" width="640" id="csSWF" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/ cabs/flash/swflash.cab#version=9,0,115,0"><param name="src" value="http://localhost/roller/main/ resource/video/showvbox_controller.swf" /><param name="bgcolor" value="#1a1a1a" /><param name="quality" value="best" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><param name="scale" value="showall" /><param name="flashVars" value="autostart=false" /><embed height="498" width="640" name="csSWF" src="http://localhost/roller/main/resource/ video/showvbox_controller.swf" bgcolor="#1a1a1a" quality="best" allowscriptaccess="always" allowfullscreen="true" scale="showall" flashvars="autostart=false&amp; thumb=http://localhost/roller/main/resource/ video/FirstFrame.png&amp; thumbscale=45&amp;color=0x000000,0x000000" pluginspage="http://www.macromedia.com/ shockwave/download/ index.cgi?P1_Prod_Version=ShockwaveFlash"/></object> Click on the Save as Draft button, to save a draft of your post. Then scroll down the page and click on the Full Preview button, to see how your post will look in your blog before publishing it. The preview will open in a new tab in your web browser:       Click on the play button and the video will begin to playback. When finished, close the preview tab and click on the Post to Weblog button to publish your new post. You can logout from Roller now. What just happened? The previous exercise showed you how to upload a video to your blog server and insert it in a post. As you can see, videos are a little more complicated than plain images. In this case, we used the following files: FirstFrame.png: This is the thumbnail image that shows up before the video begins to playback showvbox.mp4: The video file showvbox_controller.swf: The controller that plays back theshowvbox.mp4 file      The video was produced with Camtasia Studio, an excellent screen recording software application from TechSmith (http://www.techsmith.com). If you want to practice with your own videos, you can download a 30-day free trial version of Camtasia Studio from the following URL: http://www.techsmith.com/download/camtasiatrial.asp. What would happen if you wanted to embed a video from your camera or cell phone? Well, you can embed it directly in your blog, but the best thing to do is use a software application such as Camtasia Studio to create the .swf controller and the HTML code to embed into your post automatically. Then you just need to change the .swf controller and thumbnail URLs, as you did in step 9 of the previous exercise. You can use the same embed code to insert a different video in your blog; just be sure to change the URL in bold text. You could also upload your video to YouTube instead of uploading it into Roller, as we'll see later in this article.
Read more
  • 0
  • 0
  • 5004

article-image-implementing-security-adempiere-34-part-1
Packt
30 Dec 2009
10 min read
Save for later

Implementing Security in ADempiere 3.4: Part 1

Packt
30 Dec 2009
10 min read
In a real ERP implementation, there are many people (such as the General Manager, Accounting Manager, Warehouse Manager, Accounting staff, warehouse staff, shipping staff, and so on) involved in operating the system. Because every individual has his or her own responsibilities in the organization, the system should help the organization manage the access rights to information and perform activities in the system. Managing ADempiere user IDs In our ADempiere implementation, we need to define a list of users in the system. A user could be the Accounting Manager, the Warehouse Manager, or any of the staff who need to access the system. Now, log in with user ID admin, using Sistematika Fashion, Ltd Admin as the role and * as the organization. We will register a new user ID with the help of the ADempiere administrator. Creating a user ID in the system In this example, we will create two additional user IDs. Open the Menu  System Admin | General Rules | Security | User window. On the User Contact tab, enter and save the following minimum requirement information: Field 1st data 2nd data Client Sistematika Fashion, Ltd Sistematika Fashion. Ltd Organization * * Name Daniel Moses Search Key daniel moses Password 123456 123456 An example of the first set of user ID data entered in the User window is shown in the following screenshot: As these user IDs are not yet connected to any Role, they cannot currently access the ADempiere system. There are other tabs listed in the User window (for example, User Roles, User Substitute, Org Assignment, and so on). For our purpose, there is no need to set up any data here. Managing user ID access control For a computer system's security, role-based access control is an approach to restricting system access to authorized users. ADempiere uses this role-based access control approach for its internal security implementation. In the subsequent sections, we will introduce you to creating and configuring role-based access control in the ADempiere system. Introduction to ADempiere roles The ADempiere role is the place where we can define and configure the access rights for our authorized user ID. These access rights include access to: Organization Window Process Form Workflow Task Document Action In our example, we will create two roles, which have the following behavior: The first role will have all access rights The second role will have restricted or limited rights We will practice creating these sample roles and examine the impact of the security configuration. Creating a new ADempiere role Open the Menu  System Admin | General Rules | Security | Role window, and then enter and save the following minimum requirements information on the Role tab: Field 1st data 2nd data Client Sistematika Fashion, Ltd Sistematika Fashion, Ltd Organization * * Name All Access Restricted Access User Level Client + Organization Organization Manual deselected selected Preference Level Client Organization Maintain Change Log selected selected Show Accounting selected deselected Access all Orgs selected deselected Can Report selected selected Can Export selected selected For the All Access role, select all of the checkboxes in the Allow Info in Role fields group. An example for the information in the Role tab for All Access is shown in the following screenshot: On saving the All Access role (which has the Manual checkbox deselected), the Window Access, Process Access, Form Access, Workflow Access, Task Access, and Document Action Access will be granted automatically, based on User Level selection. Check it out in all of the available tabs in this Role window. This role has almost identical access rights when compared to the default Sistematika Fashion, Ltd Admin role. Attaching a user ID to a specific role With our newly-created role, you need to assign a user ID to this role. Perform the following activities: Assign user ID Daniel to the All Access role.Ensure that your active record in the Role tab of the Role window is All Access. Navigate to the User Assignment tab, and then click on the New button. Set the Organization to *, and the User/Contact field to Daniel, and then save this information. Assign user ID Moses to the Restricted Access role. Ensure that your active record in the Role tab of Role window is Restricted Access. Navigate to the User Assignment tab, and then click on the New button. Set the Organization to *, and the User/Contact field to Moses, and then save this information. With this configuration, user ID Daniel will be able to log in to the system and work in all of the available organizations. Organization assignment is automatically provided for the All Access role because, it has the Access all orgs checkbox selected. Assigning organization access to a user ID Unfortunately, although user ID Moses has already been assigned to the Restricted Access role, he will still not able to access and log in to the system. This is because the Restricted Access role has the Access all Orgs checkbox deselected. With this configuration, we need to manually assign organization access to this role. For our example, we will assign the Shirt and Dress organization to this role. Perform the following tasks: Be sure that your active record in the Role tab of Role window is Restricted Access. Navigate to the Org Access tab, set the Organization to Shirt, and then click on the Save button. While still on the Org Access tab, click on the New button, set the Organization to Dress, and finalize the task by clicking on the Save button. The result is shown in the following screenshot: Now, user ID Moses will be able to log in and access the system. Working with the Access all Orgs option If the Access all Orgs option is selected, your user ID will be able to access all of the organizations available in the client. If this option is deselected, you have two options for assigning organization access to a certain user ID: Select the Use User Org Access checkbox. This option will appear if you deselect the Access all Orgs option. You need to register the organization access through the Org Access tab in the User window. If the Use User Org Access checkbox is deselected, you can register an organization through the Org Access tab in the Role window. Working with the Maintain Change Log option To see the history of the data changes, launch another ADempiere client, log in with user ID Daniel, password 123456, using All Access as a role, and Shirt as organization. As this feature is enabled for all of the available ADempiere windows, we can practice by working in the Product window. Open this window and find the Standard product. For this product, perform the following activities: Change the UPC/EAN field to UPC-STD, and click on the Save button Once again, change the UPC/EAN field to UPC-STD001, and click on the Save button Now, click on Record Info in this window. This will show you the information shown in the following screenshot: Working with the Show accounting option With this option selected (along with having the Show Accounting Tabs option in Tools  Preference| selected), you will be able to read, modify, and execute processes related to accounting. If this option is deselected, you will not be able to: Access accounting facts/GL journal entries in any of the ADempiere documents such as MM Receipt, AR Invoice, and so on. The Posted or Not Posted button will not available in all of the documents. Access windows related to accounting (such as Accounting Fact Details, Account Combination, Account Element, GL Journal window, and so on). Access accounting configuration (such as the Accounting tab of Product, Business Partner, Cashbook, Bank window, and so on). The last two types of access are basically configurable. When registering the tab as part of constructing the window in the Window, Tab & Field window, the tab has Accounting Tab attributes. With these attributes, you can define whether or not this tab will show information related to Accounting. To unveil this configuration, launch another ADempiere client, and log in with user ID System, password System, and the role System Administrator. Open the Menu  Application Dictionary | Window|, Tab & Field window. In the upcoming Lookup Record window (search dialog window), enter Accounting Fact Details in the Name field and click on the OK button. In the Accounting Fact Details record, navigate to the Tab tab. You will see that the Accounting Tab checkbox is selected, as shown in the following screenshot: With this configuration, and while the Show Accounting checkbox is deselected for your role, you will not be able to access this tab. Because this is the only tab available in the Accounting Fact Details window, you cannot access the window. Try to access this window by using user ID user and Sistematika Fashion, Ltd User as the role. The system will display a message such as With your current role and settings, you cannot view this information. Now, log off from user ID System. Working with the Can Report option As a default, the Can Report option is selected. With this option, you can generate a report by clicking on the Report button for any window that has the reports feature. If this option is deselected, you cannot generate a report for these windows. If the Can Report option is deselected, the user ID that is connected using this role will get the following error message while creating reports: Working with the Can Export option After print previewing our reports using the Print preview or Print button, if the Can Export option is selected, we will be able to export our reports into various file formats (such as, XLS, PDF, and so on). If this option is deselected, the Export button will not be available. Therefore, you cannot export your reports. Accessing Info Window ADempiere provides us with real-time information to assess product, business partner, account information, and so on. You will be able to control the availability of this information by selecting or deselecting the corresponding Info window in the Role tab of the Role window, as shown in the following screenshot: For example, if you deselect the Allow Info BPartner checkbox, the Business Partner Info will disappear from the View menu. Assigning Window Access As described in the Assigning organization access to user ID section, user ID Moses will be able to log in, select Restricted Access as a Role and Shirt as the Organization to work in this environment. He can then start working with the available window. "Available window? There is no window available in the main menu. I can not see any window after logging in!" Yes, there is no window available while accessing the system by using the Restricted Access role. We have not yet registered the list of windows in the Window Access tab. In our example, we will register two windows for this role: Purchase Order and Material Receipt. This user ID then will have the rights to perform activities in both of these windows. Ensure that you are in the Restricted Access record in the Role tab of the Role window. Navigate to the Window Access tab, and then enter and save the following information: Field 1st data 2nd data Organization * * Window Purchase Order Material Receipt Read Write selected selected
Read more
  • 0
  • 0
  • 2337
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-introduction-jsf-part-2
Packt
30 Dec 2009
7 min read
Save for later

An Introduction to JSF: Part 2

Packt
30 Dec 2009
7 min read
Standard JSF Validators The JSF Core tag library also includes a number of built-in validators. These validator tags can also be registered with UI components to verify that required fields are completed by the user-that numeric values are within an acceptable range,and that text values are a certain length. For more specific validation scenarios, we can also write our own custom validators. User input validation happens immediately after data conversion during the JSF request lifecycle. Validating the Length of a Text Value JSF includes a built-in validator that can be used to ensure a text value entered by the user is between an expected minimum and maximum length. The following example demonstrates using the <f:validatelength> tag’s minimum and maximum attributes to check that the password entered by the user in the password field is exactly 8 characters long. It also demonstrates how to use the label attribute of certain JSF input components (introduced in JSF 1.2) to render a localizable validation message. JSF Validation Messages The JSF framework includes predefined validation messages for different input components and validation scenarios. These messages are defined in a message bundle (properties file) including in the JSF implementation jar file. Many of these messages are parameterized, meaning that since JSF 1.2 a UI component’s label can be inserted into these messages to provide more detailed information to the user. The default JSF validation messages can be overridden by specifying the same message bundle keys in the application’s message bundle. We will see an example of customizing JSF validation messages below. Notice that we also set the maxlength attribute of the <h:inputsecret> tag to limit the input to 8 characters. This does not, however, ensure that the user enters a minimum of 8 characters. Therefore, the <f:validatelength> validator tag is required.   <f:view> <h:form> <h:outputLabel value="Please enter a password (must be 8 characters): " /> <h:inputSecret maxlength="8" id="password" value="#{backingBean.password}" label="Password"> <f:validateLength minimum="8" maximum="8" /> </h:inputSecret> <h:commandButton value="Submit" /><br /> <h:message for="password" errorStyle="color:red" /> </h:form> </f:view> Validating a Required Field The following example demonstrates how to use the built-in JSF validators to ensure that a text field is filled out before the form is processed, and that the numeric value is between 1 and 10: <f:view> <h:form> <h:outputLabel value="Please enter a number: " /> <h:inputText id="number" label="Number" value="#{backingBean.price}" required="#{true}" /> <h:commandButton value="Submit" /><br /> <h:message for="number" errorClass="error" /> </h:form> </f:view> The following screenshot demonstrates the result of submitting a JSF form containing a required field that was not filled out. We render the validation error message using an <h:message> tag with a for attribute set to the ID of the text field component. We have also overridden the default JSF validation message for required fields by specifying the following message key in our message bundle. We will discuss message bundles and internationalization (I18N) shortly.   javax.faces.component.UIInput.REQUIRED=Required field. javax.faces.component.UIInput.REQUIRED_detail=Please fill in this field. Validating a numeric range The JSF Core <f:validatelongrange> and </f:validatedoublerange> tags can be used to validate numeric user input. The following example demonstrates how to use the <f:validatelongrange> tag to ensure an integer value entered by the user is between 1 and 10. <f:view> <h:form> <h:outputLabel value="Please enter a number between 1 and 10: " /> <h:inputText id="number" value="#{backingBean.number}" label="Number"> <f:validateLongRange minimum="1" maximum="10" /> </h:inputText> <h:commandButton value="Submit" /><br /> <h:message for="number" errorStyle="color:red" /> <h:outputText value="You entered: #{backingBean.number}" rendered="#{backingBean.number ne null}" /> </h:form> </f:view> The following screenshot shows the result of entering an invalid value into the text field. Notice that the value of the text field’s label attribute is interpolated with the standard JSF validation message. Validating a floating point number is similar to validating an integer. The following example demonstrates how to use the value to ensure that a floating point number is between 0.0 and 1.0.   <f:view> <h:form> <h:outputLabel value="Please enter a floating point number between 0 and 1: " /> <h:inputText id="number" value="#{backingBean.percentage}" label="Percent"> <f:validateDoubleRange minimum="0.0" maximum="1.0" /> </h:inputText> <h:commandButton value="Submit" /><br /> <h:message for="number" errorStyle="color:red" /> <h:outputText value="You entered: " rendered="#{backingBean.percentage ne null}" /> <h:outputText value="#{backingBean.percentage}" rendered="#{backingBean.percentage ne null}" > <f:convertNumber type="percent" maxFractionDigits="2" /> </h:outputText> </h:form> </f:view> Registering a custom validator JSF also supports defining custom validation classes to provide more specialized user input validation. To create a custom validator, first we need to implement the javax.faces.validator.Validator interface. Implementing a custom validator in JSF is straightforward. In this example, we check if a date supplied by the user represents a valid birthdate. As most humans do not live more than 120 years, we reject any date that is more than 120 years ago. The important thing to note from this code example is not the validation logic itself, but what to do when the validation fails. Note that we construct a FacesMessage object with an error message and then throw a ValidatorException.   package chapter1.validator; import java.util.Calendar; import java.util.Date; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.Validator; import javax.faces.validator.ValidatorException; public class CustomDateValidator implements Validator { public void validate(FacesContext context, UIComponent component, Object object) throws ValidatorException { if (object instanceof Date) { Date date = (Date) object; Calendar calendar = Calendar.getInstance(); calendar.roll(Calendar.YEAR, -120); if (date.before(calendar.getTime())) { FacesMessage msg = new FacesMessage(); msg.setSummary("Invalid birthdate: " + date); msg.setDetail("The date entered is more than 120 years ago."); msg.setSeverity(FacesMessage.SEVERITY_ERROR); throw new ValidatorException(msg); } } } } We have to declare our custom validators in faces-config.xml as follows, giving the validator an ID of customDateValidator: <validator> <description>This birthdate validator checks a date to make sure it is within the last 120 years.</description> <display-name>Custom Date Validator</display-name> <validator-id>customDateValidator</validator-id> <validator-class> chapter1.validator.CustomDateValidator </validator-class> </validator> Next, we would register our custom validator on a JSF UI component using the tag. This tag has a converterId attribute that expects the ID of a custom converter declared in faces-config.xml. Notice in the following example that we are also registering the standard JSF <f:convertdatetime></f:convertdatetime> converter on the tag. This is to ensure that the value entered by the user is first converted to a java.util.Date object before it is passed to our custom validator. <h:inputText id="name" value="#{backingBean.date}"> <f:convertDateTime type="date" pattern="M/d/yyyy" /> <f:validator validatorId="customDateValidator" /> </h:inputText> Many JSF UI component tags have both a converter and validator attribute that accept EL method expressions. These attributes provides another way to register custom converters and validators implemented in managed beans on UI components.
Read more
  • 0
  • 0
  • 3604

article-image-introduction-hibernate-and-spring-part-2
Packt
29 Dec 2009
6 min read
Save for later

An Introduction to Hibernate and Spring: Part 2

Packt
29 Dec 2009
6 min read
Object relational mapping As the previous discussion shows, we are looking for a solution that enables applications to work with the object representation of the data in database tables, rather than dealing directly with that data. This approach isolates the business logic from any relational issues that might arise in the persistence layer. The strategy to carry out this isolation is generally called object/relational mapping (O/R Mapping, or simply ORM). A broad range of ORM solutions have been developed. At the basic level, each ORM framework maps entity objects to JDBC statement parameters when the objects are persisted, and maps the JDBC query results back to the object representation when they are retrieved. Developers typically implement this framework approach when they use pure JDBC. Furthermore, ORM frameworks often provide more sophisticated object mappings, such as the mapping of inheritance hierarchy and object association, lazy loading, and caching of the persistent objects. Caching enables ORM frameworks to hold repeatedly fetched data in memory, instead of being fetched from the database in the next requests, causing deficiencies and delayed responses, the objects are returned to the application from memory. Lazy loading, another great feature of ORM frameworks, allows an object to be loaded without initializing its associated objects until these objects are accessed. ORM frameworks usually use mapping definitions, such as metadata, XML files, or Java annotations, to determine how each class and its persistent fields should be mapped onto database tables and columns. These frameworks are usually configured declaratively, which allows the production of more flexible code. Many ORM solutions provide an object query language, which allows querying the persistent objects in an object-oriented form, rather than working directly with tables and columns through SQL. This behavior allows the application to be more isolated from the database properties. Hibernate as an O/R Mapping solution For a long time, Hibernate has been the most popular persistence framework in the Java community. Hibernate aims to overcome the already mentioned impedance mismatch between object-oriented applications and relational databases. With Hibernate, we can treat the database as an object-oriented store, thereby eliminating mapping of the object-oriented and relational environments. Hibernate is a mediator that connects the object-oriented environment to the relational environment. It provides persistence services for an application by performing all of the required operations in the communication between the object-oriented and relational environments. Storing, updating, removing, and loading can be done regardless of the objects persistent form. In addition, Hibernate increases the application's effectiveness and performance, makes the code less verbose, and allows the code to be more focused on business rules than persistence logic. The following screenshot depicts Hibernates role in persistence: Hibernate fully supports object orientation, meaning all aspects of objects, such as association and inheritance, are properly persisted. Hibernate can also persist object navigation, that is, how an object is navigable through its associated objects. It caches data that is fetched repeatedly and provides lazy loading, which notably enhances database performance. As you will see, Hibernate provides caches in two levels: first-level built-in, and second-level pluggable cache strategies. Th e first-level cache is a required property for any ORM to preserve object consistency. It guaranties that the application always works with consistent objects. This is originated from the fact that many threads in the application use the ORM to persist the objects which might potentially be associated to the same table rows in the database. The following screenshot depicts the role of a cache when using Hibernate: Hibernate provides its own query language, which is Hibernate Query Language (HQL). At runtime, HQL expressions are transformed to their corresponding SQL statements, based on the database used. Because databases may use different versions of SQL and may expose different features, Hibernate presents a new concept, called an SQL dialect, t o distinguish how databases differ. Furthermore, Hibernate allows SQL expressions to be used either declaratively or programmatically, which is useful in specific situations when Hibernate does not satisfy application persistence requirements. Hibernate keeps track of object changes through snapshot comparisons to prevent unnecessary updating. Other O/R Mapping solutions Although Hibernate is the most popular persistence framework, many other frameworks do exist. Some of these are explained as follows: Enterprise JavaBeans (EJB): It is a standard J2EE (J ava 2 Enterprise Edition) technology that defines a different type of persistence by presenting entity beans. Mostly, for declarative middleware services that are provided by the application server, such as transactions, EJB may be preferred for architecture. However, due to its complexity, nontransparent persistence, and need for a container (all of which make it difficult to implement, test, and maintain), EJB is less often used than other persistence frameworks. iBatis SQL Map: It is a result set–mapping framework which works at the SQL level, allowing SQL string definitions with parameter placeholders in XML files. At runtime, the placeholders are filled with runtime values, either from simple parameter objects, JavaBeans properties, or a parameter map. To their advantage, SQL maps allow SQL to be fully customized for a specific database. To their disadvantage, however, these maps do not provide an abstraction from the specific features of the target database. Java Data Objects (JDO): It is a specification for general object persistence in any kind of data store, including relational databases and object-oriented databases. Most JDO implementations support using metadata mapping definitions. JDO provides its own query language, JDOQL, and its own strategy for change detection. TopLink: It provides a visual mapping editor (Mapping Workbench) and offers a particularly wide range of object, relational mappings, including a complete set of direct and relational mappings, object-to-XML mappings, and JAXB (Java API for XML Binding) support. TopLink provides a rich query framework that supports an object-oriented expression framework, EJB QL, SQL, and stored procedures. It can be used in either a JSE or a JEE environment. Hibernate designers has borrowed many Hibernate concepts and useful features from its ancestors Hibernate versus other frameworks Unlike the frameworks just mentioned, Hibernate is easy to learn, simple to use, comprehensive, and (unlike EJB) does not need an application server. Hibernate is well documented, and many resources are available for it. Downloaded more than three million times, Hibernate is used in many applications around the world. To use Hibernate, you need only J2SE 1.2 or later, and it can be used in stand-alone or distributed applications. The current version of Hibernate is 3, but the usage and configuration of this version are very similar to version 2. Most of the changes in Hibernate 3 are compatible with Hibernate 2. Hibernate solves many of the problems of mapping objects to a relational environment, isolating the application from getting involved in many persistence issues. Keep in mind that Hibernate is not a replacement for JDBC. Rather, it can be thought of as a tool that connects to the database through JDBC and presents an object-oriented, application-level view of the database.
Read more
  • 0
  • 0
  • 3160

article-image-introduction-hibernate-and-spring-part-1
Packt
29 Dec 2009
4 min read
Save for later

An Introduction to Hibernate and Spring: Part 1

Packt
29 Dec 2009
4 min read
This article by Ahmad Seddighi, introduces Spring and Hibernate, explaining what persistence is, why it is important, and how it is implemented in Java applications. It provides a theoretical discussion of Hibernate and how Hibernate solves problems related to persistence. Finally, we take a look at Spring and the role of Spring in persistence. Hibernate and Spring are open-source Java frameworks that simplify developing Java/JEE applications from simple, stand-alone applications running on a single JVM, to complex enterprise applications running on full-blown application servers. Hibernate and Spring allow developers to produce scalable, reliable, and effective code. Both frameworks support declarative configuration and work with a POJO (Plain Old Java Object) programming model (discussed later in this article), minimizing the dependence of application code on the frameworks, and making development more productive and portable. Although the aim of these frameworks partially overlap, for the most part, each is used for a different purpose. The Hibernate framework aims to solve the problems of managing data in Java: those problems which are not fully solved by the Java persistence API, JDBC (Java Database Connectivity), persistence providers, DBMS (Database Management Systems), and their mediator language, SQL (Structured Query Language). In contrast, Spring is a multitier framework that is not dedicated to a particular area of application architecture. However, Spring does not provide its own solution for issues such as persistence, for which there are already good solutions. Rather, Spring unifies preexisting solutions under its consistent API and makes them easier to use. As mentioned, one of these areas is persistence. Spring can be integrated with a persistence solution, such as Hibernate, to provide an abstraction layer over the persistence technology, and produce more portable, manageable, and effective code. Furthermore, Spring provides other services spread over the application architecture, such as inversion of control and aspect-oriented programming (explained later in this article), decoupling the application's components, and modularizing common behaviors. This article looks at the motivation and goals for Hibernate and Spring. The article begins with an explanation of why Hibernate is needed, where it can be used, and what it can do. We'll take a quick look at Hibernates alternatives, exploring their advantages and disadvantages. I'll outline the valuable features that Hibernate offers and explain how it can solve the problems of the traditional approach to Java persistence. The discussion continues with Spring. I'll explain what Spring is, what services it offers, and how it can help to develop a high-quality data-access layer with Hibernate. Persistence management in Java Persistence has long been a challenge in the enterprise community. Many persistence solutions from primitive, file-based approaches, to modern, object-oriented databases have been presented. For any of these approaches, the goal is to provide reliable, efficient, flexible, and scalable persistence. Among these competing solutions, relational databases (because of certain advantages) have been most widely accepted in the IT world. Today, almost all enterprise applications use relational databases. A relational database is an application that provides the persistence service. It provides many persistence features, such as indexing data to provide speedy searches; solves the relevant problems, such as protecting data from unauthorized access; and handles many complications, such as preserving relationships among data. Creating, modifying, and accessing relational databases is fairly simple. All such databases present data in two-dimensional tables and support SQL, which is relatively easy to learn and understand. Moreover, they provide other services, such as transactions and replication. These advantages are enough to ensure the popularity of relational databases. To provide support for relational databases in Java, the JDBC API was developed. JDBC allows Java applications to connect to relational databases, express their persistence purpose as SQL expressions, and transmit data to and from databases. The following screenshot shows how this works: Using this API, SQL statements can be passed to the database, and the results can be returned to the application, all through a driver. The mismatch problem JDBC handles many persistence issues and problems in communicating with relational databases. It also provides the needed functionality for this purpose. However, there remains an unsolved problem in Java applications: Java applications are essentially object-oriented programs, whereas relational databases store data in a relational form. While applications use object-oriented forms of data, databases represent data in two-dimensional table forms. This situation leads to the so-called object-relational paradigm mismatch, which (as we will see later) causes many problems in communication between object-oriented and relational environments. For many reasons, including ease of understanding, simplicity of use, efficiency, robustness, and even popularity, we may not discard relational databases. However, the mismatch cannot be eliminated in an effortless and straightforward manner.
Read more
  • 0
  • 0
  • 4939

article-image-modeling-steampunk-spacecraft-using-blender-3d-249
Packt
29 Dec 2009
5 min read
Save for later

Modeling a Steampunk Spacecraft using Blender 3D 2.49

Packt
29 Dec 2009
5 min read
Steampunk concept Before we actually begin working on the model, let's make clear the difference between a regular spacecraft and a steampunk spacecraft. Although both of them are based on science fiction, the steampunk spacecraft has a few important characteristics that differ from a regular hi-tech spacecraft. Imagine a world where the advances of science and machinery were actually developed centuries ago. For example, imagine medieval knights using hi-tech armor and destroying castles with rockets. It may sound strange, as the rockets have been made only for the army in the last century. What would a fighter jet look like in the Middle Ages? It would be a mix of steel, glass, and wood. The steampunk environment is made out of these kinds of things, modern objects and vehicles produced and developed in a parallel universe, where those discoveries were made long ago. The secret of designing a good steampunk vehicle or object is to mix the recent technology with the materials and methods available in past times, such as wood and bronze to make a space suit. If you need some inspiration to design objects like those, watch some recent movies that use a steampunk environment to create some interesting machines. But, to really get to the source, I do recommend that you read some books written by Jules Verne, who wrote about incredible environments and machines that dive deep into the ocean or travel to outer space. The following image is an example of a steampunk weapon (Image credits: Halogen Gallery, licensed under Creative Commons): Next is a steampunk historical character (Image credits: Sparr0, licensed under Creative Commons): Here are a few resources to find out more about Steam Punk: Steampunk at Wikipedia, with lots of resources:http://en.wikipedia.org/wiki/Steampunk Guide to drawing and creating steampunk machinery:http://www.crabfu.com/steamtoys/diy_steampunk/ Showcase of steampunk technology:http://www.instructables.com/id/Steampunk/ Spacecraft concept Now that we know how to design a good steampunk machine, let's discuss the concept of this spacecraft. For this project, we will design a machine that mixes some elements of steel, but not those fancy industrial plates and welded parts. Instead, our machine will have the look and feel of a machine built by a blacksmith. As it would be really strange to have wooden parts for a spacecraft, we will skip or use this material only for the interior. Other aspects of the machine that will help give the impression of a steampunk spacecraft are as follows: Riveted sheets of metal Metal with the look of bronze Valves and pipes With that in mind, we can start with this concept image to create our spacecraft: It's not a complete project, but we're off to a great start with Blender and our use of polygons to create the basis for this Incredible Machine. Project workflow This project will improve our modeling and creating skills with Blender to a great extent! So, to make the process more efficient, the workflow will be planned as this would be done by a professional studio. This is the best way to optimize the time and quality of the project. It will also guarantee that future projects will be finished in the shortest timeframe. The first step for all projects is to find some reference images or photos for the pre-visualization stage. At this point, we should make all important decisions about a project based only on your concept studies. The biggest amount of time spent on this type of project is with artistic decisions like the framing of the camera, type and color of materials, shape of the object, and environment setup. All of those decisions should be made before we open Blender and start modeling because a simple detour on the main concept could result in a partial or total loss of all work. When all of the decisions are made, the next step is to start modeling with the reference images we found on the Internet, or we can draw the references ourselves. The modeling stage involves the spacecraft and the related environment, which of course will be outer space. For this environment, Blender will help us design a space with nebulas, star fields, and even a glazing star. Right after the environment is finished, we can begin working with some materials and textures. As the object has a complex set of parts, and in some cases an organic topology, we will have to pay extra attention to the UV mapping process to add textures. We'll use a few tips when working with those complex shapes and topology to simplify the process. What would a spacecraft be without special effects? Special effects make the project more realistic. The addition of a particle system enables the spacecraft's engines to work and simulates the shooting of a plasma gun. With those two effects, we will be able to give dynamism to the scene, showing some working parts of the object. And, to finish things up, there is the light setup for the scene. A light setup for a space scene is rather easy to accomplish because we will only have a strong light source for the scene, and not so much bouncing for the light rays. The goal for this project is to end up with a great space scene. If you already know how to use Blender, get ready to put your knowledge to the test!
Read more
  • 0
  • 0
  • 2924
article-image-integrating-spring-framework-hibernate-orm-framework-part-2
Packt
29 Dec 2009
5 min read
Save for later

Integrating Spring Framework with Hibernate ORM Framework: Part 2

Packt
29 Dec 2009
5 min read
Configuring Hibernate in a Spring context Spring provides the LocalSessionFactoryBean class as a factory for a SessionFactory object. The LocalSessionFactoryBean object is configured as a bean inside the IoC container, with either a local JDBC DataSource or a shared DataSource from JNDI. The local JDBC DataSource can be configured in turn as an object of org.apache.commons.dbcp.BasicDataSource in the Spring context: <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName"> <value>org.hsqldb.jdbcDriver</value> </property> <property name="url"> <value>jdbc:hsqldb:hsql://localhost/hiberdb</value> </property> <property name="username"> <value>sa</value> </property> <property name="password"> <value></value> </property></bean> In this case, the org.apache.commons.dbcp.BasicDataSource (the Jakarta Commons Database Connection Pool) must be in the application classpath. Similarly, a shared DataSource can be configured as an object of org.springframework.jndi.JndiObjectFactoryBean. This is the recommended way, which is used when the connection pool is managed by the application server. Here is the way to configure it: <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"> <value>java:comp/env/jdbc/HiberDB</value> </property></bean> When the DataSource is configured, you can configure the LocalSessionFactoryBean instance upon the configured DataSource as follows: <bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource"/> </property> ...</bean> Alternatively, you may set up the SessionFactory object as a server-side resource object in the Spring context. This object is linked in as a JNDI resource in the JEE environment to be shared with multiple applications. In this case, you need to use JndiObjectFactoryBean instead of LocalSessionFactoryBean: <bean id="sessionFactory" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"> <value>java:comp/env/jdbc/hiberDBSessionFactory</value> </property></bean> JndiObjectFactoryBean is another factory bean for looking up any JNDI resource. When you use JndiObjectFactoryBean to obtain a preconfigured SessionFactory object, the SessionFactory object should already be registered as a JNDI resource. For this purpose, you may run a server-specific class which creates a SessionFactory object and registers it as a JNDI resource. LocalSessionFactoryBean uses three properties: datasource, mappingResources, and hibernateProperties. These properties are as follows: datasource refers to a JDBC DataSource object that is already defined as another bean inside the container. mappingResources specifies the Hibernate mapping files located in the application classpath. hibernateProperties determines the Hibernate configuration settings. We have the sessionFactory object configured as follows: <bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource"/> </property> <property name="mappingResources"> <list> <value>com/packtpub/springhibernate/ch13/Student.hbm.xml</value> <value>com/packtpub/springhibernate/ch13/Teacher.hbm.xml</value> <value>com/packtpub/springhibernate/ch13/Course.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect </prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.max_fetch_depth">2</prop> </props> </property></bean> The mappingResources property loads mapping definitions in the classpath. You may use mappingJarLocations, or mappingDirectoryLocations to load them from a JAR file, or from any directory of the file system, respectively. It is still possible to configure Hibernate with hibernate.cfg.xml, instead of configuring Hibernate as just shown. To do so, configure sessionFactory with the configLocation property, as follows: <bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource"/> </property> <property name="configLocation"> <value>/conf/hibernate.cfg.xml</value> </property></bean> Note that hibernate.cfg.xml specifies the Hibernate mapping definitions in addition to the other Hibernate properties. When the SessionFactory object is configured, you can configure DAO implementations as beans in the Spring context. These DAO beans are the objects which are looked up from the Spring IoC container and consumed by the business layer. Here is an example of DAO configuration: <bean id="studentDao" class="com.packtpub.springhibernate.ch13.HibernateStudentDao"> <property name="sessionFactory"> <ref local="sessionFactory"/> </property></bean> This is the DAO configuration for a DAO class that extends HibernateDaoSupport, or directly uses a SessionFactory property. When the DAO class has a HibernateTemplate property, configure the DAO instance as follows: <bean id="studentDao" class="com.packtpub.springhibernate.ch13.HibernateStudentDao"> <property name="hibernateTemplate"> <bean class="org.springframework.orm.hibernate3.HibernateTemplate"> <constructor-arg> <ref local="sessionFactory"/> </constructor-arg> </bean> </property></bean> According to the preceding declaration, the HibernateStudentDao class has a hibernateTemplate property that is configured via the IoC container, to be initialized through constructor injection and a SessionFactory instance as a constructor argument. Now, any client of the DAO implementation can look up the Spring context to obtain the DAO instance. The following code shows a simple class that creates a Spring application context, and then looks up the DAO object from the Spring IoC container: package com.packtpub.springhibernate.ch13; public class DaoClient { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("com/packtpub/springhibernate/ch13/applicationContext.xml"); StudentDao stdDao = (StudentDao)ctx.getBean("studentDao"); Student std = new Student(); //set std properties //save std stdDao.saveStudent(std); }}
Read more
  • 0
  • 0
  • 4486

article-image-configuring-clusters-glassfish
Packt
29 Dec 2009
7 min read
Save for later

Configuring Clusters in GlassFish

Packt
29 Dec 2009
7 min read
Configuring clusters for GlassFish In order to deliver the required performance, throughput, and reliability, a production environment typically needs to host enterprise applications using multiple running application server instances. In order to easily configure and maintain these server instances, most application server products, including GlassFish, allow these server instances to be grouped into a cluster and administered together. In this section, we first review the core concepts of the GlassFish cluster, and then show you how to configure and manage clusters. Understanding GlassFish clusters A GlassFish cluster is a logical entity that groups multiple GlassFish Server instances. The server instances within a cluster can run on different physical machines or on the same machine. The cluster is administered by the Domain Administration Server (DAS). The server instances in a cluster share the same configuration, and they host all applications and resources deployed to the cluster. The main benefit of a cluster is that it significantly simplifies the administration of server instances. Instead of configuring these server instances and deploying applications to them individually, a cluster provides a one-stop administration facility to enforce the homogeneity of server instances. Besides, a cluster provides very good support for horizontal scalability. For example, if the production environment no longer has sufficient processing power, we can dynamically create a GlassFish Server instance and add it to the existing cluster without extensive reconfiguration. Finally, with the help of a load balancer and appropriate HA configuration, a cluster can be made resilient to server instance issues. We will focus on the clustering aspect of GlassFish in this section. Load balancers and HA will be discussed later in this article. The following figure illustrates the main components of a cluster from the administration perspective. The components illustrated in the figure are described as follows: The Domain Administration Server (DAS): DAS is a special server instance responsible for administration of a domain. All administrative operations are routed to DAS. Upon receiving administrative requests, DAS is responsible for sending the request to an individual server instance, or broadcasting it to all the server instances in a cluster. DAS can administer server instances running on remote hosts as well. Node agent: A node agent is a light-weight process running on the physical server that hosts GlassFish Server instances. The node agent is responsible for managing the life cycle of these server instances. It can perform the following tasks: Start, stop, restart, create, and delete server instances Provide a view of the log files of failed server instance If the node agent crashes, it does not affect the server instances and user applications that are currently running. However, a failed node agent can no longer manage and monitor those server instances. Server instance: With the exception of DAS, all the other server instances must be created with a reference to a node agent. A server instance can be stand-alone, or it can belong to a cluster. A stand-alone instance maintains and uses its own configuration, while a clustered instance inherits majority of the configuration information from the cluster. In our experience, stand-alone server instances are rarely used. Even if you only need one server instance to host applications, we recommend that you define a cluster with only one instance. This approach always allows the server to be potentially scaled out by adding additional server instances to the cluster. The overhead of clustered instance is completely negligible. The central repository and repository cache: The central repository is maintained by DAS. The central repository contains the server instance configuration data, and the applications deployed to the GlassFish domain. Each server instance and cluster synchronizes the central repository to its local repository cache. Keep in mind that the repository cache is a subset of the central repository, because the server instance and cluster only synchronize the information pertinent to itself. The local repository cache makes it possible to keep stand-alone and clustered server instances running while DAS is shut down. In fact, many organizations indeed shut down DAS in production environment, and they only start up the DAS when there is a new deployment of applications or resources. Without the DAS running, the GlassFish configuration cannot be changed using common administrative tasks. A node agent is associated with a particular domain when it is created, and it can service only a single domain. If a physical machine hosts server instances that belong to multiple domains, it must run multiple node agents, one for each domain. DAS only needs the node agent to perform administrative operations on the server instances. The synchronization between DAS and server instances takes place directly through the JMX API remote connector. The server instance or node agent synchronizes its state with the central repository in the following cases: completely at instance or node agent creation and start-up time, and incrementally as configuration changes are made to the central repository. Now let's dive into the process of configuring a GlassFish cluster. Configuring clusters In this section, we discuss the necessary steps to configure a GlassFish cluster, and along the way we will discuss more features of the GlassFish cluster. GlassFish clusters can be created on most operating system and hardware platforms. The noticeable exceptions are Microsoft Windows running the 64-bit JDK software, and Mac OSX. Obtaining cluster support The very first thing we need to do in order to configure a cluster is to make sure that the GlassFish Server we are working with has cluster support. Earlier, we introduced the concept of the usage profile of GlassFish. As it turned out, clustering support is available in the cluster and enterprise profiles, and not in the developer profile by default. However, even if we originally installed GlassFish in the developer profile, we can easily upgrade the GlassFish Server to enable clustering support. To do this, complete the following steps: Log on to the GlassFish Admin Console. Click the Application Server node in the navigation pane. Click the General tab in the main content pane. Click Add Cluster Support, as shown in the following screenshot. Click OK to confirm the choice. Restart the GlassFish Server. Once GlassFish restarts, we can log on to the Admin Console. We can confirm the cluster support by verifying the new Admin Console, as shown in the following screenshot. As we can see, in the navigation panel, the previous Application Server node is replaced by the Domain node. If we click this node in the navigation panel, we will see just a few configuration options, such as managing the administrator password. Most of the other management options, such as JVM settings are no longer there in the Admin Console. The reason is that those features, such as JVM settings are applied to individual server instances. Therefore, these properties are now associated with the server instances in the cluster profile. For a GlassFish Server that is upgraded from the developer profile, the original server instance now becomes the DAS instance and GlassFish treats the DAS as a stand-alone server instance. When we log on to the Admin Console, this server is listed under the Stand-Alone Instances node. Once we have enabled clusters for GlassFish, we can start creating clusters. As all server instances are managed through node agents, the next step in creating a cluster is to create and start the node agents.
Read more
  • 0
  • 0
  • 3391

article-image-writing-xml-data-file-system-ssis
Packt
29 Dec 2009
5 min read
Save for later

Writing XML data to the File System with SSIS

Packt
29 Dec 2009
5 min read
Integrating data into applications or reports is one of the most important, expensive and exacting activities in building enterprise data warehousing applications. SQL Server Integration Services which first appeared in MS SQL Server 2005 and continued into MS SQL Server 2008 provides a one-stop solution to the ETL Process. The ETL Process consists of extracting data from a data source, transforming the data so that it can get in cleanly into the destination followed by loading the transformed data to the destination source. Enterprise data can be of very different kinds ranging from flat files to data stored in relational databases. Recently storing data in XML data sources has become common as exchanging data in XML format has many advantages. Creating a stored procedure that retrieves XML In the present example it is assumed that you have a copy of the Northwind database. You could use any other database. We will be creating a stored procedure that selects a number of columns from a table in the database using the For XML clause. The Select query would return an XML fragment from the database. The next listing shows the stored procedure. Create procedure [dbo].[tst]asSelect FirstName, LastName, City from Employeesfor XML raw The result of executing this stored procedure[exec tst] in the SQL Server Management Studio is shown in the next listing. <row FirstName="Nancy" LastName="Davolio" City="Seattle"/><row FirstName="Andrew" LastName="Fuller" City="Tacoma"/><row FirstName="Janet" LastName="Leverling" City="Kirkland"/><row FirstName="Margaret" LastName="Peacock" City="Redmond"/><row FirstName="Steven" LastName="Buchanan" City="London"/><row FirstName="Michael" LastName="Suyama" City="London"/><row FirstName="Robert" LastName="King" City="London"/><row FirstName="Laura" LastName="Callahan" City="Seattle"/><row FirstName="Anne" LastName="Dodsworth" City="London"/> Creating a package in BIDS or Visual Studio 2008 You require SQL Server 2008 installed to create a package. In either of these programs, File | New | Projects... brings up New Project window where you can choose to create a business intelligence project with a Integration Services Project template. You create a project by providing a name for the project. Herein it was named XMLquery. After providing a name and closing the New Project window the XMLquery project will be created with a default package with the file name, Package.dtsx. The file name can be renamed by right clicking the file and clicking OK to the window that pops up regarding the change you are making. Herein the package was named XmlToFile.dtsx. The following figure shows the project created by the program. When the program is created the package designer surface will be open with a tabbed page where you can configure control flow tasks, Data Flow Tasks and Event handlers. You can also look at the package explorer to review the contents of the package. The reader may benefit by reviewing my book, Beginners Guide to SQL Server Integration Services, on this site. Adding and configuring a ExecuteSQL task Using an ExecuteSQL Task component the stored procedure on the SQL Server 2008 will be executed. The result of this will be stored in a package variable which will then be retrieved using a Script Task. In this section you will be configuring the ExecuteSQL Task. Drag and drop a Execute SQL Task under Control Flow items in the Toolbox on to the Control Flow tabbed page of the package designer. Double click Execute SQL Task component in the package designer to display the Execute SQL Task Editor as shown. It is a good practice to provide a description to the task. Herein it is, "Retrieving XML from the SQL Server" as shown. The result set can be of any of those shown in the next figure. Since the information that is retrieved running the stored procedure is XML, XML choice is the correct one to choose. The stored procedure is on the SQL Server 2008 and therefore a connection needs to be established. Leave the connection type as OLE DB and click on an empty area along the line item, Connection. This brings up the Configure OLE DB Connection Manager window where you can select an existing connection, or create a new connection. Hit the New... button to bring the Connection Manager window as shown. The window comes up with just the right provider [Native OLE DBSQL Server Native Client10.0]. You can choose the server by browsing with the drop-down handler as shown. In the present case the Windows Authentication is used with the current user as the database administrator. If this information is correct you can browse the database objects to choose the correct database which hosts the stored procedure as shown. You may also test the connection with the Test Connection button. You must close the Connection Manager window which will bring you back to the Configure OLE DB Connection Manager window which now displays the connection you just made. To proceed further you need to close this window as well. This will bring in the connection information into the Execute SQL Task editor window. The type of input is chosen to be a direct input (the others are file and variable). The query to be executed is the stored procedure, tst described early in the tutorial. The BypassPrepare is set to false. The General page of the Execute SQL Task editor is as shown here.
Read more
  • 0
  • 0
  • 12655
article-image-configuring-load-balancers-and-high-availability-glassfish
Packt
29 Dec 2009
9 min read
Save for later

Configuring Load Balancers and High Availability in GlassFish

Packt
29 Dec 2009
9 min read
Configuring load balancers For a cluster with multiple server instances, using a load balancer in front of the server instances not only simplifies the client's view of the system through a single address, but also improves the overall system's reliability. If one server fails, the load balancer can detect the failure and distribute the load to other live server instances. In this section, we will discuss the load balancer support in GlassFish, and how to configure it. GlassFish can work with a variety of load balancers, both hardware and software based. For example, the GlassFish project maintains and releases a load balancer plug-in, which works with Apache, Sun Java System Web Server, and Microsoft IIS. The load balancer plug-in is freely downloadable at http://download.java.net/javaee5/external/<os>/aslb/jars, where <os> indicates the operating system on which the web server is running. Also, GlassFish can be load balanced by Apache using mod_jk. However, the mod_jk based load balancing is not officially supported in GlassFish 2. In this article, we will focus on the GlassFish load balancer plugin. The mod_jk based load balancing will be supported in GlassFish 3. The GlassFish load balancer plug-in accepts HTTP and HTTPS requests and forwards them to one of GlassFish instances in the cluster. It uses a health checker to detect server instance status. If a server instance fails, requests are redirected to existing, available machines. Once a failed server instance comes back online, the load balancer can also recognize when a failed instance has recovered and redistributed the load accordingly. Like most load balancer solutions for web applications, the GlassFish load balancer plugin implements session affinity or sticky session. On the first request from a client, a new session is established on the server instance node that is processing the request. The load balancer routes all subsequent requests for this session to that particular instance. The load balancer plugin configuration actually involves two steps. First, we need to configure the web server to enable the load balancer; we then need to configure the GlassFish Server to specify how the load balancer should be configured for a cluster, or an application in a cluster. In the following section, let's discuss how to configure the Apache web server for the load balancer plugin. Configuring the load balancer plug-in for Apache web server The Apache web server is the most popular web server. Its modular architecture makes it easy to extend for additional functionality. The GlassFish load balancer plugin for Apache is configured as an additional module. In this section, we discuss how to configure this module. In this section, we discuss the configuration of the load balancer plug-in for the default Apache server, version 2.2, with SSL enabled on port 443, installed on Solaris x86. The configuration process for other operating systems is very similar; the only difference is the directory structure of the Apache server. For more detailed information, you can refer to the GlassFish High Availability Administration Guide, located at http://docs.sun.com/app/docs/doc/821-0182. Complete the following steps to configure the load balancer plug-in on the Apache web server: Download the latest load-balancer plug-in from http://download.java.net/javaee5/external/<os>/aslb/jars. Extract the JAR file, and then extract the two ZIP files, SUNWaspx.zip and SUNWaslb.zip to a directory, $lbplug-in_root. Copy the errorpages directory from $lbplug-in_root/lib/webserverplug-in/<os>/apache2.2 to /usr/apache2/2.2/modules/errorpages. The errorpages directory contains the web pages used by the load balancer plug-in to render load balancer error messages. Copy the two files, LBPlug-inDefault_root.res and LBPlug-inD_root.res from $lbplug-in_root/lib/webserver-plug-in/<os>/apache2.2 to the /usr/apache2/2.2/modules/resource directory. Copy the three files, cert8.db, key3.db, and secmpd.db from $lbplugin_root/lib/webserver-plug-in/<os>/apache2.2 to the /usr/apache2/2.2/sec_db_files directory. Copy the file mod_load_balancer.so from $lbplug-in_root/lib/webserver-plug-in/<os>/apache2.2 to the /usr/apache2/2.2/libexec directory. Copy the file loadbalancer.xml.example from $lbplug-in_root/lib/install/templates to the /etc/apache2/2.2/loadblancer.xml. The loadbalancer.xml file is the primary configuration file that defines the load balancer. We will discuss this file in the next section. At this moment, we can consider it as a place holder. Copy the file sun-loadbalancer_1_2.dtd from $lbplug-in_root/lib/dtds to /etc/apache2/2.2. Append the following elements to /etc/apache2/2.2/conf.d/ modules-32.load: LoadModule apachelbplug-in_module libexec/mod_loadbalancer.so <IfModule apachelbplug-in_module> <config-file /etc/apache2/2.2/loadbalancer.xml</IfModule> Add the following definition of the LD_LIBRARY_PATH variable to /etc/apache2/2.2/envvars: LD_LIBRARY_PATH=/usr/lib/mps:$lbplug-in_root/lib:/usr/apache2/2.2/libexec:$LD_LIBRARY_PATH Copy the mpm.conf file from the /etc/apache2/2.2/envvars/samplesconf.d directory to /etc/apache2/2.2/envvars/conf.d, and change the values of the StartServers and MaxClients variables in the file to 1. This change is necessary. Otherwise, every new session request will spawn a new Apache process and the load balancer plug-in will be initialized resulting in requests landing in the same instance. Restart the Apache server. Once we have applied these steps to the Apache web server, it is ready to work as a load balancer for our GlassFish cluster. As we discussed earlier, the essential configuration file for the load balancer plug-in is loadbalancer.xml. This file captures the essential information about the server instances being load balanced, and the load distribution configuration. This information is actually generated on the GlassFish Server, and then transferred to the web server. In the next section, let's discuss how we can configure the load balancer information on GlassFish. Configuring GlassFish for load balancing Once the web server has been configured, we can define a GlassFish load balancer configuration. This can be done using the Admin Console, or the create-http-lb command of the asadmin CLI utility. To create a load balancer configuration using the Admin Console, click the HTTP Load Balancer node in the navigational panel, and then click New in the content panel. The following screenshot shows the input form for creating a load balancer configuration. The important input parameters for the load balancer configuration are explained as follows: Name: A unique name of the new load balancer configuration. All instances: Where all the server instances of the selected target will be load balanced. All applications: Whether all the applications deployed to the target will be load balanced. Device host and admin port: The load balancing device's server information. GlassFish can rely on this information to automatically push the new load balancer configuration information to the device. For software load balancers, the device is the server that runs the load balancing software. The admin port is the port through which administration tasks can be performed on the load balancing device. The port must be SSL enabled. If the device requires authentication, you should configure the device to support client certificate authentication. The information is used purely for pushing the load balancer configuration. Therefore, if you have a different mechanism to transfer the information, the device host and admin port values are not important, even though they are necessary. Automatically apply changes: Whether GlassFish pushes the new load balancer configuration information immediately to the device. Targets: The clusters and server instances that will participate in the load balancing. Once the load balancer configuration is created, we can modify the settings for the load balancer, including the following parameters: Response timeout: Time in seconds within which a server instance must return a response. If no response is received within the time period, the server is considered unhealthy. The default is 60. HTTPS routing: Whether HTTPS requests to the load balancer result in HTTPS or HTTP requests to the server instance. For more information, see Configuring HTTPS Routing. Reload pool interval: Interval between checks for changes to the load balancer configuration file loadbalancer.xml. When the check detects changes, the configuration file is reloaded. A value of 0 disables reloading. Monitoring: Whether monitoring is enabled for the load balancer. Route cookie: Whether to use cookie to store the session routing information. Name of the cookie the load balancer plug-in uses to record the route information. Target: Target for the load balancer configuration. If you specify a target, it is the same as adding a reference to it. Targets can be clusters or stand-alone instances. In addition, we can configure the load balancing algorithm, and the health checker of the load balance plug-in. By default, the load balancer uses simple round-robin mechanism to distribute the load across server instances. The load balancer plug-in also supports a weighted round robin algorithm; it allows us to favor certain instances based on their relative weights. If neither algorithm satisfies the requirement, we can develop a custom algorithm. By default, the health checker of the load balancer plugin uses a specified URL to check all unhealthy GlassFish instances, and determines if they have returned to the healthy state. If the health checker finds that an unhealthy instance has become healthy, that instance is added to the list of healthy instances, and the load balancer will distribute load to it. To configure the health checker, click the Target tab of the load balancer configuration form, and click the Edit Health Check link of a specific target. The load balancing algorithm and health checker configuration form is shown in the following screenshot. If we click the Export tab in the load balancer editing form, we get the options to either export the load balancer configuration as loadbalancer.xml file. This file can be copied to the load balancer host, which effectively updates the load balancer information. We can also click Apply Changes Now to push the configuration, provided that the load balancer device is configured appropriately.
Read more
  • 0
  • 0
  • 4637

article-image-ajax-chat-implementation-part-1
Packt
28 Dec 2009
4 min read
Save for later

AJAX Chat Implementation: Part 1

Packt
28 Dec 2009
4 min read
Lets get started. We'll keep the application simple, modular, and extensible. We won't implement a login module, support for chat rooms, the online users list, and so on. By keeping it simple we'll focus on what the goal of this article is: posting and retrieving messages without causing any page reloads. We'll also let the user pick a color for her or his messages, because this involves an AJAX mechanism that is another good exercise. The chat application can be tested online at http://ajaxphp.packtpub.com, and should look like Figure 8-1: Figure 8-1: Online chat application built with AJAX and jQuery Using jQuery as a framework will simplify things: we won't need to worry about constructing XmlHttpRequest by ourselves and implementing design patterns and best practices. Technically, the application is split into two smaller applications that build the final solution: The chat application: Here we use a MySql database and AJAX to store and retrieve the users' messages and pass them between the client and the server. The code for choosing a text color: Here we use AJAX to call the PHP script that can tell us which text color was chosen by the user from the color palette. We use an image containing the entire spectrum of colors and allow the user choose any color for the text he or she writes. When the user clicks on the palette, the mouse coordinates are sent to the server, which obtain the color code, store it in the user's DB entry, and set the user's test to that color. The chat application Here we use a MySql database and AJAX to store and retrieve the users' messages and pass them between the client and the server. The chat window contacts the server periodically to send and retrieve the newest posted messages from the server to each user. Our DB will also hold username and text color information used in the application. Implementing this functionality involves creating the files and structures shown in the following figure: Figure 8-2: The components of the AJAX Chat application The application functions following our usual coding pattern as follows: The user interface is generated by index.html, which displays the chat box and the color picker. This file loads the other client-side files, which in our case are chat.js (our JavaScript chat class), jQuery-1.3.2.js (the jQuery framework), chat.css, and palette.png (the color picker image). On the server side, the main player is chat.php, which is designed to take requests from the client. In our case, client-server communication will happen between chat.js (on the client) and chat.php (on the server). The chat.php script uses three other files—config.php, error_handler.php and chat.class.php; we'll pay special attention to the latter, which is more complex and more interesting than the others. The other server-side file that listens to client requests is color.php, which is called whenever the user clicks the color palette image. When that happens, the client script calls color.php, tells it the location the user clicked on the palette, and color.php replies by telling the color at that location. You'll also need to create a new data table named chat (refer to the following figure), which holds the chat messages exchanged by the chatters. The files to which we're paying a little attention before starting to code are chat.js and chat.class.php. The chat.class.php file contains a server-side class named Chat which includes all the server-side functionality required to manipulate chat messages, as you can see in its diagram in Figure 8-3. This class contains methods for adding, deleting, and retrieving chat messages to and from the chat database table. Figure 8-3: Server-side Chat class Then we have the Chat class in the chat.js file. This is a JavaScript class that contains the client-side functionality required for our chatting application, which include functions for retrieving the list of messages from the server, sending new messages, deleting messages, displaying error messages, and so on. Most of the features are backed up by the server-side components, which are called to perform the necessary work. Figure 8-4: Client-side Chat class
Read more
  • 0
  • 0
  • 4782
Modal Close icon
Modal Close icon