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
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - Programming

1083 Articles
article-image-arrays-and-control-structures-object-oriented-javascript
Packt
16 Oct 2009
4 min read
Save for later

Arrays and Control Structures in Object-Oriented JavaScript

Packt
16 Oct 2009
4 min read
Arrays Now that you know the basic primitive data types in JavaScript, it's time to move to a more interesting data structure—the array. To declare a variable that contains an empty array, you use square brackets with nothing between them: >>> var a = [];>>> typeof a;"object" typeof returns "object", but don't worry about this for the time being, we'll get to that when we take a closer look at objects. To define an array that has three elements, you do this: >>> var a = [1,2,3]; When you simply type the name of the array in the Firebug console, it prints the contents of the array: >>> a[1, 2, 3] So what is an array exactly? It's simply a list of values. Instead of using one variable to store one value, you can use one array variable to store any number of values as elements of the array. Now the question is how to access each of these stored values? The elements contained in an array are indexed with consecutive numbers starting from zero. The first element has index (or position) 0, the second has index 1 and so on. Here's the three-element array from the previous example: Index Value 0 1 1 2 2 3 In order to access an array element, you specify the index of that element inside square brackets. So a[0] gives you the first element of the array a, a[1] gives you the second, and so on. >>> a[0]1>>> a[1]2 Adding/Updating Array Elements Using the index, you can also update elements of the array. The next example updates the third element (index 2) and prints the contents of the new array. >>> a[2] = 'three';"three">>> a[1, 2, "three"] You can add more elements, by addressing an index that didn't exist before. >>> a[3] = 'four';"four">>> a[1, 2, "three", "four"] If you add a new element, but leave a gap in the array, those elements in between are all assigned the undefined value. Check out this example: >>> var a = [1,2,3];>>> a[6] = 'new';"new">>> a[1, 2, 3, undefined, undefined, undefined, "new"] Deleting Elements In order to delete an element, you can use the delete operator. It doesn't actually remove the element, but sets its value to undefined. After the deletion, the length of the array does not change. >>> var a = [1, 2, 3];>>> delete a[1];true>>> a[1, undefined, 3] Arrays of arrays An array can contain any type of values, including other arrays. >>> var a = [1, "two", false, null, undefined];>>> a[1, "two", false, null, undefined]>>> a[5] = [1,2,3][1, 2, 3]>>> a[1, "two", false, null, undefined, [1, 2, 3]] Let's see an example where you have an array of two elements, each of them being an array. >>> var a = [[1,2,3],[4,5,6]];>>> a[[1, 2, 3], [4, 5, 6]] The first element of the array is a[0] and it is an array itself. >>> a[0][1, 2, 3] To access an element in the nested array, you refer to the element index in another set of square brackets. >>> a[0][0]1>>> a[1][2]6 Note also that you can use the array notation to access individual characters inside a string. >>> var s = 'one';>>> s[0]"o">>> s[1]"n">>> s[2]"e" There are more ways to have fun with arrays, but let's stop here for now, remembering that: An array is a data store An array contains indexed elements Indexes start from zero and increment by one for each element in the array To access array elements we use the index in square brackets An array can contain any type of data, including other arrays
Read more
  • 0
  • 0
  • 5531

article-image-primer-agi-asterisk-gateway-interface
Packt
16 Oct 2009
2 min read
Save for later

A Primer to AGI: Asterisk Gateway Interface

Packt
16 Oct 2009
2 min read
How does AGI work Let's examine the following diagram: As the previous diagram illustrates, an AGI script communicates with Asterisk via two standard data streams—STDIN (Standard Input) and STDOUT (Standard Output). From the AGI script point-of-view, any input coming in from Asterisk would be considered STDIN, while output to Asterisk would be considered as STDOUT. The idea of using STDIN/STDOUT data streams with applications isn't a new one, even if you're a junior level programmer. Think of it as regarding any input from Asterisk with a read directive and outputting to Asterisk with a print or echo directive. When thinking about it in such a simplistic manner, it is clear that AGI scripts can be written in any scripting or programming language, ranging from BASH scripting, through PERL/PHP scripting, to even writing C/C++ programs to perform the same task. Let's now examine how an AGI script is invoked from within the Asterisk dialplan: exten => _X.,1,AGI(some_script_name.agi,param1,param2,param3) As you can see, the invocation is similar to the invocation of any other Asterisk dialplan application. However, there is one major difference between a regular dialplan application and an AGI script—the resources an AGI script consumes.While an internal application consumes a well-known set of resources from Asterisk, an AGI script simply hands over the control to an external process. Thus, the resources required to execute the external AGI script are now unknown, while at the same time, Asterisk consumes the resources for managing the execution of the AGI script.Ok, so BASH isn't much of a resource hog, but what about Java? This means that the choice of programming language for your AGI scripts is important. Choosing the wrong programming language can often lead to slow systems and in most cases, non-operational systems. While one may argue that the underlying programming language has a direct impact on the performance of your AGI application, it is imperative to learn the impact of each. To be more exact, it's not the language itself, but more the technology of the programming language runtime that is important. The following table tries to distinguish between three programming languages' families and their applicability to AGI development.
Read more
  • 0
  • 0
  • 6544

article-image-jbi-binding-components-netbeans-ide-6
Packt
16 Oct 2009
4 min read
Save for later

JBI Binding Components in NetBeans IDE 6

Packt
16 Oct 2009
4 min read
Binding Components Service Engines are pluggable components which connect to the Normalized Message Router (NMR) to perform business logic for clients. Binding components are also standard JSR 208 components that plug in to NMR and provide transport independence to NMR and Service Engines. The role of binding components is to isolate communication protocols from JBI container so that Service Engines are completely decoupled from the communication infrastructure. For example, BPEL Service Engine can receive requests to initiate BPEL process while reading files on the local file system. It can receive these requests from SOAP messages, from a JMS message, or from any of the other binding components installed into JBI container. Binding Component is a JSR 208 component that provides protocol independent transport services to other JBI components. The following figure shows how binding components fit into the JBI Container architecture: In this figure, we can see that the role of BC is to send and receive messages both internally and externally from Normalized Message Router using protocols, specific to the binding component. We can also see that any number of binding components can be installed into the JBI container. This figure shows that like Service Engines (SE), binding components do not communicate directly with other binding components or with Service Engines. All communication between individual binding components and between binding components and Service Engines is performed via sending standard messages through the Normalized Message Router. NetBeans Support for Binding Components The following table lists which binding components are installed into the JBI container with NetBeans 5.5 and NetBeans 6.0:   As is the case with Service Engines, binding components can be managed within the NetBeans IDE. The list of Binding Components installed into the JBI container can be displayed by expanding the Servers | Sun Java System Application Server 9 | JBI | Binding Components node within the Services explorer. The lifecycle of binding components can be managed by right-clicking on a binding component and selecting a lifecycle process—Start, Stop, Shutdown, or Uninstall. The properties of an individual binding component can also be obtained by selecting the Properties menu option from the context menu as shown in the following figure. Now that we've discussed what binding components are, and how they communicate both internally and externally to the Normalized Message Router, let's take a closer look at some of the more common binding components and how they are accessed and managed from within the NetBeans IDE. File Binding Component The file binding component provides a communications mechanism for JBI components to interact with the file system. It can act as both a Provider by checking for new files to process, or as a Consumer by outputting files for other processes or components. The figure above shows the file binding component acting as a Provider of messages. In this scenario, a message has been sent to the JBI container, and picked up by a protocol-specific binding component (for example, a SOAP message has been received). A JBI Process then occurs within the JBI container which may include routing the message between many different binding components and Service Engines depending upon the process. Finally, after the JBI Process has completed, the results of the process are sent to File Binding Component which writes out the result to a file. The figure above shows the file binding component acting as a Consumer of messages. In this situation, the File Binding Component is periodically polling the file system looking for files with a specified filename pattern in a specified directory. When the binding component finds a file that matches its criteria, it reads in the file and starts the JBI Process, which may again cause the input message to be routed between many different binding components and Service Engines. Finally, in this example, the results of the JBI Process are output via a Binding Component. Of course, it is possible that a binding component can act as both a provider and a consumer within the same JBI process. In this case, the file binding component would be initially responsible for reading an input message from the file system. After any JBI processing has occurred, the file binding component would then write out the results of the process to a file. Within the NetBeans Enterprise Pack, the entire set of properties for the file binding component can be edited within the Properties window. The properties for the binding component are displayed when either the input or output messages are selected from the WSDL in a composite application as shown in the following figure.
Read more
  • 0
  • 0
  • 1826

article-image-flex-101-flash-builder-4-part-1
Packt
16 Oct 2009
11 min read
Save for later

Flex 101 with Flash Builder 4: Part 1

Packt
16 Oct 2009
11 min read
  The article is intended towards developers who have never used Flex before and would like to exercise a “Hello World” kind of tutorial. The article does not aim to cover Flex and FB4 in detail but rather focuses on the mechanics of FB4 and getting an application running with minimal effort. For developers familiar with Flex and the predecessor to Flash Builder 4 (Flex Builder 2 or 3), it contains an introduction to FB4 and some differences in the way you go about building Flex Applications using FB4. Even if you have not programmed before and are looking at understanding how to make a start in developing applications, this would serve as a good start. The Flex Ecosystem The Flex ecosystem is a set of libraries, tools, languages and a deployment runtime that provides an end-to-end framework for designing, developing and deploying RIAs. All these together are being branded as a part of the Flash platform. In its latest release, Flex 4, special efforts have been put in to address the designer to developer workflow by letting graphic designers address layout, skinning, effects and general look and feel of your application and then the developers taking over to address the application logic, events, etc. To understand this at a high level, take a look at the diagram shown below. This is a very simplified diagram and the intention is to project a 10,000 ft view of the development, compilation and execution process. Let us understand the diagram now: The developer will typically work in the Flash Builder Application. Flash Builder is the Integrated Development Environment (IDE) that provides an environment for coding, compiling, running / debugging your Flex based applications. Your Flex Application will typically consist of MXML and ActionScript code. ActionScript is an ECMAScript compatible Object Oriented language, whereas MXML is an XML-based markup language. Using MXML you can define/layout your visual components like buttons, combobox, data grids, and others. Your application logic will be typically coded inside ActionScript classes/methods. While coding your Flex Application, you will make use of the Flex framework classes that provide most of the core functionality. Additional libraries like Flex Charting libraries and 3rd party components can be used in your application too. Flash Builder compiles all of this into object byte code that can be executed inside the Flash Player. Flash Player is the runtime host that executes your application. This is high level introduction to the ecosystem and as we work through the samples later on in the article, things will start falling into place. Flash Builder 4 Flash Builder is the new name for the development IDE previously known as Flex Builder. The latest release is 4 and it is currently in public beta. Flash Builder 4 is based on the Eclipse IDE, so if you are familiar with Eclipse based tools, you will be able to navigate your way quite easily. Flash Builder 4 like Flex Builder 3 previously is a commercial product and you need to purchase a development license. FB4 currently is in public beta and is available as a 30-day evaluation. Through the rest of the article, we will make use of FB4 and will be focused completely on that to build and run the sample applications. Let us now take a look at setting up FB4. Setting up your Development Environment To setup Flash Builder 4, follows these steps: The first step should be installing Flash Player 10 on your system. We will be developing with the Flex 4 SDK that comes along with Flash Builder 4 and it requires Flash Player 10. You can download the latest version of Flash Player from here: http://www.adobe.com/products/flashplayer/ Download Flash Builder 4 Public Beta from http://labs.adobe.com/technologies/flashbuilder4/. The page is shown below: After you download, run the installer program and proceed with the rest of the installation. Launch the Adobe Flash Builder Beta. It will prompt first with a message that it is a Trial version as shown below: To continue in evaluation mode, select the option highlighted above and click Next. This will launch the Flash Builder IDE. Let us start coding with Flash Builder 4 IDE. We will stick to tradition and write the “Hello World” application. Hello World using Flash Builder 4 In this section, we will be developing a basic Hello World application. While the application does not do much, it will help you get comfortable with the Flash Builder IDE. Launch the Flash Builder IDE. We will be creating a Flex Project. Flash Builder will help us create the Project that will contain all our files. To create a new Flex Project, click on the File → New → Flex Project as shown below: This will bring up a dialog in which you will need to specify more details about the Flex Project that you plan to develop. The dialog is shown below: You will need to provide at least the following information: Project Name: This is the name of your project. Enter a name that you want over here. In our case, we have named our project MyFirstFB4App. Application Type: We can develop both a Web version and a desktop version of our application using Flash Builder. The web application will then run inside of a web browser and execute within the Flash Player plug-in. We will go with the Web option over here. The Desktop application runs inside the Adobe Integrated Runtime environment and can have more desktop like features. We will skip that option for now. We will let the other options remain as is. We will use the Flex 4.0 SDK and currently we are not integrating with any Server side layer so we will leave that option as None/Other. Click on Finish at this point to create your Flex Project. This will create a main application file called MyFirstFB4App.mxml as shown below. We will come back to our coding a little later but first we must familiarize ourselves with the Flash Builder IDE. Let us first look at the Package Explorer to understand the files that have been created for the Flex Project. The screenshot is shown below: It consists of the main source file MyFirstFB4App.mxml. This is the main application file or in other words the bootstrap. All your source files (MXML and ActionScript code along with assets like images, and others should go under the src folder. They can optionally be placed in packages too. The Flex 4.0 framework consists of several libraries that you compile your code against. You would end up using its framework code, components (visual and non-visual) and other classes. These classes are packaged in a library file with an extension .swc. A list of library files is shown above. You do not need to typically do anything with it. Optionally, you can also use 3rd party components written by other companies and developers that are not part of the Flex framework. These libraries are packages as .SWC files too and they can be placed in the libs folder as shown in the previous screenshot. The typical step is to write and compile your code—build your project. If your build is successful, the object code is generated in the bin-debug folder. When you deploy your application to a Web Server, you will need to pickup the contents from this folder. We will come to that a little later. The html-template folder contains some boiler-plate code that contains the container HTML into which your object code will be referenced. It is possible to customize this but for now, we will not discuss that. Double-click MyFirstFB4App.mxml file. This is our main application file. The code listing is given below: <?xml version="1.0" encoding="utf-8"?> <s:Application minWidth="1024" minHeight="768"> </s:Application> As discussed before, you will typically write one or more MXML files that will contain typically your visual components (although there can be non-visual components also). By visual components, we mean controls like button, combobox, list, tree, and others. It could also contain layout components and containers that help you layout your design as per the application screen design. To view what components, you can place on the main application canvas, select the Design View as shown below: Have a look at the lower half of the left pane. You will see the Components tab as shown below, which would address most needs of your Application Visual design. Click on the Controls tree node as shown below. You will see several controls that you can use and from which, we will use the Button control for this application. Simply select the Button control and drag it to the Design View Canvas as shown below: This will drop an instance of the Button control on the Design View as shown below: Select the Button to see its properties panel as shown below. Properties Panel is where you can set several attributes at design time for the control. In case the Properties panel is not visible, you can get to that by selecting Window → Properties from the main menu. In the Properties panel, we can change several key attributes. All controls can be uniquely identified and addressed in your code via the ID attribute. This is a unique name that you need to provide. Go ahead and give it some meaningful name. In our case, we name it btnSayHello. Next we can change the label so that instead of Button, it can display a message for example, Say Hello. Finally we want to wire some code such that if the button is clicked, we can do some action like display a Message Box saying Hello World. To do that, click the icon next to the On click edit field as shown below. It will provide you two options. Select the option for Generate Event Handler. This will generate the code and switch to the Source view. The code is listed below for your reference. <?xml version="1.0" encoding="utf-8"?> <s:Application minWidth="1024" minHeight="768"> <fx:Script> <![CDATA[ protected function btnSayHello_clickHandler(event:MouseEvent):void { // TODO Auto-generated method stub } ]]> </fx:Script> <s:Button x="17" y="14" label="Button" id="btnSayHello" click="btnSayHello_clickHandler(event)"/> </s:Application> There are few things to note here. As mentioned most of your application logic will be written in ActionScript and that is exactly what Flash Builder has generated for you. All such code is typically added inside a scripting block marked with the <fx:Script> tag. You can place your ActionScript methods over here that can be used by the rest of the application. When we clicked on Generate Event Handler, Flash Builder generated the Event Handler code. This code is in ActionScript and was appropriately placed inside the <fx:Script> block for us. If you look at the code, you can see that it has added a function that is invoked when the click event is fired on the button. The method is btnSayHello_clickHandler and if you notice it has an empty method that is, no implementation. Let us run the application now to see what it looks like. To run the application, click on the   Run icon in the main toolbar of Flash Builder. This will launch the web application as shown below. Clicking the Say Hello button will not do anything at this point since there is no code written inside the handler as we saw above. To display the MessageBox, we add the code shown below (Only the Script section is shown below): <fx:Script> <![CDATA[ import mx.controls.Alert; protected function btnSayHello_clickHandler(event:MouseEvent):void { Alert.show("Hello World"); } ]]> </fx:Script> We use one of the classes (called Alert) from the Flex framework. Like any other language, we need to specify which package we are using the class from so that the compiler can understand it. The Alert class belongs to the mx.controls package and it has a static method called show() which takes a single parameter of type String. This String parameter is the message to be displayed and in our case it is "Hello World". To run this, click Ctrl-S to save your file or File →  Save from the main menu. And click on Run icon in the main toolbar. This will launch the application and on clicking the SayHello button, you will see the Hello World Alert window as shown below.
Read more
  • 0
  • 0
  • 3150

article-image-watching-multiple-threads-c
Packt
15 Oct 2009
6 min read
Save for later

Watching Multiple Threads in C#

Packt
15 Oct 2009
6 min read
We can use the BackgroundWorker component and then the Thread class to create new threads independent of the main application thread. The applications can respond to UI events, while the processing continues, and take full advantage of multiple cores, and can thus run faster. However, we are used to debugging applications that run in just one thread (the main thread), and there are many changes in the debugging process that generate great confusion when following the classic procedures running many concurrent threads. How can we successfully debug applications that are running many concurrent threads? Time for action – Understanding the difficulty in debugging concurrent threads Your cellular phone rings! The FBI agents have detected a problem with an encryption engine. When the application receives the same messages many times during a certain period, the encryption process generates exactly the same results, as shown in the following image: Thus, hackers could easily break the code once they discover this important bug. They ask for your help. Of course, you want to cooperate because you do not want the FBI agents to get angry with you. However, you need to debug the multithreaded encryption engine, and you have never done that! Let's create a solution for this problem! First, we are going to try to debug the multithreaded application the same way we do with a single-threaded application to understand the new problems we might face: Open the project, SMSEncryption. Define a breakpoint in the line int liThreadNumber = (int)poThreadParameter; in the ThreadEncryptProcedure procedure code. Press F5 or select Debug | Start Debugging in the main menu. Enter or copy and paste a long text (with more than 5,000 lines) in the Textbox labeled Original SMS Messages and click on the Run in a thread button. The line with the breakpoint defined is shown highlighted as the next statement that will be executed. Press F10 or select, Debug | Step Over in the main menu two or three times (depending on the number of cores you have in the computer). As you can see, the next statement that gets executed is the same even when you try to go on with the next one. It seems that the statement is not being executed. However, inspecting the value of poThreadParameter (the parameter passed to the ThreadEncryptProcedure procedure) shows that it changes each time you step over the statement, as shown in the following image: Stop the application and repeat the steps 1 to 5 to make sure you are not crazy because of parallelism, multithreading, and the FBI agents! What just happened? You are getting nervous about the debugging process! Do not worry. We will learn how to debug your encryption engine while the FBI agents kindly prepare a cup of fresh cappuccino for you. The debugger executed each new Thread class instance call to the Start method, with this line: prloThreadList[liThreadNumber].Start(liThreadNumber); Then, it entered in the ThreadEncryptProcedure method (we have used the same method for every created encryption thread) with different values for the poThreadParameter parameter. Therefore, you stayed in the same statement as many times as the threads were created (equivalent to the number of cores available in the computer) in the following line: int liThreadNumber = (int)poThreadParameter; As we can see, debugging this way is very confusing, because the IDE switches from one thread to another, and you loose control over the statements that are going to be executed next. In a debugging process, you need to know in which part of the application you are. As we tested our first attempt to debug a multithreaded application, we tried the same technique as with single-threaded applications. There are new subjects to learn and new techniques to use. Debugging concurrent threads When we need to inspect values, execute a procedure step-by-step, and find solutions to problems related to some specific code, the best way to achieve that with a multithreaded application is to work with it as a single-threaded application. But, how can we do that? It is very simple. We must run one thread at a time and freeze the other concurrent threads while we are debugging the thread in which we are interested and on which we are focusing. When we debug single-threaded applications, we are aware of the method in which we are positioned and its context. In multithreaded applications, we must also be aware of the thread in which we are positioned. If we do not know in which thread we are executing statements, we will be completely confused in just a few seconds, as happened in our previous activity. We must tailor our multithreaded applications to simplify the debugging process. If we do not do this, the debugging process will be a nightmare. Indeed, we do not want that to happen! Time for action – Finding the threads You wonder where the threads are. How can you guess in which thread you are working while executing the application step-by-step? You are an excellent C# programmer, but multithreaded debugging is very confusing. You do not want the FBI agents to realize that you are in trouble. However, you must hurry up, because they have a great training in detecting nervous people in the course of their usual interrogations. Now, we are going to use the IDE features to help us find the threads in a multithreaded application: Using the same project that we used in the previous example, with the same breakpoint defined, press F5 or select Debug | Start Debugging in the main menu. Enter or copy and paste a long text (with more than 5,000 lines) in the Textbox labeled Original SMS Messages and click on the Run in a thread button. The line with the breakpoint defined is shown highlighted as the next statement that will be executed. Select Debug | Windows | Threads in the main menu or press Ctrl + Alt + H. The Threads window will be shown, displaying all the threads created by the application process, as shown in the following image: The yellow arrow in the left of the thread list points out the current thread—the thread for which the IDE is showing the current statement. Press F10 or select Debug | Step Over in the main menu. As you can see, the next statement is the same again, but the current thread pointed out in the thread list changes, as shown in the following image: Go on running the application step-by-step and watch how the current thread changes. Observe the Threads window throughout your debugging process. What just happened? You found the threads in the debugging process. Now, you believe you will be able to make the necessary changes to the application if you learn a few debugging techniques quickly. The Threads window displays the list of threads created by the application process. Many of them are created automatically by the C# runtime. The others are created by the Thread class instances and the BackgroundWorker component we have in the application. Using the Threads window, we can easily determine in which thread we are executing when debugging a multithreaded application. It is indeed very helpful. Remember that each thread has its own stack.  
Read more
  • 0
  • 0
  • 3554

article-image-debugging-multithreaded-applications-singlethreaded-c
Packt
15 Oct 2009
6 min read
Save for later

Debugging Multithreaded Applications as Singlethreaded in C#

Packt
15 Oct 2009
6 min read
We can identify threads created using both the BackgroundWorker component and the Thread class. We can also identify the main application thread and we learned about the information shown by the Threads window. However, we must debug the encryption process to solve its problem without taking into account the other concurrent threads. How can we successfully debug the encryption engine focusing on one thread and leaving the others untouched? We can use the Threads window to control the execution of the concurrent thread at runtime without having to make changes to the code. This will affect the performance results, but it will allow us to focus on a specific part of the code as if we were working in a single-threaded application. This technique is suitable for solving problems related to a specific part of the code that runs in a thread. However, when there are problems generated by concurrency we must use other debugging tricks that we will be learning shortly. The Threads window does a great job in offering good runtime information about the running threads while offering a simple way to watch, pause, and resume multiple threads. Time for action – Leaving a thread running alone You must run the encryption procedure called by ThreadEncryptProcedure. But you want to focus on just one thread, in order to solve the problem that the FBI agents detected. Changing the code is not an option, because it will take more time than expected, and you might introduce new bugs to the encryption engine. Thus, let's freeze the threads we are not interested in! Now, we are going to leave one encryption thread running alone to focus on its code without the other threads disturbing our debugging procedure: Stay in the project, SMSEncryption. Clear all the breakpoints. Press Ctrl + Shift + F9 or select Debug | Delete AllBreakpoints in the main menu. Make sure the Threads window is visible. Define a breakpoint in the line int liThreadNumber = (int)poThreadParameter; in the ThreadEncryptProcedure procedure code. Enter or copy and paste a long text, using the same lines (with more than 30,000 lines) in the Textbox labeled Original SMS Messages, as shown in the following image: Click on the Run in a thread button. The line with the breakpoint defined in the ThreadEncryptProcedure procedure is shown highlighted as the next statement that will be executed. The current thread will be shown with a yellow arrow on the left in the Threads window. Right-click on each of the other encryption threads and select Freeze in the context menu that appears, in order to suspend them. If the current thread is Encryption #1 and there are four cores available, you will freeze the following threads—Encryption #0, Encryption #2, and Encryption #3. Right-click on the Main thread and select Freeze in the context menu that appears, in order to suspend it (we do not want the BackgroundWorker to start and interfere with our work). The only working thread that matters will be Encryption #1, as shown in the following image: Run the code step-by-step inspecting values as you do with single-threaded applications. What just happened? It is easy to debug a multi hreaded application focusing on one thread instead of trying to do it with all the threads running at the same time. We could transform a complex multi threaded application into a single-threaded application without making changes to the code. We did it at runtime using the multithreading debugging features offered by the C# IDE. We suspended the execution of the concurrent threads that would disturb our step-by-step execution. Thus, we could focus on the code being executed by just one encryption thread. Freezing and thawing threads Freezing a thread suspends its execution. However, in the debugging process, we would need to resume the thread execution. It can be done at any point of ti me by right-clicking on a suspended thread and selecting Thaw in the context menu that appears, as shown in the following image: By Freezing and Thawing threads (suspending and resuming), we can have an exhaustive control over the threads running during the debugging process. It helps a lot when we have to solve bugs related to concurrency as we can easily analyze many contexts without making changes to the code—which could generate new bugs. Nevertheless, when developing multithreaded applications, we must always test the execution with many concurrent threads running to make sure it does not have concurrency bugs. The debugging techniques allow us to isolate the code for evaluation purposes, but the final tests must use the full multithreading potential. Viewing the call stack for each running thread Each thread has its own independent stack. Using the Call Stack window, we can move through the methods that were called, as we are used to doing so in single-threaded applications. The main difference in doing this with multithreaded applications is that when the active thread changes, the Call Stack window will also show different content. Debugging a multi hreaded application using the techniques we are learning is an excellent way to understand how the different threads run and will improve our parallel programming skills. To show the call stack for the active thread, press Ctrl + Alt + C or go to Debug | Windows | Call Stack in the main menu. Make sure the Threads window is also visible to take into account the active thread when analyzing the call stack, as shown in the following image: Have a go hero – Debugging and enhancing the encryption algorithm Using the multithreaded debugging techniques we have learned so far, develop a new version of this application with the encryption problem solved. Take into account everything we have studied about freezing and thawing threads. Check the randomly generated garbage and the way it is applied to the generated encrypted string. Making some changes to it, you can have a robust encryption process that differentiates each output with the same input text. You can improve the new versions by using new randomly generated garbage to enhance the encryption algorithms. Oh no! You have to explain to the agents the changes you made to the encryption procedure, and how it works.  
Read more
  • 0
  • 0
  • 5802
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-games-fortune-scratch-14
Packt
15 Oct 2009
4 min read
Save for later

Games of Fortune with Scratch 1.4

Packt
15 Oct 2009
4 min read
Fortune-teller Most of us enjoy a good circus, carnival, or county fair. There's fun, food, and fortunes. Aah, yes, what would a fair be without the fortune-teller's tent? By the end of this article, you'll know everything you need to spin your fortunes and amaze your friends with your wisdom. Before we start the first exercise, create a new project and add two sprites. The first sprite will be the seeker. The second sprite will be the teller. Choose any sprites you want. My seeker will be a clam and my teller will be a snowman. If you want to add a background, go ahead. Time for action – create a list of questions In order to have a successful fortune-telling, we need two things: a question and an answer. Let's start by defining some questions and answers: Select the seeker from the list of sprites. From the Variables palette, click the Make a list button. In the list name dialog box, type questions and select For this sprite only. Click OK to create the list. Several new blocks display in the Variables palette, and an empty block titled seeker questions displays on the stage. Let's think about a couple of questions we may be tempted to ask, such as the following: Will my hair fall out? How many children will I have? Let's add our proposed questions to the questions list. Click the plus sign located in the bottom-left corner of the seeker questions box (on the stage) to display a text input field. Type Will my hair fall out? Press the plus sign again and enter the second question: How many children will I have? We now have two questions in our list. To automatically add the next item in the list, press enter. Let's add a say for 2 secs block to the scripts area of the seeker sprite so that we can start the dialog. From the Variables palette, drag the item of questions block to the input value of the say for 2 secs block. Double-click on the block and the seeker asks, "Will my hair fall out?" Change the value on the item block to last and double-click the block again. This time the seeker asks, "How many children will I have?" What just happened? I'm certain you could come up with a hundred different questions to ask a fortune-teller. Don't worry, you'll get your chance to ask more questions later. Did you notice that the new list we created behaved a lot like a variable? We were able to make the questions list private; we don't want our teller to peek at our questions, after all. Also, the list became visible on the screen allowing us to edit the contents. The most notable difference is that we added more than one item, and each item corresponds to a number. We essentially created a numbered list. If you work with other programming languages, then you might refer to lists as arrays. Because the seeker's questions were contained in a list, we used the item block to provide special instructions to the     say block in order to ask the question. The first value of the item block was position, which defaulted to one. The second value was the name of the list, which defaulted to questions. In contrast, if we used a variable to store a question, we would only need to supply the name of the variable to the say block. Have a go hero Create an answers list for the teller sprite, and add several items to the list. Remember, there are no wrong answers in this exercise. Work with an item in a list We can use lists to group related items, but accessing the items in the list requires an extra level of specificity. We need to know the name of the list and the position of the item within the list before we can do anything with the values. The following table shows the available ways to access a specific item in a list.
Read more
  • 0
  • 0
  • 3302

article-image-liferay-chat-portlet
Packt
15 Oct 2009
5 min read
Save for later

Liferay Chat Portlet

Packt
15 Oct 2009
5 min read
Working with Chat Portlet For the purpose of this article, we will use an intranet website called book.com  which is created  for a fictions company named "Palm Tree Publications". In order to let employees enjoy chatting and instant messaging with others, we should use the Liferay Chat portlet. Let's experience how to enjoy chatting and instant messaging first. As an administrator of "Palm Tree Publications", you need to create a Page called "Instant Messaging" under the Page, "Community", at the Book Lovers Community and also add the Chat portlet in the Page, "Instant Messaging". Adding a Participant First of all, log in as "Palm Tree" and do the following: Add a Page called "Instant Messaging" under the Page, "Community" at the Book Lovers Community Public Pages, if the Page is not already present. Add the Chat portlet in the Page, "Instant Messaging" of the Book Lovers Community where you want to set up chatting and an instant messaging environment, if Chat portlet is not already present. After adding the Chat portlet, you can view it as shown in the following figure. Then, we need to add a participant in the Chat portlet. As an editor at the Editorial department, "Lotti Stein" wants to ping the manager, "David Berger", online and further share some comments about Liferay books. Let's do it as follows: Login as "Lotti Stein" first. Go to the Page, "Instant Messaging", " under the Page, "Community", at the Book Lovers Community Public Pages. Click on the Add icon. Input a participant's email address, such as "david@book.com". Press the Enter key. You will see the participant's full name appear, such as "David Berger". After adding more participants, such as "John Stuckia" and "Rolf Hess", you can view all participants as shown in the following figure. Managing Participants All the Users you've invited will appear as a list of participants. If the User "David Berger" is online ,then the icon to the left of the User name becomes light blue. Otherwise, it remains light gray; for example, User "John Stuckia". As shown in the following figure, only two Users ("David Berger" and "Lotti Stein") are online in the server. For details about OpenFire, refer to the forthcoming section. The participants are removable. For example, "Lotti Stein" wants to remove a participant "Rolf Hess", from the list of participants. Let's do it as follows: Locate the participant, such as "Rolf Hess". Click on the icon to the left of the User name, such as "Rolf Hess". You will see that the participant "Rolf Hess" is highlighted. Click the Remove icon. This participant will be removed from the list of participants. In short, to remove a User from the list of participants, simply locate the User you want to remove by clicking on the icon to the left of the User name. Then, click the Remove icon. The selected User name will be removed from the list of participants. Starting Chatting Irrespective of whether the participants are online or not, you can begin to Chat with them. For example, as an editor of editorial department, "Lotti Stein" wants to start chatting with the manager, "David Berger". Let's do it as follows: Locate the participant, "David Berger". Click the User name, "David Berger". A Chat box will appear. Input the message, "David, how are you?" Press the Enter key. Your messages will appear starting with the keyword, Me, in the message box (as shown in the following figure). As a manager of the editorial department, "David Berger" will have to do the following, to receive the messages from "Lotti Stein": Login as "David Berger" in new browser. Go to the Page, "Instant Messaging" under the Page, "Community" at the Book Lovers Community Public Pages. Locate the participant, "Lotti Stein". Click the User name, "Lotti Stein". A chat box will appear with the messages from "Lotti Stein". Input the message, "I am fine, and you?" Press the Enter key. Your messages will appear starting with the keyword "Me:" in the message box and the messages sent by the other User, "Lotti Stein" here, will appear starting with the User's name as shown in the following figure: Generally, to start chat, locate the User you want to chat with, by the User name first. Click on the User name link. A Chat box will appear. You can chat with many Users at the same time. To do this, just click on the Users' name link. Each Chat box is only for one unique User. The Chat box contains the User's name on the upper left. You can close the current Chat box by clicking on the mark X to the upper right. Note that the Chat box is hidden in your current Page initiatively. Whenever a new message comes from the User, you are chatting with, the Chat box will pop up with the new message and possible previous messages. To send messages, simply input your messages in the message input box first, and then press the Enter key. Your messages will appear starting with the keyword, Me, in the message box, and the messages sent by the other Users will appear starting with their User names.
Read more
  • 0
  • 0
  • 2554

article-image-trixbox-ce-functions-and-features
Packt
15 Oct 2009
6 min read
Save for later

trixbox CE Functions and Features

Packt
15 Oct 2009
6 min read
Standard features The following sections will break down the list of available features by category. While the codes listed are the default settings, they can be modified in the PBX Configuration tool using the Feature Codes module. These features are invoked by dialing the code from a registered SIP or IAX endpoint, or via an analog extension plugged into an FXS port. Some of the following features require the appropriate PBX Configuration tool module to be installed. Call forwarding The call forwarding mechanism is both powerful and flexible. With the different options, you can perform a number of different functions or even create a basic find-me/follow-me setup when using a feature like call forward on no answer, or send callers to your assistant if you are on a call using call forward on busy. Function Code Call Forward All Activate *72 Call Forward All Deactivate *73 Call Forward All Prompting *74 Call Forward Busy Activate *90 Call Forward Busy Deactivate *91 Call Forward Busy Prompting Deactivate *92 Call Forward No Answer/Unavailable Activate *52 Call Forward No Answer/Unavailable Deactivate *53 Call waiting The call waiting setting determines whether a call will be put through to your phone if you are already on a call. This can be useful in some call center environments where you don't want agents to be disturbed by other calls when they are working with clients. Function Code Call Waiting Activate *70 Call Waiting Deactivate *71 Core features The core features control basic functions such as transfers and testing inbound calls. Simulating an inbound call is useful for testing a system without having to call into it. If you don't have any trunks hooked up, it is the easiest way to check your call flow. Once you have telephone circuits connected, you can still use the function to test your call flow without having to take up any of your circuits. Function Code Call Pickup ** Dial System FAX 666 Simulate Incoming Call 7777 Active call codes These codes are active during a call for features like transferring and recording calls. While some phones have some of these features built into the device itself, others are only available via feature codes. For example, you can easily do call transfers using most modern SIP phones, like Aastra's or Polycom's, by hitting the transfer button during a call. Function Code In-Call Asterisk Attended Transfer *2 In-Call Asterisk Blind Transfer ## Transfer call directly to extension's mailbox *+Extension Begin recording current call *1 End Recording current call *2 Park current call #70 Agent features The agent features are used most often in a Call Center environment to monitor different calls and for agents to log in and log out of queues. Function Code Agent Logoff *12 Agent Logon *11 ChanSpy (Monitor different channels) 555 ZapBarge (Monitor Zap channels) 888 Blacklisting If you have the PBX Configuration tool Blacklist module installed, then you have the ability to blacklist callers from being able to call into the system. This is great for blocking telemarketers, bill collectors, ex-girl/boyfriends, and your mother-in-law. Function Code Blacklist a number *30 Blacklist the last caller *32 Remove a number from the blacklist *31 Day / Night mode If you have the PBX Configuration tool Day/Night mode module installed, then you can use a simple key command to switch between day and night IVR recordings. This is great for companies that don't work off a set schedule everyday but want to manually turn on and off an off-hours greeting. Function Code Toggle Day / Night Mode *28 Do not disturb Usually, do-not-disturb functions are handled at the phone level. If you do not have phones with a DND button on them, then you can install this module to enable key commands to toggle Do Not Disturb on and off. Function Code DND Activate *78 DNS Deactivate *79 Info services The info services are some basic functions that provide information back to you without changing any settings. These are most often used for testing and debugging purposes. Function Code Call Trace *69 Directory # Echo Test *43 Speak your extension number *65 Speaking Clock *60 Intercom If you have a supported model of phone then you can install the PBX Configuration tool module to enable paging and intercom via the telephone's speakerphones. Function Code Intercom Prefix *80 User Allow Intercom *54 User Disallow Intercom *55 Voicemail If you want to access your voicemail from any extension then you need to choose 'Dial Voicemail System', otherwise using 'Dial My Voicemail' will use the extension number you are calling from and only prompt for the password. Function Code Dial Voicemail System *98 Dial My Voicemail *97 Adding new features The ability to add new features is built into the system. One common thing to do is to redirect 411 calls to a free service like Google's free service. The following steps will walk you through how to add a custom feature like this to your system. Begin by going to the Misc Destination module and enter a Description of the destination you want to create. Next, go to Misc Application to create the application. Here we will enter anotherDescription and the number we want to use to dial the application, make sure the feature is enabled, and then point to the destination that we created in the previous step. As you can see, any code can be assigned to any destination and a custom destination can consist of anything you can dial. This allows you to create many different types of custom features within your system. Voicemail features trixbox CE comes with the Asterisk Mail voicemail system. Asterisk mail is a fairly robust and useful voicemail system. The Asterisk Mail voicemail system can be accessed by any internal extension or by dialing into the main IVR system. As we saw earlier in this article, there are two ways of accessing the voicemail system, 'Dial Voicemail' and 'Dial My Voicemail'. To access the main voicemail system, we can dial *98 from any extension; we will then be prompted for our extension and our voicemail password. If we dial *97 for the 'My Voicemail' feature, the system will use the extension number you dialed in from and only prompt you for your voicemail password. The following tables will show you the basic structure of the voicemail menu system: Voicemail main menu options Press: 1 to Listen to (New) Messages 2 to Change Folders 0 for Mailbox Options * for Help # to Exit Listen to messages Press: 5 to Repeat Message 6 to Play Next Message 7 to Delete Message 8 to Forward to another userEnter Extension and press # 1 to Prepend a Message to forwarded message 2 to Forward without prepending 9 to Save Message 0 for New Messages 1 for Old Messages 2 for Work Messages 3 for Family Messages 4 for Friends Messages * for Help # to Cancel/Exit to Main Menu Change folders Press: 0 for New Messages 1 for Old Messages 2 for Work Messages 3 for Family Messages 4 for Friends' Messages # to Cancel/Exit to Main Menu Mailbox options Press: 1 to Record your Un-Available Message 2 to Record your Busy message 3 to Record your Name 4 to Change your Password # to Cancel/Exit to Main Menu
Read more
  • 0
  • 0
  • 5387

article-image-autoproxy-spring-aspect-oriented-programming-aop
Packt
14 Oct 2009
5 min read
Save for later

Autoproxy in Spring Aspect-Oriented Programming (AOP)

Packt
14 Oct 2009
5 min read
Autoproxy with classic Spring By using the class ProxyFactoryBean, AOP can be used in a classic way. But writing separately for each bean on which we want to apply an advisor is not a pleasant thing to see, especially if they are many. So let's consider it as a practicable way only if the beans to be configured in that modality are few. On the other hand, if the beans to which we have to apply AOP are many, in order to avoid finding ourselves with very long configuration files, we adopt another tactic: We use the auto proxy creator's system, which allows us to automatically create proxies for the beans and prevent using ProxyFactoryBean. There are two classes made available by Spring to allow the auto proxy creator: BeanNameAutoProxyCreator and DefaultAdvisorAutoProxyCreator. BeanNameAutoProxyCreator BeanNameAutoProxyCreator just has a list of beans names to which proxy can be created automatically. The way in which the autoproxy is created is really simple. It implements the BeanPostProcessor interface, which in its implementation replaces the bean (target) with a proxy. Example: This is the interface describing an animal. package org.springaop.chapter.three.autoproxy.domain;public interface Animal { public Integer getNumberPaws(); public Boolean hasTail(); public boolean hasFur(); public Boolean hasHotBlood(); } The (interface) Bird extends Animal. package org.springaop.chapter.three.autoproxy.domain;public interface Bird extends Animal{ public Boolean hasBeak(); public Boolean hasFeathers(); } The class that implements the Animal interface to describe Cat: package org.springaop.chapter.three.autoproxy.domain;public class Cat implements Animal{ public boolean hasFur() { return true; } public Integer getNumberPaws() { return 4; } public Boolean hasTail() { return true; } public Boolean hasHotBlood() { return true; } public void setSpecies(String species) { this.species = species; } public String getSpecies() { return species; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } private String species, colour;} The class that implements Animal and Bird to describe a Seabird: package org.springaop.chapter.three.autoproxy.domain;public class Seabird implements Animal,Bird{ public Integer getNumberPaws() { return 2; } public Boolean hasTail() { return false; } public Boolean hasBeak() { return true; } public Boolean hasFeathers() { return true; } public boolean hasFur() { return false; } public Boolean hasHotBlood() { return false; } public String getName() { return name; } public void setName(String name) { this.name = name; } private String name;} AnimalAdvice containing just the log with the target class, the invoked method, and the result. package org.springaop.chapter.three.autoproxy;import org.aopalliance.intercept.MethodInterceptor;import org.aopalliance.intercept.MethodInvocation;public class AnimalAdvice implements MethodInterceptor { public Object invoke(MethodInvocation invocation) throws Throwable { Logger log = Logger.getLogger(Constants.LOG_NAME); StringBuilder sb = new StringBuilder(); sb.append("Target Class:").append(invocation.getThis()).append("n").append(invocation.getMethod()).append("n"); Object retVal = invocation.proceed(); sb.append(" return value:").append(retVal).append("n"); log.info(sb.toString()); return retVal; }} The configuration file applicationContext.xml: <beans xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="tiger" class="org.springaop.chapter.three.autoproxy.domain.Cat"> <property name="species" value="tiger"/> <property name="colour" value="tear stripes"/></bean> <bean id="albatross" class="org.springaop.chapter.three.autoproxy.domain.Seabird"> <property name="name" value="albatross"/></bean> <!-- Pointcut --> <bean id="methodNamePointcut" class="org.springframework.aop.support.NameMatchMethodPointcut"> <property name="mappedNames"> <list> <value>has*</value> <value>get*</value> </list> </property> </bean> <!-- Advices --> <bean id="animalAdvice" class="org.springaop.chapter.three.autoproxy.AnimalAdvice"/> <!-- Advisor --> <bean id="animalAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor"> <property name="pointcut" ref="methodNamePointcut"/> <property name="advice" ref="animalAdvice"/> </bean> <bean id="autoProxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="proxyTargetClass" value="true"/> <property name="beanNames"> <list> <value>tiger</value> <value>albatross</value> </list> </property> <property name="interceptorNames"> <list> <value>animalAdvisor</value> </list> </property> </bean> </beans> Application context contains two beans, tiger and albatross. The methodNamePointcut acts on the methods starting with has and get. The animalAdvice (around advice) contains the logics to be executed, the animal advisor that links the animalAdvice to the methodNamePointcut, and the autoProxyCreator, where we declare just the beans' names and the list of interceptors' names. package org.springaop.chapter.three.autoproxy;public class AutoProxyTest { public static void main(String[] args) { String[] paths = { "org/springaop/chapter/three/autoautoproxy/applicationContext.xml" }; ApplicationContext ctx = new ClassPathXmlApplicationContext(paths); Cat tiger = (Cat)ctx.getBean("tiger"); tiger.hasHotBlood(); Bird albatross = (Bird)ctx.getBean("albatross"); albatros.hasBeak(); }} The test class invokes two methods on the beans tiger and albatross. Output:
Read more
  • 0
  • 0
  • 5917
article-image-data-modeling-erwin
Packt
14 Oct 2009
3 min read
Save for later

Data Modeling with ERWin

Packt
14 Oct 2009
3 min read
Depending on your data modeling need and what you already have, there are two other ways to create a data model: Derive from an existing model and Reverse Engineer an existing database. Let’s start with creating a new model by clicking the Create model button. We’d like to create both logical and physical models, so select Logical/Physical. You can see in the Model Explorer that our new model gets Model_1 name, ERWin’s default name. Let’s rename our model to Packt Model. Confirm by looking at the Model Explorer that our model is renamed correctly. Next, we need to choose the ER notation. ERWin offers two notations: IDEF1X and IE. We’ll use IE for our logical and physical models. It’s a good practice during model development to save our work from time to time. Our model is still empty, so let’s next create a logical model in it. Logical Model Logical model in ERWin is basically ER model. An ER model consists of entities and their attributes, and their relationships. Let’s start by creating our first entity: CUSTOMER and its attributes. To add an entity, load (click) the Entity button on the toolbar, and drop it on the diagramming canvas by clicking your mouse on the canvas. Rename the entity’s default E/1 name to CUSTOMER by clicking on the name (E/1) and typing its new name over it. To add an attribute to an entity, right-click the entity and select Attributes. Click the New button. Type in our first attribute name (CUSTOMER_NO) over its name, and select Number as its data type, and then click OK. We want this attribute as the entity’s primary key, so check the Primary Key box. In the same way, add an attribute: CUSTOMER_NAME with a String data type. Our CUSTOMER entity now has two attributes as seen in its ER diagram. Notice that the CUSTOMER_NO attribute is at the key area, the upper part of the entity box; while the CUSTOMER_NAME is in the common attribute area, the bottom part. Similarly, add the rest of the entities and their attributes in our model. When you’re done, we’ll have six entities in our ER diagram. Our entities are not related yet. To rearrange the entities in the diagram, you can move around the entities by clicking and dragging them.
Read more
  • 0
  • 0
  • 4017

article-image-developing-wiki-seek-widget-using-javascript
Packt
14 Oct 2009
8 min read
Save for later

Developing Wiki Seek Widget Using Javascript

Packt
14 Oct 2009
8 min read
If you’re searching for details of a particular term in Google, you’re most probably going to see a link for relevant articles from wikipedia.org in the top 10 result list. Wikipedia, is the largest encyclopedia on the Internet, and contains huge collections of articles in many languages. The most significant feature of this encyclopedia is that it is a Wiki, so anybody can contribute to the knowledge base. A Wiki, (a new concept of web2.0), is a collection of web pages whose content can be created and changed by the visitor of the page with simplified mark-up language. Wikis are usually used as knowledge management systems on the web. Brief Introduction to Wikipedia Wikipedia has defined itself as : … a free, multilingual, open content encyclopedia project operated by the United States-based non-profit Wikimedia Foundation. Wikipedia is built upon an open source wiki package called MediaWiki. MediaWiki uses PHP as a server side scripting language and MySql as the database. Wikipedia uses MediaWiki’s wikitext format for editing the text, so the user (without any necessary  knowledge of HTML and CSS) can edit them easily. The Wikitext language (also called Wiki Markup) is a markup language which gives instruction on how outputted text will be displayed. It provides a simplified approach to writing pages in a wiki website. Different types of wiki software employ different styles of Wikitext language. For example, the Wikitext markup language has ways to hyperlink pages within the website but a number of different syntaxes are available for creating such links. Wikipedia was launched by Jimmy Wales and Larry Sanger in 2001 as a means of collecting and summarizing human knowledge in every major language. As of April 2008, Wikipedia had over 10 million articles in 253 languages. With so many articles, it is the largest encyclopedia ever assembled. Wikipedia articles are written collaboratively by volunteers, and any visitor can modify the content of article. Any modification must be accepted by the editors of Wikipedia otherwise the article will be reverted to the previous content. Along with popularity, Wikipedia is also criticized for systematic bias and inconsistency since the modifications must be cleared by the editors. Critics also argue that it’s open nature and the lack of proper sources for many articles makes it unreliable. Searching in Wikipedia To search for a particular article in Wikipedia, you can use the search box in the home page of wikipedia.org.Wikipedia classifies its articles in different sub-domains according to language; “en.wikipedia.org” contains articles in English language whereas “es.wikipedia.org” contains Spanish articles. Whenever you select “english” language in the dropdown box, the related articles will be searched over “en.wikipedia.org” and so on for the another language. You can also search the articles of Wikipedia from a remote server. For this, you have to send the language and search parameters to http://www.wikipedia.org/search-redirect.php via the GET method Creating a Wiki Seek Widget Up till now, we’ve looked at the background concept of Wikipedia. Now, let’s start building the widget. This widget contains a form with three components. A textbox where the visitors enters the search keyword, a dropdown list which contains the language of the article and finally a submit button to search the articles of Wikipedia. By the time we’re done, you should have a widget that looks like this: Concept for creating form Before looking at the JavaScript code, first let’s understand the architecture of the form with the parameters to be sent for searching Wikipedia. The request should be sent to http://www.wikipedia.org/search-redirect.php via the GET method. <form action="http://www.wikipedia.org/search-redirect.php" ></form> If you don’t specify the method attribute in the form, the form uses GET, which is the default method. After creating the form element, we need to add the textbox inside the above form with the name search because we’ve to send the search keyword in the name of search parameter. <input type="text" name="search" size="20" /> After adding the textbox for the search keyword, we need to add the dropdown list which contains the language of the article to search. The name of this dropdown-list should be language as we’ve to send the language code to the above URL in the language parameter. These language codes are two or three letter codes specified by ISO. ISO has assigned three letter language codes for most of the popular languages of the world. And, there are a few languages that are represented by two letter ISO codes. For example, eng and en are the three and two letter language code for English. Some of the article languages of Wikipedia don’t have ISO codes, and you have to find the value of the language parameter from Wikipedia. For example, articles in the Alemannisch language is als. Here is the HTML code for constructing a dropdown list in major languages : <select name="language"><option value="de" >Deutsch</option><option value="en" selected="selected">English</option><option value="es" >Español</option><option value="eo" >Esperanto</option><option value="fr" >Français</option><option value="it" >Italiano</option><option value="hu" >Magyar</option><option value="nl" >Nederlands</option></select> As you can see in the above dropdown list, English is the default language selected. Now, we just need to add a submit button in the above form to complete the form for searching the article in wikipedia. <input type="submit" name="go" value="Search" title="Search in wikipedia" /> Put all the HTML code together to create the form. JavaScript Code As we’ve already got the background concept of the HTML form, we just have to use the document.write() to output the HTML to the web browser. Here is the JavaScript code to create the Wiki Seek Widget : document.write('<div>');document.write('<form action="http://www.wikipedia.org/search-redirect.php" >');document.write('<input type="text" name="search" size="20" />');document.write('&nbsp;<select name="language">');document.write('<option value="de" >Deutsch</option>');document.write('<option value="en" selected="selected">English</option>');document.write('<option value="es" >Español</option>');document.write('<option value="eo" >Esperanto</option>');document.write('<option value="fr" >Français</option>');document.write('<option value="it" >Italiano</option>');document.write('<option value="hu" >Magyar</option>');document.write('<option value="nl" >Nederlands</option>');document.write('</select>');document.write('&nbsp;<input type="submit" name="go" value="Search" title="Search in wikipedia" />');document.write('</form>');document.write('</div>'); In the above code, I’ve used division (div) as the container for the HTML form. I’ve also saved the above code in a wiki_seek.js file. The above JavaScript code displays a non-stylish widget. To make a stylish widget, you can use style property in the input elements of the form. Using Wiki Seek widget To use this wiki seek widget we’ve to follow these steps: First of all, we need to upload the above wiki_seek.js to a web server so that it can be used by the client websites. Let’s suppose that is uploaded and placed in the URL : http://www.widget-server.com/wiki_seek.js Now, we can widget in any web pages by placing the following JavaScript Code in the website. <script type="text/javascript" language="javascript"src="http://www.widget-server.com/wiki_seek.js"></script> The Wiki Seek widget is displayed in any part of web page, where you place the above code.
Read more
  • 0
  • 0
  • 3687

article-image-design-spring-aop
Packt
14 Oct 2009
12 min read
Save for later

Design with Spring AOP

Packt
14 Oct 2009
12 min read
Designing and implementing an enterprise Java application means not only dealing with the application core business and architecture, but also with some typical enterprise requirements. We have to define how the application manages concurrency so that the application is robust and does not suffer too badly from an increase in the amount of requests. We have to define the caching strategies for the application because we don't want that CPU or data-intensive operations to be executed over and over. We have to define roles and profiles, applying security policies and restricting access to application parts, because different kind of users will probably have different rights and permissions. All these issues require writing additional code that clutters our application business code and reduces its modularity and maintainability. But we have a choice. We can design our enterprise Java application keeping AOP in mind. This will help us to concentrate on our actual business code, taking away all the infrastructure issues that can be otherwise expressed as crosscutting concerns. This article will introduce such issues, and will show how to design and implement them with Spring 2.5 AOP support. Concurrency with AOP For many developers, concurrency remains a mystery. Concurrency is the system's skill to act with several requests simultaneously, so that threads don't corrupt the state of the objects when they gain access at the same time. A number of good books have been written on this subject, such as Concurrent Programming in Java and Java Concurrency in Practice. They deserve much attention, since concurrency is an aspect that's hard to understand, and not immediately visible to developers. Problems in the area of concurrency are hard to reproduce. However, it's important to keep concurrency in mind to assure that the application is robust regardless of the number of users it will serve. If we don't take into account concurrency and document when and how the problems of concurrency are considered, we will build an application taking some risks by supposing that the CPU will never simultaneously schedule processes on parts of our application that are not thread-safe. To ensure the building of robust and scalable systems, we use proper patterns: There are JDK packages just for concurrency. They are in the java.util.concurrent package, a result of JSR-166. One of these patterns is the read-write lock pattern, of which there is the interface java.util.concurrent.locks.ReadWriteLock and implementations, one of which is ReentrantReadWriteLock. The goal of ReadWriteLock is to allow the reading of an object from virtually endless number of threads, while only one thread at a time can modify it. In this way, the state of the object can never be corrupted because threads to reading the object's state will always read up-to-date data, and the thread modifying the state of the object in question will be able to act without the possibility of the object's state being corrupted. Another necessary skill is that the result of a thread's action can be visible to the other threads. The behavior is the same as we could have achieved using synchronized, but when using a read-write lock we are explicitly synchronizing the actions, whereas with synchronized synchronization is implicit. Now let's see an example of ReadWriteLock on BankAccountThreadSafe object. Before the read operation, that needs to be safe, we set the read lock. After the read operation, we release the read lock. Before the write operation that needs to be safe, we set the write lock. After a state modification, we release the write lock. package org.springaop.chapter.five.concurrent; import java.util.Date; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public final class BankAccountThreadSafe { public BankAccountThreadSafe(Integer id) { this.id = id; balance = new Float(0); startDate = new Date(); } public BankAccountThreadSafe(Integer id, Float balance) { this.id = id; this.balance = balance; startDate = new Date(); } public BankAccountThreadSafe(Integer id, Float balance, Date start) { this.id = id; this.balance = balance; this.startDate = start; } public boolean debitOperation(Float debit) { wLock.lock(); try { float balance = getBalance(); if (balance < debit) { return false; } else { setBalance(balance - debit); return true; } } finally { wLock.unlock(); } } public void creditOperation(Float credit) { wLock.lock(); try { setBalance(getBalance() + credit); } finally { wLock.unlock(); } } private void setBalance(Float balance) { wLock.lock(); try { balance = balance; } finally { wLock.unlock(); } } public Float getBalance() { rLock.lock(); try { return balance; } finally { rLock.unlock(); } } public Integer getId() { return id; } public Date getStartDate() { return (Date) startDate.clone(); } ... private Float balance; private final Integer id; private final Date startDate; private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final Lock rLock = lock.readLock(); private final Lock wLock = lock.writeLock(); } BankAccountThreadSafeis a class that doesn't allow a bank account to be overdrawn (that is, have a negative balance), and it's an example of thread-safe class. The final fields are set in the constructors, hence implicitly thread-safe. The balance field, on the other hand, is managed in a thread-safe way by the setBalance,getBalance, creditOperation, and debitOperation methods. In other words, this class is correctly programmed, concurrency-wise. The problem is that wherever we would like to have those characteristics, we have to write the same code (especially the finally block containing the lock's release). We can solve that by writing an aspect that carries out that task for us. A state modification is execution(void com.mycompany.BankAccount.set*(*)) A safe read is execution(* com.mycompany.BankAccount.getBalance()) package org.springaop.chapter.five.concurrent; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; @Aspect public class BankAccountAspect { /*pointcuts*/ @Pointcut("execution(* org.springaop.chapter.five.concurrent.BankAccount.getBalance())") public void safeRead(){} @Pointcut("execution(* org.springaop.chapter.five.concurrent.BankAccount.set*(*))") public void stateModification(){} @Pointcut( "execution(* org.springaop.chapter.five.concurrent.BankAccount.getId())") public void getId(){} @Pointcut("execution(* org.springaop.chapter.five.concurrent.BankAccount.getStartDate())) public void getStartDate(){} /*advices*/ @Before("safeRead()") public void beforeSafeRead() { rLock.lock(); } @After("safeRead()") public void afterSafeRead() { rLock.unlock(); } @Before("stateModification()") public void beforeSafeWrite() { wLock.lock(); } @After("stateModification()") public void afterSafeWrite() { wLock.unlock(); } private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final Lock rLock = lock.readLock(); private final Lock wLock = lock.writeLock(); } The BankAccountAspect class applies the crosscutting functionality. In this case, the functionality is calling the lock and unlock methods on the ReadLock and the WriteLock. The before methods apply the locks with the @Before annotation, while the after methods release the locks as if they were in the final block, with the @After annotation that is always executed (after-finally advice). In this way the BankAccount class can become much easier, clearer, and briefer. It wouldn't have any perception that it can be executed in a thread-safe manner. package org.springaop.chapter.five.concurrent; import java.util.Date; public class BankAccount { public BankAccount(Integer id) { this.id = id; this.balance = new Float(0); this.startDate = new Date(); } public BankAccount(Integer id, Float balance) { this.id = id; this.balance = balance; this.startDate = new Date(); } public BankAccount(Integer id, Float balance, Date start) { this.id = id; this.balance = balance; this.startDate = start; } public boolean debitOperation(Float debit) { float balance = getBalance(); if (balance < debit) { return false; } else { setBalance(balance - debit); return true; } } public void creditOperation(Float credit) { setBalance(getBalance() + credit); } private void setBalance(Float balance) { this.balance = balance; } public Float getBalance() { return balance; } public Integer getId() { return id; } public Date getStartDate() { return (Date) startDate.clone(); } private Float balance; private final Integer id; private final Date startDate; } Another good design choice, together with the use of ReadWriteLock when necessary, is: using objects that once built are immutable, and therefore, not corruptible and can be easily shared between threads. Transparent caching with AOP Often, the objects that compose applications perform the same operations with the same arguments and obtain the same results. Sometimes, these operations are costly in terms of CPU usage, or may be there is a lot of I/O going on while executing those operations. To get better results in terms of speed and resources used, it's suggested to use a cache. We can store in it the results corresponding to the methods' invocations as a key-value pair: method and arguments as key and return object as value. Once you decide to use a cache you're just halfway. In fact, you must decide which part of the application is going to use the cache. Let's think about a web application backed by a database. Such web application usually involves Data Access Objects (DAOs), which access the relational database. Such objects are usually a bottleneck in the application as there is a lot of I/O going on. In other words, a cache can be used there. The cache can also be used by the business layer that has already aggregated and elaborated data retrieved from repositories, or it can be used by the presentation layer putting formatted presentation templates in the cache, or even by the authentication system that keeps roles according to an authenticated username. There are almost no limits as to how you can optimize an application and make it faster. The only price you pay is having RAM to dedicate the objects that are to be kept in memory, besides paying attention to the rules on how to manage life of the objects in cache. After these preliminary remarks, using a cache could seem common and obvious. A cache essentially acts as a hash into which key-value pairs are put. The keys are useful to retrieve objects from the cache. Caching usually has configuration parameters that'll allow you to change its behavior. Now let's have a look at an example with ehcache (http://ehcache.sourceforge.net). First of all let's configure it with the name methodCache so that we have at the most 1000 objects. The objects are inactive for a maximum of five minutes, with a maximum life of 10 minutes. If the objects count is over 1000, ehcache saves them on the filesystem, in java.io.tmpdir. <ehcache> ... <diskStore path="java.io.tmpdir"/> ... <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> ... <cache name="methodCache" maxElementsInMemory="1000" eternal="false" overflowToDisk="false" timeToIdleSeconds="300" timeToLiveSeconds="600" /> </ehcache> Now let's create an CacheAspect . Let's define the cacheObject to which the ProceedingJoinPoint is passed. Let's recover an unambiguous key from the ProceedingJoinPoint with the method getCacheKey. We will use this key to put the objects in cache and to recover them. Once we have obtained the key, we ask to cache the Element with the instruction cache.get(cacheKey). The Element has to be evaluated because it may be null if the cache didn't find an Element with the passed cacheKey. If the Element is null, advice invokes the method proceed(), and puts in the cache the Element with the key corresponding to the invocation. Otherwise, if the Element recovered from the cache is not null, the method isn't invoked on the target class, and the value taken from the cache is given back to the caller. package org.springaop.chapter.five.cache; import it.springaop.utils.Constants; import net.sf.ehcache.Cache; import net.sf.ehcache.Element; import org.apache.log4j.Logger; import org.aspectj.lang.ProceedingJoinPoint; public class CacheAspect { public Object cacheObject(ProceedingJoinPoint pjp) throws Throwable { Object result; String cacheKey = getCacheKey(pjp); Element element = (Element) cache.get(cacheKey); logger.info(new StringBuilder("CacheAspect invoke:").append("n get:") .append(cacheKey).append(" value:").append(element).toString()); if (element == null) { result = pjp.proceed(); element = new Element(cacheKey, result); cache.put(element); logger.info(new StringBuilder("n put:").append(cacheKey).append( " value:").append(result).toString()); } return element.getValue(); } public void flush() { cache.flush(); } private String getCacheKey(ProceedingJoinPoint pjp) { String targetName = pjp.getTarget().getClass().getSimpleName(); String methodName = pjp.getSignature().getName(); Object[] arguments = pjp.getArgs(); StringBuilder sb = new StringBuilder(); sb.append(targetName).append(".").append(methodName); if ((arguments != null) && (arguments.length != 0)) { for (int i = 0; i < arguments.length; i++) { sb.append(".").append(arguments[i]); } } return sb.toString(); } public void setCache(Cache cache) { this.cache = cache; } private Cache cache; private Logger logger = Logger.getLogger(Constants.LOG_NAME); } Here is applicationContext.xml <beans xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> ... <bean id="rockerCacheAspect" class="org.springaop.chapter.five.cache.CacheAspect" > <property name="cache"> <bean id="bandCache" parent="cache"> <property name="cacheName" value="methodCache" /> </bean> </property> </bean> <!-- CACHE config --> <bean id="cache" abstract="true" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager" ref="cacheManager" /> </bean> <bean id="cacheManager" class="org.springframework.cache.ehcache. EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:org/springaop/chapter/five/cache/ehcache.xml" /> </bean> ... </beans> The idea about the caching aspect is to avoid repetition in our code base and have a consistent strategy for identifying objects (for example using the hash code of an object) so as to avoid objects from ending up in the cache twice. Employing an around advice, we can use the cache to make the method invocations give back the cached result of a previous invocation of the same method in a totally transparent way. In fact, to the methods of the classes defined in the interception rules in pointcuts will be given back the return values drawn from the cache or, if they are not present, they will be invoked and inserted in the cache. In this way, the classes and methods don't have any cognition of obtaining values retrieved from the cache.
Read more
  • 0
  • 0
  • 18570
article-image-mixing-aspnet-webforms-and-aspnet-mvc
Packt
12 Oct 2009
6 min read
Save for later

Mixing ASP.NET Webforms and ASP.NET MVC

Packt
12 Oct 2009
6 min read
Ever since Microsoft started working on the ASP.NET MVC framework, one of the primary concerns was the framework's ability to re-use as many features as possible from ASP.NET Webforms. In this article by Maarten Balliauw, we will see how we can mix ASP.NET Webforms and ASP.NET MVC in one application and how data is shared between both these technologies. (For more resources on .NET, see here.) Not every ASP.NET MVC web application will be built from scratch. Several projects will probably end up migrating from classic ASP.NET to ASP.NET MVC. The question of how to combine both technologies in one application arises—is it possible to combine both ASP.NET Webforms and ASP.NET MVC in one web application? Luckily, the answer is yes. Combining ASP.NET Webforms and ASP.NET MVC in one application is possible—in fact, it is quite easy. The reason for this is that the ASP.NET MVC framework has been built on top of ASP.NET. There's actually only one crucial difference: ASP.NET lives in System.Web, whereas ASP.NET MVC lives in System.Web, System.Web.Routing, System.Web.Abstractions, and System.Web.Mvc. This means that adding these assemblies as a reference in an existing ASP.NET application should give you a good start on combining the two technologies. Another advantage of the fact that ASP.NET MVC is built on top of ASP.NET is that data can be easily shared between both of these technologies. For example, the Session state object is available in both the technologies, effectively enabling data to be shared via the Session state. Plugging ASP.NET MVC into an existing ASP.NET application An ASP.NET Webforms application can become ASP.NET MVC enabled by following some simple steps. First of all, add a reference to the following three assemblies to your existing ASP.NET application: System.Web.Routing System.Web.Abstractions System.Web.Mvc After adding these assembly references, the ASP.NET MVC folder structure should be created. Because the ASP.NET MVC framework is based on some conventions (for example, controllers are located in Controllers), these conventions should be respected. Add the folder Controllers, Views, and Views | Shared to your existing ASP.NET application. The next step in enabling ASP.NET MVC in an ASP.NET Webforms application is to update the web.config file, with the following code: < ?xml version="1.0"?> <configuration> <system.web> <compilation debug="false"> <assemblies> <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </assemblies> </compilation> <pages> <namespaces> <add namespace="System.Web.Mvc"/> <add namespace="System.Web.Mvc.Ajax"/> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing"/> <add namespace="System.Linq"/> <add namespace="System.Collections.Generic"/> </namespaces> </pages> <httpModules> <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </httpModules> </system.web> </configuration> Note that your existing ASP.NET Webforms web.config should not be replaced by the above web.config! The configured sections should be inserted into an existing web.config file in order to enable ASP.NET MVC. There's one thing left to do: configure routing. This can easily be done by adding the default ASP.NET MVC's global application class contents into an existing (or new) global application class, Global.asax. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace MixingBothWorldsExample { public class Global : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{resource}.aspx/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); } protected void Application_Start() { RegisterRoutes(RouteTable.Routes); } } } This code registers a default ASP.NET MVC route, which will map any URL of the form /Controller/Action/Idinto a controller instance and action method. There's one difference with an ASP.NET MVC application that needs to be noted—a catch-all route is defined in order to prevent a request for ASP.NET Webforms to be routed into ASP.NET MVC. This catch-all route looks like this: routes.IgnoreRoute("{resource}.aspx/{*pathInfo}"); This is basically triggered on every request ending in .aspx. It tells the routing engine to ignore this request and leave it to ASP.NET Webforms to handle things. With the ASP.NET MVC assemblies referenced, the folder structure created, and the necessary configurations in place, we can now start adding controllers and views. Add a new controller in the Controllers folder, for example, the following simpleHomeController: using System.Web.Mvc; namespace MixingBothWorldsExample.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewData["Message"] = "This is ASP.NET MVC!"; return View(); } } } The above controller will simply render a view, and pass it a message through the ViewData dictionary. This view, located in Views | Home | Index.aspx, would look like this: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MixingBothWorldsExample.Views.Home.Index" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <head id="Head1" runat="server"> <title></title> </head> <body> <div> <h1><%=Html.Encode(ViewData["Message"]) %></h1> </div> </body> </html> The above view renders a simple HTML page and renders the ViewData dictionary's message as the page title.
Read more
  • 0
  • 1
  • 46362

article-image-elements-spring-web-flow-configuration-file
Packt
12 Oct 2009
9 min read
Save for later

The Elements of the Spring Web Flow Configuration File

Packt
12 Oct 2009
9 min read
Let's take a look at the XML Schema Definition (XSD) file of the Spring Web Flow configuration file. To make the file more compact and easier to read, we have removed documentation and similar additions from the file. The complete file is downloadable from http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd. An XSD file is a file that is used to describe an XML Schema, which in itself is a W3C recommendation to describe the structure of XML files. In this kind of definition files, you can describe which elements can or must be present in an XML file. XSD files are primarily used to check the validity of XML files that are supposed to follow a certain structure. The schema can also be used to automatically create code, using code generation tools. The elements of the Spring configuration file are: flow The root element of the Spring Web Flow definition file is the flow element. It has to be present in all configurations because all other elements are sub-elements of the flow tag, which defines exactly one flow. If you want to define more than one flow, you will have to use the same number of flow tags. As every configuration file allows only one root element, you will have to define a new configuration file for every flow you want to define. attribute Using  the attribute tag, you can define metadata for a flow. You can use this metadata to change the behavior of the flow. secured The secured tag is used to secure your flow using Spring Security. The element is defined like this: <xsd:complexType name="secured"> <xsd:attribute name="attributes" type="xsd:string" use="required" /> <xsd:attribute name="match" use="optional"> <xsd:simpleType> <xsd:restriction base="xsd:string"> <xsd:enumeration value="any" /> <xsd:enumeration value="all" /> </xsd:restriction> </xsd:simpleType> </xsd:attribute> </xsd:complexType> If you want to use the secured element, you will have to at least define the attributes attribute. You can use the attributes element to define roles that are allowed to access the flow, for example. The match attribute defines whether all the elements specified in the attributes attribute have to match successfully (all), or if one of them is sufficient (any). persistence-context The persistence-context element enables you to use a persistence provider in your flow definition. This lets you persist database objects in action-states. To use persistence-context tag, you also have to define a data source and configure the persistence provider of your choice (for example, Hibernate or the Java Persistence API) in your Spring application context configuration file. The persistence-context element is empty, which means that you just have to add <persistence-context /> to your flow definition, to enable its features. var The var element can be used to define instance variables, which are accessible in your entire flow. These variables are quite important, so make sure that you are familiar with them. Using var elements, you can define model objects. Later, you can bind these model objects to the forms in your JSP web sites and can store them in a database using the persistence features enabled with the persistence-context element.  Nevertheless, using instance variables is not mandatory, so you do not have to define any, unless required in your flow. The element is defined as shown in the following snippet from the XSD file: <xsd:element name="var" minOccurs="0" maxOccurs="unbounded"> <xsd:complexType> <xsd:attribute name="name" type="xsd:string" use="required" /> <xsd:attribute name="class" type="type" use="required" /> </xsd:complexType> </xsd:element> The element has two attributes that are both required. The instance variable you want to define needs a name, so that you can reference it later in your JSP files. Spring Web Flow also needs to know the type of the variable, so you have to define the class attribute with the class of your variable. input You can use the input element to pass information into a flow. When you call a flow, you can (or will have to, depending on whether the input element is required or not) pass objects into the flow. You can then use these objects to process your flow. The XML Schema definition of this element looks like this: <xsd:complexType name="input"> <xsd:attribute name="name" type="expression" use="required" /> <xsd:attribute name="value" type="expression" /> <xsd:attribute name="type" type="type" /> <xsd:attribute name="required" type="xsd:boolean" /> </xsd:complexType> The input element possesses certain attributes, of which only the name attribute is required. You have to specify a name for the input argument, which you can use to reference the variable in your flow. The value attribute is used to specify the value of the attribute, for example, if you want to define a default value for the variable. You can also define a type (for example int or long) for the variable if you want a specific type of information. A type conversion will be tried if the argument passed to the flow does not match the type you expect. With the required attribute, you can control if the user of your flow has to pass in a variable, or if the input attribute is optional. output While you can define input parameters with the input element, you can specify return values with the output element. These are variables that will be passed to your end-state as the result value of your flow. Here's the XML Schema definition of the output element: <xsd:complexType name="output"> <xsd:attribute name="name" type="expression" use="required" /> <xsd:attribute name="value" type="expression" /> <xsd:attribute name="type" type="type" /> <xsd:attribute name="required" type="xsd:boolean" /> </xsd:attribute> </xsd:complexType> The definition is quite similar to the input element. You can also see that the name of the output element is required. Otherwise, you have no means of referencing the variable from your end-state. The value attribute is the value of your variable, for example, the result of a computation or a user returned from a database. Of course, you can also specify the type you expect your output variable to be. As with the input element, a type conversion will be attempted if the type of the variable does not match the type specified here. The required attribute will check if nothing was specified, or the result of a computation is null. If it is null, an error will be thrown.   actionTypes Per se, this is not an element which you can use in your flow definition, but it is a very important part of the XML Schema definition, referenced by many other elements. The definition is quite complex and looks like this: <xsd:group name="actionTypes"> <xsd:choice> <xsd:element name="evaluate"> <xsd:complexType> <xsd:sequence> <xsd:element name="attribute" type="attribute" minOccurs="0" maxOccurs="unbounded" /> </xsd:sequence> <xsd:attribute name="expression" type="expression" use="required" /> <xsd:attribute name="result" type="expression" use="optional" /> <xsd:attribute name="result-type" type="type" use="optional" /> </xsd:complexType> </xsd:element> <xsd:element name="render"> <xsd:complexType> <xsd:sequence> <xsd:element name="attribute" type="attribute" minOccurs="0" maxOccurs="unbounded" /> </xsd:sequence> <xsd:attribute name="fragments" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> <xsd:element name="set"> <xsd:complexType> <xsd:sequence> <xsd:element name="attribute" type="attribute" minOccurs="0" maxOccurs="unbounded" /> </xsd:sequence> <xsd:attribute name="name" type="expression" use="required" /> <xsd:attribute name="value" type="expression" use="required" /> <xsd:attribute name="type" type="type" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:group> actionTypes is a group of sub-elements, namely evaluate, render, and set. Let's go through the single elements to understand how the whole definition works. evaluate With the evaluate element, you can execute code based on the expression languages. As described by the above source code, the element has three attributes; one of them is required. The expression attribute is required and executes the code that you want to run. The result value of the expression, if present, can be stored in the result attribute. Using the result-type attribute, you can convert the result value in the specified type, if needed. Additionally, you can define attributes using a sub-element of the attribute element. render Use the render element to partially render content of a web site. Using the required fragments attribute, you can define which fragments should be rendered. When the link on a web site is clicked the entire web site is not a re-load. Spring JavaScript allows you to update chosen parts of your web page. The remaining web site will not be reloaded, which can greatly enhance the performance of your web application. As is the case with the evaluate element, you can also specify additional attributes using the attribute sub-element. set The set element can be used to set attributes in one of the Spring Web Flows scopes. With the name attribute you can define where (in which scope) you want to define the attribute, and how it should be called. The following short source code illustrates how the set element works: <set name="flowScope.myVariable" value="myValue" type="long" /> As you can see, the name consists of the name of the scope and the name of your variable, delimited by a dot (.). Both the name attribute and the value attribute are required. The value is the actual value of your variable. The type attribute is optional and describes the type of your variable. As before, you can also define additional attributes using the attribute sub-element.
Read more
  • 0
  • 0
  • 2806
Modal Close icon
Modal Close icon