Latest Entries »

Wednesday, May 30, 2012

Installation of Hudson/Jenkins, Sonar plugins and configure SpringSource Tool Suite (STS IDE)


Software Installers Repository

All the required software and SDKs can be found in the internet, please download it from the respective sites.


Prerequisites
JDK 1.6
STS IDE


Installation and basic Configurations


1.       Start the STS IDE
2.       Go to HelpàDashboard
3.       Find “Hudson”
4.       Select the check box and click on the install



This completes the installation of Hudson plugin.



Now we will discuss about the configuration of Hudson

1.       Go to WindowàShow viewàOther
2.       Find “builds”
3.       Select OK


4.       Go to “New Build Server Location”
5.       Select “Add build server”
6.       Choose “Hudson” then Next
7.       Enter the details required


8.       After filling all the details validate the settings by clicking “Validate”
9.       Finally Click “Finish”

Following actions can be performed using this plugin

1.       Open last build
2.       Last build: details and console output
3.       Plan
4.       Run Build
5.       History


On mouse hover you will find the following updates


Installation of Sonar

1.       Go to HelpàInstall New Software




3.       Select Sonar check box
4.       Go Next to Finish

Adding project to Sonar
1.       Go to project explorer
2.       Select project
3.       Right click and navigate to configure
4.       Select “Associate with Sonar…”


GroupId and ArtifactId can’t be found for our project as they are related to Maven configurations and we are using ant (free style project)


Wednesday, April 4, 2012

How to change the default JRE for tomcat bundle in Liferay

To change the default liferay tomcat JRE, go to C:\Sravan Modugula\workspace\bundles\tomcat-6.0.18\bin and modify setenv.bat file

if not "%JAVA_HOME%" == "" (
    set JAVA_HOME=
)

set JRE_HOME=C:\Program Files (x86)\Java\jre6

set JRE_HOME=%CATALINA_HOME%/jre1.5.0_17/win -------------- old

set JAVA_OPTS=%JAVA_OPTS% -Xmx1024m -XX:MaxPermSize=256m -Dfile.encoding=UTF8 -Duser.timezone=GMT -Djava.security.auth.login.config="%CATALINA_HOME%/conf/jaas.config" -Dorg.apache.catalina.loader.WebappClassLoader.ENABLE_CLEAR_REFERENCES=false

Saturday, July 24, 2010

When does it make sense to choose an abstract class over an interface?

In Java, under what circumstances would you use abstract classes instead of interfaces? When you declare a method as abstract, can other nonabstract methods access it? In general, could you explain what abstract classes are and when you might use them?

Those are all excellent questions: the kind that everyone should ask as they begin to dig deeper into the Java language and object-oriented programming in general

Yes, other nonabstract methods can access a method that you declare as abstract.
But first, let's look at when to use normal class definitions and when to use interfaces. Then I'll tackle abstract classes.
Class vs. interface

Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.
For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.
With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need.
This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity.

Interface vs. abstract class

Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.
Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.




Thanks to Tony Sintes

Friday, July 23, 2010

What is the difference between an application server and a Web server ?

Taking a big step back, a Web server serves pages for viewing in a Web browser, while an application server provides methods that client applications can call. A little more precisely, you can say that:

A Web server exclusively handles HTTP requests, whereas an application server serves business logic to application programs through any number of protocols.

Let's examine each in more detail.

The Web server
A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page. To process a request, a Web server may respond with a static HTML page or image, send a redirect, or delegate the dynamic response generation to some other program such as CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScript’s, or some other server-side technology. Whatever their purpose, such server-side programs generate a response, most often in HTML, for viewing in a Web browser.

Understand that a Web server's delegation model is fairly simple. When a request comes into the Web server, the Web server simply passes the request to the program best able to handle it. The Web server doesn't provide any functionality beyond simply providing an environment in which the server-side program can execute and pass back the generated responses. The server-side program usually provides for itself such functions as transaction processing, database connectivity, and messaging.

While a Web server may not itself support transactions or database connection pooling, it may employ various strategies for fault tolerance and scalability such as load balancing, caching, and clustering—features oftentimes erroneously assigned as features reserved only for application servers.

The application server
As for the application server, according to our definition, an application server exposes business logic to client applications through various protocols, possibly including HTTP. While a Web server mainly deals with sending HTML for display in a Web browser, an application server provides access to business logic for use by client application programs. The application program can use this logic just as it would call a method on an object (or a function in the procedural world).

Such application server clients can include GUIs (graphical user interface) running on a PC, a Web server, or even other application servers. The information traveling back and forth between an application server and its client is not restricted to simple display markup. Instead, the information is program logic. Since the logic takes the form of data and method calls and not static HTML, the client can employ the exposed business logic however it wants.

In most cases, the server exposes this business logic through a component API, such as the EJB (Enterprise JavaBean) component model found on J2EE (Java 2 Platform, Enterprise Edition) application servers. Moreover, the application server manages its own resources. Such gate-keeping duties include security, transaction processing, resource-pooling, and messaging. Like a Web server, an application server may also employ various scalability and fault-tolerance techniques.
An example

As an example, consider an online store that provides real-time pricing and availability information. Most likely, the site will provide a form with which you can choose a product. When you submit your query, the site performs a lookup and returns the results embedded within an HTML page. The site may implement this functionality in numerous ways. I'll show you one scenario that doesn't use an application server and another that does. Seeing how these scenarios differ will help you to see the application server's function.

Scenario 1: Web server without an application server
In the first scenario, a Web server alone provides the online store's functionality. The Web server takes your request, then passes it to a server-side program able to handle the request. The server-side program looks up the pricing information from a database or a flat file. Once retrieved, the server-side program uses the information to formulate the HTML response, then the Web server sends it back to your Web browser.

To summarize, a Web server simply processes HTTP requests by responding with HTML pages.

Scenario 2: Web server with an application server
Scenario 2 resembles Scenario 1 in that the Web server still delegates the response generation to a script. However, you can now put the business logic for the pricing lookup onto an application server. With that change, instead of the script knowing how to look up the data and formulate a response, the script can simply call the application server's lookup service. The script can then use the service's result when the script generates its HTML response.

In this scenario, the application server serves the business logic for looking up a product's pricing information. That functionality doesn't say anything about display or how the client must use the information. Instead, the client and application server send data back and forth. When a client calls the application server's lookup service, the service simply looks up the information and returns it to the client.

By separating the pricing logic from the HTML response-generating code, the pricing logic becomes far more reusable between applications. A second client, such as a cash register, could also call the same service as a clerk checks out a customer. In contrast, in Scenario 1 the pricing lookup service is not reusable because the information is embedded within the HTML page. To summarize, in Scenario 2's model, the Web server handles HTTP requests by replying with an HTML page while the application server serves application logic by processing pricing and availability requests.

Caveats
Recently, XML Web services have blurred the line between application servers and Web servers. By passing an XML payload to a Web server, the Web server can now process the data and respond much as application servers have in the past.

Additionally, most application servers also contain a Web server, meaning you can consider a Web server a subset of an application server. While application servers contain Web server functionality, developers rarely deploy application servers in that capacity. Instead, when needed, they often deploy standalone Web servers in tandem with application servers. Such a separation of functionality aids performance (simple Web requests won't impact application server performance), deployment configuration (dedicated Web servers, clustering, and so on), and allows for best-of-breed product selection.



Thanks to Tony Sintes

Thursday, June 24, 2010

Maven install:install-file (Access is denied)

Sometimes silly mistakes will build more frustration and this is the same happened to me while installing an artifact from the command prompt (cmd)

Initially I was driven into the error

C:\Sravan.Modugula>mvn install:install-file -Dfile=C:\lib
-DgroupId=org.portletfaces -DartifactId=portletfaces-bridge-impl -Dversion=2.0
.0.ALPHA4 -Dpackaging=jar -DgeneratePom=true
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'install'.
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Default Project
[INFO] task-segment: [install:install-file] (aggregator-style)
[INFO] ------------------------------------------------------------------------
[INFO] [install:install-file {execution: default-cli}]
[INFO] Installing D:\lib to C:\repository\org\portletfaces\portletfaces-bridge-i
mpl\2.0.0.ALPHA4\portletfaces-bridge-impl-2.0.0.ALPHA4.jar
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Error installing artifact 'org.portletfaces:portletfaces-bridge-impl:jar'
: Error installing artifact: D:\lib (Access is denied)

[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: < 1 second
[INFO] Finished at: Thu Sep 23 18:31:03 IST 2010

After reading some expert opinions and several irrelevant blogs I came to a conclusion that I haven’t specified the complete path @ -Dfile. We must specify the complete path including jar file name.

-Dfile=D:\lib\portletfaces-bridge-impl-2.0.0.ALPHA4.jar

Here is the working command

mvn install:install-file -Dfile=D:\lib\portletfaces-bridge-impl-2.0.0.ALPHA4.jar -DgroupId=org.portletfaces -DartifactId=portletfaces-bridge-impl -Dversion=2.0.0.ALPHA4 -Dpackaging=jar -DgeneratePom=true

I hope this information will help few readers.

Wednesday, June 23, 2010

Manually installing missing artifacts

We declare all the repositories and the dependencies in the pom.xml, if any dependencies are missing from the repository you will get the exception like

Missing:
----------
1) org.portletfaces:portletfaces-bridge-impl:jar:2.0.0.ALPHA4

Try downloading the file manually from the project website.

Then, install it using the command:
mvn install:install-file -DgroupId=org.portletfaces -DartifactId=portletfaces-bridge-impl -Dversion=2.0.0.ALPHA4 -Dpackaging=jar -Dfile=/path/to/file

Alternatively, if you host your own repository you can deploy the file there:

mvn deploy:deploy-file -DgroupId=org.portletfaces -DartifactId=portletface
s-bridge-impl -Dversion=2.0.0.ALPHA4 -Dpackaging=jar -Dfile=/path/to/file -Durl=
[url] -DrepositoryId=[id]

Path to dependency:
1) test.jsf2:jsf2:war:0.0.1-SNAPSHOT
2) org.portletfaces:portletfaces-bridge-impl:jar:2.0.0.ALPHA4

To resolve this issue you can manually add the required jar files to the local repository using the following command

mvn install:install-file -Dfile=D:\lib\portletfaces-bridge-impl-2.0.0.ALPHA4.jar -DgroupId=org.portletfaces -DartifactId=portletfaces-bridge-impl -Dversion=2.0.0.ALPHA4 -Dpackaging=jar -DgeneratePom=true

Wednesday, May 12, 2010

Unit testing with JUnit and EasyMock

Error while displaying content...

JUnit 4.x Quick Tutorial

How does JUnit work?


JUnit is a library packed in a jar file. Among other things it contains a tool (called test runner) to run your test files. It is not an automated testing tool: you still have to write your test files by hand. JUnit does give you some support so that you can write those test files more conveniently.

Suppose you have a class C that you want to test. We will write the tests in a new class; let’s call it Ctest. This Ctest is our test file. Actually, test class is a better name. We will typically group the tests in Ctest in a bunch of methods called test methods. You will see an example soon.

To actually test C we need to execute its test class Ctest. This is done by calling JUnit’s test runner tool; we pass the name Ctest to it. That’s all. JUnit will then execute Ctest for you.

JUnit will report how many of the test methods in Ctest succeed, and how many fail. The detail of each failure will be reported; this will be in the form of a print of Java’s stack trace leading to the location of the failure.

Locate it first

If you don’t have JUnit yet, you need to download it (from JUnit site). To use it you just need the jar file. A full download also contains its documentation.

Now locate where this jar file is; it is usually called:

junit-version-number.jar

To use JUnit you will need to add the full path to this jar to your class path. We will see examples latter.

A simple example

Let us consider the simple class below. This is the class that we want to test; but first let me explain a bit about what it is.

The class is called Subscription; an instance of it represents a subscription to something (e.g. newspaper, but it doesn’t really matter here). Each subscription has its total price, stored in the variable price. This price is in Euro-cent. It also has the length of the subscription, given in months.


















For example, new Subscription(1000,2) will create a new subscription of 1000 Euro-cent for the total period of 2 months.

By the way, the class has a number of bugs; e.g. pricePerMonth is supposed to return the price per month in euro. However it calculates the price in cent.

Let’s write a test

Let us write two simple tests to check if pricePerMonth correctly calculates the price per month:

1. If we have a subscription of 200 cent for a period of 2 month, its monthly price should be 1 euro, right?

2. The monthly price is supposed to be rounded up to the nearest cent. So, if we have a subscription of 200 cent for a period of 3 month, its monthly price should be 0:67 euro.

Of course we can write tests without JUnit; but this tutorial is about JUnit. So here is how we write them in JUnit.

Each of the tests above will be implemented as a test method; you then group your test methods in a test class. Usually you would group all the test methods that test a certain target class C is a test class called CTest, but you can also have multiple test classes if you want, and call them whatever you want.

Here is my test class implementing the above two tests:











The marker @Test is called an annotation in Java. When we later execute JUnit’s test runner it needs to know which methods in your test class are test methods (e.g. you may have several helper methods in your test class). The @Test is used to mark that a method is a test method.

In the first test (test_returnEuro) we first create a Subscription; we call it S. Then we want to check that S.pricePerMonth() will return the expected value of 1.0. The checking is done by the code:

assertTrue(S.pricePerMonth() == 1.0)

By the way, the annotation @Test and the method assertTrue are things exported by the JUnit library; so you need the imports as in the above code to use them.

Compiling and executing your test

Next we want to execute the above test class (SubscriptionTest). I’ll show how to do this from a console. If you use an IDE the steps are a bit different.

Open a console. You first need to compile the test class, and then you can execute it. The commands are (in Windows):

prompt> javac -cp .; SubscriptionTest.java

prompt> java -cp .; org.junit.runner.JUnitCore SubscriptionTest

(In e.g. Mac you probably have to use ':' instead of ';')

The first command will compile the test class. The second will execute JUnit’s test runner; we pass to it the name of your test class.

This is what you will get from JUnit; it reports that both tests fail. Notice also that it reports which lines exactly in your test class fail.

Time: 0,015
There were 2 failures:

1) test_returnsEuro(SubscriptionTest)
java.lang.AssertionError:
...
at SubscriptionTest.test_returns_Euro(SubscriptionTest.java:13)
...
2) test_roundUp(SubscriptionTest)
...
at SubscriptionTest.test_roundUp(SubscriptionTest.java:19)
...

Tests run: 2, Failures: 2

The next thing you want to do is to fix your Subscription class and then test it again. We keep fixing it until we get no more failures. You may in the mean time also want to add more tests to your test class.

Monday, March 29, 2010

The Quest for Excellence

Excellence should be the goal of every software engineer and programmer. We should seek to build good software that makes meaningful contributions to society. We should seek to constantly improve our talents and skills to be able to design better, program more effectively and become the best that we can. In our desire for excellence however, we should always consider at the cost of becoming better in our field and how it will effect our life.

There are many at the top of their fields, who are very successful in their careers but whose lives lack meaning and substance. We should not neglect family and friendships or compromise our health or our integrity to make it “to the top”. True success is the measure of one’s life, not just one’s career. It is better to be a good person and an average programmer than to be an exceptional programmer and a lousy person. It is however, better to be both.

Achieving the best of both your professional and personal life is hard, but trying to achieve your greatest potential in your career while failing in other areas in life is harder in the long run and very unsatisfying. The trick to achieving excellence in both is to make a balanced effort all around. This requires planning, preparation and keeping our priorities what they should be. It may mean turning down good opportunities in order to give time to more important things. It also means that we will have to give up what we want now, for what we want in the long run.

Acheiving excellence is a process, something we must constantly work on and improve. We must give the best of ourselves, day after day to the things that really matter. By so doing, we can live a more full life, satisfying and meaningful in all aspects.

Friday, March 26, 2010

Quality Code

No one writes perfect code. Programming is a process that takes a lot of planning, reviewing, and testing until an individual or team is satisfied that what they have produced is reasonably free of bugs and errors and works the way it should. However, despite our best efforts to produce quality code, customers will inevitably find ways to break it. They will find unexpected ways to use what we make, creating unexpected results.

The importance of writing good code depends on the type of system or program you are creating. For example, when programming a chess game, it is less important to eliminate bugs than when creating a program used to access someone’s bank account or deploy safety airbags in someone’s car. When we write code can cause financial problems, injury or even death, we better make sure that our code works reasonably well. This requires additional planning, revision and testing. Failure to do so can result in the loss of millions of dollars or even human lives.

Ultimately, the organization that sells the code should be responsible for its quality. If it is important that the product they sell be bug free, they should do additional testing to ensure quality. The only exception to this is when a programmer intentionally creates malicious code or leaves security flaws to later exploit the code for their own gain or to cause damage and harm. In such cases, both the organization and the programmer should be held responsible. Organizations should be responsible to hire good programmers, fire bad ones and create an environment in which quality is emphasized and good code is produced.

With that said, every programmer should take pride in their work and try to create as high-quality, bug-free code as possible. Additional planning in the design phase of a project and knowing your customer and how they will interact with what you are creating can help. Education, research, peer programming and using good programming techniques, data structures and algorithms will also lead to higher quality code. As always, the code produced should go through some sort of quality assurance, to make sure that it works reasonably well.

Making these extra efforts will not always guarantee that your code will be bug-free. It will however help it to perform better, have less bugs and cause less problems. Good code should be the goal of every programmer.

Wednesday, November 11, 2009

Google Talk: Run Multiple Instances or Login as Multiple Users

If you have several Google talk accounts, you may want to run multiple instances of Google talk at once. Here’s how to do it.

Many users, including myself, like to have several different personalities on IM–Work, play, etc. By default Google talk with only allow you to run instance of the program at a time. Here’s how to get around that…
Run Google talk with the following switch: /nomutex
If you installed Google talk to the default location, you can easily create a shortcut to this setting.

1. Right-click on the desktop
2. Select New
3. Select Shortcut
4. Paste this into the text box:
"c:\program files\google\google talk\googletalk.exe" /nomutex
5. Click Next6. Name it whatever: Google Talk Multiple, etc.
7. Click OK until you are done.

How to Run Multiple Yahoo! Messengers and Login to Multi Yahoo! Messengers Accounts

For Yahoo! Messenger with Voice 8 users, it’s now possible to run multiple instances of Yahoo!. Messengers (polygamy feature) and log into multiple Y!Msgr accounts with just a simple registry hack. So if you need to open and log-in multiple Yahoo! Messenger accounts as you have a few Yahoo! ID or various other reason, just use the small registry registration file below that once click, will modify and merge the registry setting required to run and execute multiple Yahoo! Messengers at the same time on a computer.

Download ym8multi.zip, extract it and run “ym8multi.reg” contained inside the archive. Once the registry is patched, you can now starting and running multi Yahoo! Messenger with different login or Yahoo! ID accounts. If you want to uninstall the patch/hack, download the ym8multi_uninst.zip uninstaller which contains ym8multi_uninst.reg. Once double click on this uninstaller registration registry value file, it will edit the registry value and set it to disable the ability for Y! M 8 to launch multiple copies of instances.



If you prefer to edit and change the registry setting yourself manually, without using the above registry registration file, simply launch the registry editor (type regedit at Run command), and navigate to the following registry branch:

HKEY_CURRENT_USER\Software\yahoo\pager\Test

Then, on the right pane, right click on the registry editor and select “New”, then create a new DWORD registry value. Name the new registry key as Plural, and assign it the value of 1 (decimal). If some case, the value of 2 should also works. To disable or disallow multiple instances of Yahoo Messengers, simply change and set the “Plural” registry key’s value to 0, or delete the “Plural” key.

Monday, November 2, 2009

Marker Interface in Java

Marker Interface most of the people know the definition, but many of them are not aware of the purpose of the Marker Interface and how it works. Very often I heard the question from my friends that the Marker Interface doesn't have methods then what is the use of Marker Interface.

One of the basic feature of Java Programing Language is that it mandates a separation between Interfaces and Classes. Interfaces are used in Java to specify the behavior of the derived class.

While working on the Java Programing Language many of the programmers might have observed the Interfaces which doesn't have no behavior. In other words they are just empty Interface definitions. These Interfaces are knows as Marker Interfaces.

Basic Definition: Interfaces with empty body.
Example: Serializable, Cloneable, Remote, EventListener


Marker Interfaces are also called as Tag Interfaces because they tag all the derived classes into a category based on their purpose. If we consider a real time example for this scenario, lets pick Cloneable from the abouve examples given. All classes that implement Cloneable Interface can be cloned by calling clone(); method. Now the Java Compiler checks to make sure that if the clone(); method is called on a class and the class implements the Cloneable Interface. If we have the Object obj and call clone(); method on this as

MyObject obj = new MyObject();
MyObject ref = (MyObject)(obj.clone());

Here if the MyObject doesn't implement the Cloneable Interface and Cloneable is not implemented any of the super class that MyObject inherits from, the compiler will mark this line as error. This is because the clone() method may only be called by objects of the type Cloneable.

Here our Cloneable Interface is an Interface with empty body, but still it serving a major role.

To create a copy of any Object, in our case we have MyObject to create a clone for this Object we need to have a clone(); method which should implement Cloneable Interface.

The above scenario clearly states that we are marking the class Cloneable so that the Object can be Cloneable. For this purpose we have Marker Interfaces in Java.

When ever we implement Serializable, Cloneable JVM understands that this thing is to be serialized or cloned and no methods involved in this process.

Hope this article will clear your ambiguities about Marker Interfaces.

Tuesday, October 27, 2009

JavaServer Faces Interview Questions

1. What is JSF (or JavaServer Faces)?

A server side user interface component framework for Java™ technology-based web applications. JavaServer Faces (JSF) is an industry standard and a framework for building component-based user interfaces for web applications.

JSF contains an API for representing UI 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. What are the advantages of JSF?

The major benefits of JavaServer Faces technology are:

  • JavaServer Faces architecture makes it easy for the developers to use. In JavaServer Faces technology, user interfaces can be created easily with its built-in UI component library, which handles most of the complexities of user interface management.
  • Offers a clean separation between behavior and presentation.
  • Provides a rich architecture for managing component state, processing component data, validating user input, and handling events.
  • Robust event handling mechanism.
  • Events easily tied to server-side code.
  • Render kit support for different clients
  • Component-level control over statefulness
  • Highly 'pluggable' - components, view handler, etc
  • JSF also supports internationalization and accessibility
  • Offers multiple, standardized vendor implementations

3. What are differences between struts and JSF?

In a nutshell, Faces has the following advantages over Struts:

· Eliminated the need for a Form Bean

· Eliminated the need for a DTO Class

· Allows the use of the same POJO on all Tiers because of the Backing Bean

The primary advantages of Struts as compared to JavaServer Faces technology are as follows:

· Because Struts is a web application framework, it has more sophisticated controller architecture than does JavaServer Faces technology. It is more sophisticated partly because the application developer can access the controller by creating an Action object that can integrate with the controller, whereas JavaServer Faces technology does not allow access to the controller. In addition, the Struts controller can do things like access control on each Action based on user roles. This functionality is not provided by JavaServer Faces technology.

· Struts includes a powerful layout management framework, called Tiles, which allows you to create templates that you can reuse across multiple pages, thus enabling you to establish an overall look-and-feel for an application.

· The Struts validation framework includes a larger set of standard validators, which automatically generate both server-side and client-side validation code based on a set of rules in a configuration file. You can also create custom validators and easily include them in your application by adding definitions of them in your configuration file.

The greatest advantage that JavaServer Faces technology has over Struts is its flexible, extensible UI component model, which includes:

· A standard component API for specifying the state and behavior of a wide range of components, including simple components, such as input fields, and more complex components, such as scrollable data tables. Developers can also create their own components based on these APIs, and many third parties have already done so and have made their component libraries publicly available.

· A separate rendering model that defines how to render the components in various ways. For example, a component used for selecting an item from a list can be rendered as a menu or a set of radio buttons.

· An event and listener model that defines how to handle events generated by activating a component, such as what to do when a user clicks a button.

· Conversion and validation models for converting and validating component data.


4. What are the available implementations of JavaServer Faces?

The main implementations of JavaServer Faces are:

  • Reference Implementation (RI) by Sun Microsystems.
  • Apache MyFaces is an open source JavaServer Faces (JSF) implementation or run-time.
  • ADF Faces is Oracle’s implementation for the JSF standard.





6. What typical JSF application consists of?

A typical JSF application consists of the following parts:

  • JavaBeans components for managing application state and behavior.
  • Event-driven development (via listeners as in traditional GUI development).
  • Pages that represent MVC-style views; pages reference view roots via the JSF component tree.

7. What Is a JavaServer Faces Application?

JavaServer Faces applications are just like any other Java web application. They run in a Servlet container, and they typically contain the following:

  • JavaBeans components containing application-specific functionality and data.
  • Event listeners.
  • Pages, such as JSP pages.
  • Server-side helper classes, such as database access beans.

In addition to these items, a JavaServer Faces application also has:

  • A custom tag library for rendering UI components on a page.
  • A custom tag library for representing event handlers, validators, and other actions.
  • UI components represented as stateful objects on the server.
  • Backing beans, which define properties and functions for UI components.
  • Validators, converters, event listeners, and event handlers.
  • An application configuration resource files for configuring application resources.

8. What is Managed Bean?

JavaBean objects managed by a JSF implementation are called managed beans. A managed bean describes how a bean is created and managed. It has nothing to do with the bean's functionalities.

9. What is Backing Bean?

Backing beans are JavaBeans components associated with UI components used in a page. Backing-bean management separates the definition of UI component objects from objects that perform application-specific processing and hold data.

The backing bean defines properties and handling-logics associated with the UI components used on the page. Each backing-bean property is bound to either a component instance or its value. A backing bean also defines a set of methods that perform functions for the component, such as validating the component's data, handling events that the component fires and performing processing associated with navigation when the component activates.

10. What are the differences between a Backing Bean and Managed Bean?

Backing Beans are merely a convention, a subtype of JSF Managed Beans which have a very particular purpose. There is nothing special in a Backing Bean that makes it different from any other managed bean apart from its usage.

What makes a Backing Bean is the relationship it has with a JSF page; it acts as a place to put component references and Event code.

Backing Beans

Managed Beans

A backing bean is any bean that is referenced by a form.

A managed bean is a backing bean that has been registered with JSF (in faces-config.xml) and it automatically created (and optionally initialized) by JSF when it is needed.


The advantage of managed beans is that the JSF framework will automatically create these beans, optionally initialize them with parameters you specify in faces-config.xml,

Backing Beans should be defined only in the request scope

The managed beans that are created by JSF can be stored within the request, session, or application scopes

Backing Beans should be defined in the request scope, exist in a one-to-one relationship with a particular page and hold the entire page specific event handling code. In a real-world scenario, several pages may need to share the same backing bean behind the scenes. A backing bean not only contains view data, but also behavior related to that data.

11. What is view object?

A view object is a model object used specifically in the presentation tier. It contains the data that must display in the view layer and the logic to validate user input, handle events, and interact with the business-logic tier. The backing bean is the view object in a JSF-based application. Backing bean and view object are interchangeable terms.





12. What is domain object model?

Domain object model is about the business object and should belong in the business-logic tier. It contains the business data and business logic associated with the specific business object.

13. What is the difference between the domain object model and a view object?

In a simple Web application, a domain object model can be used across all tiers, however, in a more complex Web application, a separate view object model needs to be used. Domain object model is about the business object and should belong in the business-logic tier. It contains the business data and business logic associated with the specific business object. A view object contains presentation-specific data and behavior. It contains data and logic specific to the presentation tier.

14. What do you mean by Bean Scope?

Bean Scope typically holds beans and other objects that need to be available in the different components of a web application.

15. What are the different kinds of Bean Scopes in JSF?

JSF supports three Bean Scopes. viz.,

  • Request Scope: The request scope is short-lived. It starts when an HTTP request is submitted and ends when the response is sent back to the client.
  • Session Scope: The session scope persists from the time that a session is established until session termination.
  • Application Scope: The application scope persists for the entire duration of the web application. This scope is shared among all the requests and sessions.

16. What is the difference between JSP-EL and JSF-EL?

JSP-EL

JSF-EL

In JSP-EL the value expressions are delimited by ${…}.

In JSF-EL the value expressions are delimited by #{…}.

The ${…} delimiter denotes the immediate evaluation of the expressions, at the time that the application server processes the page.

The #{…} delimiter denotes deferred evaluation. With deferred evaluation, the application server retains the expression and evaluates it whenever a value is needed.


note:As of JSF 1.2 and JSP 2.1 ,the syntax of both expression languages has been unified.

17. What are the main tags in JSF?

JSF application typically uses JSP pages to represent views. JSF provides useful special tags to enhance these views. Each tag gives rise to an associated component. JSF (Sun Implementation) provides 43 tags in two standard JSF tag libraries:

  • JSF Core Tags Library.
  • JSF Html Tags Library.

18. How do you declare the managed beans in the faces-config.xml file?

The bean instance is configured in the faces-config.xml file:

login

com.developersBookJsf.loginBean

request

This means: Construct an object of the class com.developersBookJsf.loginBean, give it the name login, and keep it alive for the duration of the request.

19. How to declare the Message Bundle in JSF?

We can declare the message bundle in two ways:
(Let’s assume com.developersBookJsf.messages is the properties file)

1. The simplest way is to include the following elements in faces-config.xml file:

com.developersBookJsf.messages

message


2. Alternatively, you can add the f:loadBundle element to each JSF page that needs access to the bundle:

20. How to declare the page navigation (navigation rules) in faces-config.xml file?

Navigation rules tells JSF implementation which page to send back to the browser after a form has been submitted. We can declare the page navigation as follows:

/index.jsp

login

/welcome.jsp



This declaration states that the login action navigates to /welcome.jsp, if it occurred inside /index.jsp.

21. What if no navigation rule matches a given action?

If no navigation rule matches a given action, then the current page is redisplayed.





22. What are the JSF life-cycle phases?

The six phases of the JSF application lifecycle are as follows (note the event processing at each phase):

1. Restore view
2. Apply request values; process events
3. Process validations; process events
4. Update model values; process events
5. Invoke application; process events
6. Render response

23. Explain briefly the life-cycle phases of JSF?

1. Restore View: A request comes through the FacesServlet controller. The controller examines the request and extracts the view ID, which is determined by the name of the JSP page.
2. Apply request values: The purpose of the apply request values phase is for each component to retrieve its current state. The components must first be retrieved or created from the FacesContext object, followed by their values.
3. Process validations: In this phase, each component will have its values validated against the application's validation rules.
4. Update model values: In this phase JSF updates the actual values of the server-side model, by updating the properties of your backing beans.
5. Invoke application: In this phase the JSF controller invokes the application to handle Form submissions.
6. Render response: In this phase JSF displays the view with all of its components in their current state.

24. What does it mean by render kit in JSF?

A render kit defines how component classes map to component tags that are appropriate for a particular client. The JavaServer Faces implementation includes a standard HTML render kit for rendering to an HTML client.

25. Is it possible to have more than one Faces Configuration file?

We can have any number of config files. Just need to register in web.xml.
Assume that we want to use faces-config(1,2,and 3),to register more than one faces configuration file in JSF, just declare in the web.xml file

javax.faces.CONFIG_FILES

/WEB-INF/faces-config1.xml,

/WEB-INF/faces-config2.xml,

/WEB-INF/faces-config3.xml