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

How-To Tutorials

7019 Articles
article-image-php-data-objects-error-handling
Packt
22 Oct 2009
11 min read
Save for later

PHP Data Objects: Error Handling

Packt
22 Oct 2009
11 min read
In this article, we will extend our application so that we can edit existing records as well as add new records. As we will deal with user input supplied via web forms, we have to take care of its validation. Also, we may add error handling so that we can react to non-standard situations and present the user with a friendly message. Before we proceed, let's briefly examine the sources of errors mentioned above and see what error handling strategy should be applied in each case. Our error handling strategy will use exceptions, so you should be familiar with them. If you are not, you can refer to Appendix A, which will introduce you to the new object-oriented features of PHP5. We have consciously chosen to use exceptions, even though PDO can be instructed not to use them, because there is one situation where they cannot be avoided. The PDO constructors always throw an exception when the database object cannot be created, so we may as well use exceptions as our main error‑trapping method throughout the code. Sources of Errors To create an error handling strategy, we should first analyze where errors can happen. Errors can happen on every call to the database, and although this is rather unlikely, we will look at this scenario. But before doing so, let's check each of the possible error sources and define a strategy for dealing with them. This can happen on a really busy server, which cannot handle any more incoming connections. For example, there may be a lengthy update running in the background. The outcome is that we are unable to get any data from the database, so we should do the following. If the PDO constructor fails, we present a page displaying a message, which says that the user's request could not be fulfilled at this time and that they should try again later. Of course, we should also log this error because it may require immediate attention. (A good idea would be emailing the database administrator about the error.) The problem with this error is that, while it usually manifests itself before a connection is established with the database (in a call to PDO constructor), there is a small risk that it can happen after the connection has been established (on a call to a method of the PDO or PDO Statement object when the database server is being shutdown). In this case, our reaction will be the same—present the user with an error message asking them to try again later. Improper Configuration of the Application This error can only occur when we move the application across servers where database access details differ; this may be when we are uploading from a development server to production server, where database setups differ. This is not an error that can happen during normal execution of the application, but care should be taken while uploading as this may interrupt the site's operation. If this error occurs, we can display another error message like: "This site is under maintenance". In this scenario, the site maintainer should react immediately, as without correcting, the connection string the application cannot normally operate. Improper Validation of User Input This is an error which is closely related to SQL injection vulnerability. Every developer of database-driven applications must undertake proper measures to validate and filter all user inputs. This error may lead to two major consequences: Either the query will fail due to malformed SQL (so that nothing particularly bad happens), or an SQL injection may occur and application security may be compromised. While their consequences differ, both these problems can be prevented in the same way. Let's consider the following scenario. We accept some numeric value from a form and insert it into the database. To keep our example simple, assume that we want to update a book's year of publication. To achieve this, we can create a form that has two fields: A hidden field containing the book's ID, and a text field to enter the year. We will skip implementation details here, and see how using a poorly designed script to process this form could lead to errors and put the whole system at risk. The form processing script will examine two request variables:$_REQUEST['book'], which holds the book's ID and $_REQUEST['year'], which holds the year of publication. If there is no validation of these values, the final code will look similar to this: $book = $_REQUEST['book'];$year = $_REQUEST['year'];$sql = "UPDATE books SET year=$year WHERE id=$book";$conn->query($sql); Let's see what happens if the user leaves the book field empty. The final SQL would then look like: UPDATE books SET year= WHERE id=1; This SQL is malformed and will lead to a syntax error. Therefore, we should ensure that both variables are holding numeric values. If they don't, we should redisplay the form with an error message. Now, let's see how an attacker might exploit this to delete the contents of the entire table. To achieve this, they could just enter the following into the year field: 2007; DELETE FROM books; This turns a single query into three queries: UPDATE books SET year=2007; DELETE FROM books; WHERE book=1; Of course, the third query is malformed, but the first and second will execute, and the database server will report an error. To counter this problem, we could use simple validation to ensure that the year field contains four digits. However, if we have text fields, which can contain arbitrary characters, the field's values must be escaped prior to creating the SQL. Inserting a Record with a Duplicate Primary Key or Unique Index Value This problem may happen when the application is inserting a record with duplicate values for the primary key or a unique index. For example, in our database of authors and books, we might want to prevent the user from entering the same book twice by mistake. To do this, we can create a unique index of the ISBN column of the books table. As every book has a unique ISBN, any attempt to insert the same ISBN will generate an error. We can trap this error and react accordingly, by displaying an error message asking the user to correct the ISBN or cancel its addition. Syntax Errors in SQL Statements This error may occur if we haven't properly tested the application. A good application must not contain these errors, and it is the responsibility of the development team to test every possible situation and check that every SQL statement performs without syntax errors. If this type of an error occurs, then we trap it with exceptions and display a fatal error message. The developers must correct the situation at once. Now that we have learned a bit about possible sources of errors, let's examine how PDO handles errors. Types of Error Handling in PDO By default, PDO uses the silent error handling mode. This means that any error that arises when calling methods of the PDO or PDOStatement classes go unreported. With this mode, one would have to call PDO::errorInfo(), PDO::errorCode(), PDOStatement::errorInfo(), or PDOStatement::errorCode(), every time an error occurred to see if it really did occur. Note that this mode is similar to traditional database access—usually, the code calls mysql_errno(),and mysql_error() (or equivalent functions for other database systems) after calling functions that could cause an error, after connecting to a database and after issuing a query. Another mode is the warning mode. Here, PDO will act identical to the traditional database access. Any error that happens during communication with the database would raise an E_WARNING error. Depending on the configuration, an error message could be displayed or logged into a file. Finally, PDO introduces a modern way of handling database connection errors—by using exceptions. Every failed call to any of the PDO or PDOStatement methods will throw an exception. As we have previously noted, PDO uses the silent mode, by default. To switch to a desired error handling mode, we have to specify it by calling PDO::setAttribute() method. Each of the error handling modes is specified by the following constants, which are defined in the PDO class: PDO::ERRMODE_SILENT – the silent strategy. PDO::ERRMODE_WARNING – the warning strategy. PDO::ERRMODE_EXCEPTION – use exceptions. To set the desired error handling mode, we have to set the PDO::ATTR_ERRMODE attribute in the following way: $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); To see how PDO throws an exception, edit the common.inc.php file by adding the above statement after the line #46. If you want to test what will happen when PDO throws an exception, change the connection string to specify a nonexistent database. Now point your browser to the books listing page. You should see an output similar to: This is PHP's default reaction to uncaught exceptions—they are regarded as fatal errors and program execution stops. The error message reveals the class of the exception, PDOException, the error description, and some debug information, including name and line number of the statement that threw the exception. Note that if you want to test SQLite, specifying a non-existent database may not work as the database will get created if it does not exist already. To see that it does work for SQLite, change the $connStr variable on line 10 so that there is an illegal character in the database name: $connStr = 'sqlite:/path/to/pdo*.db'; Refresh your browser and you should see something like this: As you can see, a message similar to the previous example is displayed, specifying the cause and the location of the error in the source code. Defining an Error Handling Function If we know that a certain statement or block of code can throw an exception, we should wrap that code within the try…catch block to prevent the default error message being displayed and present a user-friendly error page. But before we proceed, let's create a function that will render an error message and exit the application. As we will be calling it from different script files, the best place for this function is, of course, the common.inc.php file. Our function, called showError(), will do the following: Render a heading saying "Error". Render the error message. We will escape the text with the htmlspecialchars() function and process it with the nl2br() function so that we can display multi-line messages. (This function will convert all line break characters to tags.) Call the showFooter() function to close the opening and tags. The function will assume that the application has already called the showHeader() function. (Otherwise, we will end up with broken HTML.) We will also have to modify the block that creates the connection object in common.inc.php to catch the possible exception. With all these changes, the new version of common.inc.php will look like this: <?php/*** This is a common include file* PDO Library Management example application* @author Dennis Popel*/// DB connection string and username/password$connStr = 'mysql:host=localhost;dbname=pdo';$user = 'root';$pass = 'root';/*** This function will render the header on every page,* including the opening html tag,* the head section and the opening body tag.* It should be called before any output of the/*** This function will 'close' the body and html* tags opened by the showHeader() function*/function showFooter(){?></body></html><?php}/*** This function will display an error message, call the* showFooter() function and terminate the application* @param string $message the error message*/function showError($message){echo "<h2>Error</h2>";echo nl2br(htmlspecialchars($message));showFooter();exit();}// Create the connection objecttry{$conn = new PDO($connStr, $user, $pass);$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch(PDOException $e){showHeader('Error');showError("Sorry, an error has occurred. Please try your requestlatern" . $e->getMessage());} As you can see, the newly created function is pretty straightforward. The more interesting part is the try…catch block that we use to trap the exception. Now with these modifications we can test how a real exception will get processed. To do that, make sure your connection string is wrong (so that it specifies wrong databasename for MySQL or contains invalid file name for SQLite). Point your browser to books.php and you should see the following window:
Read more
  • 0
  • 0
  • 6809

article-image-seam-and-ajax
Packt
22 Oct 2009
11 min read
Save for later

Seam and AJAX

Packt
22 Oct 2009
11 min read
What is AJAX? AJAX (Asynchronous JavaScript and XML) is a technique rather than a new technology for developing highly interactive web applications. Traditionally, when JavaScript is written, it uses the browser's XMLHttp DOM API class to make asynchronous calls to a server-side component, for example, servlets. The server-side component generates a resulting XML package and returns this to the client browser, which can then update the browser page without having to re-render the entire page. The result of using AJAX technologies (many different technologies can be used to develop AJAX functionality, for example, PHP, Microsoft .NET, Servlets, and Seam) is to provide an appearance similar to a desktop, for web applications. AJAX and the Seam Framework The Seam Framework provides built-in support for AJAX via its direct integration with libraries such as RichFaces and AJAX4JSF. Discussing the AJAX support of RichFaces and AJAX4JSF could fill an entire book, if not two books, so we'll discuss these technologies briefly, towards the end of this article, where we'll give an overview of how they can be used in a Seam application. However, Seam provides a separate technology called Seam Remoting that we'll discuss in detail in this article. Seam Remoting allows a method on Seam components to be executed directly from JavaScript code running within a browser, allowing us to easily build AJAX-style applications. Seam Remoting uses annotations and is conversation-aware, so that we still get all of the benefits of writing conversationally-aware components, except that we can now access them via JavaScript as well as through other view technologies, such as Facelets. Seam Remoting provides a ready-to-use framework, making AJAX applications easier to develop. For example, it provides debugging facilities and logging facilities similar to the ones that we use everyday when writing Java components. Configuring Seam applications for Seam Remoting To use Seam Remoting, we need to configure the Seam web application to support JavaScript code that is making asynchronous calls to the server back end. In a traditional servlet-based system this would require writing complex servlets that could read, parse, and return XML as part of an HTTP GET or POST request. With Seam Remoting, we don't need to worry about managing XML data and its transport mechanism. We don't even need to worry about writing servlets that can handle the communication for us—all of this is a part of the framework. To configure a web application to use Seam Remoting, all we need to do is declare the Seam Resource servlet within our application's WEB-INF/web.xml file. We do this as follows. <servlet> <servlet-name>Seam Resource Servlet</servlet-name> <servlet-class> org.jboss.seam.servlet.SeamResourceServlet </servlet-class></servlet><servlet-mapping> <servlet-name>Seam Resource Servlet</servlet-name> <url-pattern>/seam/resource/*</url-pattern></servlet-mapping> That's all we need to do to make a Seam web application work with Seam Remoting. To make things even easier, this configuration is automatically done when applications are created with SeamGen, so you would have to worry about this configuration only if you are using non-SeamGen created projects. Configuring Seam Remoting server side To declare that a Seam component can be used via Seam Remoting, the methods that are to be exposed need to be annotated with the @WebRemote annotation. For simple POJO components, this annotation is applied directly on the POJO itself, as shown in the following code snippet. @Name("helloWorld")public class HelloWorld implements HelloWorldAction { @WebRemote public String sayHello() { return "Hello world !!";} For Session Beans, the annotation must be applied on the Session Beans business interface rather than on the implementation class itself. A Session Bean interface would be declared as follows. import javax.ejb.Local;import org.jboss.seam.annotations.remoting.WebRemote;@Localpublic interface HelloWorldAction { @WebRemote public String sayHello(); @WebRemote public String sayHelloWithArgs(String name);} The implementation class is defined as follows: import javax.ejb.Stateless;import org.jboss.seam.annotations.Name;@Stateless@Name("helloWorld")public class HelloWorld implements HelloWorldAction { public String sayHello() { return "Hello world !!"; } public String sayHelloWithArgs(String name) { return "Hello "+name; }} Note that, to make a method available to Seam Remoting, all we need to do is to annotate the method with @WebRemote and then import the relevant class. As we can see in the preceding code, it doesn't matter how many parameters our methods take. Configuring Seam Remoting client side In the previous sections, we've seen that minimal configuration is required to enable Seam Remoting and to declare Seam components as Remoting-aware. Similarly in this section, we'll see that minimal work is required within a Facelets file to enable Remoting. The Seam Framework provides built-in JavaScript to enable Seam Remoting. To use this JavaScript, we first need to define it within a Facelets file in the following way: <script type="text/javascript" src="/HelloWorld/seam/resource/ remoting/resource/remote.js"></script><script type="text/javascript" src="/HelloWorld/seam/resource/ remoting/interface.js?helloWorld"> To include the relevant JavaScript into a Facelets page, we need to import the /seam/resource/remoting/resource/remote.js and /seam/resource/remoting/interface.js JavaScript files. These files are served via the Seam resource servlet that we defined earlier in this article. You can see that the interface.js file takes an argument defining the name of the Seam component that we will be accessing (this is the name of the component for which we have defined methods with the @WebRemote annotation). If we wish to use two or more different Seam components from a Remoting interface, we would specify their names as parameters to the interface.js file separated by using an "&", for example: <script type="text/javascript" src="/HelloWorld/seam/resource/ remoting/interface.js?helloWorld&mySecondComponent& myThirdComponent"> To specify that we will use Seam components from the web tier is straight-forward, however, the Seam tag library makes this even easier. Instead of specifying the JavaScript shown in the preceding examples, we can simply insert the <s:remote /> tag into Facelets, passing the name of the Seam component to use within the include parameter. <ui:compositiontemplate="layout/template.xhtml"> <ui:define name="body"> <h1>Hello World</h1> <s:remote include="helloWorld"/> To use the <s:remote /> tag, we need to import the Seam tag library, as shown in this example. When the web page is rendered, Seam will automatically generate the relevant JavaScript. If we are using the <s:remote /> tag and we want to invoke methods on multiple Seam components, we need to place the component names as comma-separated values within the include parameter of the tag instead, for example: <s:remote include="helloWorld, mySecondComponent, myThirdComponent" /> Invoking Seam components via Remoting Now that we have configured our web application, defined the services to be exposed from the server, and imported the JavaScript to perform the AJAX calls, we can execute our remote methods. To get an instance of a Seam component within JavaScript, we use the Seam.Component.getInstance() method. This method takes one parameter, which specifies the name of the Seam component that we wish to interact with. Seam.Component.getInstance("helloWorld") This method returns a reference to Seam Remoting JavaScript to allow our exposed @WebReference methods to be invoked. When invoking a method via JavaScript, we must specify any arguments to the method (possibly there will be none) and a callback function. The callback function will be invoked asynchronously when the server component's method has finished executing. Within the callback function we can perform any JavaScript processing (such as DOM processing) to give our required AJAX-style functionality. For example, to execute a simple Hello World client, passing no parameters to the server, we could define the following code within a Facelets file. <ui:define name="body"> <h1>Hello World</h1> <s:remote include="helloWorld"/> <p> <button onclick="javascript:sayHello()">Say Hello</button> </p> <p> <div id="helloResult"></div> </p> <script type="text/javascript"> function sayHello() { var callback = function(result) { document.getElementById("helloResult").innerHTML=result; }; Seam.Component.getInstance("helloWorld"). sayHello(callback); } </script></ui:define> Let's take a look at this code, one piece at a time, to see exactly what is happening. <s:remote include="helloWorld"/> <p> <button onclick="javascript:sayHello()">Say Hello</button> </p> In this part of the code, we have specified that we want to invoke methods on the helloWorld Seam component by using the <s:remote /> tag. We've then declared a button and specified that the sayHello() JavaScript method will be invoked when the button is clicked. <div id="helloResult"></div> Next we've defined an empty <div /> called helloResult. This <div /> will be populated via the JavaScript DOM API with the results from out server side method invocation. <script type="text/javascript"> function sayHello() { var callback = function(result) { document.getElementById("helloResult").innerHTML=result; }; Seam.Component.getInstance("helloWorld"). sayHello(callback); }</script> Next, we've defined our JavaScript function sayHello(), which is invoked when the button is clicked. This method declares a callback function that takes one parameter. The JavaScript DOM API uses this parameter to set the contents of the helloResult <div /> that we have defined earlier. So far, everything that we've done here has been simple JavaScript and hasn't used any Seam APIs. Finally, we invoke the Seam component using the Seam.Component.getInstance().sayHello() method, passing the callback function as the final parameter. When we open the page, the following flow of events occurs: The page is displayed with appropriate JavaScript created via the<s:remote /> tag. The user clicks on the button. The Seam JavaScript is invoked, which causes the sayHello() method on the helloWorld component to be invoked. The server side component completes execution, causing the JavaScript callback function to be invoked. The JavaScript DOM API uses the results from the server method to change the contents of the <div /> in the browser, without causing the entire page to be refreshed. This process shows how we've developed some AJAX functionality by writing a minimal amount of JavaScript, but more importantly, by not dealing with XML or the JavaScript XMLHttp class. The preceding code shows how we can easily invoke server side methods without passing any parameters. This code can easily be expanded to pass parameters, as shown in the following code snippet: <s:remote include="helloWorld"/><p> <button onclick="javascript:sayHelloWithArgs()"> Say Hello with Args </button></p><p> <div id="helloResult"></div></p><script type="text/javascript"> function sayHelloWithArgs() { var name = "David"; var callback = function(result) { document.getElementById("helloResult").innerHTML=result; }; Seam.Component.getInstance("helloWorld"). sayHelloWithArgs(name, callback); }</script> The preceding code shows that the process for invoking remote methods with parameters is similar to the process for invoking remote methods with no parameters. The important point to note is that the callback function is specified as the last parameter. When our simple application is run, we get the following screenshot. Clicking on either of the buttons on the page causes our AJAX code to be executed, and the text of the <div /> component to be changed. If we want to invoke a server side method via Seam Remoting and we want the method to be invoked as a part of a Seam conversation, we can use the Seam.Remoting.getcontext.setConversationId() method to set the conversation ID. This ID will then by used by the Seam Framework to ensure that the AJAX request is a part of the appropriate conversation. Seam.Remoting.getContext().setConversationId(#{conversation.id});
Read more
  • 0
  • 0
  • 2556

article-image-consuming-adapter-outside-biztalk-server
Packt
22 Oct 2009
3 min read
Save for later

Consuming the Adapter from outside BizTalk Server

Packt
22 Oct 2009
3 min read
In addition to infrastructure-related updates such as the aforementioned platform modernization, Windows Server 2008 Hyper-V virtualization support, and additional options for fail over clustering, BizTalk Server also includes new core functionality. You will find better EDI and AS2 capabilities for B2B situations and a new platform for mobile development of RFID solutions. One of the benefits of the new WCF SQL Server Adapter that I mentioned earlier was the capability to use this adapter outside of a BizTalk Server solution. Let's take a brief look at three options for using this adapter by itself and without BizTalk as a client or service. Called directly via WCF service reference If your service resides on a machine where the WCF SQL Server Adapter (and thus, the sqlBinding) is installed, then you may actually add a reference directly to the adapter endpoint. I have a command-line application, which serves as my service client. If we right-click this application, and have the WCF LOB Adapter SDK installed, then Add Adapter Service Reference appears as an option. Choosing this option opens our now-beloved wizard for browsing adapter metadata. As before, we add the necessary connection string details and browse the BatchMaster table and opt for the Select operation. Unlike the version of this wizard that opens for BizTalk Server projects, notice the Advanced options button at the bottom. This button opens a property window that lets us select a variety of options such as asynchronous messaging support and suppression of an accompanying configuration file. After the wizard is closed, we end up with a new endpoint and binding in our existing configuration file, and a .NET class containing the data and service contracts necessary to consume the service. We should now call this service as if we were calling any typical WCF service. Because the auto-generated namespace for the data type definition is a bit long, I first added an alias to that namespace. Next, I have a routine, which builds up the query message, executes the service, and prints a subset of the response. using DirectReference = schemas.microsoft.com.Sql._2008._05.Types.Tables.dbo; … private static void CallReferencedSqlAdapterService() { Console.WriteLine("Calling referenced adapter service");TableOp_dbo_BatchMasterClient client = new TableOp_dbo_BatchMasterClient("SqlAdapterBinding_TableOp_dbo_BatchMaster"); try{string columnString = "*";string queryString = "WHERE BatchID = 1";DirectReference.BatchMaster[] batchResult =client.Select(columnString, queryString);Console.WriteLine("Batch results ...");Console.WriteLine("Batch ID: " + batchResult[0].BatchID.ToString());Console.WriteLine("Product: " + batchResult[0].ProductName);Console.WriteLine("Manufacturing Stage: " + batchResult[0].ManufStage);client.Close(); Console.ReadLine(); } catch (System.ServiceModel.CommunicationException){client.Abort(); } catch (System.TimeoutException) { client.Abort(); } catch (System.Exception) { client.Abort(); throw; } } Once this quick block of code is executed, I can confirm that my database is accessed and my expected result set returned.
Read more
  • 0
  • 0
  • 1899

article-image-building-jsfejb3-applications
Packt
22 Oct 2009
15 min read
Save for later

Building JSF/EJB3 Applications

Packt
22 Oct 2009
15 min read
Building JSF/EJB3 Applications This practical article shows you how to create a simple data-driven application using JSF and EJB3 technologies. The article also shows you how to effectively use NetBeans IDE when building enterprise applications. What We Are Going to Build The sample application we are building throughout the article is very straightforward. It offers just a few pages. When you click the Ask us a question link on the welcomeJSF.jsp page, you will be taken to the following page, on which you can submit a question:     Once you’re done with your question, you click the Submit button. As a result, the application persist your question along with your email in the database. The next page will look like this:     The web tier of the application is build using the JavaServer Faces technology, while EJB is used to implement the database-related code. Software You Need to Follow the Article Exercise To build the sample discussed here, you will need the following software components installed on your computer: Java Standard Development Kit (JDK) 5.0 or higher Sun Java System Application Server Platform Edition 9 MySQL NetBeans IDE 5.5 Setting Up the Database The first step in building our application is to set up the database to interact with. In fact, you could choose any database you like to be the application’s backend database. For the purpose of this article, though, we will discuss how to use MySQL. To keep things simple, let’s create a questions table that contains just three columns, outlined in the following table: Column Type Description trackno INTEGER AUTO_INCREMENT PRIMARY KEY Stores a track number generated automatically when a row is inserted. user_email VARCHAR(50) NOT NULL   question VARCHAR(2000) NOT NULL   Of course, a real-world questions table would contain a few more columns, for example, dateOfSubmission containing the date and time of submitting the question. To create the questions table, you first have to create a database and grant the required privileges to the user with which you are going to connect to that database. For example, you might create database my_db and user usr identified by password pswd. To do this, you should issue the following SQL commands from MySQL Command Line Client:   CREATE DATABASE my_db; GRANT CREATE, DROP, SELECT, INSERT, UPDATE, DELETE ON my_db.* TO 'usr'@'localhost' IDENTIFIED BY 'pswd'; In order to use the newly created database for subsequent statements, you should issue the following statement:   USE my_db   Finally, create the questions table in the database as follows:   CREATE TABLE questions(      trackno INTEGER AUTO_INCREMENT PRIMARY KEY,      user_email VARCHAR(50) NOT NULL,      question  VARCHAR(2000) NOT NULL ) ENGINE = InnoDB;     Once you’re done, you have the database with the questions table required to store incoming users’ questions. Setting Up a Data Source for Your MySQL Database Since the application we are going to build will interact with MySQL, you need to have installed an appropriate MySQL driver on your application server. For example, you might want to install MySQL Connector/J, which is the official JDBC driver for MySQL. You can pick up this software from the "downloads" page of the MySQL AB website at http://mysql.org/downloads/. Install the driver on your GlassFish application server as follows: Unpack the downloaded archive containing the driver to any directory on your machine Add mysql-connector-java-xxx-bin.jar to the CLASSPATH environment variable Make sure that your GlassFish application server is up and running Launch the Application Server Admin Console by pointing your browser at http://localhost:4848/ Within the Common Tasks frame, find and double-click the ResourcesJDBCNew Connection Pool node On the New Connection Pool page, click the New… button The first step of the New Connection Pool master, set the fields as shown in the following table: Setting Value Name jdbc/mysqlPool Resource type javax.sql.DataSource Database Vendor mysql   Click Next to move on to the second page of the master On the second page of New Connection Pool, set the properties to reflect your database settings, like that shown in the following table: Name Value databaseName my_db serverName localhost port 3306 user usr password pswd   Once you are done with setting the properties, click Finish. The newly created jdbc/mysqlPool connection pool should appear on the list. To check it, you should click its link to open it in a window, and then click the Ping button. If everything is okay, you should see a message telling you Ping succeeded Creating the Project The next step is to create an application project with NetBeans. To do this, follow the steps below: Choose File/New project and then choose the EnterpriseEnterprise Application template for the project. Click Next On the Name and Location page of the master, specify the name for the project: JSF_EJB_App. Also make sure that Create EJB Module and Create Web Application Module are checked. And click Finish As a result, NetBeans generates a new enterprise application in a standard project, containing actually two projects: an EJB module project and Web application project. In this particular example, you will use the first project for EJBs and the second one for JSF pages. Creating Entity Beans and Persistent Unit You create entity beans and the persistent unit in the EJB module project—in this example this is the JSF_EJB_App-ejb project. In fact, the sample discussed here will contain the only entity bean: Question. You might automatically generate it and then edit as needed. To generate it with NetBeans, follow the steps below: Make sure that your Sun Java System Application Server is up and running In the Project window, right click JSF_EJB_App-ejb project, and then choose New/Entity Classes From Database. As a result, you’ll be prompted to connect to your Sun Java System Application Server. Do it by entering appropriate credentials. In the New Entity Classes from Database window, select jdbc/mysqlPool from the Data Source combobox. If you recall from the Setting up a Data Source for your MySQL database section discussed earlier in this article, jdbc/mysqlPool is a JDBC connection pool created on your application server In the Connect dialog appeared, you’ll be prompted to connect to your MySQL database. Enter password pswd, set the Remember password during this session checkbox, and then click OK In the Available Tables listbox, choose questions, and click Add button to move it to the Selected Tables listbox. After that, click Next On the next page of the New Entity Classes from Database master, fill up the Package field. For example, you might choose the following name: myappejb.entities. And change the class name from Questions to Question in the Class Names box. Next, click the Create Persistent Unit button In the Create Persistent Unit window, just click the Create button, leaving default values of the fields In the New Entity Classes from Database dialog, click Finish As a result, NetBeans will generate the Question entity class, which you should edit so that the resultant class looks like the following:   package myappejb.entities; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "questions") public class Question implements Serializable { @Id @Column(name = "trackno") private Integer trackno; @Column(name = "user_email", nullable = false) private String userEmail; @Column(name = "question", nullable = false) private String question; public Question() { } public Integer getTrackno() { return this.trackno; } public void setTrackno(Integer trackno) { this.trackno = trackno; } public String getUserEmail() { return this.userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public String getQuestion() { return this.question; } public void setQuestion(String question) { this.question = question; } }     Once you’re done, make sure to save all the changes made by choosing File/Save All. Having the above code in hand, you might of course do without first generating the Question entity from the database, but simply create an empty Java file in the myappejb.entities package, and then insert the above code there. Then you could separately create the persistent unit. However, the idea behind building the Question entity with the master here is to show how you can quickly get a required piece of code to be then edited as needed, rather than creating it from scratch. Creating Session Beans To finish with the JSF_EJB_App-ejb project, let’s proceed to creating the session bean that will be used by the web tier. In particular, you need to create the QuestionSessionBean session bean that will be responsible for persisting the data a user enters on the askquestion page. To generate the bean’s frame with a master, follow the steps below: In the Project window, right click JSF_EJB_App-ejb project, and then choose New/Session Bean In the New Session Bean window, enter EJB name: QuestionSessionBean. Then specify the package: myappejb.ejb. Make sure that the Session Type is set to Stateless and Create Interface is set to Remote. Click Finish As a result, NetBeans should generate two Java files: QuestionSessionBean.java and QuestionSessionRemote.java. You should modify QuestionSessionBean.java so that it contains the following code:   package myappejb.ejb; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceUnit; import javax.transaction.UserTransaction; import myappejb.entities.Question; @Stateless <b>@TransactionManagement(TransactionManagementType.BEAN)</b> public class QuestionSessionBean implements myappejb.ejb.QuestionSessionRemote { /** Creates a new instance of QuestionSessionBean */ public QuestionSessionBean() { } @Resource private UserTransaction utx; @PersistenceUnit(unitName = "JSF_EJB_App-ejbPU") private EntityManagerFactory emf; private EntityManager getEntityManager() { return emf.createEntityManager(); } public void save(Question question) throws Exception { EntityManager em = getEntityManager(); try { utx.begin(); em.joinTransaction(); em.persist(question); utx.commit(); } catch (Exception ex) { try { utx.rollback(); throw new Exception(ex.getLocalizedMessage()); } catch (Exception e) { throw new Exception(e.getLocalizedMessage()); } } finally { em.close(); } } }   Next, modify the QuestionSessionRemote.java so that it looks like this:   package myappejb.ejb; import javax.ejb.Remote; import myappejb.entities.Question; @Remote public interface QuestionSessionRemote { void save(Question question) throws Exception; }   Choose File/Save All to save the changes made. That’s it. You just finished with your EJB module project. Adding JSF Framework to the Project Now that you have the entity and session beans created, let’s switch to the JSF_EJB_App-war project, where you’re building the web tier for the application.Before you can proceed to building JSF pages, you need to add the JavaServer Faces framework to the JSF_EJB_App-war project. To do this, follow the steps below: In the Project window, right click JSF_EJB_App-war project, and then choose Properties In the Project Properties window, select Frameworks from Categories, and click Add button. As a result, the Add a Framework dialog should appear In the Add a Framework dialog, choose JavaServer Faces and click OK Then click OK in the Project Properties dialog As a result, NetBeans adds the JavaServer Faces framework to the JSF_EJB_App-war project. Now if you extend the Configuration Files folder under the JSF_EJB_App-war project node in the Project window, you should see, among other configuration files, faces-config.xml there. Also notice the appearance of the welcomeJSF.jsp page in the Web Pages folder Creating JSF Managed Beans The next step is to create managed beans whose methods will be called from within the JSF pages. In this particular example, you need to create only one such bean: let’s call it QuestionController. This can be achieved by following the steps below: In the Project window, right click JSF_EJB_App-war project, and then choose New/Empty Java File In the New Empty Java File window, enter QuestionController as the class name and enter myappjsf.jsf in the Package field. Then, click Finish In the generated empty java file, insert the following code:   package myappjsf.jsf; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import myappejb.entities.Question; import myappejb.ejb.QuestionSessionBean; public class QuestionController { @EJB private QuestionSessionBean sbean; private Question question; public QuestionController() { } public Question getQuestion() { return question; } public void setQuestion(Question question) { this.question = question; } public String createSetup() { this.question = new Question(); this.question.setTrackno(null); return "question_create"; } public String create() { try { Integer trck = sbean.save(question); addSuccessMessage("Your question was successfully submitted."); } catch (Exception ex) { addErrorMessage(ex.getLocalizedMessage()); } return "created"; } public static void addErrorMessage(String msg) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg); FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage(null, facesMsg); } public static void addSuccessMessage(String msg) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg); FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage("successInfo", facesMsg); } }   Next, you need to add information about the newly created JSF managed bean to the faces-config.xml configuration file automatically generated when adding the JSF framework to the project. Find this file in the following folder: JSF_EJB_App-warWeb PagesWEB-INF in the Project window, and then insert the following tag between the and tags:   <managed-bean> <managed-bean-name>questionJSFBean</managed-bean-name> <managed-bean-class>myappjsf.jsf.QuestionController</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean>   Finally, make sure to choose File/Save All to save the changes made in faces-config.xml as well as in QuestionController.java. Creating JSF Pages To keep things simple, you create just one more JSF page: askquestion.jsp, where a user can submit a question. First, though, let’s modify the welcomeJSF.jsp page so that you can use it to move on to askquestion.jsp and then return to, once a question has been submitted. To achieve this, modify welcomeJSF.jsp as follows:   <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <f:view> <h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/> <h:form> <h1><h:outputText value="Ask us a question" /></h1> <h:commandLink action="#{questionJSFBean.createSetup}" value="New question"/> <br> </h:form> </f:view> </body> </html> Now you can move on and create askquestion.jsp. To do this, follow the steps below: In the Project window, right click JSF_EJB_App-war project, and then choose New/JSP In the New JSP File window, enter askquestion as the name for the page, and click Finish Modify the newly created askquestion.jsp so that it finally looks like this:   <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <html>     <head>         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />         <title>New Question</title>     </head>     <body>         <f:view>             <h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/>             <h1>Your question, please!</h1>             <h:form>                 <h:panelGrid columns="2">                     <h:outputText value="Your Email:"/>                     <h:inputText id="userEmail" value= "#{questionJSFBean.question.userEmail}" title="Your Email" />                     <h:outputText value="Your Question:"/>                     <h:inputTextarea id="question" value= "#{questionJSFBean.question.question}"  title="Your Question" rows ="5" cols="35" />                 </h:panelGrid>                 <h:commandLink action="#{questionJSFBean.create}" value="Create"/>                 <br>                 <a href="/JSF_EJB_App-war/index.jsp">Back to index</a>             </h:form>         </f:view>     </body> </html>   The next step is to set page navigation. Turning back to the faces-config.xml configuration file, insert the following code there.   <navigation-rule> <navigation-case> <from-outcome>question_create</from-outcome> <to-view-id>/askquestion.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <navigation-case> <from-outcome>created</from-outcome> <to-view-id>/welcomeJSF.jsp</to-view-id> </navigation-case> </navigation-rule> Make sure that the above tags are within the <faces-config> and </faces-config> root tags. Check It You are ready now to check the application you just created. To do this, right-click JSF_EJB_App-ejb project in the Project window and choose Deploy Project. After the JSF_EJB_App-ejb project is successfully deployed, right click the JSF_EJB_App-war project and choose Run Project. As a result, the newly created application will run in a browser. As mentioned earlier, the application contains very few pages, actually three ones. For testing purposes, you can submit a question, and then check the questions database table to make sure that everything went as planned. Summary Both JSF and EJB 3 are popular technologies when it comes to building enterprise applications. This simple example illustrates how you can use these technologies together in a complementary way.
Read more
  • 0
  • 0
  • 3251

article-image-soap-and-php-5
Packt
22 Oct 2009
16 min read
Save for later

SOAP and PHP 5

Packt
22 Oct 2009
16 min read
SOAP SOAP, formerly known as Simple Object Access Protocol (until the acronym was dropped in version 1.2), came around shortly after XML-RPC was released. It was created by a group of developers with backing from Microsoft. Interestingly, the creator of XML-RPC, David Winer, was also one of the primary contributors to SOAP. Winer released XML-RPC before SOAP, when it became apparent to him that though SOAP was still a way away from being completed, there was an immediate need for some sort of web service protocol. Like XML-RPC, SOAP is an XML-based web service protocol. SOAP, however, satisfies a lot of the shortcomings of XML-RPC: namely the lack of user-defined data types, better character set support, and rudimentary security. It is quite simply, a more powerful and flexible protocol than REST or XML-RPC. Unfortunately, sacrifices come with that power. SOAP is a much more complex and rigid protocol. For example, even though SOAP can stand alone, it is much more useful when you use another XML-based standard, called Web Services Descriptor Language (WSDL), in conjunction with it. Therefore, in order to be proficient with SOAP, you should also be proficient with WSDL. The most-levied criticism of SOAP is that it is overly complex. Indeed, SOAP is not simple. It is long and verbose. You need to know how namespaces work in XML. SOAP can rely heavily on other standards. This is true for most implementations of SOAP, including Microsoft Live Search, which we will be looking at. The most common external specifications used by a SOAP-based service is WSDL to describe its available services, and that, in turn, usually relies on XML Schema Data (XSD) to describe its data types. In order to "know" SOAP, it would be extremely useful to have some knowledge of WSDL and XSD. This will allow one to figure out how to use the majority of SOAP services. We are going to take a "need to know" approach when looking at SOAP. Microsoft Live Search's SOAP API uses WSDL and XSD, so we will take a look at SOAP with the other two in mind. We will limit our discussion on how to gather information about the web service that you, as a web service consumer, would need and how to write SOAP requests using PHP 5 against it. Even though this article will just introduce you to the core necessities of SOAP, there is a lot of information and detail. SOAP is very meticulous and you have to keep track of a fair amount of things. Do not be discouraged, take notes if you have to, and be patient. All three, SOAP, WSD, and XSD are maintained by the W3C. All three specifications are available for your perusal. The official SOAP specification is located at http://www.w3.org/TR/soap/. WSDL specification is located at http://www.w3.org/TR/wsdl. Finally, the recommended XSD specification can be found at http://www.w3.org/XML/Schema. Web Services Descriptor Language (WSDL) With XML Schema Data (XSD) Out of all the drawbacks of XML-RPC and REST, there is one that is prominent. Both of these protocols rely heavily on good documentation by the service provider in order to use them. Lacking this, you really do not know what operations are available to you, what parameters you need to pass in order to use them, and what you should expect to get back. Even worse, an XML-RPC or REST service may be poorly or inaccurately documented and give you inaccurate or unexpected results. SOAP addresses this by relying on another XML standard called WSDL to set the rules on which web service methods are available, how parameters should be passed, and what data type might be returned. A service's WSDL document, basically, is an XML version of the documentation. If a SOAP-based service is bound to a WSDL document, and most of them are, requests and responses must adhere to the rules set in the WSDL document, otherwise a fault will occur. WSDL is an acronym for a technical language. When referring to a specific web service's WSDL document, people commonly refer to the document as "the WSDL" even though that is grammatically incorrect. Being XML-based, this allows clients to automatically discover everything about the functionality of the web service. Human-readable documentation is technically not required for a SOAP service that uses a WSDL document, though it is still highly recommended. Let's take a look at the structure of a WSDL document and how we can use it to figure out what is available to us in a SOAP-based web service. Out of all three specifications that we're going to look at in relationship to SOAP, WSDL is the most ethereal. Both supporters and detractors often call writing WSDL documents a black art. As we go through this, I will stress the main points and just briefly note other uses or exceptions. Basic WSDL Structure Beginning with a root definitions element, WSDL documents follow this basic structure:     <definitions>        <types>        …        </types>        <message>        …        </message>        <portType>        …        </portType>        <binding>        …        </binding>    </definitions> As you can see, in addition to the definitions element, there are four main sections to a WSDL document: types, message, portType, and binding. Let's take a look at these in further detail. Google used to provide a SOAP service for their web search engine. However, this service is now deprecated, and no new developer API keys are given out. This is unfortunate because the service was simple enough to learn SOAP quickly, but complex enough to get a thorough exposure to SOAP. Luckily, the service itself is still working and the WSDL is still available. As we go through WSDL elements, we will look at the Google SOAP Search WSDL and Microsoft Live Search API WSDL documents for examples. These are available at http://api.google.com/GoogleSearch.wsdl and http://soap.search.msn.com/webservices.asmx?wsdl respectively. definitions Element This is the root element of a WSDL document. If the WSDL relies on other specifications, their namespace declarations would be made here. Let's take a look at Google's WSDL's definition tag:     <definitions name="GoogleSearch"        targetNamespace="urn:GoogleSearch"                                                > The more common ones you'll run across are xsd for schema namespace, wsdl for the WSDL framework itself, and soap and soapenc for SOAP bindings. As these namespaces refer to W3C standards, you will run across them regardless of the web service implementation. Note that some searches use an equally common prefix, xs, for XML Schema. tns is another common namespace. It means "this namespace" and is a convention used to refer to the WSDL itself. types Element In a WSDL document, data types used by requests and responses need to be explicitly declared and defined. The textbook answer that you'll find is that the types element is where this is done. In theory, this is true. In practice, this is mostly true. The types element is used only for special data types. To achieve platform neutrality, WSDL defaults to, and most implementations use, XSD to describe its data types. In XSD, many basic data types are already included and do not need to be declared. Common Built-in XSD Data Types Time Date Boolean String Base64Binary Float Double Integer Byte For a complete list, see the recommendation on XSD data types at http://www.w3.org/TR/xmlschema-2/. If the web service utilizes nothing more than these built-in data types, there is no need to have special data types, and thus, types will be empty. So, the data types will just be referred to later, when we define the parameters. There are three occasions where data types would be defined here: If you want a special data type that is based on a built-in data type. Most commonly this is a built-in, whose value is restricted in some way. These are known as simple types. If the data type is an object, it is known as a complex type in XSD, and must be declared. An array, which can be described as a hybrid of the former two. Let's take a look at some examples of what we will encounter in the types element. Simple Type Sometimes, you need to restrict or refine a value of a built-in data type. For example, in a hospital's patient database, it would be ludicrous to have the length of a field called Age to be more than three digits. To add such a restriction in the SOAP world, you would have to define Age here in the types section as a new type. Simple types must be based on an existing built-in type. They cannot have children or properties like complex types. Generally, a simple type is defined with the simpleType element, the name as an attribute, followed by the restriction or definition. If the simple type is a restriction, the built-in data type that it is based on, is defined in the base attribute of the restriction element. For example, a restriction for an age can look like this:     <xsd:simpleType name="Age">        <xsd:restriction base="xsd:integer">            <xsd:totalDigits value="3" />        </xsd:restriction>    </xsd:simpleType> Children elements of restriction define what is acceptable for the value. totalDigits is used to restrict a value based on the character length. A table of common restrictions follows: Restriction Use Applicable In enumeration Specifies a list of acceptable values. All except boolean fractionDigits Defines the number of decimal places allowed. Integers length Defines the exact number of characters allowed. Strings and all binaries maxExclusive/ maxInclusive Defines the maximum value allowed. If Exclusive is used, value cannot be equal to the definition. If Inclusive, can be equal to, but not greater than, this definition. All numeric and dates minLength/ maxLength Defines the minimum and maximum number of characters or list items allowed. Strings and all binaries minExclusive/ minInclusive Defines the minimum value allowed. If Exclusive is used, value cannot be equal to the definition. If Inclusive, can be equal to, but not less than, this definition. All numeric and dates pattern A regular expression defining the allowed values. All totalDigits Defines the maximum number of digits allowed. Integers whiteSpace Defines how tabs, spaces, and line breaks are handled. Can be preserve (no changes), replace (tabs and line breaks are converted to spaces) or collapse (multiple spaces, tabs, and line breaks are converted to one space. Strings and all binaries A practical example of a restriction can be found in the MSN Search Web Service WSDL. Look at the section that defines SafeSearchOptions.     <xsd:simpleType name="SafeSearchOptions">        <xsd:restriction base="xsd:string">            <xsd:enumeration value="Moderate" />            <xsd:enumeration value="Strict" />            <xsd:enumeration value="Off" />    </xsd:restriction> </xsd:simpleType> In this example, the SafeSearchOptions data type is based on a string data type. Unlike a regular string, however, the value that SafeSearchOptions takes is restricted by the restriction element. In this case, the several enumeration elements that follow. SafeSearchOptions can only be what is given in this enumeration list. That is, SafeSearchOptions can only have a value of "Moderate", "Strict", or "Off". Restrictions are not the only reason to use a simple type. There can also be two other elements in place of restrictions. The first is a list. If an element is a list, it means that the value passed to it is a list of space-separated values. A list is defined with the list element followed by an attribute named itemType, which defines the allowed data type. For example, this example specifies an attribute named listOfValues, which comprises all integers.     <xsd:simpleType name="listOfValues">        <xsd:list itemType="xsd:integer" />    </xsd:simpleType> The second is a union. Unions are basically a combination of two or more restrictions. This gives you a greater ability to fine-tune the allowed value. Back to our age example, if our service was for a hospital's pediatrics ward that admits only those under 18 years old, we can restrict the value with a union.     <xsd:simpleType name="Age">        <xsd:union>            <xsd:simpleType>                <xsd:restriction base="decimal">                        <xsd:minInclusive value="0" />                </xsd:restriction>            </xsd:simpleType>            <xsd:simpleType>                <xsd:restriction base="decimal">                        <xsd:maxExclusive value="18" />                </xsd:restriction>            </xsd:simpleType>        </xsd:union>    </xsd:simpleType> Finally, it is important to note that while simple types are, especially in the case of WSDLs, used mainly in the definition of elements, they can be used anywhere that requires the definition of a number. For example, you may sometimes see an attribute being defined and a simple type structure being used to restrict the value. Complex Type Generically, a complex type is anything that can have multiple elements or attributes. This is opposed to a simple type, which can have only one element. A complex type is represented by the element complexType in the WSDL. The most common use for complex types is as a carrier for objects in SOAP transactions. In other words, to pass an object to a SOAP service, it needs to be serialized into an XSD complex type in the message. The purpose of a complexType element is to explicitly define what other data types make up the complex type. Let's take a look at a piece of Google's WSDL for an example:     <xsd:complexType name="ResultElement">        <xsd:all>            <xsd:element name="summary" type="xsd:string"/>            <xsd:element name="URL" type="xsd:string"/>            <xsd:element name="snippet" type="xsd:string"/>            <xsd:element name="title" type="xsd:string"/>            <xsd:element name="cachedSize" type="xsd:string"/>            <xsd:element name=                        "relatedInformationPresent" type="xsd:boolean"/>            <xsd:element name="hostName" type="xsd:string"/>            <xsd:element name=                        "directoryCategory" type="typens:DirectoryCategory"/>            <xsd:element name="directoryTitle" type="xsd:string"/>        </xsd:all>    </xsd:complexType> First thing to notice is how the xsd: namespace is used throughout types. This denotes that these elements and attributes are part of the XSD specification. In this example, a data type called ResultElement is defined. We don't exactly know what it is used for right now, but we know that it exists. An element tag denotes complex type's equivalent to an object property. The first property of it is summary, and the type attribute tells us that it is a string, as are most properties of ResultElement. One exception is relatedInformationPresent, which is a Boolean. Another exception is directoryCategory. This has a data type of DirectoryCategory. The namespace used in the type attribute is typens. This tells us that it is not an XSD data type. To find out what it is, we'll have to look for the namespace declaration that declared typens.
Read more
  • 0
  • 0
  • 5329

article-image-functional-testing-jmeter
Packt
22 Oct 2009
5 min read
Save for later

Functional Testing with JMeter

Packt
22 Oct 2009
5 min read
JMeter is a 100% pure Java desktop application. JMeter is found to be very useful and convenient in support of functional testing. Although JMeter is known more as a performance testing tool, functional testing elements can be integrated within the Test Plan, which was originally designed to support load testing. Many other load-testing tools provide little or none of this feature, restricting themselves to performance-testing purposes. Besides integrating functional-testing elements along with load-testing elements in the Test Plan, you can also create a Test Plan that runs these exclusively. In other words, aside from creating a Load Test Plan, JMeter also allows you to create a Functional Test Plan. This flexibility is certainly resource-efficient for the testing project. In this article by Emily H. Halili, we will give you a walkthrough on how to create a Test Plan as we incorporate and/or configure JMeter elements to support functional testing. Preparing for Functional Testing JMeter does not have a built-in browser, unlike many functional-test tools. It tests on the protocol layer, not the client layer (i.e. JavaScripts, applets, and many more.) and it does not render the page for viewing. Although, by default that embedded resources can be downloaded, rendering these in the Listener | View Results Tree may not yield a 100% browser-like rendering. In fact, it may not be able to render large HTML files at all. This makes it difficult to test the GUI of an application under testing. However, to compensate for these shortcomings, JMeter allows the tester to create assertions based on the tags and text of the page as the HTML file is received by the client. With some knowledge of HTML tags, you can test and verify any elements as you would expect them in the browser. It is unnecessary to select a specific workload time to perform a functional test. In fact, the application you want to test may even reside locally, with your own machine acting as the "localhost" server for your web application. For this article, we will limit ourselves to selected functional aspects of the page that we seek to verify or assert. Using JMeter Components We will create a Test Plan in order to demonstrate how we can configure the Test Plan to include functional testing capabilities. The modified Test Plan will include these scenarios: 1. Create Account —New Visitor creating an Account 2. Login User —User logging in to an Account Following these scenarios, we will simulate various entries and form submission as a request to a page is made, while checking the correct page response to these user entries. We will add assertions to the samples following these scenarios to verify the 'correctness' of a requested page. In this manner, we can see if the pages responded correctly to invalid data. For example, we would like to check that the page responded with the correct warning message when a user enters an invalid password, or whether a request returns the correct page. First of all, we will create a series of test cases following the various user actions in each scenario. The test cases may be designed as follows: CREATE ACCOUNT Test Steps Data Expected 1 Go to Home page. www.packtpub.com Home page loads and renders with no page error 2 Click Your Account link (top right). User action 1. Your Account page loads and renders with no page error.2. Logout link is not found. 3 No Password: - Enter email address in Email text field.- Click the Create Account and Continue button. email=EMAIL 1. Your Account page resets with Warning message-Please enter password.2. Logout link not found. 4 Short Password: - Enter email address in Email text field.- Enter password in Password text field.- Enter password in Confirm Password text field. - Click Create Account and Continue button. email=EMAILpassword=SHORT_PWD confirm password=SHORT_PWD 1. Your Account page resets with Warning message-Your password must be 8 characters or longer.2. Logout link is not found. 5 Unconfirmed Password: - Enter email address in Email text field.- Enter password in Password text field.- Enter password in Confirm Password text field. - Click Create Account and Continue button. email=EMAILpassword=VALID_PWDconfirm password=INVALID_PWD 1. Your Account page resets with Warning messagePassword does not match.2. Logout link is not found. 6 Register Valid User: - Enter email address in Email text field.- Enter password in Password text field.- Enter password in Confirm Password text field. - Click Create Account and Continue button. email=EMAILpassword=VALID_PWDconfirm password=VALID_PWD 1. Logout link is found.2. Page redirects to User Account page.3. Message found: You are registered as: e:<EMAIL>. 7 Click Logout link. User action 1. Logout link is NOT found.     LOGIN USER Test Steps Data Expected 1 Click Home page. User action 1. WELCOME tab is active. 2 Log in Wrong Password: - Enter email in Email text field- Enter password at Password text field.- Click Login button. email=EMAILpassword=INVALID_PWD 1. Logout link is NOT found.2. Page refreshes.3. Warning message-Sorry your password was incorrect appears. 3 Log in Non-Exist Account:- Enter email in Email text field.- Enter password in Password text field.- Click Login button. email=INVALID_EMAILpassword=INVALID_PWD 1. Logout link is NOT found.2. Page refreshes.3. Warning message-Sorry, this does not match any existing accounts. Please check your details and try again or open a new account below appears. 4 Log in Valid Account:- Enter email in Email text field.- Enter password in Password text field.- Click Login-button. email=EMAILpassword=VALID_PWD 1. Logout link is found.2. Page reloads.3. Login successful message-You are logged in as: appears. 5 Click Logout link. User action 1. Logout link is NOT found.    
Read more
  • 0
  • 3
  • 12881
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-podcasting-linux-command-line-tools-and-audacity
Packt
22 Oct 2009
5 min read
Save for later

Podcasting with Linux Command Line Tools and Audacity

Packt
22 Oct 2009
5 min read
Introduction Recording a good podcast is as much about good voice training and delivery, as much as it is about the technology used to record it. As with other things, you only get better with practice. In this article we will use Linux command line tools and optionally Audacity to create a quick, no-frills podcast with a background music track. The only other GUI-based tool we will manipulate, will be the ALSA Mixer. The mixer has a command-line interface too, but the GUI is intuitive and quicker. The emphasis is on quick turnaround. If you are the type that attaches a quick voice message to an e-mail for impact, ("We simply must get this done by Friday!!") then the podcast creation method outlined here should appeal to you. If you are new to podcasting and audio mixer setups, the next few sections might be tedious. But towards the end of this article, we will see how quickly one can run down these steps so that you spend more time recording your message than wrestling with technology or complicated screens. The Recording Setup A stereo headset with a microphone works best for making or listening to podcasts; but do not despair if you have a desktop microphone and a pair of speakers. You can always upgrade your setup later. For now just make sure that the sound from the speakers does not directly reach the microphone and cause feedback. Place the microphone towards the lower right of your mouth as you speak, away from your nose. This avoids breathing sounds getting captured. Minimizing ambient noise by choosing a quieter time of the day is also a good idea. Recording Tips All through the recording and mixing process, there are a couple of things to keep in mind. First, stay above the noise floor. The signal should be recorded high enough to stay above the background noise and hiss. If your audio signals are like little, beautiful flowers growing in a grassy field, make sure their stalks are tall enough to tower over the field. Else you would lose the flowers in the prickly grass just as your audio signal would be lost in the background hiss and noise. Second, stay below the clipping or overload level of the audio channels. If your audio channels were like open water canals, then overloading them past the clipping limit would have a similar undesirable effect on your audio experience as a canal overflowing its banks -- puddles around your feet or a jarring quality to your sound. Since sound level is a dynamic quantity, record your audio at a level of around 80% keeping some margin (or headroom) against clipping. Setting up the Audio Mixer Connections An audio mixer application helps us record our podcast by allowing us to mix various signal sources in the right proportion. You can bring up the sound mixer from the Linux start menu by getting into the Sound and Video category. To those who are new to the red and green lights of the Linux ALSA mixer, let us run a quick intro. There are audio signal sources and there are destinations. An audio mixer allows you to route one or more sources after adjusting their relative levels to one or more destinations and achieve your project goal. The project goal might be listening to music -- the destination in this case being a pair of headphones or speakers; or it might be a recording device, say, to capture a podcast as we will do presently. Once the ALSA mixer or Kmix is up, select the Output tab. Make sure the Master output channel as well as the PCM channel is switched on (click over the green lights so they turn on) and their gains -- the slider positions -- are at the maximum. Briefly, go the Switches tab and click over the LED indicator to switch on the 'Mix Mono'. We will use this mixing switch to mix the microphone (voice) and the CD (background score) signals to both the monitoring and the recording channels. You can optionally select the 'Mic Boost' switch but experiment with your microphone to check if you indeed need it. Now, go to the Input tab. The two input sources that interest us are the 'Mic' or microphone for our voice and the CD for our background music score. We need to mix these two signal sources in the right proportion and deliver them to the Capture device. Turn on the green LEDs for the 'Mic' and 'CD' sources ensuring that their outputs feed into the 'Mono Mix' and also to your monitoring headphones or speakers. That way you get to listen to what is being recorded. All other input sources should be off (their corresponding green LEDs should be off). Lastly, turn on the red LED under the Capture slider on the Input tab ensuring that the 'Mix Mono' output gets connected to the recording channel.
Read more
  • 0
  • 0
  • 27058

article-image-modeling-orchestration-and-choreography-service-oriented-architecture
Packt
22 Oct 2009
30 min read
Save for later

Modeling Orchestration and Choreography in Service Oriented Architecture

Packt
22 Oct 2009
30 min read
  Choreography versus Orchestration Choreography and orchestration, in an SOA context, pertain to the use of processes that span multiple participants, with message traffic moving in all directions according to a complex set of rules. Choreography and orchestration are attempts to coordinate or control all of this activity. They attack the problem by putting rigor on how message exchanges are represented, and by organizing the overall process using the right set of control flow patterns. Use cases in this area can be inter-organizational (for example, B2B commerce involving buyer, seller, and wholesaler), or intra-organizational if the organization is large enough and the participants act as separate organizations (for example, bank account processes spanning the front office, the back office, and the fraud department). By convention, choreography describes the global protocol governing how individual participants interact with one another. Each participant has its own process, but choreography is a master process that acts as a kind of traffic cop. Significantly, the choreography process does not actually run. It is not a central broker in the live message exchange, but merely a message exchange protocol. If the participants follow the protocol, the live exchange will run as smoothly as if there were a central broker. 'Traffic cop' is not exactly right then; choreography is more like a set of traffic rules. To mix metaphors, choreography teaches the participant processes how to dance as a group. The process for each participant is referred to as an orchestration process, whose principal job is to build a flow of control around (that is, to orchestrate) its interactions with partners. Orchestration processes are difficult to model, especially those faced with complex combinations of inbound events. If the process is subject to choreography, its structure can be derived from the choreography; in fact, as we'll see, there are tools that can generate skeletal orchestration processes from choreography definitions. The idea is simple: the choreography tells the complete story, so the participant can determine its role by isolating the parts in which it's involved. Not all orchestrations, alas, have a choreography to guide them (not all inter-organizational domains have a precise protocol defined). If the use case is sufficiently complex, the participant ought to create its own choreography anyway, not to share with its partners but simply to improve its own understanding of its orchestration. An orchestration process has public and private activities. The public activities are those that are required by the choreography. Private activities are there to meet internal requirements, but are not visible to partners. The next figure shows the public activities of the orchestration process for an energy retailer. The steps shown (for example, Send Request to Distributor) are those required by the enrollment choreography, in which the retailer is but one participant. The next figure shows the same process with private steps (for example, Update Account) included. In the figure, steps marked with a P are public steps. We examine the energy example in detail in this article. Web Services Choreography Description Language (WS-CDL) is the leading choreography language; Business Process Execution Language (BPEL) is the dominant process orchestration language. Although these XML-based languages feature a similar flow-oriented design style, only BPEL is meant to have an actual runtime platform: BPEL processes run; WS-CDL choreographies are protocols. BPEL is better known than WS-CDL in part because orchestration is more prevalent than choreography. BPEL's user community is much larger than WS-CDL's. Today, every company is building an SOA platform, and if they don't use BPEL as their SOA orchestration language, they use something similar. The user community for choreography consists of industry committees that publish protocols such as the enrollment and funds transfer choreographies we discuss in this article. Choreography might also work as part of a large organization's enterprise architecture, helping to sort out the communication of the organization's numerous systems. Few of these committees use WS-CDL to document their protocols anyway. Choreography is more often documented less formally using English descriptions, flowchart diagrams, and an XML message schema. Examples-Energy Enrollment and Email Bank Transfer The two examples from industry that showcase our technique for modeling choreography and orchestration are the enrollment of customers with retailers in a deregulated energy market and the procedure for transferring funds by email between two banks. In the energy market for a state or small country there are three parties: customers (who use electricity to power their homes), retailers (who sell electricity to customers), and the distributor (who supplies the electricity). Before deregulation, the distributor sold electricity directly to customers; there were no retailers back then. Deregulation introduced competition and broke up the distributor's monopoly. Customers can now buy electricity from one of many competing retailers. The distributor is now merely a supplier, having moved out of the retail sales business. When a customer enrolls with a retailer, the retailer uses the following protocol to complete the enrollment: The retailer submits the customer's request for enrollment to the distributor. The distributor responds in one of the three ways. If there is a problem with the request (for example, the customer has another enrollment in progress, or the customer has been flagged for fraud), the distributor sends a rejection to the retailer. If the request is valid and the customer is not currently enrolled with a retailer, the distributor sends an acceptance to the retailer. If the customer is currently enrolled with a competing retailer but intends to switch, the distributor sends a notice of pending switch to both the retailers. In the acceptance case, there is a 10-day waiting period during which the customer may cancel the enrollment. To cancel, the customer contacts the retailer, who forwards the cancellation request to the distributor. Assuming the customer does not cancel, at the end of the waiting period, the distributor sends a completion event to the retailer. The customer is now enrolled with the retailer. In the switch case, there is also a 10-day waiting period. To cancel, the customer contacts the initiating retailer (that is, the retailer to whom the customer is switching). The initiating retailer forwards the cancellation to the distributor, who then sends completion events to both retailers indicating that the customer will remain enrolled with the original retailer. Assuming the customer does not cancel, at the end of the waiting period, the distributor sends completion events to both retailers indicating that the customer is now enrolled with the initiating retailer. Email bank transfer is a protocol for wiring money by email. It works as follows: The person sending the money contacts his bank (the Sender bank), specifying from which account to draw the funds, how much money to send, and the name and email address of the recipient. The Sender bank sets aside the amount and sends an email to the recipient with instructions on how to complete the transfer. The Sender bank sets aside the amount and sends an email to the recipient with instructions on how to complete the transfer. The Recipient bank submits the transfer request to the Sender bank. The Sender bank accepts, and the funds are moved into the recipient's account, completing the transfer. At any point, either the sender or recipient may cancel the transfer, and the transaction is automatically canceled if not completed within 30 days. On cancellation, the funds are returned to the sender's account. (We assume both banks are members of the email transfer programme.) The following figure shows the most common scenarios in these examples: Modeling Choreography in BPMN In BPMN, two possible models for choreography are as follows: Invisible hub: Although choreography is fundamentally decentralized, we imagine there is a central hub through which all messages pass, and model the choreography as the process of that hub. Sum of parts: The public process of each participant (that is, the process containing steps required by the choreography, with private steps omitted) is drawn in a swim lane. Message flow (dashed lines) is used to show inter-participant communication. A sum-of-parts model for the enrollment choreography is shown in next figure. There are three swim lanes in the diagram: one for the distributor (referred to as Distributor), one for the initiating retailer (referred to as Retailer), and one for the current retailer (referred to as CurrentRetailer). Each lane contains the public process of the participant. The dashed arrows show the flow of messages between participants. The enrollment choreography is, according to this approach, the combination of the public processes of each participant plus the message flow that connects them. The choreography begins when the customer enrolls with the retailer (Cust Enrolls in the Retailer lane). The retailer then submits the enrollment request to the distributor by calling Dist.enroll. This call sends a message to the distributor, which triggers the event Enroll (the first step in the Distributor lane). The Distributor process is now underway, and it responds to the enrollment request either by rejecting the request, accepting it, or notifying the initiating retailer and the current retailer of a pending switch. The distributor rejects by calling Ret.reject, and, as the dashed line signifies, triggers the event Dist.reject in the retailer. The remaining steps are straightforward. The sum-of-parts method is intuitive, and variations on it can be found in business process literature (in the WSCI and BPMN specifications, for example). Sum-of-parts, however, has two disadvantages. First, the message flow creates an indecipherable clutter, making complex choreographies almost impossible to read; the swim lanes, for their part, use a lot of real estate. Aesthetics aside, sum-of-parts fails to present a global, consolidated view of the choreography. We grow bug-eyed trying to keep track of what each participant is doing. We are forced to watch each dancer rather than the group as a whole. The invisible-hub representation is comparatively compact. The next figure, which shows the enrollment choreography as a hub, has fewer steps than the sum-of-parts equivalent, and it makes do without lanes or dashed lines. The hub works as you would expect a hub to work: it listens for inbound events and routes them to their intended recipients. The act of receiving an event and sending it elsewhere is a single unit of work (shown in the figure as a rounded box with a dashed line), known as an interaction. The hub choreography represents the communication of its participants as a process of interactions. Before walking through this process, consider the following notational conventions: The event with a thin border (Ret.enroll(Dist)) is the process' start event. Events with a double-line border (for example, Dist.reject(Ret)) are intermediate events, which occur over the course of the process. Intermediate events can be used in three ways: for cancellation, for deferred choice, or simply to wait for the next message before continuing. The enrollment hub has examples of the latter two forms. We'll come back to cancellation while discussing the email transfer hub. Deferred choice, also known as an event pick, uses a diamond containing an inscribed star (known as an event-based gateway) with arrows leading to a set of intermediate events. The intent is to wait for one of those events to occur, execute its activities, and discard the remaining events. There are three deferred choices in the enrollment hub. The first occurs in three steps, and selects one of the three events: Dis.reject(Ret), Dist.accept(ret), or Dist.pendingSwitch(Ret, CurrRet). If, say, Dist.reject(Ret) occurs first, the activity Ret1.reject(Dist) is executed. The intermediate event Dist.switchCompleteCurrent(Ret, CurrRet) simply waits for something to happen before continuing. This event is sandwiched between the activities Dist.cancel(Ret) and Ret.switchCompleteCurrent, CurrRet.switchCompleteCurrent(Dist). Thus, when the first activity completes, that branch of the process waits for the event to occur before continuing with the second activity. Events have labels of the form Sender.msg (Recipients), meaning that the event received by the hub is a message from the sender bound for the specified recipients. (There must be at least one.) Thus, Dist.switchCompleteCurrent(Ret, CurrRet) is the message switchCompleteCurrent from the distributor (Dist) to both the initiating retailer (Ret) and the current retailer (CurrRet). Send tasks (rounded boxes with a straight border) are labeled Recipient.msg(Sender), meaning that hub is sending the specified message to the recipient and is indicating that the message originated with the specified sender. In Dist.enroll(Ret), for instance, the hub sends the message enroll to the distributor (Dist), and is indicating to the distributor that this message came from the retailer (Ret). If the event that preceded it specifies multiple recipients, the send task sends the message to each recipient. Each send counts as one interaction.Ret.pendingSwitch, CurrRet.pendingSwitch (Dist), for example, sends the message pendingSwitch to both the retailer (Ret) and the current retailer (CurrRet), and thus spans two interactions. A rounded box with a dashed border, known in BPMN as a group, pairs up an event and a send task. Thus, the grouping of Ret.enroll(Dist) and Dist.enroll(Ret) means that when the hub receives the message enroll from the retailer bound for the distributor, it sends that message to the distributor, indicating to the distributor that the message originated with the retailer. A group that contains multiple interactions has a label in the top-center of the dashed box indicating the number of interactions. The number of interactions is equal to the number of recipients. The enrollment hub diagram reads as follows: The choreography begins with the interaction in which the retailer sends an enrollment request to the distributor. For convenience, this interaction is labeled a in the figure. Exactly one of the three interactions can happen next: the distributor sends a rejection to the retailer (b); the distributor sends an acceptance to the retailer (c); or the distributor sends a notice of pending switch to both the initiating and current retailers (d). Exactly one of the two interactions can follow acceptance: the retailer sends a cancellation to the distributor e, or the distributor sends a completion event to the retailer (f). In the pending switch case, one of the two interactions follows the notice of pending switch: the initiating retailer sends a cancellation to the distributor (g); or the distributor sends a switch completion event to both the initiating and current retailers indicating that the current retailer won (h). If the switch is cancelled, the distributor sends a switch completion event to both retailers indicating that the initiating retailer won (i). The choreography has 12 interactions assembled in a process flow. (There are nine groups, but three of them have two interactions each.) Reading the diagram means spotting the 12 interactions and traversing the control flow that connects them. The email transfer choreography hub, shown in the next figure, is somewhat more complex. The email transfer hub reads as follows: The choreography begins when the sender submits the transfer request to the sender bank (a). The sender bank can reject the request (b), or accept it (c). The acceptance event in c is routed to both the sender and the recipient, and thus results in two interactions. The remainder of the hub process is a loop that continues until the transfer is completed. The loop is modeled as a BPMN embedded sub-process labeled Loop. The arched arrow pointing counter-clockwise in the bottom-center of the sub-process box denotes that this sub-process is iterative. In the first step of the loop, the recipient requests her bank to transfer the funds into his or her account (d). The recipient's bank either rejects (e) or accepts (f) the request. In the rejection case, the recipient's bank sends a rejection notice to the recipient. In the next iteration of the loop, the recipient can try again. In the acceptance case, the recipient's bank sends a transfer request to the sender's bank. The sender's bank can either accept (g) or reject (h) the request. In the acceptance case, the sender's bank sends a transferOK message to both the recipient's bank and the sender. The recipient's bank then notifies the recipient (i), and the choreography completes. (The Set Done task sets the loop's continuation condition to false, which causes the loop to exit and the hub process to complete.) In the rejection case, the sender's bank sends a rejectTransfer message to the recipient's bank, and the recipient's bank notifies the recipient of this (j). In the next iteration of the loop, the recipient can try again. While the loop is executing, any of the parties may cancel the request (k). The label in the event *.cancel (SenderBank) informs the hub to listen for a cancel message from any party—the * works as a wildcard—and to route that message to the sender's bank. The sender's bank, in turn, sends an abort message (l) to the sender, the recipient, and the recipient's bank (the bank into which the recipient is currently requesting the transfer). Interaction (k) is an example of a cancellation intermediate event; it terminates the loop and transition into a series of cancellation activities. Choreographies are not executable, as we discussed previously. A choreography is a protocol, a set of traffic laws. It is, emphatically, not a central hub through which all participant interactions flow. Our hub model is merely a specification of how the individual participants should communicate. There are countless senders, recipients, and banks in the world of email transfer, but there is no hub that helps them talk to each other. The invisible hub for email transfer is merely a model; it is every bit as hypothetical as the invisible hand of Adam Smith's free-market economy. The economy is self-powered, and does not require the intervention of a hand; email transfer goes on without a hub. Still, the BPMN hub model is more than an informative picture. As we'll see, it maps easily to WS-CDL, and it serves as the basis for the generation of participant stubs and a choreography 'protocol' tester. Our BPMN method is practical and built with implementation in mind. Choreography modeling is also a hot topic in the academic world. Useful papers in this arena include Inheritance of Interorganizational Workflows: How to agree to disagree without loosing control? (Wil van der Aalst," BETA Working Paper Series, BP46, Eindhoven University, http://is.tm.tue.nl/staff/wvdaalst/publications/p109.pdf) and 'Let's Dance' (servicechoreographies.com, http://sky.fit.qut.edu.au/~dumas/LetsDance/01-Overview.html). The Invisible Hub in BPEL BPEL is principally an orchestration language, as just discussed, but it can also be used to model invisible hub choreographies. The code shown in the next figure is a simplified version of an actual BPEL implementation of the enrollment hub. The mapping from the BPMN hub to this BPEL implementation is straightforward: The event that starts the choreography in BPMN (Ret.enroll(Dist)) is receive that creates the BPEL process instance, marked as Start Event in the figure. An intermediate event that simply waits for a message between activities (for example, Dist.switchCompleteCurrent (Ret, CurrRet) in the BPMN model) is a BPEL receive, such as the line marked Intermediate Event in the figure. Deferred choice is a BPEL pick. The events in the choice are onMessage handlers. For example, the deferred choice in the BPMN model of Dist.reject(Ret), Dist.accept(Ret) and Dist.pendingSwitch(Ret, CurrRet) is the pick marked as Deferred Choice in the figure. The handlers are the three onMessage blocks that sit underneath the pick. Send tasks are BPEL invoke activities. For example, Dist.enroll(Ret) in the BPMN representation becomes the invoke in the line marked Send Task in the figure. The set of partner links used in the BPEL process is the union of all sender and recipient participants in the hub. Many partner links are bidirectional: they can either call the BPEL process or the BPEL process can call the partner link. The three partner links in this example, which are referred to in each receive, invoke, and onMessage tag are Ret, Dist, and CurrRet. BPEL supports dynamic partner links (where the BPEL process determines the physical address of its partner service at runtime). The series of four steps marked Dynamic partner links in the figure provides an example. The initial receive is a message from the distributor intended for one of the two retailers (either the current or the initiating retailer). The invoke that follows sends the message to that retailer. The endpoint of that retailer is resolved at runtime, based on the contents of the receive message. The next receive is a message from the distributor intended for the second retailer, and the invoke that follows sends the message to that retailer, again resolving the endpoint at runtime. In the majority of BPEL processes, partner links are resolved at deployment time, but that approach does not work in scenarios like ours. An interaction in which the sender sends to N recipients is modeled in BPEL as N separate inbound events and invokes. The series of four steps discussed in the previous bullet (and marked with Send to Multiple in the figure) provides an example. These steps model the activity Dist.switchCompleteCurrent (Ret, CurrRet) from the BPMN hub. In the BPEL code, the effect of the distributor sending the message switchCompleteCurrent to both the initiating and current retailers is achieved by having the hub receive the message from the distributor twice (using a receive), in each case forwarding the message (using an invoke) to one of the retailers. Dynamic partner links are used to resolve the endpoint of the recipient. The figure maps lines of code in the BPEL hub to interaction groups in the BPMN model. The first two lines, for example, represent group A. The reader can easily verify the mapping for groups B to I. There are two advantages to having the hub model in BPEL form: BPEL's XML form is an alternative to the leading XML choreography representation, WS-CDL (discussed in the next section). If we require an XML representation of choreography, BPEL might be a better choice than WS-CDL, because it is more familiar and has broader tool support. The BPEL hub is executable! There are numerous BPEL runtime platforms that can run this process as an actual hub. Granted, choreographies are not meant to run as part of the live exchange of actual participants, but having an executable version enables two important types of testing, shown in the next figure: unit testing of the choreography itself, and protocol testing of a particular participant. In unit testing, we build a Test Harness, driven by scripted scenarios, that sends messages to the hub and compares responses received with those expected. In protocol testing, we build the public process of a participant (say the retailer), but point it to the hub rather than its actual partners. We can embellish the hub to use test scripts to control how it responds. Once we have tested all of the scenarios and verified that the participant behaves as required, we can point the participant process to the real partners and go live Choreography in WS-CDL with Pi4SOA The description of choreography in WS-CDL with P14SOA is as follows: Defining Roles and Relationships Web Services Choreography Description Language (WS-CDL) is a specification from the W3C (Web Services Choreography Description Language Version 1.0, http://www.w3.org/TR/ws-cdl-10) for building choreographies in XML form. Like our invisible hub model, WS-CDL takes the global view: a choreography is not the sum of the public processes of its participants, but a single control flow of interactions. The WS-CDL language is exceedingly rich and best learned by example. In this section, we study how the enrollment choreography is represented in WS-CDL. Rather than building the choreography's XML from scratch, we use a visual modelling tool known as pi4SOA. pi4SOA, an open-source implementation that plugs into Eclipse, is one of the few WS-CDL implementations available today. The first step in building a WS-CDL choreography is to define participants and their structural relationships. The following figure shows the enrollment choreography open in the Participants, Roles, and Relationships tab of the pi4SOA editor.   There are five participants (shown with building icons) in the figure: Distributor, Retailer, CurrentRetailer, Customer (to model a customer's interaction with a retailer), and DistributorBizCal (a subsystem of the distributor to model the management of business calendars for completion and switch periods). Each participant has a role of the same name (designated by a stick-man icon), and each role has a behavior named for its role: Distributor's behavior is DistributorBehavior, Retailer's behaviour is RetailerBehavior, and so on. In WS-CDL, a behavior is a web service interface, and a role is a group of behaviors. A role can have multiple behaviors and a participant can have multiple roles. In our case, each participant has one role and one participant. The lines connecting roles are called relationships. There are four relationships: RD is the relationship between Retailer and Distributor, CRD the relationship between CurrentRetailer and Distributor, RC the relationship between Retailer and Customer, and DInt the relationship between Distributor and DistributorBizCal. When two roles have a relationship, they can interact by calling each other's services. The next figure shows the Base Types tab of the choreography editor. To the participants, roles, and relationships defined above, we add four important elements: information types, tokens, token locators, and channel types. An information type is an XML data type (generally based on an XML schema) exchanged during interactions. A token is a field in an information type. A token locator defines how to extract—generally using an XPath expression—the token from the information type. Our choreography has one information type, called EnergyMsg with five tokens and token locators (custID, retailer, txID, currentRetailer, and reason). A channel type is an inbound communication endpoint for a role behavior. In the enrollment choreography, there are channels for the retailer, current retailer and distributor. Each channel type is configured for one-way asynchronous requests only. Hence, Retailer receives requests on its RetailerChannel; CurrentRetailer receives requests on its CurrentRetailerChannel; and Distributor receives requests on its DistributorChannel. Combining our definitions of relationships and channels, we have the following communication structure: In the relationship RD, Retailer sends to Distributor on DistributorChannel, and Distributor sends to Retailer on RetailerChannel   In the relationship CRD, Distributor sends to CurrentRetailer on CurrentRetailerChannel. (CurrentRetailer could also send to Distributor on DistributorChannel, but the use case does not require it.) In the relationship RC, Customer sends to Retailer on RetailerChannel. (Customer does not have a channel, so the reverse direction is not permitted.) In the relationship DInt, DistributorBizCal sends to Distributor on DistributorChannel. (DistributorBizCal does not have a channel, so the reverse direction is not permitted.) Building a Control Flow of Interactions The next figure shows the overall control flow that defines the behaviour of the choreography. There are three steps. The first, RequestC2R, is an interaction in which the Customer participant sends an enrollment request to the Retailer participant. The request has the information type EnrollmentMsg, and is sent on RetailerChannel as part of the RC relationship. In the interaction that follows, RequestR2D, the retailer forwards that request to the distributor; or, in the language of WS-CDL, Retailer sends the request with information type EnrollmentMsg on the DistributorChannel as part of the RD relationship. The step that follows, enrollmentResult, is a flow construct known as a choice. There are three possible outcomes of an enrollment request—acceptance, rejection, or a pending switch. The choice allows exactly one to occur. The next figure shows the acceptance and rejection paths; the switch path is omitted for brevity. The rejection path (housed in a sequence labelled rejectEnrollment) has one interaction, RejectD2R, in which the distributor sends a rejection message to the retailer. The more complicated acceptance path is housed in the sequence labelled newEnrollment, which begins with the interaction in which the distributor notifies the retailer that the enrollment is accepted (AcceptD2R). Next is a silent action, setCompletionTimer, in which the distributor sets a timer that expires at the end of the ten-day cancellation period. A silent action in WS-CDL is a private operation performed by a role. The acceptance path has a nested choice, labelled completionPeriod, which documents the two possible outcomes for an accepted enrolment: periodExpired is a sequence that specifies what happens when the ten-day timer expires, and cancel handles the case in which the customer cancels the enrollment during the cancellation period. Each path contains two interactions. In the periodExpired sequence, the periodExpired interaction (sent from DistributorBizCal to Distributor by the DInt relationship) notifies the distributor that time is up, whereupon the distributor sends a completion event to the retailer (CompleteD2R). In the cancel sequence, the customer cancels with the retailer (CancelC2R by the RC relationship), and the retailer, in turn, cancels with the distributor (CancelR2D by the RD relationship). The following is a snippet of the WS-CDL XML encoding of the enrollment choreography, covering the acceptance case only. For the sake of simplicity, numerous details are omitted: <package name="EnergyChoreo">   <choreography name="main" root="true">     <sequence>       <!-- Cust sends request to retailer -->       <interaction channelVariable="tns:retailerChannel"                    name="RequestC2R" operation="enroll">         <participate fromRoleTypeRef="tns:Customer"                      relationshipType="tns:RC" toRoleTypeRef="tns:Retailer"/>       </interaction>       <!-- Retailer sends request to distributor -->       <interaction channelVariable="tns:distributorChannel"                    name="RequestR2D" operation="enroll">         <participate fromRoleTypeRef="tns:Retailer"                relationshipType="tns:RD" toRoleTypeRef= "tns:Distributor"/>       </interaction>       <!-- Choose what comes next -->       <choice>         <!-- Path taken if distributor rejects -->         <sequence>           <!-- This is the interaction that heads the reject path -->             <interaction name="RejectD2R" operation="reject">             </interaction>         </sequence>         <!-- Path taken if distributor accepts -->         <sequence>           <!-- This is the interaction that heads the accept path -->             <interaction name="AcceptD2R" operation="accept">             </interaction>             <silentAction name="setCompletionTimer"                           roleType="tns:Distributor">             <choice>               <!-- Accept subpaths omitted -->             </choice>          </sequence>          <!-- Omitted: switch path -->       </choice>     </sequence>   </choreography> </package> The two key elements in this example are choice and interaction. They are mapped to our hub model as follows: A receive-send pair in the hub is a WS-CDL interaction. In WS-CDL, a relationship is defined between sender and recipient, and the recipient has a channel on which the sender sends the message. An example of this is the interaction shown in bold from the customer (fromRoleTypeRef="tns: Customer") to the retailer (toRoleTypeRef="tns:Retailer") on the RC relationship (relationshipType="tns:RC"). The event arrives on the retailer's channel (channelVariable="tns:retailerChannel"). A deferred choice in the hub is a choice structure in WS-CDL. Generally, a path in the choice is a sequence. The set of events from which we are choosing is the set of first interactions on each path. The main choice structure in the choreography, shown in bold, has two interactions from which to choose: acceptance and rejection interactions (also shown in bold). The interaction that actually occurs determines which path is taken.   Generating a BPEL Role Process In addition to producing conformant WS-CDL code, pi4SOA's capabilities include scenario testing and BPEL and Java endpoint generation. The BPEL generation feature is especially useful, as BPEL is a suitable implementation choice to build orchestration process of a given participant. Here, in pseudo-code, is the BPEL process that pi4SOA generates for the distributor: <process>   <sequence>     <receive operation="enroll" partnerLink="RD"              portType="DistributorBehavior"/>       <!-- Dist receives interaction -->     <switch name="enrollmentResult"> <!-- Dist choice is switch -->       <case condition="accepted">         <sequence>           <invoke operation="accept" partnerLink="RD"                   portType="RetailerBehavior"/> <!-- Dist is sender -->           <scope name="setCompletionTimer"/>           <pick name="completionPeriod">             <onMessage operation="periodExpired" partnerLink="DInt"                        portType="DistributorBehavior">               <sequence>                 <invoke operation="complete" partnerLink="RD"                         portType="RetailerBehavior"/>               </sequence>             </onMessage>             <onMessage operation="cancel" partnerLink="RD"                        portType="DistributorBehavior"/>           </pick>         </sequence>       </case>       <case condition="rejected ">         <invoke operation="reject" partnerLink="RD"                 portType="RetailerBehavior"/>       </case>       <case condition="switch">         <!-- omitted -->       </case>   </switch> </sequence> </process> Two salient features of this process are the mapping of interactions and the conversion of the WS-CDL choice to a BPEL switch as follows: An interaction in which the distributor is the sender is a BPEL invoke activity whose partner link is the WS-CDL relationship and whose port type is the recipient's behavior. The operation element in the invoke matches the one specified in the interaction. The invoke shown in bold, for example, which is sent to the retailer, has partner link RD, port type RetailerBehavior, and operation accept. An interaction in which the participant is the recipient is either a receive activity or an onMessage handler in a pick. The partner link is the name of the relationship, and port type is the participant's behavior. The operation element, as before, matches that specified in the interaction. The bolded receive in the BPEL sample is the enroll operation on the partner link RD and port type DistributorBehavior. The WS-CDL choice is a switch for the BPEL distributor process (as the bolded comment in the switch line indicates), because the distributor begins each path of the choice by sending a message. From the distributor's perspective, the choice represents its decision to reject the request, accept it, or initiate a pending switch. Each case in the switch handles one of these possibilities. The retailer, on the other hand, begins each path by waiting for an event from the distributor. From the retailer's point of view, the choice is a pick, as in the following snippet: <pick name="enrollmentResult"> <!-- For Ret, choice is a pick -->   <onMessage operation="accept" partnerLink="RD"              portType="RetailerBehavior">     <!-- code omitted -->   </onMessage>   <onMessage operation="reject" partnerLink="RD"              portType="RetailerBehavior" />   <onMessage operation="pendingSwitch" partnerLink="RD"              portType="RetailerBehavior" >     <!-- code omitted -->   </onMessage> </pick> We have only scratched the surface of WS-CDL. Other notable capabilities are state alignment, coordination, and channel passing. WS-CDL's supporters boast that their language has its foundations in the Pi Calculus, a mathematical scheme for describing concurrent processes and how they pass messages to each other. Robin Milner, the mathematician who devised the Pi Calculus, is an advisor to the WS-CDL working group. Sadly, WS-CDL has not gained much traction in the field. There are scant tools to build WS-CDL choreographies and, frankly, not many use cases that require choreography. Few people who practice SOA technology have even heard of this language. WS-CDL is winning the mathematics battle but losing the marketing war. Summary Choreography is the global protocol governing the interaction of SOA processes partnering to achieve some business ends. An orchestration process is a process whose principal job is to build a flow of control around its interactions with partners. WS-CDL is the dominant choreography standard. BPEL is the dominant orchestration standard. Both standards provide a way to build process flows in an XML form, though only BPEL processes are meant to actually execute. The modeling tool pi4SOA is ideal for building WS-CDL examples. Key WS-CDL elements are interaction (which corresponds to the receive-send pair in the invisible hub) and choice (a kind of deferred choice in the choreography's flow of control. pi4SOA generates skeletal BPEL code for each participant in the choreography.
Read more
  • 0
  • 0
  • 7700

article-image-xen-virtualization-work-mysql-server-ruby-rails-and-subversion
Packt
22 Oct 2009
7 min read
Save for later

Xen Virtualization: Work with MySQL Server, Ruby on Rails, and Subversion

Packt
22 Oct 2009
7 min read
Base Appliance Image We will use an Ubuntu Feisty domain image as the base image for creating these appliances. This image should be made as sparse and small as possible, and free of any cruft. A completely stripped down version of Linux with only the bare necessities would be a great start. In this case, we will not need any graphical desktop environments, so we can completely eliminate software packages like the X11 and any window manager like Gnome or KDE. Once we have a base image, we can back it up and then start using it for creating Xen appliances. In this article we will use an Ubuntu Feisty domain as the base image. Once this domain image is ready we are going to update it and clean it up a little bit so it can be our base. Edit the sources list for apt and add in other repositories that we will need to get software packages we will need when creating these appliances. Update your list of software. This will connect to the apt repositories and get the latest list of packages. We will do the actual update in the next step. Upgrade the distribution to ensure that you have the latest versions of all the packages. Automatically clean the image so all unused packages are removed. This will ensure that the image stays free of cruft.   Now we have the base appliance image ready, we will use it to create some Xen appliances. You can make a backup of the original base image and every time you create an appliance you can use a copy as the starting point or template. The images are nothing but domU images, which are customized for running only specific applications. You start them up and run them like ay other Xen guest domains. MySQL Database Server MySQL is one of the most popular open-source databases in the world. It is a key component of the LAMP architecture – (Linux Apache MySQL and PHP). It is also very easy to get started with MySQL and is one of the key factors driving its adoption across the enterprise. In this section we will create a Xen appliance that will run a MySQL database server and also provide the ability to automatically backup the database on a given schedule. Time for Action – Create our first Xen appliance We will use our base Ubuntu Feisty domain image, and add MySQL and other needed software to it. Please ensure that you have updated your base image to the latest versions of the repositories and software packages before creating this appliance. Install mysql-server using apt. Once it is installed, Ubuntu will automatically start the database server. So before we make our other changes, stop MySQL. Edit the /etc/mysql/my.cnf and comment out the line for the bind-address parameter. This will ensure that MySQL will accept connections from external machines and not just the localhost. Start a mysql console session to test that everything is installed and working correctly. Next we will install the utility for doing the automated backups. In order to do that we will first need to install the wget utility for transferring files. This is not a part of the base Ubuntu Feisty installation. Download the automysqlbackup script from the website. Copy this script to wherever you like, maybe /opt. Create a link to this location so it’s easy to do future updates. # cp automysqlbackup.sh.2.5 /opt# ln -s automysqlbackup.sh.2.5 automysqlbackup.sh Edit the script and modify the parameters at the top of the script to match your environment. Here are the changes to be made in our case. # Username to access the MySQL server e.g. dbuserUSERNAME=pchaganti# Username to access the MySQL server e.g. passwordPASSWORD=password# Host name (or IP address) of MySQL server e.g localhostDBHOST=localhost# List of DBNAMES for Daily/Weekly Backup e.g. "DB1 DB2 DB3"DBNAMES="all"# Backup directory location e.g /backupsBACKUPDIR="/var/backup/mysql"# Mail setupMAILCONTENT="quiet" Schedule this backup script to be run daily by creating a crontab entry for it, in the following format. 45 5 * * * root  /opt/automysqlbackup.sh >/dev/null 2>&1 Now we have a MySQL database server with automatic daily backups as a nice reusable Xen appliance. What just happened? We created our first Xen appliance! It is running the open-source MySQL database server along with an automated backup of the database as per the given schedule. This image is essentially a domU image and it can be uploaded along with its configuration file to a repository somewhere, and can be used by anyone in the enterprise or elsewhere with their Xen server. You can either start up the domain manually as and when you need it or set it up to boot automatically when your xend server starts. Ruby on Rails Appliance Ruby on Rails is one of the hottest web development frameworks around. It is simple to use and you can use all the expressive power of the Ruby language. It provides a great feature set and has really put the Ruby language on the map. Ruby on Rails is gaining rapid adoption across the IT landscape and for a wide variety of web applications. In this section, we are going to create a Rails appliance that contains Ruby, Rails, and the Mongrel cluster for serving the Rails application and nginx web server for the static content. This appliance gives you a great starting point for your explorations into the world of Ruby on Rails and can be an excellent learning resource. Time for Action – Rails on Xen We will use our base Ubuntu Feisty domain image and add Rails and other needed software to it. Please ensure that you have updated your base image to the latest versions of the repositories and software packages before creating this appliance. Install the packages required for compiling software on an Ubuntu system. This is required as we will be compiling some native extensions. Once the image is done, you can always remove this package if you want to save space. Install Ruby and other packages that are needed for it. Download the RubyGems package from RubyForge. We will use this to install any Ruby libraries or packages that we will need, including Rails. Now install Rails. The first time when you run this command on a clean Ubuntu Feisty system, you will get the following error. Ignore this error and just run the command once again and it will work fine. This will install Rails and all of its dependencies. Create a new Rails application. This will create everything needed in a directory named xenbook. $ rails xenbook  Change into the directory of the application that we created in the previous step and start the server up. This will start Ruby’s built-in web server, webrick by default. Launch a web browser and navigate to the web page for our xenbook application. We have everything working for a simple Rails install. However, we are using webrick, which is a bit slow. So let’s install the Mongrel server and use it with Rails. We will actually install mongrel_cluster that will let us use a cluster of Mongrel processes for serving up our Rails application.
Read more
  • 0
  • 0
  • 2985

article-image-visual-sourcesafecreating-service-oriented-application
Packt
22 Oct 2009
17 min read
Save for later

Visual SourceSafe:Creating a Service-Oriented Application

Packt
22 Oct 2009
17 min read
I will build a prototype for a hotel reservation system outlining the way Software Configuration Management makes the job easier. Don't worry if you are not fully familiar with the technologies used. The purpose of this application is purely for reference, so you can sit back and relax. At this point I will use my time machine and get a screenshot for the final application so you can see how it will look like. Or, I can insert the screenshot after it finished. I think the first way seems more reasonable. This is what the public reservation site looks like: If you like it, you can download the application from the book's website: http://orbitalhotel.alexandruserban.com. Now let's get back to our time and start the development lifecycle on the Orbital Hotel product. The first phase is the specifications phase. Specifications—Project Architecture In order to build a software system, we need a list of requirements. What is the purpose of the system? What are the actions performed by the system and against the system? Who will use the system and how? The answers to these questions will let us identify the main parts of the system and the way these parts work together. System Requirements Let's take a look at the Orbital Hotel's reservation system's requirements. The purpose of the reservation system is to allow guests to make room reservations. There are several room types each having a number, occupancy, price, availability, description, and image. The reservations can be made by using the hotel's internet website, through the websites of travel agencies (third parties), or by making phone calls to the hotel's client service. Reservations can be also made by internal client service staff who receive phone calls from guests. When guests use the hotel's website, they will create a user with a username and password and input their personal details such as first name, last name, address, city, zip code, state, country, phone, email address, and card number. Then they will choose a room and complete the reservation details such as arrival date, the number of nights they will be staying and the number of adults, teenagers, children, and pets. They will also be able to cancel their reservation. When making a reservation over the phone, a guest will provide the same personal information and reservation details to the hotel's client-service staff. The staff will create a reservation for the guest using an internal application. The staff members will also authenticate using a username and password. Travel agencies and other third parties must also be able to make hotel reservations. Taking a big picture about the type of system we are going to build, what we need is an application design that will be as flexible as possible. It should provide us with a variety of options like reservations through phone calls, personal or third-party websites, smart devices like PDAs or cell phones, and so on. This is where we gather the specifications and plan the system architecture. In this phase we have to consider as many aspects as we can, based on our requirements and specifications. So, let's see what the main existing application architectures are, and see what application architecture fits our requirements. Application Architectures The computer and computer programming history is a very short one in comparison with that of other industries. Although it is short, it has evolved and continues to evolve very rapidly, changing the way we live. Taking into account the architectures used at the beginning of computer programming, we can see an evolution from the single, powerful, fault-tolerant, expensive super mainframe computer applications, towards multiple, distributed, less expensive smaller machine applications, the personal computers. During this evolution, three main application architectures can be identified: Compact application architecture Component application architecture Service-Oriented Architecture (SOA) We are going to take a brief look at these application architectures and outline their characteristics. Compact Application Architecture During application development for the single mainframe, there was no clear separation between application layers and no reusable components were used. All the data access, business logic, and user interface-specific code were contained in a single executable program. This traditional compact architecture was used because the mainframe computers had specific proprietary programming languages and formats for accessing and manipulating the data. All the data access-specific procedures as well as the business logic and business rules code are written in this programming language. At the surface, a user interface is presented to the user for data visualisation and manipulation. This application architecture works for applications that do not need data input from multiple sources and can be easily developed by a single programmer. However, this approach has several major disadvantages when it comes to building large-scale systems: Application components cannot be reused in other applications because they are tightly coupled and dependent on one another. Tight coupling means that in order for a piece of code to use another piece of code, it must have intimate knowledge about its implementation details. Being tightly coupled, a change to one component can affect the functionality of another, making debugging and maintenance a difficult task. The application is actually a black box; no one, except the main developer, knows what it is in there. Applying security is another problem because the user interface cannot be separated from the business logic components using security-specific mechanisms like authentication and authorization. Application integration is affected because the code is platform dependent. Integration between two such applications requires special and specific coding and can be difficult to maintain. Scalability issues are considered when the system grows and need to be scaled across several machines. Using this application architecture, scalability is not possible as you can't separate different application parts across different physical boundaries because of the tight coupling. To address the issues with the compact application architecture, the component-based application architecture was developed. Component Application Architecture In the component application architecture, the application's functionality is defined using components. A component is like a black box, a software unit that encapsulates data and code and provides at the surface a set of well-defined interfaces used by other components. Since a component only needs to support a well-defined set of interfaces, it can change the inner implementation details without affecting other components that use its external interfaces. Components that export the same interfaces can be interchanged, allowing them to be reused and tight coupling to be eliminated. This makes them loosely coupled because they don't need to know internal implementation details of one another. This separation of application functionality using components allows the distribution of development tasks across several developers and makes the overall application more maintainable and scaleable. In the Windows environment, the most used component application architecture is the Component Object Model (COM). Typically, components are grouped into logical layers. For example, an application uses the data access layer to access the different data sources, the business logic layer to process the data according to the business rules, and the presentation layer also known as the user interface layer to present the data to end users. Using well-defined application layers allows for a modular design, component decoupling, and therefore the possibility for component reuse. Data Access Layer This architecture forms a chain of layers that communicate with one another. The base is the data access layer, which is responsible for querying, retrieving, and updating the data from and to different data sources while providing a uniform data view to the layers above. Business Layer Above the data access layer is the business logic layer. The business logic layer uses the uniform data provided by the data access layer and processes it according to the business rules it contains. The business logic layer doesn't need to know from what source and how the data was obtained. Its purpose is only data manipulation and processing. Presentation Layer At the top of the chain is the presentation layer or the user interface layer. Its purpose is to present the data processed by the business logic layer to end users and to receive input and commands from these end users. The presentation layer will propagate these commands down the chain to the business layer for processing. Characteristics The component application architecture solves many software problems and it has been used extensively in the past. But because software evolves continuously, new requirements introduce new challenges. Let's suppose we have several applications on different platforms, each incorporating its presentation layer, business logic layer, and data access layer. We want to integrate them into a bigger distributed system, a system that spans across several heterogeneous environments. At some point, one application will need to access the data existing in another application. While components can work well in a homogenous environment on the same platform, for example COM in the Windows environment, problems appear in components working across several platforms. For example, it is very difficult for a COM component to be used from a Java application or vice-versa, mainly because they don't speak the same language. Integration between two or more applications running on different platforms would require a middle component-dependent intercommunication layer that is expensive, difficult to build, and reintroduces tight coupling between systems, which is what we tried to avoid in the first place. Avoiding building this intercommunication layer would require that the data exchange between these applications be done by a person who will read the necessary data from the source application and write it into the target application. We need to integrate these systems, and maintain the loose coupling between them. What we need to do, is make these components understand each other, making them to speak the same language. This is where the concept of services and Service-Oriented Architecture (SOA) comes into play. Service-Oriented Architecture SOA describes an information technology architecture that enables distributed computing environments with many different types of computing platforms and applications. To enable distributed computing environments, SOA defines the concept of services. A service is a well-defined, self-contained unit of functionality, independent of the state of other services. Let's see how services can be used to create distributed applications, integrate component-based applications, and make them communicate with each other. We keep our data access layer and business logic layer as they are, but we completely decouple the presentation layer so we can change it later without affecting the other layers. In order to expose the functionality of the business logic layer, we wrap it in a service interface. The service interface wraps the business logic layer components offering a point of access for any process that needs to access the business logic, whose functionality has now become a service. Service-oriented architecture is basically a collection of services that communicate with each other. The communication can involve either simple data passing or it can involve two or more services coordinating some activity. Whatever the required functionality may be, we have now separated the functionality of applications into specific units, the services that we use to construct flexible, distributed applications. Typically services reside on different machines. They are exposed to the outside world by service interfaces. A service provider provides its functionality using the service interfaces that are used or consumed by the service consumers. A service consumer sends a service request to a service interface and receives a service response. The following figure represents a typical service consumer-service provider request. A service can be a service provider and a service consumer at the same time as it can consume other services. They communicate using a communication medium like a local area network for internal services or the Internet for external services. This communication medium is called a service bus. We saw that services don't have a presentation layer as we've decoupled the presentation layer from the rest. This presents an advantage because we can now use any platform able to understand and consume the service to build a presentation layer. The service interface has to provide a standard and open way of communication, a common language that both service providers and service consumers can understand, regardless of the machine type they are deployed on, their physical location, and the language in which they are written. XML Web Services In today's world, the communication standard used to connect services is achieved using web services. Web services are small, reusable applications that help computers with many different operating system platforms work together by exchanging messages. Web services are based on industry protocols that include XML (Extensible Markup Language), SOAP (Simple Object Access Protocol), and WSDL (Web Services Description Language). These protocols help computers work together across platforms and programming languages enabling data exchange between otherwise unconnected sources: Client-to-Client: Devices, also called smart clients, can host and consume XML web services, allowing data sharing anywhere, anytime. Client-to-Server: A server application can share data with desktop or mobile devices using XML web services over the Internet. Server-to-Server: Independent server applications can use XML web services as a common interface to share and exchange data. Service-to-Service: Systems that work together to deliver complex data processing can be created using XML web services. The following figure shows an example of services exposed using web services, which deliver their functionality to a wide variety of platforms and applications. Service-oriented architecture provides us with the maximum flexibility in building applications. Individual services define specific application functions and interact with one another to provide the entire business process functionality. Encapsulation: Just as an object encapsulates its internal implementation details inside while providing public methods to external objects, services encapsulate their internal complexity and implementation from the service consumers who don't have to know the internal details. Mobility: As services are independent and encapsulated, they can be deployed in any location. Since they are using the same standard communication language, they are accessed in the same way irrespective of their physical location or implementation details. Parallel development: A service-oriented application is built using several service layers and clients. These application components can be built in parallel by developers specialized in specific layer functionality, speeding up the development process. Platform independence: Service providers and service consumers can be written in any language and deployed on any platform, as long as they can speak the standard communication language. Security: More security can be added to a service-oriented application at the service interface layer. Different application components require different security levels. The security can be enforced by using firewalls configured to allow access only to the required service providers only by the required service consumers. In addition, by using Web Service Enhancements (WSE), authentication, authorization, and encryption can be easily added. Reusability: Once a service is constructed and deployed, it can be used by any other service consumer without problems related to platform integration and interoperability. Choosing an Application Architecture Now that we have seen the existing application architectures, we must choose one that meets our project requirements. As you may have guessed by this point, the best application architecture we can use for our project is a Service-Oriented Architecture (SOA). The SOA allows us to build a distributed system, a system that has great flexibility and interoperability with other systems on other platforms. This will allow us to build the business logic functions and expose them as services that will be used by higher functionality layers. Choosing an Application Platform After choosing our application architecture, we must choose a platform capable of building and supporting it. For the purpose of our system we will choose the Microsoft .NET Framework platform and build the system using Microsoft Visual Studio.NET 2005 and Microsoft SQL Server as the back-end database for storing the data. Microsoft .NET Framework From a Service-Oriented Architecture point of view, the .NET Framework is the Microsoft strategy for connecting systems, information, and devices through software such as web services. .NET technology provides the capability to quickly build, deploy, manage, and use connected, security-enhanced solutions through the use of web services. Intrinsically, the .NET Framework is an environment for development and execution that allows different programming languages and libraries to work together to create Windows-based applications that are easier to build, manage, deploy, and integrate with other networked systems. The .NET core components are: The Common Language Runtime (CLR): A language-neutral development and execution environment that provides a consistent model and services to manage application execution that includes: Support for different programming languages: A variety of over 20 programming languages that target the CLR, such as C#, VB.NET, and J#, can be used to develop applications. Support for libraries developed in different languages: Libraries developed in different languages integrate seamlessly, making application development faster and easier. Support for different platforms: .NET applications are not tied to a single platform and can be executed on any platform that supports the CLR. Enhanced security: The .NET Code Access Security model provides a managed environment for application execution and security. Automatic resource management: The CLR automatically handles process, memory, and thread management, enabling developers to focus on the core business logic code.   The Framework Class Libraries (FCL): An object-oriented library of classes that extends a wide range of functionality including: Support for basic operations: Input/output and string management, standard network protocols, and network standards such as TCP/IP, XML, SOAP, and HTTP are supported natively to allow basic operations and system connections. Support for data access and data manipulation: The FCL includes a range of data access and data manipulation classes forming the ADO.NET technology that natively supports XML and data environments such as SQL Server and Oracle. Support for desktop applications: Rich desktop and mobile client applications can be easily created using the Windows Forms technology. Support for web applications: Thin web clients, websites, and web services can be created using web forms and XML web services technologies that form ASP.NET.   In the planning phase we've gathered the project requirements and specifications and we've also chosen an application architecture. The next phase is the design phase. Designing the System In the design phase, we will create an application design based on the application architecture, project requirements, and specifications. Gathering all the information needed to design the system is a difficult task, but the most important step is to start writing down the first idea. System Structure The system will be composed from the following main component categories: Core components (Data Access Layer, Business Logic Layer) forming the middle-tier component layers. Web service components (XML Web service) forming the Service Interface layer. Website components (ASP.NET website) forming the front-end WebReservation application, a web presentation layer. Windows Application components (Windows Forms Application) forming the WinReservation application, a Windows presentation layer. The following figure illustrates the overall system structure, outlining each system component: As we saw earlier, one major advantage of a service-oriented application is the decoupling of the presentation layer from the business logic layer. This allows for the business logic layer being exposed as a web service to be used by other third parties to integrate its functionality into their business process. Database Structure The back-end database is hosted by a Microsoft SQL Server system. According to the project specifications the internal database structure will be composed of the following database tables: User (Contains the user accounts) Guest (Contains the personal details of the guests) Room (Contains the details of each of the hotel's rooms) Reservation (Contains the details of the reservation made by each user) The following figure illustrates these tables and the relations between them. The bold fields are mandatory (not NULL). The User table contains the following rows:    
Read more
  • 0
  • 0
  • 4652
article-image-creating-accessible-tables-joomla
Packt
22 Oct 2009
5 min read
Save for later

Creating Accessible Tables in Joomla!

Packt
22 Oct 2009
5 min read
Creating Accessible Tables Tables got a bad review in accessibility circles, because they used to create complex visual layouts. This was due to the limitations in the support for presentational specifications like CSS and using tables for layout was a hack—that worked in the real world—when you wanted to position something in a precise part of the web page. Tables were designed to present data of all shapes and sizes, and that is really what they should be used for. The Trouble with Tables So what are tables like for screen reader users? Tables often contain a lot of information, so sighted users need to look at the information at the top of the table (the header info), and sometimes the first column in each row to associate each data cell. Obviously this works for sighted users, but in order to make the tables accessible to a screen reader user we need to find a way of associating the data in each cell with its correct header so the screen reader can inform the user which header relates to each data cell. Screen reader users can navigate between data cells easily using the cursor keys. We will see how to make tables accessible in simple steps. There are methods of conveying the meaning and purpose of a table to the screen reader user by using the caption element and the summary attribute of the table element that you will find more on in the next section. We will learn how to build a simple table using Joomla! and the features contained within the WYSIWYG editors that can make the table more accessible. Before we do that though I want you to ask yourself about why you want to use tables (though sometimes it is unavoidable) and what forms should they take. Simple guidelines for tables: Try to make the table as simple as possible.    If possible don't span multiple cells etc. The simpler the table, the easier it is to make accessible.    Try to include the data you want to present in the body text of your site. Time for Action—Create an Accessible Table (Part 1) In the following example we will build a simple table that will list the names of some artists, some albums they have recorded, and the year in which they recorded the albums. First of all click the table icon from the TinyMCE interface and add a table with a suitable number of columns and rows.            By clicking on the Advanced tab you will see the Summary field. The summary information is very important. It provides the screen reader user a summary of the table. For example, I filled in the following text: "A list of some funk artists, my favorite among their records, and the year they recorded it in". My table then looked as follows: What Just Happened? There is still some work to be done in order to make the content more accessible. The controls that the WYSIWYG editor offers are also a little limited so we will have to edit the HTML by hand. Adding the summary information is a very good start. The text that I entered "A list of some funk artists, my favorite among their records, and the year they recorded it in." will be read out by the screen reader as soon as it receives a focus by the user. Time for Action—Create an Accessible Table (Part 2) Next we are going to add a Caption to the table, which will be helpful to both sighted and non-sighted users. This is how it's done. Firstly, select the top row of the table, as these items are the table heading. Then click on the Table Row properties icon beside the Tables icon and select Table Head under General Properties. Make sure that the Update current Row is selected in the dialogue box in the bottom left. You will apply these properties to your selected row. If you wish to add a caption to your table you need to add an extra row to the table and then select the contents of that row and add the Caption in the row properties dialogue box. This will tell the browser to display the caption text, in this case Funky Table Caption, else it will remain hidden. What Just Happened? By adding caption to the table, you provide useful information to the screen reader user. This caption should be informative and should describe something useful about the table. As the caption element is wrapped in a heading it is read out by the screen reader when the user starts exploring the table—so it is slightly different to the summary attribute, which is read out automatically. Does it Work? What we just did using the WYSIWYG editor, TinyMCE, is enough to make a good start towards creating a more accessible table, but we will have to work a little more in order to truly make the table accessible. So we will now edit the HTML. The good news is that you have made some good steps in the right direction and the final step is of associating the data cells with their suitable headers, as this is something that we cannot really do with the WYSIWYG editor alone, and is essential to make your tables truly accessible.
Read more
  • 0
  • 0
  • 2244

article-image-themes-e107
Packt
22 Oct 2009
4 min read
Save for later

Themes in e107

Packt
22 Oct 2009
4 min read
What is a Theme? Back in the mid 1970s, programming code became so immense that changing even the smallest part of a piece of code could have unpredictable effects in the other areas of the program. This led to the development of a concept called modular programming, which essentially broke the program down into smaller more manageable junks that were called upon by the main program when needed. The term for modular programming these days is separation of concerns or SoC. But no matter what you call it, this is its function. In e107 a theme contains a set of modular code containing XHTML (eXtensible HyperText Markup Language) and CSS (Cascading Style Sheets). In its most basic explanation, XHTML allows us to take a text document, create a link to other documents, and the eXtensible part of the language allows you to create your own tags describing data. Thus a program like e107 can use these tags to extract the information it needs. The data shouldn’t show up on the screen like a computer printout; CSS is employed to define the layout of the various elements and tags such that they may be viewed with consistency by all browsers. The screenshot below shows you the theme files that are available in e107 on the left, and the typical files and folders that make up a particular theme on the right. They say a picture is worth a thousand words so I have used the PHP code that makes up the Reline theme, which is what we are using for our front end. Open up your FTP client and go to /public_html/e107_themes/reline/. Locate the file theme.php and use your FTP client's view/edit feature to open the file. As you can see, there is a fair amount of work that goes into creating a theme. If you want to design your own themes, I strongly recommend that you are thoroughly familiar with PHP, XHTML, and CSS before making the attempt. We won't be tackling theme making in this article. We completely need a different book for that subject; however, if you have the knowledge and want to create your own theme you can find information in the WIKI at http://wiki.e107.org/?title=Creating_a_theme_from_scratch. But I wanted to show you that these themes take effort so you will appreciate those who take the time to develop themes, especially those who develop themes and share them at no charge. Remember to thank them, encourage them, and offer to send a little money if you like the theme and can use it. It is not a requirement but it encourages more development. For more information on customizing your website, visit: ThemesWiki.org Understanding the Theme Layout The first thing you can to do is log in as administrator and select Admin Area | Menus. The screenshot below shows the correlation between the areas displayed on the administrator's menu items control page and those on the non-administrator page. Psychology of Color One of the biggest mistakes people make is to choose their theme based on their personal preferences for layout and colors. You can have the perfect layout and great material on your site and yet, people will just not like the site. So you need to ask yourself, "why do people not like my site?" or "why aren't they buying from my site?" The answer is probably that your theme uses a color that is sending out a very different message to your viewers' brains. This is a subject of protracted discussion and there are college courses on this subject. Professionally it is referred to as psychology of color. Your best bet for online information on colors is at http://www.pantone.com. Selecting a Theme Sometimes, the default theme does not quite convey the style you want for your site. While functionality is always the primary consideration, it does not mean that you have to abandon your sense of style just because you are using a CMS. There are three types of themes available for e107. These are the core themes, additional themes (located at http://www.e107themes.org), and custom themes.
Read more
  • 0
  • 0
  • 2497

article-image-search-engine-optimization-joomla
Packt
22 Oct 2009
8 min read
Save for later

Search Engine Optimization in Joomla!

Packt
22 Oct 2009
8 min read
What is SEO? Search-engine optimization, or SEO, refers to the process of preparing your website to be spidered, indexed, and ranked by the major search engines so that when Internet users search for your keywords, your website will appear on their results page. Proper search engine optimization is a crucial step to ensure success and should be undertaken with care and diligence. It should also be noted that SEO is an interdisciplinary concern, combining web design functions with marketing and promotional concerns. If aimed properly, SEO would be a powerful weapon in your arsenal. Proper SEO is: Optimizing META data Optimizing page titles Optimizing page content Selecting proper keywords Testing your optimizations Promoting link popularity Using standards-compliant HTML Optimizing image ALT tags Using a logical website structure Validating your content Proper SEO isn't: Keyword spamming Hidden text Cloaking content Link-farming Excessive content or site duplication Paying for questionable links Structural Optimization Optimizing your site's actual structure and presentation is the most immediate approach to SEO. Since these factors are under the immediate control of the webmaster, they represent a foundational approach to the SEO problem. Once you've optimized your site's structural components, you can optimize the promotional aspects of SEO, which we'll discuss momentarily. Items That Search Engines Look for in Your Site's Content It's important to remember that today's search engine rankings are determined by highly sophisticated algorithms. Trying to stay one step ahead of the major engines with bad tactics is not only a very bad idea, but also a waste of time. Well written content will win repeatedly. Giving the search engine robots a well prepared sitepage contributes in promoting your site. Three items that many search engine robots look for are: Relevant page titles to your content Relevant keywords and descriptions (META tags) Relevant, keyword-rich content, presented in clean and valid HTML Take a note of the recurring theme—"relevancy". If your site is relevant in terms of what the user is looking for, you will achieve respectable search engine rankings without any additional promotion. However, this is not a place to stop, as search engines correlate your site's standings among your peers and competitors by evaluating certain external factors. External Views of Your Site by Search Engines Search giant, Google, likes to describe its proprietary algorithm, known as PageRankTM, by discussing how the external factors can accurately define your site's relevancy, when considered along with your site's actual content. Most search engines today follow this formula in determining link popularity. Some popular items that are used to measure are: How many websites link to yours Where they link in your content What words are used in the actual link text (i.e. the description of the page) The topical relevancy of the sites that link to your site The power of web search lies in the search engine's ability to provide accurate and relevant results that someone can quickly use to find the information they seek. More importantly, the other end of the search process guarantees that the visitors we draw from search engines are truly after the information or services we provide. Another way to look at it would be it's the right message, but the wrong person. Thus we see that our interests, the interests of the search engines, and the interests of web surfers actually coincide! If we tune our content properly, and connect our content with similarly relevant content, we can expect to be rewarded with targeted traffic eager to devour our information and buy our services. If we try to deceive the search engines, or common people, we deceive ourselves. It's that simple. Optimizing META Data Metadata is the data about the data. It's the section where you define what a search engine should expect to find on your page. If you've never taken note of META tags before, then take a brief tour of the Web and view the source code of several websites. You'll see how this data is organized, primarily into descriptions and keyword listings. Joomla! provides functionality for modifying and dynamically generating META tags, in the Site | Global Configuration | Metadata dialog, as well as within individual articles via the META tab on the right-hand panel. This is where the dynamic aspect of metadata becomes important—your main page will have certain needs for proper META optimization and your individual Joomla! content articles will require special tuning to make the best of their potential. This is accomplished though key words and phrases scattered through out the text. Keep in mind that each search engine is different; however keeping ratio of about 3 to 1 for keywords and META (keyword) in the top 1/3rd of the page is a decent rule of thumb. Using the Site | Global Configuration | Metadata dialog, is pretty straight forward.You can enter descriptions, keywords and key phrases that are pertinent to your siteon a global level. You should select the META keywords based on the keywords appearing in your content with the greatest frequency. Be honest and use META keywords that actually appear in your content. Search engines penalize you for over use of keywords, known as keyword stuffing. Title Optimization What's in the actual title of your page? The keywords you insert into your site and article's titles play a huge role in successful search engine optimization. As with META tags, the key is to insert frequently-used, but not stuffed, keywords into your title, which correlate the relevancy of the site's title (what we say about our site)with the metadata (how we describe what it's about) and the actual content, which is indisputably "what the website is about". Content Optimization Writing clear content that uses pertinent language in our intended message or service is the key to content optimization. In your content, include naturally-written, keyword-rich content. This will tie into your META tags, title description and other portions of your site to help you achieve content relevance and thus higher search engine rankings. One note of caution—while we use our best keywords frequently within our text; we should not cram these words into our content. So don't be afraid to break out the thesaurus and include some alternative words and descriptions! Good content SEO is about achieving a balance between what the search engines see, and what your readers expect on arrival. Keyword Research and Optimization Researching our keywords not only gives us an idea of how our competitors are optimizing their websites, but also gives us a treasure-trove of alternative keywords that we can use to further optimize our own sites. There are several online tools that can give us an idea of what keywords are most typically searched for, and how the end-users phrase their searches. This provides avital two-way pathway into the visitor's minds, showing not only how they reach the products and information they seek, but also how they perceive those items. You can find a listing of free keyword research tools at:http://www.joomlawarrior.com. For our example, we'll use Google's freely available keyword suggestion tool for its AdWords program, and use Joomla! itself as our intended optimization candidate.See http://www.google.com/adwords for the keyword tool. The following example will demonstrate the AdWords tool and how it helps you determine good keywords for your site. Entering joomla into Google's keyword suggestion tool yields the following display: The three key pieces of information as seen in the previous figure, which help us inmaking a decision about keywords, are as follows: Keywords: This column indicates the keyword whose Search Volume and Advertiser Competition we want to check. Advertiser Competition: This is graphical indicator of how many ads are in rotation for this keyword. Search Volume: Graphical indication of how many people in the world are searching this keyword for a product or service. As we see from the example, when we search for the keyword joomla we see a lower Advertiser Competition than content management system, but a higher SearchVolume. If we then examine open source we see a heavy Advertiser Competition, but the same Search Volume as joomla. What this means is that if we advertise in the crowded keyword space—"open source", we can expect a lot of competition. Changing our keyword to Joomla! would give us less competition and about the same Search Volume. If we advertise something related to Joomla! then that would be the best choice. However, if we were advertising a tool for open source, we would want to spend our money on the keyword "open source". The last take away from this is if we are selling a joomla template, you see from the figure that there isn't much competition (at the time thiswas taken), but a healthy amount of Search Volume.
Read more
  • 0
  • 0
  • 2232
article-image-enterprise-javabeans
Packt
22 Oct 2009
10 min read
Save for later

Enterprise JavaBeans

Packt
22 Oct 2009
10 min read
Readers familiar with previous versions of J2EE will notice that Entity Beans were not mentioned in the above paragraph. In Java EE 5, Entity Beans have been deprecated in favor of the Java Persistence API (JPA). Entity Beans are still supported for backwards compatibility; however, the preferred way of doing Object Relational Mapping with Java EE 5 is through JPA. Refer to Chapter 4 in the book Java EE 5 Development using GlassFish Application Server for a detailed discussion on JPA. Session Beans As we previously mentioned, session beans typically encapsulate business logic. In Java EE 5, only two artifacts need to be created in order to create a session bean: the bean itself, and a business interface. These artifacts need to be decorated with the proper annotations to let the EJB container know they are session beans. Previous versions of J2EE required application developers to create several artifacts in order to create a session bean. These artifacts included the bean itself, a local or remote interface (or both), a local home or a remote home interface (or both) and a deployment descriptor. As we shall see in this article, EJB development has been greatly simplified in Java EE 5. Simple Session Bean The following example illustrates a very simple session bean: package net.ensode.glassfishbook; import javax.ejb.Stateless; @Stateless public class SimpleSessionBean implements SimpleSession { private String message = "If you don't see this, it didn't work!"; public String getMessage() { return message; } } The @Stateless annotation lets the EJB container know that this class is a stateless session bean. There are two types of session beans, stateless and stateful. Before we explain the difference between these two types of session beans, we need to clarify how an instance of an EJB is provided to an EJB client application. When EJBs (both session beans and message-driven beans) are deployed, the EJB container creates a series of instances of each EJB. This is what is typically referred to as the EJB pool. When an EJB client application obtains an instance of an EJB, one of the instances in the pool is provided to this client application. The difference between stateful and stateless session beans is that stateful session beans maintain conversational state with the client, where stateless session beans do not. In simple terms, what this means is that when an EJB client application obtains an instance of a stateful session bean, the same instance of the EJB is provided for each method invocation, therefore, it is safe to modify any instance variables on a stateful session bean, as they will retain their value for the next method call. The EJB container may provide any instance of an EJB in the pool when an EJB client application requests an instance of a stateless session bean. As we are not guaranteed the same instance for every method call, values set to any instance variables in a stateless session bean may be "lost" (they are not really lost; the modification is in another instance of the EJB in the pool). Other than being decorated with the @Stateless annotation, there is nothing special about this class. Notice that it implements an interface called SimpleSession. This interface is the bean's business interface. The SimpleSession interface is shown next: package net.ensode.glassfishbook; import javax.ejb.Remote; @Remote public interface SimpleSession { public String getMessage(); } The only peculiar thing about this interface is that it is decorated with the @Remoteannotation. This annotation indicates that this is a remote business interface . What this means is that the interface may be in a different JVM than the client application invoking it. Remote business interfaces may even be invoked across the network. Business interfaces may also be decorated with the @Local interface. This annotation indicates that the business interface is a local business interface. Local business interface implementations must be in the same JVM as the client application invoking their methods. As remote business interfaces can be invoked either from the same JVM or from a different JVM than the client application, at first glance, we might be tempted to make all of our business interfaces remote. Before doing so, we must be aware of the fact that the flexibility provided by remote business interfaces comes with a performance penalty, because method invocations are made under the assumption that they will be made across the network. As a matter of fact, most typical Java EE application consist of web applications acting as client applications for EJBs; in this case, the client application and the EJB are running on the same JVM, therefore, local interfaces are used a lot more frequently than remote business interfaces. Once we have compiled the session bean and its corresponding business interface,we need to place them in a JAR file and deploy them. Just as with WAR files, the easiest way to deploy an EJB JAR file is to copy it to [glassfish installationdirectory]/glassfish/domains/domain1/autodeploy. Now that we have seen the session bean and its corresponding business interface, let's take a look at a client sample application: package net.ensode.glassfishbook; import javax.ejb.EJB; public class SessionBeanClient { @EJB private static SimpleSession simpleSession; private void invokeSessionBeanMethods() { System.out.println(simpleSession.getMessage()); System.out.println("nSimpleSession is of type: " + simpleSession.getClass().getName()); } public static void main(String[] args) { new SessionBeanClient().invokeSessionBeanMethods(); } } The above code simply declares an instance variable of type net.ensode.SimpleSession, which is the business interface for our session bean. The instance variable is decorated with the @EJB annotation; this annotation lets the EJB container know that this variable is a business interface for a session bean. The EJB container then injects an implementation of the business interface for the client code to use. As our client is a stand-alone application (as opposed to a Java EE artifact such as a WAR file) in order for it to be able to access code deployed in the server, it must be placed in a JAR file and executed through the appclient utility. This utility can be found at [glassfish installation directory]/glassfish/bin/. Assuming this path is in the PATH environment variable, and assuming we placed our client code in a JAR file called simplesessionbeanclient.jar, we would execute the above client code by typing the following command in the command line: appclient -client simplesessionbeanclient.jar Executing the above command results in the following console output: If you don't see this, it didn't work! SimpleSession is of type: net.ensode.glassfishbook._SimpleSession_Wrapper which is the output of the SessionBeanClient class. The first line of output is simply the return value of the getMessage() method we implemented in the session bean. The second line of output displays the fully qualified class name of the class implementing the business interface. Notice that the class name is not the fully qualified name of the session bean we wrote; instead, what is actually provided is an implementation of the business interface created behind the scenes by the EJB container. A More Realistic Example In the previous section, we saw a very simple, "Hello world" type of example. In this section, we will show a more realistic example. Session beans are frequently used as Data Access Objects (DAOs). Sometimes, they are used as a wrapper for JDBC calls, other times they are used to wrap calls to obtain or modify JPA entities. In this section, we will take the latter approach. The following example illustrates how to implement the DAO design pattern in asession bean. Before looking at the bean implementation, let's look at the business interface corresponding to it: package net.ensode.glassfishbook; import javax.ejb.Remote; @Remote public interface CustomerDao { public void saveCustomer(Customer customer); public Customer getCustomer(Long customerId); public void deleteCustomer(Customer customer); } As we can see, the above is a remote interface implementing three methods; thesaveCustomer() method saves customer data to the database, the getCustomer()method obtains data for a customer from the database, and the deleteCustomer() method deletes customer data from the database. Let's now take a look at the session bean implementing the above business interface. As we are about to see, there are some differences between the way JPA code is implemented in a session bean versus in a plain old Java object. package net.ensode.glassfishbook; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.sql.DataSource; @Stateless public class CustomerDaoBean implements CustomerDao { @PersistenceContext private EntityManager entityManager; @Resource(name = "jdbc/__CustomerDBPool") private DataSource dataSource; public void saveCustomer(Customer customer) { if (customer.getCustomerId() == null) { saveNewCustomer(customer); } else { updateCustomer(customer); } } private void saveNewCustomer(Customer customer) { customer.setCustomerId(getNewCustomerId()); entityManager.persist(customer); } private void updateCustomer(Customer customer) { entityManager.merge(customer); } public Customer getCustomer(Long customerId) { Customer customer; customer = entityManager.find(Customer.class, customerId); return customer; } public void deleteCustomer(Customer customer) { entityManager.remove(customer); } private Long getNewCustomerId() { Connection connection; Long newCustomerId = null; try { connection = dataSource.getConnection(); PreparedStatement preparedStatement = connection .prepareStatement( "select max(customer_id)+1 as new_customer_id " + "from customers"); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet != null && resultSet.next()) { newCustomerId = resultSet.getLong("new_customer_id"); } connection.close(); } catch (SQLException e) { e.printStackTrace(); } return newCustomerId; } } The first difference we should notice is that an instance of javax.persistence. EntityManager is directly injected into the session bean. In previous JPA examples,we had to inject an instance of javax.persistence.EntityManagerFactory, then use the injected EntityManagerFactory instance to obtain an instance of EntityManager. The reason we had to do this was that our previous examples were not thread safe. What this means is that potentially the same code could be executed concurrently by more than one user. As EntityManager is not designed to be used concurrently by more than one thread, we used an EntityManagerFactory instance to provide each thread with its own instance of EntityManager. Since the EJB container assigns a session bean to a single client at time, session beans are inherently thread safe, therefore, we can inject an instance of EntityManager directly into a session bean. The next difference between this session bean and previous JPA examples is that in previous examples, JPA calls were wrapped between calls to UserTransaction.begin() and UserTransaction.commit(). The reason we had to do this is because JPA calls are required to be in wrapped in a transaction, if they are not in a transaction, most JPA calls will throw a TransactionRequiredException. The reason we don't have to explicitly wrap JPA calls in a transaction as in previous examples is because session bean methods are implicitly transactional; there is nothing we need to do to make them that way. This default behavior is what is known as Container-Managed Transactions. Container-Managed Transactions are discussed in detail later in this article. When a JPA entity is retrieved in one transaction and updated in a different transaction, the EntityManager.merge() method needs to be invoked to update the data in the database. Invoking EntityManager.persist() in this case will result in a "Cannot persist detached object" exception.
Read more
  • 0
  • 0
  • 2635

article-image-data-processing-using-derived-column-and-aggregate-data-transformations
Packt
22 Oct 2009
3 min read
Save for later

Data Processing using Derived Column and Aggregate Data Transformations

Packt
22 Oct 2009
3 min read
Details of Data Processing: This package accomplishes the following: Connect to the SQL Server 2005 and access the MyNorthwind (a copy of the Northwind) database. A Data Reader Source will extract data using the following query: Select orderID, quantity, UnitPrice from [Order details] A Derived Column data transformation will add a column to the data flow which contains a combination of data from two other columns. A Conditional Split transformation divides the data flow into two flows based on a certain value in the derived column. The rows that satisfies the condition are captured in a recordset destination. The rest of the flow (bad data) gets routed to the next processor, the Aggregate Transformation. The Aggregate transformation orders the data coming into it showing group averages of the derived column. This grouped data then gets into a recordset destination. Although the final data ends up in recordset destinations, they can also be persisted to other destinations such as Data Reader, OLEDB and File system. Implementation in the Visual Studio 2005 Designer Before going into the details of the data processing let us take a look at the building blocks from the VS 2005 Toolbox that can be used to implement it and the interconnections between the building blocks. In addition to the data flow controls three data viewers are also inserted to stop and inspect the data before it goes any further. Data Extraction The data is extracted from MyNorthwind database on the SQL Server 2005. While configuring the Data Reader, you make use of a Connection Manager. The details of this Connection Manager is shown in its editor as in the next figure. The connection uses the SqlClient Data Provider. The SQL Server is a default installation with the name [.] and as it is set for SQL Server authentication username and password are required. The database connection is chosen from the drop-down as shown. The connectivity test can be performed and it now allows the data reader to extract data from the database. The Data Reader is added to the design surface by double clicking the control in the Toolbox. The Data Reader uses the connection manager to access the SQL Server as you see in the next figure in its Connection Manager's tab. The Data Reader's Property shows some of the other configuration details made by the other tabs in the above editor. In particular it shows the query used in extracting the data. It extracts three columns from the Order Details table in the MyNorthwind database and provides this to the next component in the data processing implementation.    
Read more
  • 0
  • 0
  • 4429
Modal Close icon
Modal Close icon