Tech Passion

Articles, Tutorials, Interview Questions on Java, J2EE, Open Source Java Frameworks (Struts, Struts2, Spring, Hibernate, MyFaces), Javascript Libraries, CSS

Java Collection Questions

Posted by Admin on July 13, 2009

1.) What are the differences between ArrayList and LinkedList?

Answer
An ArrayList is a List implementation backed by a Java array, similar to the Vector class. As the number of elements in the collection increases, the internal array grows to fit them. If there are lots of growth periods, performance degrades as the old array needs to be copied into the new array. However, random access is very quick as it uses an array index to access.

With a LinkedList, the List implementation is backed by a doubly linked list data structure, allowing easy inserts/deletions anywhere in the structure, but really slow random accesses as the access must start at an end to get to the specific position.

Which you use really depends on the type of operations you need to support.

Posted in Core Java, Java | Leave a Comment »

Garbage collection tuning in Java 5.0

Posted by Admin on June 3, 2009

Written by Peter V. Mikhalenko
Peter V. Mikhalenko is a Sun certified professional who works for Deutsche Bank as business consultant.

Memory management is a major factor that affects software application performance. More time is usually spent allocating and deallocating memory than performing actual data computation.

While C++ offers direct control over when memory is allocated and freed up, Java attempts to abstract memory management by using garbage collection to reclaim memory that the program no longer needs. However, the “pause” associated with garbage collection has been the central argument against using Java when real-time performance is required.

Garbage collection is typically a periodic process that pauses normal program execution to analyze object references and reclaim memory that was allocated but can no longer be accessed by reference. In large Java applications, the pause for garbage collection can last several seconds, which is enough time to disrupt any type of real-time communication or control system.

Consequently, the memory abstraction provided by garbage collection requires some developers to think more carefully about memory management. Even though Java does not provide the same level of control over memory deallocations as C++, programming patterns can still make a huge difference in the memory performance of Java applications.

In this article, I will briefly review Java 5.0 capabilities in the tuning of garbage collection.
Principles of garbage collection in Java 5.0

The goal of a new Java 1.5 feature called ergonomics is to provide good performance from the JVM with a minimum of command-line tuning. Ergonomics attempts to match the best selection of proper garbage collector, heap size, and runtime compiler for an application.

When does the choice of a garbage collector matter to the user? For many applications, it doesn’t matter. That is, the application can perform within its specifications in the presence of garbage collection with pauses of modest frequency and duration. An example where this is not the case would be a large application that scales well to a large number of threads, processors, sockets, and a lot of memory.

An object is considered garbage when it can no longer be reached from any pointer in the running program. The most straightforward garbage collection algorithms simply iterate over every reachable object. Any objects left over are then considered garbage. The time this approach takes is proportional to the number of live objects, which is prohibitive for large applications maintaining lots of live data.

Starting with Java 2, the virtual machine incorporated a number of different garbage collection algorithms that are combined using generational collection. While naive garbage collection examines every live object in the heap, generational collection exploits several empirically observed properties of most applications to avoid extra work. The most important of these observed properties is so-called infant mortality. There are a plenty of objects that “have died” soon after being allocated. Iterator objects, for example, are often alive for the duration of a single loop. To optimize for this scenario, memory is managed in generations, or memory pools holding objects of different ages. Garbage collection occurs in each generation when the generation fills up. Objects are allocated in a generation for younger objects or the young generation, and most objects die there because of infant mortality.

If the garbage collector has become a bottleneck, you may wish to customize the generation sizes. Check the verbose garbage collector output, and then explore the sensitivity of your individual performance metric to the garbage collector parameters.

At initialization, a maximum address space is virtually reserved but not allocated to physical memory unless it is needed. The complete address space reserved for object memory can be divided into the young and tenured generations. The young generation consists of eden plus two survivor spaces. Objects are initially allocated in eden. One survivor space is empty at any time and serves as a destination of the next, copying collection of any live objects in eden and the other survivor space. Objects are copied between survivor spaces in this way until they are old enough to be tenured, or copied to the tenured generation. A third generation closely related to tenured is the permanent generation. This generation is special because it holds data needed by the virtual machine to describe objects that do not have an equivalent at the Java language level. For example, objects describing classes and methods are stored in the permanent generation.
Performance considerations

There are two metrics of performance of a Java application (and garbage collection in particular): throughput and pauses. Throughput is the percentage of total time not spent in garbage collection, considered over long periods of time. Throughput includes time spent in allocation (but tuning for speed of allocation is generally not needed). Pauses are the times when an application appears unresponsive because garbage collection is occurring.

Some users are sensitive to other considerations as well. For instance, footprint is the working set of a process, measured in pages and cache lines. On systems with limited physical memory or many processes, footprint may dictate scalability. Promptness is the time between when an object becomes dead and when the memory becomes available; this is an important consideration for distributed systems, including remote method invocation (RMI).

In general, a particular generation sizing chooses a trade off between these considerations. For example, a very large young generation may maximize throughput, but it does so at the expense of footprint, promptness, and pause times. You can minimize young generation pauses by using a small young generation at the expense of throughput.

When you want to improve the performance of your application with larger numbers of processors, you should use the throughput collector. You can enable the throughput collector by using the command-line flag -XX:+UseParallelGC. You can control the number of garbage collector threads with the ParallelGCThreads command-line option -XX:ParallelGCThreads=. The maximum pause time goals are specified with the command-line flag -XX:MaxGCPauseMillis=. This is interpreted as a hint to the throughput collector that pause times of milliseconds or less are desired. There are plenty of generation sizes adjustment options such as -XX:YoungGenerationSizeIncrement= for the young generation and -XX:TenuredGenerationSizeIncrement= for the tenured generation.

If your application would benefit from shorter garbage collector pauses and can afford to share processor resources with the garbage collector when the application is running, I suggest using the concurrent low pause collector. A concurrent collection will start if the occupancy of the tenured generation grows above the initiating occupancy (i.e., the percentage of the current heap that is used before a concurrent collection is started). The initiating occupancy by default is set to about 68%. You can set it with the parameter -XX:CMSInitiatingOccupancyFraction= where is a percentage of the current tenured generation size. You can use the concurrent collector in a mode in which the concurrent phases are done incrementally. This mode (referred to here as “i-cms”) divides the work done concurrently by the collector into small chunks of time, which are scheduled between young generation collections. This feature is useful when applications that need the low pause times provided by the concurrent collector are run on machines with small numbers of processors.
Fine-tuning garbage collection

The command-line argument -verbose:gc prints information at every collection. If it is switched on, you will see similar output at every garbage collection. For example:

[GC 325407K->83000K(776768K), 0.2300771 secs]

[GC 325816K->83372K(776768K), 0.2454258 secs]

[Full GC 267628K->83769K(776768K), 1.8479984 secs]

There are two minor collections and one major one (Full GC). The flag -XX:+PrintGCDetails prints additional information about the collections. The flag -XX:+PrintGCTimeStamps will additionally print a timestamp at the start of each collection. Listing A is what you will see when both flags are set.

Additionally, the information is shown for a major collection delineated by Tenured. The tenured generation usage was reduced here to about 10% and took approximately 0.13 seconds.

A number of parameters affect generation size. At initialization of the virtual machine, the entire space for the heap is reserved. You can specify the size of the space reserved with the -Xmx option. If the value of the -Xms parameter is smaller than the value of the -Xmx parameter, not all of the reserved space is immediately committed to the virtual machine. The different parts of the heap (permanent generation, tenured generation, and young generation) can grow to the limit of the virtual space as needed.

By default, the virtual machine grows or shrinks the heap at each collection to try to keep the proportion of free space to live objects at each collection within a specific range. This target range is set as a percentage by the parameters -XX:MinHeapFreeRatio= and -XX:MaxHeapFreeRatio=, and the total size is bounded below by -Xms and above by -Xmx. Unless you have problems with pauses, try granting as much memory as possible to the virtual machine. The default size (64MB) is often too small. You can find descriptions of other VM options on Sun’s Web site.

You can also set a proportion of the heap dedicated to the young generation. The bigger the young generation, the less often minor collections occur. However, for a bounded heap size, a larger young generation implies a smaller tenured generation, which will increase the frequency of major collections. The optimal choice depends on the lifetime distribution of the objects allocated by the application. The young generation size is controlled by NewRatio. For example, setting -XX:NewRatio=3 means that the ratio between the young and tenured generation is 1:3. If desired, the parameter SurvivorRatio can be used to tune the size of the survivor spaces, but this is often not as important for performance. For example, -XX:SurvivorRatio=6 sets the ratio between each survivor space and eden to 1:6. Unless you find problems with excessive major collection or pause times, grant plenty of memory to the young generation.

Java 5.0 has implemented three different garbage collectors. The throughput collector uses a parallel version of the young generation collector. It is used if the -XX:+UseParallelGC option is passed on the command line. The concurrent low pause collector is used if the -Xincgc or -XX:+UseConcMarkSweepGC option is passed on the command line. In this case, the application is paused for short periods during the collection. The incremental low pause collector is used only if -XX:+UseTrainGC is passed on the command line. It will not be supported in future releases, but if you want more information, please see Sun’s documentation on using this collector. (Note: Do not use -XX:+UseParallelGC with -XX:+UseConcMarkSweepGC.)
Conclusion

Garbage collection can become a bottleneck in different applications depending on the requirements of the applications. By understanding the requirements of the application and the garbage collection options, it is possible to minimize the impact of garbage collection.

Posted in Core Java, Java | 1 Comment »

Difference between Struts and Struts2(Webwork + Struts)

Posted by Admin on June 2, 2009

1.  Servlet Dependency:
Actions in Struts1 have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse objects are passed to the execute method when an Action is invoked but in case of Struts 2, Actions are not container dependent because they are made simple POJOs. In struts 2, the servlet contexts are represented as simple Maps which allows actions to be tested in isolation. Struts 2 Actions can access the original request and response, if required. However, other architectural elements reduce or eliminate
the need to access the HttpServetRequest or HttpServletResponse directly.

2.  Action classes
Programming the abstract classes instead of interfaces is one of design issues of struts1 framework that has been resolved in the struts 2 framework. Struts1 Action classes needs to extend framework dependent abstract base class. But in case of Struts 2 Action class may or may not implement interfaces to enable optional and custom services. In case of Struts 2 , Actions are not container dependent because they are made simple POJOs. Struts 2 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is
not required. Any POJO object with an execute signature can be used as an Struts 2 Action object.

3.  Validation

Struts1 and Struts 2 both supports the manual validation via a validate method. Struts1 uses validate method on the ActionForm, or validates through an extension to the Commons Validator. However, Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the
properties class type and the validation context.


4.  Threading Model

In Struts1, Action resources must be thread-safe or synchronized. So Actions are singletons and thread-safe, there should only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts1 Actions and
requires extra care to develop. However in case of Struts2, Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty
or impact garbage collection.)


5.  Testability

Testing Struts1 applications are a bit complex. A major hurdle to test Struts1 Actions is that the execute method because it exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts1. But the Struts 2 Actions can be tested by instantiating the Action, setting properties and invoking methods. Dependency Injection support also makes testing simpler. Actions in struts2 are simple POJOs and are framework independent,  hence testability is quite easy in struts2.

6.  Harvesting Input
Struts1 uses an ActionForm object to capture input. And all ActionForms needs to extend a framework dependent base class. JavaBeans cannot be used as ActionForms, so the developers have to create redundant classes to capture input. However Struts 2 uses Action properties (as input
properties independent of underlying framework) that eliminates the need for a second input object, hence reduces redundancy. Additionally in struts2, Action properties can be accessed from the web page via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Even rich object types, including business or domain objects, can be used as input/output objects.


7.  Expression Language

Struts1 integrates with JSTL, so it uses the JSTL-EL. The struts1 EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can also use JSTL, however it supports a more powerful and flexible expression language called “Object Graph Notation Language” (OGNL).

8.  Binding values into views
In the view section, Struts1 uses the standard JSP mechanism to bind objects (processed from the model section) into the page context to access. However Struts 2 uses a “ValueStack” technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows the reuse of views across a range of types which may have the same property name but different property types.

9.  Type Conversion
Usually, Struts1 ActionForm properties are all Strings. Struts1 uses Commons-Beanutils for type conversion. These type converters are per-class and not configurable per instance. However Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common
object types and primitives.

10.  Control Of Action Execution
Struts1 supports separate Request Processor (lifecycles) for each module, but all the Actions in a module must share the same lifecycle. However Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with
different Actions as needed.

Posted in Struts Framework | Tagged: , | 3 Comments »

SOA interview questions

Posted by Admin on June 2, 2009

What are the main benefits of SOA ?

SOA helps create greater alignment between IT and line of business while generating more flexibility – IT flexibility to support greater business flexibility. Your business processes are changing faster and faster and global competition requires the flexibility that SOA can provide.
SOA can help you get better reuse out of your existing IT investments as well as the new services you’re developing today. SOA makes integration of your IT investments easier by making use of well-defined interfaces between services. SOA also provides an architectural model for integrating business partners’, customers’ and suppliers’ services into an enterprise’s business processes. This reduces cost and improves customer satisfaction

What is a reusable Service?

It is an autonomous, reusable, discoverable, stateless functionality that has the necessary granularity, and can be part of a composite application or a composite service.
A reusable service should be identified with a business activity described by the service specifications (design-time contract).

A service’s constraints, including security, QoS, SLA, usage policies, may be defined by multiple run-time contracts, multiple interfaces (the WSDL for a SOAP Web Service), and multiple implementations (the code).

A reusable service should be governed at the enterprise level throughout its entire lifecycle, from design-time through run-time. Its reuse should be promoted through a prescriptive process, and that reuse should be measured.

Talking about Service identification, which approach between top-down and bottom-up methodologies encourages re-use and mantainance ?

Since the top-down approach is business-driven it can be practical to separate the different concerns of business and IT on different plans, providing a common ground in between. So in most situations it the most appropriate if you want to improve reuse and ROI in the medium/long term. Anyway

How can you achieve loose coupling in a soa ?

One strategy for achieving loose coupling is to use the service interface (the WSDL for a SOAP Web Service) to limit this dependency, hiding the service implementation from the consumer. Loose coupling can be addressed by encapsulating the service functionalities in a manner that limits the impact of changes to the implementation on the service interface. However, at some point you will need to change the interface and manage versioning without impacting service consumers, in addition to managing multiple security constraints, multiple transports, and other considerations

Do you recall any pattern which could be use to leverage loose coupling ?

The Mediation pattern, using an enterprise service bus (ESB), will help in achieving this.
Mediation will take loose coupling to the highest level. It will establish independence between consumers and providers on all levels, including message formats, message types (including SOAP, REST, XML, binary) and transport protocols (including HTTP, HTTPS, JMS).
Architecturally speaking this means the separation of concerns between consumers and providers on the transport, message type, and message format levels.

The Service of a SOA should be engineered as stateless or stateful ?

Service should be stateless. It may have a context within its stateless execution, but it will not have an intermediary state waiting for an event or a call-back. The retention of state-related data must not extend beyond a request/response on a service. This is because state management consumes a lot of resources, and this can affect the scalability and availability that are required for a reusable service.

What is composition of a Service ?

Composition is the process by which services are combined to produce composite applications or composite services. A composite application consists of the aggregation of services to produce an enterprise portal or enterprise process. A composite service consists of an aggregation of services that produces another reusable service. It’s just like combining electronic components to create a computer motherboard, and then using that motherboard in a computer. Think of the motherboard as a reusable composite service that is a component of the computer, and of the computer as the composite application.

How do I integrate my Legacy applications with SOA ?

Legacy applications are frequently at the core of your IT environment. With the right skills and tools, you need to identify discrete elements within your legacy applications and “wrap” them in standards-based interfaces and use them as services within your SOA.

How does the ESB fits in this picture ?

The Enterprise Service Bus is a core element of any SOA. ESBs provide the “any to any” connectivity between services within your own company, and beyond your business to connect to your trading partners. But SOA does not stop at just implementing an ESB. Depending on what your goals are, you may want to use an ESB to connect other services within your SOA such as information services, interaction services and business process management services. Additionally, you will need to consider development services and IT service management services. The SOA reference architecture can help you lay out an SOA environment that meets your needs and priorities. The ESB is part of this reference architecture and provides the backbone of an SOA but it should not be considered an SOA by itself.

What are the common pitfalls of SOA ?

One of the most common pitfalls is to view SOA as an end, rather than a means to an end. Developers who focus on building an SOA solution rather than solving a specific business problem are more likely to create complex, unmanageable, and unnecessary interconnections between IT resources.

Another common pitfall is to try to solve multiple problems at once, rather than solving small pieces of the problem. Taking a top-down approach—starting with major organization-wide infrastructure investments—often fails either to show results in a relevant timeframe or to offer a compelling return on investment.

What’s the difference between services and components?

Services are logical grouping of components to achieve business functionality. Components are implementation approaches to make a service. The components can be in JAVA, C#, C++ but the services will be exposed in a general format like Web Services.

What are ends, contract, address, and bindings?

These three terminologies on which SOA service stands. Every service must expose one or more ends by which the service can be available to the client. End consists of three important things where, what and how:-

Contract is an agreement between two or more parties. It defines the protocol how client should communicate with your service. Technically, it describes parameters and return values for a method.

An Address indicates where we can find this service. Address is a URL, which points to the location of the service.

Bindings determine how this end can be accessed. It determines how communications is done. For instance, you expose your service, which can be accessed using SOAP over HTTP or BINARY over TCP. So for each of these communications medium two bindings will be created.
Below figure, show the three main components of end. You can see the stock ticker is the service class, which has an end hosted on
www.soa.com with HTTP and TCP binding support and using Stock Ticker interface type.

soa interview questions

The concept of SOA is nothing new, however why everyone started to talk about SOA only in the last years ?

Yes I agree the basic concept of SOA aren’t new, however some technology technology changes in the last 10 years made service-oriented architecture more practical and applicable to more organizations than it was previously. Among this:

  • Universally-accepted industry standards such as XML, its many variants, and Web-services standards have contributed to the renewed interest in SOA.
  • Data governance frameworks, which are important to a successful SOA implementation, have well test and refined over the years.
  • A variety of enabling technologies and tools (e.g., modeling, development, infrastructure/middleware, management, and testing) have matured.

Understanding of business and business strategies has grown, shifting attention from technology to the people, cultural changes, and process that are key business success factors.

What is the most important skill you need to adopt SOA ? technical or cultural ?

Surely cultural
. SOA does require people to think of business and technology differently. Instead of thinking of technology first (e.g., If we implement this system, what kinds of things can we do with it?), practitioners must first think in terms of business functions, or services (e.g., My company does these business functions, so how can I set up my IT system to do those things for me most efficiently?).It is expected that adoption of SOA will change business IT departments, creating service-oriented (instead of technology-oriented) IT organizations.

Is SOA really needed on your opinion?

SOA is not for everyone. While SOA delivers significant benefits and cost savings, SOA does require disciplined enforcement of centralized governance principals to be successful. For some organizations, the cost of developing and enforcing these principals may be higher than the benefits realized, and therefore not a sound initiative.

Posted in SOA ESB Web Services | Tagged: | Leave a Comment »

JBoss Seam tutorial

Posted by Admin on June 2, 2009

To be useful, your application has to be a multitiered application that uses specific components for the presentation, business, and persistence tiers.
If you have already developed one multitiered application you know that lots of time is devoted to writing lots of “glue” code in order to connect your tier.

Starting from the presentation layer, in your forms  you’ll reference your JSF Beans, your JSF Beans will  in turn reference your Business classes, your Business classes will call your EJB maybe passing some wrapper Java Bean classes, your EJB will finally reach your DAO layer and do datapersistence.

So how can JBoss Seam help me ? I guess you already have asked yourself: why cannot I reference my EJB directly from my JSP page ?

Let me tell you, Seam it’s not only about this, but the same way when you want to conquer a location in a battle you need a bridgehead, so that’s your bridgehead.
Imagine how beatiful would be if in your JSP form you could reference directly your Entity Beans field, you push “Submit” and the data goes straight on the DB.
Imagine next if you need to query the data, simply reference your Session Bean doQuery Method.

Seam achieves this by eliminating the need for “plumbing” code. Essentially, we are allowing Seam to handle the plumbing and to have the business logic interact with the JSF pages themselves. One of the nice things about Seam is that even if you already have code you want to use, you will be able to
keep your existing EJBs and JSF pages, thus being able to maintain a mixed environment if you choose.

jboss seam tutorialHow can Seam do it ? to keep it simple, Seam uses Interceptors at all layer levels. By using  interceptors you’re allowed to use Seam specific annotations into already-existing classes. This will cut drammatically the time needed to develop “glue” code and leaving more time to spend actually developing the business functionality.

So let’s get how hands dirty, first of all download Seam from the distribution:

http://www.seamframework.org/Download

In this release we will use the stable 2.0.3 CR1 release. Now let’s see first in detail how to configure Seam Listeners.

I ) web.xml – Seam Servlet Listener

In order to initialize the Seam core services and to correctly manage some Seam contexts that are in common with standard web container contexts, you have to install the Seam servlet listener in your web.xml deployment descriptor:
<web-app>
. . .
<listener>
<listener-class>org.jboss.seam.servlet.SeamListener</listener-class>
</listener>
. . .
</web-app>

Ok, that’s one, let’s go on.

II ) faces-config.xml – JSF Phase Listener

At the heart of Seam’s component and context services is the Seam JSF phase listener. It receives events from the JSF runtime during request processing, allowing Seam to keep its various contexts in their proper state, among other things.

The Seam phase listener is installed in your faces-config.xml file:

<faces-config>
. . .
<lifecycle>
<phase-listener>org.jboss.seam.jsf.SeamPhaseListener</phase-listener>
</lifecycle>
. . .
</faces-config>

III ) ejb-jar.xml – EJB Seam Interceptor

The last tier that needs Seam glue is the EJB-tier. Here we’ll use the old  ejb-jar.xml. (Thought you got rid of it, isn’t it ?)  Here we just define SeamInterceptor for all the EJBs but of course you could choose to use it only for a subset of them.

<ejb-jar>
. . .
<assembly-descriptor>
<interceptors>
<interceptor>
<interceptor-class>
org.jboss.seam.ejb.SeamInterceptor
</interceptor-class>
</interceptor>
</interceptors>
<interceptor-binding>
<ejb-name>*</ejb-name>
<interceptor-class>
org.jboss.seam.ejb.SeamInterceptor
</interceptor-class>
</interceptor-binding>
</assembly-descriptor>
. . .
</ejb-jar>

The Seam interceptor allows EJB components to be used as Seam components, by “plugging” them into the Seam component life cycle when you annotate your EJBs with the Seam @Name annotation.

JNDI pattern : Seam’s components.xml

In order for Seam to work  with the EJB container, you need to include an entry for Seam’s core initialization component, and this entry needs to include a setting for the JNDI pattern that Seam should use to find your application’s EJB components in the JNDI services of the application server.
The following example shows how this setting is provided for the JBoss application
server

<?xml version=”1.0″ encoding=”UTF-8″?>
<components xmlns=”http://jboss.com/products/seam/components
xmlns:core=”http://jboss.com/products/seam/core
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=
http://jboss.com/products/seam/core http://jboss.com/products/seam/core-2.0.xsd
http://jboss.com/products/seam/components http://jboss.com/products/seam/components-2.0.xsd“>

<core:init jndi-pattern=”@jndiPattern@”/>

</components>

Seam Registration Example reloaded

Here we’ll use on example application provided with Seam distribution but we’ll add a few additions to make it more interesting. The example is located under the “registration” example folder. Let’s start from the Home page, register.xhtml

<f:view>
<h:form>
<s:validateAll>
<h:panelGrid columns=”2″>
Username: <h:inputText value=”#{user.username}required=”true”/>
Real Name: <h:inputText value=”#{user.name}required=”true”/>
Password: <h:inputSecret value=”#{user.password}required=”true”/>
</h:panelGrid>
</s:validateAll>
<h:messages/>
<h:commandButton value=”Register” action=”#{register.registerUser}“/>
</h:form>
</f:view>

Well if you’re practical with JSF you’ll notice nothing strange except..how does JSF resolves the “user” and “register” fields ? You say in a configuration file ? wrong answer!. JBoss Seam uses , as well as EJB 3.0, a lot of annotations. Let’s see our User Entity Bean and you’ll understand better:

  1. package org.jboss.seam.example.registration;
  2. import static org.jboss.seam.ScopeType.SESSION;
  3. import java.io.Serializable;
  4. import javax.persistence.Entity;
  5. import javax.persistence.Id;
  6. import javax.persistence.Table;
  7. import org.hibernate.validator.Length;
  8. import org.hibernate.validator.NotNull;
  9. import org.jboss.seam.annotations.Name;
  10. import org.jboss.seam.annotations.Scope;
  11. @Entity
  12. @Name(“user”)
  13. @Scope(SESSION)
  14. @Table(name=“users”)
  15. public class User implements Serializable
  16. {
  17. private static final long serialVersionUID = 1881413500711441951L;
  18. private String username;
  19. private String password;
  20. private String name;
  21. public User(String name, String password, String username)
  22. {
  23. this.name = name;
  24. this.password = password;
  25. this.username = username;
  26. }
  27. public User() {}
  28. @NotNull
  29. public String getName()
  30. {
  31. return name;
  32. }
  33. public void setName(String name)
  34. {
  35. this.name = name;
  36. }
  37. @NotNull @Length(min=5, max=15)
  38. public String getPassword()
  39. {
  40. return password;
  41. }
  42. public void setPassword(String password)
  43. {
  44. this.password = password;
  45. }
  46. @Id @NotNull @Length(min=5, max=15)
  47. public String getUsername()
  48. {
  49. return username;
  50. }
  51. public void setUsername(String username)
  52. {
  53. this.username = username;
  54. }
  55. @Override
  56. public String toString()
  57. {
  58. return “User(“ + username + “)”;
  59. }
  60. }
package org.jboss.seam.example.registration;

import static org.jboss.seam.ScopeType.SESSION;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.validator.Length;
import org.hibernate.validator.NotNull;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

@Entity
@Name("user")
@Scope(SESSION)
@Table(name="users")
public class User implements Serializable
{
   private static final long serialVersionUID = 1881413500711441951L;

   private String username;
   private String password;
   private String name;

   public User(String name, String password, String username)
   {
      this.name = name;
      this.password = password;
      this.username = username;
   }

   public User() {}

   @NotNull
   public String getName()
   {
      return name;
   }

   public void setName(String name)
   {
      this.name = name;
   }

   @NotNull @Length(min=5, max=15)
   public String getPassword()
   {
      return password;
   }

   public void setPassword(String password)
   {
      this.password = password;
   }

   @Id @NotNull @Length(min=5, max=15)
   public String getUsername()
   {
      return username;
   }

   public void setUsername(String username)
   {
      this.username = username;
   }

   @Override
   public String toString() 
   {
      return "User(" + username + ")";
   }
}

jboss seam tutorialAs we said, Jboss seam needs a component name specified by the @Name annotation. This name must be unique within the Seam application. So  JSF when meets the variable “user” delegates  Seam to resolve a context variable with a name “user”.

When Seam instantiates the  component, it binds the new instance of a User to a context variable in the component’s default context. The default context is specified using the @Scope annotation. In our case the User bean is a session scoped component

Our Entity Bean has a façade which will be accessed by our clients. The façade is a standard Stateless Session Bean, but with special Jboss Seam Annotations.

jboss seam ejb

Picture 1: presentation tier invoke the RegisterAction EJB.

  1. package org.jboss.seam.example.registration;
  2. import java.util.List;
  3. import javax.ejb.Stateless;
  4. import javax.persistence.EntityManager;
  5. import javax.persistence.PersistenceContext;
  6. import org.jboss.seam.annotations.In;
  7. import org.jboss.seam.annotations.Logger;
  8. import org.jboss.seam.annotations.Name;
  9. import org.jboss.seam.faces.FacesMessages;
  10. import org.jboss.seam.log.Log;
  11. import org.jboss.seam.annotations.Factory;
  12. import org.jboss.seam.annotations.datamodel.DataModel;
  13. @Stateless
  14. @Name(“register”)
  15. public class RegisterAction implements Register
  16. {
  17. @In
  18. private User user;
  19. @PersistenceContext
  20. private EntityManager em;
  21. @Logger
  22. private static Log log;
  23. @DataModel
  24. private List items=null;
  25. public String registerUser()
  26. {
  27. em.persist(user);
  28. log.info(“Registered new user #{user.username}”);
  29. return “/registered.jspx”;
  30. }
  31. @Factory(“items”)
  32. public void getItems() {
  33. List list = em.createQuery(“From User u order by u.name”).getResultList();
  34. items = list;
  35. }
  36. }
package org.jboss.seam.example.registration;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;

import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.datamodel.DataModel;

@Stateless
@Name("register")
public class RegisterAction implements Register
{

   @In
   private User user;

   @PersistenceContext
   private EntityManager em;

   @Logger
   private static Log log;

   @DataModel
   private List items=null;

   public String registerUser()
   {

         em.persist(user);
         log.info("Registered new user #{user.username}");
         return "/registered.jspx";

   }

   @Factory("items")
    public void getItems() {
        List list = em.createQuery("From User u order by u.name").getResultList();
        items = list;
   }

}

Let’s see in detail: well about the “name” annotation we have already discussed,

The @In annotation marks an attribute of the bean as injected by Seam. In this case, the attribute is injected from a context variable named user (the instance variable name).
The Seam @Logger annotation is used to inject the component’s Log instance.

Let’s move on the registerUser: this is the core method of the application which persist the data on the DB. Notice that it has no parameters because the Bean is injected with the @In annotation.

jboss seam tutorialMaybe you have noticed that this method contains a redirection: well you may asking what happened to JSF navigation rules ? well they still exist but Seam has a nice shortcut which is useful for small application : you can simply return the view as the outcome, eliminating the requirement for a navigation rule. For larger applications of course is better to keep a higher level of indirection and so using navigation rules.

Last piece of the puzzle are @DataModel and the @Factory annotation

Data models are pretty handy components when it’s necessary to display database data onto a presentation tier. This allows you a fairly simple way to look up the data, determine the selected row, and use it for computations and display purposes.

As you’ll see the DataModel will be used to populate the JSF DataTable element with the Values provided in the @Factory method getItems()

<h:dataTable var=”u” value=”#{items}rendered=”#{items.rowCount>0}“>
<h:column>

<f:facet name=”header”>
<h:outputText value=”username”/>
</f:facet>
<h:outputText value=”#{u.username}“/>

</h:column>

<h:column>

<f:facet name=”header”>
<h:outputText value=”password”/>
</f:facet>
<h:outputText value=”#{u.password}“/>

</h:column>

</h:dataTable>
So when JSF meets the variable “items” will delegate to the @Factory method getItems which will simply create a List of User objects.

@Factory(“items”)
public void getItems() {
List list = em.createQuery(“From User u order by u.name”).getResultList();
items = list;
}

Once instantiated the list will be stored in the variable

@DataModel
private List<User> items=null;

when this is clear, retrieving the single fields is just a piece of cake

<h:outputText value=”#{u.username}”/>
<h:outputText value=”#{u.password}”/>

jboss seam ejb

Picture 2: Data is queried using the RegisterAction’s Factory method.

JBoss Seam Project picture:

So this is how our Seam application looks like.
jboss seam tutorial
Picture 3: How a typical Seam project is made up.

jboss seam tutorialBefore packing, in the jboss-seam-registration.jar you need to add a seam property file: the seam.properties file is empty here but it is required for JBoss to know that this JAR file contains Seam EJB3 bean classes, and process the annotations accordingly.

One thing you might wonder what is the file is how do you connect to your Datasource: well that’s managed by the persistence.xml file which simply points to the Default HSQL Datasource

<persistence-unit name=”userDatabase”>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/DefaultDS</jta-data-source>
<properties>
<property name=”hibernate.hbm2ddl.auto” value=”create-drop“/>
</properties>
</persistence-unit>

If you want to build this application, the easiest way is simply replace the files that you find under the registration example provided with the Seam distribution. Siimply build and deploy your project with ant and you’re done !

Several Java EE APIs (EJB, JSF, etc.), as well as popular open source frameworks like Spring, make use of the concept of dependency injection. Injection involves the automatic, runtime insertion of a property value into a bean. This simple concept can greatly simplify development, especially in a Java EE environment.

The Seam component model also supports a more general version of dependency injection, called bijection. Standard dependency injection involves a one-time initialization of a bean reference within a component, typically done by some kind of container or other runtime service.

Seam introduces the notion of bijection as a generalization of injection.

In contrast to injection, bijection is:

  • contextual – bijection is used to assemble stateful components from various different contexts (a component from a “wider” context may even have a reference to a component from a “narrower” context)
  • bidirectional – values are injected from context variables into attributes of the component being invoked, and also outjected from the component attributes back out to the context, allowing the component being invoked to manipulate the values of contextual variables simply by setting its own instance variables
  • dynamic – since the value of contextual variables changes over time, and since Seam components are stateful, bijection takes place every time a component is invoked

Before seeing Seam bijection, let’s see what is Simple Injection, from an Example

  1. @Name(“MyBean”)
  2. public class MyBean {
  3. @In
  4. private OtherBean otherBean;
  5. public SomeBean getOtherBean() {
  6. return otherBean;
  7. }
  8. public void setOtherBean(OtherBean b)
  9. {
  10. otherBean = b;
  11. }
  12. }
@Name("MyBean") 
public class MyBean { 
@In 
private OtherBean otherBean; 

  public SomeBean getOtherBean() { 
   return otherBean;
  }
  public void setOtherBean(OtherBean b) 
 { 
  otherBean = b; 
 } 
}

Here, we’re annotating the formBean property on the Seam component MyBean, telling Seam to inject the value of this property whenever MyBean is invoked. In this case, we’re using @In with no arguments to inject an otherBean instance in MyBean class.

By default, Seam will search all of its contexts for a component with the same name as the annotated property “otherBean.” : the first one it finds (in an ordered search of contexts, starting from the event context and ending with application context) is used as the value of the annotated property. If no component of the given name is found anywhere, the injection will not happen, and the property will remain uninitialized.

JBoss Seam Bijection

As mentioned at the start of this section, Seam extends simple injection by introducing the concept of outjection, or the export of a component value from one component back into the scope where the component lives.

Let’s recall our previous Registration example and add some spice to it. The User Entity Bean will stay the same, we won’t change our model. Rather we add a new Stateless Bean, UserAction

  1. @Stateless
  2. @Name(“useraction”)
  3. public class UserAction implements UserItf {
  4. @In @Out private User user;
  5. @Out private List userList;
  6. @PersistenceContext private EntityManager em;
  7. public String addAndDisplay() {
  8. em.persist (user);
  9. user = new User ();
  10. userList = em.createQuery(“From User u order by u.name”).getResultList();
  11. return null;
  12. }
@Stateless 
@Name("useraction") 

public class UserAction implements UserItf { 
@In @Out private User user; 
@Out private List userList; 

@PersistenceContext private EntityManager em; 

 public String addAndDisplay() { 
  em.persist (user); 
  user = new User (); 
  userList = em.createQuery("From User u order by u.name").getResultList(); 
  return null; 
 }

The useraction component in Seam is the UserAction session bean, as specified by the @Name annotation on the class. The UserAction class has user and userList fields annotated with the @In and @Out annotations.

The @In and @Out annotations are at the heart of the Seam programming model. So, let’s look at exactly what they do here.

The @In annotation tells Seam to assign the user component, which is composed from the JSF form data, to the user field (dependency injection) before executing any method in the session bean. You can specify an arbitrary name for the injected component in @In. But if there is no named specified, as it is here, Seam will just inject the component with the same type and same name as the receiving field variable.

The @Out annotations tell Seam to assign values of the userList and user fields to the managed components of the same names after any method execution. We call this action “dependency outjection” in Seam. This way, in the addAndDisplay method, we simply need to update the user and userList field values and they will be automatically available on the web page.

So the addAndDisplay() method simply saves the fields to the database via the JPA EntityManager,then it refreshes the user and userList objects, which are outjected after the method exits. The addAndDisplay() returns null to indicate that the current JSF page will be re-displayed with the most up-to-date model data after the call.

jboss seam tutorialIn short, bijection lets you alias a context variable to a component instance variable, by specifying that the value of the instance variable is injected, outjected, or both.

This is the hello.xhtml view

<f:view>
<h:form>Please enter your info:<br/>

Username: <h:inputText value=”#{user.username}” required=”true”/>
Real Name: <h:inputText value=”#{user.name}” required=”true”/>
Password: <h:inputSecret value=”#{user.password}” required=”true”/>
<h:commandButton type=”submit” value=”Add User” action=”#{useraction.addAndDisplay}“/>
</h:form>

<h:dataTable value=”#{userList}” var=”u”>
<h:column>
<h:outputText value=”#{u.username}“/>&nbsp;
<h:outputText value=”#{u.name}“/>&nbsp;
</h:column>
</h:dataTable>
</f:view>

As you can see, the datatable references the userList, which is populated in the addAndDisplayMethod by the following query

userList = em.createQuery(“From User u order by u.name”).getResultList();

Picture 1: Seam bijection depicted
jboss seam tutorial

Getter / Setter Based Bijection

In the above example, we demonstrated Seam bijection against field variables. You can also biject components against getter and setter methods. For instance, take a look at the following code:

  1. private User user;
  2. private List userList;
  3. @In public void setUser (User user) {
  4. this.user = user;
  5. }
  6. @Out public User getUser () {
  7. return user;
  8. }
  9. @Out public List getUserList () {
  10. return userList;
  11. }
private User user; 
private List userList; 

 @In public void setUser (User user) {
   this.user = user; 
 } 
 @Out public User getUser () { 
  return user; 
 } 
 @Out public List getUserList () { 
  return userList; 
 }

You may wonder why not complicating so much the lift with getter/setter bijection ?
the real value of this change is that you can add custom logic to manipulate the bijection process.
For instance, you can validate the injected object or retrieve the outjected object on the fly from the database.

Posted in JBoss Seam Framework | Tagged: | Leave a Comment »

JavaScript interview questions

Posted by Admin on June 2, 2009

JavaScript interview questions and answers

By admin | May 28, 2006

  1. What’s relationship between JavaScript and ECMAScript? – ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3.
  2. What are JavaScript types? – Number, String, Boolean, Function, Object, Null, Undefined.
  3. How do you convert numbers between different bases in JavaScript? – Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt (“3F”, 16);
  4. What does isNaN function do? – Return true if the argument is not a number.
  5. What is negative infinity? – It’s a number in JavaScript, derived by dividing negative number by zero.
  6. What boolean operators does JavaScript support? – &&, || and !
  7. What does “1”+2+4 evaluate to? – Since 1 is a string, everything is a string, so the result is 124.
  8. How about 2+5+”8″? – Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.
  9. What looping structures are there in JavaScript? – for, while, do-while loops, but no foreach.
  10. How do you create a new object in JavaScript? – var obj = new Object(); or var obj = {};
  11. How do you assign object properties? – obj[“age”] = 17 or obj.age = 17.
  12. What’s a way to append a value to an array? – arr[arr.length] = value;
  13. What is this keyword? – It refers to the current object.

Posted in Javascript, CSS, HTML/XHTML | Tagged: | Leave a Comment »

CSS Best Practices

Posted by Admin on June 2, 2009

General CSS Rules

  • Build and test your CSS in Firefox (or Safari if you are working on a Mac).
  • Specify units for non-zero values, but not for zero values.
  • Don’t use quotation marks around paths/URLs when setting a background image or loading in an imported file
  • Try to avoid applying padding/borders and a fixed width to an element. Rather, apply padding to the parent element.
  • Minimize number of ID’s used
  • Minimize number of classes used
  • Don’t use anchors, instead use ID’s.
  • Sandbox your style declarations
  • Combine selectors.
  • Use good naming conventions
  • Control the browsers CSS: Start with a clean slate.
  • Declare relative font sizes instead of absolute.
  • Create classes for error handling named based on the error
  • Avoid !important.
  • Avoid in-line CSS
  • Code link pseudo-classes in this order: Link, Visited, Hover, Active.

Stylesheet Maintenance

  • Minimize and clean up your css
  • Organize your CSS file
  • There are pros and cons to using Multiple stylesheets

HTML Development

  • Separate Structure and Presentation
  • Use HTML structure
  • Encompass everything in an element.
  • Use HTML elements for their intented purpose:
  • Avoid excess code
  • Avoid meaningless markup
  • Case sensitivity

General CSS Rules

Build and test your CSS in Firefox or Safari if you are working on a Mac.

  • Do not look at it or test your code in other browsers, especially IE, until the code is complete, approved and validated. This way you will start with clean, standards-compliant code that you can alter for non-standards compliant browsers, rather hacking from buggy code to support good browsers
  • If developing in Safari, develop with embedded styles in the header, but launch with imported styles to eliminate potential caching issues.
  • @import or <link> the css. It is better to <link rel="stylesheet" type="text/css" ... > because using @import can delay the rendering of your page.
  • Use as few browser hacks as possible, and document them with comments. Try to use valid CSS filters instead of non-validating hacks

Specify units for non-zero values.

  • Zero is zero, so do don’t include a unit type. For all other cases, CSS requires you to specify units on all quantities such as fonts, margins and sizes. Example: margin: 0 4px 0 2em;

Don’t use quotation marks around paths/URLs when setting a background image or loading in an imported file

  • They are not required or necessary and they will freeze IE5 on the Mac.

Try to avoid applying padding/borders and a fixed width to an element. Rather, apply padding to the parent element.

  • Because of IE 6 (and lower) box-model issues, if you apply padding to the parent element instead of the child element, IE will render the same as standards compliant browsers.

Minimize use of ID’s:

  • By encompassing sections in a named outer div, you can generally stylize all the contained components without the use of classes.
  • Use IDs sparingly: IDs have to be unique on a page, so using them for structural elements means that you can only ever have one content block on a page. #mainnavigation li li a should suffice for a drop down menu link and can be overwritten with #mainnavigation li li li a if there are submenus.
  • With minimal use of ID’s one can still target almost any element on the page, while allowing ASP.net autogenerated code (which is “ID happy”) to have the freedom to put ID’s all over the page.
  • Combine your selectors and sandbox your declarations (see below)

Minimize use of classes

  • Only use classes on elements that have any chance of being repeated on a page and in different locations, if the element is going to exist in a predictable location cascade based on the parent div ID,

Don’t use anchors, instead use ID’s.

  • Less code with multi-purpose code. Instead of using <a name=”anchor”> give an id to the parent of where that anchor would fall. All ID’s need to be unique, but so do the named anchors, so you are actually saving code and avoiding the pitfall of the effects of a a:hover defined for actual links

Sandbox your style declarations

  • Limit the “reach” of style declarations by pre-pending the class name, such as #maincontent p{}.

Combine selectors.

  • Keeping your CSS light is important to minimize download times; as much as possible, group selectors and rely on inheritance.

Naming conventions:

  • Never use layout descriptives in class names. Rather, use functional names for your classes, avoid words that describe how they look or where they are located on the page. “mainnavigation” is better than “leftnavigation”. Use “.copyright” and “.pullquote” instead of “smallgrey” or “indentitalic”. Name classes/IDs based on function, not appearance. If you create a .smallblue class, and later get a request to change the text to large and red, the class stops making any form of sense. Instead use descriptive classes like
  • Always use intention revealing classnames: Its tempting to use short cryptic class names (.s, .lbl) but unless you keep a glossary up to date of your class names, you will forget what they do. You may also run into problems with older browsers that can occasionally confuse classnames that start the same (i.e. .err and .errors are sometimes confused)
  • Avoid using the same classname for different purposes. The cascade can be very powerful but sometimes there is a temptation to use the same generic classname in many places. If you don’t sandbox your Css well, you can run into troubles.
  • Always use the same classname for similar purposes: Becuase the cascade is so powerful, you should reuse a classname in different places when they represent the same concept.
  • Put your classname on the outer-most element. The child elements can be targeted with the parent elements classname or ID. Often you see things like:<div>...</div>
    <div>...</div>
    <div>...</div>
    It’s far better to write:

    <div id="header">
    <h3>...</h3>
    <p>...</p>
    <ul><li>...</li><ul>
    </div>

  • Although class and div names can include lowercase, uppercase, numbers and additional characters in class and div names, it is best to use all lower case letters and to for multiple word classes, separate the words with an underscore or use camel case. HTML attributes “id” and “class” are case sensitive!
  • Never use javascript method or property names as ID values.  JavaScript DOM bindings specifies that javascript can index by id. For example, using “length” as an ID value on an element will cause headaches when using myObjects.length.

Start with a clean slate.

  • Create default page with no rendering; include this code but change color and font-family if necessarybody, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, fieldset, input, p, blockquote, th, td { font-family: Arial, Helvetica, sans-serif; color:#000000; font-size: x-small;}
    table{border-collapse: collapse; border-spacing:0;}
    fieldset, img{border:0;}
    address, caption, cite, code, dfn, em, strong, th, var{font-style: normal; font-weight:normal;}
    h1, h2, h3, h4, h5, h6 {font-size:100%;}
    q:before, q:after{content:'';}
  • If you select other fonts for display, you don’t need to declare default classes since the first declaration declares default classes for all necessary elements.

Declare relative font sizes instead of absolute.

  • Always declare font-sizes in percentages or ems for maximum usability, consistency, and accessibility. This will enable pages to grow organically when user chooses to make text larger or smaller. Ems are easier to control than pixels.

Create classes for error handling named based on the error:

  • Form error handling is a good place to use multiple classnames. As an example, if you have a form, fields are typically either required or optional and have an error or not. Use “error required”, “error optional, “error feedback” (for a total of 4 classes, instead of 6), etc. Don’t call the classes “rederror”, redbigerror, etc, because when coding new error messages it won’t be obvious to the programmers which class to use.

Avoid !important.

Avoid in-line CSS

  • Inline styles negates the power of CSS and should only be used for testing purposes, such as including style=”border: 1px solid #ff0000;” to identify box model quirks

Code link pseudo-classes in this order: Link, Visited, Hover, Active.

  • In your CSS, code the links in order of a:link, a:visited, a:hover and a:active. Some people remember this best by the mneumonic “LoVe HAte”. In the hover definition, include visited:hover to ensure your hover effect works on visited links.

Stylesheet Maintenance

Minimize and clean up your css

  • Use as little CSS as possible, remove styles and parts of styles not being used or that were experimented with in the design process.

Organize your CSS file

  • Introduce your stylesheets with comments and explanation of how the particular sheet fits in with other sheets and with the site.
  • Use a predictable format. Organize similar rules together and use comments before each section to help you keep track of things for future redesigns/updates.
  • Group your styles with short and precise labels via comments
  • Make sure to comment blocks of CSS appropriately, group like-selectors, and establish a consistent naming convention, white space formatting. Incase different developers are using different platforms to edit the CSS, it is best to use spaces instead of tabs for white spce. Also, it is helpful to have consistent property order, though this is one I don’t do.
  • Start with clearing all default values, as mentioned above: this will reduce redundancy. Follow this by global styles. Lastly include section specific styles. For example, declare default element values. Next create sections of code for each section of your document. Next come the content sections which I generally divide into #header, #navigation, #maincontent and #footer. Include all the layout for the various elements for each of these id’s that are site global within each section
  • After site-wide declarations grouped by section/ID, if there are different “page colors” or layout looks, include a section for each of the different looks. If a declaration is valid for all “looks”, include it in the declarations above. If a declaration is valid for a subset of looks only, first declare a section for the multiple subset looks. This should be followed by unique page sections.
  • Finally, declare “weird” effects that only effect a paragraph type, a link based on value, etc.

Multiple stylesheets

  • Multiple stylesheets are appropriate for large and complexly styled sites, however extra http calls should be minimized.
  • Make sure multiple style sheets are really worth while – a single long CSS file can at least be searched easily (”find all instances of h2″)
  • The base styles file contains CSS rules that can be applied on every page, more specific sheets based on section or page color schema.

HTML Development

Separate Structure and Presentation

  • The goal should be to only have one line of CSS on the entire page: the call to an external style sheet.
    The eventual goal should also be to have one line of JavaScript – the call to the external file, with no inline event handlers, but we haven’t covered that yet.
  • Use semantic HTML structure that have semantic meaning such as <strong> and <em>
    instead of <b> and <large>. To give emphasis to a title, or stylizing a p tag, use semantic mark up such as <h1> thru <h6>

Encompass everything in an element.

  • <div> and <span> have no intrinsic meaning. Encompass all text in appropriate elements: <h1><h6>, <p>, <cite>, etc.

Use HTML elements for their intented purpose:

  • Use <blockquote> for blockquotes. <li> for list items, <cite> for citations.
  • Use list items for lists of links. Remember, navigations are generally a list of links and it is appropriate to use lists.

Avoid excess code,

  • Instead of repeated <br /> and   use margin and padding

Avoid meaningless markup

  • Instead of <b> and <i>, use <strong> and <em>

Case sensitivity

  • All HTML markup, JavaScript, and CSS should be lowercase. Event handlers should be written in all lower case: use onlick not onClick. Use <p>, not <P>. Attribute values should all be lower case as well, unless referring to a file name that includes other characters. File names and file extensions should also be lowercase (no rule on this, just easier to remember class names, file names, image names, etc. if you don’t have to worry about case.
  • If a header should be all-caps, code it in regular case as you would want to see it printed, and then transform the text to all uppercase with CSS text transformation.

Posted in Javascript, CSS, HTML/XHTML | Tagged: | Leave a Comment »

XHTML, CSS & JavaScript Web Developer Applicant Questions

Posted by Admin on June 2, 2009

XHTML Web Standards Interview Question

Question:

What is a DTD? What DTD do you generally use? Why? Pros and cons.

Answer

See the bottom half of DTD: the Document Type Declaration

Answer Rating:

  1. Completely wrong answer though pretends to know it
  2. I don’t know (I give points for honesty), trying unsuccessfully but honestly to give the right answer
  3. Knowledge of the definition, but doesn’t know why they are used.
  4. Knowledge of which one to use and why
  5. Explanation of Quirks mode versus Regular mode and analysis of which one is best for different media

Accessibility Interview Question

Question

Tell me some considerations in selecting font size?

Answer

Font sizes should be declared using relative measurement values, such as ems, via a style sheet, without the use of the term !important. There are issues with browser font size enlarging which can be rectified via CSS.

Answer Rating

  1. uses <font> tag
  2. Gives an answer using pixels using CSS
  3. Explains that font size should be declared using relative font sizes
  4. Explains that font size should be declared using ems or percentages
  5. Gives the answer above

CSS Interview Question

Question

a) What are the possible values for the display attribute that are supported by all browsers?
b) What is the default value for the display attribute for the image element? (what is the difference between inline and block level elements)
c)What does display: run-in do?
d) Difference between “visibility:hidden” and “display:none”? What are the pros and cons of using display:none?

Answer

main values: none, block, inline, list-item, run-in
all values: inline | block | list-item | run-in | compact | marker | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | none | inherit
default value: inline, block or list-item, depending on the element. The <img> is an inline element.
Run-in should make the run-in element be the first line of the next sibling block level element, if it is before a block level element that is not floated or absolutely positioned. If the next sibling is positioned or floated, then the run-in element will be a block level element instead of appearing in-line.
PPK’s Quirksmode explains it well. The w3schools lists table display values.
When visibility is set to hidden, the element being hidden still occupies its same place in the layout of the page. If the display is set to none, the element does not occupy any space on the page — as if it didn’t exist..

Answer Rating

  1. Doesn’t know
  2. Knows the answer to A
  3. Knows the answer to A and D
  4. Knows the answer to A, B and D
  5. Knows the answer to C too!

CSS Interview Question

Question

a) What are the five possible values for “position”?
b) What is the default/initial value for “position”?
c) How does the browser determine where to place positioned elements
d) What are the pros and cons of using absolute positioning?
e) if they are really advanced, ask about IE z-index issues with positioned elements.

Answer

a) Values for position: static, relative, absolute, fixed, inherit
b) Static
c) They are placed relative to the next parent element that has absolute or relative value declared
d) Absolutely positioned elements are removed from the document flow. The positioned element does not flow around the content of other elements, nor does their content flow around the positioned element. An absolutely positioned element may overlap other elements, or be overlapped by them.
e) IE treats a position like a z-index reset, so you have to declare position of static on the parent element containing the z-indexed elements to have them responsd to z-index correctly.

Answer Rating

  1. Doesn’t know
  2. Knows 4 out of 5 answers in part A
  3. Knows A & B
  4. Knows A, B & C
  5. Knows A-D
  6. Knows E too

CSS Interview Question

Question:

Write a snippet of CSS that will display a paragraph in blue in older browsers, red in newer browsers, green in IE6 and black in IE7

Possible Answer:

#content p{color:blue}
html>body #content p {color:red}
* html #content p{color:green}
html>body #content p {*color:black;}

Answer Rating

  1. Doesn’t know
  2. Knows how to declare one color, but no hacks
  3. knows the html>body hack and * html hack
  4. Knows all the hacks, but doesn’t validate or uses conditional comments in the HTML
  5. Gives you the right answer and explains why the CSS won’t validate, or, uses a valid hack, other than conditional IE comments, instead of the above answer.

Basic Javascript Interview Question

Question:

What is the correct way to include JavaScript into your HTML?

Answer:

See Including Javascript in XHTML for answers.

Answer Rating:

  1. <a href=”javscript:function()”> – and other incorrect answers
  2. verbally explains the theory but doesn’t know how to do it
  3. correct explanation using inline event handlers or inline code
  4. discusses and knows how to implement javascript event listeners
  5. Explainst how you include JS within an XHTML document and ensure it validates using CDATA, explains

Basic Javascript Array / XHTML Form Interview Question

Question

Are the following all equal, and, if so, what would your code look like to make the following all equal the same thing:

  alert(document.forms["myform"].elements["field"].value);
  alert(document.forms[1].elements[1].value);
  alert(document.myform.field.value);

answer:

<form name="myform" method="post" action="something">
<input name="anything" value="anything" type="something" />
<input name="field" value="something" type="something" />
</form>

Answer includes knowing that the form is the second form on the page, and that the field input element is the second element within that form.

Answer Rating

  1. Doesn’t know how to code forms and doesn’t know that the first index of an array is 0.
  2. Knows either how to code forms with valid XHTML or that array starts at 0, but not both.
  3. Knows how to code forms but not correctly, but omits something like doesn’t know that the form needs to be the second one on the page, and the element is the second one in the form. Would know how to do it if they actually put thought into it.
  4. Codes the form correctly, but uses ID instead of name
  5. Codes everything correctly

JavaScript Interview Question

Question:

How do you dynamically add a paragraph with stylized content to a page?

Possible Answer:

newParagraph = document.createElement('p');
newParagraph.setAttribute('class', 'myClass');
newText = document.createTextNode('this is a new paragraph');
newParagraph.appendChild(newText);
myLocation = document.getElementById('parent_of_new_paragraph);
myLocation.appendChild(newParagraph);

Answer Rating:

  1. Wrong Answer (i.e. “you can’t”), I don’t know.
  2. Use JavaScript, with no knowledge or incomplete knowledge of how that is done. Suggesting innerHTML, but not really knowing. Or explanation of accessibilty issues surrounding this.
  3. Able to explain how you create a node, add content to the node, add a class attributes to that element, and then add that node as a child of the parent element (the above example)
  4. Explanation of how to do it (worth 3 points) and explanation as to issues that arise when doing it, such as screen readers not knowing that text has changed, IE6 and IE7 not applying styles included with added content, not duplicating IDs, etc.
  5. Has no clue how to do it to start, but can figure it out with guidance: extra points for the quick learner!

Other questions ideas:

Q: How do you organize your CSS? How do you come up with id and class names (what naming conventions do you use)?
A: While there are no right answers, there are best practices. Issues to look for are not having div mania, no inline CSS, no presentational markup, minimal use of classes, understanding the CSS cascade.

Q: What do you think of hacks? When should you use them? If you use them, how do you maintain them? What can be done to avoid needing to use box-model hacks? (if they aren’t pros, you can ask them what is the issue with x-browsers and the box model)

Q: What are the pros and cons of using tables for layout? Do you use tables? What are the pros and cons of tableless design? How do you generally layout your pages?
A: check for them NOT using tables

Q: Check to ensure that they separate structure and semantics first from presentation later? Do not ask about this during HTML, but do in webstandards.

Q: What are some deprecated elements and attributes that you use, and in what instances do you use them?
A: List of deprecated elements and attributes.

Q: What is involved in making a website accessible? What are arguments you use to convince others to invest in making their web site accessible.
A: See Making the web Accessible. Making sites accessible also makes them more search engine friendly (saves money), makes your pages accessible to the 20% of the population that has some type of disability (so you can make more money) and it’s the law in many places.

Q: Define what web standards mean to you? How do you implement web standards?

Q: In CSS, how can you make a form elments background-color change when the user is entering text? will this work in all browsers?

Q: How can you target an element in your HTML using the DOM?

Posted in Javascript, CSS, HTML/XHTML | Tagged: , , | Leave a Comment »

Hibernate Interview Questions

Posted by Admin on May 30, 2009

1.What is ORM ?

ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.

2.What does ORM consists of ?

An ORM solution consists of the followig four pieces:

  • API for performing basic CRUD operations

  • API to express ries refering to classes

  • Facilities to specify metadata

  • Optimization facilities : dirty checking,lazy associations fetching

3.What are the ORM levels ?

The ORM levels are:

  • Pure relational (stored procedure.)

  • Light objects mapping (JDBC)

  • Medium object mapping

  • Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

4.What is Hibernate?

Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.

5.Why do you need ORM tools like hibernate?

The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:

  • Improved productivity

    • High-level object-oriented API

    • Less Java code to write

    • No SQL to write

  • Improved performance

    • Sophisticated caching

    • Lazy loading

    • Eager loading

  • Improved maintainability

    • A lot less code to write

  • Improved portability

    • ORM framework generates database-specific SQL for you

6.What Does Hibernate Simplify?

Hibernate simplifies:

  • Saving and retrieving your domain objects

  • Making database column and table name changes

  • Centralizing pre save and post retrieve logic

  • Complex joins for retrieving related items

  • Schema creation from object model

7.What is the need for Hibernate xml mapping file?

Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:

Hibernate Mapping file

8.What are the most common methods of Hibernate configuration?

The most common methods of Hibernate configuration are:

  • Programmatic configuration

  • XML configuration (hibernate.cfg.xml)

9.What are the important tags of hibernate.cfg.xml?

An Action Class is an adapter between the contents of an incoming HTTP rest and the corresponding business logic that should be executed to process this rest.

hibernate.cfg.xml

10.What are the Core interfaces are of Hibernate framework?

The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.

  • Session interface

  • SessionFactory interface

  • Configuration interface

  • Transaction interface

  • Query and Criteria interfaces

11.What role does the Session interface play in Hibernate?

The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession();

Session interface role:

  • Wraps a JDBC connection

  • Factory for Transaction

  • Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

12.What role does the SessionFactory interface play in Hibernate?

The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work

SessionFactory sessionFactory = configuration.buildSessionFactory();

13.What is the general flow of Hibernate communication with RDBMS?

The general flow of Hibernate communication with RDBMS is :

  • Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files

  • Create session factory from configuration object

  • Get one session from this session factory

  • Create HQL Query

  • Execute query to get list containing Java objects

14.What is Hibernate Query Language (HQL)?

Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.

15.How do you map Java Objects with Database tables?

  • First we need to write Java domain objects (beans with setter and getter). The variables should be same as database columns.

  • Write hbm.xml, where we map java class to table and database columns to Java class variables.

Example :

<hibernate-mapping>
  <class name="com.test.User"  table="user">
   <property  column="USER_NAME" length="255"
      name="userName" not-null="true"  type="java.lang.String"/>
   <property  column="USER_PASSWORD" length="255"
     name="userPassword" not-null="true"  type="java.lang.String"/>
 </class>
</hibernate-mapping>

 16.What’s the difference between load() and get()? 
load() vs. get() :-
load() get()
Only use the load() method if you are sure that the object exists. If you are not sure that the object exists, then use one of the get() methods.
load() method will throw an exception if the unique id is not found in the database. get() method will return null if the unique id is not found in the database.
load() just returns a proxy by default and database won’t be hit until the proxy is first invoked. get() will hit the database immediately.
 17.What is the difference between and merge and update ?
Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

  18.How do you define sequence generated primary key in hibernate?
Using <generator> tag.
 Example:-
<id column="USER_ID" name="id" type="java.lang.Long"> 
    <generator class="sequence"> 
     <param name="table">SEQUENCE_NAME</param>
   <generator>
</id>

19.Define cascade and inverse option in one-many mapping?

cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.

inverse="true|false"

Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?
20.What do you mean by Named – SQL query?
Named SQL queries are defined in the mapping xml document and called wherever required.
Example:
<sql-query name = "empdetails">
   <return alias="emp" class="com.test.Employee"/>
      SELECT emp.EMP_ID AS {emp.empid},
                 emp.EMP_ADDRESS AS {emp.address},
                 emp.EMP_NAME AS {emp.name}
      FROM Employee EMP WHERE emp.NAME LIKE :name
</sql-query>

Invoke Named Query :

List people = session.getNamedQuery("empdetails")
                     .setString("TomBrady", name)
                     .setMaxResults(50)
                     .list();

21.How do you invoke Stored Procedures?
<sql-query name="selectAllEmployees_SP" callable="true">
 <return alias="emp" class="employee">
   <return-property name="empid" column="EMP_ID"/>       
   <return-property name="name" column="EMP_NAME"/>       
   <return-property name="address" column="EMP_ADDRESS"/>
    { ? = call selectAllEmployees() }
 </return>
</sql-query>

22.Explain Criteria API
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
Example :
List employees = session.createCriteria(Employee.class)
                         .add(Restrictions.like("name", "a%") )
                         .add(Restrictions.like("address", "Boston"))
                         .addOrder(Order.asc("name") )
                         .list();

23.Define HibernateTemplate?
org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.
24.What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :
  • HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
  • Common functions are simplified to single method calls.
  • Sessions are automatically closed.
  • Exceptions are automatically caught and converted to runtime exceptions.
25.How do you switch between relational databases without code changes?
Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.
26.If you want to see the Hibernate generated SQL  statements on console, what should we do?
In Hibernate configuration file set as follows:
<property name="show_sql">true</property>

27.What are derived properties?
The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.
28.What is component mapping in Hibernate?
  • A component is an object saved as a value, not as a reference
  • A component can be saved directly without needing to declare interfaces or identifier properties
  • Required to define an empty constructor
  • Shared references not supported
Example:

Component Mapping

29.What is the difference between sorted and ordered collection in hibernate?
sorted collection vs. order collection :-
sorted collection order collection
A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator. Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is not large, it will be more efficient way to sort it. If your collection is very large, it will be more efficient way to sort it .
31.What is the advantage of Hibernate over jdbc? 
Hibernate Vs. JDBC :-
JDBC Hibernate
With JDBC, developer has to write code to map an object model’s data representation to a relational data model and its corresponding database schema. Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.
With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.
With JDBC, caching is maintained by hand-coding. Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.
In JDBC there is no check that always every user has updated data. This check has to be added by the developer. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.
32.What are the Collection types in Hibernate ?
  • Bag
  • Set
  • List
  • Array
  • Map
33.What are the ways to express joins in HQL?
HQL provides four ways of expressing (inner and outer) joins:-
  • An implicit association join
  • An ordinary join in the FROM clause
  • A fetch join in the FROM clause.
  • A theta-style join in the WHERE clause.
34.Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.

inverse="true|false"

Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

35.What is Hibernate proxy? 
The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.
36.How can Hibernate be configured to access an instance variable directly and not through a setter method ?
By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

37.How can a whole class be mapped as immutable?
Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.

38.What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
  • dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed
  • dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.
39.What do you mean by fetching strategy ?
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.

40.What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.

41.What is transactional write-behind?
Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.

42.What are Callback interfaces?
Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.

43.What are the types of Hibernate instance states ?
Three types of instance states:
  • Transient -The instance is not associated with any persistence context
  • Persistent -The instance is associated with a persistence context
  • Detached -The instance was associated with a persistence context which has been closed – currently not associated
44.What are the differences between EJB 3.0 & Hibernate

Hibernate Vs EJB 3.0 :-
Hibernate EJB 3.0
Session–Cache or collection of loaded objects relating to a single unit of work Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit
XDoclet Annotations used to support Attribute Oriented Programming Java 5.0 Annotations used to support Attribute Oriented Programming
Defines HQL for expressing queries to the database Defines EJB QL for expressing queries
Supports Entity Relationships through mapping files and annotations in JavaDoc Support Entity Relationships through Java 5.0 annotations
Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API Provides and Entity Manager Interface for managing CRUD operations for an Entity
Provides callback support through lifecycle, interceptor, and validatable interfaces Provides callback support through Entity Listener and Callback methods
Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships Entity Relationships are bidirectional or unidirectional
45.What are the types of inheritance models in Hibernate?
There are three types of inheritance models in Hibernate:
  • Table per class hierarchy
  • Table per subclass
  • Table per concrete class

Posted in Hibernate Framework | Tagged: | 1 Comment »

JSF Interview Questions

Posted by Admin on May 29, 2009

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 a 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 file 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 all of the 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:

      <managed-bean>
    	 <managed-bean-name>login</managed-bean-name>
    	 <managed-bean-class>com.developersBookJsf.loginBean</managed-bean-class>
    	 <managed-bean-scope>request</managed-bean-scope>
      </managed-bean>

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:

        <application>
    	<resource-bundle>
    	<base-name>com.developersBookJsf.messages</base-name>
    	<var>message</var>
    	</resource-bundle>
        </application>

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

       <f:loadBundle baseName = “com.developersBookJsf.messages” var=”message”/>

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:

      <naviagation-rule>
        <from-view-id>/index.jsp</from-view-id>
        <navigation-case>
    	 <from-outcome>login</from-outcome>
    	 <to-view-id>/welcome.jsp</to-view-id>
        </navigation-case>
      </naviagation-rule>

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

    	<context-param>
    		<param-name>javax.faces.CONFIG_FILES</param-name>
    		<param-value>
    			/WEB-INF/faces-config1.xml,
    			/WEB-INF/faces-config2.xml,
    			/WEB-INF/faces-config3.xml
    		</param-value>
    	</context-param>

Posted in JSF | Tagged: | 1 Comment »