Showing posts with label jee. Show all posts
Showing posts with label jee. Show all posts

Friday, December 27, 2013

JSF: Passing parameters to JSF action methods from page directly, a nice feature of JavaEE 6+

One of the JSF 2+ nice features presented in Java enterprise edition JavaEE 6+, is that you can pass parameters to any action components action method like commandButton or commandLink components.
Based on that you can minimize the number of methods inside your managed bean.

In addition, to minimize many parameters to set inside the bean to be used by action to decide navigation logic, which reduce memory consumption if your beans in scopes greater than request scope.
How it works:
  1. Open your favorite IDE, I am going to use Netbeans 7.4.1. (Use any IDE that supports JavaEE 6 or 7).

  2. Create web project.
    File --> New Project --> Java Web (left pan) --> Web Application (right pan) --> Next.

  3. Name it whatever you like (JSFeatures for me)--> Next --> Server Glassfish4 --> Java EE 7 Web profile --> Context path "/JSFeatures" --> Next.


  4. From frameworks chose "Java Server Faces" --> Finish.


  5. You should have project structure like this:


  6. Right click on the JSFeatures project --> new "JSF Managed Bean". and its name and config like this:

  7. With the bean opened in the editor page, copy and paste the following code after package statement:
  8. Open the index.xhtml which is generated by default, and copy the following code and past it in your file:

  9. Right click on the index.xhtml then --> Run; you should see something like this:

  10. Click submit button and watch h:outputText value, its value should be "Hi there I am an action method."

  11. Now everything is working fine. Let us do the actual work I need to demonstrate.

  12. Change addNumbers() method signature to the following (without restarting the application server):
    1. Bean method:

    2. Then your button call to:

    3. Press the button and output text value should be:

  13. 13. Do it one more time:
    1. Bean method:

    2. Then your button call to:

    3. Press the button and output text value should be:

Note: the parameter could be with different parameters type not expected to be the same type, also method could return a value for navigation to other pages, in this example it returns null to be on the same page.

I liked this feature too much enjoy it, very helpful and handy, and happy coding.

References:
1- JavaEE 7 tutorial (7.5 Navigation Model).

Thursday, June 13, 2013

JEE: Java EE 7 (Glassfish v4.0) is out, putting the productivity at your hands.


My participation:

I am so proud of being part of Adopt-A-JSR program and my involvement in the testing, evaluating and evangelist JEE 7 JSRs and related technologies.
Alongside FishCAT program that target the enhancement and stabilizing Glassfish version 4.0.

Java EE 7 is out:

The most interesting and productive shipped with plumbing of cutting-edge (innovative) technology support; Java Enterprise Edition 7 (JEE 7) is out for public, as promised to be released in Q2 of 2013. The JSR 342 Java Platform, Enterprise Edition 7 could be downloaded from here.

Java EE 7 release is being designed with primary focus on the following features:

  1. Higher Productivity.
  2. HTML5 Support.

Alongside JEE 7 specification release, its modular and most efficient reference implementation application server Glassfish v4.0 is out for development of JEE 7 applications, and could be downloaded from glassfish.org web site. In addition, it is the world's first Java EE 7 Application Server.

Glassfish.org web site redesigned with new clear, fresh design as well. It looks very neat.

For release notes, it could be downloaded from here.

There are also many examples to get start, which could be found in documentation section.

Java EE 7 IDE is out:

For sake of development and get your hands dirt with JEE 7 specification that should be tested on Glassfish v4.0, there is a Netbeans 7.3.1 IDE, which includes support for JEE 7 full JSRs stack. It could be also downloaded from netbeans.org. Also, bear in mind that Netbeans JEE version includes Glassfish v4.0.

Consult the following page to see more IDEs (Integrated Development Environment) that supports Java EE 7 development: IDEs and plugins.

Try, Develop and have fun

As by now you have the JEE7 specification, Glassfish v4.0 and supported IDE Netbeans v7.3.1 (everything you need comes out-of-the-box without any plugin), so what are you waiting for, click to download and develop to get the feel of new smile of the technology.

Maven Development

For maven fans to develop a Java EE7 application here is the minimal POM pom.xml file:


For Java EE 7 Full Platform

For Java EE 7 Web Profile

For other Java EE 7 JSRs coordination, please visit Java EE 7 Maven Coordinates Wiki link.

Webcasts and Developer days

Besides the finished event "Java EE 7 Launch Webcast", there is another java developer day covering Java EE 7, SE, and Embedded named "Java Developer Day - June 25 - Java SE, Java EE & Java Embedded" that will be online at Tuesday, June 25, 2013, register here.

Tutorials and examples

Visit Java EE 7 Documentation: JEE 7 Tutorial, for full tutorials and examples on how to use the specification alongside its JSRs.

All my sessions, hacks and code contribution could be downloaded from this link under Adopt-A-JSR organization under Github Java EE 7 Hacks, codes and sessions.

Thursday, March 21, 2013

JEE7: Where we are now, Glassfish v4 and JEE7 roadmap.

GlassFish 4.0 is intended to be the next major release in Project GlassFish which will be in Q2 2013.This release will implement the Java EE 7 specifications which will be released also at Q2 of 2013 as well.

Glassfish v4 is now under testing, project FishCAT maintain this by the contribution of all JCP members, JUGs, and individual for delivering the most stable and functional reference implementation for JEE7 specs.

FishCAT is a GlassFish Community Acceptance Testing program. The main goal of this program is to provide an opportunity to the community to significantly influence the quality of GlassFish as well as to get early feedback on stability and usability through testing early builds.

The release is being designed with primary focus on the following features:

  1. Higher Productivity.
  2. HTML5 Support.

JEE 7 Specification Status

Specification Status Links
Java EE 7 Platform JSR 342 Public Review list, project
Concurrency Utilities for Java EE (JSR 236) Proposed Final Draft list, project, javadocs
Java Persistence API 2.1 (JSR 338) Proposed Final Draft list, project, javadocs
Java API for RESTful Web Services 2.0 (JSR 339) Proposed Final Draft
list, project, javadocs
Servlets 3.1 (JSR 340) Public Review 
list, project, javadocs
Expression Language 3.0 (JSR 341) Public Review
list, project, javadocs
Java Message Service 2.0 (JSR 343) Proposed Final Draft
list, project, javadocs
JavaServer Faces 2.2 (JSR 344) Public Review
list, project, javadocs 
Enterprise JavaBeans 3.2 (JSR 345) Public Review
list, project, javadocs
Context & Dependency Injection 1.1 (JSR 346) Public Review
list, project, javadocs
Bean Validation 1.1 (JSR 349) Public Review
list, project, javadocs
Batch Applications for the Java Platform (JSR 352) Proposed Final Draft
list, project, javadocs
Java API for JSON Processing (JSR 353) Proposed Final Draft
list, project, javadocs
Java API for WebSocket (JSR 356) Public Review
list, project, javadocs
Java EE Connector Architecture 1.7 (A MR of JSR 322) Maintenance Review list, project, javadocs
Interceptors 1.2 (A MR of JSR 318) Maintenance Review list, project, javadocs

For more visit the following links :

  1. Glashfish v4 roadmap.
  2. FishCAT project.


Saturday, February 16, 2013

Mac: How to start any JavaEE servers on MAC

Here I will explain how you can start any JavaEE server on MAC OS X. The example here applies on any server like (IBM websphere, Oracle Weblogic, Tomcat, TomEE and Glassfish …. Etc.) The same steps on MAC, but the difference is that you should be familiar with the starting up files location for each server.

Lets take for the sake of demonstration the glassfish 3.2.1.1 server for our example here, Oh! Let’s starts.
  1. First if you don’t have Glassfish 3.2.1.1 (the .zip version), then go to download it first from here.
  2. Unzip it at your favorite location.
  3. Open new terminal window.
  4. Navigate to your installation folder manually using CD command with TAB for ease of navigation, or jump to step 5.
  5. Open new finder window (Command + N), and navigate to you server location that you have unzipped it at before.
  6. On terminal write cd, then drag and drop the bin folder from finder window into the terminal window, as the following Figure 1.

    Figure 1

  7. Hit enter and you should see the following as Figure 2.

    Figure 2

  8. At the terminal type the following “./asadmin” and hit return, you should notice that the prompt has changed as in Figure 3.
    Don’t forget the “./”, as if you just have typed “asadmin” you will prompted from bash shell that this command is not recognized, because the asadmin is not a bash command.

    Figure 3

  9. At the terminal type the following command “start-domain domain1” and the terminal should output the following if everything goes correct in Figure 4.

    Figure 4

  10. To test your progress, open your favorite browser and type the following in the address bar http://localhost:4848/ and you should see the admin page of glassfish server as Figure 5.

    Figure 5

  11. Finally to stop the server, from the terminal type “stop-domain domain1”

Saturday, December 8, 2012

Glassfish3+ & ADF 11g: Developing ADF apps on Glassfish using Jdeveloper 11g

There was no opportunity before to develop an Oracle ADF (Application Development Framework) applications on any open source application server such as Tomcat, or Glassfish, while Glassfish is the Oracle reference implementation now for JEE specifications. The only way is to develop on Oracle Weblogic application server. Even using oracle enterprise pack (OEPE) for development on eclipse IDE.

Nowadays oracle releases the ADF essentials.With the new Oracle ADF Essentials which is offering you now the ability to deploy applications that leverage Oracle ADF on the open source Glassfish 3.1 server.

At Oracle ADF Essentials home page you can check what are supported in comparison with the full ADF library, and also there are a lot of tutorials for learning the framework.

Now will get an introduction on how to setup the development environment, then we will develop a small application using Jdeveloper 11g and deploy it on the Glassfish 3.1.2.2 application server.

  • Setting up the environment:

    1. Download the following if you don’t have any of them:ADF essential library (11.1.2.3), JDeveloper 11g (11.1.2.3.0) and Glassfish 3.1.2.2.
    2. Install Jdeveloper 11g and Glassfish server and check that everything is up and running.
    3. Once ADF essential library downloaded, we need to unzip it inside the lib folder of Glassfish domain1 (or any domain you have created) this will get you an adf-essentials.zip file.

    4. To install ADF essentials:

      1. Copy the adf-essentials.zip file into the lib(on a default windows install this would be: "C:\glassfish3\glassfish\domains\domain1\lib\ext") folder of your glassfish domain.
      2. In lib folder open command window and issue a "unzip -j adf_essentials.zip"


      3. Note: you should use "-j" option with unzip (JDK program) command or you will ends up with folders not the jar files, try it and you will see.

    5. After successful extraction of the ADF libraries to the directory. Now you can start the Glassfish server (you can start your domain by the following command inside "bin" folder of your "domain" "asadmin start-domain domain1" from command line console, wait for domain to start then you should ends up with message "Command start-domain executed successfully.").

    6. We need to configure the glassfish to work with application of ADF type:
      1. Invoke the admin console of glassfish (http://localhost:4848) and log into your admin account.
      2. Go to Configurations->Server-config->JVM Settings and choose the JVM Options tab
      3. Add the following entries:
        1. -XX:MaxPermSize=512m (note this entry should already exist so just make sure it has a big enough value)
        2. -Doracle.mds.cache=simple
    7. There is a new extension ("Glassfish 1.3" as time of writing) that allows you to start and stop an external GlassFish instance, as well as start it in debug mode (which will allow JDeveloper to remotely debug your application as it runs on the server. Also a button that will invoke the web admin console of Glassfish.

    8. After installing Jdeveloper, open it, the extension is available from help->check for updates, or you can download it directly from here, and then use help->check for updates pointing to the local zip file (Thanks Shay Shmeltzer's who developed this extension).

    9. After the Jdeveloper finished download and the installation of the extension, you should find 4 glassfish buttons in the menu.


    10. Go to Tools -> Preferences -> Glassfish Preferences, here you can configure the glassfish paths and configurations you like.

  • Developing and deploying the ADF application:

    1. Creating and configuring the application to work with Glassfish:

      1. In JDeveloper choose File -> new, the New Gallery window will pop up, from right hand menu choose General-> Applications, and then from left hand choose Fusion Web Application.


      2. After successful application creation.
      3. Go into the project properties of your viewController project, under the deployment section click to edit the deployment profile that is defined there.
      4. Go to Platform and choose Glassfish 3.1 from the drop down list. Click ok to go back to your project properties.
      5. Under Java EE Application section in project properties change the Java EE web application name and context to the same value "ADFGF" (for ease of access when deploy the application).
      6. Go to Application -> Application Properties-> Deployment
      7. Go to Platform and choose Glassfish 3.1 from the drop down list. Click ok to go back to your project.
      8. This step will make sure that JDeveloper will automatically add the necessary ADF libraries to the EAR file that is being generated for deployment on Glassfish.

    2. Developing and Deploying the application:

      1. Right click on viewController project and choose new.
      2. Under Web Tier -> JSF/Facelets -> Page -> Ok.
      3. File name: TestADFGF.jsf, under the managed bean tab name: testADFGF leave the others with default values. Click ok.
      4. The page will be opened in visual editor.
      5. Drag and drop any components you like as a command button, check box, choose date and choose color component.
      6. We need to create application server connection.
      7. Start the application server from glassfish start icon in the JDeveloper menu.
      8. From Application servers Navigator, right click on application servers -> new. From New Gallery windows choose General-> Connections -> Application Server Connection -> ok.
      9. In the new windows Connection name: Glassfish3122, type: Glassfish 3.1 next.
      10. Provide your application server username and password then next.
      11. Configure your ports and host name, next.
      12. In the final step with glassfish running hit test connection button and the four testing steps should succeed.
      13. Go to your Application->Deploy and deploy either to an EAR file or directly to a Glassfish server connection that you created.
      14. After successful deployment you should get the following message:
      15. Open you browser and type the following URL (http://localhost:9090/ADFGF/faces/TestADFGF.jsf), you should see the following result:
      16. Things should just work, but if they don't then look up the server.log in the log directory and check out what error is in there.

Congratulations, you did it, now you are have the capabilities to develop any JSF/ADF applications from JDeveloper and host it on Glassfish 3.1.2.2.

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.

Saturday, July 14, 2012

JEE: Java Naming and Directory Interface API (JNDI)

The Java Naming and Directory Interface (JNDI) API provides naming and directory functionality, enabling applications to access multiple naming and directory services, including existing naming and directory services, such as LDAP, NDS,DNS, and NIS.

The JNDI API provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes.

Using JNDI, a Java EE application can store and retrieve any type of named Java object, allowing Java EE applications to coexist with many legacy applications and systems.

Java EE naming services provide application clients, enterprise beans, and web components with access to a JNDI naming environment. A naming environment allows a component to be customized without the need to access or change the component’s source code. A container implements the component’s environment and provides it to the component as a JNDI naming context.

A Java EE component can locate its environment naming context by using JNDI interfaces. A component can create a javax.naming.InitialContext object and look up the environment naming context in InitialContext under the name java:comp/env.

A component’s naming environment is stored directly in the environment naming context or in any of its direct or indirect subcontexts.

A Java EE component can access named system-provided and user-defined objects. The names of system-provided objects, such as JTA UserTransaction objects, are stored in the environment naming context java:comp/env. The Java EE platform allows a component to name user-defined objects, such as enterprise beans, environment entries, JDBC DataSource objects, and message connections. An object should be named within a subcontext of the naming environment according to the type of the object.

For example, enterprise beans are named within the subcontext java:comp/env/ejb, and JDBC DataSource references are named within the subcontext java:comp/env/jdbc.


JEE: Java EE Connector Architecture (JCA)

The Java EE Connector architecture is used by tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged in to any Java EE product.

A resource adapter is a software component that allows Java EE application components to access and interact with the underlying resource manager of the EIS.

Because a resource adapter is specific to its resource manager, a different resource adapter typically exists for each type of database or enterprise information system.

The Java EE Connector architecture also provides a performance-oriented, secure, scalable, and message-based transactional integration of Java EE based web services with existing EISs that can be either synchronous or asynchronous.

Existing applications and EISs integrated through the Java EE Connector architecture into the Java EE platform can be exposed as XML-based web services by using JAX-WS and Java EE component models.

Thus JAX-WS and the Java EE Connector architecture are complementary technologies for enterprise application integration (EAI) and end-to-end business integration.

The Java EE 6 platform requires Java EE Connector architecture 1.6.


Wednesday, July 11, 2012

ADF: ADF & JSF Object Scope Lifecycles

At runtime, you pass data to pages by storing the needed data in an object scope where the page can access it. The scope determines the lifespan of an object. Once you place an object in a scope, it can be accessed from the scope using an EL expression.

For example, you might create a managed bean named foo, and define the bean to live in the Request scope. To access that bean, you would use the expression #{requestScope.varName}.

There are three types of scopes in a standard JSF application:
  • applicationScope: The object is available for the duration of the application.

  • sessionScope: The object is available for the duration of the session.

  • requestScope: The object is available for the duration between the time an HTTP request is sent until a response is sent back to the client.

In addition to the standard JSF scopes, ADF Faces provides the following scopes:
  • pageFlowScope: The object is available as long as the user continues navigating from one page to another. If the user opens a new browser window and begins navigating, that series of windows will have its own pageFlowScope scope.

  • viewScope: The object is available until the ID for the current view changes. Use viewScope scope to hold values for a given page.

  • backingBeanScope: Used for managed beans for page fragments and declarative components only. The object is available for the duration between the time an HTTP request is sent until a response is sent back to the client. This scope is needed because there may be more than one page fragment or declarative component on a page, and to avoid collisions between values, any values must be kept in separate scope instances. Use backingBeanScope scope for any managed bean created for a page fragment or declarative component.
Note:
--------
Because these are not standard JSF scopes, EL expressions must explicitly include the scope to reference the bean. For example, to reference theMyBean managed bean from the pageFlowScope scope, your expression would be #{pageFlowScope.MyBean}.

Object scopes are analogous to global and local variable scopes in programming languages. The wider the scope, the higher the availability of an object.

During their lifespan, these objects may expose certain interfaces, hold information, or pass variables and parameters to other objects.

For example, a managed bean defined in sessionScope scope will be available for use during multiple page requests. However, a managed bean defined in requestScope scope will be available only for the duration of one page request.

Finally:
-----------
When determining what scope to register a managed bean with or to store a value in, always try to use the narrowest scope possible. Use the sessionScope scope only for information that is relevant to the whole session, such as user or context information. Avoid using the sessionScope scope to pass values from one page to another.


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.



Wednesday, April 11, 2012

JPA: Dynamic search builder, the power of annotation, reflection and generics.

JPA (Java persistence API) is a powerful tool for domain objects mapping, and object oriented view perspective of database.

Always I used to use JPA in my projects, but JPA2 introduces extra feature that facilitate the generic way of persisting, merging, deleting and searching. Also introduces dynamic criteria API, which I was looking for.

But with time I have to change the dynamic query or do it myself or else to create new dynamic one which the panic way.

I need a component to search dynamically based on passed object attributes value, and not changed by the time.

For example if I have Bank that has (id, name, address, and state object), and I have created a bank object with name and address has values construct the JPQL SELECT statement (SELECT b FROM Bank b where b.name = :name AND b.address = :address) and search by it and so on.

I have developed a component to implement the above case called DynamicQueryBuilder with advanced techniques, and configurations.

In this article I will describe how I built this component with support of annotation, reflection and generics. In the code snippets you will find a brief description about each line of code and methods, the annotation developed to support the component and I will describe also the overall functionality of the component and how to call it to work dynamically…

Wednesday, March 21, 2012

JEE6: Who Needs Aspect-Oriented Programming?

In Java EE, there is rarely an obvious use case for AOP.

According to Wikipedia, aspectoriented programming aims to separate reusable functionality from the business logic:

“In computing, aspectoriented programming (AOP) is a programming paradigm which aims to increase modularity by allowing the separation of cross-cutting concerns. AOP forms a basis for aspect-oriented software development.”
AOP was a hot topic a few years ago, but it never really took off in J2EE—and for good reason.

Aspects Are Commodities The integral parts of the Enterprise JavaBeans (EJB) 1.0 specification (JSR 318) in early 1998 were aspects. The developer had to develop the Bean class and the Remote and Home interfaces but none of the cross-cutting aspects. Threading, pooling, security, transactions, session handling, and even persistence were configurable aspects cleanly separated from the business logic.

The cross-cutting functionality was configurable in the early EJB 1.0 days with POJOs.

With the advent of EJB 1.1 and J2EE, Java classes were replaced with XML, and the recent Java EE 5 and Java EE 6 specifications made XML optional. You can configure the vast majority of all use cases with annotations and override them with XML.

Although the whole EJB 1.0 idea was based on aspects, you will find only two mentions of the word aspect in the original specification in different contexts.

AOP and EJB 1.0 were “invented” nearly at the same time.

In J2EE, the configurable decoration of an EJB bean with, for example, transactions was just an integral part of the development experience. Other frameworks
provided the same functionality but called that functionality AOP.

You will have a number of aspects by defining a simple EJB 3.1 bean. For example, a stateless EJB 3.1 bean comes with transaction and lifecycle aspects out of the box.

The method greet() is never invoked directly. The container dispatches the invocations to free EJB instances from the pool. Also, transactions are started before each method invocation.

The method call is processed by a chain of default and configurable aspects until it reaches the actual business logic. Outside the application server, you would probably implement the same functionality with the decorator pattern or with a more generic solution, such as AOP.

* For complete article by Adam Bien in Java Magazine check it out here

Monday, March 19, 2012

JPA: Query, incompatible types compilation error

I have faced a problem while I am writing a generic JPA query like the following:

Compile it and you will get the following error in Jdeveloper 11.1.2.1.0
• Error(200,37): incompatible types.

It works for Query.getResultList(), but it doesn't work for Query.getSingleResult().

A work around solves the problem which is, cast to T as (T) query.getSingleResult();

After investigation the perfect solution is to rewrite the following statement:

To be:

Use TypedQuery instead of Query and JDeveloper will remove all "Unchecked conversions from Object to T unsound but tolerated" warnings.

Note: that TypedQuery introduced in JPA 2.

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