The basic portlet life cycle of a JSR 168 portlet is: The portlet container manages the portlet life cycle and calls the corresponding methods on the portlet interface. Every portlet must implement the portlet interface, or extend a class that implements the portlet interface. The portlet interface consists of the following methods: A portlet mode indicates the function a portlet performs. Usually, portlets execute different tasks and create different content depending on the functions they currently perform. A portlet mode advises the portlet what task it should perform and what content it should generate. When invoking a portlet, the portlet container provides the current portlet mode to the portlet. Portlets can programmatically change their mode when processing an action request. JSR 168 splits portlet modes into three categories: A window state indicates the amount of portal page space that will be assigned to the content generated by a portlet. When invoking a portlet, the portlet container provides the current window state to the portlet. The portlet may use the window state to decide how much information it should render. Portlets can programmatically change their window state when processing an action request. JSR 168 defines the following window states:Portlet life cycle
Portlet interface
init(PortletConfig config):
to initialize the portlet. This method is called only once after instantiating the portlet. This method can be used to create expensive objects/resources used by the portlet. processAction(ActionRequest request, ActionResponse response):
to notify the portlet that the user has triggered an action on this portlet. Only one action per client request is triggered. In an action, a portlet can issue a redirect, change its portlet mode or window state, modify its persistent state, or set render parameters. render(RenderRequest request, RenderResponse response):
to generate the markup. For each portlet on the current page, the render method is called, and the portlet can produce markup that may depend on the portlet mode or window state, render parameters, request attributes, persistent state, session data, or backend data. destroy():
to indicate to the portlet the life cycle's end. This method allows the portlet to free up resources and update any persistent data that belongs to this portlet.Portlet modes
Window states
Monday, June 18, 2007
JSR 168 Portlet life cycle
Posted by iCehaNgeR's hAcK NoteS at 4:29 PM 9 comments
Friday, June 8, 2007
Spring Hibernate FAQ
Q. Explain DI or IOC pattern. A: Dependency injection (DI) is a programming design pattern and architectural model, sometimes also referred to as inversion of control or IOC, although technically speaking, dependency injection specifically refers to an implementation of a particular form of IOC. Dependancy Injection describes the situation where one object uses a second object to provide a particular capacity. For example, being passed a database connection as an argument to the constructor instead of creating one internally. The term "Dependency injection" is a misnomer, since it is not a dependency that is injected, rather it is a provider of some capability or resource that is injected. There are three common forms of dependency injection: setter-, constructor- and interface-based injection. Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way in which an object obtains references to its dependencies. This is often done by a lookup method. The advantage of inversion of control is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing. Q. What are the different IOC containers available? A. Spring is an IOC container. Other IOC containers are HiveMind, Avalon, PicoContainer. Q. What are the different types of dependency injection. Explain with examples. A: There are two types of dependency injection: setter injection and constructor injection. Setter Injection: Normally in all the java beans, we will use setter and getter method to set and get the value of property as follows: public class namebean {
String name;
public void setName(String a) {
name = a; }
public String getName() {
return name; }
}
We will create an instance of the bean 'namebean' (say bean1) and set property as bean1.setName("tom"); Here in setter injection, we will set the property 'name' in spring configuration file as showm below:
Constructor injection: For constructor injection, we use constructor with parameters as shown below, public class namebean {
String name;
public namebean(String a) {
name = a;
}
}
We will set the property 'name' while creating an instance of the bean 'namebean' as namebean bean1 = new namebean("tom");
Here we use the Q. What is spring? What are the various parts of spring framework? What are the different persistence frameworks which could be used with spring? A. Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development. The Spring modules are built on top of the core container, which defines how beans are created, configured, and managed, as shown in the following figure. Each of the modules (or components) that comprise the Spring framework can stand on its own or be implemented jointly with one or more of the others. The functionality of each component is as follows: The core container: The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application’s configuration and dependency specification from the actual application code. Spring context: The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality. Spring AOP: The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components. Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO’s JDBC-oriented exceptions comply to its generic DAO exception hierarchy. Spring ORM: The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring’s generic transaction and DAO exception hierarchies. Spring Web module: The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects. Spring MVC framework: The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI. Q. What is AOP? How does it relate with IOC? What are different tools to utilize AOP? A: Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. AOP and IOC are complementary technologies in that both apply a modular approach to complex problems in enterprise application development. In a typical object-oriented development approach you might implement logging functionality by putting logger statements in all your methods and Java classes. In an AOP approach you would instead modularize the logging services and apply them declaratively to the components that required logging. The advantage, of course, is that the Java class doesn't need to know about the existence of the logging service or concern itself with any related code. As a result, application code written using Spring AOP is loosely coupled. The best tool to utilize AOP to its capability is AspectJ. However AspectJ works at he byte code level and you need to use AspectJ compiler to get the aop features built into your compiled code. Nevertheless AOP functionality is fully integrated into the Spring context for transaction management, logging, and various other features. In general any AOP framework control aspects in three possible ways: Joinpoints: Points in a program's execution. For example, joinpoints could define calls to specific methods in a class
Pointcuts: Program constructs to designate joinpoints and collect specific context at those points
Advices: Code that runs upon meeting certain conditions. For example, an advice could log a message before executing a joinpoint
Q. What are the advantages of spring framework? A.
Q. Can you name a tool which could provide the initial ant files and directory structure for a new spring project. A: Appfuse or equinox. Q. Explain BeanFactory in spring. A: Bean factory is an implementation of the factory design pattern and its function is to create and dispense beans. As the bean factory knows about many objects within an application, it is able to create association between collaborating objects as they are instantiated. This removes the burden of configuration from the bean and the client. There are several implementation of BeanFactory. The most useful one is "org.springframework.beans.factory.xml.XmlBeanFactory" It loads its beans based on the definition contained in an XML file. To create an XmlBeanFactory, pass a InputStream to the constructor. The resource will provide the XML to the factory. BeanFactory factory = new XmlBeanFactory(new FileInputStream("myBean.xml")); This line tells the bean factory to read the bean definition from the XML file. The bean definition includes the description of beans and their properties. But the bean factory doesn't instantiate the bean yet. To retrieve a bean from a 'BeanFactory', the getBean() method is called. When getBean() method is called, factory will instantiate the bean and begin setting the bean's properties using dependency injection. myBean bean1 = (myBean)factory.getBean("myBean"); Q. Explain the role of ApplicationContext in spring. A. While Bean Factory is used for simple applications, the Application Context is spring's more advanced container. Like 'BeanFactory' it can be used to load bean definitions, wire beans together and dispense beans upon request. It also provide 1) a means for resolving text messages, including support for internationalization.
2) a generic way to load file resources.
3) events to beans that are registered as listeners.
Because of additional functionality, 'Application Context' is preferred over a BeanFactory. Only when the resource is scarce like mobile devices, 'BeanFactory' is used. The three commonly used implementation of 'Application Context' are 1. ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
2. FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code
ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
3. XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.
Q. How does Spring supports DAO in hibernate? A. Spring’s HibernateDaoSupport class is a convenient super class for Hibernate DAOs. It has handy methods you can call to get a Hibernate Session, or a SessionFactory. The most convenient method is getHibernateTemplate(), which returns a HibernateTemplate. This template wraps Hibernate checked exceptions with runtime exceptions, allowing your DAO interfaces to be Hibernate exception-free. Example: public class UserDAOHibernate extends HibernateDaoSupport {
public User getUser(Long id) {
return (User) getHibernateTemplate().get(User.class, id);
}
public void saveUser(User user) {
getHibernateTemplate().saveOrUpdate(user);
if (log.isDebugEnabled()) {
log.debug(“userId set to: “ + user.getID());
}
}
public void removeUser(Long id) {
Object user = getHibernateTemplate().load(User.class, id);
getHibernateTemplate().delete(user);
}
}
Q. What are the id generator classes in hibernate?
A: increment: It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment.
identity: It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.
sequence: The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int
hilo: The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection.
seqhilo: The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.
uuid: The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.
guid: It uses a database-generated GUID string on MS SQL Server and MySQL.
native: It picks identity, sequence or hilo depending upon the capabilities of the underlying database.
assigned: lets the application to assign an identifier to the object before save() is called. This is the default strategy if no 1. An interface that defines the functions.
2. An Implementation that contains properties, its setter and getter methods, functions etc.,
3. A XML file called Spring configuration file.
4. Client program that uses the function.
Q. How do you define hibernate mapping file in spring? A. Add the hibernate mapping file entry in mapping resource inside Spring’s applicationContext.xml file in the web/WEB-INF directory. Q. How do you configure spring in a web application? A. It is very easy to configure any J2EE-based web application to use Spring. At the very least, you can simply add Spring’s ContextLoaderListener to your web.xml file: Q. Can you have xyz.xml file instead of applicationcontext.xml?
A. ContextLoaderListener is a ServletContextListener that initializes when your webapp starts up. By default, it looks for Spring’s configuration file at WEB-INF/applicationContext.xml. You can change this default value by specifying a Q. How do you configure your database driver in spring? A. Using datasource "org.springframework.jdbc.datasource.DriverManagerDataSource". Example: Q. How can you configure JNDI instead of datasource in spring applicationcontext.xml? A. Using "org.springframework.jndi.JndiObjectFactoryBean". Example: Q. What are the key benifits of Hibernate? A: These are the key benifits of Hibernate:
Q. What is hibernate session and session factory? How do you configure sessionfactory in spring configuration file? A. Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows applications to create hibernate session by reading hibernate configurations file hibernate.cfg.xml. // Initialize the Hibernate environment
Configuration cfg = new Configuration().configure();
// Create the session factory
SessionFactory factory = cfg.buildSessionFactory();
// Obtain the new session object
Session session = factory.openSession();
The call to Configuration().configure() loads the hibernate.cfg.xml configuration file and initializes the Hibernate environment. Once the configuration is initialized, you can make any additional modifications you desire programmatically. However, you must make these modifications prior to creating the SessionFactory instance. An instance of SessionFactory is typically created once and used to create all sessions related to a given context. The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states: transient: never persistent, not associated with any Session
persistent: associated with a unique Session
detached: previously persistent, not associated with any Session
A Hibernate Session object represents a single unit-of-work for a given data store and is opened by a SessionFactory instance. You must close Sessions when all work for a transaction is completed. The following illustrates a typical Hibernate session: Session session = null; UserInfo user = null; Transaction tx = null; try { session = factory.openSession(); tx = session.beginTransaction(); user = (UserInfo)session.load(UserInfo.class, id); tx.commit(); } catch(Exception e) { if (tx != null) { try { tx.rollback(); } catch (HibernateException e1) { throw new DAOException(e1.toString()); } } throw new DAOException(e.toString()); } finally { if (session != null) { try { session.close(); } catch (HibernateException e) { } } } Q. What is the difference between hibernate get and load methods? A. The load() method is older; get() was added to Hibernate’s API due to user request. The difference is trivial: The following Hibernate code snippet retrieves a User object from the database: User user = (User) session.get(User.class, userID); The get() method is special because the identifier uniquely identifies a single instance of a class. Hence it’s common for applications to use the identifier as a convenient handle to a persistent object. Retrieval by identifier can use the cache when retrieving an object, avoiding a database hit if the object is already cached. Hibernate also provides a load() method: User user = (User) session.load(User.class, userID); If load() can’t find the object in the cache or database, an exception is thrown. The load() method never returns null. The get() method returns null if the object can’t be found. The load() method may return a proxy instead of a real persistent instance. A proxy is a placeholder instance of a runtime-generated subclass (through cglib or Javassist) of a mapped persistent class, it can initialize itself if any method is called that is not the mapped database identifier getter-method. On the other hand, get() never returns a proxy. Choosing between get() and load() is easy: If you’re certain the persistent object exists, and nonexistence would be considered exceptional, load() is a good option. If you aren’t certain there is a persistent instance with the given identifier, use get() and test the return value to see if it’s null. Using load() has a further implication: The application may retrieve a valid reference (a proxy) to a persistent instance without hitting the database to retrieve its persistent state. So load() might not throw an exception when it doesn’t find the persistent object in the cache or database; the exception would be thrown later, when the proxy is accessed. Q. What type of transaction management is supported in hibernate? A. Hibernate communicates with the database via a JDBC Connection; hence it must support both managed and non-managed transactions. non-managed in web containers: managed in application server using JTA: Q. What is lazy loading and how do you achieve that in hibernate? A. Lazy setting decides whether to load child objects while loading the Parent Object. You need to specify parent class.Lazy = true in hibernate mapping file. By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database. Examples: Address child of User class can be made lazy if it is not required frequently. But you may need to load the Author object for Book parent whenever you deal with the book for online bookshop. Hibernate does not support lazy initialization for detached objects. Access to a lazy association outside of the context of an open Hibernate session will result in an exception. Q. What are the different fetching strategy in Hibernate? A. Hibernate3 defines the following fetching strategies: Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.
Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.
Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.
For more details read short primer on fetching strategy at http://www.hibernate.org/315.html
Q. What are different types of cache hibernate supports ? A. Caching is widely used for optimizing database applications. Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided. In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects. The query cache should always be used in conjunction with the second-level cache. Hibernate supports the following open-source cache implementations out-of-the-box:
Q. What are the different caching strategies? A. The following four caching strategies are available:
Q. How do you configure 2nd level cach in hibernate?
A. To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows: Q. What is the difference between sorted and ordered collection in hibernate? A. A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause. Example: Let us take the simple example of 3 java classes. Class Manager and Worker are inherited from Employee Abstract class.
1. Table per concrete class with unions : In this case there will be 2 tables. Tables: Manager, Worker [all common attributes will be duplicated]
2. Table per class hierarchy: Single Table can be mapped to a class hierarchy. There will be only one table in database called 'Employee' that will represent all the attributes required for all 3 classes. But it needs some discriminating column to differentiate between Manager and worker;
3. Table per subclass: In this case there will be 3 tables represent Employee, Manager and Worker |
Posted by iCehaNgeR's hAcK NoteS at 2:19 PM 4 comments
Thursday, June 7, 2007
Versions
JDK 1.4 and 1.5 Struts 1.3 Hibernet 3.1.3 Spring 1.2.8 Apache Tomcat Eclipse RAD WAS
Posted by iCehaNgeR's hAcK NoteS at 8:40 PM 0 comments
UML diagrams
http://www.holub.com/goodies/uml/
Posted by iCehaNgeR's hAcK NoteS at 8:39 PM 0 comments
Webservices
1. How to implement Webservice. steps.
Posted by iCehaNgeR's hAcK NoteS at 8:39 PM 0 comments
Patterns
1.Different types of patterns.
Posted by iCehaNgeR's hAcK NoteS at 8:38 PM 0 comments
JMS.
1.How to do lookup in JMS.
JMS API Architecture
A JMS application is composed of the following parts.
Pub/sub messaging has the following characteristics.
- Each message can have multiple consumers.
- Publishers and subscribers have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages.
/* * Look up connection factory and queue. If either does * not exist, exit. */ try { queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("java:comp/env/jms/MyQueueConnectionFactory"); queue = (Queue) jndiContext.lookup("java:comp/env/jms/QueueName"); } catch (NamingException e) { System.out.println("JNDI lookup failed: " + e.toString()); System.exit(1); } /* * Create connection. * Create session from connection; false means session is * not transacted. * Create sender and text message. * Send messages, varying text slightly. * Finally, close connection. */ try { queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queueSender = queueSession.createSender(queue); message = queueSession.createTextMessage(); for (int i = 0; i < NUM_MSGS; i++) { message.setText("This is message " + (i + 1)); System.out.println("Sending message: " + message.getText()); queueSender.send(message); } Receiving Message Using MDB ---------------------------
- public interface TextMessage extends Message
ATextMessage
object is used to send a message containing ajava.lang.String
. It inherits from theMessage
interface and adds a text message body. implement the Message Driven Bean with implements MessageDrivenBean, MessageListener /** * onMessage method, declared as public (but not final or * static), with a return type of void, and with one argument * of type javax.jms.Message. * * Casts the incoming Message to a TextMessage and displays * the text. * * @param inMessage the incoming message */ public void onMessage(Message inMessage) { TextMessage msg = null; try { if (inMessage instanceof TextMessage) { msg = (TextMessage) inMessage; System.out.println("MESSAGE BEAN: Message " + "received: " + msg.getText()); } else { System.out.println("Message of wrong type: " + inMessage.getClass().getName()); } } catch (JMSException e) { System.err.println("MessageBean.onMessage: " + "JMSException: " + e.toString()); mdc.setRollbackOnly(); } catch (Throwable te) { System.err.println("MessageBean.onMessage: " + "Exception: " + te.toString()); } } } catch (JMSException e) {
Posted by iCehaNgeR's hAcK NoteS at 8:38 PM 0 comments
JDBC
1. How to do JDBC connection 2. Prepared statement
Posted by iCehaNgeR's hAcK NoteS at 8:37 PM 0 comments
EJB
BMP and CMB 1. Methods in EJB 2. EJB life cycle
Stateless session bean life cycle
Life cycle means when an EJBean is created and removed by EJB Container, and when the Container calls methods of EJBean. The following figure illustrates the life cycle of Stateless session bean.
You can control life cycle by mentioning instance pool size in vendor specific deployment descriptor. For example weblogic server's weblogic-ejb-jar.xml has element for instance pool size
and JBoss server's jboss.xml has an element
When the server starts up, the EJB Container/Server creates 50 beans using Class.newInstance() method and puts it in the pool and it calls the following call back methods of the bean.
setSessionContext(ctx) and
ejbCreate() methods
these 50 beans are ready to be accessed by 50 clients concurrently. If the client accesses exceed 50 then the Container creates beans and calls the above methods till the number of beans is equal to 100 (maximum beans in the pool). So at any time the Container can only have a maximum of 100 beans to serve clients. What will happen if the concurrent clients are more than 100? Then the container puts clients in the queue. We will discuss about this in the next section on how you can tune the pool size.
The Container removes the beans from the pool if the number of clients accessing beans are less. When the Container removes the beans depending on its specific algorithms ( perhaps LRU, Least Recently Used). At this time Container calls ejbRemove() method of the bean.
If the client calls the home.create() method, the Container creates EJBObject and assigns existing bean from the pool to the the client, at this time client neither creates a bean nor calls ejbCreate() method because it is already called when it created and is put in the pool. In the same manner, if the client calls home.remove() / remote.remove() method, the Container removes EJBObject and deassigns the bean from the client and puts it back to the pool but does not remove from the pool. In Stateless session bean life cycle, Client does not have control over bean's life cycle and bean's call back methods, it does not know when the creation, destruction and call back methods occur. So In Stateless session beans the creation, destruction and call back methods depend upon the pool size, clients concurrent access and Container algorithms.
As the name implies, a Stateless session bean does not maintain any state ( instance variables values) across methods, that is the reason why ejbActivate() and ejbPassivate() methods do not have significance in Stateless session bean. So the Container can assign different beans from the pool to the client for successive methods.
With this discussion, we understand the importance of pool size and when the call back methods are executed in Stateless session beans. Now let us discuss how we can tune Stateless session beans.
Tune Stateless session beans instance pool size
The creation and destruction of beans is expensive. To reduce this cost, The EJB Container/Server creates pool of beans that depending upon vendor specific configuration, you need to give a proper value for this pool size to increase performance. As we discussed above, configure pool size, for example weblogic's weblogic-ejb-jar.xml has an element
The number of maximum beans in pool impacts performance. If this is less, then the Container has to put the clients in the queue when the number of clients accessing is more than the maximum pool size. This degrades the performance and clients take more time to execute. For best performance, give maximum beans as equal to number of maximum clients accesses.
Stateful session bean life cycle
The life cycle of Stateful and Stateless bean is differs. The reason is, Stateful session bean has to maintain state (instance variables values) across the methods for a client. That means once a client assigns values for instance variables using one method, those values are available for other methods also. The following figure illustrates the life cycle of Stateful session bean.
Figure7: Stateful session bean life cycle
Here you see the instance cache instead of instance pool. Cache maintains beans that have state (Stateful) whereas pool maintains beans that don't have state (Stateless). You can control life cycle by describing instance cache size in vendor specific deployment descriptor file. For example weblogic's weblogic-ejb-jar.xml has element for instance cache size
and JBoss server's jboss.xml has an element
For detailed information, look at their documentation and for other servers look at vendors documentation for instance cache configuration.
Here you can specify minimum beans and maximum beans in cache. Some vendors such as weblogic do not support configuring minimum beans but support configuring maximum beans. So look at your vendor documentation for detailed information on what your EJB Container/server supports.
Here life cycle of stateful session bean starts when the client calls create() method. When the the client calls create() method, the Container creates the bean using Class.newInstance() and calls
setSessionContext(ctx) and
ejbCreate() methods
and puts it in the instance cache. Then onwards, the client is assigned to that bean till client calls remove() method, thus container calls ejbRemove() and destroys the bean. In Stateful session bean, the client controls life cycle ( creation and removal but not activation and passivation). So when does container call ejbActivate() and ejbPassivate() methods? For example, if you set maximum beans in cache as 100 beans, when clients are accessing a bean concurrently, container creates beans till 100 (maximum bean limit) and assigns those beans to clients. After this limit, if the 101st client accesses this bean, Container passivates some of the idle beans that depending on Container algorithms. Just before passivating beans, it calls ejbPassivate() method. Here passivation means, it stores the bean's state (instance variables values) in the secondary storage (file storage or database). The passivation happens through Serialization. Later if the the idle client accesses the bean again, then Container activates the bean and reassigns the passivated values to its instance variables and calls ejbActivate() method.
Here what we understand is that client controls creation and destruction of beans but not activation and passivation. Activation and passivation are controlled by Container and depend on instance cache size.
With this discussion, we understand the importance of instance cache size and when the call back methods are executed in Stateful session beans. Now let us discuss how we can tune Stateful session beans.
Tune Stateful session beans instance cache size
As discussed above, You control activation and passivation indirectly by describing instance cache size in vendor specific deployment descriptor file . Activation and passivation is expensive because of serialization process. If the instance cache size is less and concurrent active clients are more than instance cache size then activation and passivation occur often, thus degrading performance. So in order to increase performance, give optimal cache size.
Set optimal bean age for Stateful session beans
The removal of EJBean instance by the Container from the instance cache depends not only on when the client calls remove() method but also on EJBean time out value (bean age) that you can configure in the vendor specific descriptor file. If the beans time out value is less, the Container needs to remove and create often,which is expensive. So set optimal bean age to minimise removal and creation process.
The life cycle of Entity beans is a combination of Stateless and Stateful bean life cycles. There is slight difference between Container managed persistence (CMP) and Bean managed persistence (BMP) entity bean's life cycle that is negligible. So here we will discuss a generalized life cycle that applies to both.
The following figure illustrates the life cycle of Entity beans.
Figure7: Entity session bean life cycle
Here you see both instance pool and instance cache. instance pool maintains entity beans without state data and instance cache maintains entity beans with state data.
You can control life cycle in Entity beans by mentioning instance pool size and instance cache size in vendor specific deployment descriptor. For example weblogic's weblogic-ejb-jar.xml has element for instance pool size,
and instance cache size
and in JBoss, jboss.xml has an element
and for instance cache size
If you mention 50 beans as initial beans and 100 beans as maximum beans for instance pool, 50 (min) and 100(max) for instance cache, life cycle starts when the server starts up.
When the server starts up, First, the EJB Container/Server creates 50 beans using Class.newInstance() method and puts them in the pool and it calls setEntityContext() method on each bean. The Container can remove beans from the pool depending on clients accesses and idle time of beans in the pool. When it removes the bean from the pool it calls unSetEntityContext() method on the bean.
Next, When the client calls the create() method, the Container calls corresponding ejbCreate() method on one of the beans in the instance pool and creates a row in the database and populates the values to the variables and puts it in the instance cache after returning primary key. At this stage an EJBObject is assigned to the client that communicates to the bean in the instance cache. Next, the Container calls ejbPostCreate() method. At this stage, the bean is moved from pool to cache and is ready to serve clients business methods.
Next, When the client calls the business method, the Container calls ejbLoad() that updates the beans state, executes the business method, and calls ejbStore() method to store the data in the database. If the concurrent active clients are more than cache size then the container passivates a bean and calls ejbStore(), ejbPassivate() methods and puts it back in the instance pool. If the idle client calls again after some time, container calls ejbLoad() to get latest data, and calls ejbActivate() method and puts it in the instance cache.
Next, If the client calls remove() method, the Container calls ejbRemove() method that removes the data from the database and puts the bean back in the instance pool from instance cache.
With this discussion, we understand that
1. Client controls life cycle of a bean that involves creation of data in the database thus moving the bean from pool to the cache and removal of data from the database thus moving the bean from cache to the pool.
2. Container controls the life cycle in the pool and cache and also activation and passivation process in the cache.
3. Both client and container control ejbLoad() and ejbStore() methods depending upon client's method calls and Container activation and passivation process.
Finally the overall life cycle depends upon clients concurrent operations, instance pool size and instance cache size.
Now let us discuss how we can tune Entity beans.
Tune Entity beans instance pool size
As per Entity bean life cycle discussion, we understand that we can control creation and destruction of beans by describing pool size(min and max) in vendor specific deployment descriptor (or other vendor specific manner). If this size is less (if your default size is less or you configure a smaller size) then the Container has to put the clients in the queue when the number of concurrent clients accessing ( create/finder/home methods) are more than the max pool size. And also instance cache depends up on instance pool because the instance cache needs to get beans from the instance pool. So if the pool size is less, It degrades the performance and clients take more time to execute. For best performance, give maximum beans in pool as equal to number of maximum concurrent client accesses (create/finder/home methods), so that it reduces creation and destruction of beans.
You can configure your pool size in vendor specific deployment descriptor ( or other vendor specific manner). In the above Entity bean life cycle section, We discussed how to configure this pool size in Weblogic and JBoss servers.
4. Different EJB's 5. How to do lookup.
Posted by iCehaNgeR's hAcK NoteS at 8:37 PM 0 comments
Hibernate
1. Difference between SQL and HQL
2. Why is hbernate useful
3. How is it used step by step
Mapping is done in .hbm.xml
applicationContext-hibernate.xml
An ApplicationContext provides the following functionalities:
* Bean factory methods, inherited from ListableBeanFactory. This avoids the need for applications to use singletons.
* The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface.
* The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface.
* The ability to publish events. Implementations must provide a means of registering event listeners.
* Inheritance from a parent context. Definitions in a descendant context will always take priority. This means, for example, that a single parent context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet.
Things to be defined in the applicationContext
DriverManagerDataSource
LocalSessionFactoryBean --
HibernateTransactionManager
DAOImplementation
TransactionProxyFactoryBean
Posted by iCehaNgeR's hAcK NoteS at 8:36 PM 0 comments
Struts
Model-View-Controller (MVC) MVC Model 2
- Model The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.
- View The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.
- Controller The controller reacts to the user input. It creates and sets the model.
1. Different classes in Struts. 2. Objects in struts 3. Steps in Struts with Flow and the Class Figure 5. Struts overview
Struts overview
- Client browser An HTTP request from the client browser creates an event. The Web container will respond with an HTTP response.
- Controller
The Controller receives the request from the browser, and makes the decision where to send the request. With Struts, the Controller is a command design pattern implemented as a servlet. The
struts-config.xml
file configures the Controller. - Business logic
The business logic updates the state of the model and helps control the flow of the application. With Struts this is done with an
Action
class as a thin wrapper to the actual business logic. - Model state The model represents the state of the application. The business objects update the application state. ActionForm bean represents the Model state at a session or request level, and not at a persistent level. The JSP file reads information from the ActionForm bean using JSP tags.
- View The view is simply a JSP file. There is no flow logic, no business logic, and no model information -- just tags. Tags are one of the things that make Struts unique compared to other frameworks like Velocity.
The ActionMapping
class
An incoming event is normally in the form of an HTTP request, which the servlet Container turns into an HttpServletRequest
. The Controller looks at the incoming event and dispatches the request to an Action
class. The struts-config.xml
determines what Action
class the Controller calls. The struts-config.xml
configuration information is translated into a set of ActionMapping
, which are put into container of ActionMappings
. (If you have not noticed it, classes that end with s are containers)
The ActionMapping
contains the knowledge of how a specific event maps to specific Actions
. The ActionServlet
(Command) passes the ActionMapping
to the Action
class via the perform()
method. This allows Action
to access the information to control flow.
ActionMappings
ActionMappings
is a collection of ActionMapping
objects.
Posted by iCehaNgeR's hAcK NoteS at 8:36 PM 0 comments
Spring.
1. Spring Layers
*. Core Container: The core container provides the fundamental functionality of Spring. It's primary component is the 'BeanFactory', an implementation of the Factory pattern. The BeanFactory applies the IOC pattern to separate an application's configuration and dependency specification from the actual application code.
*. Spring Context/Application Context:The Spring context is a configuration file that provides context information to the Spring framework . The Spring context supplies enterprise services such as JNDI access, EJB integration, e-mail, internalization, validation, and scheduling functionality.
*. Spring AOP:(Aspect-Oriented)The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result we can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP we can incorporate declarative transaction management into our applications without relying on EJB components. The Spring AOP module also introduces metadata programming to Spring. Using this we can add annotation to the source code that instructs Spring on where and how to apply aspects.
*. Spring DAO:The Spring's JDBC and DAO abstraction layer offers a meaningful exception hierarchy for managing the databaase connection, exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of code that we need to write, such as opening and closing connections. This module also provide transaction management services for objects in a spring application.
*. Spring ORM:The Spring framework can be integrated to several ORM frameworks to provide Object Relational tool, including JDO, Hibernate, OJB and iBatis SQL Maps.
*. Spring Web module:The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts, JSF and webworks. The Web module also eases the tasks of handling multipart requests and binding request parameters to domain objects.
*. Spring MVC Framework:The MVC framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles and the generation of PDF and Excel Files.
Declerative ManagementWe don't directly connect our components and services together in code but describe which services are needed by which components in a configuration file. A container is responsible for hooking it up. This concept is similar to 'Declarative Management'.
Dependency Lookup:The container provides callbacks to components and a lookup context. The managed objects are responsible for their other lookups Dependency Injection: In this application objects is not responsible for looking up resources they depend on. Instead IoC container configures the object externalizing resource lookup from application code into the container. That is, dependencies are injected into objects. Thus lookups are completely removed from application objects and it can be used outside the container also. cle
Posted by iCehaNgeR's hAcK NoteS at 8:35 PM 0 comments
Servlet life cycle
init()
doGet()
doPost()
destroy()
What are the different cases for using sendRedirect() vs. getRequestDispatcher()?
When you want to preserve the current request/response objects and transfer them to another resource WITHIN the context, you must use getRequestDispatcher or getNamedDispatcher.
If you want to dispatch to resources OUTSIDE the context, then you must use sendRedirect. In this case you won't be sending the original request/response objects, but you will be sending a header asking to the browser to issue a request to the new URL.
http://faqs.javabeat.net/servlet/java-servlets-interview-questions-faqs-8.php
Posted by iCehaNgeR's hAcK NoteS at 8:35 PM 0 comments
Methods in Servlet
ServletContext, HttpSession, ServletConfig
Posted by iCehaNgeR's hAcK NoteS at 8:34 PM 0 comments
JSP/Servlet.
Posted by iCehaNgeR's hAcK NoteS at 8:34 PM 0 comments
Pass By Value Pass By reference
Java pass everything by Value. Objects are manuplated by refrence though for methods its all Value.
Posted by iCehaNgeR's hAcK NoteS at 8:33 PM 0 comments
When to use Vector? When to use ArrayList?
Posted by iCehaNgeR's hAcK NoteS at 8:33 PM 0 comments
ArrayList v/s Vector
Arraylist is not synchronized while vector is. (not thread safe) Arraylist has no default size while vector has a default size of 10. Arraylist don't define any increment size while vector does. ArrayList implements Iterator Interface for traversing While Vector implements Innumerator Interface for traverse.
Posted by iCehaNgeR's hAcK NoteS at 8:32 PM 0 comments
Singleton
Creating only one instance of the class
Posted by iCehaNgeR's hAcK NoteS at 8:31 PM 0 comments
Static Class
A static member class will have the static keyword
Posted by iCehaNgeR's hAcK NoteS at 8:30 PM 0 comments
Final , Finaly and Finalize
Final data
Many programming languages have a way to tell the compiler that a piece of data is “constant.” A constant is useful for two reasons:
- It can be a compile-time constant that won’t ever change.
- It can be a value initialized at run time that you don’t want changed.
Final methods
There are two reasons for final methods. The first is to put a “lock” on the method to prevent any inheriting class from changing its meaning. This is done for design reasons when you want to make sure that a method’s behavior is retained during inheritance and cannot be overridden. Feedback
The second reason for final methods is efficiency. If you make a method final, you are allowing the compiler to turn any calls to that method into inline calls. When the compiler sees a final method call, it can (at its discretion) skip the normal approach of inserting code to perform the method call mechanism (push arguments on the stack, hop over to the method code and execute it, hop back and clean off the stack arguments, and deal with the return value) and instead replace the method call with a copy of the actual code in the method body. This eliminates the overhead of the method call.
Final classes
When you say that an entire class is final (by preceding its definition with the final keyword), you state that you don’t want to inherit from this class or allow anyone else to do so. In other words, for some reason the design of your class is such that there is never a need to make any changes, or for safety or security reasons you don’t want subclassing
Finaly Thefinally
block always executes when the try
block exits. This ensures that the finally
block is executed even if an unexpected exception occurs. But finally
is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return
, continue
, or break
. Putting cleanup code in a finally
block is always a good practice, even when no exceptions are anticipated.
Finalize.
- every class inherits the finalize() method from java.lang.Object
- the method is called by the garbage collector when it determines no more references to the object exist
- the Object finalize method performs no actions but it may be overridden by any class
- normally it should be overridden to clean-up non-Java resources ie closing a file
Posted by iCehaNgeR's hAcK NoteS at 8:29 PM 0 comments
UnChecked Exception
*"Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time." * are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException * a method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation.
Posted by iCehaNgeR's hAcK NoteS at 8:29 PM 0 comments
Exception
Checked Exception * represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files) * are subclasses of Exception * a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)
Posted by iCehaNgeR's hAcK NoteS at 8:28 PM 0 comments
Thread lifecycle
Extend the Abstract Class Thread or implement Runnabel overide the run method. call the start method to ivoke the run start--> run() Yield method is used to allow other thread to use the resource. sleep also can be used to pause for execution the thread Demon Thread. A demon thread is one that is supposed to provide a general service in the background as long as the program is running, this have to be called before start
Posted by iCehaNgeR's hAcK NoteS at 8:27 PM 1 comments
Package
A Java package is a mechanism for organizing Java classes into namespaces A package provides a unique namespace for the types it contains. Classes in the same package can access each other's protected members.
Posted by iCehaNgeR's hAcK NoteS at 8:27 PM 0 comments
Encapsulation.
Encapsulation is the ability of an object to be a container (or capsule) for related properties (ie. data variables) and methods (ie. functions). Data hiding is the ability of objects to shield variables from external access. These private variables can only be seen or modified by use of object accessor and mutator methods. Private, Public and Protected. usage of Package. etc.
Posted by iCehaNgeR's hAcK NoteS at 8:26 PM 0 comments
Polymorphisms
Polymorphisms is the capability of an action or method to do different things based on the object that it is acting upon. method overloading , overriding and dynamic method binding. Overloading It happens in same Class. method name should be the same but argument and return type can change Overriding It happens in the derived Class with specif new definition should have same method name , argument and return type like the parent class. Dynamic Binding A mechanism by which, when the compiler can't determine which method implementation to use in advance, the runtime system (JVM) selects the appropriate method at runtime, based on the class of the object
Posted by iCehaNgeR's hAcK NoteS at 8:24 PM 0 comments
Inheritance
Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. An example of where this could be useful is with an employee records system. You could create a generic employee class with states and actions that are common to all employees. Then more specific classes could be defined for salaried, commissioned and hourly employees. The generic class is known as the parent (or superclass or base class) and the specific classes as children (or subclasses or derived classes). The concept of inheritance greatly enhances the ability to reuse code as well as making design a much simpler and cleaner process.
Posted by iCehaNgeR's hAcK NoteS at 8:23 PM 0 comments
OOPS !
Corner Stone. Polymorphisms , Inheritance, Encapsulation
Posted by iCehaNgeR's hAcK NoteS at 8:22 PM 0 comments
Object
2. What is an Object An Object is a instance of class. An Object has state, behavior and identity. Object Class The Object class is the superclass of Java. All other classes are subclasses of the Object class. The object class includes methods such as: clone() finalize() hashCode() toString() copy(Object src) getClass() notifyAll() wait()
Posted by iCehaNgeR's hAcK NoteS at 8:21 PM 0 comments
Class
1. What is a Class * Class describes a set of objects that have identical characteristics (data elements) and behaviors (functionality). * A class is a definition or prototype whereas an object is an instance or living representation of the prototype. * A class specifies the properties (data) and methods (actions) that objects can work with. It is a template or prototype for each of many objects made to the class design.
Posted by iCehaNgeR's hAcK NoteS at 8:17 PM 1 comments