157
What is EJB? Enterprise JavaBeans (EJB) is Sun Microsystems' specification for a distributed object system similar to CORBA and Microsoft Transaction Server, but based on the Java platform. EJB specifies how developers should build components that can be accessed remotely and how EJB vendors should support those components. EJB components, called enterprise beans, automatically handle transactions, persistence, and authorization security, so that the developer can focus on the business logic. What is an Enterprise Bean? An enterprise bean is a server-side component -- defined in the Java technology -- which adheres to the Enterprise JavaBeans server-side component model. A server-side component is business object that can be accessed remotely. Many server-side component models exist: CORBA specifies CORBA objects; Microsoft Transaction Server (MTS) defines COM/DCOM; and EJB specifies enterprise beans. Enterprise beans can be developed to represent business concepts like Employee, Order, TravelAgent, etc. Enterprise beans can be assembled into applications that solve enterprise business problems. EJB has two basic types of enterprise beans: Session and Entity. Depending on the type of enterprise bean used, features like persistence, transactions, security, and multiple concurrent access can be managed automatically. Are Enterprise JavaBeans and JavaBeans the same thing? Answer Enterprise JavaBeans and JavaBeans are not the same thing; nor is one an extension of the other. They are both component models, based on Java, and created by Sun Microsystems, but their purpose and packages (base types and interfaces) are completely different. JavaBeans The original JavaBeans specification is based on the java.beans package which is a standard package in the JDK. Components built on the JavaBeans specification are intraprocess components that live in one address space and are typically used for Graphical User Interface (GUI) as visual widgets like buttons, tables, HTML viewers, etc. Enterprise JavaBeans Page 1 of 157

J2EE Questions

Embed Size (px)

Citation preview

Page 1: J2EE Questions

What is EJB?Enterprise JavaBeans (EJB) is Sun Microsystems' specification for a distributed object system similar to CORBA and Microsoft Transaction Server, but based on the Java platform. EJB specifies how developers should build components that can be accessed remotely and how EJB vendors should support those components. EJB components, called enterprise beans, automatically handle transactions, persistence, and authorization security, so that the developer can focus on the business logic.

What is an Enterprise Bean?An enterprise bean is a server-side component -- defined in the Java technology -- which adheres to the Enterprise JavaBeans server-side component model. A server-side component is business object that can be accessed remotely. Many server-side component models exist: CORBA specifies CORBA objects; Microsoft Transaction Server (MTS) defines COM/DCOM; and EJB specifies enterprise beans. Enterprise beans can be developed to represent business concepts like Employee, Order, TravelAgent, etc. Enterprise beans can be assembled into applications that solve enterprise business problems. EJB has two basic types of enterprise beans: Session and Entity. Depending on the type of enterprise bean used, features like persistence, transactions, security, and multiple concurrent access can be managed automatically.

Are Enterprise JavaBeans and JavaBeans the same thing? Answer Enterprise JavaBeans and JavaBeans are not the same thing; nor is one an extension of the other. They are both component models, based on Java, and created by Sun Microsystems, but their purpose and packages (base types and interfaces) are completely different. JavaBeans The original JavaBeans specification is based on the java.beans package which is a standard package in the JDK. Components built on the JavaBeans specification are intraprocess components that live in one address space and are typically used for Graphical User Interface (GUI) as visual widgets like buttons, tables, HTML viewers, etc. Enterprise JavaBeans

The EJB specification is based on the javax.ejb package, which is a standard extension package. Components built on the EJB specification are interprocess components that live in multiple address spaces as distributed object. These components are used as transactional business objects that are accessed as remote objects. JavaBeans components are small-grained application bits. You can use JavaBeans to assemble larger-grained components or to build entire applications. JavaBeans, however, are development components and are not deployable components. You typically do not deploy a JavaBean because a JavaBean is not a complete application; rather, JavaBeans help you construct larger software that is deployable. And because they cannot be deployed, JavaBeans do not need a runtime environment in which to live. JavaBeans do not need a container to instantiate them, to destroy them, and to provide other services to them because the application itself is made up of JavaBeans. By way of comparison, the Enterprise JavaBeans (EJB) standard defines a component architecture for deployable

Page 1 of 112

Page 2: J2EE Questions

components called enterprise beans. Enterprise beans are larger, coarser-grained application components that are ready to be deployed. They can be deployed as is, or they can be assembled with other components into larger application systems. Deployable components must be deployed in a container that provides runtime services to the components, such as services to instantiate components as needed.

What is passivation and activation?

Passivation and activation are two phases of a resource management technique that reduces the number of bean instances needed to service all clients. Passivation is the process of disassociating a bean instance from its EJB object so that the instance can be reused or evicted to conserve memory. Activation is the process of associating a bean instance with an EJB object so that it can service a request. Beans are passivated when there is a lull in their use and activated when the EJB object receives a client request. The javax.ejb.SessionBean and javax.ejb.EntityBean interface include two callback methods that notify a bean instance when it is about to passivated or activated. The ejbPassivate( ) method notifies a bean that it is about to passivated; the ejbActivate( ) method notifies a bean that it is about to activated. The mechanisms employed in passivation and activation change depending on the bean type. Stateful beans are usually evicted, while entity beans and stateless beans are pooled. A more detailed account of how different bean types passivated and activated is found under the FAQs for that type.

How do beans manage resource connections to back-end services other than databases ? While EJB 1.1 provides the JNDI ENC for managing standard resources like URL, JDBC, JavaMail and JMS, connections to other types of resources are not addressed by EJB 1.0 or EJB 1.1, but there are solutions. Below is a list of some strategies that can provide access to "back-ends" besides relational databases. Leveraging the instance fields:Each EJB vendor implements resource management differently. In EJB servers where the instance is pooled and reused it may be possible to allow a back-end resource connection to be maintained through passivation. The back-end connection might wrapped in a CORBA or Java RMI object, accessed by a raw network socket, or some other connection facility. This strategy works in stateless session beans and entity beans in EJB servers that pool and reuse these bean types. In stateless beans you can simply reference the resources using the instance fields -- stateless beans are not passivated in EJB. In entity beans you can also reference the connections using instance fields but the field used must not be declared as a container-managed field in the deployment descriptor. In both stateless and entity beans there are methods can be used safely to open and close resource connections at the beginning and end of the beans life. In stateless session beans long-lived resources should be opened in the setSessionContext( ) method and closed in the ejbRemove( ) method. These methods are invoked at the beginning and end of a stateless session instance's life; when it's first instantiated and before its evicted form the container. In entity beans long-lived resource should be opened in the setEntityContext( ) method and closed in the unsetEntityContext( ) method. These methods are invoked at the

Page 2 of 112

Page 3: J2EE Questions

beginning and end of an entity instance's life; when it's first instantiated and before its evicted form the container.

What are the constraints or drawbacks of container managed EJB's ? CMP in beans depends a lot on the EJB vendor implementation and utilities. With some implementations container-managed entity beans can only by mapped to one table, while other implemenations offer Multiple table mappings to a single bean. The bottom line,It depends on the container provider being used.

How can my JSP page communicate with an EJB Session Bean? The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean: <%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject,foo.AccountHome, foo.Account" %><%! //declare a "global" reference to an instance of the home interface of the session bean AccountHome accHome=null;

public void jspInit() { //obtain an instance of the home interface InitialContext cntxt = new InitialContext( ); Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB"); accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class); }%><% //instantiate the session bean Account acct = accHome.create(); //invoke the remote methods acct.doWhatever(...); // etc etc...%>

What's an .ear file? An .ear file is an "Enterprise Archive" file. The file has the same format as a regular .jar file (which is the same as ZIP, incidentally). The .ear file contains everything necessary to deploy an enterprise application on an application server. It contains both the .war (Web Archive) file containing the web component of the application as well as the .jar file. In addition there are some deployment descriptor files in XML.

Let's assume I use a JavaBean as a go-between a JSP and an EJB, and have, say, 50 concurrent clients that need to access the EJB functionality. Will the JSP container actually instantiate 50 instances of the bean, or can it reuse a single instance to access the EJB? It depends on the scope you associate with the JavaBean. If you assign the bean with page (which is the default) scope or request scope, a new bean will be instantiated for

Page 3 of 112

Page 4: J2EE Questions

each incoming request. If you assign the bean with session scope, you will still have 50 instances loaded in memory (assuming each incoming request is triggered by a distinct client), although some may have been instantiated from an earlier request from the same client. However, you may not want to use the session scope for a high-volume site as these beans will continue to reside in memory, long after the request has been serviced, consuming valuable resources until they are invalidated either explicitly or due to a session timeout. You can also assign the bean with application scope, in which case it is instantiated just once before being placed into the servlet context of the container. It can then be accessed at a later time, as long as the server is up and running. Although this may sound like an attractive proposition, do note that you will have to contend with significant multithreading issues. For instance, you'll have to ensure that the bean is accessed in a thread-safe manner from each of the JSP files. While you can do this using explicit synchronization from within the JSP file, do note that your application may take a significant performance hit because of this - especially if you expect tens or hundreds of concurrent clients accessing your pages. So, in short, your best bet may be to assign the bean with request scope.

Which IDEs are available that support EJB development? And are any free or low-cost? WebGain's StructureBuilder 3.3, which supports a UML-to-Javacode cyclical development, and with its new "ejbCreate" facility, supports 1.0 and 1.1 EJB development.

How can I debug my EJB applications? This depends upon which EJB Container you are using. Borland's JBuilder 3.5, Foundation Edition allows you to debug any Java 2 application, including the Inprise Application Server, WebLogic Server and J2EE Reference implementation. You can download it free from www.borland.com/jbuilder. There are other IDE's out there including NetBeans/Forte www.sun.com/forte/ffj/ce/ that can also debug EJB.

What's the difference between EJBHome, EJB Home, EJB Object, EJBObject and EJB (not to mention Home Interface and Remote Interface)? First, an Enterprise JavaBean is not a JavaBean (but you already knew that). The "Home Interface" is actually a Factory Object. It is responsible for locating or creating instances of the desired bean, and returning remote references. When you write the source code for the EJB Home Interface, you must extend the interface EJBHome, and provide method signatures for all the desired create() and find() methods. An object that implements the Home Interface is automatically generated by the EJB Server tools. The "EJB Object", or Remote Object, is actually a Wrapper. It sits somewhere inside the container, between the client and your code. It is responsible for performing all the setup and shutdown tasks (like opening transactions, or restoring data state) immediately before and after your enterprise bean is called. The "EJB Object" is generated by the EJB Server tools -- you don't have to write any part of it. However, you do have to write another interface, called the "Remote Interface" or the "EJBObject Interface," that extends interface EJBObject, and provides method signatures for all the business methods. The server automatically generates a Java class that

Page 4 of 112

Page 5: J2EE Questions

implements the Remote Interface; it is this object that is registered with RMI, and a reference to it is returned by the Home Interface (which we now know is actually a Factory Object). The "EJB," or Enterprise Bean, ironically, is not the EJB Object (even though it is an EJB and it is an object). It doesn't even implement the EJBObject interface, nor does it implement the Remote Interface. Instead, it implements either the EntityBean interface or the SessionBean interface. It also must implement all the methods defined in the Remote Interface -- but it doesn't actually implement the interface (in the Java sense). This is unfortunate, since we cannot rely on the Java compiler to make sure we've implemented all the right methods. It must also implement one ejbCreate() method for each create() method in the Home Interface (as well as ejbFind()/find()).

What is an EJB Context? EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions.

What is "hot deployment" in WebLogic? "Hot Deployment" in weblogic is the act of deploying, re-depolying, and un-deploying EJBs while the server is still running (you don't have to shutdown the server to deploy an EJB).

What is a three-tier architecture? A three-tier architecture is any system which enforces a general separation between the following three parts: 1. Client Tier or user interface 2. Middle Tier or business logic 3. Data Storage Tier Applied to web applications and distributed programming, the three logical tiers usually correspond to the physical separation between three types of devices or hosts:

1. Browser or GUI Application 2. Web Server or Application Server 3. Database Server (often an RDBMS or Relational Database) However, inside of the application server, there is a further division of program code into three logical tiers. This is kind of fractal: the part (app server object design) resembles the whole (physical system architecture). In a classic JSP/Servlet system, these objects are usually implemented as: 1. JSPs or Servlets responsible for creating HTML or WML user interface pages 2. Servlets or JavaBeans responsible for business logic 3. Servlets, JavaBeans, or Java classes responsible for data access. These objects usually use JDBC to query the database. In an EJB system, the three logical tiers are usually implemented somewhat differently: 1. JSPs, Servlets, or Java client applications responsible for user interface

Page 5 of 112

Page 6: J2EE Questions

2. Session Beans or Entity Beans whose methods implement business logic and business rules 3. Entity Beans whose fields represent data; these fields are "persisted" (stored and retrieved) either by the EJB server (for container-managed persistence) or by the Entity Beans themselves (for bean-managed persistence) As you can see, the precise definition of "tiers" can vary widely depending on the particular needs and choices of an application designer. However, they all maintain the general division of client-logic-storage. If the architecture contains more than three logical tiers -- for instance, multiple data feeds, multiple transactional data sources, multiple client applications -- then it is typically called an "N-tier" or "Distributed" architecture.

Is it possible to have a Container Managed Persistent Entity Bean which refers to a view rather than a table. Yes it is possible. Using Views is a good way of mapping multiple tables to one Entity Bean. Remember that you will also need to write a Primary Key class for your Entity Bean.

What is the role of serialization in EJB? A big part of EJB is that it is a framework for underlying RMI: remote method invocation. You're invoking methods remotely from JVM space 'A' on objects which are in JVM space 'B' -- possibly running on another machine on the network. To make this happen, all arguments of each method call must have their current state plucked out of JVM 'A' memory, flattened into a byte stream which can be sent over a TCP/IP network connection, and then deserialized for reincarnation on the other end in JVM 'B' where the actual method call takes place. If the method has a return value, it is serialized up for streaming back to JVM A. Thus the requirement that all EJB methods arguments and return values must be serializable. The easiest way to do this is to make sure all your classes implement java.io.Serializable.

What is the meaning of marshalling and unmarshalling? In few words, "marshalling" refers to the process of converting the data or the objects inbto a byte-stream, and "unmarshalling" is the reverse process of converting the byte-stream beack to their original data or object. The conversion is achieved through "serialization". The purpose of the "marshalling/unmarshalling" process is to transfer data between the RMI system.

What is a BMP bean? A BMP bean is an entity bean that synchronizes its state with the database manually. In other words, the bean developer must code explicit database calls into the bean itself. BMP provides the bean developer with more flexibility in the how the bean reads and writes its data than a container-managed persistence (CMP) bean. CMP bean is limited to the mapping facilities provided by the EJB vendor, BMP beans are only limited by skill of the bean developer. The ability to code an entity bean's persistence logic explicitly is important when the EJB container's CMP features are insufficient to meet the needs of the entity bean. Entity beans that need to synchronize their state with several data sources are excellent

Page 6 of 112

Page 7: J2EE Questions

candidates for BMP. So are beans that need to access to data sources (possibly legacy systems) that are not supported by CMP. In addition, BMP bean are often employed when a vendors CMP facilities are not sophisticated enough to handle complex Object-to-Relational mapping. The BMP bean manages its own persistence, but relies on the container to coordinate its reads and writes so that persistence is accomplished in a transactional safe manner. Coordination with the container is accomplished through two mechanisms: The persistence callback methods (ejbLoad( ) and ejbStore( )); and the Environment Naming Context (EJB). The ejbLoad( ) and ejbStore( ) methods notify a bean that its time to read and write data to the database respectively. In a BMP entity bean the code for reading and writing data to the database is done within these methods. The ejbLoad( ) is called at the beginning of a transaction, just before any business methods are executed, and the ejbStore( ) is called at the end of a transaction just before its committed. This keeps the bean state in perfect synchronization with transactions being executed, without the bean developer having to explicitly manage the transactional operations. When JDBC is used to for persistence, the Environment Naming Context (ENC) is a JNDI namespace that provides the bean with access to database connections (among other things). The database connections obtained from the JNDI ENC are managed by the container, so that they are automatically enrolled in transactions and pooled. (The extent to which this is supported depends largely on the EJB vendor.) The container may also manage other data source APIs, but JDBC is standard. Below is an example of an entity bean, the Customer bean that is designed to use BMP to synchronize its own state with a CUSTOMER table in the database.

public class CustomerBean implements javax.ejb.EntityBean { // persistent bean-managed fields public long customerNumber; public String lastName; public String firstName;

// non-persistent context fields public javax.naming.Context jndiContext; public javax.ejb.EntityContext ejbContext;

// business methods public PersonName getName( ){ return new PersonName(firstName, lastName); } public void setName(PersonName name){ firstName = name.getFirstName( ); lastName = name.getLastName( ); } // called just before a business method can be invoked at the beginning of a transaction

Page 7 of 112

Page 8: J2EE Questions

public void ejbLoad( ){ try{ javax.sql.DataSource ds = (DataSource)jndiContext.lookup("java:comp/env/jdbc/Database"); java.sql.Connection con = ds.getConneciton( ); PreparedStatement ps = con.prepareStatement("select lastname, firstname from CUSTOMER where id = ?"); CustomerKey key = (CustomerKey)ejbContext.getPrimaryKey( ); customerNumber = key.id; ps.setLong(1, customerNumber); java.sql.ResultSet result = ps.executeQuery( ); while(result.next()){ lastName = result.getString("lastname"); firstName = result.getString("firstname"); } con.close();

}catch(Exception e){ throw new EJBException(e); } }

// called at the end of a transaction just before a commit is attempted public void ejbStore( ){ try{ javax.sql.DataSource ds = (DataSource)jndiContext.lookup("java:comp/env/jdbc/Database"); java.sql.Connection con = ds.getConneciton( ); PreparedStatement ps = con.prepareStatement("update CUSTOMER set lastname = ?, firstname = ? where id = ?"); ps.setString(1, lastName); ps.setString(2, firstName); ps.setLong(3, customerNumber); if( ps.executeUpdate( ) != 1) throw new EJBException("SQL update failed. ejbStore( ) failed"); con.close();

}catch(Exception e){ throw new EJBException(e); } }... }

Page 8 of 112

Page 9: J2EE Questions

Note: BMP beans use the ejbLoad( ) and ejbStore( ) callback methods differently than the Container-Managed Persistence (CMP) beans. See Java:API:EJB:EntityBean:CMP for details on how CMP beans use these methods.

What is an EJB primary key? How is it implemented when the database doesn't have a primary key? primary key is an object that uniquely identifies the entity bean. According to the specification, the primary key must be unique for each entity bean within a container. Hence the bean's primary key usually maps to the PK in the database (provided its persisted to a database). You may need to create a primary key in the database for the sake of referential integrity. This does not, however, mean you NEED a primary key in the database. As long as the bean's primary key (which maps to a column or set of columns) can uniquely identify the bean it should work.

What is a session bean? A session bean is a type of enterprise bean; a type of EJB server-side component. Session bean components implement the javax.ejb.SessionBean interface and can be stateless or stateful. Stateless session beans are components that perform transient services; stateful session beans are components that are dedicated to one client and act as a server-side extension of that client. Session beans can act as agents modeling workflow or provide access to special transient business services. As an agent, a stateful session bean might represent a customer's session at an online shopping site. As a transitive service, a stateless session bean might provide access to validate and process credit card orders. Session beans do not normally represent persistent business concepts like Employee or Order. This is the domain of a different component type called an entity bean. A session bean corresponds to a client server session. The session bean is created when a client requests some query on the database and exists as long as the client server session exists.Session Beans are generally tied to the lifetime of a given client session. They are relatively short-lived; stateful Session objects are created in response to a single client's request,communicate exclusively with a single client, and die when the client no longer needs them.

What is the difference between session and entity beans? When should I use one or the other? An entity bean represents persistent global data from the database; a session bean represents transient user-specific data that will die when the user disconnects (ends his session). Generally, the session beans implement business methods (e.g. Bank.transferFunds) that call entity beans (e.g. Account.deposit, Account.withdraw).

Life Cycle of Stateful and Stateless Session BeansStateful Session Bean

Page 9 of 112

Page 10: J2EE Questions

A stateless session bean has only two states: Does Not Exists and Method Ready Pool.A bean has not yet instantiated (so it is not an instance in memory) when it is in the Does Not Exists state. When the EJB container needs one or more beans, it creates and set them in the Method Ready Pool state. This happens through the creation of a new instance (Class.newInstance()), then it is set its context (setSessionContext()) and finally calls the ejbCreate() method. The ejbRemove() method is called to move a bean from the Method Ready Pool back to Does Not Exists state.

Stateful Session BeanUnlike Stateless, a Stateful Session Bean has three states. Does not exists, Method Ready and Passivated states. Like Stateless beans, when the Stateful Session Bean hasn't been instantiated yet (so it is not an instance in memory) is it in the Does not exists state.Once a container creates one or more instances of a Stateful Session Bean it sets them in a Method Ready state. In this state it can serve requests from its clients. Like Stateless Session Beans, a new instance is created (Class.newInstance()), the context is passed (setSessionContext()) and finally the bean is created with ejbCreate().During the life of a Stateful Session Bean, there are periods of inactivity. In these periods, the container can set the bean to the Passivate state. This happens through the ejbPassivate() method. From the Passivate state the bean can be moved back to the Method Ready state, via ejbActivate() method, or can go directly to the Does Not Exists state with ejbRemove().

Is this item helpful? yes no Previous votes Yes: 1 No: 0 Can a Session Bean be defined without ejbCreate() method? The ejbCreate() methods is part of the bean's lifecycle, so, the compiler will not return an error because there is no ejbCreate() method. However, the J2EE spec is explicit: * the home interface of a Stateless Session Bean must have a single create() method with no arguments, while the session bean class must contain exactly one ejbCreate() method, also without arguments. * Stateful Session Beans can have arguments (more than one create method)

What is a stateful session bean? A stateful session bean is an enterprise bean (EJB component) that acts as a server-side extension of the client that uses it. The stateful session bean is created by a client and will work for only that client until the client connection is dropped or the bean is explicitly removed. The stateful session bean is EJB component that implements the javax.ejb.SessionBean interface and is deployed with the declarative attribute "stateful". Stateful session beans are called "stateful" because they maintain a conversational state with the client. In other words, they have state or instance fields that can be initialized and changed by the client with each method invocation. The bean can use the conversational state as it process business methods invoked by the client.

Page 10 of 112

Page 11: J2EE Questions

Stateful session beans are usually developed to act as agents for the client, managing the interaction of other beans and performing work on behalf of the client application. An example is a shopping cart stateful session bean that tracks a client's product choices and can execute a sale when requested. Below is partial example of a stateful session bean that is used as a shopping cartpublic class ShoppingCartBean implements javax.ejb.SessionBean { // instance fields; The conversational state Vector products = new Vector( ); Customer customer; // initializes bean with reference to customer bean public void ejbCreate(Customer cust){ customer cust; }

//add a product to shopping cart public void addItem(Product item) { products.addElement(item); }

//charge customer for products and create a shipping order public void executeSale(){

// get the customer's credit card object CreditCard card = customer.getCreditCard( );

// calculate a total price from products chosen double total; for(int i = 0; i products.size(); i++){ Product product = (Product)products.elementAt(i); total += product.getPrice( ); }

// get reference to the CreditService bean and process the customers charge CreditService cardSwipper = ... get credit card service bean Charge charge = cardSwipper.charge(CreditCard, total);

// get reference to the OrderHome and create a new shipping order bean (record) OrderHome orderHome = ... get the Order beans Home object Order order = orderHome.create(customer, products, charge); }...}

Page 11 of 112

Page 12: J2EE Questions

In the example above the ShoppingCartBean keeps track of the Customer and the items chosen by the client application. This is the bean's conversational state. Once the client application is ready to execute a sale, the ShoppingCartBean manages the interactions of the Customer, Product, CreditServer, and Order beans in a workflow that results in a charge against the customers credit card and the creation of a shipping order. The ShoppingCartBean behaves as an agent for the client managing the interaction of these other beans, tracking chosen items, and executing the sale. The below table identifies the beans types used in the ShoppingCartBean example above. Bean NameBean TypeShoppingCartBeanStateful SessionCreditServiceStateless SessionCustomerEntityProductEntityOrderEntityFrom the clients perspective only the Customer and ShoppingCart beans are visible, because the client application works with the bean's remote interface while the bean itself resides on the server. This means that the client need only be concerned with the business methods made public by the ShoppingCartBean. Below is an example of the client applications view of the ShoppingCartBean. (Note: The client interacts with the beans remote interface not the bean itself. The remote interface is called the ShoppingCart.) // somewhere in the client application (applet, servlet, etc.)// obtain the home objects (factories) for the Customer and ShoppingCart beansCustomerHome custHm = ... get CustomerHomeShoppingCartHome shpCrtHm = ... get ShoppingCartHome

// locate the bean representing the customer named, Bob JohnstenCustomer customer = custHome.findByName("Bob","Johnsten");

// create a new ShoppingCart initialized with the Bob Johnsten Customer beanShoppingCart shoppingCart = shpCrtHm.create(customer); ...Product product = ... get reference to bean representing the product chosen// add product to customer's shopping cart

shoppingCart.addItem(product);...//charge customer for products and create a shipping ordershoppingCart.executeSale( );

Page 12 of 112

Page 13: J2EE Questions

Session beans like the shoppingCartBean only live as long as the client maintains a connection. In other words, they represent some aspect of the client's current session with the system and die when the client ends that session. Session beans are generally not fault tolerant. A system failure or shut down will result in the death of session bean and a loss of any conversation state it maintained prior to the failure. (This is a conceptual lifecycle of a session bean. Some vendors can make them more fault tolerant and longer lasting).

What is a stateless session bean? A stateless session bean is an enterprise bean (EJB component) that provides a stateless service to the client. Conceptually, the business methods on a stateless session bean are similar to procedural applications or static methods; there is no instance state, so all the data needed to execute the method is provided by the method arguments. The stateless session bean is an EJB component that implements the javax.ejb.SessionBean interface and is deployed with the declarative attribute "stateless". Stateless session beans are called "stateless" because they do not maintain conversational state specific to a client session. In other words, the instance fields in a stateless session bean do not maintain data relative to a client session. This makes stateless session beans very lightweight and fast, but also limits their behavior. Stateless session beans are usually developed as a set of related and simple services. Think of a session bean as a functional API where each business method represents an isolated independent service. An example is a CreditService bean that provides methods for making charges against different types of credit cards (MC, Visa, Discovery, etc).

public class CreditService implements javax.ejb.SessionBean {

public Charge charge (String accountToCredit, CreditCard card, double amount) throws ValidationException, RemoteException{ // attempt to obtain Merchant bean representing the retailer making the charge. try{ MerchantHome mrchntHome = ... get VendorHome reference Merchant merchant = mrchntHome.findByPrimaryKey(vendorToCredit); }catch(ObjectNotFoundException onfe){ throw new ValidationException("Invalid merchant account number"); }

// attempt to create a Charge bean based on the vendor, amount, and credit card info try{ ChargeHome chgHome = ... get ChargeHome reference Charge charge = chgHome.create(merchant, card, amount); return charge; }catch(CreateException ce){ throw new ValidationException(ce.getMessage());

Page 13 of 112

Page 14: J2EE Questions

} }...}In the above example the CreditService bean method charge( ) is completely independent of the bean state or any other methods. The charge( ) method is a stateless service and the CreditService bean is a stateless bean. The charge( ) method uses two other bean types to process the charge. Its normal for stateless beans to use other beans but they can also access the database directly or even other resources like proprietary connections. Below is a list the beans used in this example. Bean NameBean TypeCreditServiceStateless SessionMerchantEntityChargeEntity

EJB interview questions1. Is is possible for an EJB client to marshal an object of class java.lang.Class to an EJB? - Technically yes, spec. compliant NO! - The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language. 2. Is it legal to have static initializer blocks in EJB? - Although technically it is legal, static initializer blocks are used to execute some piece of code before executing any constructor or method while instantiating a class. Static initializer blocks are also typically used to initialize static fields - which may be illegal in EJB if they are read/write - In EJB this can be achieved by including the code in either the ejbCreate(), setSessionContext() or setEntityContext() methods. 3. Is it possible to stop the execution of a method before completion in a SessionBean? - Stopping the execution of a method inside a Session Bean is not possible without writing code inside the Session Bean. This is because you are not allowed to access Threads inside an EJB. 4. What is the default transaction attribute for an EJB? - There is no default transaction attribute for an EJB. Section 11.5 of EJB v1.1 spec says that the deployer must specify a value for the transaction attribute for those methods having container managed transaction. In WebLogic, the default transaction attribute for EJB is SUPPORTS. 5. What is the difference between session and entity beans? When should I use one or the other? - An entity bean represents persistent global data from the database; a session bean represents transient user-specific data that will die when the user disconnects (ends his session). Generally, the session beans implement business methods (e.g. Bank.transferFunds) that call entity beans (e.g. Account.deposit, Account.withdraw)

Page 14 of 112

Page 15: J2EE Questions

6. Is there any default cache management system with Entity beans ? In other words whether a cache of the data in database will be maintained in EJB ? - Caching data from a database inside the Application Server are what Entity EJB's are used for.The ejbLoad() and ejbStore() methods are used to synchronize the Entity Bean state with the persistent storage(database). Transactions also play an important role in this scenario. If data is removed from the database, via an external application - your Entity Bean can still be "alive" the EJB container. When the transaction commits, ejbStore() is called and the row will not be found, and the transaction rolled back. 7. Why is ejbFindByPrimaryKey mandatory? - An Entity Bean represents persistent data that is stored outside of the EJB Container/Server. The ejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the container, similar to a SELECT statement in SQL. By making this method mandatory, the client programmer can be assured that if they have the primary key of the Entity Bean, then they can retrieve the bean without having to create a new bean each time - which would mean creating duplications of persistent data and break the integrity of EJB. 8. Why do we have a remove method in both EJBHome and EJBObject? - With the EJBHome version of the remove, you are able to delete an entity bean without first instantiating it (you can provide a PrimaryKey object as a parameter to the remove method). The home version only works for entity beans. On the other hand, the Remote interface version works on an entity bean that you have already instantiated. In addition, the remote version also works on session beans (stateless and stateful) to inform the container of your loss of interest in this bean. 9. How can I call one EJB from inside of another EJB? - EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth. 10. What is the difference between a Server, a Container, and a Connector? - An EJB server is an application, usually a product such as BEA WebLogic, that provides (or should provide) for concurrent client connections and manages system resources such as threads, processes, memory, database connections, network connections, etc. An EJB container runs inside (or within) an EJB server, and provides deployed EJB beans with transaction and security management, etc. The EJB container insulates an EJB bean from the specifics of an underlying EJB server by providing a simple, standard API between the EJB bean and its container. A Connector provides the ability for any Enterprise Information System (EIS) to plug into any EJB server which supports the Connector architecture. See Sun's J2EE Connectors for more in-depth information on Connectors. 11. How is persistence implemented in enterprise beans? - Persistence in EJB is taken care of in two ways, depending on how you implement your beans: container managed persistence (CMP) or bean managed persistence (BMP) For CMP, the EJB container which your beans run under takes care of the persistence of the fields you have declared to be persisted with the database - this declaration is in the deployment descriptor. So, anytime you modify a field in a CMP bean, as soon as the method you have executed is finished, the new data is persisted to the database by the container. For BMP, the EJB bean developer is responsible for defining the persistence routines in the proper places in the bean, for instance, the ejbCreate(), ejbStore(), ejbRemove() methods would be developed by the bean developer to make calls to the database. The container is responsible, in BMP, to call the appropriate method on the bean. So, if the bean is being

Page 15 of 112

Page 16: J2EE Questions

looked up, when the create() method is called on the Home interface, then the container is responsible for calling the ejbCreate() method in the bean, which should have functionality inside for going to the database and looking up the data. 12. What is an EJB Context? - EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details. 13. Is method overloading allowed in EJB? - Yes you can overload methods 14. Should synchronization primitives be used on bean methods? - No. The EJB specification specifically states that the enterprise bean is not allowed to use thread primitives. The container is responsible for managing concurrent access to beans at runtime. 15. Are we allowed to change the transaction isolation property in middle of a transaction? - No. You cannot change the transaction isolation level in the middle of transaction. 16. For Entity Beans, What happens to an instance field not mapped to any persistent storage, when the bean is passivated? - The specification infers that the container never serializes an instance of an Entity bean (unlike stateful session beans). Thus passivation simply involves moving the bean from the "ready" to the "pooled" bin. So what happens to the contents of an instance variable is controlled by the programmer. Remember that when an entity bean is passivated the instance gets logically disassociated from it's remote object. Be careful here, as the functionality of passivation/activation for Stateless Session, Stateful Session and Entity beans is completely different. For entity beans the ejbPassivate method notifies the entity bean that it is being disassociated with a particular entity prior to reuse or for dereference. 17. What is a Message Driven Bean, what functions does a message driven bean have and how do they work in collaboration with JMS? - Message driven beans are the latest addition to the family of component bean types defined by the EJB specification. The original bean types include session beans, which contain business logic and maintain a state associated with client sessions, and entity beans, which map objects to persistent data. Message driven beans will provide asynchrony to EJB based applications by acting as JMS message consumers. A message bean is associated with a JMS topic or queue and receives JMS messages sent by EJB clients or other beans. Unlike entity beans and session beans, message beans do not have home or remote interfaces. Instead, message driven beans are instantiated by the container as required. Like stateless session beans, message beans maintain no client-specific state, allowing the container to optimally manage a pool of message-bean instances. Clients send JMS messages to message beans in exactly the same manner as they would send messages to any other JMS destination. This similarity is a fundamental design goal of the JMS capabilities of the new specification. To receive JMS messages, message driven beans implement the javax.jms.MessageListener interface, which defines a single "onMessage()" method. When a message arrives, the container ensures that a message bean corresponding to the message topic/queue exists (instantiating it if necessary), and calls its onMessage method passing the client's message as the single argument. The message bean's

Page 16 of 112

Page 17: J2EE Questions

implementation of this method contains the business logic required to process the message. Note that session beans and entity beans are not allowed to function as message beans. 18. Does RMI-IIOP support code downloading for Java objects sent by value across an IIOP connection in the same way as RMI does across a JRMP connection? - Yes. The JDK 1.2 support the dynamic class loading. 19. The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes? - The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate instance for each client request. The instance pool maintainence is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is again up to the implementer. 20. What is the advantage of putting an Entity Bean instance from the "Ready State" to "Pooled state"? - The idea of the "Pooled State" is to allow a container to maintain a pool of entity beans that has been created, but has not been yet "synchronized" or assigned to an EJBObject. This mean that the instances do represent entity beans, but they can be used only for serving Home methods (create or findBy), since those methods do not relay on the specific values of the bean. All these instances are, in fact, exactly the same, so, they do not have meaningful state. Jon Thorarinsson has also added: It can be looked at it this way: If no client is using an entity bean of a particular type there is no need for cachig it (the data is persisted in the database). Therefore, in such cases, the container will, after some time, move the entity bean from the "Ready State" to the "Pooled state" to save memory. Then, to save additional memory, the container may begin moving entity beans from the "Pooled State" to the "Does Not Exist State", because even though the bean's cache has been cleared, the bean still takes up some memory just being in the "Pooled State". 21. Can a Session Bean be defined without ejbCreate() method? - The ejbCreate() methods is part of the bean's lifecycle, so, the compiler will not return an error because there is no ejbCreate() method. However, the J2EE spec is explicit: the home interface of a Stateless Session Bean must have a single create() method with no arguments, while the session bean class must contain exactly one ejbCreate() method, also without arguments. Stateful Session Beans can have arguments (more than one create method) stateful beans can contain multiple ejbCreate() as long as they match with the home interface definition. You need a reference to your EJBObject to startwith. For that Sun insists on putting a method for creating that reference (create method in the home interface). The EJBObject does matter here. Not the actual bean. 22. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB? - You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be consider as "passed-by-value", that means that it's read-only in the EJB. If anything is altered from inside the EJB, it won't be reflected back to the HttpSession of the Servlet Container.The "pass-by-reference" can be used between EJBs

Page 17 of 112

Page 18: J2EE Questions

Remote Interfaces, as they are remote references. While it IS possible to pass an HttpSession as a parameter to an EJB object, it is considered to be "bad practice (1)" in terms of object oriented design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejb's api. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction will be flexible enough to support it. (1) Core J2EE design patterns (2001) 23. Is there any way to read values from an entity bean without locking it for the rest of the transaction (e.g. read-only transactions)? We have a key-value map bean which deadlocks during some concurrent reads. Isolation levels seem to affect the database only, and we need to work within a transaction. - The only thing that comes to (my) mind is that you could write a 'group accessor' - a method that returns a single object containing all of your entity bean's attributes (or all interesting attributes). This method could then be placed in a 'Requires New' transaction. This way, the current transaction would be suspended for the duration of the call to the entity bean and the entity bean's fetch/operate/commit cycle will be in a separate transaction and any locks should be released immediately. Depending on the granularity of what you need to pull out of the map, the group accessor might be overkill. 24. What is the difference between a "Coarse Grained" Entity Bean and a "Fine Grained" Entity Bean? - A 'fine grained' entity bean is pretty much directly mapped to one relational table, in third normal form. A 'coarse grained' entity bean is larger and more complex, either because its attributes include values or lists from other tables, or because it 'owns' one or more sets of dependent objects. Note that the coarse grained bean might be mapped to a single table or flat file, but that single table is going to be pretty ugly, with data copied from other tables, repeated field groups, columns that are dependent on non-key fields, etc. Fine grained entities are generally considered a liability in large systems because they will tend to increase the load on several of the EJB server's subsystems (there will be more objects exported through the distribution layer, more objects participating in transactions, more skeletons in memory, more EJB Objects in memory, etc.) What is EJBDoclet? - EJBDoclet is an open source JavaDoc doclet that generates a lot of the EJB related source files from custom JavaDoc comments tags embedded in the EJB source file.

Question How can I write EJBs that will run (unmodified) in any EJB-Container? What do I have to pay attention to? Derived from An unanswered question originally posed by Alek Opitz Topics Java:API:EJB

Answer EJB containers are provided by App servers like Weblogic, Websphere etc. EJB specification does not assure any interoperability between different App servers , in turn between containers generated by app servers.

Page 18 of 112

Page 19: J2EE Questions

When writing EJBs, do not use any vendor specific packages. Stick to javax packages (as per EJB spects). If you observe this rule, your EJB s should run on any App server.

Also, check EJB 2.0 spects. They define minimum interoperability standards between app servers using RMI - IIOP. But I did not find whether it's mandatory for the vendors or not. I am waiting for the final EJB 2.0 spec to be released.

2000-07-14 14:36:53.147 I'm not sure why the answer to this question dwells on interoperability, as my reading of the question is purely portability. At any rate: other things to be carefull of for portability: With CMP entity beans, be careful of how you map SQL types to Java types: WebLogic, at least, is pretty touchy here. If you're lucky enough to be using a container whose CMP can handle dependant ('value') objects, don't use that feature - it's not at all portable in EJB 1.1 (2.0 is much better, but much different) As the above points imply, BMP might tend to be much more portable. Make sure that you do datasource lookups by the spec, though, and you might want to think about making the datasource JNDI name (the whole shot: "java:/comp/env/jdbc/DataSourceName") an environment entry (I've run into bugs where containers weren't putting datasources in the spec-ordained "java:/comp/env/jdbc" namespace Make sure you use the ejb-reference deployment descriptor stuff, don't use a client-style lookup from an EJB Stick with the spec, even if you're using a server that allows more fredom. Don't use threads, don't read the filesystem directly, etc. (Some containers will let you get away with some of these) I've got some CMP beans that will run in Weblogic and IAS, getting there was a bit of an adventure. Question When (manually) deploying an EJB where do you specify the JNDI name that the bean is bound to in the JNDI tree? Derived from An unanswered question originally posed by Henrik Buch Topics Java:API:EJB, Java:API:JNDI, Java:API:EJB:Deployment Descriptor

Answer [Questioner continues: According to the EJB1.1 spec there is no relation between the <ejb-name> tag in the deployment descriptor (or assembly descriptor) and the JNDI name. I can see that a client can use a "logical" name that can be mapped via vendor specific deployment info (e.g. orion-application-client.xml).] When you are deploying the application in using Web Logic 4.5.1 server, in the deployment wizard you can specify the JNDI name and using the same name you can look up from the client.

[Is there any standard way to do it? If not, can someone give feedback with info for other servers? -Alex]

Feedback and Comments kishore_k_v k

Page 19 of 112

Page 20: J2EE Questions

2000-09-11 00:11:41.227 In Weblogic5.1,the deployer has a provision for u to specify the jndi-name. however i think using the build batch file is more standard--you can specify the jndi name in the weblogic-ejb-jar.xml file (a template comes along with the server). Anil Datt 2000-10-11 08:26:49.636 The JNDI name is specified within the tags <jndi-name></jndi-name>

in the namespace <weblogic-enterprise-bean> for weblogic server 5.x. This is specified in the weblogic-ejb-jar.xml file Question What's so special about Enterprise JavaBeans? Topics Java:API:EJB

Answer Enterprise JavaBeans simplifies the task of developing distributed objects systems. It's easier for developers to create transactional distributed object applications with EJB than with any other Java based component architecture. With Enterprise JavaBeans, transactions, security, and persistence can be handled automatically allowing developer to focus on the business logic. Enterprise JavaBeans has been adopted by most distributed object vendors and is considered a standard for developing distributed object systems in Java. All EJB vendors must implement the same EJB specification which guarantees a consistent programming model across servers. In addition, because EJB is widely supported by many vendors, corporations do not have to worry about vendor lock-in; enterprise beans will run in any EJB compliant server.

Feedback and Comments Jonathan Rasmusson 1999-12-02 09:16:05.199 I must take exception to the comment made: 'In addition, because EJB is widely supported by many vendors, corporations do not have to worry about vendor lock-in; enterprise beans will run in any EJB compliant server.' This simple is not true (today). I have been performing EJB compatiblity tests between SynerJ (Suns application server purchased recently in the Forte merger) and WebLogic. Because of differences in deployment descriptor implementations, looseness and changes in the EJB spec, you simply can not move an EJB from one app server to another. Even the implementation of the EJB API itself may very from vendor to vendor (as was the case with SynerJ and WebLogic - they both have different method signatures for the ejbRemove() method of entity bean. As you probably know, Sun has taken steps to tighten up the spec, to ensure vendors implement more compatible EJB containers. Hopefully this time next year, after a few more iterations of the spec, we will be able to move EJBs from one app server to another. You probably already know all this already and I may have taken your FAQ out of context. I am just saying people should be aware that due to the imaturity of the spec, EJBs simply are not portable between the 40 odd vendors out there. Note: I am a big fan of this site and think you are all doing an excellent job. Keep up the great work. Yours truly, Jonathan Rasmusson

Page 20 of 112

Page 21: J2EE Questions

Subramaniam Kumar 2000-01-22 09:26:58.269 I agree with Jonathan and I still see EJB in specification mode. For enterprises like mine it is mandatory that we use mature Products not an evolving (probably diverging specifications). If EJB is not ready yet what is the alternative the Java camp provides for Enterprise level distributed object computing. Feedback

Q4Question Is there any performance problem with calling one EJB from another EJB running in the same container? Derived from An unanswered question originally posed by gurdeep singh Topics Java:API:EJB

Answer There are two potential performance issues here, one of which has been eliminated by most (if not all) container vendors, and the other of which many container vendors have optional optimization for. The first issue is that given naive implementations of the JNDI context objects that the beans use to look each other up, the calls might go through RMI, which involves quite a bit of overhead even within a process. Again, though most if not all container vendors optimize this right out of your way. Don't worry about this one.

The second potential issue, though, comes from the spec. The EJB specification dictates that the container copy all method parameters and return values on these calls. Here is the quote from section 18.2.3: <quote> Specifically, the EJB Container is not allowed to pass non-remote objects by reference on inter-EJB invocations when the calling and called enterprise beans are collocated in the same JVM. Doing so could result in the multiple beans sharing the state of a Java object, which would break the enterprise bean's semantics. </quote> All this copying has obvious performance implications. However, most container vendors allow this behavior to be overridden for performance reasons.

Q5Question When should I use bean-managed transactions instead of specifying transaction information in the deployment descriptor? Derived from An unanswered question originally posed by hari narayandas Topics Java:API:EJB:Transactions

Answer

Hi Hari,

The Sun J2EE EJB Guide says like this:

Although beans with container-managed transactions require less coding, they have one limitation: When a method is executing, it can be associated with either a single transaction or no transaction at all. If this limitation will make coding your session bean difficult, you should consider using bean-managed transactions.

Page 21 of 112

Page 22: J2EE Questions

The following pseudo-code illustrates the kind of fine-grained control you can obtain with bean-managed transactions. By checking various conditions, the pseudo-code decides whether to start and stop different transactions within the business method.

begin transaction...update table-a...if (condition-x) commit transactionelse if (condition-y) update table-b commit transactionelse rollback transaction begin transaction update table-c commit transaction...

I think what it means is there are some limitations in j2ee transaction support. In a container managed situation, nested or multiple transactions are not allowed within a method. if a biz method needs those features you need to go for bean managed transactions.

Feedback and Comments Alex Chaffee 2000-04-17 10:43:04.116 Actually, BMT isn't about nested transactions. It just allows you finer control than the various transaction options provided by the container. If you tell it to in the DD, the container will suspend an existing transaction, create a new one, join on the an existing one, and so forth, automatically doing the right thing before and after your method. Bean-managed transactions just allow you to do the same sort of stuff, only with more control over the conditions under which that would happen. That is, you can do transaction stuff *inside* a method, rather than letting the method be the level of granularity. It turns out that nested transactions are not currently supported by Java TP implementations. Or has that changed?

Question My session beans call other bean methods within a transaction. Using bean-managed transactions, how should I take care of commit and rollback ? Derived from An unanswered question originally posed by Shalabh Nigam Topics Java:API:EJB:SessionBean, Distributed computing:Transactions, Java:API:EJB:Transactions

Answer There are two steps here:

Page 22 of 112

Page 23: J2EE Questions

1. Coding step:

public class exBean implements SessionBean { EJBContext ec; javax.transaction.UserTransaction utxn; . . . utxn = ec.getUserTransaction(); utxn.begin();

// do all your txn stuff // getting DB connections, updates, other bean methods, etc. . . utxn.commit();}

Note you have to begin a txn before opening dB connections and close connections before committing.

2. Deployment step:

- Your app server must support a JTS for distributed txns. Most do.

- Verify there is no conflict with the bean transaction properties in calling beans.

Feedback and Comments Shalabh Nigam 2000-07-03 15:12:21.415 Are there any issues if each of my bean methods uses a different DB Connection?

Q7Question Why use EJB when we can do the same thing with servlets? Derived from An unanswered question originally posed by sreenivasulu kadirimangalam Topics Java:API:EJB, Java:API:Servlets:Architecture and Design

Answer Actually, servlets/JSPs and EJB are complimentary, not competing technologies: Servlets provide support for writing web based applications whereas EJBs provide support for writing transactional objects. In larger web systems that require scalability, servlet and JSP or XML/XSL technologies provide support for the front end (UI, client) code, where EJB provides support for the back end (database connection pooling, declaritive transactions, declaritive security, standardized parameterization...)

Page 23 of 112

Page 24: J2EE Questions

The most significant difference between a web application using only servlets and one using servlets with EJBs is that the EJB model mandates a separation between display and business logic. This is generally considered a Good Thing in non-trivial applications because it allows for internal reuse, allows flexibility by providing a separation of concerns, gives a logical separation for work, and allows the business logic to be tested separately from the UI (among others).

Some of the hings that servlets and JSPs can do that EJBs cannot are:

Respond to http/https protocol requests. (With JSP) provide an easy way to format HTML output. Easily associate a web user with session information Some of the things that EJBs enable you to do that servlets/JSPs do not are:

Declaritively manage transactions. In EJB, you merely specify whether a bean's methods require, disallow, or can be used in the context of a transaction. The EJB container will manage your transaction boundaries appropriately. In a purely servlet architecture, you'll have to write code to manage the transaction, which is difficult if a logical transaction must access multiple datasources. Declaritively manage security. The EJB model allows you to indicate a security role that the user must be assigned to in order to invoke a method on a bean. In Servlets/JSPs you must write code to do this. Note, however that the security model in EJB is sufficient for only 90% to 95% of application code - there are always security scenarios that require reference to values of an entity, etc.

Q9Question Do I need to commit after an INSERT call in JDBC or does JDBC do it automatically in the DB? Topics Java:API:JDBC

Answer If your autoCommit flag (managed by the Connection.setAutoCommit method) is false, you are required to call the commit() method - and vice versa.

2000-05-29 06:35:08.31 When you open a connection to a database, the default JDBC behavior is to automatically commit each SQL statement after execution.

To change this behavior, and to execute multiple SQL statements as part of a transaction, you have to invoke the setAutoCommit(false) method on your Connection object. If auto commit is false, then SQL statements won't be committed until you invoke the commit() method on the connection. You also have the option of invoking the rollback() method, to rollback the database changes since the previous commit (or since the opening of the connection, if there was no previous commit).

If the underlying database doesn't support transactions, then all SQL statements will be committed after execution, regardless of whether you have set auto commit or not. See

Page 24 of 112

Page 25: J2EE Questions

your database vendor's documentation and your JDBC driver's documentation for detailed information about what features are supported in your specific case.

Q10Question What is a CMP bean? Topics Java:API:EJB:EntityBean:CMP

Answer CMP: Container-Managed Persistence A CMP bean is an entity bean whose state is synchronized with the database automatically. In other words, the bean developer doesn't need to write any explicit database calls into the bean code; the container will automatically synchronize the persistent fields with the database as dictated by the deployer at deployment time.

When a CMP bean is deployed, the deployer uses the EJB tools provided by the vendor to map the persistent fields in the bean to the database. The persistence fields will be a subset of the instance fields, called container-managed fields, as identified by the bean developer in the deployment descriptor.

In the case of a relational database, for example, each persistent field will be associated with a column in a table. A bean may map all its fields to one table or, in the case of more sophisticated EJB servers, to several tables. CMP are not limited to relational database. CMP beans can be mapped to object databases, files, and other data stores including legacy systems.

With CMP, the bean developer doesn't need to write any database access logic into the bean, but bean is notified by the container when its state is synchronized with the database. The container notifies the bean using the ejbLoad( ) and ejbStore( ) methods.

The ejbLoad( ) method alerts the bean that its container-managed fields have just been populated with data from the database. This gives the bean an opportunity to do any post processing before the data can be used by the business methods. The ejbStore( ) method alerts the bean that its data is about to be written to the database. This give the bean an opportunity to do any pre-processing to the fields before they are written to the database. The below bean code demonstrates how these method might be employed on a Customer CMP entity bean.

public class CustomerBean implements javax.ejb.EntityBean { // container-managed fields public long customerNumber; public String lastName; public String firstName;

// not a container-managed field

Page 25 of 112

Page 26: J2EE Questions

public PersonName name = null;

// business methods public PersonName getName( ){ return name; } public void setName(PersonName name){ name = name; } // called just after container-managed fields are updated from database public void ejbLoad( ){ name = PersonName(firstName, lastName); } // called just before container-managed fields are written to database public void ejbStore( ){ lastName = name.getLastName( ); firstName = name.getFirstName( ); }... }

In the case of the Customer bean the ejbLoad( ) and ejbStore( ) are used to wrapper the name fields (lastName and firstName) in a PersonName object which is more user friendly for the bean client. The ejbLoad( ) method wrappers the fields so that the getName( ) method access an up-to-date copy of the name data. The ejbStore( ) method unwraps the name data and places them back into the container-managed fields so that the database is updated with the most recent changes.

The ejbLoad( ) and ejbStore( ) methods are typically called just before a transaction begins and when a transaction is about to commit. This ensures that the container-managed fields are synchronized with the database when the bean is in use. Some EJB servers will optimize the container so that data is not written to the database unless its dirty; that container-managed fields have been changed.

CMP is the most difficult EJB feature for vendors to support. It requires very sophisticated tools for mapping bean fields to a data source and generating the underlying stubs and skeletons to support this mapping. CMP, however, provide a unique opporutnity for organizations developing distributed object systems. With CMP, a shrink-wrapped bean ( a bean developed by a third party) can be deployed and mapped into an organization's existing database. Obviously, this is an idyllic scenario, but not unreasonable. CMP entity beans exemplify the spirit of component technology; the reuse of components across projects, organizations, and industries.

Page 26 of 112

Page 27: J2EE Questions

Note: CMP beans use the ejbLoad( ) and ejbStore( ) callback methods differently than the Bean-Managed Persistence (BMP) beans. See Java:API:EJB:EntityBean:BMP for details on how BMP beans use these methods.

Q11Question How can I make batch updates using JDBC? Topics Java:API:JDBC:2.0

Answer One of the more advanced features of JDBC 2.0 is the ability to submit multiple update statements to the database for processing as a single unit. This batch updating can be significantly more efficient compared to JDBC 1.0, where each update statement has to be executed separately. Consider the following code segment demonstrating a batch update:

try {dbCon.setAutoCommit(false);

Statement stmt= dbCon.createStatement();stmt.addBatch("INSERT INTO bugs "+

"VALUES (1007, 'Server stack overflow', 1,2,{d '1999-01-01'})");stmt.addBatch("INSERT INTO bugs "+ "VALUES (1008,'Cannot load DLL', 3,1,{d '1999-01-01'})");stmt.addBatch("INSERT INTO bugs "+ "VALUES (1009,'Applet locks up',2,2,{d '1999-01-01'})");

int[] updCnt = stmt.executeBatch();dbCon.commit();

} catch (BatchUpdateException be) {

//handle batch update exceptionint[] counts = be.getUpdateCounts();for (int i=0; I counts.length; i++) {

System.out.println("Statement["+i+"] :"+counts[i]);}dbCon.rollback();

}catch (SQLException e) {

//handle SQL exceptiondbCon.rollback();

}

Page 27 of 112

Page 28: J2EE Questions

Before carrying out a batch update, it is important to disable the auto-commit mode by calling setAutoCommit(false). This way, you will be able to rollback the batch transaction in case one of the updates fail for any reason. When the Statement object is created, it is automatically associated a "command list", which is initially empty. We then add our SQL update statements to this command list, by making successive calls to the addBatch() method. On calling executeBatch(), the entire command list is sent over to the database, and are then executed in the order they were added to the list. If all the commands in the list are executed successfully, their corresponding update counts are returned as an array of integers. Please note that you always have to clear the existing batch by calling clearBatch() before creating a new one.

If any of the updates fail to execute within the database, a BatchUpdateException is thrown in response to it. In case there is a problem in returning the update counts of each SQL statement, a SQLException will be thrown to indicate the error.

Feedback and Comments Srinivas Gamini 2000-01-17 13:06:11.108 Hi, This is an interesting article. I would appreciate, if you could tell me which jdbc driver will support this feature. I tried this feature with Oracle database and 8.1.6 sdk driver but unfortunately it is giving errors like feature is not implemented... Thanks in advance. Gamini [email protected]

Q12Question Why are beans not allowed to create their own threads? Derived from An unanswered question originally posed by dan benanav Topics Java:API:EJB

Answer

Enterprise beans exist inside a container at run time. The container is responsible for managing every aspect of the enterprise bean's life including: transactions, access control, persistence, resource pooling, etc. In order for the container to manage the runtime environment of a bean, it must have complete control over the threads that access and run within a bean. This means that beans can not start or manage their own threads. Containers deny enterprise beans the privilege to manage threads for three basic reasons: Resource management, security, and thread-sensitive storage.

Resource ManagementContainers manage every aspect of the runtime environment used by enterprise beans including transactions, access control, life cycle, resource connections, VM security, class loading, and threads. This allows the container to conserve as many resources as possible, which is important when there are hundreds of enterprise beans servicing thousands of clients. Without strict management of resources like memory and threads, EJB systems might consume to many resources (memory and cycles), which would result in a slow system, a prospect that is untenable in a high-transaction environment. Threads started and managed by enterprise beans would not be managed by the container, which would make it difficult to conserve resources.

Page 28 of 112

Page 29: J2EE Questions

SecurityThere is no way for a container system to know in advance that a bean's use of threads is benign. While intentions may be sincere it is possible -- probably inevitable -- that developers would create malignant beans that spawn so many threads that the entire system slows down. One bean instance's misuse of threads or the commutative effect of many instances could cause a system slowdown. This is an insurgent denial of service, where the beans themselves sabotage a system's ability to respond to client requests. Security is a very good reason for denying bean's the privilege of starting and managing their own threads.

Thread-Specific Storage Thread-Specific Storage (TSS) is an established and common technique employed by vendors to propagate and track client requests through the container system. It involves associating data with a thread. The data may be information about the client's identity, the transaction context, and other information, which can be accessed by any part of the container without having to pass the data explicitly. This is especially useful when enterprise beans invoke other enterprise beans or access resources, because it provides a convenient and transparent mechanism for transferring information about the who is making the request and under what circumstances. Each vendor will use the TSS technique differently according to the mechanics of their server. Threads started and managed by the enterprise bean explicitly would not have the proper TSS -- that would require intimate knowledge and access to the vendors container system. Without the right TSS the enterprise bean's threads can not operate within the container system properly. This is another reason why bean are not allowed to start and manage their own threads, it would short-circuit the vendor's use of TSS.

Related FAQs:

Can I use Threads in an enterprise bean? What is a container?

Feedback and Comments Richard Monson-Haefel 2000-02-28 05:23:15.425 The following is a quote from Mark Hapner, Sun's lead enteprise Java architect. "Although conflict with the container is one of the reasons why EJBs are not allowed to create threads, there is a more important reason.

A major objective of EJB is to achieve the creation of a multi-user service by implementing single threaded components. Writing robust, multi-threaded code is hard and eliminating the [requirement] that this skill to be mastered in order to implement a middle-tier service is one of the main benefits of EJB.

The goal is to delegate all responsibility for managing concurrency to a container and its resources (DBMSs, etc). EJB 1.1 succeeds in doing this for many types of applications.

Page 29 of 112

Page 30: J2EE Questions

EJB 2.0 will significantly expand the EJB app domain by adding support for asynchronous invocation (JMS integration).

So, the question is not what you can do within your container it is what your container can do for you :>). Why should you be worrying about creating threads if you can get the container to handle all of that complexity?"

-- Mark Hapner, EJB-INTEREST mailing list post "Re: Threads question (Concrete examples?)"

Sathish Srinivasan 2000-05-09 03:52:10.559 I had a requirement of asynchronous method invocation. What should I do with EJB1.1 Container( apart from waiting for my particular EJB2.0 complaint app server )? I knew I could create a queue and write another bean/ process to do the job.But for my scenario, I thought, it is too much overhead.

I went ahead with Threads. Any thoughts on how I should have proceeded.?

Q13Question What is a stateful session bean? Topics Java:API:EJB:SessionBean:Stateful Author Richard Monson-Haefel Created 12-Nov-99 Answer A stateful session bean is an enterprise bean (EJB component) that acts as a server-side extension of the client that uses it. The stateful session bean is created by a client and will work for only that client until the client connection is dropped or the bean is explicitly removed. The stateful session bean is EJB component that implements the javax.ejb.SessionBean interface and is deployed with the declarative attribute "stateful". Stateful session beans are called "stateful" because they maintain a conversational state with the client. In other words, they have state or instance fields that can be initialized and changed by the client with each method invocation. The bean can use the conversational state as it process business methods invoked by the client.

Stateful session beans are usually developed to act as agents for the client, managing the interaction of other beans and performing work on behalf of the client application. An example is a shopping cart stateful session bean that tracks a client's product choices and can execute a sale when requested. Below is partial example of a stateful session bean that is used as a shopping cart.

public class ShoppingCartBean implements javax.ejb.SessionBean {

Page 30 of 112

Page 31: J2EE Questions

// instance fields; The conversational state Vector products = new Vector( ); Customer customer; // initializes bean with reference to customer bean public void ejbCreate(Customer cust){ customer cust; }

//add a product to shopping cart public void addItem(Product item) { products.addElement(item); }

//charge customer for products and create a shipping order public void executeSale(){

// get the customer's credit card object CreditCard card = customer.getCreditCard( );

// calculate a total price from products chosen double total; for(int i = 0; i products.size(); i++){ Product product = (Product)products.elementAt(i); total += product.getPrice( ); }

// get reference to the CreditService bean and process the customers charge CreditService cardSwipper = ... get credit card service bean Charge charge = cardSwipper.charge(CreditCard, total);

// get reference to the OrderHome and create a new shipping order bean (record) OrderHome orderHome = ... get the Order beans Home object Order order = orderHome.create(customer, products, charge); }...}

In the example above the ShoppingCartBean keeps track of the Customer and the items chosen by the client application. This is the bean's conversational state. Once the client application is ready to execute a sale, the ShoppingCartBean manages the interactions of the Customer, Product, CreditServer, and Order beans in a workflow that results in a charge against the customers credit card and the creation of a shipping order. The

Page 31 of 112

Page 32: J2EE Questions

ShoppingCartBean behaves as an agent for the client managing the interaction of these other beans, tracking chosen items, and executing the sale. The below table identifies the beans types used in the ShoppingCartBean example above. Bean Name Bean Type ShoppingCartBean Stateful Session CreditService Stateless Session Customer Entity Product Entity Order Entity

From the clients perspective only the Customer and ShoppingCart beans are visible, because the client application works with the bean's remote interface while the bean itself resides on the server. This means that the client need only be concerned with the business methods made public by the ShoppingCartBean. Below is an example of the client applications view of the ShoppingCartBean. (Note: The client interacts with the beans remote interface not the bean itself. The remote interface is called the ShoppingCart.)

// somewhere in the client application (applet, servlet, etc.)

// obtain the home objects (factories) for the Customer and ShoppingCart beansCustomerHome custHm = ... get CustomerHomeShoppingCartHome shpCrtHm = ... get ShoppingCartHome

// locate the bean representing the customer named, Bob JohnstenCustomer customer = custHome.findByName("Bob","Johnsten");

// create a new ShoppingCart initialized with the Bob Johnsten Customer beanShoppingCart shoppingCart = shpCrtHm.create(customer); ...Product product = ... get reference to bean representing the product chosen// add product to customer's shopping cartshoppingCart.addItem(product);...//charge customer for products and create a shipping ordershoppingCart.executeSale( );

Session beans like the shoppingCartBean only live as long as the client maintains a connection. In other words, they represent some aspect of the client's current session with the system and die when the client ends that session. Session beans are generally not fault tolerant. A system failure or shut down will result in the death of session bean and a loss of any conversation state it maintained prior to the failure. (This is a conceptual lifecycle of a session bean. Some vendors can make them more fault tolerant and longer lasting).

Page 32 of 112

Page 33: J2EE Questions

Q14Question What is a stateless session bean? Topics Java:API:EJB:SessionBean:Stateless

Answer A stateless session bean is an enterprise bean (EJB component) that provides a stateless service to the client. Conceptually, the business methods on a stateless session bean are similar to procedural applications or static methods; there is no instance state, so all the data needed to execute the method is provided by the method arguments. The stateless session bean is an EJB component that implements the javax.ejb.SessionBean interface and is deployed with the declarative attribute "stateless". Stateless session beans are called "stateless" because they do not maintain conversational state specific to a client session. In other words, the instance fields in a stateless session bean do not maintain data relative to a client session. This makes stateless session beans very lightweight and fast, but also limits their behavior.

Stateless session beans are usually developed as a set of related and simple services. Think of a session bean as a functional API where each business method represents an isolated independent service. An example is a CreditService bean that provides methods for making charges against different types of credit cards (MC, Visa, Discovery, etc).

public class CreditService implements javax.ejb.SessionBean {

public Charge charge (String accountToCredit, CreditCard card, double amount) throws ValidationException, RemoteException{ // attempt to obtain Merchant bean representing the retailer making the charge. try{ MerchantHome mrchntHome = ... get VendorHome reference Merchant merchant = mrchntHome.findByPrimaryKey(vendorToCredit); }catch(ObjectNotFoundException onfe){ throw new ValidationException("Invalid merchant account number"); }

// attempt to create a Charge bean based on the vendor, amount, and credit card info try{ ChargeHome chgHome = ... get ChargeHome reference Charge charge = chgHome.create(merchant, card, amount); return charge; }catch(CreateException ce){ throw new ValidationException(ce.getMessage()); } }...}

Page 33 of 112

Page 34: J2EE Questions

In the above example the CreditService bean method charge( ) is completely independent of the bean state or any other methods. The charge( ) method is a stateless service and the CreditService bean is a stateless bean. The charge( ) method uses two other bean types to process the charge. Its normal for stateless beans to use other beans but they can also access the database directly or even other resources like proprietary connections. Below is a list the beans used in this example.

Bean Name Bean Type CreditService Stateless Session Merchant Entity Charge Entity

An example of how the CreditService bean could be used by a client application or bean is shown in the FAQ entry Java:API:EJB:SessionBean:Stateful:What is a stateful session bean?

Feedback and Comments Shibu TN 2000-02-26 12:37:29.11 What happens if remove( ) is never invoked on a session

Q14Question Why would a session bean use bean-managed transactions? Topics Java:API:EJB:SessionBean:Stateful, Distributed computing:Transactions

Answer

In some situations, it's necessary for a (stateful) session bean to selectively control which methods participate in transactions, and then take over the bundling of operations that form a logical unit of work.

J2EE interview questionsThanks to Sachin Rastogi for contributing these.1. What makes J2EE suitable for distributed multitiered Applications?- The J2EE platform uses a multitiered distributed application model. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. The J2EE application parts are: o Client-tier components run on the client machine. o Web-tier components run on the J2EE server. o Business-tier components run on the J2EE server. o Enterprise information system (EIS)-tier software runs on the EIS server. 2. What is J2EE? - J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications. 3. What are the components of J2EE application?

Page 34 of 112

Page 35: J2EE Questions

- A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components: 1. Application clients and applets are client components. 2. Java Servlet and JavaServer Pages technology components are web components. 3. Enterprise JavaBeans components (enterprise beans) are business components. 4. Resource adapter components provided by EIS and tool vendors. 4. What do Enterprise JavaBeans components contain? - Enterprise JavaBeans components contains Business code, which is logicthat solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program. 5. Is J2EE application only a web-based? - No, It depends on type of application that client wants. A J2EE application can be web-based or non-web-based. if an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a servlet running in the web tier. 6. Are JavaBeans J2EE components? - No. JavaBeans components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture. 7. Is HTML page a web component? - No. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either. 8. What can be considered as a web component? - J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content. 9. What is the container? - Containers are the interface between a component and the low-level platform specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container. 10. What are container services? - A container is a runtime support of a system-level entity. Containers provide components with services such as lifecycle management, security, deployment, and threading.

Page 35 of 112

Page 36: J2EE Questions

11. What is the web container? - Servlet and JSP containers are collectively referred to as Web containers. It manages the execution of JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE server. 12. What is Enterprise JavaBeans (EJB) container? - It manages the execution of enterprise beans for J2EE applications.Enterprise beans and their container run on the J2EE server. 13. What is Applet container? - IManages the execution of applets. Consists of a Web browser and Java Plugin running on the client together. 14. How do we package J2EE components? - J2EE components are packaged separately and bundled into a J2EE application for deployment. Each component, its related files such as GIF and HTML files or server-side utility classes, and a deployment descriptor are assembled into a module and added to the J2EE application. A J2EE application is composed of one or more enterprise bean,Web, or application client component modules. The final enterprise solution can use one J2EE application or be made up of two or more J2EE applications, depending on design requirements. A J2EE application and each of its modules has its own deployment descriptor. A deployment descriptor is an XML document with an .xml extension that describes a component's deployment settings. 15. What is a thin client? - A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications. 16. What are types of J2EE clients? - Following are the types of J2EE clients: o Applets o Application clients o Java Web Start-enabled rich clients, powered by Java Web Start technology. o Wireless clients, based on Mobile Information Device Profile (MIDP) technology. 17. What is deployment descriptor? - A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a component's deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizationsfor an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly. 18. What is the EAR file? - An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file. 19. What is JTA and JTS? - JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesn't call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your application uses to control transaction. and JTS is a low level transaction interface and ejb uses behind the scenes (client code doesn't directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA.

Page 36 of 112

Page 37: J2EE Questions

20. What is JAXP? - JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations. 21. What is J2EE Connector? - The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource adapter. Note: A resource adapter is a software component that allows J2EE application components to access and interact with the underlying resource manager. Because a resource adapter is specific to its resource manager, there is typically a different resource adapter for each type of database or enterprise information system. 22. What is JAAP? - The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization. 23. What is Java Naming and Directory Service? - The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming anddirectory services such as LDAP, NDS, DNS, and NIS. 24. What is Struts? - A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between. 25. How is the MVC design pattern used in Struts framework? - In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an application's business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans. Jakarta struts questionsA reader sent it a set of Jakarta Struts questions used at his company.1. What is Jakarta Struts Framework? - Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of

Page 37 of 112

Page 38: J2EE Questions

any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java. 2. What is ActionServlet? - The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests. 3. How you will make available any Message Resources Definitions file to the Struts Framework Environment? - Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through <message-resources /> tag.Example:<message-resources parameter="MessageResources" /> 4. What is Action Class? - The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object. 5. Write code of any Action Class? - Here is the code of Action Class that returns the ActionForward object. 6. import javax.servlet.http.HttpServletRequest;7. import javax.servlet.http.HttpServletResponse;8. import org.apache.struts.action.Action;9. import org.apache.struts.action.ActionForm;10. import org.apache.struts.action.ActionForward;11. import org.apache.struts.action.ActionMapping;12. 13. public class TestAction extends Action14. {15. public ActionForward execute(16. ActionMapping mapping,17. ActionForm form,18. HttpServletRequest request,19. HttpServletResponse response) throws Exception20. {21. return mapping.findForward(\"testAction\");22. }23. }24. What is ActionForm? - An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web

Page 38 of 112

Page 39: J2EE Questions

application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side. 25. What is Struts Validator Framework? - Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings. 26. Give the Details of XML files used in Validator Framework? - The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean. 27. How you will display validation fail errors on jsp page? - The following tag displays all the errors:<html:errors/> 28. How you will enable front-end validation based on the xml in validation.xml? - The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code: <html:javascript formName="logonForm" dynamicJavascript="true" staticJavascript="true" /> generates the client side java script for the form "logonForm" as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script. Question : Which of the following are invalid states in the life of a Stateful Session Bean? A Does Not ExistB Method Ready PoolC Method Ready in TransactionD Method ReadyE ReadyF PooledG Passive Answer : Choices B, E and F are correct. The valid life cycle states of a Stateful Session Bean are 'Does Not Exist', 'Method Ready', 'Method Ready in Transaction' and 'Passive'. 'Method Ready Pool' is a life cycle state of

Page 39 of 112

Page 40: J2EE Questions

Stateless Session Beans. 'Pooled' and 'Ready' are life cycle states of Entity Beans. Hence choices B, E and F are correct. Question : What is the sequence of steps in the life cycle of a Stateless Session Bean? A class.newInstance(), setSessionContext (ctx), ejbCreate()B ejbCreate(), setSessionContext (ctx), class.newInstance()C class.newInstance(), ejbCreate(), setSessionContext (ctx)D setSessionContext (ctx), ejbCreate(), class.newInstance() Answer : Choice A is correct. When Stateless Session Beans transition from 'Does Not Exist' to 'Method Ready Pool', the container invokes newInstance(), setSessionContext() and ejbCreate() methods. Hence choice A is correct.Although choices B, C and D have the same methods, the order in which they appear to be called is wrong. Therefore choices B, C and D are incorrect.

Question : HTTPS is defined as A HTTP with SecurityB HTTP on secure lineC HTTP over SSLD HTTP with SSL Answer : Choice C is correct HTTPS stands for HTTP over SSL. With HTTPS, SSL sits above the TCP-IP layer and below the application protocol layer. Hence choice C is correct.Question : HTTP is A Connection LessB Connection BaseC StatefulD Stateless

Page 40 of 112

Page 41: J2EE Questions

E Secure Answer : Choice B and D are correct. HTTP (HyperText Transfer Protocol) is a transport mechanism for MIME (Multipurpose Internet Mail Extensions) documents. MIME documents often contain HTML (HyperText Markup Language) code for display in browser windows. HTTP consists of a request sent by the client to the server, followed by a response sent from the server back to the client. HTTP uses TCP/IP as the underlying transport and network protocols. The following is taken from:http://www.w3.org/Protocols/Activity.html "Whenever a client accesses a document, an image, a sound bite etc. HTTP/1.0 creates a new TCP connection and as soon as it is done, it is immediately dismissed and never reused." "HTTP/1.1 fixes this in two ways. First, it allows the client to reuse the same TCP connection (persistent connections) again and again when talking to the same server. Second, it makes sure that the courier carries as much information as possible (pipelining) so that it doesn't have to run back and forth as much. That is, not only does HTTP/1.1 use less TCP connections, it also makes sure that they are better used. The result is less traffic jam and faster delivery."The following is taken from:http://www.w3.org/Protocols/HTTP/HTTP2.html"HTTP is a protocol with the lightness and speed necessary for a distributed collaborative hypermedia information system. It is a generic stateless object-oriented protocol, which may be used for many similar tasks such as name servers, and distributed object-oriented systems, by extending the commands, or 'methods', used."Hence choices B and D are correct. Since choices A and C are the opposite, they are incorrect.HTTP can be made secure by using 'HTTP over SSL' or HTTPS. But by itself, HTTP is not secure. Hence choice E is incorrect. Question : Asynchronous communication is achieved by using: A Remote Procedure CallsB RMI/IIOPC Message Oriented MiddlewareD CORBA Answer :

Page 41 of 112

Page 42: J2EE Questions

Choice C is correct.

Message Oriented Middleware or MOM is used for asynchronous messaging between applications. Most popular implementations support Point to Point (one to one) and Publish Subscribe (one to many) messaging. Hence choice C is correct.Remote Procedure Calls are used for synchronous communication between applications. CORBA and RMI/IIOP are two protocols that support RPC based communication. Hence choices A, B and D are incorrect. Question : Which of the following is not part of the Messaging architecture: A Decentralized messaging using IP MulticastingB Decentralized messaging using Secure Sockets Layer (SSL)C Use of virtual channels called QueuesD Use of virtual channels called Topics Answer : Choice B is correct. Only choice B is not a standard paradigm in messaging architecture. Hence choice B is correct.IP Multicasting can be used as a technique for decentralized messaging. Queues and Topics are used with Point to Point and Publish Subscribe messaging. Hence choices A, C and D are incorrect. Question : In P2P, clients send messages to: A A designated queueB Multiple QueuesC A specific node for redistribution to subscribersD CORBA compliant ORB Answer : Choice A is correct. P2P or Point to Point messaging is used for one to one communication between two components or applications. In the P2P model, message producers send messages to a designated queue. Hence choice A is correct.

Page 42 of 112

Page 43: J2EE Questions

Although it is possible to mimic Publish Subscribe architecture by sending P2P messages to multiple queues, it is not a standard practice. Hence choice B is incorrect.In Publish Subscribe architecture, messages are sent to a specific node for redistribution to subscribers. Hence choice C is incorrect.CORBA is an RPC protocol and is not used for asynchronous messaging. Hence choice D is incorrect.Question : Happy Joe Banking Corporation is building a Banking application to provide online access to their account holders. They have chosen 2 SUN 450s for their web server cluster and 1 SUN E10000 for their application server. The business requirements indicate that to become a customer, a person must have at least a primary checking account with the bank. Further since the customer will be using the Internet to view confidential information, security is considered paramount.What do you understand about the requirements of the system? A The need for Security is a classic example of a functional service level requirement and the checking account rule, an example of non-functional QoS requirement.B The discussion about Security and the mandatory checking account both illustrate functional service level requirements.C Neither Security nor the mandatory Checking Account is an example of any kind of requirements, theoretically speaking.D Security is an Architectural non-functional requirement and the Mandatory Checking Account a functional design requirement.E They are both examples of Business Use Cases. Answer : Choice D is correct. Successful software architecture deals with addressing the non-functional service level requirements of a system. The Design process takes all the functional business requirements into account. Security is considered a non-functional requirement and specific business rules, such as the one described with the checking account are considered functional requirements. D is the only choice that accurately describes this.A is incorrect because the functional and non-functional requirements are flipped over.B is incorrect because only one of them is a functional requirement.C is incorrect because as described above, one of them is a functional requirement and the other, a non-functional requirement.Finally E is incorrect because business analysis may start with use cases (where the checking account rules may be captured), but this discussion is specifically questioning functional vs. non-functional requirements.Question :

Page 43 of 112

Page 44: J2EE Questions

In an interview between the senior management of Happy Joe Banking Corporation and the J2EE application architect Scott Khosla, the following points were discussed:I. The system needed to respond within 5 secondsII. The system is needed to have a 99.9% uptimeIII. HJBC was in the process of acquiring another bank which would add two hundred thousand customers to their already existing half million.IV. Each phase of the SDLC was to have a clear sign off process.V. The development team was expected to provide a detailed unit test plan and user documentation.VI. In order to ensure privacy, HTTPS was to be used. What non-functional requirements were discussed? A Scalability, Availability, Extensibility, Manageability and SecurityB Performance, Reliability, Elaboration, Transition, Documentation and SecurityC Specification, Elaboration, Construction, Transition, Use Cases and SecurityD Performance, Availability, Scalability and SecurityE Reliability, Availability, Scalability, Manageability and Security Answer : Choice D is correct. The non-functional service level requirements discussed are Performance (system needs to respond within 5 seconds), Availability (system is needed to have a 99.9% uptime), Scalability (additional two hundred thousand subscribers), and Security (HTTPS is to be used.) Hence choice D is correct.There is no mention of extensibility (ability to easily add or extend functionality) and Manageability (ability to monitor the health of the system.) Hence choice A is incorrect.Specification, Elaboration, Construction, Transition, Documentation and use cases are not non-functional service level requirements. Hence choices B and C are incorrect.While scalability and reliability may be related (will the system perform as reliably when more users operate on it), there is no mention of reliability in the question. Hence choice E is incorrect Question : N-tier applications show better performance than 2-tier applications because they are modular in nature, which means that they can be scaled easily, by tuning components and containers individually. True/False ? A TrueB False Answer :

Page 44 of 112

Page 45: J2EE Questions

Choice A is correct. N-Tier applications (especially those based on J2EE) are designed to be very modular in nature. The tiers and layers separate roles and responsibilities of each component and container. Hence components and containers can be individually targeted and scaled as needed. This results in better performance. Hence choice A is correct.Question : Moon Microsystems has a web-based solution that was originally built using Servlets. However, in recent months, the IS manager has asked developers to use JSP technology with Java Scriptlets embedded in HTML code. Scott Khosla, the architect, however is insisting that the code be modularized and that EJBs be used instead of Servlets and JSP for business logic processing. In asking developers to modularize existing code, what software development technique is Scott asking the developers to follow? A Code Break upB Code engineeringC Code TieringD Code Factoring Answer : Choice D is correct. Software applications have a tendency to grow in complexity over time. When that happens, they become difficult to extend, maintain and modify. They also become hard to understand.Code factoring is a modularization technique that deals with the separation of responsibilities in code. Factored code has loose coupling and minimal dependencies, making components and code more reusable. Hence choice D is correct.There are no concepts like code break up, code engineering or code tiering. Hence choices A, B and C are incorrect.Question : Fragile Oars, a manufacturer of boating supplies has a mainframe based legacy application for customer and order management. Recently, Fragile Oars embarked on a project to add Internet presence to its products and services and hence created a company website. Since then, its management has realized the importance of having an eFront and wants to start conducting business over the Internet. Fragile Oars wants to use Applets as the front-end. What is the best method to connect to this legacy system? A Using the same appletsB Using different appletsC Using Java Server PagesD Using Java Servlets

Page 45 of 112

Page 46: J2EE Questions

Answer : Choice D is correct. The best approach in this case is to have the applets talk to Servlets that can act as mediators between the applets and the Legacy system. Hence choice D is correct.Applets and JSP are used to construct the view of an MVC application. They should not be used as controllers for dispatching requests. Hence choices B and C are incorrect.Question : Julia Fractals Inc. is building a J2EE based application for Order Entry and management of their fractal software. Once the order is taken, it is submitted to a relational database. A provisioning system then queries data and makes appropriate calls to various subsystems using JMS on MQ Series. What design pattern is JMS an example of here? A ObserverB MediatorC AdapterD BridgeE Visitor Answer : Choice D is correct. Bridge (GOF 151)"Decouple an abstraction from its implementation so that the two can vary independently." In this case JMS is the abstraction. The implementation could be MQ Series, TIBCO Rendezvous and Vitria Businessware. Hence choice D is correct.Observer (GOF 293)"Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically." Hence choice A is incorrect.Mediator (GOF 273)"Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and lets you vary their interaction independently." Hence choice B is incorrect.Adapter (GOF 139)"Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces." Hence choice C is incorrect.Visitor (GOF 331)"Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates." Hence choice E is incorrect. Question : What design pattern best explains the use of the stub and the skeleton in CORBA based RPC applications? A Factory Method

Page 46 of 112

Page 47: J2EE Questions

B SingletonC StrategyD ProxyE Decorator Answer : Choice D is correct. Proxy (GOF 207)"Provide a surrogate or placeholder for another object to control access to it." Hence choice E is incorrect. The applicability section (GOF 208) defines 'remote proxy' as"A remote proxy provides a local representative for an object in a different address space." Using the stub and the skeleton, CORBA based applications provide local representatives for distributed objects. Hence choice D is correct.Factory Method (GOF 107)"Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses." Hence choice A is incorrect.Singleton (GOF 127)"Ensure a class only has one instance, and provide a global point of access to it." Hence choice B is incorrect.Strategy (GOF 315)"Define a family of algorithms, encapsulate each one and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it." Hence choice C is incorrect.Decorator (GOF 175)"Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality." Hence choice E is incorrect. Question : An application has three Stateless Session Beans - SB1, SB2 and SB3. The stubs that implement the respective Home Interfaces are SH1, SH2 and SH3. A client application performs a JNDI lookup to obtain a reference to one of these Home Objects. This is then narrowed and used to create the remote reference to the corresponding remote object. What design pattern best explains the creation of the Remote Object, in this case? A PrototypeB BuilderC Factory MethodD Business delegateE Service Locator Answer : Choice C is correct. Factory Method (GOF 107)"Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses."

Page 47 of 112

Page 48: J2EE Questions

Hence the closest pattern this concept is similar to is the Factory Method pattern. Therefore choice C is correct. Prototype (GOF 117)" Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype." Hence choice A is incorrect. Builder (GOF 97)"Separate the construction of a complex object from its representation so that the same construction process can create different representations." Hence choice B is incorrect. The following is taken from: http://java.sun.com/blueprints/patterns/BusinessDelegate.html "In distributed applications, lookup and exception handling for remote business components can be complex. When applications use business components directly, application code must change to reflect changes in business component APIs. These problems can be solved by introducing an intermediate class called a business delegate, which decouples business components from the code that uses them. The Business Delegate pattern manages the complexity of distributed component lookup and exception handling, and may adapt the business component interface to a simpler interface for use by views." Hence choice D is incorrect. The following is taken from: http://java.sun.com/blueprints/patterns/ServiceLocator.html "Enterprise applications require a way to look up the service objects that provide access to distributed components. Java(tm) 2 Platform, Enterprise Edition (J2EE) applications use Java Naming and Directory Interface (JNDI) to look up enterprise bean home interfaces, Java Message Service (JMS) components, data sources, connections, and connection factories. Repetitious lookup code makes code difficult to read and maintain. Furthermore, unnecessary JNDI initial context creation and service object lookups can cause performance problems. The Service Locator pattern centralizes distributed service object lookups, provides a centralized point of control, and may act as a cache that eliminates redundant lookups. It also encapsulates any vendor-specific features of the lookup process." Hence choice E is incorrect. Question : Compact Computers is a small computer assembly company. Their online application allows customers to pick and choose accessories to build their own PCs. The accessories are: i. Processor - 800Mhz, 1Ghz, 1.2Ghzii. HDD - 40 GB, 60 GB, 80 GB

Page 48 of 112

Page 49: J2EE Questions

iii. Memory - 128 MB, 256 MB, 512 MB If a computer can have exactly 1 processor, 1 HDD and 1 memory stick, what pattern would be best used here? A Factory MethodB BuilderC PrototypeD Abstract FactoryE Singleton Answer : Choice B is correct. Builder (GOF 97) separates the construction of a complex object from its representation so that the same construction process can create different representations. Here the complex object is a computer. A computer is always made up of exactly one processor, one HDD and one Memory stick (problem description.) However there is no predetermined formula for combining the parts. Hence Builder is the best pattern here and B is therefore the right answer.Answer A is incorrect because Factory Method (GOF 107) defines an interface for creating an object but lets subclasses decide which class to instantiate. You may use factories of factories to construct a complex object, but by itself, the Factory method is good for creating one out of many. Example: create one processor out of a set of three processors.Answer C is incorrect because Prototype (GOF 117) specifies the kinds of objects to create using a prototypical instance. Example: Given a processor, if you were asked to create a computer that used multi processors, this would be a good option.Answer D is incorrect because Abstract Factory (GOF 87) provides an interface for creating a family of related or dependent objects. If the question had defined a relation such as 'A computer of 800 MHz processor can only be coupled with a 40 GB HDD and 128 MB RAM stick', this would have been an ideal solution.Answer E is incorrect because Singleton (GOF 127) ensures that a class has only one instance (or a well-defined number of variable instances) and appropriate global pointers are available to the instance(s). Question : Heartbreak Hospital has two applications - Patient Registration System and Patient Billing System. Patient Billing, an older application has CORBA interfaces for updating Billing Information. The newer Patient Registration system was built as a Java based Application. Heartbreak now wants to automatically update Billing Information from the Patient Registration Application. What Java technology may be most suited for this?

Page 49 of 112

Page 50: J2EE Questions

A RMI-JRMPB RMI-JNIC RMI-IIOPD EJBE Java IDLF Java-CORBA Bridge Answer : Choice E is correct. The following is taken from:http://java.sun.com/j2se/1.3/docs/guide/idl/"Java IDL adds CORBA (Common Object Request Broker Architecture) capability to the Java platform, providing standards-based interoperability and connectivity. Java IDL enables distributed Web-enabled Java applications to transparently invoke operations on remote network services using the industry standard IDL (Object Management Group Interface Definition Language) and IIOP (Internet Inter-ORB Protocol) defined by the Object Management Group." Hence choice E is correct.RMI-JRMP is used for distributed processing in a pure Java environment. Hence choice A is incorrect.There is no indication whether the Patient Billing system supports JNI. Hence choice B is incorrect.RMI-IIOP is useful when dealing with EJB applications. Hence choices C and D are incorrect.There is no such thing as a Java-CORBA bridge. The Java IDL API performs that function. Hence choice F is incorrect. Question : In which of the following cases would an application not necessarily benefit from the use of Enterprise Java Beans? A Small Scale deploymentB Large scale deploymentC Transactional in natureD No Transactional requirements Answer : Choices A and D are correct. Enterprise Java Beans are best used with large and complex enterprise applications with high deployment and transactional requirements. Hence choices A And D are correct. Question :

Page 50 of 112

Page 51: J2EE Questions

The container applies what memory management techniques in the case of Session Beans? A Bean PoolingB Bean PassivationC Bean PersistenceD Bean Purge Answer : Choices A and B are correct. While EJBs offer business services, EJB Containers offer many peripheral services such as memory management, persistence, transactions and so on. Bean Pooling (in the case of Stateless Session Beans) and Bean Passivation (in the case of Stateful Session Beans and Entity Beans) are two techniques the container uses for managing memory. Hence choices A and B are correct.Bean persistence refers to persisting the data represented by Entity Beans to physical storages such as Relational, Object or other databases. It has nothing to do with memory management. Therefore choice C is incorrect.There is nothing called Bean Purge. Beans are removed when the client calls the remove() method on the Home Interface (Stateful Session Beans) and when the container decides (in the case of Stateless Session Beans and Entity Beans which reside in Bean Pools when not in use.) In the case of Entity Beans, the remove() method also deletes the data the bean instance represents. Hence choice D is incorrect. Question : Outstanding Perf is a perfume manufacturing company. The management is currently in the process of architecting a new J2EE based solution for their online catalog. If performance is paramount and session state needs to be managed as well, it would be preferable to use HTTP and HTTPSession object as opposed to using HTTPS. True/False? A TrueB False Answer : Choice A is correct. The question specifies that performance is important. There is no mention of the security requirements. Apart from providing Session State, HTTPS includes additional functionality for allowing secure communication between the client and the server. Because of all the extra processing with encryption and decryption, HTTPS is slower than HTTP. Hence in

Page 51 of 112

Page 52: J2EE Questions

this case, it may be preferable to use HTTP (which is stateless) with HTTPSession Object (to store state on the server.) Hence choice A is correct. Question : Staledexho, A renowned catering company has just contracted your services to track their orders. An online menu is available, for each country serviced. Customers choose what they want, the quantity and provide relevant billing information. Fed Ex ships the food in a special container.What classes and APIs are you most likely to use to support Internationalization? A LocaleB Collection InterfaceC ListIteratorD ResourceBundleE KeyStore F OutputStreamWriter Answer : Choices A, D and F are correct.

The following is taken from:http://developer.java.sun.com/developer/technicalArticles/Intl/IntlIntro/"Locales are used throughout the Java class libraries to customize how data is presented and formatted. They affect language choice, collation, calendar usage, date and time formats, number and currency formats, and many other culturally sensitive data representations. If you intend to create international Java applications, you'll definitely use the java.util.Locale class. There's no getting around it; you'll use Locales to create well-behaved, internationalized, multilingual Java applications. So, if you haven't had time to explore all the JDK 1.1 international features yet, you'll get a clearer understanding of the core of the internationalization model, the Locale, as you read and understand the descriptions and examples in this article.A Locale is a relatively simple object. It identifies a specific language and a geographic region. In fact, the only significant contents of a Locale object are language and country. Although superficially these attributes are not particularly impressive, they represent a very rich and interesting set of information. A Locale object represents the language and cultural preferences of a geographic area. Language is a fairly easy idea to grasp; cultural preferences may not be immediately clear. Dates, time, numbers, and currency are all examples of data that is formatted according to cultural expectations. Cultural preferences are tightly coupled to a geographic area; that's why country is an important element of locale. Together these two elements (language and country) provide a precise context in which information can be presented. Using Locale, you can present information in the language and form that is best understood and appreciated by the user.

Page 52 of 112

Page 53: J2EE Questions

Resource Bundles - This internationalization feature of the JDK provides a mechanism for separating user interface (UI) elements and other locale-sensitive data from the application logic in a program. Separating locale-sensitive elements from other code allows easy translation. It allows you to create a single code base for an application even though you may provide 30 different language versions. Although you might be predisposed to think of text only, remember that any localizable element is a resource, including buttons, icons, and menus.The JDK uses resource bundles to isolate localizable elements from the rest of the application. The resource bundle contains either the resource itself or a reference to it. With all resources separated into a bundle, the Java application simply loads the appropriate bundle for the active locale. If the user switches locales, the application just loads a different bundle.Resource bundle names have two parts: a base name and a locale suffix. For example, suppose you create a resource bundle named MyBundle. Imagine that you have translated MyBundle for two different locales, ja_JP and fr_FR. The original MyBundle will be your default bundle; the one used when others cannot be found, or when no other locale-specific bundles exist. However, in addition to the default bundle, you'll create two more bundles. In the example these bundles would be named MyBundle_ja_JP and MyBundle_fr_FR. The ResourceBundle.getBundle method relies on this naming convention to search for the bundle used for the active locale.The java.util.ResourceBundle class is abstract, which means you must use a subclass of ResourceBundle. The JDK provides two subclasses: PropertyResourceBundle and ListResourceBundle. If these don't meet your needs, you can create your own subclass of ResourceBundle." The following is taken from:http://java.sun.com/docs/books/tutorial/i18n/text/stream.html"The java.io package provides classes that allow you to convert between Unicode character streams and byte streams of non-Unicode text. With the InputStreamReader class, you can convert byte streams to character streams. You use the OutputStreamWriterclass to translate character streams into byte streams."Thus we can see that Locale, ResourceBundle and OutputStreamWriter play a vital role in Java Internationalization. Hence choices A, D and F are correct.The Collection interface, ListIterator and KeyStore are not relevant to I18N. Hence choices B, C and E are incorrect. Question : The conversion between 16-bit Unicode and 8-bit local encoding formats is done by: A MessageFormat and NumberFormatB Locale and ResourceBundleC Properties filesD InputStreamReader and OutputStreamWriter Answer :

Page 53 of 112

Page 54: J2EE Questions

Choice D is correct. The following is taken from:http://java.sun.com/docs/books/tutorial/i18n/text/stream.html"The java.io package provides classes that allow you to convert between Unicode character streams and byte streams of non-Unicode text. With the InputStreamReader class, you can convert byte streams to character streams. You use the OutputStreamWriter class to translate character streams into byte streams." Hence choice D is correct.MessageFormat, NumberFormat, Locale, ResourceBundle and properties files are all used in I18N. These are not however used for conversion between Unicode character format and local 8-bit byte streams. Hence choices A, B and C are incorrect. Question : Fire Hall, manufacturers of fire extinguishers, is building a corporate Intranet and wants its employees to access payroll information via the Internet. They are planning to use Applets, because of its richer GUI capabilities. The View401K applet requires a Java 1.4 plug in on the host where it is being executed. This applet will read data cached on a temporary directory in the host to calculate 401K distributions.What are your observations on the use of Applets for this purpose? A The Applet technology is not a viable solution for this application because applets are subjected to the sandbox model, which prevents them from reading from or writing to the host where they are being executed.B The Applet technology is a viable solution for this application because the Security policy of the Java 2 Platform is totally flexible. Answer : Choice B is correct. The following is taken from:http://java.sun.com/docs/books/tutorial/security1.2/overview/index.html "JDK 1.1 introduced the concept of a "signed applet," as illustrated in the next figure. A digitally signed applet is treated like local code, with full access to resources, if the public key used to verify the signature is trusted. Unsigned applets are still run in the sandbox. Signed applets are delivered, with their respective signatures, in signed JAR (Java Archive) files. JDK 1.2 introduces a number of improvements over JDK 1.1. First, all code, regardless of whether it is local or remote, can now be subject to a security policy. The security policy defines the set of permissions available for code from various signers or locations and can be configured by a user or a system administrator. Each permission specifies a permitted

Page 54 of 112

Page 55: J2EE Questions

access to a particular resource, such as read and write access to a specified file or directory or connect access to a given host and port. The runtime system organizes code into individual domains, each of which encloses a set of classes whose instances are granted the same set of permissions. A domain can be configured to be equivalent to the sandbox, so applets can still be run in a restricted environment if the user or the administrator so chooses. Applications run unrestricted, as before, by default but can optionally be subject to a security policy." As we can see, the Java 2 Security model is totally flexible. Hence choice B is correct. Question : Which of the following statements is true about SSL? A SSL runs above high-level application protocols such as HTTP and LDAPB SSL runs below TCP-IPC SSL runs above TCP-IP and below application protocolsD SSL does not have anything to do with either the application or the network layer in the OSI model Answer : Choice C is correct. The following is taken from:http://developer.netscape.com/docs/manuals/security/sslin/contents.htm "The Transmission Control Protocol/Internet Protocol (TCP/IP) governs the transport and routing of data over the Internet. Other protocols, such as the HyperText Transport Protocol (HTTP), Lightweight Directory Access Protocol (LDAP), or Internet Messaging Access Protocol (IMAP), run "on top of" TCP/IP in the sense that they all use TCP/IP to support typical application tasks such as displaying web pages or running email servers. The SSL protocol runs above TCP/IP and below higher-level protocols such as HTTP or IMAP. It uses TCP/IP on behalf of the higher-level protocols, and in the process allows an SSL-enabled server to authenticate itself to an SSL-enabled client, allows the client to authenticate itself to the server, and allows both machines to establish an encrypted connection." Therefore choice C is correct. Choice A is incorrect because it suggests that SSL runs above application protocols. Choice B is incorrect because it suggests that SSL runs below TCP/IP. SSL runs between TCP/IP and HTTP. Hence choice D is incorrect. Question :

Page 55 of 112

Page 56: J2EE Questions

What happens when the remove() method is called on the Home Interface of an Entity Bean? A The remote reference is invalidatedB The bean instance is destroyedC The bean instance is PassivatedD The data represented by the bean instance is deleted from the databaseE The Bean Instance moves from pooled state to ready state Answer : Choices A and D are correct. The remove() method, in the case of Entity Beans, invalidates the client stub, and deletes the data represented by the bean, from the database. Hence choices A and D are correct. The bean instance is returned to the pool. It is not destroyed when the remove() method is called on an Entity Bean. Therefore choice B is incorrect. The container passivates the bean instance whenever required (for memory management.) It is not a consequence of the remove() method though. Hence choice C is incorrect. The Bean instance moves from the Ready State to the Pooled State upon removal, not the other way round as the point suggests. Hence choice E is incorrect. Question : What types of transactions are supported by Enterprise Java Beans? A Implicit Declarative TransactionsB Explicit JTA based transactionsC Either A or B (based on vendor implementation)D Both A and B Answer : Choice D is correct. Enterprise Java Beans specification supports both Implicit Declarative transactions and explicit Java Transaction API (JTA) based transactions. Hence choice D is correct. Question : With Entity Beans, the container automatically generates implementations of all find methods at deployment time.True/False?

Page 56 of 112

Page 57: J2EE Questions

A TrueB False Answer : The above statement is False. The container only generates implementations of the find methods at deployment time, in the case of Container Managed Persistence. Question : The company you have been working for has released the next generation of its sales system. You have several very powerful servers and a few basic servers at your disposal. A network expert has suggested that in order to get the best possible performance out of these machine you use reverse proxy load balancing? What is reverse proxy load balancing? A Splitting requests evenly amongst all back end serversB The proxy sits behind the backend servers monitoring the performance of each one. When it notices one is being used too much it will automatically forward requests to a different server.C Splitting requests amongst all back end servers depending on the amount of spare CPU time each server has available.D A technique used to target certain requests to certain backend servers, e.g. All Servlet requests from one server. All static HTML from another.E A way of filtering out certain requests. It is used to protect against denial of service attacks Answer : Choice D is correct. Reverse proxy load balancing is generally used when you have servers with different amounts of CPUs and Memory. You might have some really powerful servers just to be used for SSL sessions and others to handle static html. Using this will maximize the performance of your application Choice A is a description of round-robin load distribution. Choice B doesn't describe any particular method of load balancing. Choice C is an inaccurate description of reverse-proxy load balancing and you would need access to the mainframes source code to do this. Choice E is a cross between a firewall and a standard proxy server this does not do any load balancing.

Page 57 of 112

Page 58: J2EE Questions

Question : You are working for a web design company and one of your clients would like to convert their website that currently uses Perl and CGI scripts over to a language that is easier to maintain and reuse. Their website is a sports betting website where the customer is able to logon and place bets on a variety of different sporting events. What would you replace this with? A JSP/ServletsB JSP/Servlets/EJBsC JMSD ASP Answer : Choice B is correct. The key to this question is that the site offers the facility to place bets online. Therefore transactions are involved and this means that Enterprise Java Beans need to be used. It is very hard to implement transactions with just Servlets and JSPs. Hence choice B is correct.Choice A is incorrect because transactions are involved. JMS is the messaging package of the J2EE and therefore C is incorrect. And choice D well, enough said! Question : Your company's employee assistance program (EAP) application is now required to be deployed on the Web. The following are characteristics and requirements of the new system:

• The UI is an off-the-shelf, unsigned terminal-emulator applet. • The applet communicates with a terminal server using a proprietary TCP/IP-based protocol. • The terminal server sits behind the corporate firewall and listens on port 10001. • The only configurable items for the applet are the host IP and port of the terminal server. • You company's firewall only allows traffic through on port 80 for HTTP and port 443 for HTTPS. Problem: The applet is unable to communicate through the firewall. Which two statements about this architecture are false? (Choose two) A. If the applet were signed, it could communicate directly with the terminal server. B. If the terminal server were signed, the applet could communicate with it directly on port 10001. C. The applet can communicate with the terminal server if the firewall is modified to allow traffic through on port 10001. D. The applet can communicate with the terminal server if it is configured to communicate with the terminal server on port 80 or 443. Answer : Answer: A, B

Page 58 of 112

Page 59: J2EE Questions

Question : Which two improve software maintainability? (Choose two) A. Code factoring B. Reusing components C. Public instance variables D. Dependencies between components Answer : Answer: A, B

Question : Your supply chain software currently runs a standalone application which communicates to the backend services using IIOP. The new requirements for the software are: • The client software must run as an applet. • The user's firewall will only allow port 80 and 443 traffic through its firewall. • All the backend services will be CORBA-based. • A Web server sits in front of the COBRA services. • The backend Web server runs on port 80 and 443. Which two solutions support the new requirements? (Choose two) A. You convert the application to an applet and use IIOP to communicate with the backend services. B. You convert the application to an applet running outside the browser and send XML through port 443. C. You convert the application to an applet and use IIOP tunneled through HTTP to communicate with the backend services. D. You convert the application to an applet and use HTTPS to communicate with a servlet which communicates with the backend services using IIOP. Answer : Answer: C, D Question : What decreases software maintainability? (Choose two) A. Code reuse B. Data sharing C. High coupling D. Code factoring Answer : Answer: B, C Question :

Page 59 of 112

Page 60: J2EE Questions

You are in the process of migrating your existing system to a new architecture to support your growing user base. The current system consists of: • Browser-based HTML./JavaScript UI. • One Web server instance. • One J2EE application server instance. • A database The new architecture has the following requirements: • Browser-based HTML./JavaScript UI. • Cluster of Web servers. • Cluster of J2EE application servers. • A database. Which two statements are true? (Choose two) A. Clustering increases scalability. B. Clustering impacts availability, not scalability. C. DNS round-robin can be used to load-balance the Web servers. D. Clustering the application servers provides automatic EJB fault-tolerance. Answer : Answer: A, C Question : What increase software maintainability? (Choose two) A. Code reuse B. Data sharing C. High coupling D. Code factoring Answer : Answer: A, D Question : Which two features of a firewall might interfere with the operation of IIOP? (Choose two) A. Port filtering B. Load balancing C. Address filtering D. Network address translation Answer : Answer: A, C Question : As an architect, you are interested in the architecture characteristics of a system. Which two are architectural characteristics? (Choose two) A. Liability B. Reliability C. Inheritance D. Performance

Page 60 of 112

Page 61: J2EE Questions

Answer : Answer: B, D Question : Which two statements are true about management of an EJB's resources? (Choose two) A. The reference to the remote object is obtained through JNDI to improve maintainability and flexibility. B. The reference to home object is obtained through JNDI to improve maintainability and flexibility. C. The EJB container can manage the instance's access to its resources because the home object acts as a proxy. D. The EJB container can manage the instance's access to its resourced because the remote object acts as a proxy. Answer : Answer: B, D Question : What is a benefit of bean pooling in an EJB container? A. It improves the portability between databases. B. It reduces the number of database connections. C. It provides better support to object-oriented databases. D. It reduces the memory allocation and garbage-collection cycles. Answer : Answer: D Question : Which statement about an EJB container's lifecycle management of session beans is true? A. The client is responsible for the object identity for session beans. B. The client can passivate a session bean after a specified timeout period. C. The container can passivate a stateful session bean to free limited resources. D. The container can passivate a stateless session bean to free limited resources. Answer : Answer: C Question : Which statement about passivating session beans is true? A. The passivated stateful session bean should close all connections before being passivated. B. The passivated stateless session bean should close all connections before being passivated. C. The container ensures that the passivated bean's open connections are closed or returned to the

Page 61 of 112

Page 62: J2EE Questions

connection pool. D. The container ensures that the passivated stateless session bean is reassigned to the remote object upon activation. Answer : Answer: A Question : A telecommunications company, Certkiller , is building an enterprise system to allow the Certkiller support staff to access customer information over an intranet. All of the customer information is stored in a legacy system and can only be accessed using a VT100 terminal session. You must create an architecture to access the legacy system. What should you use to encapsulate access to the legacy system? A. A JDBC connection that uses SQL to query the legacy system. B. AN EJB entity bean that uses JMS to interact with the legacy system. C. A distributed CORBA object that uses IIOP to interact with the legacy system. D. An EJB session bean that uses a screen-scraping tool to interact with the legacy system. Answer : Answer: A Question : A manufacturing company, Certkiller GmBh, is building an enterprise system to allow the sales staff to place customer orders over an intranet. All orders must be placed using a legacy system running MQSeries. You must create an architecture to interact with the legacy system. How would you encapsulate interaction with that legacy system? A. With an EJB session bean that uses JMS to message the legacy system. B. With a Java class that uses a screen-scraping tool to interact with the legacy system. C. With a distributed CORBA object that uses IIOP to interact directly with the legacy system. D. With an EJB entity bean that uses container-managed persistence to encapsulate the legacy system. Answer : Answer: A Question : Certkiller .com, a shipping company, is building an enterprise system to track the location of packages. One part of the tracking system is a network of wireless inventory devices. The devices can only be accessed using a custom, synchronous TCP/IP protocol.

Page 62 of 112

Page 63: J2EE Questions

How should you encapsulate interaction with the wireless inventory system? A. With an EJB session bean that uses a JMS to interact with the inventory system. B. With a Java class that uses custom Java networking to interact with the inventory system. C. With a distributed CORBA object that uses IIOP to interact directly with the inventory system. D. With an EJB entity bean that uses container-managed persistence to encapsulate the inventory system. Answer : Answer: CQuestion : What are two features of JRMP? (Choose two) A. It is secure. B. It is connectionless. C. It is connection-based. D. It is used for load balancing. E. It is used for hypermedia requests. F. It is used for remote-object communications. Answer : Answer: C, F Question : A steel industry association has hired you, a Certkiller network consultant, to create a B2B architecture for the steel industry. What does this mean? A. You have to create a portal to allow consumers to order steel products. B. You have to create a portal to exchange news and information about the steel industry. C. You have to create an infrastructure to allow the exchange of product catalog information between steel companies. D. You have to create an architecture to allow the exchange of order information between steel companies order systems. Answer : Answer: D Question : Which items provides tools to allow the formatting of currency and date information according to local conventions? A. java.text package B. java.util.Locale class C. javla.lang.String class D. Pluggable look and feel in Swing

Page 63 of 112

Page 64: J2EE Questions

E. Readers and Writers in the java.io package Answer : Answer: A Question : Which three are aspects of an application are most likely to be determined at runtime based on the user's declared nationality of locale? (Choose three) A. Currency formats. B. Network protocols. C. Textual output messages.

D. Calculations and/or algorithms. E. Server host names and/or addresses Answer : Answer: A, C, E

Question : Which three statements about container-managed persistence are true? (Choose three) A. A container-managed enterprise bean requires less code. B. Container-managed persistence provides less bean control. C. Container-managed persistence can require complex mapping techniques. D. Container-managed persistence manages a session bean's conversational state. Answer : Answer: A, B, C Question : What acts as a proxy to an EJB? A. IDL instance B. Home instance C. Bean instance D. Remote instance Answer : Answer: D Question : Certkiller 's application uses several entity beans accessing each other for information. The company found the architecture to be low in flexibility because they embedded entity relationships in the entity beans. What is an alternative solution?

Page 64 of 112

Page 65: J2EE Questions

A. Use a stateful session bean as a Mediator to the entity beans. B. Use a stateful session bean as a Façade to other session beans. C. Use a servlet to give clients direct access to data in a database table. D. Use a stateless session bean to access the database directly instead of using entity beans. Answer : Answer: A Question : A client makes a transactionless method call to an EJB that has a transaction attribute of Required in the deployment descriptor. Which statement is true? A. The container creates a new transaction.

B. The EJB throws an EJBException since it requires transaction context. C. The EJB throws a RemoteException since it requires a transaction context. D. The container throws a RemoteException since the EJB must have a transaction context. Answer : Answer: A Question : Which two statements about stateless session beans are true? (Choose two) A. They provide a generic service. B. They maintain a cached state on behalf of a specific client. C. They maintain a conversational state on behalf of several clients. D. They may provide high performance by being available for multiple clients. Answer : Answer: A, D Question : You are creating an architecture for an online ordering system with the following requirements: • Users will order products over the Internet. • Business objects will reside on a local application server. • All product information is stored in a local RDBMS. • Credit card information must be validated by an external system. • All local systems will be secured behind a firewall. • All communications with the external systems must be secure. Which two design decisions will increase the flexibility of the system? (Choose two) A. Using an entity bean to track the user's shopping cart. B. Using an entity bean to encapsulate product information. C. Using a stateless session bean to validate user ID and password. D. Using an entity bean to encapsulate the external credit card system.

Page 65 of 112

Page 66: J2EE Questions

Answer : Answer: B, C Question :

The following statement is true about which type of EJB? "All bean instances are equivalent when they are not involved in serving a client-invoked method". A. Stateful session bean B. Stateless session bean C. Entity bean with bean-managed persistence D. Entity bean with container-managed persistence Answer : Answer: B

Question : Your client is a bank that wants to allow its customers to access their bank accounts over the Internet. Given the following requirements, which protocol communicates with the Web browser? • Confidential information must be protected. • Customers will access their accounts using only a simple Web browser with no extension. A. IIOP B. HTTP C. SNMP D. HTTPS Answer : Answer: D Question : A department of Certkiller Inc uses entity beans with bean-managed persistence to access an RDBMS. The entity beans contain the code to access the database directory. Certkiller decides that other departments can reuse the business logic to access their database, which include an OODBMS and a different type of RDBMS. Which statement best describes how Certkiller can integrate their departmental business logic to access the various databases, and to ensure that the entity bean code is easy to read? A. Use session beans to access an entity bean through a data access object.

Page 66 of 112

Page 67: J2EE Questions

B. Move the data-access code out of the entity beans into a data-access object. C. Distribute the data-access code among several entity beans to access different databases. D. Use session beans to access several entity beans that represents the data in all three databases. Answer : Answer: B Question : Certkiller Grapes, a vineyard, is developing an online ordering system to sell wine online. Because of local sales restrictions, the vineyard is working with local wine stored to deliver wine to the customers. The requirements for the system are: • Customers keep their choices in a "wine list". • Requests are fulfilled as the vintage become available. • Local wine shops track wines that have been ordered by customers in their area. • All order and product data is stored in an RDBMS. • Both customers and local wine shops use the Internet to access the system. • The system must be scalable and secure. Which two interactions must be secure? (Choose two) A. Customers adding wine to their wine list. B. The application server generating a sales report. C. The application server updating the order information into the DB. D. The local wine stop checking what wines have been ordered locally. Answer : Answer: A, D Question : Which pattern provides a means to access the elements on an aggregate object sequentially without exposing the underlying structure? A. Proxy B. Iterator C. Strategy D. Observer E. Singleton Answer : Answer: B

Question :

Page 67 of 112

Page 68: J2EE Questions

You have determined that the interactions between objects in a system are complex, and that the objects are tightly coupled. Furthermore, additional functionality would require the modification of many objects in the system. Which pattern will solve this problem? A. Façade B. Mediator C. Template D. Prototype E. Command Answer : Answer: B

Question : What are two benefits of the Façade pattern? (Choose two) A. It hides complex subsystems from clients. B. It allows objects to masquerade as different objects. C. It decouples the object interface from the implementation. D. It encourages weak coupling between the client and the subsystem. Answer : Answer: A, D Question : Which design pattern is represented by the EJB Home interface? A. Proxy B. Visitor C. Façade D. Abstract Factory Answer : Answer: D Question : What are three benefits of design patterns? (Choose three) A. They act as a learning aid. B. They provide standard code libraries. C. They provide a common design vocabulary. D. They standardize the way designs are developed. E. They describe an object-oriented development process. Answer : Answer: A, C, D Question :

Page 68 of 112

Page 69: J2EE Questions

What are two clear advantages to using message services in an application? (Choose two) A. Provides scalability B. Provides secure communication services. C. Allows loose coupling between components. D. Allows clients and servers to communicate directly. Answer : Answer: A, C Question : The requirements for an online shopping application are: • It must support millions of customers. • The invocation must be transactional. • The shopping cart must be persistent. Which technology is required to support these requirements? A. JNI B. JMS C. EJB D. JMX Answer : Answer: C Question : Which two statements about JMS are true? (Choose two) A. JMS supports Publish/Subscribe. B. JMS uses JNDI to find the destination. C. JMS enhances access to email services. D. JMS uses JMX to create a connectionFactory. Answer : Answer: A, B

Question : Which statement describes a normal default security restriction applied to untrusted classes by a Javaenabled browser? A. Untrusted classes cannot read data from arbitrary files. B. Untrusted classes cannot initiate any network connections. C. Untrusted classes cannot write sensitive data to the screen. D. Untrusted classes cannot make unrestricted use of CPU power. E. Untrusted classes cannot read sensitive data from the keyboard.

Page 69 of 112

Page 70: J2EE Questions

Answer : Answer: A Question :

These are the requirements for your new system: • All current business logic is in the form of database-stored procedures. • All current and new business logic is to be migrated to EJB. • The system is an online, Web-based system. The UI is HTML-based. • There are three EJBs: Customer, Order, and Account. There is one Java object, ShoppingList, which holds the current list of ordered items. • Only account and order data are stored in the database. • The Customer EJB maintains a reference to the ShoppingList. Which three architectural decisions adhere to the requirements? (Choose three) A. Make Order and Account an entity EJB. B. Make Customer a stateful-session EJB. C. Make Customer a stateless-session EJB. D. Make Customer an entity EJB and put business logic in it. E. Make Customer a session EJB and put business logic in it. F. Use the Container Managed Persistence policy for the Customer session EJB. Answer : Answer: A, B, E Question : You are developing an HR application with the following requirements: • Users access the systems over an intranet, using a standard Web browser. • Organization information is stored in LDAP. • Benefits information is stored in an RDBMS. • Complaints are sent directly to a third-party system for compliance. Which J2EE technology would allow the system to interact with the LDAP server? A. EJB B. JSP C. JMS D. JTA E. JNDI F. JDBC Answer : Answer: E Question : Which two services does EJB provide? (Choose two) A. HTML generation B. Transaction services C. Lifecycle management D. Remote-method invocation

Page 70 of 112

Page 71: J2EE Questions

Answer : Answer: B, C http://www.geekinterview.com/question_details/9351

SCBD Beta Exam Information and Mocks

TopicAnswerExam NameSun Certified Business Component Developer for J2EEExam Code311-090Exam TypeMultiple Choice and Drag and Drop questionsNo. of Qs183Time4 hoursExam ValidityJUNE 6 - JULY 7, [email protected] No. of Objectives54 under 14 categoriesAcknowledgementKathy Sierra, Bert Bates, Valentin Crettaz, JavaRanchPrepared byMuhammad Ashikuzzaman (Fahim)Last Modification Date 27-06-2003Version1.4

What is SCBCD?SCBCD is the abbreviation for Sun Certified Business Component Developer for Java 2 Platform, Enterprise Edition. This is another J2EE certification from sun not to be confused with SCWCD. SCWCD focuses on the Web tier (Servlets, JSPs and other web components stuff), while SCBCD is dedicated to the Business tier (EJBs). You may find an introduction on web tier/business tier descriptions from J2EE tutorial of Sun at - http://java.sun.com/j2ee/1.4/docs/tutorial/doc/Overview3.html#wp81104

Figure-1: The road towards SCBCD Certificate

Page 71 of 112

Page 72: J2EE Questions

Objectives (Short)

o Client View of a Session Beano EJB Overviewo Session Bean Component Contracto Session Bean Lifecycleo Component Contract for Container-Managed Persistence (CMP)o Client View of an Entityo CMP Entity Bean Lifecycleo Entity Beanso EJB-QLo Message-Driven Bean Component Contracto Transactionso Exceptionso Enterprise Bean Environmento Security Management

Objectives (Details)

1 EJB Overview1.1 Identify the use, benefits, and characteristics of Enterprise JavaBeans Technology, for version 2.0 of the EJB specification.1.2 Identify EJB 2.0 container requirements - spec p-56.1.3 Identify correct and incorrect statements or examples about EJB programming restrictions - spec p-494.1.4 Match EJB roles with the corresponding description of the role's responsibilities, where the description may include deployment descriptor information - spec p-33.1.5 Given a list, identify which are requirements for an EJB-jar file - spec p-46, 487.

2 Client View of a Session Bean2.1 Identify correct and incorrect statements or examples about the client view of a session bean's local and remote home interfaces, including the code used by a client to locate a session bean's home interface.2.2 Identify correct and incorrect statements or examples about the client view of a session bean's local and remote component interfaces.

3 Session Bean Component Contract3.1 Identify correct and incorrect statements or examples about session beans, including conversational state, the SessionBean interface, and create methods.3.2 Identify the use of, and the behavior of, the ejbPassivate method in a session bean, including the responsibilities of both the container and the bean provider.3.3 Identify the interface and method for each of the following: Retrieve the session bean's remote home interface, Retrieve the session bean's local component interface, Determine if the session bean's caller has a particular role, Allow the instance to mark the current transaction as a roleback, Retrieve the UserTransaction interface, Prepare the instance for re-use following passivation, Release resources prior to removal, Identify the invoker of

Page 72 of 112

Page 73: J2EE Questions

the bean instance's component interface, Be notified that a new transaction has begun, be notified that the current transaction has completed.3.4 Match correct descriptions about purpose and function with which session bean type they apply to: stateless, stateful, or both.3.5 Given a list of responsibilities related to session beans, identify those which are the responsibility of the session bean provider, and those which are the responsibility of the EJB container provider.3.6 Given a list of requirements, identify those which are the requirements for a session bean class, remote component interface, remote home interface, create methods, business methods, local component interface, remote component interface.

4 Session Bean Lifecycle4.1 Identify correct and incorrect statements or examples about the lifecycle of a stateful or stateless session bean instance.4.2 Given a list of methods of a stateful or stateless session bean class, define which of the following operations can be performed from each of those methods: SessionContext interface methods, UserTransaction methods, JNDI access to java:comp/env environment naming context, resource manager access and other enterprise bean access.4.3 Given a list of scenarios, identify which will result in an ejbRemove method not being being called on a bean instance.

5 Client View of an Entity5.1 Identify correct and incorrect statements or examples about the client view of an entity bean's local and remote home interface, including the code used to locate an entity bean's home interface, and the home interface methods provided to the client.5.2 Identify correct and incorrect statements or examples about the client view of an entity bean's local component interface (EJBLocalObject).5.3 Identify correct and incorrect statements or examples about the client view of a entity bean's remote component interface (EJBObject).5.4 Identify the use, syntax, and behavior of, the following entity bean home method types, for CMP: finder methods, create methods, remove methods, and home methods.

6 Component Contract for Container-Managed Persistence (CMP)6.1 Identify correct and incorrect statements or examples about the entity bean provider's view and programming contract for CMP, including the requirements for a CMP entity bean.6.2 Identify correct and incorrect statements or examples about persistent relationships, remove protocols, and about the abstract schema type, of a CMP entity bean.6.3 Identify correct and incorrect statements or examples about the rules and semantics for relationship assignment, and relationship updating, in a CMP bean.6.4 Match the name with a description of purpose or functionality, for each of the following deployment descriptor elements: ejb-name, abstract-schema-name, ejb-relation, ejb-relationship-role, cmr-field, cmr-field-type, and relationship-role-source.6.5 Identify correctly-implemented deployment descriptor elements for a CMP bean (including containermanaged relationships).

Page 73 of 112

Page 74: J2EE Questions

6.6 Identify the interface(s) and methods a CMP entity bean must and must not implement.

7 CMP Entity Bean Lifecycle7.1 Identify correct and incorrect statements or examples about the lifecycle of a CMP entity bean.7.2 From a list, identify the purpose, behavior, and responsibilities of the bean provider for a CMP entity bean, including but not limited to: setEntityContext, unsetEntityContext, ejbCreate, ejbPostCreate, ejbActivate, ejbPassivat, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.7.3 From a list, identify the responsibility of the container for a CMP entity bean, including but not limited to: setEntityContext, unsetEntityContext, ejbCreate, ejbPostCreate, ejbActivate, ejbPassivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

8 Entity Beans8.1 From a list of behaviors, match them with the appropriate EntityContext method responsible for that behavior.8.2 Identify correct and incorrect statements or examples about an entity bean's primary key and object identity.

9 EJB-QL9.1 Identify correct and incorrect syntax for an EJB QL query including the SELECT, FROM, and WHERE clause.9.2 Identify correct and incorrect statements or examples about the purpose and use of EJB QL.9.3 Identify correct and incorrect conditional expressions, between expression, in expressions, like expressions, and comparison expressions.

10 Message-Driven Bean Component Contract10.1 Identify correct and incorrect statements or examples about the client view of a message-driven bean, and the lifecycle of a message-driven bean.10.2 Identify the interface(s) and methods a JMS Messaged-Driven bean must implement.10.3 Identify the use and behavior of the MessageDrivenContext interface methods.10.4 From a list, identify the responsibility of the bean provider, and the responsibility of the container provider for a message-driven bean.

11 Transactions11.1 Identify correct and incorrect statements or examples about EJB transactions, including bean-managed transaction demarcation, and container-managed transaction demarcation.11.2 Identify correct and incorrect statements about the Application Assembler's responsibilities, including the use of deployment descriptor elements related to transactions, and the identification of the methods of a particular bean type for which a transaction attribute must be specified.

Page 74 of 112

Page 75: J2EE Questions

11.3 Given a list of transaction behaviors, match them with the appropriate transaction attribute.11.4 Given a list of responsibilities, identify whose which are the container's with respect to transactions, including the handling of getRollbackOnly, setRollbackOnly, getUserTransaction, SessionSynchronzation callbacks, for both container and bean-managed transactions.

12 Exceptions12.1 Identify correct and incorrect statements or examples about exception handling in EJB.12.2 Given a list of responsibilities related to exceptions, identify those which are the bean provider's, and those which are the responsibility of the container provider. Be prepared to recognize responsibilities for which neither the bean or container provider are resopnsible.12.3 Identify correct and incorrect statements or examples about application exceptions and system exceptions in entity beans, session beans, and message-driven beans.12.4 Given a particular method condition, identify the following: whether an exception will be thrown, the type of exception thrown, the container's action, and the client's view.12.5 Identify correct and incorrect statements or examples about the client's view of exceptions received from an enterprise bean invocation.

13 Enterprise Bean Environment13.1 Identify correct and incorrect statements or examples about an enterprise bean's environment JNDI naming.13.2 Identify correct and incorrect statements about the purpose and/or use of the deployment descriptor elements for environment entrys, ejb references, and resource manager connection factory references, including whether a given code listing is appropriate and correct with respect to a particular deployment descriptor element.13.3 Given a list of responsibilities, identify which belong to the deployer, bean provider, application assembler, container provider, system administrator, or any combination.

14 Security Management14.1 Identify correct and incorrect statements about the EJB support for security management including security roles, security role references, and method permissions.14.2 From a list of responsibilities, identify which belong to the application assembler, bean provider, deployer, container provider, or system administrator.14.3 Given a code listing, determine whether it is a legal and/or appropriate way to programmatically access a caller's security context.14.4 Given a security-related deployment descriptor tag, identify correct and incorrect statements and/or code related to that tag.

Study Resources

* EJB 2.0 Specification - http://java.sun.com/j2ee/1.3/download.html#sdk* Enterprise JavaBeans, 3rd Edition by Monson-Haefel (O' Reilly)* Mastering EJB, 2nd Edition by Ed Roman (Wiley)

Page 75 of 112

Page 76: J2EE Questions

* JDiscuss Mock Exam on SCBCD at http://www.jdiscuss.com/Enthuse/jsp/ShowAvailableTests.jsp* Valentine's Exception Handling Cheat Sheet at http://www.valoxo.ch/jr/ExceptionHandling.pdf * Instructions to download sample chapters of Kathy's SCBCD book - http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=70&t=000107* BrainBench's exam on EJB - http://www.brainbench.com* Erik Kaellgren's mock at http://kaellgren.freewebpage.org/ * HTML version of this note - http://www.geocities.com/francisco_guimaraes/ashik* Whizlabs SCDBCD Mock Exam Simulator - http://www.whizlabs.com/scbcd/scbcd.html* Kathy and Bert's Head First Java - http://www.amazon.com/exec/obidos/ASIN/0596005717/electricporkchop* Valentine's cheat sheets - http://www.valoxo.ch/jr/cheatsheets.html* JDiscuss free mock tests of SCBCD - http://www.jdiscuss.com/Enthuse/jsp/ShowAvailableTests.jsp

Valentine's Mapping between Exam Objectives and EJB 2.0 Spec1. EJB Overview1.1 -> 1.2, 2.1, 2.31.2 -> 24.21.3 -> 24.1.21.4 -> 25 + *'s responsibilities sections all over the spec1.5 -> 23.3 2. Client View of a Session Bean2.1 -> 6.2.1, 6.32.2 -> 6.5 3. Session Bean Component Contract3.1 -> 7.4, 7.5.1, 7.5.5, 7.9.13.2 -> 7.4.1, 7.7.53.3 -> 7.5.1, 7.5.2, 7.5.33.4 -> 7.6, 7.7, 7.8, 7.93.5 -> 7.10, 7.113.6 -> 7.10.2, 7.10.5, 7.10.6, 7.10.3, 7.10.4, 7.10.7, 7.10.8 4. Session Bean Lifecycle4.1 -> 7.6, 7.84.2 -> 7.6.1, 7.8.24.3 -> 7.6.3 5. Client View of an Entity5.1 -> 9.5, 9.6, 9.4.15.2 -> 9.105.3 -> 9.95.4 -> 9.5, 9.6 6. Component Contract for Container-managed Persistence (CMP)6.1 -> 10.3, 10.3.16.2 -> 10.3.2, 10.3.46.3 -> 10.3.6, 10.3.7, 10.3.8

Page 76 of 112

Page 77: J2EE Questions

6.4 -> 10.3.136.5 -> 10.3.136.6 -> 10.6 7. CMP Entity Bean Lifecycle7.1 -> 10.57.2 -> 10.5.2, 10.67.3 -> 10.5.3, 10.7 8. Entity Beans8.1 -> 10.5.48.2 -> 10.8, 10.3.5 9. EJB-QL9.1 -> 11.2.6, 11.2.7, 11.2.89.2 -> 11.39.3 -> 11.2.7.5, 11.2.7.7, 11.2.7.8, 11.2.7.9, 11.2.7.10, 11.2.7.11 10. Message-Driven Bean Component Contract10.1 -> 15.3, 15.510.2 -> 15.410.3 -> 15.4.310.4 -> 15.7, 15.8 11. Transactions11.1 -> 17.2, 17.3.1, 17.3.3, 17.3.411.2 -> 17.4, 17.7.411.3 -> 17.4.1, 17.6.2, 17.6.311.4 -> 17.6.1, 17.6.2, 17.6.3 12. Exceptions12.1 -> 1812.2 -> 18.2, 18.312.3 -> 18.2, 18.3.1, 18.3.2, 18.412.4 -> 18.2, 18.312.5 -> 18.4 13. Enterprise Bean Environment13.1 -> 20.213.2 -> 20.2, 20.3, 20.413.3 -> 20.2, 20.3, 20.4, 20.5 14. Security Management14.1 -> 21.2.5.3, 21.3.1, 21.3.2, 21.3.3, 21.4.214.2 -> 21.2, 21.3, 21.4, 21.6, 21.7, 22.1, 22.2, 22.3, 22.414.3 -> 21.2.514.4 -> 21.2.5.3, 21.3, 21.4.2, 21.4.3, 22.3 Things You Can Ignore for the Exam (Kathy)

* Anything at all about EJB 1.1 (or earlier)* Anything at all about EJB 2.1* Anything at all about non-EJB parts of the J2EE spec, in other words, no web components.

Page 77 of 112

Page 78: J2EE Questions

* Anything about what is in the EJBMetaData interface. You DO need to know how to get it (especially so that you can recognize when you are looking at a local vs. remote home -- remember, the geEJBMetaData() method is ONLY in the remote home, so if you see that method, it's a Big Clue...) * Details about the 'handles'. You DO need to know under which circumstances they are available (remote interfaces ONLY!), and what they're for, but that's it. * Anything about BMP (so, chapter 12 and 13 are out, as well as chapter 14 about CMP 1.1) * Deep details about JMS. You *do* need to know about message-driven beans, per the objectives, but you will only have a handful of questions on MDB, and you aren't expected to be a JMS expert. * Anything about isolation levels (other than knowing that you can't control them from EJB! And that the 2.0 spec really has nothing to say about isolation levels) * Chapter 19!! (Support for distribution and interoperability) The whole thing. You DO need to know that IIOP is the assumed wire protocol (even if it isn't used) and that this is why you need PortableRemoteObject.narrow() with your remote home stubs, but this is covered in the objectives on "client view". So, no details on propagation of security, IDL, etc. * Every possible exact tag syntax for the DD. BUT... be warned that there *are* questions that will expect you to know WHICH tags/elements are used in a particular scenario. You will need to recognize which tags make up a particular element. Especially the ones that matter. So you will need to know the difference between, say, security roles and security role *references*, but you won't necessarily have to memorize the exact tag structure. Still, I'd become pretty familiar with the DD. Yes we DO expect that you might use tools to generate the DD, but as a developer it is still YOU who must supply the information to the tool, so you need to know about each part of the DD in pretty good detail. * Anything about security that is not covered in the spec. So, you don't need to know about authorization mechanisms. You DO need to know about roles/references, and how to use programmatic security info (getCallerPrincipal() and isCallerInRole(), and know about the 'run-as' feature in 2.0) * Anything in the J2EE API (including things that have been promoted to J2SE as of 1.4), EXCEPT for the interfaces / classes covered in the objectives: So, you DO need to know exactly what is in the EJBObject, EJBHome, EJBLocalHome, EJBLocalObject, SessionBean, EnterpriseBean, MessageDrivenBean, EntityBean, SessionContext, EntityContext,MessageDrivenContext, MessageListener, UserTransaction, and... I think that's it. Let me know if I left something out here... * The APIs and technology requirements of EJB, EXCEPT you need to know exactly WHICH are part of EJB. In other words, you MUST know that JavaMail 1.1 (sending only) is included in any EJB 2.0 Page 77 of 98container, but you do NOT need to know anything about the JavaMail API. Same for JNDI (except for the things covered in other objectives, mainly: client lookup and a bean's environment (java:comp/env)

You MUST know that JDBC, JTA, JMS, JAXP are all part of the EJB 2.0 specification. But you don't need to know how they work, beyond what you need for the other objectives,

Page 78 of 112

Page 79: J2EE Questions

mainly: javax.transaction.UserTransaction (for JTA) and the MessageListener interface (for JMS). Oh yeah, you do need to know about JMS topics and queues, but not in detail. * ANYTHING that is vendor-specific.* ANYTHING that involves a particular app server, including the reference implementation.

I cannot think of a single question that is not taken directly from the spec. What makes the questions challenging is that the questions expect you to *infer* certain things from looking at code or a scenario. For example, if you see a client doing a lookup, and the client does NOT perform a narrow on the home, AND you are told to assume the client code is legal... what does this tell you? That the interface is local! But of course, that's not what the question will ask... it might ask you if you can use that same reference to call getHomeHandle(), which you will say NO, because you can see from the code that you're working with a local interface, and therefore getHomeHandle() does not apply.

Additionally

RMI -- This is covered on the exam only to the extend that you must know what it means to be 'remote'. For example, you must know that: * EJBObject and EJBHome both extend java.rmi.Remote, which is a marker interface (no methods to implement with Remote). * ALL methods in a remote interface MUST declare java.rmi.RemoteException * You must understand, but not know any details about, the fact that a stub class is generated from the implementation of the remote interface, and that the container is responsible for BOTH of the those classes -- the implementation of your remote interface AND the stub made from that interface. (And of course this is true for both Home and Component interfaces) * You do NOT have to know about:* rmic* skeletons* how to 'export' a remote object* how to place the remote object in the naming service* the wire protocol, except you MUST know that you are to assume IIOP. Implication? You MUST 'narrow' the Home reference if it is a remote home interface.* that arguments and return types MUST be serializable if they are passed in or out of remote methods.JNDI -- you do not need to know much about the JNDI API. But you must know: * What it means to get a JNDI Context and InitialContext.* How to do a client lookup (initialContext.lookup("foo"))* Most importantly, you must understand the bean's own JNDI environment (java:comp/env), which is the bean's own private space for looking up: 1) references to other beans (EJB references)2) resources, such as JDBC,(resource factory references)3) environment entrys (deploy-time customized values, like properties) Be sure you know EXACTLY how those things are used both in the deployment descriptor, and in code, and be sure you know WHICH EJB role is responsible for which part... for example, you must know that the deployer is responsible for *ensuring* that all

Page 79 of 112

Page 80: J2EE Questions

environment entrys have a valid value, even though it is often the app assembler who puts in the value. And be sure you know that there are three levels of mapping for, say, configuring a database into the EJB app -- the database itself is configured into the server, then the factory reference is given a name in JNDI, and then a logical name (that may NOT be the JNDI name!) is used in code (this is the resource factory reference name in the DD), and that logical name must be mapped back to the *real* JNDI name, at deploy time.

Last Minute Tips by Kathy

CODE EXAMPLES: Assuming that the code is legal (and you aren't tested on any Java syntax! -- If the code is illegal, that's because it won't work according to EJB rules or APIs) * If you see a call to getRollbackOnly(), what does that tell you?-- this MUST be a CMT bean! BMT beans can't call this, because they can use only the UserTransaction interface, which has getStatus(), but not setRollbackOnly() * If you see a call to setRollbackOnly(), what does this tell you?-- NOTHING, until you look at which interface the method was invoked on -- is it EJBContext? Then you have a CMT bean. UserTransaction? BMT bean. * If you see code that does not perform a narrow on the home stub, what does this tell you?-- this is a local client! * If you see code that *successfully* invokes getPrimaryKey(), what does that tell you?-- this is an entity bean * If you see code that successfully invokes getHandle(), what does this tell you?-- that you are looking at a remote interface; local interfaces aren't involved with handles -- if you see code that invokes a remove(pk) on the home, you know you are dealing with an entity bean (and that you are seeing code invoked on the home) -- if you see code that invokes a remove(handle), you know you are looking at a remote client -- could be session or entity -- and that you are seeing code invoked on the home -- if you see the no-arg remove(), then it must be the component interface SECURITY: * if you see isCallerInRole(aString), what do you know? - you are NOT looking at a message-driven bean- the method is invoked on an EJBContext

- "aString" must be declared in the deployment descriptor as a security role REFERENCE -- be SURE you understand the difference between security ROLE and security role REFERENCE the reference is something the bean provider must put in, to tell everyone that he has hard-coded a role String. Remember, the bean provider does not *really* know what the actual security roles are in the company, so he just makes one up that sounds good, and then describes it in the deployment descriptor. The someone *else* must map from security role REFERENCES to security ROLES in the deployment descriptor (often this is the Application Asssembler), and finally, the Deployer must map from security ROLES (in the deployment descriptor) to *real* security roles for principals/users/groups in the real

Page 80 of 112

Page 81: J2EE Questions

"operational environment". This final mapping is NOT part of the EJB spec! It is NOT done in the ejb-jar.xml document. Session Beans: -- know the lifecycle ---- stateless session beans ejbCreate is not in any way connected to a client calling create-- same with remove -- passivation is ONLY for stateFUL beans.-- they will never be passivated while in a transaction!-- If a stateful bean times out while passivated, the container will NOT "wake the bean up" (i.e. activate) just to kill it. So, the bean will be killed WITHOUT getting a remove() call. So don't rely on remove() [which will also be missed if there's a server crash] -- be sure you know that setSessionContext is called very early in the bean's life, and only ONCE (this is true for all beans), and that within setSessionContext, you do not yet have access to your component interface, you must wait until you are in ejbCreate! -- do not do ANYTHING in your bean's constructors. An object does not have any "beanness" at that point. It is *legal* to put some code there, but don't. -- a transaction on a stateFUL bean can span multiple invocations from the client. In other words, you can start a tx in one method and then leave it uncomplete when the method ends. -- a stateLESS bean must complete its tx before the end of the method -- a stateLESS bean must NOT implement SessionSynchronization TRANSACTIONS:

-- BMT is for Session (both types) and Message-driven beans ONLY --- A BMT bean will not run in a tx unless it is the tx started by the bean itself. -- A BMT bean's transaction will propogate to other beans that the BMT bean calls.

-- a BMT bean must not start one tx before completing the previous one. -- BMT means must never call setRollbackOnly or getRollbackOnly on the context. CMP:-- know the SIX transaction attributes, and know exactly how they will behave, depending on whether or not the calling method is in a transaction. -- know that MANDATORY and NEVER will throw exceptions -- which transaction attributes can an mdb have? Only Required and NotSupported! The others do not make any sense for an MDB, since it can NEVER be invoked with an existing tx (it is only the container who invokes the onMessage()) -- know that a bean with SessionSynchronization must NOT use Never, NotSupported, or Supports. In other words, a bean that wants to know about its tx status better be in a transaction! -- look up in the spec what it means to have "an unspecified transaction context", and understand the circumstances in which a method will run that way. -- know exactly WHICH methods must have a tx attribute;- Session: just the business methods from component interface, nothing else -- Message: just onMessage()

Page 81 of 112

Page 82: J2EE Questions

-- Entity -- all the business methods, the methods YOU define in the home (create(), finders, etc.) AND the three remove() methods from the two interfaces! (or two remove() methods if its local) EXCEPTIONS:-- know the difference between System and Application exceptions. -- most importantly, know that only System exceptions result in an automatic rollback. For application exceptions. -- Know that application exceptions go to the client AS-IS (in other words, exactly as they were thrown by the bean / conainer) -- System exceptions are wrapped in a RemoteException for remote clients -- local clients WILL get an EJBException, but a remote client never will.

-- you must know which are checked and which are not, so that you know what your responsibility is for declaring them, and what the client's responsbilitiy is. EJBObject is a runtime exception, so you can throw it anytime without declaring Know the FIVE application exceptions from javax.ejb: Finder--ObjectNotFound Create-- DuplicateKeyException Remove Know that a client might not always GET the DuplicateKeyException even when that is the problem. Don't count on it. Know the difference between ObjectNotFound and NoSuchObject. ObjectNotFound is ONLY for finder methods, and only for single-row finder methods.To remember: "ObjectNotFOUND goes with FINDER methods" NoSuchObject means that at one point the client had a reference to an EJBObject, but that EJBObject is no longer there -- in other words, you have a stub but the thing it connected to (the remote object) is gone. Know that NoSuchObject is a standard RMI exception, but that now there is a NoSuchLocalObject exception as well. Know that even though RemoteException is a checked exception, is is NOT an application exception. Anything else you declare in one of your interfaces IS an application exception (which must also be a checked exception). Know that system exceptions cause the bean to be discarded, application exceptions do not. Know what it MEANS to discard a bean:-- stateless session clients can still use their EJBObject reference (container just grabs a different one from the pool) -- stateful session beans will have to go back through the home again and start over -- entity beans can still use their EJBObject reference (the pool...) When you believe a client cannot recover from something that YOU caught in your bean code, throw an EJBException to the container. If you are throwing an application exception, then you must decide yourself whether the tx should be rolled back. Know the SCOPE of java:comp/env ---- it is per BEAN, not per JAR or application

Page 82 of 112

Page 83: J2EE Questions

-- Know that it is the bean's private environment. Understand:* Environment Entries-- if the bean provider coded one in, the provider MUST announce that in the DD -- the app assembler or bean provider can put in the value (probably the app assembler) but the Deployer MUST ensure that there is a value * be sure you know how the DD element matches what you put in code to access it.(java:comp/env/foo should be just "foo" in the DD, without the quotes) * Be sure you know the TYPES that an environment entry can be! Be sure you understand that tx attributes in the DD can be specified on a method-per-method basis, and KNOW what the elements look like for specifying a tx attribute. Be sure you understand how the wildcard "*" works for this. Know the DD tags for the security role references and roles Know what it means to access a bean from a bean:that you use an ejb reference. Be familiar with the DDelement, and how it maches the code;java:comp/env/ejb/Advice means: "ejb/Advice" in the DD -- know all the rules for the circumstances for load and store, etc.if you see ejbLoad, you know you are looking at an entity bean, and you know that the bean has already been populated with the state from the persistent store (because we are ONLY talking about CMP) -- I'm not going to go into the CMP stuff here (too much), so just be familiar with the way that CMP and CMR works!!!

Strategies for Dealing with RemoteException or EJBException in Client (Valentine)

Figure-2: Strategies for Dealing with RemoteException or EJBException in Client

What to Know from Syed AliRaza ZaidiSecurity: What other tags should be written in <run-As> tag ?Whose responsibility is to define security role refrence tag?What other tags can be in security refrence tag and security role tag?Whose responsibilty is to define security roles ?What should must be define in a deployment Descriptor to use isCallerInRole(string s) method? What type of object is returned by getCallerPrincipal() method?What class or interface contains Programmatic security methods?What is requirement for Programmatic Security?

EJB-QL:You should know how to write a queryYou should know whats illegal in EJB-QL query

Page 83 of 112

Page 84: J2EE Questions

You should know about WHERE , FROM , IN ,AS clausesYou should know about PathexpressionsYou should know about collectionsYou should know that ejbSelect<Methods>are written in bean class not in home interfaceYou should know that ejbFind<Methods> are written in home interfaceYou should know the difference between find and select methodYou should be aware of PrimaryKey field, class , typeYou should be aware of defining custom composite primary key class and the things it need to containYou should know that what variables should be part of both PrimaryKey class as well as the cmp bean?You should know about EJB-QL and Abstract Presistance Schema Entity Beans / Session Beans / MDB: You should know Life cycle of entiy beanMemorize sequence diagramsLearn them inside outtheir Limitation from SpecificationStatless beans in context of transactionStatefull bean and conversational state

Transactions:Know how to define CMT by using Deployment DescriptorKnow how to define BMTAll transaction attributes should be rememberedYou should know all things related to transactions and Exceptions

Exceptions : You should know the difference between two System and Application ExceptionsYou should know actions and effects of these exception on container transactionsYou should be able to identify the exceptions

Environment:You should know about JNDI-ENC and resources you can get from it

Kathy as a reply of a question

But your other questions: RMI -- This is covered on the exam only to the extend that you must know what it means to be 'remote'. For example, you must know that: * EJBObject and EJBHome both extend java.rmi.Remote, which is a marker interface (no methods to implement with Remote). * ALL methods in a remote interface MUST declare java.rmi.RemoteException * You must understand, but not know any details about, the fact that a stub class is generated from the implementation of the remote interface, and that the container is responsible for BOTH of the those classes -- the implementation of your remote interface

Page 84 of 112

Page 85: J2EE Questions

AND the stub made from that interface. (And of course this is true for both Home and Component interfaces) * You do NOT have to know about:* rmic* skeletons* how to 'export' a remote object* how to place the remote object in the naming service* the wire protocol, except you MUST know that you are to assume IIOP. Implication? You MUST 'narrow' the Home reference if it is a remote home interface.* that arguments and return types MUST be serializable if they are passed in or out of remote methods.

JNDI -- you do not need to know much about the JNDI API. But you must know: * What it means to get a JNDI Context and InitialContext.* How to do a client lookup (initialContext.lookup("foo"))* Most importantly, you must understand the bean's own JNDI environment (java:comp/env), which is the bean's own private space for looking up: 1) references to other beans (EJB references)2) resources, such as JDBC,(resource factory references)3) environment entrys (deploy-time customized values, like properties) Be sure you know EXACTLY how those things are used both in the deployment descriptor, and in code, and be sure you know WHICH EJB role is responsible for which part... for example, you must know that the deployer is responsible for *ensuring* that all environment entrys have a valid value, even though it is often the app assembler who puts in the value. And be sure you know that there are three levels of mapping for, say, configuring a database into the EJB app -- the database itself is configured into the server, then the factory reference is given a name in JNDI, and then a logical name (that may NOT be the JNDI name!) is used in code (this is the resource factory reference name in the DD), and that logical name must be mapped back to the *real* JNDI name, at deploy time.Sockets -- NOT part of the exam, except for you to know that ServerSockets are not allowed (i.e listening on a Socket) but that Sockets *are* allowed. But that's it. Assume that you will NOT be tested for knowledge of the Socket API.

Sample Questions

CQ1. Which of the following statements about business methods in a bean class is incorrect [choose 1]:A. The signature requirements for business methods are always the same for both session and entity beans.B. The argument and return types must always be legal types for the Java RMI API.C. The throws clause may include any exceptions defined by your application.D. A business method should always throw the javax.ejb.EJBException to indicate a system-level problem.

Page 85 of 112

Page 86: J2EE Questions

CQ2. Which of the following statements about Home methods in a bean class is incorrect for Container Managed Persistence [choose 1]:A: The method must not access relationships.B. The throws clause of the method may include the java.rmi.RemoteException.C. The method must not access the bean's persistence state.D. The method cannot be declared static.E. The throws clause may include any exceptions defined by your application.

CQ3. Which of the following are requirements for a message-driven bean [choose 4]:A. It implements the MessageListener and MessageDrivenBean interfaces.B. It implements one or more ejbCreate methods.C. It implements one onMessageReceived method.D. It must not define the finalize method.E. It implements one ejbRemove method.F. It must not have a remote or local interface.

CQ4. With CMP, the primary key for an entity bean may be automatically generated by the container if the entity bean meets certain requirements. Which of the following is true [choose 1]?A. In the deployment descriptor, the primary key class must be defined as a java.lang.Object. The primary key field must not specified.B. In the home interface, the argument of the findByPrimaryKey method must be a java.lang.ObjectC. In the entity bean class, the return type of the ejbCreate method must be a java.lang.Object.D. All of the above are requirements.E. None of the above are requirements.

Answer: CQ1-B, CQ2-B, CQ3-A, D, E, F CQ4. D

SQ1. Which are true about session beans? A. A client can pass a remote home object reference to another application. B. The javax.ejb.EJBMetaData interface is intended to allow application assembly tools to discover information about the session bean, and to allow loose client/server binding and client-side scripting. C. The javax.ejb.EJBLocalHome interface defines the method create() which returnsjavax.ejb.EJBLocalObject. D. The javax.ejb.EJBLocalHome interface defines the method remove(Object primaryKey)which returns null. SQ2. Consider the following session bean class: import javax.ejb.*;import javax.naming.*;import javax.sql.*;import javax.jms.*;public class MySessionBean implements SessionBean {private SessionContext sessionContext;

Page 86 of 112

Page 87: J2EE Questions

private Context jndiContext;private Queue queue;private UserDefinedClass userDefinedClass; public void ejbCreate() {try {queue = (Queue) jndiContext.lookup("java:comp/env/jms/StockQueue");} catch (NamingException ne) {throw new EJBException(ne);}userDefinedClass = new UserDefinedClass();} public void ejbRemove() {...}public void ejbActivate() {...}public void ejbPassivate() {...} public void setSessionContext(SessionContext sessionContext) {this.sessionContext = sessionContext;try {jndiContext = new InitialContext();} catch (NamingException ne) {throw new EJBException(ne);}} public class UserDefinedClass {String dummy;private DataSource dataSource;public UserDefinedClass() {try {dataSource = (DataSource) jndiContext.lookup("java:comp/env/jdbc/MyDB");} catch (NamingException ne) {throw new EJBException(ne);}}}} Which of the following are true about the conversational state? A. The state of the variable sessionContext is kept after passivation/activation. B. The state of the variable jndiContext is kept after passivation/activation. C. The state of the variable queue is kept after passivation/activation. D. The state of the variable userDefinedClass is kept after passivation/activation. E. The container must be able to properly save and restore the reference to the home and component interfaces of the EJBs stored in the instance¡¦s state even if the classes that implement the object references are not serializable. F. The container may use the object replacement technique (java.io.ObjectOutputStream/ObjectInputStream) to externalize the home and

Page 87 of 112

Page 88: J2EE Questions

component references. SQ3. Which are true about session beans? (Choose all that apply) A. An attempt to remove a session object while the object is in a transaction will cause the container to throw the IllegalStateException to the client. B. A session bean class must not implement the session bean's component interface. C. A session bean class must not implement the ejbCreate() method. D. The business methods of a session bean must not be declared as final or static. E. The remote interface methods must not expose the managed collection classes that are used for CMP entity beans as arguments or results. SQ4. Given a CMP entity bean, which of the following statements are correct?(Choose all that apply) A. All the exceptions defined in the throws clause of the method of the remote interfacemust be defined in the throws clause of the matching method of the enterprise Bean class. B. The ejbSelect<METHOD>(...) must not be declared as static or abstract. C. The ejbHome<METHOD>(...) can be declared as final. D. The return value type of a business method of an entity bean class could be of MyClass definedas follows:public class MyClass {public int result;public int getResult() { return result; }public void setResult(int result) { this.result = result; }} E. The throws clause of an ejbPostCreate<METHOD>(...) may definearbitrary application specific exceptions including javax.ejb.CreateException. F. The bean provider must always define a query for each finder method in the deployment descriptor. SQ5. Which of these is/are correct about exception? (Choose all that apply) A. When a RemoveException is thrown from the ejbRemove() method of an entity beanwhere the corresponding remove() method has CMT attribute Mandatory,the client will receive this RemoveException. B. If the Container denies a client access to a business method, the client willreceive RemoteException or EJBException. C. When a NoSuchObjectException is thrown from an ejbHome<METHOD>(...) method of an entity beanwhere the corresponding home method has CMT attribute RequiresNew,the client's transaction if any must be marked for rollback. D. When a system exception is thrown from the onMessage() method of a MDBwith BMT, any transaction that has been started, but not yet completed, by the instancemust be marked for rollback. Answer: A, B, DFor option A: RemoveException is application exception, ejbRemove() runs in the context of the caller's transaction, so container will re-throw the exception to the client, thus client can receive RemoveException.For option B: Although ejbRemove() runs with unspecified transaction context, but client can still receive RemoveException.

Page 88 of 112

Page 89: J2EE Questions

For option C: NoSuchObjectException is system exception, only container-started transaction will be rollbacked, the client transaction may or may not be marked for rollback.For option D: when system exception is generated from MDB's bean method with BMT, the container will log the exception and mark for a rollback a transaction has been started, but not yet completed, and discard the instance.SQ6. Which are true about EJB environment? (Choose all that apply) A. A resource manager connection factory reference is scoped to the EJB whose declarationcontains the resource-ref element. B. By default, connections to a resource manager are shareable across other EJBsin the application that use the same resource in the same transaction context. C. The Deployer must ensure that all the declared resource environment references are bound toadministered objects that exist in the operational environment. The Deployer may use, forexample, the JNDI LinkRef mechanism to create a symbolic link to the actual JNDI name ofthe target object. D. The Deployer should be able to customize an EJB's business logic. SQ7. Which is/are true about security responsibilities? (Choose all that apply) A. The Deployer is responsible for configuring principal mapping for inter-EJB calls.The management of caller principals passed on inter-EJB invocations is set up by the Deployer and System Administrator. B. Security roles are defined by the Bean Provider in the deployment descriptor. C. The EJB Container can, but is not required to, provide support for multiple security domains, and/or multiple principal realms. D. If the client is in a different security domain than the target enterprise bean, the system administrator is responsible for mapping the principals used by the client to the principals defined for the enterprise bean. SQ8. Which is/are true about ejb security? (Choose all that apply) A. If the security infrastructure performs principal mapping, the getCallerPrincipal() method must return the original caller principal. B. If the run-as security identity is set up for the bean, its method getCallerPrincipal()returns the principal that corresponds to the run-as security identity. C. If transactional requests within a single transaction arrive from multiple clients, all requestswithin the same transaction must be allowed to be associated with different security context. D. The Container must allow multiple-deployed enterprise beans to co-exist at runtime.============================

APQ1. Given a database table:

code:

Page 89 of 112

Page 90: J2EE Questions

EmpID Salary FirstName LastName Gender DepartmentID101 40000 'George' 'Smith' 'M' 'SUP'102 22000 'Sally' 'Jones' 'F' 'PLN'103 25000 'Bob' 'Smythe' 'M' 'MRK'104 60000 'Julie' 'Rodriguez' 'F' 'IT'

Employee has a 1:1 unidirectional relationship with department. What would be the correct EJB-QL query for the following finder method? (select one): java.util.Collection findSalaryInDepartment(int minSalary, DepartmentLocal dep) throws FinderException;

A.==SELECT emp.salaryFROM Employee AS empWHERE emp.salary > ?1 AND emp.department = ?2 B.==SELECT emp.salaryFROM Employee AS emp

WHERE emp.salary > ?1 AND emp.departmentID = ?2 C==SELECT DISTINCT emp.salaryFROM Employee AS empWHERE ?1 < emp.salary AND ?2 = department D==SELECT DISTINCT emp.salaryFROM Employee AS empWHERE ?1 < emp.salary AND ?2 = departmentID E==These are not valid finder queries.

Which two must be included in every ejb-jar file? (Choose two.)a). Stubs for the EJBHome and EJBObject interface.b). The JAR Manifest file.c). A deployment descriptor.d). The JNDI context.e). The EJB's home interface.

Answer: e

Page 90 of 112

Page 91: J2EE Questions

KQ1. Given this code in a stateful session bean business method:

try {Socket s = new Socket(x,y);} catch (Exception ex) {ex.printStackTrace();} And assuming that x and y are the port and IP address of a running service running on the same server, what is the result? (Assume all other bean code is correct and legal.)

A) Compilation failsB) Deployment failsC) An exception is thrown at runtimeD) Code compiles, deploys, and runsE) Indeterminate. The code may deploy, but is not guaranteed to be portable to all EJB 2.0 containers.[Hint: Look in section 24.1.2 of the spec]Answer: So, what is this question looking for? Your knowledge of the programming restrictions. You'll see other questions testing your knowledge of what is and isn't allowed. But rather than simply asking: Is <some thing> allowed? The questions will offer scenarios or code examples. Don't panic that this question assumes knowledge of the Socket API -- I figure you all know it (or can look it up); rest assured that the real exam will not include questions that require API knowledge about things unrelated to J2EE, unless it has been covered in the SCJP exam. (So, I might take a few liberties with my mock exam questions, that wouldn't be on the *real* exam. I'll let you know if and when I do that.) Look in section 24.1.2 of the spec

KQ2. Which two are guaranteed to be restored to their pre-passivated state when a passivated stateful session bean is activated with an ejbActivate() call? (Choose two.) A) A reference to a non-serializable SessionContext object. B) A reference to a UserTransaction object. C) A transient reference variable. D) A JDBC connection. [hint: look in section 7.4 of the spec]

Answer: KQ1. DKQ2. A, B. Since the container is *required* to successfully passivate/activate a SessionContext reference, even if the reference is to a non-serializable object.

KQ3. Match the operation in list ONE with the method in list TWO in which that operation can be performed, for a stateful session bean:

LIST ONE: Operations (things you want to do)

Page 91 of 112

Page 92: J2EE Questions

1) invoke the SessionContext.setRollbackOnly() 2) invoke the UserTransaction.setRollbackOnly() 3) access this bean's own EJBObject interface 4) access this bean's own home interface 5) access a reference to another EJB

LIST TWO: Bean methods in which the operations from list one can be performed: A) ejbCreate B) afterBegin C) business method D) setSessionContext E) afterCompletion Note: There *may* be more than one correct answer!

Answer By Andrew:1. J) client invokes create on the home2. I) bean constructor invoked3. H) setSessionContext invoked on the bean4. B) ejbCreate invoked on the bean5. A) Client invokes a business method6. E) afterBegin is called7. G) business method invoked on the bean8. F) beforeCompletion is called9. C) transaction committed10.D) afterCompletion is called KQ4. In what order will the following events in a stateful session bean's lifecycle occur? Assume the client already has a reference to a bean's home object, and needs to invoke a business method on a bean. (place a number next to each one) A) Client invokes a business method B) ejbCreate invoked on the bean C) transaction committed D) afterCompletion is called E) afterBegin is called F) beforeCompletion is called G) business method invoked on the bean H) setSessionContext invoked on the bean I) bean constructor invoked J) client invokes create on the home

KQ5. Here is an example of the way transaction attribute questions appear on the exam:

Assume that the image describes method invocations and shows the transaction context in which each of the methods will run. Assuming that all methods run without exception, which of the following shows transaction attributes that will produce this scenario?

Page 92 of 112

Page 93: J2EE Questions

(In the diagram, a ___ indicates that there is no transactional context for the method)

Answer options:A) Method R - RequiresNewMethod S - SupportsMethod T - RequiredMethod U - NotSupportedMethod V - SupportsB) Method R - MandatoryMethod S - RequiredMethod T - MandatoryMethod U - NotSupportedMethod V - NeverC) Method R - RequiresNewMethod S - MandatoryMethod T - SupportsMethod U - NeverMethod V - NotSupportedD) Method R - RequiresNewMethod S - MandatoryMethod T - RequiredMethod U - SupportsMethod V - Supports

KQ6. Which two are true about message-driven beans? (Choose two.) A) Message-driven beans do not expose a client view.B) Message-driven beans must implement the JMSListener interface.C) Message-driven beans cannot throw application exceptions.D) Message-driven beans must not use bean-managed transaction demarcation.E) Message-driven beans can use the getCallerPrincipal() method of MessageDrivenContext.==================================== KQ6B. Which transaction attributes can be specified for a message-driven bean? (Check all that apply, from none to all) A) RequiredB) RequiresNewC) SupportsD) NotSupportedE) MandatoryF) Never

KQ7: Which three are true about transactions in EJB? (Choose three.) A) EJB 2.0 supports nested transactions. B) EJB 2.0 allows you to specify isolation levels.

Page 93 of 112

Page 94: J2EE Questions

C) Message-driven beans must not use bean-managed transaction demarcation. D) Entity beans must not use bean-managed transaction demarcation. E) Stateful session bean state will not be rolled back if the transaction rolls back. F) Stateful session beans that start a transaction must complete the transaction before ending a business method. G) A message-driven bean must commit or rollback a transaction before onMessage returns.

KQ8: Which two are true about bean-managed transaction demarcation? A) A transaction used by a BMT bean MUST have been started by the bean. B) The caller's transaction will be propagated into a BMT bean. C) Transactions in a BMT bean do not propagate when the BMT bean calls a method on another bean. D) A bean cannot use both CMT and BMT together. E) BMT beans must not specify transaction attributes.

Answer: KQ7. D, E, G KQ8. D, E

Kathy - 5 (posted May 22, 2003 12:23 PM) as answer

KQ9. "Which three types of methods are you required to implement in a Session Bean?"

Answer: 1) Methods of the SessionBean interface (which your bean must implement) 2) Business methods from your COMPONENT INTERFACE.(all business methods defined in your component interface must be implemented. Otherwise, the poor client will call x.doReallyImportantStuff() and when the container gets the call, it (the container) will completely freak out because your bean class can't do it!)(yes, most deploytools will stop you from getting that far, but there's no guarantee...) 3) ejbCreate methods from your HOME INTERFACE(a matching ejbCreate for every create in your home)

KQ10. "What does ejbPassivate mean to a SessionBean and to an EntityBean?"

Answer:

"For a SessionBean, it means the bean MUST be stateful, and is about to be... passivated, which means taken out of RAM to preserve resources while we wait for the client to make up his mind and add something else to the shopping cart... at which time the container will say, "Whoa! Somebody's calling a business method again; I better get this bean re-activated.Remember: stateless beans are NOT passivated. They just go back to the pool, so they are not consuming any resources on behalf of a client EXCEPT when the client is in the middle of a business method invocation on the bean." "For an EntityBean, it means the bean is going to be put back into the pool, losing his identity as a particular entity. In other words, his 'state' will be *erased* as he slides back

Page 94 of 112

Page 95: J2EE Questions

to the pool without a care in the world... and no primary key... ready to sip umbrella drinks and cavort with the other beans in the deep end until the container realizes that , 'Hey, somebody is trying to access Gus T. with a primary key of 42, so we better pull a bean out so that it can *become* Gus T.' at which time, the bean will be reactivated."

BQ1. Which two are guaranteed capabilities of EJB 2.0?a). Local home interfaces for messages driven beans.b). Dirty detection mechanisms to reduce memory footprints.c). Run-as security identity functionality. d). The JDBC 2.0 extension.e). Read only CMP entity beans.

BQ2. Which API is NOT guaranteed to be supported by EJB 2.0 containers?a). JAXPb). JNDIc). JXTAd). JDBCe). JMS

BQ3. When programming business methods, which technique should be avoided to ensure bean portability across all EJB 2.0 containers?a). Using the java.net.Socket class.b). Using inner classes.c). Using the 'final' modifier for fields.d). Passing 'this' as an argument.

BQ4. Which two are typically responsible for creating ejb-jar files? (Choose two.) a). The bean provider.b). The application assembler.c). The deployer.d). The system administrator.

BQ5. Which two must be included in every ejb-jar file? (Choose two.)a). Stubs for the EJBHome and EJBObject interface.b). The JAR Manifest file.c). A deployment descriptor.d). The JNDI context.e). The EJB's home interface.

Answer: BQ1. C, D BQ2. C BQ3. D BQ4. A, B BQ5. C, E

BQ6. Which statement about session beans is true? a). The bean provider must write the method public void remove() in both stateless and stateful session classes.b). Local clients can remove session beans by calling a method on the bean's home.

Page 95 of 112

Page 96: J2EE Questions

c). The << remove >> method in the component interface can be used only by remote clients.d). To ask the EJBHome to remove a session bean, the client must provide the bean's handle. Answer: drevision: 2c was << ejbRemove >> BQ7. Which statement about locating or using a session bean's home interface is true? a). Acquiring an 'InitialContext' is required only for remote clients.b). The 'InitialContext' must be narrowed before it can be used.c). Once acquired by a client, a home interface can be used multiple times.d). The client can acquire a handle for the bean's local home interface. Answer: c BQ8. When comparing two session objects, what is true? (Choose all that apply.) a). Using the 'isIdentical' method, stateless session beans from the same home will always return true.b). Using the 'isIdentical' method, stateful session beans from the same home will always return true.c). The 'isIdentical' method can be used only for remote object references.d). Using the 'equals' method, stateless session beans from the same home will always return true.e). Using the 'equals' method, stateful session beans from the same home will always return true. Answer: a BQ9. Which method can be called << without exception >>, by both remote and local clients on a reference to a session bean's component interface? a). ejbCreateb). getSessionContextc). getPrimaryKeyd). getEJBHomee). remove Answer: erevision: added 'without exception' BQ10. Which are directly invoked by the client? (Choose all that apply.) a). ejbPassivateb). business methodsc). setSessionContextd). newInstancee). create Answer: b, e

BQ11. Which is true about passivation for stateful session beans? a). The container can passivate a stateful session bean regardless of the bean's << transactional >> state.b). The client can passivate a session bean.c). References to JNDI contexts are lost during passivation.d). References to 'SessionContext' are preserved during passivation.

Page 96 of 112

Page 97: J2EE Questions

e). A passivated, stateful session bean instance will always be re-activated prior to removal. Answer: drevision: 3.2.a - added << transactional >> BQ12. Match the methods on the left with the interfaces in which those methods can be found, on the right. A match is correct if the method is either declared in, or inherited by, the interface. Note: There may be some many-to-one and one-to-many relationships in your answer.code:

a). afterCompletion 1. SessionSynchronization b). getUserTransaction 2. SessionContextc). afterBegin 3. SessionBeand). isCallerInRole 4. UserTransactione). getRollbackOnlyf). setSessionContextg). setRollbackOnly << new method !!!!!!! >>

Answers: a - 1b - 2c - 1d - 2e - 2f - 3 << answer for new method g - 2,4 >> revision: added a new method BQ13. Which statements about stateful and stateless session beans are true?(Choose all that apply.) a). Only stateful session beans support transactions.b). Only stateful session beans can be passivated.c). Only stateful session beans have a 'setSessionContext' method.d). Both stateful and stateless session beans can support overloaded 'ejbCreate' methods.e). Both stateful and stateless session beans can implement the 'javax.ejb.SessionSynchronization' interface.f). Both stateful and stateless session beans can have instance variable state. Answer: b, f BQ14. Which statements about a session bean class are true? (Choose all that apply.) a). They can be marked 'final'b). They can support overloaded constructors.c). Their business methods can be 'private'.d). Their business method names must start with "ejb".e). Their 'ejbCreate' methods must not be declared as 'final'. Answer: e

Page 97 of 112

Page 98: J2EE Questions

BQ15. For this drag and drop type question, you can use each element only once. Which interface should be matched with which fact, so that all four matches are correct?code:

1. remote component a. does not have a getHomeHandle() method2. remote home b. extends 'javax.ejb.EJBObject'3. local component c. methods must NOT throw 'java.rmi.RemoteException'4. local home d. can be used to retrieve an EJBObject reference.

Answers: 1 - b2 - d3 - a4 - c BQ16. Which two are true about container managed transactions in EJB 2.0? (Choose all that apply.) a). Differentiating between overloaded methods is possible in the bean's deployment descriptor.b). A transactional attribute must be individually declared in the method-name tag, for every business method in the bean class.c). The container will interpose only on method invocations with container-managed transaction demarcation.d). If an 'onMessage' method returns before committing a transaction the container will throw an exception.e). A message-driven bean with CMT demarcation must not invoke the EJBContext.getUserTransaction method. Answers: a, e BQ17. When a business method in an entity bean calls the getRollbackOnly method, which transaction attribute settings will cause the container to throw an exception? (Choose all that apply.) a). NotSupportedb). Requiredc). Supportsd). RequiresNewe). Mandatoryf). Never Answers: a, c, f BQ18. When a session bean has container-managed demarcation value of 'Supports', which << three >> methods run in an unspecified transaction context? (Choose << three >>.) a). ejbActivateb). getRollbackOnlyc). getUserTransactiond). ejbRemovee). afterBegin

Page 98 of 112

Page 99: J2EE Questions

f). afterCompletion Answers: a, d, f revision: changed 'two' to 'three' Ashik's Questions

AQ1. Find out two true statements from the following.A) Rearly used data should be represented as entity bean.B) Session beans should be used for transaction controlled business logic.C) Session Beans are good for logic that's shared outside of the limited context of a single application.D) It's a good practice to put business logic into data objects.E) Stateful session beans may serve many clients during their lifetime.F) Entity beans may not have a unique property.

Answer: B, C

AQ2. Performance tuning of the whole EJB system is the responsibility of - A) Bean ProviderB) Tool VendorC) Application AssemblerD) EJB DeployerE) System AdministratorF) Container and Server Provider Answer: D

AQ3. Find out two false statements from the following. A) A message-driven bean is decoupled from any client that sends message to it.B) Message-driven beans do not hold conversational state or in other words MDBs are stateless.C) Message-driven beans can be both durable or nondurable subscribers.D) Message-driven beans may not send exceptions back to teh client.E) Message-driven beans do not have any home, local home or local interfaces but only remote interface.F) Message-driven beans may be single-threaded or multi-threaded. Answer: E, F.

JK1. Which of the following EJB Transaction Attributes ensures that the method call always takes place in a transaction, either client started, or container started? a TX_SUPPORTS b TX_MANDATORY c TX_REQUIRED d TX_REQUIRES_NEW Answer: C, D

Page 99 of 112

Page 100: J2EE Questions

GZ1. Which methods can't have transaction attribute (Choose all apply)

1. onMessage() for MDB2. remove() for session bean's javax.ejb.EJBObject3. business method defined in session bean's component interface.4. method defined in session bean's home interface.5. method defined in super interface of entity bean's component interface.

Answer: 4

SPQ1. While of the following can be included in the conversational state of stateful session beans: (choose four) 1 SessionContext2 EJBContex3 Transient variables4 Handle5 EJBHome6 EJBObject Answer: SPQ2. When a client closes a connection obtained from the connection pool, which of the following occurs? 1. The connection is permanently closed 2. The connection is never closed - simply returned to the pool 3. The connection is closed, but reopened and returned to the pool 4. Impossible to tell for sure with the given information Answer: 2Which one can be defined as an application exception?A.EJBExceptionB.IOExceptionC.RemoteExceptionD.NoSuchObjectExceptionAnswer: B APQ1. We have a Stateless Session Bean defined and minimum/maximum pool size variables in the container is set to 1. Which of the two is true? 1) The bean instance could be used as a Singleton - each time we request a new bean we will get the same instance. 2) The bean instance can't be used as a Singleton - the EJB spec does not guarantee that the pool will not be cleared and bean instance re-created at some stage. Answer: B

Page 98 of 98

1. What is JNDI?The Java Naming and Directory Interface (JNDI) is an application programming interface (API) for accessing different kinds of naming and directory services. JNDI is not specific to a particular naming or directory

Page 100 of 112

Page 101: J2EE Questions

service, it can be used to access many different kinds of systems including file systems; distributed objects systems like CORBA, Java RMI, and EJB; and directory services like LDAP, Novell NetWare, and NIS+.JNDI provides two APIs and one SPI. JNDI has a naming API that allows Java applications to access naming systems like CORBA's Naming services and a directory API that extends the naming service to provide access to directory services like LDAP. JNDI also has a SPI (Service-Provider Interface) which is a programming model that vendors use to write JNDI plug-ins or implementations for their specific product.

2. What's a Naming System or Service?

A naming system associates names with addresses. A phone book is a perfect example of a naming system that associate people's names with phone numbers and addresses. Naming systems are used in computing to make it easier for user to locate and utilize software that is addressable. A software system that exposes a naming system to other software is called a naming service.

3. What are the principal technologies of the J2EE platform?

The principal technologies which constiture the J2EE platfom are:

Enterprise JavaBeans JavaServer Pages Servlets Java Naming and Directory Interface (JNDI) Java Interface Definition Language (IDL) JDBC Java Message Service (JMS) Java Transaction API (JTA) Java Transaction Service (JTS) JavaMail RMI-IIOP

4. What is a CMP bean?A CMP bean is an entity bean whose state is synchronized with the database automatically. In other words, the bean developer doesn't need to write any explicit database calls into the bean code; the container will automatically synchronize the persistent fields with the database as dictated by the deployer at deployment time.

5. What is a BMP bean?A BMP bean is an entity bean that synchronizes its state with the database manually. In other words, the bean developer must code explicit database calls into the bean itself. BMP provides the bean developer with more flexibility in the how the bean reads and writes its data than a container-managed persistence (CMP) bean. CMP bean is limited to the mapping facilities provided by the EJB vendor, BMP beans are only limited by skill of the bean developer.

6. A local home or component interface for an EJB can only be used by:  A. Another EJB   B. A web-tier client   C. A business logic-tier client   D. A client located in the same JavaTM Virtual Machine (JVM)1

answer D

7. Local interfaces have declarative:  A. Transactions and security

Page 101 of 112

Page 102: J2EE Questions

  B. Transactions only   C. Security only   D. Neither, for performance reasons

Answer A

8. An entity in a unidirectional relationship that is the target of a role with a cmr field:  A. Must have local home and component interfaces   B. Must have remote home and compnent interfaces   C. May have either local or remote interfaces, but not both   D. May have any combination of local or remote interfaces

Answer A

9. An entity in a unidirectional relationship that is the source of a role with a cmr field:  A. Must have local home and component interfaces   B. Must have remote home and compnent interfaces   C. May have either local or remote interfaces, but not both   D. May have any combination of local or remote interfaces

Answer D

10. The bean class for an entity that uses the EJB 2.0 model of container-managed persistence:  A. Must implement java.io.Serializable   B. Is only used for better integration with popular IDEs   C. Must be abstract   D. Must not be abstract

Answer c

11. The legal collection class type(s) to represent a many-valued relationship are:  A. java.util.Collection only   B. java.util.Collection and java.util.Set   C. java.util.List, java.util.Set, and java.util.Map   D. java.util.Map only

Answer b

12. If you call a "set" abstract accessor for a cmr field, it can:  A. Throw a java.sql.SQLException   B. Automatically cascade delete an entity   C. Automatically change the value of cmr fields in up to three additional beans   D. You can never call an abstract accessor

answer c

13. You can only specify cascade-delete on a relationship role if:  A. The role has a multiplicity of 'One'   B. The other role in the relationship has a multiplicity of 'One'   C. The role has a multiplicity of 'Many'   D. The other role in the relationship does not already use cascade-delete

answer B

Page 102 of 112

Page 103: J2EE Questions

14. If an entity has a relationship to another entity, it must:  A. Declare that entity reference in the deployment descriptor using the <ejb-ref> element   B. Declare that entity reference in the deployment descriptor using the <ejb-local-ref> element   C. Declare that entity reference in the deployment descriptor using the <ejb-link> element   D. No entity reference declaration is required

answer D

15. The bean developer must be cautious when iterating over a relationship collection class, because:  A. Concurrent transactions can modify the values   B. Changes to its contents can violate foreign key constraints in the database   C. Changes to its contents can trigger a referential integrity change to the collection class itself   D. The container developer is not required to support the Iterator class's next method

answer C

16. The EJB 2.0 specification introduces ejbSelect methods. These are:  A. Abstract methods in the bean class that call a query   B. The local home interface equivalent of a finder method   C. Methods in the component interface that call a query   D. A method that allows the bean developer to choose between a local and remote interface

answer A

17. The new EJB Query Language (EJB-QL) has three clauses: select, from, and where. Of these:  A. Only the from clause is mandatory   B. Only the select and from clauses are mandatory   C. Only the where clause is mandatory.   D. All clauses are mandatory.

answer B18. In EJB-QL, date and time literals are represented by:  A. A string in the format MM-DD-YYYY HH:MM:SS +MILLISECONDS   B. A string in a locale-determined format   C. A string in a vendor specific format   D. A long value that represents a millisecond count, such as 979837813000

answer D

19. The type of interface (local or remote) returned from an ejbSelect statement can be:  A. Specified in the query   B. Specified in the deployment descriptor   C. Specified by the client   D. Is always a local interface

answer B20. The functions available for use in the where clause of an EJB-QL query are:  A. All functions defined in standard SQL   B. All functions defined by the target database   C. All functions with defined escapes in JDBCTM 2.0   D. A limited subset of the functions defined for JDBC 2.0

Page 103 of 112

Page 104: J2EE Questions

answer D

21. difference between javabeans and ejb

JavaBeans components are small-grained application bits. You can use JavaBeans to assemble larger-grained components or to build entire applications. JavaBeans, however, are development components and are not deployable components. You typically do not deploy a JavaBean because a JavaBean is not a complete application; rather, JavaBeans help you construct larger software that is deployable. And because they cannot be deployed, JavaBeans do not need a runtime environment in which to live. JavaBeans do not need a container to instantiate them, to destroy them, and to provide other services to them because the application itself is made up of JavaBeans. By way of comparisonThe Enterprise JavaBeans (EJB) standard defines a component architecture for deployable components called enterprise beans. Enterprise beans are larger, coarser-grained application components that are ready to be deployed. They can be deployed as is, or they can be assembled with other components into larger application systems. Deployable components must be deployed in a container that provides runtime services to the components, such as services to instantiate components as needed.

22. Web Server and Application ServerWebserver is for hosting ur webapplications (Servlets and jsps). Applicationserver is server which provides services like transactions, security,messaging, and other j2ee services like jndi etc to the application. Theapplications can be built using ejb which use all the declarative services,which minimizes the lines of code and reduces the application development time.

WebServer is a service or a daemon running at a given IP and a Port that is capable of accepting and responding to all HTTP events. It is created to understand the HTTP transfer protocol. The basic functionality of a WebServer is to accept a browser request for HTML pages and respond it with the resources in it. To completely understand a webserver, i will suggest, write your own webserver. Dont get scared. Writting a webserver using java is no big deal.

Creating your own WebServer

* Create a Server Socket using the ServerSocket class.* Configure it to accept requests at a default HTTP port that is port 80.* Once a connection is established and a request is send, read the HTTP header in the request. * From the HTTP header, do normal parsing using StringTokenizer, and you can get the filename that is requested.* Once u get the filename, open a filestream and read the file into some DataOutputStream object.* Write this object over the open connection.* Now Flush the data. This is the most basic HTTP server that can be written in JAVA. I did this long time back, let me know if you require code, i ll try finding it in my old backups.Over this basic functionality you can build a better and powefull WebServer.For instance you can start with using threads to support more requests. You can set unset session id to track Sessions. You can Read the MIME type in the header to respond to various file formats like JPEG, MPEG, GIF etc. And other things. So now you understand what a web server is.

A WebServer is a service running on some remote machine that can communicate with your webBrowser and fetch you files using HTTP protocol.

And thats it, nothing more nothing less. For instance IIS and Apache are webServers. Though they do many other things then serving webpages. But that is not a part of a simple webServer.

Page 104 of 112

Page 105: J2EE Questions

Applicatin server. Anything u know abt app servers minus the defn of the web server that i just stated is the job of an application server. An application server executes an application code written in some language and bundles the results in form of HTTP response, which can be send over wire by the HTTP Web Server. (Dont get confused). For instance IIS is a combination of both application server as well as web server. The webserver part is supposed to deal with the browser sending and receiving request and response objects using the HTTP protocol. The application server is responsible of doing all the processing work, executing scripts, accessing the database, bla bla.. Today's Application servers evolved long way back from there ancistors -> CGI or common gateway interface. Though CGI are not true app server as per todays defn of application servers, but it provides a backbone for the application technology that is build in the middleware.

So to make the discussion short, lets define application server

An Application server is a service or daemon running on some remote machine that communicates with the WebServer using HTTP protocol and hosts a range of services and applications. Not to explain, these services can be anything like ACLs, Object pooling, Transaction management, etc etc.

A noteworthy difference betn the two is webservers communicate with the Browser, where as app server communicate with the webServers. Here u can very well question "but y so" ?

The ans is simple. Let me give you one eg, and things will be clear.In 1 of my project we had the following congifuration. We used the Weblogic server, providing its service at 7001 port. This is where our application(JSP, EJB, Servlets etc etc) was hosted. Then we had a IIS server providing service on 80 port. So if i connect http:\\www.mysite.com\index.html, the index.html page will be served directly by the IIS server. Now we had a configuration in IIS server which stated that all the application related requests be directed to the WebLogic server. So wheneveer IIS gets a request asking for *.jsp, *.class (say http:\\www.mysite.com\index.jsp) it gets routed to WebLogic app server. WL will get the request object, execute the script, create the response object and dump it back to IIS. IIS will wait till it receives a response from  WL or till timeout occurs. On response it will just fwd it to the browser.

This architecture clearly differentiates the app server from the web server. Most of the app servers also bundle a webserver with them. That is, they behave as a single web+app server. So we dont understand the difference betwn the dual role. (above architecture is used in many scenarios, but detailed explaination is out of the scope of this discussion.)

One last thing. we can summarize by saying that serving files is the job of an webserver. And serving appliactions is the job of app server. Remember, we can access the application sevices without using the HTTP protocol. HTTP protocol was specifically created for web servers. If you have used WebLogic, there is something called as T3 services. This is the application protocol that gives you access directly to the app server services. We had an application that accessed WL directly using t3 to get the job done. (again detailed explaination of t3 or app protocols is out of the scope of this discussion)

23. When weblogic is bundled with a web server why did you choose IIS ??

Consider this scenario: You have a enterprise with heterogenious environment. Say you have a massive flight reservation portal, which is using the same database. But one of its module(say Schedule search) is implemented by some third party vendor. Now this vendor is using ASP to create his part of the portal. Rest of the team is using JSP and J2EE as the Enterprise standard. Parent company cannot force the third party vendor to convert his code into JSP. What will you do in this case?  There are 2 solutions to this problem. 

Page 105 of 112

Page 106: J2EE Questions

Solution 1: One solution is to use webServices. In which the complete search module is created and deployed as a single webService component, so that any other application can talk thro it using SOAP protocol. But is it really feasible(time wise and cost wise)? actually depends on the scope..sounds scary, isnt it !!

Solution 2: I will simply use a common webserver say IIS webServer. Now i will configure 2 ips (proxies) in this webserver. First one will be the 3rd party server hosting my search engine and the second one will be my enterprise server hosting rest of the portal. Once i plugin these components, i will configure there properties, which will say: Any ASP type request that i get on my webServer be directed to the IP of the 3rd part vendor. All other requests(JSP, class etc) be directed to my weblogic server.

Now say for instance I need to add a server hosting some functionality in PHP or some other scripting language, what do i do? U got it ! I will install a IIS plugin for that server and configure IIS to redirect all PHP requests to the new server.

24. How to do all these configurations ?

Not a big deal. With every appserver you use, u generally get a file IISProxy.dll. Go in IIS options, just point to that file and key in all your properties there.

I will find the webServer code and mail you ASAP. Though its not a complete WebServer, but it can still fetch you plain HTML. Let me search my old back up CDs

25. we have 1000 rows in the db and if each instance of ejb represents onerow,how many instanes of ejb are created at startup.It is assumed that there are 1000 rows at startup.

For the stateless session, entity, and Message Driven EJB's you can specify the "initial-beans-in-the free-pool". Its default value is 0. Weblogic Server populates the free pool with the specified number of bean instances for every bean class at startup. The container creates the instance using newInstance() method and then invokes the setEntityContext() method to pass the instance a reference to the EntityContext interface.The instance is now, in the available pool, the instance is not associated with any particular entity object identity (record ). All instances in the pool are considered equivalent, and therefore any instance can be assigned by the container to any entity object identity. The number of bean instance is not related to the number of entity object. An Entity Object may exist before the container and the entity beans are deployed.

When Client request comes the container will take a bean instance from the available pool and associate it with the particular Entity Object. If there is no free instance are available contain may create new bean instance and bind it with the particular Entity object.

26. Performance?

Entity beans are more costly then Session beans for one simple reason that Entity beans are special types of Session beans(Entity beans are build over session beans). One point to note is that Entity beans never store any state like statefull beans (They are database persistant and not memory persistant like StateFull beans). For every call or for any update or for any operation it will query the database. Now again there are two considerations in entity beans, CMP and BMP. A project coded using Session beans will any time perform better then BMP's. So the level of performance can be listed in the order of best to worse (in case of database operations)

1.Session Beans  2.BMPs  3.CMPs

Page 106 of 112

Page 107: J2EE Questions

U may consider this before u make any decision. In one of my project we had to drop the CMP design at the last moment because of the speed consideration. Entity type beans are ment as a better s/w design practice and not ment for a better performance. You should consider a tradeof, may be by using BMP's.

27. what are some of the java utilities that you cannot use in EJBs?

awt,I/O,sockets and multithreading

28. Container-Managed vs Bean-Managed Persistence1. speed. You can avoid some of the unnecessary container initialized databases calls, if you use

BMP's2. In CMP, the developer uses the deployment descriptor to tell the container which attributes of the

entity bean to persist.

Bean-Managed persistence gives the developer explicit control of the management of a bean instance's state.

The main advantage of BMP is Database Acess Flexbility ,

LOng back i read that BMP has acts as an interface to complex legacy SQL databases via JDBC and also enterprise data sources such as CICS, MQ-Series e.t.c.,

Disadvantage of BMP is writing the hard program for all callback methods by us ..

3. For example with BMP, it takes two SQL stements to load an entity bean. the first call- a finder method ( loading only the primary key ) and a second, during ejbLoad() to load the actual data. A collection of n BMP requires n+1 database calls to load that data.(one finder to find a collection of primary keys, and then n loads).

With CMP, the container can reduce the n+1 database calls to a single call, by performing one giant SELECT statement. You set this up using container specific flags."

You can refer "Matering Enterprise Java Beans" second edition Ed Roman.

The container cannot do the same sort of sql optimization for BMPs for the simple reason that thecontainer has no control over the sqls. One of the main disadvanteges of CMP is that you can'tcall Stored Procedure from CMP.

will go for BMP in the following cases:

1.My persistent data is in non-RDBMS and the EJB container does not support this.2.The database schema does not map exactly to Entity fields.3.For better performance I would like to use Stored procedure.4.I want to manage relationship between entities for which I need to use BMP (This is solved by using EJB 2.0 but for preEJB 2.0...)5.I have my data from different tables or databases.

29. Is session bean a coarse grained bean??YES, session beans are coarse grained bean. Entity beans are fine grained beans.

Actually it depends on how you use them. You can have design in which even Session beans can behave as fine grained beans. One eg. of coarse gained session... Instead of accessing entity beans directly, many a

Page 107 of 112

Page 108: J2EE Questions

times we use session beans as a wrapper over a number of entity beans in the system. If a business functionality requires access to say 10 entity beans, that functionality can be encapsulated in a single session bean. Thus making it what we say coarse grained. In this case, entity beans can be said as fine grained.

A fine grained entity bean directly mapped to one relational table. A coarse grained entity bean is larger and more complex, either because its attributes include values or lists from other tables, or because it has more sets of dependent objects. The coarse grained bean might be mapped to a single table or flat file.

30. Is there is any difference between the way the ejbActivate() & ejbPassivate work with Statefull session Beans & Enity Beans?

There is a difference. In session beans, activiation & passivation are basically swaps to and from disk. While in entity beans, the swapping is to and from an entity bean pool. In your entity beans, you should allocate any resource the bean requires inside the ejbActivate() method, and remove these same resources inside the ejbPassivate() method. This ensures that any connections or other resources your bean needs are allocated and cleared at the right times.

In stateful session beans, you can leave these methods empty since there is no conversational state involved.

Weblogic Server,consists of application server and Web server. How do these server communicate internally ? What is the architecture behind it?

that communication protocol is called as "t3 protocol". Why is such a protocol required? J2EE related servers are known for there "Independency". If we develope an application using the weblogic's native protocol (t3) related features, it will soon be dependent on that app server.. Then how will we port that app on some other J2EE compliant app servers ? Has BEA done it purposely to restrict its users to the WebLogic domain, or is it of any significance ? If they have done it purposely, then why use J2EE at all?

Isnt the J2EE specifications enough for any type of application services ?

31. What is MultiPooling?

Muli pool is nothing but pool of connection pools. WEBLOGIC server provides multipool facility

32. Advantages of MVC Arch?

Advantages of MVC are:1.multiple view for the same model. one can use HTML,WML using the same model.2.It is easier to add new type of clients..tomorrow ican use the same model but the view could be swing..

33. Differnce in create() in ejb for stateless and statefulStateful should have parameters but for stateless it is optional

34. Reentrant beans ?

Reentrant beans are those where more than one thread can invoke the bean instance method. Non reentrant beans are one there is only 1 thread working with the

Page 108 of 112

Page 109: J2EE Questions

object. All sessions beans are Non reenetrant but entity beans can be declared as reentrant.However, the specification recommends that this not be allowed,unless it is essential.

35. Can a Bean have a multiple ejbCreate() method /with diffrent param?What type situtions it is used ?

An ejbCreate() will be called by the home object to create the remote object. The parameterized ejbCreate will be used for Statefull session and entity beans but not for stateless session beans. So you can have multiple ejbCreate() with diff. params.. It will be simillar to multiple constructors with diff params. But make sure, you should have to have corresponding create() methods in Home object.

36. What is ejbPostCreate()

What is an ejbSelect() method in EJB2.0A select method is similar to a finder method for Entity Beans, they both use EJB-QL to define the semantics of the method. hey differ in that an ejbSelect method(s) are not exposed to the client and the ejbSelect method(s) can return values that are defined as cmp-types or cmr-types.

37. Why there is not unsetcontext /unsetsessioncontext for an satatefull and statless EJB where as it exists for enity bean (unsetentitycontext)?

38. What is Lazy Activation?Lazy activation allows dynamic binding of object implementation into the registry. With lazy activation there is no need to bind the object with rmiregistry in the begining. When the server receives the first request from client it looks for the correct implementation and activates that object. 39. How can you start the rmi registry by code.rmiregistry is an executable program. You start the registry from the command shell. If you wan to start from java program use Runtime.exec as any normal shell executable.

40. What is the use of ejbActivate and ejbPassivate methods in Stateless Session Bean?They are not part of SLSB. Container never sends call back to these methods.ejbActivate and ejbPassivate are not used in SLSB as it is nonconversational bean,not specific to single client .

41. Then Why there is ejbActivate and ejbPassivate in SLSB when not used ??

Both Stateless and Stateful Session Bean implement javax.ejb.SessionBean and this would not be possible if stateless session bean is to remove ejbActivate and ejbPassivate from the interface.

42 .What are the 2 methods in a Primary Key class that should be implemented? why?

The 2 methods are hashCode & equals.These methods are required to compare the data of each row for uniqueness.

43. How will use Where Clause in an CMP Bean ?

EJB2.0 introduced concept of EJB-QL to retrieve CMP beans. You can use WHERE clause in your EJB-QL and pass in parameters as part of findBy method parameters. Here is a sample ejb-ql which demonstrates a findBy method with EJB-QL having WHEREclause.

<ejb-jar> <enterprise-beans>

Page 109 of 112

Page 110: J2EE Questions

<entity> <ejb-name>hotelEJB</ejb-name> ...

<abstract-schema-name>hotelSchemaName</abstract-schema-name>

<cmp-field>... ... <query> <query-method> <method-name>findByCity</method-name> <method-params> <method-param>java.lang.String</method-param> </method-params> </query-method> <ejb-ql> <![CDATA[SELECT OBJECT(h) FROM hotelSchemaName AS h WHERE h.city = ?1]]> </ejb-ql> </query> </entity> ... </enterprise-beans> ... </ejb-jar>

44. What is the purpose of ejbRemove() in an Stateless BeanTo deallocate any resources. This method releases resources that were acquired within the ejbCreate and business methods.

45. How to handle the Connection pool when maximum no of connections are opened in the App server  

There is a connection pool listener , we can implement it and get all the events.... Thereby act accordingly.

46. What makes a Java class an enterprise bean?

An enterprise bean is composed of many parts, not just a single class. Essentially, an enterprise bean is constructed with a bean class, remote interface, home interface and deployment descriptor. These constituents are discussed below.

A bean class is the implementation class of the bean that defines its business, persistence, and passivation logic. The bean class implements either the javax.ejb.EntityBean or javax.ejb.SessionBean interface and runs inside the EJB container. Instances of the bean class service client request indirectly; instances of the bean class are not visible to the client.

The remote interface defines the business methods that will be visible to the client's that use the enterprise bean. The remote interface extends the javax.ejb.EJBObject interface and is implemented by a remote (distributed object) reference. Client applications interact with the enterprise bean through its remote interface.

The home interface defines the create, delete (remove), and query methods for an enterprise bean type. The home interface extends the javax.ejb.EJBHome interface and is implemented by a remote (distributed object) reference. The client application will use the home interface to create beans, find existing beans, and remove specific beans.

Page 110 of 112

Page 111: J2EE Questions

The deployment descriptor is used to describe the enterprise bean's runtime behavior to the container. Among other things the deployment descriptor allows the transaction, persistence, and authorization security behavior of a bean to be defined using declarative attributes. This greatly simplifies the programming model when developing beans. An enterprise bean represents the sum of all these parts (remote, home, bean class, and deployment descriptor) as one component. An enterprise bean is not an enterprise bean if any one of these parts is missing. A change to anyone of these parts -- changing even one attribute in the deployment descriptor for example -- creates an entirely new enterprise bean.

47. What is the need of Remote and Home interface. Why cant it be in one?

The home interface is your way to communicate with the container, that is who is responsable of creating, locating even removing one or more beans.The remote interface is your link to the bean, that will allow you to remotely access to all its methods and members.

At run time only we create remote object based on user input in create method(whether to access Wesley or x account)so it is not possible to know exactly user input and what remote object it want only at run time he gives input and based on user input remote object is created so we use Factory pattern while creating Remote object.so if we use Factory pattern we need two things either two class or interfac instance. 1, one instance takes input from user--- this is Home Interface instance 2, Based on input it returns an instance --- this Remote interface instance RemotInt it1=homeint.create();RemotInt it2=homeint.create(1,2);RemotInt it3=homeint.create(1,2,5); In above example based on user input one remote instance is returned from group of 3 so if we merge home and remote interface ,how will u bind JNDI name with (homeMergeRemote) object ,only based on user input container creates Remote object so we cannot predict what input he gives and based on input we create Remote object without object we cannot bind it with JNDI tree.so we have separate Interface Home and Remote  Basic function of Homeobject is 1. To create Remote object simultaneously container will take bean instance from pool and associates with Remoteobject 2. To delete Remoteobject simultaneously container will disassociate bean instance from remote object, pull the bean instance back to the pool. so home instance function is just like house keeping i.e creating ,locating,associating and deleteing the remote object.it has nothing do with bean instance or functionalty or business logic where as incase of Remoteobject it access the bean business logic Now it clear that we divide the work so we have two separate interface EJB Home and EJB Remote

48. Following are the changes in CMP2.01)CMP entity beans are subclassed.2)CMP entity beans have no declared fields.3)CMP get/set methods are defined in the subclass.4)CMP entity beans have an Abstract persisitence schema.5)CMP entity beans have a query language.6)CMP entity beans can have ejbSelect() methods

49. What are the features of Weblogic?

Page 111 of 112

Page 112: J2EE Questions

50. what exception is thrown while container trying to create EntityBean instance if it founds in database that there is no primary key and duplicate rows present in DB?

a) javax.ejb.FinderExceptionb) javax.ejb.ObjectNotFoundExceptionc) javax.ejb.FinderExceptiond) javax.ejb.NoSuchEntityException

51. Is Syncronized methods are allowed in EJB ?If Not Why :)?

52. What are the diffrent types of Connection Pooling

53. What is Scalable Portablity in J2EE ?

54. Where does EJB stores it's state when the container calls the Passivate method ?

55. Diff between JavaSpaces vs. JMS.

56. What are the significant diffrences between Weblogic and Websphere?

57.What are the constraints or drawbacks of container managed EJB's ?

58. What are the differences of Container Managed Persitence 1.1 and 2.0

Page 112 of 112