Showing posts with label web. Show all posts
Showing posts with label web. Show all posts

Saturday, September 7, 2013

HTML5: Parse and Generate JSON data using only Javascript, no external APIs.

JSON
JavaScript Object Notation (best known as JSON) is a lightweight data interchange format known to be compatible with almost every language in common use. It is sometimes used in JavaScript as a replacement for other transport formats, like XML.

JSON is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays.
  • An object is an unordered collection of zero or more name/value pairs.
  • An array is an ordered sequence of zero or more values.
  • The values can be strings, numbers, booleans, null, and these two structured types.

JSON can be used in Ajax requests or to store and load information on the client side.

ECMAScript 5 includes a native JSON object that is also included in other older browsers. This object allows us to convert standard objects, arrays, and JavaScript variables to a string JSON format using JSON.stringify() and to convert JSON string files to objects again using JSON.parse().

Most modern smartphone and tablet browsers support this object directly, and for older devices we can use a "Douglas Crockford" JavaScript polyfill.

Explore the following code on how those APIs could be used.

Thursday, September 5, 2013

jQuery: Disabling the native right-click contextual menu of the browser

Sometime you need to disable the default right-click context menu of the browser, on your web site, here is how to do it.

By using JavaScript, you can disable the browser’s native right-click contextual menu. Doing so with jQuery is a snap. We simply cancel the contenxtmenu event.

To test the functionality on your page, copy and paste the following code into index.html blank page:


You may be wondered where is the <head> and <title> tags, they are optional in HTML5 :).

Wednesday, August 14, 2013

Why not jQuery? it is Fast, powerful, cross browsers and easy to use framework.

jQuery, jQuery then jQuery, yeah it simplifies the way you touch the HTML via JavaScript.

On jQuery site, its definition as the following:
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
Yes, I agree totally with this statement, I make use of the JavaScript framework, jQuery. jQuery simplifies common tasks and provides a single interface to actions that are implemented inconsistently in different browsers. Perhaps the most common use of jQuery in my development is reading in files (XML, JSON, text …etc) or other data from web services, but it also make it easy for traversing the DOM and applying CCS to components in easy way.

The following section is meant to give a quick introduction to using jQuery, and making your hands dirty with code to get the idea. For advanced features of the framework, you can branch to jQuery documentation and API references.

But, wait here for a second, be patient, before you can use jQuery, you need to include it in your web page. You can do so by downloading the latest version at http://jquery.com/ or by grabbing a Google-hosted version by adding the following to the <head> section of your HTML file:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
As of time of this writing, the latest version of jQuery is 2.0.3, and also there are Other CDNs could be used, and are listed on jQuery home page, I have used here Google one.

After adding the library to your page lets, get in touch with jQuery functionality and development.

Once you have included jQuery in your document, you can use its functions via two global variables: jQuery and its shorthand, $.

Demo page structure:
We will use this page in our journey, for the sake of clarity of how to use jQuery.
<head>

jQuery Example
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style>
.content
{
 padding: 20px;
 width: 200px;
 height: 200px;
 background-color: #CCC;
}

#eventInfo
{
 width: 420px;
 height: 20px;
 background-color: #000;
 color: #CCC;
 font-weight: bold;
 margin-top: 10px;
}
</style>

</head>
<body>
</body>
Query Document Objects
Among its many uses, jQuery is very helpful at quickly and easily extracting elements from your HTML page into JavaScript code. You can query by id, tag name, CSS class, or combinations of these factors. jQuery makes this task easier, so you can focus on what you want to do with those elements.

To grab a single piece of the page, such as the content <div>, you call it by its id. Much of jQuery’s syntax is borrowed from CSS, which may look familiar.

Here is how you would call an object with an id of content:
Notice:
I am using the dollar-sign shorthand. Then I add parentheses because $ is a variable and a function (jQuery stretches the bounds of JavaScript in ways that you and I probably will not). Inside the function, we pass a string with the CSS we would use to style the map div, #content.

Let us see how to add a text to this div content, just use one of the following snippets of code:
Or simple chaining one
You have now used your first jQuery function to query for a specific element and add a text to it. You can achieve the same result with JavaScript’s standard document.getElementById function, but jQuery’s method is faster to type. Plus, the result using $ allows you to chain other jQuery functions, such as visual effects, binding events or applying values and css as we have made in the previous code.

Notice:
Every jQuery function returns a jQuery object wrapping the queried element(s). Therefore, we can use the functions call-chaining mechanism, this pattern is called builder design pattern.

jQuery can also do more than just query individual elements; it can gather multiple elements in a single call. Here are a few examples:
Each of these examples shows a different type of querying—and many more are possible. You can learn about what jQuery calls selectors at http://api.jquery.com/category/selectors/.

Use jQuery to fire browser events
jQuery provides a lean way to use and fires browser events, such as clicking, double clicking or dragging. You can also react to events anywhere in the browser, and jQuery makes reacting a simple process for us.

To respond to an event, you first need to be listening for it. To do so when your page first loads, you register your intention to react to an event. You can do this by adding a JavaScript function to the onload attribute of your <body> tag. Or you can do this with a special jQuery ready event.

Although creating an event to register other events may seem counterintuitive, but believe me it works. Here is an example that waits until the page is ready:
Notice:
That the element we are querying for is a little different from in the past. Instead of a string inside the parentheses, we have inserted a standard JavaScript object, document. When enough of the page has loaded that the browser knows all the objects it contains, we call the register_events function.

That register_events function does not exist, however, so we need to write it. Or, instead, we could react to the same event with an anonymous function:
As with most anonymous functions, you usually want to keep it to just a few lines. If you have many events to register, you are probably best served with a named function.

Note
A big difference exists between using your browser’s onload attribute and jQuery’s ready event. With onload, you wait until the entire page is loaded, including images and other external files. With $(document).ready, you can run code, such as registering events and hiding objects, the moment the browser is ready. Using jQuery here often translates to a better user experience.
Now that you have waited for the browser to be ready to register other events, let us register them. Here is the basic pattern for jQuery events:
The element portion is usually a selector, such as an element’s id (though it can also be any browser object, as shown in the ready example). The event piece is the name of the function, as declared by jQuery. Finally, function is the function reference, either an anonymous function or the name of the function to call.

Here is how you would listen for a particular element to be double clicked:
If you are familiar with JavaScript events included in HTML, you might be wondering where the on, as in onDblClick, went. In jQuery, events are referenced with only the action so it is dblclick.

You can also get additional information about the event. The information available may be a little different depending on the event. Here is how you find out where the user has double-clicked on a page:
I used a dblclick event. Because we want more information about the event, I included an optional parameter e to the anonymous function. Within the function, I can use that variable to get information, such as where the user double clicked. This data comes in two pieces:

The number of pixels from the left side of the page X and the number from the top of the page Y. You can see a sampling of available events in Table 1, along with the additional information that is passed in the optional parameter to each event.

Tip: Try also to double click inside content1 div, at different location and watch how X and Y
value changes.
Table 1: Some Useful jQuery Events

Event Name

Objects Available

Additional Information

click

Any


Page location: pageX, pageY

dblclick

Any

Page location: pageX, pageY

mousemove

Any

Page location: pageX, pageY

keydown

document, window

Key code

focus

Form elements

 
Events will make your web pages much more interactive. For a full list of events (and additional event information available), see jQuery’s documentation at http://api.jquery.com/category/events/.

Insert and Hide Content

Once you have one or more elements from the page using jQuery, you need to do something to them. Here, I will show you a way to add or replace the content inside a page element. In addition, I will also demonstrate an effect that will hide the content, so later, you can make it reappear.

Let us say you want an element on your page where you can show the event information raised from previous double click event such as event type and the event source id. You can add the element with HTML using something like this:
When you are ready to add the event information, you can use jQuery to find the element and then display the event information. If you want to display the content of a variable called info, you could use this single line of jQuery:
This line will find the element on the page with the id of eventInfo and then replace its inner HTML with the value in the info variable. If you just want to add additional content to the element, use this line instead:
Alternatively, use can use chaining feature as the following.
Now the eventInfo div content will look something like this:

Event Info: Event type is: dblclick, raised from: content1

You have seen how to insert content, but what about making that same content disappear? For example, before adding the event Information, a page with just Results: without anything after it looks a bit funny. So when the page loads, run the following code to hide the results element:
Moreover, when you are ready to display the results to the user, include this code:
On the other hand, append it to the last of your chaining command as the following:
These two functions are simple (and very useful) examples of jQuery effects. Many more effects are listed on the jQuery website at http://api.jquery.com/category/effects/.

Final code


jQuery Example
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style>
.content
{
 padding: 20px;
 width: 200px;
 height: 200px;
 background-color: #CCC;
}

#eventInfo
{
 width: 420px;
 height: 20px;
 background-color: #000;
 color: #CCC;
 font-weight: bold;
 margin-top: 10px;
}
</style>
<script type="text/javascript" language="javascript">
   //Use ready function to execute all code after browser parse and build DOM tree.
   $(document).ready(function(e) {
     
  // Hideing div with id eventInfo
  $('#eventInfo').hide(); 
  
  // Setting dive text and applying css value for the text to be of color red
  $('#content').text('My name is Mohamed Taman').css('color','red').append('

');
  
   //Get the first span wrapped inside the div with css class 'content' and set its text 
  $('.content span:first').text('Number of divs in the document are: ' + $('div').length);
  
  
  // Register div with id content1 to double click event
  $('#content1').dblclick(function(e) {
        alert('I am double clicked with and event location at, X: '+ e.pageX +', and Y: '+ e.pageY);
 
  var info = 'Event type is: '+ e.type +', raised from: '+ e.target.id;

  $('#eventInfo').html('Event Info: ').append(info).show();
    });
});
</script>

<body>
</body>
Let's wrap up

By now, we have reached to the end of the article, and I hope you enjoyed and find it useful.

In the next part, I will demonstrate an important issue, which is loading and reading data files using jQuery either it is JSON or XML data files. So If you want to interact with data outside of your current HTML file, jQuery has some excellent tools for doing these sorts of Ajax calls. Though Ajax is short for Asynchronous JavaScript And XML, you can access any type of data with Ajax.

Tuesday, July 23, 2013

Web: Faulty HTML, JS, and CSS code, hurts your page Performance, Quality and Debugging.

HTML page is the core

Yes, it is the core of every web project. Therefore, it is very important to code your HTML page properly since it forms the foundation for everything else. Because it is the core of every web page, so without a solid foundation, the stuff you build upon it will easily break.

All web browsers are very forgiving and will often render a page correctly even if the HTML is slightly faulty, and your page finally will render, but you should get your attention for such behavior. I do, however, recommend that you make sure the HTML is coded properly, for a number of reasons:

  • Performance
    Correct HTML code renders faster than incorrect HTML.

    How it comes? Okay let us see, if your code done properly, the browser will interpret the HTML in strict mode, in which it assumes that you know what you are doing. Incorrectly done, and it will switch to quirks mode, in which it is a lot more forgiving in its interpretation of the code.

    This means that you can get away with sloppy code, but since the browser has to guess what you mean, the page takes longer to render.

  • Quality
    Naturally, you want to look professional, and you just don’t look good with HTML that doesn’t validate. Invalid code is the sign of a developer who doesn’t know what he’s doing.

  • Debugging

    In addition, if you don’t have the HTML right, strange errors may occur in your CSS or JavaScript that are really hard to find.

    Both the CSS and a lot of the JavaScript code relies on the HTML being correct, so to make it easier for yourself, make sure that your HTML is correct by validating it frequently.

    This will save you a lot of time and grief.

How do you know that you have a correct HTML code?

It is a simple answer, fortunately W3C (World Wide Web Consortium) provides a tool which validate your code, whether it is a live page by providing its URL, or resides on your computer by uploading the file or past the code.

You will find this validator at W3C markup validation service.

Also your browsers are bundled with validation and inspection tools such as developer tools, alongside a bunch of extensions you can add to your browser for validation process.

Some of Firefox browser tools:

  1. Page Validator: https://addons.mozilla.org/en-US/firefox/addon/2250
  2. Html Validator: https://addons.mozilla.org/en-US/firefox/addon/249
  3. Web Developer Toolbar: https://addons.mozilla.org/en-US/firefox/addon/60

With these tools at your disposal, you are more than ready to get started.


Saturday, February 2, 2013

Barcode: Developing advanced Barcode applications using "BarcodeEngine" library.


Learn how to generate and read back any generated barcode using Barcode Engine 1.3 library.

Introduction

Developing Barcode API that decode and encode barcode images (or binary streams) from your application, integration with hardware or even your mobile is a demanding market requirement nowadays.
I will demonstrate my experience in tutorial like steps, to explain how to develop a barcode application to generate and consume back generated barcode to extract the encoded data, also decode any other generated picture that contains barcode, using my developed barcode library BarcodeEngine 1.3L (L for library).
It is useful to read the first article about the barcode (Barcode: Professional java barcode API (reader & writer)), to get the basic idea that will make it easy to understand this article.
Also the required software to install to be able to compile and run my BarcodeEngine 1.3L as it depends on two libraries the core.jar and javase.jar jars.

Software Pre-requisites

The following pieces of software are required to develop your barcode application:
  1. The core.jar, javase.jar jars.
  2. The BarcodeEngine 1.3L and could be downloaded from here.

Prepare the project

After getting the required software libraries as described in previous section. Now we are going to create your first project that will be used to run the barcode engine. I will use the Netbeans IDE (7.x) here, but indeed you are free to develop on your favorite IDE.
The following steps we are going to walk through will guides you to complete the barcode engine application:
  1. Open Netbeans and press (Ctrl + Shift + N) to open create project window, under categories list choose Java then in the other right hand list (Projects) choose Java Application then press next.

  2. In next window Name and Location write the following:


  3. Press Finish button and you should see something like this.


  4. Now we are going to attach the libs which we got earlier from the pre-requisites section, right click on the project and choose properties. In the categories choose libraries and on right hand side under compiler tab choose Add JAR/Folder and navigate to your libs to attach them then click open as the following snapshot.


  5. If all libs are added successfully, you should see something like this.


  6. Now our project is ready for developing barcode application.

Developing the application

Now after everything is setup successfully and ready. Let's explore the BarcodeEngine v1.3 library and do the coding to generate and read the barcodes, using proper configurations.
  1. Open already created class named "BarcodeApplication" which contains the main method.
  2. Inside the main method copy and paste the following code:
  3. Run the code and you should find the generated barcode images created in the specified folder as the following:


  4. In the output console you should see the following output:

How it works

Now after we have created our application, and see the created barcodes and reading back its contents, let's explore the application and see how it works.
First we have declared two files for two different barcode types, qrCodeFile and PDF417File in a specific folder which doesn't exists.
The second step is to create the encoding configuration (instance of EncodeConfig) which used by the barcode engine, encode method as hints for encoding barcode contents to the type we need to generate. The createDirectories(Boolean.TRUE) is responsible for forcing the engine to create the directories if it doesn't exists.
Note: that EncodeConfig and DecodeConfig configuration classes using builder pattern for creating the instances.
Then we have defined the contents to be encoded into QRCode as the following.
Then after configuration we asked the BarcodeEngine to encode the contentto qrCodeFile using encodeConfig encoding configurations. We did the same for the other type PDF417File. I do this to show up how to create the different types of barcodes.
Now it is the time to read back the barcode type's contents which we have generated before, using our BarcodeEngine API to decode and get back the results.
As we did before we need to configure the decoding configuration using a DecodeConfig instance, to be able to read the contents of any image containing barcode.
We pass the created decoding configuration along with the barcode file need to be decoded, to BarcodeEngine decode method, which return the result in form of map of DecodeResult enum as key and object as value.

We get the values from map as the following:


Note: All the BarcodeEngine API methods are static methods, and contain an Utils inner class that has many general useful methods.
Barcode engine also has other methods that extract the barcode from within an image, crop certain portion of the image, and rotate image. Consult the java documentation associated with API for more information.

Explain the API

Consult the java documentation associated with API for more information, about BarcodeEngine class, and its configuration classes (Encode and Decode configurations), alongside with the utility classes.

Finally

The final project source could be downloaded from here.

Friday, July 27, 2012

EL: Expression language 2.2 Distilled

Here I will give a brief introduction and also some improvement done in JSR 245, The Expression Language (also referred to as the EL),
which provides an important mechanism for enabling the presentation layer (web pages) to communicate with the application logic (managed beans).

The EL is used by both JavaServer Faces technology and JavaServer Pages (JSP) technology.

The EL represents a union of the expression languages offered by JavaServer Faces technology and JSP technology.

The EL allows page authors to use simple expressions to dynamically access data from JavaBeans components.

For example, the test attribute of the following conditional tag is supplied with an EL expression that compares 0 with the number of items in the session-scoped bean named cart.


JavaServer Faces technology uses the EL for the following functions:
  • Deferred and immediate evaluation of expressions.

  • The ability to set as well as get data.

  • The ability to invoke methods.

To summarize, the EL provides a way to use simple expressions to perform the following tasks:
  • Dynamically read application data stored in JavaBeans components, various data structures, and implicit objects.

  • Dynamically write data, such as user input into forms, to JavaBeans components.

  • Invoke arbitrary static and public methods.

  • Dynamically perform arithmetic operations.

The EL is also used to specify the following kinds of expressions that a custom tag attribute will accept:
  • Immediate evaluation expressions or deferred evaluation expressions. An immediate evaluation expression is evaluated at once by the underlying technology, such as JavaServer Faces.

    A deferred evaluation expression can be evaluated later by the underlying technology using the EL.

  • Value expression or method expression. A value expression references data, whereas a method expression invokes a method.

  • Rvalue expression or lvalue expression. An rvalue expression can only read a value, whereas an lvalue expression can both read and write that value to an external object.

Immediate and Deferred Evaluation Syntax
---------------------------------------------------
The EL supports both immediate and deferred evaluation of expressions. Immediate evaluation means that the expression is evaluated and the result returned as soon as the page is first rendered.

Deferred evaluation means that the technology using the expression language can use its own machinery to evaluate the expression sometime later during the page’s lifecycle, whenever it is appropriate to do so, because of its multiphase lifecycle, JavaServer Faces technology uses mostly deferred evaluation expressions.

Those expressions that are evaluated immediately use the ${} syntax. Expressions whose evaluation is deferred use the #{} syntax.
  1. Immediate Evaluation
    ----------------------------
    All expressions using the ${} syntax are evaluated immediately. These expressions can be used only within template text or as the value of a tag attribute that can accept runtime expressions.

    The following example shows a tag whose value attribute references an immediate evaluation expression that gets the total price from the session-scoped bean named cart:

    The JavaServer Faces implementation evaluates the expression ${sessionScope.cart.total}, converts it, and passes the returned value to the tag handler.

    Immediate evaluation expressions are always read-only value expressions. The preceding example expression cannot set the total price, but instead can only get the total price from the cart bean.

  2. Deferred Evaluation
    -----------------------
    Deferred evaluation expressions take the form #{expr} and can be evaluated at other phases of a page lifecycle as defined by whatever technology is using the expression. In the case of JavaServer Faces technology, its controller can evaluate the expression at different phases of the lifecycle, depending on how the expression is being used in the page.

    The following example shows a JavaServer Faces h:inputText tag, which represents a text field component into which a user enters a value. The h:inputText tag’s value attribute references a deferred evaluation expression that points to the name property of the customer bean:

    For an initial request of the page containing this tag, the JavaServer Faces implementation evaluates the #{customer.name} expression during the render-response phase of the lifecycle.

    During this phase, the expression merely accesses the value of name from the customer bean, as is done in immediate evaluation.

    For a postback request, the JavaServer Faces implementation evaluates the expression at different phases of the lifecycle, during which the value is retrieved from the request, validated, and propagated to the customer bean.

    As shown in this example, deferred evaluation expressions can be:
    • Value expressions that can be used to both read and write data.

    • Method expressions.

    Value expressions (both immediate and deferred) and method expressions are explained in the next section.
Value and Method Expressions
--------------------------------------
The EL defines two kinds of expressions: value expressions and method expressions. Value expressions can either yield a value or set a value. Method expressions reference methods that can be invoked and can return a value.

Value Expressions
--------------------------
Value expressions can be further categorized into rvalue and lvalue expressions. Rvalue expressions can read data but cannot write it. Lvalue expressions can both read and write data.

All expressions that are evaluated immediately use the ${} delimiters and are always rvalue expressions. Expressions whose evaluation can be deferred use the #{} delimiters and can act as both rvalue and lvalue expressions. Consider the following two value expressions:

The former uses immediate evaluation syntax, whereas the latter uses deferred evaluation syntax. The first expression accesses the name property, gets its value, adds the value to the response, and gets rendered on the page. The same can happen with the second expression. However, the tag handler can defer the evaluation of this expression to a later time in the page lifecycle, if the technology using this tag allows.

In the case of JavaServer Faces technology, the latter tag’s expression is evaluated immediately during an initial request for the page. In this case, this expression acts as an rvalue expression. During a postback request, this expression can be used to set the value of the name property with user input. In this case, the expression acts as an lvalue expression.

Method Expressions
----------------------------
Another feature of the EL is its support of deferred method expressions. A method expression is used to invoke an arbitrary public method of a bean, which can return a result.

In JavaServer Faces technology, a component tag represents a component on a page. The component tag uses method expressions to invoke methods that perform some processing for the component. These methods are necessary for handling events that the components generate and for validating component data, as shown in this example:

The h:inputText tag displays as a text field. The validator attribute of this h:inputText tag references a method, called validateName, in the bean, called customer.

Because a method can be invoked during different phases of the lifecycle, method expressions must always use the deferred evaluation syntax. Like lvalue expressions, method expressions can use the (.) and the ([]) operators.

For example,
#{object.method} is equivalent to #{object["method"]}. The literal inside the [] is converted to String and is used to find the name of the method that matches it. Once the method is found, it is invoked, or information about the method is returned.

Parameterized Method Calls
------------------------------------
The EL offers support for parameterized method calls.Method calls can use parameters without having to use static EL functions.

Both the . and [] operators can be used for invoking method calls with parameters, as shown in the following expression syntax:
  • expr-a[expr-b](parameters)

  • expr-a.identifier-b(parameters)
In the first expression syntax, expr-a is evaluated to represent a bean object. The expression expr-b is evaluated and cast to a string that represents a method in the bean represented by expr-a. In the second expression syntax, expr-a is evaluated to represent a bean object, and identifier-b is a string that represents a method in the bean object. The parameters in parentheses are the arguments for the method invocation. Parameters can be zero or more values or expressions, separated by commas.

Parameters are supported for both value expressions and method expressions. In the following example, which is a modified tag from the guessnumber application, a random number is provided as an argument rather than from user input to the method call:

The preceding example uses a value expression.

Consider the following example of a JavaServer Faces component tag that uses a method expression:

The EL expression trader.buy calls the trader bean’s buy method. You can modify the tag to pass on a parameter.Here is the revised tag where a parameter is passed:

In the preceding example, you are passing the string ’SOMESTOCK’ (a stock symbol) as a parameter to the buy method.

Literal Expressions
-------------------------
A literal expression is evaluated to the text of the expression, which is of type String. A literal expression does not use the ${} or #{} delimiters.

If you have a literal expression that includes the reserved ${} or #{} syntax, you need to escape these characters as follows:
  • By creating a composite expression as shown here:
    • ${’${’}exprA}
    • #{’#{’}exprB}
    The resulting values would then be the strings ${exprA} and #{exprB}.

  • By using the escape characters \$ and \# to escape what would otherwise be treated as an eval-expression:
    • \${exprA}
    • \#{exprB}
The resulting values would again be the strings ${exprA} and #{exprB}. When a literal expression is evaluated, it can be converted to another type.

Literal expressions can be evaluated immediately or deferred and can be either value or method expressions. At what point a literal expression is evaluated depends on where it is being used. If the tag attribute that uses the literal expression is defined to accept a deferred value expression, when referencing a value, the literal expression is evaluated at a point in the lifecycle that is determined by other factors, such as where the expression is being used and to what it is referring.

In the case of a method expression, the method that is referenced is invoked and returns the specified String literal.

Refrences:
--------------

Saturday, July 21, 2012

JSF: The JavaServer Faces Technology

JavaServer Faces Technology

JavaServer Faces technology is a server-side component framework for building Java technology-based web applications.

JavaServer Faces technology consists of the following:
--------------------------------------------------------------------
  1. An API for representing components and managing their state; handling events, server-side validation, and data conversion; defining page navigation; supporting internationalization and accessibility; and providing extensibility for all these features.

  2. Tag libraries for adding components to web pages and for connecting components to server-side objects JavaServer Faces technology provides a well-defined programming model and various tag libraries. These features significantly ease the burden of building and maintaining web applications with server-side user interfaces (UIs). With minimal effort, you can complete the following tasks.
    • Create a web page.
    • Drop components onto a web page by adding component tags.

    • Bind components on a page to server-side data.

    • Wire component-generated events to server-side application code.

    • Save and restore application state beyond the life of server requests.

    • Reuse and extend components through customization.

What Is a JavaServer Faces Application?
--------------------------------------------------

The functionality provided by a JavaServer Faces application is similar to that of any other Java web application. A typical JavaServer Faces application includes the following parts:
  • A set of web pages in which components are laid out.

  • A set of tags to add components to the web page.

  • A set of managed beans, which are lightweight container-managed objects (POJOs) with minimal requirements. They support a small set of basic services, such as resource injection, lifecycle callbacks and interceptors.

  • A web deployment descriptor (web.xml file).

  • Optionally, one or more application configuration resource files, such as a faces-config.xml file, which can be used to define page navigation rules and configure beans and other custom objects, such as custom components.

  • Optionally, a set of custom objects, which can include custom components, validators, converters, or listeners, created by the application developer.

  • A set of custom tags for representing custom objects on the page.
Figure 1 shows the interaction between client and server in a typical JavaServer Faces application. In response to a client request, a web page is rendered by the web container that implements JavaServer Faces technology.


Figure 1: Responding to a Client Request for a JavaServer Faces Page.

The web page, index.xhtml, is built using JavaServer Faces component tags. Component tags are used to add components to the view (represented by helloUI in the diagram), which is the server-side representation of the page. In addition to components, the web page can also reference objects, such as the following:
  • Any event listeners, validators, and converters that are registered on the components.

  • The JavaBeans components that capture the data and process the application-specific functionality of the components.

On request from the client, the view is rendered as a response. Rendering is the process whereby, based on the server-side view, the web container generates output, such as HTML or XHTML, that can be read by the client, such as a browser.

JavaServer FacesTechnology Benefits
----------------------------------------------

One of the greatest advantages of JavaServer Faces technology is that it offers a clean separation between behavior and presentation for web applications. A JavaServer Faces application can map HTTP requests to component-specific event handling and manage components as stateful objects on the server. JavaServer Faces technology allows you to build web applications that implement the finer-grained separation of behavior and presentation that is traditionally offered by client-side UI architectures.

The separation of logic from presentation also allows each member of a web application development team to focus on a single piece of the development process and provides a simple programming model to link the pieces. For example, page authors with no programming expertise can use JavaServer Faces technology tags in a web page to link to server-side objects without writing any scripts.

Another important goal of JavaServer Faces technology is to leverage familiar component and web-tier concepts without limiting you to a particular scripting technology or markup language. JavaServer Faces technology APIs are layered directly on top of the Servlet API, as shown in Figure 2.



Figure 2: Java Web Application Technologies.

This layering of APIs enables several important application use cases, such as using different presentation technologies, creating your own custom components directly from the component classes, and generating output for various client devices.

Facelets technology, available as part of JavaServer Faces 2.0, is now the preferred presentation technology for building JavaServer Faces technology-based web applications.

Facelets technology offers several advantages:
  • Code can be reused and extended for components through the templating and composite component features.

  • When you use the JavaServer Faces Annotations feature, you can automatically register the managed bean as a resource available for JavaServer Faces applications. In addition, implicit navigation rules allow developers to quickly configure page navigation. These features reduce the manual configuration process for applications.

  • Most important, JavaServer Faces technology provides a rich architecture for managing component state, processing component data, validating user input, and handling events.

For more information on JavaServer Faces technology, see:
---------------------------------------------------------------------------

Thursday, July 19, 2012

Glassfish: Dynamic Reloading Feature

Dynamic Reloading

If dynamic reloading is enabled, you do not have to redeploy an application or module when you change its code or deployment descriptors. All you have to do is copy the changed pages or class files into the deployment directory for the application or module. The deployment directory for a web module named context-root is domain-dir/applications/context-root.

The server checks for changes periodically and redeploys the application, automatically and dynamically, with the changes.

This capability is useful in a development environment because it allows code changes to be tested quickly.

Dynamic reloading IS NOT RECOMMENDED for a production environment, however, because it may degrade performance. In addition, whenever a reload is done, the sessions at that time become invalid, and the client must restart the session.

Note: In the GlassFish Server, dynamic reloading is enabled by default.

To Disable or ModifyDynamic Reloading

If for some reason you do not want the default dynamic reloading behavior, follow these steps in the Administration Console.
  1. Open the URL http://localhost:4848/ in a browser.

  2. Select the GlassFish Server node.

  3. Select the Advanced tab.

  4. To disable dynamic reloading, deselect the Reload Enabled check box.

  5. To change the interval at which applications and modules are checked for code changes and dynamically reloaded, type a number of seconds in the Reload Poll Interval field.

    The default value is 2 seconds.

  6. Click the Save button.

Wednesday, June 6, 2012

ADF: How to use an af:popup during long running tasks?

For long-running tasks in your application, a pop-up message window can be raised to alert the users that the specific task may take a while.

This can be accomplished using a combination of ADF Faces components (af:popup and af:dialog) and some JavaScript code.

In this recipe, we will initiate a long-running task in a managed bean, and raise a pop-up for the duration of the task to alert us to the fact that this operation may take a while. We will hide the pop-up once the task completes.

Getting ready
----------------
You will need to create a skeleton Fusion Web Application (ADF) workspace before you proceed with this recipe.

How to do it
--------------

  1. Create a new JSF page called longRunningTask.jsf based on any of the quick start layouts.

  2. Drop a Button (af:commandButton) component from the Component Palette to the page.
    You may need to surround the button with an af:toolbar component. Using the Property Inspector, change the button's Text property to Long Running Task and set its PartialSubmit property to true.

  3. Create an action listener for the button by selecting Edit… from the Property Menu next to the ActionListener property in the Property Inspector. Create a new managed bean called LongRunningTaskBean and a new method called longRunningTask.

  4. Edit the LongRunningTaskBean Java class and add the following code to the longRunningTask() method:

  5. Return to the longRunningTask.jsf page editor. Right-click on the af:commandButton in the Structure window and select Insert Inside af:commandButton | ADF Faces….

    From the Insert ADF Faces Item dialog, select Client Listener. In the Insert Client Listener dialog, enter longRunningTask for the Method field and select action for the Type field.

  6. Add an af:resource to the af:document tag.
    Make sure that the af:resource type attribute is set to javascript and add the following JavaScript code inside it:

  7. Finally, add a Popup (af:popup) ADF Faces component to the page with an embedded Dialog (af:dialog) component in it.
    Ensure that the pop-up identifier is set to longRunningPopup and that its ContentDelivery attribute is set to immediate.
    Also add an af:outputText component to the dialog with some text indicating a long running process.
    Your pop-up should look similar to the following:

Here is the complete code for the backing bean:

And jsf page:

How it works
--------------
In steps 1 and 2, we created a JSF page called longRunningTask.jsf and added a button component to it. When pressed, the button will initiate a long-running task through an action listener. The action listener is added to the button in steps 3 and 4. It is defined to a method called longRunningTask() in a managed bean. The implementation of longRunningTask() simply waits for 5 seconds (step 4). We have also ensured (in step 2) that the button component's partialSubmit property is set to true. This will enable us to call the clientListener method that is added in steps 5 and 6.

In steps 5 and 6, we defined a clientListener for the button component. The client listener is implemented by the longRunningTask() JavaScript method, added to the page in step 6. The longRunningTask() JavaScript method adds a busy state listener for the pop-up component (the pop-up itself is added to the page in step 7) by calling addBusyStateListener() and prevents any user input by calling preventUserInput() on the JavaScript event. The busy state listener is implemented by the JavaScript method busyStateListener(). In it, we hide the pop-up and remove the busy state listener once the event completes.

Finally, in step 7, we added the longRunningPopup pop-up to the page. The pop-up is raised by the busyStateListener() as long as the event is busy (for 5 seconds). We made sure that the pop-up's contentDelivery attribute was set to immediate to deliver the pop-up content immediately once the page is loaded.

To test the recipe, right-click on the longRunningTask.jsf page in the Application Navigator and select Run or Debug from the context menu. When you click on the button, the pop-up is raised for the duration of the long-running task (the action listener in the managed bean). The pop-up is hidden once the long-running task completes.



Sunday, March 18, 2012

ADF: BIDI via EL in AdfFacesContext

At some point, you may have an inlineStyle whose value is BIDI sensitive; in LTR (left-to-right) mode, you may want a “left” style but in RTL (right-to-left) mode, you may want a “right” style. You don’t have to write a managed bean to give you the corresponding style as i did before, you can use EL (expression language).

Here’s an example assigning a padding for the “start” side of 10px:

Also you can use CSS and af:isRTL() function, if you editing ADF skin for your application, or prefers the CSS style, finally both ways works with CSS option, refere to "ADF: Add locale aware CSS to an individual component" for more info.

For other properties
See oracle.adf.view.rich.context.AdfFacesContext

Saturday, March 17, 2012

ADF: showPopupBehavior operation & load trigger

Sometimes I need to dual authenticate the entrance of a page that contains a very sensitive information such Payroll page.

In my old days I implement such a case by developing a page to open it as dialog and handle the load in page phase listener life cycle.

Now I will introduce a more easer and professional mechanism for such a case, by opening a popup in page load in a simple way.

Project structure is an ADF fusion application, and ADF web project as the following:



With ADF Faces it's so easy to open a popup on page load. All what I needs to do is to define af:showPopupBehavior operation for af:document tag.

Note: af:showPopupBehavior trigger type should be set to load.
There are a lot of triggers for this operation could be found in "Oracle® Fusion Middleware Web User Interface Developer's Guide for Oracle ADF 11g R2(11.1.2.1.0)" usage and implementation.

This will ensure, it will be executed during document load and will call popup during page rendering phase:


The payroll.jsf page code is as the following:

When you run the application Popup is popped up on page load:


References:
1- Oracle® Fusion Middleware Web User Interface Developer's Guide for ADF 11g Release 2(11.1.2.1.0)
2- ADF Faces Cheat Sheets 11.1.2.1.0

Monday, March 12, 2012

ADF: Add locale aware CSS to an individual component

Some locales have a right to left layout orientation. When creating a skin in ADF Faces, it's (relatively) easy to add locale aware CSS using the :rtl psuedo-class on the end of a skinning key to indicate that the skinning key should be used when the renderer is rendering right to left.
Example:

In this example, we want some padding before the start of the text in the content element of the component. In right to left locales, the start of the text is on the right side by default, so we need to change the padding from the left to the right.

Let's say, however, that you want to specify a locale aware CSS style on an individual component using the contentStyle attribute. There is a handy ADF Faces EL function to help you out here: isRTL. For our example, let's say we want an inputText component whose text content is 'end' aligned. If you weren't considering RTL locales, you could code this as:

This, however, will be right aligned regardless of locale. This is where isRTL() comes to the rescue. This is how we would code this to be locale aware:

The af:isRTL() EL function returns true if we are rendering in RTL, so we can use it to pick the appropriate text alignment.

Friday, March 9, 2012

Webservice: Part 3- Create, compile and publish WS using JDK only (No App. Server)

In Part 1 i have introduced the web services, and how to create, implement and publish WS then show the resulting WSDL.

After that in Part 2 i have implemented a Java Requester for the Web Service created in part 1.

In this part i will implement a multithreading version of the Endpoint Publisher to accept concurrent requests.

Multithreading the Endpoint Publisher

In the examples so far, the Endpoint publisher has been single-threaded and, therefore, capable of handling only one client request at a time: the published service completes the processing of one request before beginning the processing of another request. If the processing of the current request hangs, then no subsequent request can be processed unless and until the hung request is processed to completion.

In production mode, the Endpoint publisher would need to handle concurrent requests so that several pending requests could be processed at the same time. If the underlying computer system is, for example, a symmetric multiprocessor (SMP), then separate CPUs could process different requests concurrently.

On a single-CPU machine, the concurrency would occur through time sharing; that is, each request would get a share of the available CPU cycles so that several requests would be in some stage of processing at any given time. In Java, concurrency is achieved through multithreading. At issue, then, is how to make the Endpoint publisher multithreaded. The JWS framework supports Endpoint multithreading without forcing the programmer to work with difficult, error-prone constructs such as the synchronized block or the wait and notify method invocations.

An Endpoint object has an Executor property defined with the standard get/set methods. An Executor is an object that executes Runnable tasks; for example, standard Java Thread instances. (The Runnable interface declares only one method whose declaration is public void run().) An Executor object is a nice alternative to Thread instances, as the Executor provides high-level constructs for submitting and managing tasks that are to be executed concurrently.

The first step to making the Endpoint publisher multithreaded is thus to create an Executor class such as the following very basic one:

The class MyThreadPool creates a pool of 10 threads, using a fixed-size queue to store the threads that are created under the hood. If the pooled threads are all in use, then the next task in line must wait until one of the busy threads becomes available.

All of these management details are handled automatically. The MyThreadPool class overrides a few of the available methods to give the flavor.

A MyThreadPool object can be used to make a multithreaded Endpoint publisher. Here is the revised publisher, which now consists of several methods to divide the work:

Once the ThreadPoolWorker has been coded, all that remains is to set the Endpoint publisher's executor property to an instance of the worker class. The details of thread management do not intrude at all into the publisher.

The multithreaded Endpoint publisher is suited for lightweight production, but this publisher is not a service container in the true sense; that is, a software application that readily can deploy many web services at the same port.

A web container such as Tomcat, which is the reference implementation, is better suited to publish multiple web services.

References:
Java Web Services: Up and Running, 1st Edition

Webservice: Part 2- Create, compile and publish WS using JDK only (No App. Server)

In part 1 i gives an introduction to web services,then created, implemented and published a WS, after that show the resulting WSDL.

In this part i will show you how to implement a Java Requester of the Web Service created in part 1.

A Java Requester of the Web Service

Example 1. Java client for the Java web service

The Java client uses the same URL with a query string, but the Java client explicitly creates an XML qualified name, which has the syntax namespace URI:local name.

A URI is a Uniform Resource Identifier and differs from the more common URL in that a URL specifies a location, whereas a URI need not specify a location. In short, a URI need not be a URL. For now, it is enough to underscore that the Java class java.xml.namespace.QName represents an XML-qualified name.

In this example, the namespace URI is provided in the WSDL, and the local name is the SIB class name TimeServerImpl with the word Service appended. The local name occurs in the service section, the last section of the WSDL document.

Once the URL and QName objects have been constructed and the Service.create method has been invoked, the statement of interest:

Executes. Recall that, in the WSDL document, the portType section describes, in the style of an interface, the operations included in the web service. The getPort method returns a reference to a Java object that can invoke the portType operations.

The port object reference is of type eg.com.tm.ws.ts.TimeServer, which is the SEI type. The Java client invokes the two web service methods; and the Java libraries generate and process the SOAP messages exchanged transparently to enable the successful method invocations.

In part 3 i will show you how to implement WS created in part 1 to accept concurrent requests.

Webservice: Part 1- Create, compile and publish WS using JDK only (No App. Server)

This is 3 parts series as the following:
  1. Part1: introduction to web services, create, implement and publish WS then show the resulting WSDL.
  2. Part2: A Java Requester of the Web Service created in part 1.
  3. Part3: Multithreading the Endpoint Publisher version for the same service created in part 1.
What Are Web Services?

Although the term web service has various, imprecise, and evolving meanings, a glance at some features typical of web services will be enough to get us into coding a web service and a client, also known as a consumer or requester. As the name suggests, a web service is a kind of webified application, that is, an application typically delivered over HTTP (Hyper Text Transport Protocol).

A web service is thus a distributed application whose components can be deployed and executed on distinct devices. For instance, a stock-picking web service might consist of several code components, each hosted on a separate business-grade server, and the web service might be consumed on PCs, handhelds, and other devices.

Web services can be divided roughly into two groups, SOAP-based and REST-style. The distinction is not sharp because, as a code example later illustrates, a SOAP-based service delivered over HTTP is a special case of a REST-style service. SOAP originally stood for Simple Object Access Protocol but, by serendipity, now may stand for Service Oriented Architecture (SOA) Protocol.

Deconstructing SOA is nontrivial but one point is indisputable: whatever SOA may be, web services play a central role in the SOA approach to software design and development. (This is written with tongue only partly in cheek. SOAP is officially no longer an acronym, and SOAP and SOA can live apart from one another.)