KEMBAR78
Java Interview Questions Answers Guide Section 2 | PDF
Find more WWW.ThesisScientist.com
1
Java/J2EE Job
Interview Companion
Section 2
Find more WWW.ThesisScientist.com
3
60 Enterprise Java
Enterprise - J2EE
Q 01: What is J2EE? What are J2EE components and services? SF
A 01: J2EE (Java 2 Enterprise Edition) is an environment for developing and deploying enterprise applications. The
J2EE platform consists of J2EE components, services, Application Programming Interfaces (APIs) and protocols
that provide the functionality for developing multi-tiered and distributed Web based applications.
J 2 E E P h y s ic a l T ie r s , C o n ta in e r s , C o m p o n e n ts , S e r v ic e s & A P Is
C lie n t
C lie n t T ie r
F ir e w a ll
D M Z
F ir e w a ll
in te rn e t
W e b S e r v e r A p p lic a tio n S e r v e r
A p p lic a tio n T ie r (M id d le T ie r )
D a ta b a s e S e r v e r
D a ta (E IS ) T ie r
( X ) H T M L , H T T P ( S
)X M L
( B r o w s e r )
A p p le t
H T T P ( S
)
C lie n t A p p lic a tio n
(s ta n d a lo n e J a v a
p r o g r a m )
W e b J 2 E E A p p lic a tio n S e r v e r
S e r v e r
W e b C o n ta in e r J D B C
H T M L
T a g
lib r a ry
S e rv le ts J S P J avaM a
C S S
R
M
I
/
I
I
O
P
JN
DI
JTA
JDBC
JMS
JavaMail
JAF
R M I
P
OI
I
/
I
M
R
J M S
E J B C o n ta in e r
R M I/IIO P IIO P
S e s s io n B e a n s
E n tity B e a n s M e s s a g e d riv e n b e a n s
R
M
I
/
I
I
O
P
J
N
D
I
JTA
JDB
C
J
M
S
JavaM
ail
JAF
J N D I
O th e r S e r v ic e s + A P I s p r o v id e d b y s e r v e r / c o n ta in e r :
S e c u r ity (S S L , A C L , J A A S ,X .5 0 9 )
tr a n s a c tio n s , th r e a d in g , R e s o u r c e p o o lin g (E g : C o n n e c tio n p o o lin g ) e tc
,F a u lt T o le r a n c e , L o a d B a la n c in g , c lu s te r in g
M o n ito r in g , A u d itin g , L o g g in g e tc
m o r e ...............
R D B M S
il
J a v a
A p p lic a tio n
M e s s a g in g
C o r b a S e r v e r
D ir e c t o r y
S e r v ic e
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:
Component type Components Packaged as
Applet applets JAR (Java ARchive)
Application client Client side Java codes. JAR (Java ARchive)
Web component JSP, Servlet WAR (Web ARchive)
Enterprise JavaBeans Session beans, Entity beans, Message driven beans JAR (EJB Archive)
Enterprise application WAR, JAR, etc EAR (Enterprise ARchive)
Resource adapters Resource adapters RAR (Resource Adapter ARchive)
Find more WWW.ThesisScientist.com
So what is the difference between a component and a service you may ask? A component is an application
level software unit as shown in the table above. All the J2EE components depend on the container for the system
level support like transactions, security, pooling, life cycle management, threading etc. A service is a component
Find more WWW.ThesisScientist.com
Enterprise Java 61
that can be used remotely through a remote interface either synchronously or asynchronously (e.g. Web service,
messaging system, sockets, RPC etc).
Containers (Web & EJB containers) are the interface between a J2EE component and the low level platform
specific functionality that supports J2EE components. Before a Web, enterprise bean (EJB), or application client
component can be executed, it must be assembled into a J2EE module (jar, war, and/or ear) and deployed into its
container.
A J2EE server provides system level support services such us security, transaction management, JNDI (Java
Naming and Directory Interface) lookups, remote access etc. J2EE architecture provides configurable and non-
configurable services. The configurable service enables the J2EE components within the same J2EE application
to behave differently based on where they are deployed. For example the security settings can be different for the
same J2EE application in two different production environments. The non-configurable services include enterprise
bean (EJB) and servlet life cycle management, resource pooling etc.
Protocols are used for access to Internet services. J2EE platform supports HTTP (HyperText Transfer Protocol),
TCP/IP (Transmission Control Protocol / Internet Protocol), RMI (Remote Method Invocation), SOAP (Simple
Object Access Protocol) and SSL (Secured Socket Layer) protocol.
The J2EE API can be summarised as follows:
J2EE technology category API (Application Program Interface)
Component model technology Java Servlet, JavaServer Pages(JSP), Enterprise JavaBeans(EJB).
JAXP (Java API for XML Processing), JAXR (Java API for XML Registries), SAAJ (SOAP
Web services technology with attachment API for Java), JAX-RPC (Java API for XML-based RPC), JAX-WS (Java
API for XML-based Web Services).
JDBC (Java Database Connectivity), JNDI (Java Naming and Directory Interface), JMS
Other (Java Messaging Service), JCA (J2EE Connector Architecture), JTA (Java Transaction
API), JavaMail, JAF (JavaBeans Activation Framework – used by JavaMail), JAAS (Java
Authentication and Authorization Service), JMX (Java Management eXtenstions).
Q 02: Explain the J2EE 3-tier or n-tier architecture? SFDC
A 02: This is a very commonly asked question. Be prepared to draw some diagrams on the board. The J2EE platform is
a multi-tiered system. A tier is a logical or functional partitioning of a system.
2 – tier system 3 – tier system
2 -T ier (C lien t/S erv er)
C lien t M /C 1 C lien t M /C 2
U s e rIn te rfa c e U serInterface
/display Logic /display Logic
B usiness B usiness
logic logic
D atabase D atabase
logic logic
B usiness Logic
D atabase logic
D ata
D atabase
When the developers are not disciplined, The
display logic, business logic and database
logic are muddled up and/or duplicated in a 2-
tier client server system.
3-T ier (or n -tier)
Client M /C 1 Client M /C 2
U s e rIn te rfa c e U serInterface
/display logic /display logic
M iddle-tier server
B usiness Logic
D atabase Logic
Data
D atabase
The advantages of the multi-tier architecture are:
Forced separation of user interface logic and business logic.
Business logic sits on small number of centralized machines (may be
just one).
Easy to maintain, to manage, to scale, loosely coupled etc.
Each tier is assigned a unique responsibility in a 3-tier system. Each tier is logically separated and loosely coupled
from each other, and may be distributed.
Find more WWW.ThesisScientist.com
62 Enterprise Java
Client tier represents Web browser, a Java or other application, Applet, WAP phone etc. The client tier makes
requests to the Web server who will be serving the request by either returning static content if it is present in the
Web server or forwards the request to either Servlet or JSP in the application server for either static or dynamic
content.
Presentation tier encapsulates the presentation logic required to serve clients. A Servlet or JSP in the
presentation tier intercepts client requests, manages logons, sessions, accesses the business services, and finally
constructs a response, which gets delivered to client.
Business tier provides the business services. This tier contains the business logic and the business data. All the
business logic is centralised into this tier as opposed to 2-tier systems where the business logic is scattered
between the front end and the backend. The benefit of having a centralised business tier is that same business
logic can support different types of clients like browser, WAP, other stand-alone applications etc.
Integration tier is responsible for communicating with external resources such as databases, legacy systems,
ERP systems, messaging systems like MQSeries etc. The components in this tier use JDBC, JMS, J2EE
Connector Architecture (JCA) and some proprietary middleware to access the resource tier.
Resource tier is the external resource such as a database, ERP system, Mainframe system etc responsible for
storing the data. This tier is also known as Data Tier or EIS (Enterprise Information System) Tier.
H i g h L e v e l
T i e r s
C l i e n t T i e r
C l i e n t
M i d d l e T i e r
W e b S e r v e r
A p p lic a t i o n S e r v e r
J 2 E E T i e r s
L o g i c a l o r
F u n c t i o n a l T i e r s
C l i e n t T i e r
A p p le t s , H T M L , W M L , J a v a S c r ip t , A p
p lic a t io n C lie n t s e t c
P r e s e n t a t i o n T i e r
H T M L , C S S , G I F F ile s e t c ( s t
a t ic c o n t e n t )
J S P , S e r v le t s , T a g lib r a r y a n d o t
h e r U I e le m e n t s ( C S S , G I F , e t c )
B u s i n e s s T i e r
E J B , J a v a C la s s e s , B u s in e s s O b
je c t s e t c
I n t e g r a t i o n T i e r
J M S , J D B C , C o n n e c t o r s ( J C A ) , a
n d L e g a c y
y l
p p
a
s n
r e
t t
a p
E
E
2 J
D a t a T i e r
X M L
R D B M S
R e s o u r c e T i e r
D a t a b a s e s , E R P & C R M s y s t e m s , L e g
a c y S y s t e m s e t c
Note: On a high level J2EE can be construed as a 3-tier system consisting of Client Tier, Middle Tier (or
Application Tier) and Data Tier. But logically or functionally J2EE is a multi-tier (or n-tier) platform.
The advantages of a 3-tiered or n-tiered application: 3-tier or multi-tier architectures force separation among
presentation logic, business logic and database logic. Let us look at some of the key benefits:
Manageability: Each tier can be monitored, tuned and upgraded independently and different people can have
clearly defined responsibilities.
Find more WWW.ThesisScientist.com
Enterprise Java 63
Scalability: More hardware can be added and allows clustering (i.e. horizontal scaling).
Maintainability: Changes and upgrades can be performed without affecting other components.
Availability: Clustering and load balancing can provide availability.
Extensibility: Additional features can be easily added.
Q 03: Explain MVC architecture relating to J2EE? DCDP
A 03: This is also a very popular interview question. MVC stands for Model-View-Controller architecture. It divides the
functionality of displaying and maintaining of the data to minimise the degree of coupling (i.e. promotes loose
coupling) between components.
J2E E M V C (M odel-V iew -C ontroller)
p
la
y
is
d
to
a
ta
D
t
g
e
M odel
(E ntitiy B eans (E JB ), S ession B eans (E
JB ), P lain Java C lasses )
E ncapsulates business logic and
application state .
s t a
t e
c h a
n g e
V iew
(JS P , JavaB eans, S W IN G ,
C usto m Tag s, etc )
R enders the m odel & has only
display logic.
S ends user actions to the
controller
A llow s controller to select a view
.
U ser A ctio n (eg: subm itting a
form , clicking a button etc)
V iew selection (eg: selecting the next JS P page
to display as a response )
C ontroller
(S ervlet, S truts A ction etc)
controls application behaviour
M aps user actions to m odel.
selects view for response .
usually one for each
functionality.
Browser
C on troller
1 . R e q u e s t
2S ervlet
.
i
t n
s
c a
re t
t
i n
i
d a
t
re e
. s
4
V iew M od el 3. read/update
5 E JB or P lain Java database6 . R espo nse data
JS P class
C lient Tier M iddleTier (A pplication Tier) D ata Tier
N ote: T ypical M V C architecture is show n above. V ariations are possible (eg: M odel 1 vs M odel 2 M V C )
A model represents the core business logic and state. A model commonly maps to data in the database and will
also contain core business logic.
A View renders the contents of a model. A view accesses the data from the model and adds display logic to
present the data.
A Controller acts as the glue between a model and a view. A controller delegates the request to the model for
application logic and state and also centralises the logic for dispatching the request to the next view based on the
input parameters from the client and the application state. A controller also decouples JSP pages and the Servlet
by handling the view selection.
Find more WWW.ThesisScientist.com
64 Enterprise Java
Q 04: How to package a module, which is, shared by both the WEB and the EJB modules? SF
A 04: Package the modules shared by both WEB and EJB modules as dependency jar files. Define the Class-Path:
property in the MANIFEST.MF file in the EJB jar and the Web war files to refer to the shared modules. [Refer Q7
in Enterprise section for diagram: J2EE deployment structure].
The MANIFEST.MF files in the EJB jar and WEB war modules should look like:
Manifest-Version: 1.0
Created-By: Apache Ant 1.5
Class-Path: myAppsUtil.jar
Q 05: Why use design patterns in a J2EE application? DP
A 05:
They have been proven. Patterns reflect the experience and knowledge of developers who have successfully
used these patterns in their own work. It lets you leverage the collective experience of the development
community.
Example Session facade and value object patterns evolved from performance problems experienced due to
multiple network calls to the EJB tier from the WEB tier. Fast lane reader and Data Access Object patterns
exist for improving database access performance. The flyweight pattern improves application performance
through object reuse (which minimises the overhead such as memory allocation, garbage collection etc).
They provide common vocabulary. Patterns provide software designers with a common vocabulary. Ideas
can be conveyed to developers using this common vocabulary and format.
Example Should we use a Data Access Object (DAO)? How about using a Business Delegate? Should we
use Value Objects to reduce network overhead? Etc.
Q 06: What is the difference between a Web server and an application server? SF
A 06:
Web Server Application Server
Supports HTTP protocol. When the Web server receives Exposes business logic and dynamic content to the client
an HTTP request, it responds with an HTTP response, through various protocols such as HTTP, TCP/IP, IIOP, JRMP etc.
such as sending back an HTML page (static content) or
delegates the dynamic response generation to some
other program such as CGI scripts or Servlets or JSPs in
the application server.
Uses various scalability and fault-tolerance techniques. Uses various scalability and fault-tolerance techniques. In addition
provides resource pooling, component life cycle management,
transaction management, messaging, security etc.
Provides services for components like Web container for servlet
components and EJB container for EJB components.
With the advent of XML Web services the line between application servers and Web servers is not clear-cut. By passing XML
documents between request and response the Web server can behave like an application server.
Q 07: What are ear, war and jar files? What are J2EE Deployment Descriptors? SF
A 07: ear, war and jar are standard application deployment archive files. Since they are a standard, any application
server (at least in theory) will know how to unpack and deploy them.
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. JAR files can‟t have other JAR files. But EAR and WAR
(Web ARchive) files can have JAR files.
An EAR file contains all the JARs and WARs belonging to an application. JAR files contain the EJB classes and
WAR files contain the Web components (JSPs, static content (HTML, CSS, GIF etc), Servlets etc.). The J2EE
application client's class files are also stored in a JAR file. EARs, JARs, and WARs all contain an XML-based
deployment descriptor.
Find more WWW.ThesisScientist.com
Enterprise Java 65
J2EE deployment structure (ear, war, jar )
MyApps.ear
MANIFEST.MF
Manifest-Version: 1.0
META-INF
Craeted-By: Apache Ant
application.xml
deployment descriptor
log4j.jar (3rd party jars) class files, properties files,configuration files etc
MyAppsCommon.jar , MyAppsUtil.jar
class files, properties files,configuration files etc
(shared by both EJB and Web modules)
MyAppsEJB.jar
MANIFEST.MF
class-path: log4j.jar MyAppsCommon.jar MyAppsUtil.jar
META-INF
ejb-jar.xml
deployment descriptor
ejb classes , non-ejb class etc
MyAppsWeb.war
JSP, HTML, CSS, GIF (can have
public sub-folders)
directory
(document
root)
META-INF
WEB-INF
private
lib
directory
classes
MANIFEST.MF
class-path: log4j.jar MyAppsCommon.jar MyAppsUtil.jar
web.xml
deployment descriptor
struts.jar, crimson.jar
3rd party jar files
class files
Deployment Descriptors
A deployment descriptor is an XML based text file with a “.xml” extension that describes a component's
deployment settings. A J2EE application and each of its modules has its own deployment descriptor. Pay attention
to elements marked in bold in the sample deployment descriptor files shown below.
application.xml: is a standard J2EE deployment descriptor, which includes the following structural
information: EJB jar modules, WEB war modules, <security-role> etc. Also since EJB jar modules are
packaged as jars the same way dependency libraries like log4j.jar, commonUtil.jar etc are packaged, the
application.xml descriptor will distinguish between these two jar files by explicitly specifying the EJB jar
modules.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE application PUBLIC "-//Sun Microsystems, Inc.//DTD J2EE Application
1.2//EN" "http://java.sun.com/j2ee/dtds/application_1_2.dtd">
<application id="Application_ID">
<display-name>MyApps</display-name>
<module id="EjbModule_1">
<ejb>MyAppsEJB.jar</ejb>
</module>
<module id="WebModule_1">
<web>
Find more WWW.ThesisScientist.com
66 Enterprise Java
<web-uri>MyAppsWeb.war</web-uri>
<context-root>myAppsWeb</context-root>
</web>
</module>
<security-role id="SecurityRole_1">
<description>Management position</description>
<role-name>managger</role-name>
</security-role>
</application>
ejb-jar.xml: is a standard deployment descriptor for an EJB module.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans
1.1//EN" "http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd">
<ejb-jar id="ejb-jar_ID"> <display-
name>MyAppsEJB</display-name>
<enterprise-beans>
<session id="ContentService"> <ejb-
name>ContentService</ejb-name>
<home>ejb.ContentServiceHome</home>
<remote>ejb.ContentService</remote>
<ejb-class>ejb.ContentServiceBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Bean</transaction-type>
</session>
<entity> <ejb-name>Bid</ejb-
name>
<home>ejb.BidHome</home>
<remote>ejb.Bid</remote> <ejb-
class>ejb.BidBean</ejb-class>
<persistence-type>Container</persistence-type> <prim-
key-class>ejb.BidPK</prim-key-class>
<reentrant>False</reentrant> <cmp-field><field-
name>bid</field-name></cmp-field> <cmp-field><field-
name>bidder</field-name></cmp-field> <cmp-field><field-
name>bidDate</field-name></cmp-field> <cmp-
field><field-name>id</field-name></cmp-field>
</entity>
</enterprise-beans>
<!-- OPTIONAL -->
<assembly-descriptor>
<!-- OPTIONAL, can be many --
> <security-role>
<description>
Employee is allowed to ...
</description> <role-
name>employee</role-name>
</security-role>
<!-- OPTIONAL. Can be many -->
<method-permission>
<!-- Define role name in "security-role" --
> <!-- Must be one or more --> <role-
name>employee</role-name>
<!-- Must be one or more -->
<method>
<ejb-name>ContentService</ejb-
name> <!-- * = all methods -->
<method-name>*</method-name>
</method>
<method> <ejb-
name>Bid</ejb-name>
<method-name>findByPrimaryKey</method-
name> </method>
</method-permission>
Find more WWW.ThesisScientist.com
Enterprise Java 67
<!-- OPTIONAL, can be many. How the container is to manage
transactions when calling an EJB's business methods -->
<container-transaction>
<!-- Can specify many methods at once here -->
<method>
<ejb-name>Bid</ejb-name>
<method-name>*</method-name>
</method>
<!-- NotSupported|Supports|Required|RequiresNew|Mandatory|Never --
> <trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
web.xml: is a standard deployment descriptor for a WEB module.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app> <display-
name>myWebApplication</display-name>
<context-param>
<param-name>GlobalContext.ClassName</param-name>
<param-value>web.GlobalContext</param-value>
</context-param>
<servlet> <servlet-
name>MyWebController</servlet-name>
<servlet-class>web.MyWebController</servlet-
class> <init-param>
<param-name>config</param-name> <param-value>/WEB-
INF/config/myConfig.xml</param-value>
</init-param> <load-on-
startup>1</load-on-startup>
</servlet>
<servlet-mapping> <servlet-
name>MyWebController</servlet-name> <url-
pattern>/execute/*</url-pattern>
</servlet-mapping>
<error-page> <error-
code>400</error-code>
<location>/WEB-
INF/jsp/errors/myError.jsp</location> </error-page>
<taglib> <taglib-uri>/WEB-INF/struts-
bean.tld</taglib-uri>
<taglib-location>/WEB-INF/lib/taglib/struts/struts-bean.tld</taglib-
location> </taglib>
<security-constraint>
<web-resource-collection>
<web-resource-name>Employer</web-resource-name>
<description></description> <url-
pattern>/execute/employ</url-pattern> <http-
method>POST</http-method> <http-
method>GET</http-method> <http-method>PUT</http-
method>
</web-resource-collection>
<auth-constraint>
<description></description>
<role-name>advisor</role-name>
</auth-constraint>
</security-constraint>
<login-config> <auth-
method>FORM</auth-method>
<realm-name>FBA</realm-name>
<form-login-config>
<form-login-page>/execute/MyLogon</form-login-page>
Find more WWW.ThesisScientist.com
68 Enterprise Java
<form-error-page>/execute/MyError</form-error-
page> </form-login-config>
</login-config>
<security-role>
<description>Advisor</description>
<role-name>advisor</role-name>
</security-role>
</web-app>
Q 08: Explain J2EE class loaders? SF
A 08: J2EE application server sample class loader hierarchy is shown below. (Also refer to Q4 in Java section). As per
the diagram the J2EE application specific class loaders are children of the “ System –classpath” class loader.
When the parent class loader is above the “System –Classpath” class loader in the hierarchy as shown in the
diagram (i.e. bootstrap class loader or extensions class loader) then child class loaders implicitly have visibility to
the classes loaded by its parents. When a parent class loader is below a “System -Classpath” class loader then
the child class loaders will only have visibility into the classes loaded by its parents only if they are explicitly
specified in a manifest file (MANIFEST.MF) of the child class loader.
Example As per the diagram, if the EJB module MyAppsEJB.jar wants to refer to MyAppsCommon.jar and
MyAppsUtil.jar we need to add the following entry in the MyAppsEJB.jar‟s manifest file MANIFEST.MF.
class-path: MyAppsCommon.jar MyAppsUtil.jar
J 2 E E a p p lic a tio n se rv e r s a m p le cla s s lo a d e r h ie ra rc h y
M yA p p s .e a rB oo t st r a p ( JV M )
(rt.jar, i1 8 .ja r)
M yA p p s U til.ja r
E x te n sio n s(JV M )
(lib/ e xt)
M yA p p s C o m m o n .ja r
S y stem (JV M ) M yA p p s E JB .ja r
(- clas sp ath)
M yA p p s W e b .w a r
A pp lica tio n c la ss A p p lic atio n clas s E a ch E A R ge ts its
lo ad e r (E A R ) loa de r (E A R ) o w n in sta nc e of c la s s
loa d e r
E JB c la ss lo a de r
W A R c la ss W A R clas s
lo ad e r loa de r
E JB c la ss loa d er
W A R c las
s lo ad e r
All the E JB ja rs in a e ar file
s h are th e s am e EJ B cla
ss lo a de r.
E a ch W A R g e ts its o w n
ins ta nc e o f cla ss loa d er.
Th e W E B -IN F /lib libra ries
a re s pe c ific to e ac h W A R
N o te : A p p lic atio n ve n d o r's S e rve r c la s s lo ad e r h ie ra rc h y m ig h t s lig h tly va ry
.
This is because the application (EAR) class loader loads the MyAppsCommon.jar and MyAppsUtil.jar. The EJB
class loader loads the MyAppsEJB.jar, which is the child class loader of the application class loader. The WAR
class loader loads the MyAppsWeb.war.
Every J2EE application or EAR gets its own instance of the application class loader. This class loader is
responsible for loading all the dependency jar files, which are shared by both WEB and EJB modules. For
example third party libraries like log4j, utility classes, shared classes or common classes (Exception thrown by an
EJB module should be caught by a WEB module) etc.
The key difference between the EJB and WAR class loader is that all the EJB jars in the application share the
same EJB class loader whereas WAR files get their own class loader. This is because the EJBs have inherent
relationship between one another (ie EJB-EJB communication between EJBs in different applications but hosted
on the same JVM) but the Web modules do not. Every WAR file should be able to have its own WEB-INF/lib third
party libraries and need to be able to load its own version of converted logon.jsp Servlet so each WEB module is
isolated in its own class loader.
Find more WWW.ThesisScientist.com
Enterprise Java 69
So if two different WEB modules want to use two different versions of the same EJB then we need to have two
different ear files. As was discussed in the Q4 in Java section the class loaders use a delegation model where
the child class loaders delegate the loading up the hierarchy to their parent before trying to load it itself only if the
parent can‟t load it. But with regards to WAR class loaders, some application servers provide a setting to turn this
behaviour off (DelegationMode=false). This delegation mode is recommended in the Servlet 2.3 specification.
As a general rule classes should not be deployed higher in the hierarchy than they are supposed to exist. This is because
if you move one class up the hierarchy then you will have to move other classes up the hierarchy as well. This is because
classes loaded by the parent class loader can‟t see the classes loaded by its child class loaders (uni-directional bottom-up
visibility).
Enterprise - Servlet
Q 09: What is the difference between CGI and Servlet? SF
Q 09:
Traditional CGI Java Servlet
(Common Gateway Interface)
Traditional CGI creates a heavy weight process to handle each Spawns a lightweight Java thread to handle each http
http request. N number of copies of the same traditional CGI request. Single copy of a type of servlet but N number of
programs is copied into memory to serve N number of threads (thread sizes can be configured in an application
requests. server).
In the Model 2 MVC architecture, servlets process requests and select JSP views. So servlets act as controller.
Servlets intercept the incoming HTTP requests from the client (browser) and then dispatch the request to the
business logic model (e.g. EJB, POJO - Plain Old Java Object, JavaBeans etc). Then select the next JSP view for
display and deliver the view to client as the presentation (response). It is the best practice to use Web tier UI
frameworks like Struts, JavaServer Faces etc, which uses proven and tested design patterns.
Q 10: HTTP is a stateless protocol, so how do you maintain state? How do you store user data between requests? SF
PIBP
A 10: This is a commonly asked question as well. You can retain the state information between different page requests
as follows:
HTTP Sessions are the recommended approach. A session identifies the requests that originate from the same
browser during the period of conversation. All the servlets can share the same session. The JSESSIONID is
generated by the server and can be passed to client through cookies, URL re-writing (if cookies are turned off) or
built-in SSL mechanism. Care should be taken to minimize size of objects stored in session and objects
stored in session should be serializable. In a Java servlet the session can be obtained as follows: CO
HttpSession session = request.getSession(); //returns current session or a new session
Sessions can be timed out (configured in web.xml) or manually invalidated.
Session Management
ServerClient
(Browser)
A new session is created on the Server
1. Initial Request[No session] side with JSESSIONID where JSESSIONID Name Value
state can be maintained as
xsder12345 Firstname Peter
2. JSESSIONID is passed to client with name/value pair.
e xsder12345 LastName Smith
the response through onfor thati
rm
fo
cookies or URL re-writing dstate
in
NIDre IO
e
sto S
S
v SE
trie ed J
re
3. Client uses the JSESSIONID pli
sup
for subsequent requests
Find more WWW.ThesisScientist.com
70 Enterprise Java
Hidden Fields on the pages can maintain state and they are not visible on the browser. The server treats both
hidden and non-hidden fields the same way.
<INPUT type=”hidden” name=”Firstname” value=”Peter”>
<INPUT type=”hidden” name=”Lastname” value=”Smith”>
The disadvantage of hidden fields is that they may expose sensitive or private information to others.
URL re-writing will append the state information as a query string to the URL. This should not be used to maintain
private or sensitive information.
Http://MyServer:8080/MyServlet?Firstname=Peter&Lastname=Smith
Cookies: A cookie is a piece of text that a Web server can store on a user‟s hard disk. Cookies allow a website to
store information on a user‟s machine and later retrieve it. These pieces of information are stored as name-value
pairs. The cookie data moves in the following manner:
If you type the URL of a website into your browser, your browser sends the request to the Web server. When
the browser does this it looks on your machine for a cookie file that URL has set. If it finds it, your browser
will send all of the name-value pairs along with the URL. If it does not find a cookie file, it sends no cookie
data.
The URL‟s Web server receives the cookie data and requests for a page. If name-value pairs are received,
the server can use them. If no name-value pairs are received, the server can create a new ID and then sends
name-value pairs to your machine in the header for the Web page it sends. Your machine stores the name
value pairs on your hard disk.
Cookies can be used to determine how many visitors visit your site. It can also determine how many are new
versus repeated visitors. The way it does this is by using a database. The first time a visitor arrives, the site
creates a new ID in the database and sends the ID as a cookie. The next time the same user comes back, the site
can increment a counter associated with that ID in the database and know how many times that visitor returns.
The sites can also store user preferences so that site can look different for each visitor.
Which mechanism to choose?
Session Description
mechanism
HttpSession ƒ There is no limit on the size of the session data kept.
ƒ The performance is good.
ƒ This is the preferred way of maintaining state. If we use the HTTP session with the application server‟s
persistence mechanism (server converts the session object into BLOB type and stores it in the
Database) then the performance will be moderate to poor.
When using HttpSession mechanism you need to take care of the following points:Note:
ƒ Remove session explicitly when you no longer require it.
ƒ Set the session timeout value.
ƒ Your application server may serialize session objects after crossing a certain memory limit. This is
expensive and affects performance. So decide carefully what you want to store in a session.
Hidden fields ƒ There is no limit on size of the session data.
ƒ May expose sensitive or private information to others (So not good for sensitive information).
ƒ The performance is moderate.
URL rewriting ƒ There is a limit on the size of the session data.
ƒ Should not be used for sensitive or private information.
ƒ The performance is moderate.
Cookies ƒ There is a limit for cookie size.
ƒ The browser may turn off cookies.
ƒ The performance is moderate.
The benefit of the cookies is that state information can be stored regardless of which server the client talks to
and even if all servers go down. Also, if required, state information can be retained across sessions.
Q 11: Explain the life cycle methods of a servlet? SF
A 11: The Web container is responsible for managing the servlet‟s life cycle. The Web container creates an instance of
the servlet and then the container calls the init() method. At the completion of the init() method the servlet is in
Find more WWW.ThesisScientist.com
Enterprise Java 71
ready state to service requests from clients. The container calls the servlet‟s service() method for handling each
request by spawning a new thread for each request from the Web container‟s thread pool [It is also possible to
have a single threaded Servlet, refer Q16 in Enterprise section]. Before destroying the instance the container will
call the destroy() method. After destroy() the servlet becomes the potential candidate for garbage collection.
Note on servlet reloading:
Most servers can reload a servlet after its class file has been modified provided the servlets are deployed to
$server_root/servlets directory. This is achieved with the help of a custom class loader. This feature is handy for development
and test phases. This is not recommended for production since it can degrade performance because of timestamp comparison
for each request to determine if a class file has changed. So for production it is recommended to move the servlet to server‟s
class path ie $server_root/classes.
When a server dispatches a request to a servlet, the server first checks if the servlet's class file has changed on disk. If it has
changed, the server abandons the class loader used to load the old version and creates a new instance of the custom class
loader to load the new version. Old servlet versions can stay in memory indefinitely (so the effect is the other classes can still
hold references to the old servlet instances, causing odd side effects, but the old versions are not used to handle any more
requests. Servlet reloading is not performed for classes found in the server's classpath because the core, primordial class loader,
loads those classes. These classes are loaded once and retained in memory even when their class files change.
Servlet Life Cycle
called once
thread 1 : client request
thread 2 : client request
thread 3 : client request
called once
ins tan tiate
& call init()
init()
ready to serve requests
handle m ultiple
servic e() requests and send response.
destroy()
Q 12: Explain the directory structure of a WEB application? SFSE
A 12: Refer Q7 in Enterprise section for diagram: J2EE deployment structure and explanation in this section where
MyAppsWeb.war is depicting the Web application directory structure. The directory structure of a Web application
consists of two parts:
A public resource directory (document root): The document root is where JSP pages, client-side classes
and archives, and static Web resources are stored.
A private directory called WEB-INF: which contains following files and directories:
web.xml : Web application deployment descriptor.
*.tld : Tag library descriptor files.
classes : A directory that contains server side classes like servlets, utility classes, JavaBeans etc.
lib : A directory where JAR (archive files of tag libraries, utility libraries used by the server side
classes) files are stored.
Note: JSP resources usually reside directly or under subdirectories of the document root, which are directly
accessible to the user through the URL. If you want to protect your Web resources then hiding the JSP files
behind the WEB-INF directory can protect the JSP files from direct access. Refer Q35 in Enterprise section.
Q 13: What is the difference between doGet () and doPost () or GET and POST? SFSE
Find more WWW.ThesisScientist.com
72 Enterprise Java
A 13:
GET or doGet() POST or doPost()
The request parameters are transmitted as a query string The request parameters are passed with the body of the
appended to the request. Allows browser bookmarks but not request.
appropriate for transmitting private or sensitive information.
More secured.http://MyServer/MyServlet?name=paul
This is a security risk.
GET was originally intended for static resource retrieval. POST was intended for input data submits where the results
are expected to change.
GET is not appropriate when large amounts of input data are
being transferred.
Q 14: What are the ServletContext and ServletConfig objects? What are Servlet environment objects? SF
A 14: The Servlet Engine uses both objects.
ServletConfig
The ServletConfig parameters are for a particular Servlet.
The parameters are specified in the web.xml (ie
deployment descriptor).
ServletContext
The ServletContext parameters are specified for the entire Web
application. The parameters are specified in the web.xml (ie
deployment descriptor).
Servlet Environment Objects
Servlet Engine
Web App1 init param for
ServletContext
web.xml (Deployment Descriptor) snippets
the web app <web-app>
<context-param>
<param-name>GlobalClassName</param-name>
<param-value>MyWebAppClass</param-value>
</context-param>
MyServlet1 config <servlet>
<servlet-name>MyServlet1</servlet-name>
<servlet-class>com.MyServlet</servlet-class>
<init-param>
MyServlet2 config
<param-name>config</param-name>
<param-value>/WEB-INF/config/config.xml</param-value>
</init-param>
ServletConfig objects init
<load-on-startup>1</load-on-startup>
</servlet>
params set for eachSevlet
</web-app>
Web App2
............
........
Q 15: What is the difference between HttpServlet and GenericServlet? SF
A 15:
GenericServlet HttpServlet
A GenericServlet has a service() method to The HttpServlet extends GenericServlet and adds support for HTTP
handle requests. protocol based methods like doGet(), doPost(), doHead() etc.
Protocol independent. Protocol dependent.
Q 16: How do you make a Servlet thread safe? What do you need to be concerned about with storing data in Servlet
instance fields? CIPIBP
A 16: As shown in the figure Servlet Life Cycle in Q11 in Enterprise section, a typical (or default) Servlet life cycle
creates a single instance of each servlet and creates multiple threads to handle the service() method. The multi-
threading aids efficiency but the servlet code must be coded in a thread safe manner. The shared resources
(e.g. instance variables, utility or helper objects etc) should be appropriately synchronized or should only use
variables in a read-only manner. Having large chunks of code in synchronized blocks in your service methods can
adversely affect performance and makes the code more complex.
Find more WWW.ThesisScientist.com
Enterprise Java 73
Alternatively it is possible to have a single threaded model of a servlet by implementing the marker or null
interface javax.servlet.SingleThreadedModel. The container will use one of the following approaches to ensure
thread safety:
Instance pooling where container maintains a pool of servlets.
Sequential processing where new requests will wait while the current request is being processed.
Best practice: It is best practice to use multi-threading and stay away from the single threaded model of the
servlet unless otherwise there is a compelling reason for it. Shared resources can be synchronized or used in
read-only manner or shared values can be stored in a database table. The single threaded model can adversely
affect performance.
Q 17: What is pre-initialization of a Servlet? LF
A 17: By default the container does not initialize the servlets as soon as it starts up. It initializes a servlet when it
receives a request for the first time for that servlet. This is called lazy loading. The servlet deployment descriptor
(web.xml) defines the <load-on-startup> element, which can be configured to make the servlet container load and
initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called
pre-loading or pre-initializing a servlet. We can also specify the order in which the servlets are initialized.
<load-on-startup>2</load-on-startup>
Q 18: What is a RequestDispatcher? What object do you use to forward a request? LFCO
A 18: A Servlet can obtain its RequestDispatcher object from its ServletContext.
//…inside the doGet() method
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
forwards the control to another servlet or JSP to generate response. This method allows one servlet to do preliminary
//processing of a request and another resource to generate the response
rd.forward(request,response);
or
includes the content of the resource such as Servlet, JSP, HTML, Images etc into the calling Servlet‟s response.
rd.include(request, response);
Q 19: What is the difference between forwarding a request and redirecting a request? LFDC
A 19: Both methods redirect you to a new resource like Servlet, JSP etc. But
redirecting - sendRedirect() forward
Sends a header back to the browser, which contains the name of Forward action takes place within the server without
the resource to be redirected to. The browser will make a fresh the knowledge of the browser.
request from this header information. Need to provide absolute
URL path.
Has an overhead of extra remote trip but has the advantage of No extra network trip.
being able to refer to any resource on the same or different domain
and also allows book marking of the page.
Q 20: What are the considerations for servlet clustering? DCSI
A 20: The clustering promotes high availability and scalability. The considerations for servlet clustering are:
Objects stored in a session should be serializable to support in-memory replication of sessions. Also
consider the overhead of serializing very large objects. Test the performance to make sure it is acceptable.
Design for idempotence. Failure of a request or impatient users clicking again can result in duplicate
requests being submitted. So the Servlets should be able to tolerate duplicate requests.
Avoid using instance and static variables in read and write mode because different instances may exist
on different JVMs. Any state should be held in an external resource such as a database.
Avoid storing values in a ServletContext. A ServletContext is not serializable and also the different
instances may exist in different JVMs.
Avoid using java.io.* because the files may not exist on all backend machines. Instead use
getResourceAsStream().
Find more WWW.ThesisScientist.com
74 Enterprise Java
Q 21: If an object is stored in a session and subsequently you change the state of the object, will this state change
replicated to all the other distributed sessions in the cluster? DCSI
A 21: No. Session replication is the term that is used when your current service state is being replicated across multiple
application instances. Session replication occurs when we replicate the information (ie session attributes) that
are stored in your HttpSession. The container propagates the changes only when you call the setAttribute(……)
method. So mutating the objects in a session and then by-passing the setAttribute(………..) will not replicate the
state change. CO
Example If you have an ArrayList in the session representing shopping cart objects and if you just call
getAttribute() to retrieve the ArrayList and then add or change something without calling the
setAttribute(……………) then the container may not know that you have added or changed something in the
ArrayList. So the session will not be replicated.
Q 22: What is a filter, and how does it work? LFDP
A 22: A filter dynamically intercepts requests and responses to transform or use the information contained in the
requests or responses but typically do not themselves create responses. Filters can also be used to transform the
response from the Servlet or JSP before sending it back to client. Filters improve reusability by placing recurring
tasks in the filter as a reusable unit.
A good way to think of Servlet filters is as a chain of steps that a request and response must go through before
reaching a Servlet, JSP, or static resource such as an HTML page in a Web application.
F i l t e r
W e b C o n ta in e r
S e r v le t, J S P , H T M L
F ilte r 3
Requ
est
F ilte r 2
Respon
se
F ilte r 1
C lie n t
The filters can be used for caching and compressing content, logging and auditing, image conversions (scaling up
or down etc), authenticating incoming requests, XSL transformation of XML content, localization of the request and
the response, site hit count etc. The filters are configured through the web.xml file as follows:
<web-app>
<filter>
<filter-name>HitCounterFilter</filter-name>
<filter-class>myPkg.HitCounterFilter</filter-class>
</filter>
<filter-mapping> <filter-
name>HitCounterFilter</filter-name> <url-
pattern>/usersection/*</url-pattern>
</filter-mapping>
...
</web-app>
The HitCounterFilter will intercept the requests from the URL pattern /usersection followed by any resource name.
Design Pattern: Servlet filters use the slightly modified version of the chain of responsibility design pattern.
Unlike the classic (only one object in the chain handle the request) chain of responsibility where filters allow
multiple objects (filters) in a chain to handle the request. If you want to modify the request or the response in the
chain you can use the decorator pattern (Refer Q11 in How would you go about… section).
Q 23: Explain declarative security for WEB applications? SE
Find more WWW.ThesisScientist.com
Enterprise Java 75
A 23: Servlet containers implement declarative security. The administration is done through the deployment descriptor
web.xml file. With declarative security the Servlets and JSP pages will be free from any security aware code.
You can protect your URLs through web.xml as shown below:
web-app> <security-
constraint>
<web-resource-collection> <web-resource-
name>PrivateAndSensitive</web-resource-name>
<url-pattern>/private/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>executive</role-name>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<!-- form based authorization --
> <login-config>
<auth-method>FORM</auth-
method> <form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/error.jsp</form-error-page>
</form-login-
config> </login-
config> </web-app>
The user will be prompted for the configured login.jsp when restricted resources are accessed. The container also
keeps track of which users have been previously authenticated.
Benefits: Very little coding is required and developers can concentrate on the application they are building and
system administrators can administer the security settings without or with minimal developer intervention. Let‟s
look at a sample programmatic security in a Web module like a servlet: CO
User user = new User();
Principal principal = request.getUserPrincipal(); if
(request.isUserInRole("boss"))
user.setRole(user.BOSS_ROLE);
Q 24: Explain the Front Controller design pattern or explain J2EE design patterns? DP
A 24: Problem: A J2EE system requires a centralized access point for HTTP request handling to support the integration
of system services like security, data validation etc, content retrieval, view management, and dispatching. When
the user accesses the view directly without going through a centralized mechanism, two problems may occur:
Each view is required to provide its own system services often resulting in duplicate code.
View navigation is left to the views. This may result in shared code for view content and view navigation.
Distributed control is more difficult to maintain, since changes will often need to be made in numerous
places.
Solution: Generally you write specific servlets for specific request handling. These servlets are responsible for
data validation, error handling, invoking business services and finally forwarding the request to a specific JSP view
to display the results to the user.
J 2 E E F ro n t C o n tro lle r p a tte rn
d is p a tc h e s V ie w
c lie n t
C lie n t r e q u e s t F r o n tC o n tr o lle r d e le g a te s A p p lic a tio n F lo w C o n tr o lle r
C o m m a n d
(e g : S T R U T S A c tio n )
in v o k e s
< < s e rv le t> >
F ro n tC o n tro lle rS e rv le t
< < J S P > >
F ro n tC o n tro lle rJ S P
Find more WWW.ThesisScientist.com
76 Enterprise Java
The Front Controller suggests that we only have one Servlet (instead of having specific Servlet for each specific
request) centralising the handling of all the requests and delegating the functions like validation, invoking business
services etc to a command or a helper component. For example Struts framework uses the command design
pattern to delegate the business services to an action class.
Benefits
Avoid duplicating the control logic like security check, flow control etc.
Apply the common logic, which is shared by multiple requests in the Front controller.
Separate the system processing logic from the view processing logic.
Provides a controlled and centralized access point for your system.
Q 25: Briefly discuss the following patterns Composite view, View helper, Dispatcher view and Service to worker? Or
explain J2EE design patterns? DP
A 25:
Composite View: Creates an aggregate view from atomic sub-views. The Composite View entirely focuses
on the View. The View is typically a JSP page, which has the HTML, JSP Tags etc. The JSP display pages
mostly have a side bar, header, footer and main content area. These are the sub-views of the view. The sub-
views can be either static or dynamic. The best practice is to have these sub-views as separate JSP pages
and include them in the whole view. This will enable reuse of JSP sub-views and improves maintainability
by having to change them at one place only.
Composite View
BasicView
1
View Com positeView
View Helper: When processing logic is embedded inside the controller or view it causes code duplication in
all the pages. This causes maintenance problems, as any change to piece of logic has to be done in all the
views. In the view helper pattern the view delegates its processing responsibilities to its helper classes. The
helper classes JavaBeans: used to compute and store the presentation data and Custom Tags: used for
computation of logic and displaying them iteratively complement each other.
Benefits Avoids embedding programming logic in the views and facilitates division of labour between Java
developers and Web page designers.
Service to Worker and Dispatcher View: These two patterns are a combination of Front Controller and View
Helper patterns with a dispatcher component. One of the responsibilities of a Front Controller is choosing a
view and dispatching the request to an appropriate view. This behaviour can be partitioned into a separate
component known as a dispatcher. But these two patterns differ in the way they suggest different division of
responsibility among the components.
Service to Worker Dispatcher View
Combines the front controller (Refer Q24 in Enterprise This pattern is structurally similar to the service to worker
section) and dispatcher, with views and view helpers (refer but the emphasis is on a different usage pattern. This
Q25 in Enterprise section) to handle client requests and combines the Front controller and the dispatcher with the
dynamically prepares the response. view helpers but
ƒ Controllers delegate the content retrieval to the view ƒ Controller does not delegate content retrieval to
helpers, which populates the intermediate model view helpers because this activity is deferred to
content for the view. view processing.
ƒ Dispatcher is responsible for the view management ƒ Dispatcher is responsible for the view management
and view navigation. and view navigation.
Find more WWW.ThesisScientist.com
Enterprise Java 77
Promotes more up-front work by the front controller Relatively has a lightweight front controller and
and dispatcher for the authentication, authorization, dispatcher with minimum functionality and most of the
content retrieval, validation, view management and work is done by the view.
navigation.
Q 26: Explain Servlet URL mapping? SF
Q 26:
S ervlet U R L m ap p in g
W ith o u t M ap p in g in w eb .xm l
U R L h ttp ://< h o s tn a m e :p o rt> /< w e b a p p n a m e > /se rvle t /< p a th n a m e > /< re s o u rce n a m e >
U R L eg h ttp ://lo ca lh o s t:8 0 8 0 /m yA p p s / se rvlet/m y P a th /M yS e rvle t
F ile S E R V E R _ H O M E W e b A p p s m yA p p sW E B -IN F C la s s e s m y P a th M y S e rv le t
S e rv e r R o o t
D o c u m e n t ro o t
W ith M ap p in g in w eb .xm l d ep lo ym en t d e scrip to r file
W e ca n d e fin e th e s e rvle t m a p p in g in th e w e b .x m l d e p lo y m n e t d e scrip to r file a s sh o w n b e lo w :
w e b -a p p >
se rvle t>
se rvle t-n a m e > M y S e rv le t< /s e rvle t-n a m e >
se rvle t-cla ss> m y P a th .M y S e rv le t< /se rv le t-cla s s>
/se rv le t>
se rvle t-m a p p in g >
se rvle t-n a m e > M y S e rv le t< /se rv le t-n a m e >
u rl-p a tte rn > m in e /*.d o < /u rl-p a tte rn >
/se rv le t-m a p p in g >
w e b -a p p >
U R L after m ap p in g h ttp ://lo c a lh o s t:8 0 8 0 /m y A p p s /m in e /te s t.d o
N o te : W h ich m e a n s e v e ry re q u e st w h ich h a s a p a tte rn o f h ttp ://lo c a lh o s t:8 0 8 0 /m y A p p s / m in e /*.d o w ill b e h a n d le d b y
th e m y P a th .M y S e rv le t c la ss . (* d e n o te s w ild ch a ra cte r fo r a n y a lp h a n u m e ric n a m e ). A ls o p o ssib le to m a p M yS e rvle t to
th e p a tte rn o f /m in e /* , th e * in d ica te s a n y re so u rce n a m e fo llo w e d b y /m in e .
H o w d o w e g et th e w eb ap p n a m e "m yA p p s"
T h e w e b a p p n a m e is d e fin e d in th e a p p lic a tio n .x m l d e p lo y m e n t d e scrip to r file . T h e < co n te xt-ro o t > d e n o te s th e
w e b a p p n a m e a s sh o w n b e lo w
a p p lic a tio n >
............
m o d u le id = "W e b M o d u le _ 1 ">
w e b >
w e b -u ri> m y A p p sW e b .w a r< /w e b -u ri>
c o n te xt-ro o t> m y A p p s < /c o n te xt-ro o t>
/w e b >
/m o d u le >
........
m o d u le id = "E jb M o d u le _ 1 ">
e jb > m yE JB .ja r< /e jb >
/m o d u le >
.....
< /a p p lica tio n >
Enterprise - JSP
Q 27: What is a JSP? What is it used for? What do you understand by the term JSP translation phase or compilation
phase? SF
A 27: JSP (Java ServerPages) is an extension of the Java Servlet technology. JSP is commonly used as the
presentation layer for combining HTML and Java code. While Java Servlet technology is capable of generating
HTML with out.println(“<html>….. </html>”) statements, where out is a PrintWriter. This process of embedding
HTML code with escape characters is cumbersome and hard to maintain. The JSP technology solves this by
providing a level of abstraction so that the developer can use custom tags and action elements, which can speed
up Web development and are easier to maintain.
Find more WWW.ThesisScientist.com
78 Enterprise Java
As shown in the figure the JSPs have a translation or a compilation process where the JSP engine translates
and compiles a JSP file into a JSP Servlet. The translated and compiled JSP Servlet moves to the execution
phase (run time) where they can handle requests and send response.
Unless explicitly compiled ahead of time, JSP files are compiled the first time they are accessed. On large
production sites, or in situations involving complicated JSP files, compilation may cause unacceptable delays to
users first accessing the JSP page. The JSPs can be compiled ahead of time (ie precompiled) using application
server tools/settings or by writing your own script.
J S P m o v in g p a rts
A p p lic a tio n S e rv e r
W e b C o n ta in e r
H T T P
(Browser)CLIE
NT
re q u e s t
E
n
g
i
n
e
S
e
r
v
l
e
t
E
n
g
i
n
e
J
S
P
S
e
r
v
e
r
W
e
b
S e rvle ts
J S P s
J S P S e rvle ts
H T T P
re s p o n s e
s ta tic d o c s
(H T M L ,C S S e tc )
Q 28: Explain the life cycle methods of a JSP? SF
A 28:
Pre-translated: Before the JSP file has been translated and compiled into the Servlet.
Translated: The JSP file has been translated and compiled as a Servlet.
Initialized: Prior to handling the requests in the service method the container calls the jspInit() to initialize the
Servlet. Called only once per Servlet instance.
Servicing: Services the client requests. Container calls this method for each request.
Out of service: The Servlet instance is out of service. The container calls the jspDestroy() method.
Q 29: What are the main elements of JSP? What are scriplets? What are expressions? SF
A 29: There are two types of data in a JSP page.
Static part (ie HTML, CSS etc), which gets copied directly to the response by the JSP Engine.
Dynamic part, which contains anything that can be translated and compiled by the JSP Engine.
There are three types of dynamic elements. (TIP: remember SAD as an abbreviation for Scripting, Action and
Directive elements).
Scripting Elements: A JSP element that provides embedded Java statements. There are three types of scripting
elements.
Declaration Element: is the embedded Java declaration statement, which gets inserted at the Servlet class
level.
<%! Calendar c = Calendar.getInstance(); %>
Important: declaring variables via this element is not thread-safe, because this variable ends up in the generated Servlet as an
instance variable, not within the body of the _jspservice() method. Ensure their access is either read-only or synchronized.
Expression Element: is the embedded Java expression, which gets evaluated by the service method.
<%= new Date()>
Find more WWW.ThesisScientist.com
Enterprise Java 79
Scriptlet Elements: are the embedded Java statements, which get executed as part of the service method.
(Note: Not recommended to use Scriptlet elements because they don‟t provide reusability and maintainability.
Use custom tags (like JSTL, JSF tags, etc) or beans instead).
<%
//Java codes
String userName=null;
userName=request.getParameter("userName");
%>
Action Elements: A JSP element that provides information for execution phase.
<jsp:useBean id="object_name" class="class_name"/>
<jsp:include page="scripts/login.jsp" />
Directive Elements: A JSP element that provides global information for the translation phase.
<%@ page import=”java.util.Date” %>
<%@ include file=”myJSP” %>
<%@ taglib uri=”tagliburi” prefix=”myTag”%>
Q 30: What are the different scope values or what are the different scope values for <jsp:usebean> ? SF
A 30:
Scope Object Comment
Page PageContext Available to the handling JSP page only.
Request Request Available to the handling JSP page or Servlet and forwarded JSP page or Servlet.
Session Session Available to any JSP Page or Servlet within the same session.
Application Application Available to all the JSP pages and Servlets within the same Web Application.
Q 31: What are the differences between static and a dynamic include? SF DC
A 31:
Static include <%@ include %> Dynamic include <jsp:include …..>
During the translation or compilation phase all the The dynamically included JSP is compiled into a separate Servlet.
included JSP pages are compiled into a single Servlet. It is a separate resource, which gets to process the request, and
the content generated by this resource is included in the JSP
response.
No run time performance overhead. Has run time performance overhead.
Which one to use: Use “static includes” when a JSP page does not change very often. For the pages, which change frequently,
use dynamic includes. JVM has a 64kb limit on the size of the method and the entire JSP page is rendered as a single method. If
a JSP page is greater than 64kb, this probably indicates poor implementation. When this method reaches its limit of 64kb it
throws an error. This error can be overcome by splitting the JSP files and including them dynamically (i.e. using
<jsp:include…….>) because the dynamic includes generate separate JSP Servlet for each included file.
Note: The “dynamic include” (jsp:include) has a flush attribute. This attribute indicates whether the buffer should be flushed
before including the new content. In JSP 1.1 you will get an error if you omit this attribute. In JSP 1.2 you can omit this attribute
because the flush attribute defaults to false.
Q 32: What are implicit objects and list them? SF
A 32: Implicit objects are the objects that are available for the use in JSP documents without being declared first. These
objects are parsed by the JSP engine and inserted into the generated Servlet. The implicit objects are:
Implicit object Scope comment
request Request request
response Page response
pageContext Page page environment
session Session session
application Application same as ServletContext
out Page writing to the outputstream
config Page same as ServletConfig
page Page this page‟s Servlet
exception Page exception created on this page.
Find more WWW.ThesisScientist.com
80 Enterprise Java
Note: Care should be taken not to name your objects the same name as the implicit objects. If you have your own object with the
same name, then the implicit objects take precedence over your own object.
Q 33: Explain hidden and output comments? SF
A 33: An output comment is a comment that is sent to the client where it is viewable in the browser‟s source. CO
<!--This is a comment which is sent to the client-->
A hidden comment documents a JSP page but does not get sent to the client. The JSP engine ignores a hidden
comment, and does not process any code within hidden comment tags.
<%-- This comment will not be visible to the client --%>
Q 34: Is JSP variable declaration thread safe? CI
A 34: No. The declaration of variables in JSP is not thread-safe, because the declared variables end up in the generated
Servlet as an instance variable, not within the body of the _jspservice() method.
The following declaration is not thread safe: because these are declarations, and will only be evaluated
once when the page is loaded
<%! int a = 5 %>
The following declaration is thread safe: because the variables declared inside the scriplets have the local
scope and not shared.
<% int a = 5 %>
Q 35: Explain JSP URL mapping? What is URL hiding or protecting the JSP page? SFSE
A 35: As shown in the figure, the JSP resources usually reside directly or under subdirectories (e.g. myPath) of the
document root, which are directly accessible to the user through the URL. If you want to protect your Web
resources then hiding the JSP files behind the WEB-INF directory can protect the JSP files, css (cascading style
sheets) files, Java Script files, pdf files, image files, html files etc from direct access. The request should be made
to a servlet who is responsible for authenticating and authorising the user before returning the protected JSP page
or its resources.
JSP URL Mapping
URL http://<hostnam e:port>/<webapp name><pathname>/<resourcename>
URL eg http://localhost:8080/myApps/myPath/myPage.jsp
File SERVER_HOMEW ebAppsmyAppsmyPathmyPage.jsp
Server Root
Unhidden URL
Document root
Hidden URL
myPage.jsp is dircetly accessible through URL myPage.jsp is hidden or protected. cannot be
MyApps directly accessed through URL
MyApps
myPath myPage.jsp
W EB-INF
W EB-INF
myPath myPage.jsp
lib
lib
classes
classes
Find more WWW.ThesisScientist.com
Enterprise Java 81
Q 36: What are custom tags? Explain how to build custom tags? SF
A 36: Custom JSP tag is a tag you define. You define how a tag, its attributes and its body are interpreted, and then
group your tags into collections called tag libraries that can be used in any number of JSP files. So basically it is a
reusable and extensible JSP only solution. The pre-built tags also can speed up Web development. CO
STEP: 1
Construct the Tag handler class that defines the behaviour.
T ag E valu atio n P ro cess
start
C all setX X X () m eth o ds on the Tag
d oS tartTag ()
evaluate body of the T ag loop
doA fterB ody()
doE ndT ag()
release()
S am p le co d e u sin g o n ly d o S atartT ag ()
pack age m yT agP k g;
public class M yT ag extends T agS upport
{
int attr = null;
public int setA ttr(int attr){this .attr = attr} public
int getA ttr(){return attr;}
public int doS tartT ag() throw s JspE xception {
.......
return S K IP _ B O D Y ;
}
public void release(){.....}
}
STEP: 2
The Tag library descriptor file (*.tld) maps the XML element names to the tag implementations. The code sample
MyTagDesc.tld is shown below:
<taglib>
<tag>
<name>tag1</name>
<tagclass>myTagPkg.MyTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>attr</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>
STEP: 3
The web.xml deployment descriptor maps the URI to the location of the *.tld (Tag Library Descriptor) file. The code
sample web.xml file is shown below:
<web-app>
<taglib>
<taglib-uri>/WEB-INF/MyTagURI</taglib-uri> <taglib-
location>/WEB-INF/tags/MyTagDesc.tld</taglib-location>
</taglib>
</web-app>
STEP: 4
The JSP file declares and then uses the tag library as shown below:
<%@ taglib uri="/WEB-INF/ MyTagURI" prefix="myTag" %>
< myTag:tag1 attr=”abc”></ myTag:tag1> or < myTag:tag1 attr=”abc” />
Find more WWW.ThesisScientist.com
82 Enterprise Java
Q 37: What is a TagExtraInfo class? SF
A 37: A TagExtraInfo class provides extra information about tag attributes to the JSP container at translation time.
Returns information about the scripting variables that the tag makes available to the rest of the JSP page
to use. The method used is:
VariableInfo[] getVariableInfo(TagData td)
Example
<html>
<myTag:addObjectsToArray name=”myArray” />
<myTag:displayArray name=”myArray” />
</html>
Without the use of TagExtraInfo, if you want to manipulate the attribute myArray in the above code in a
scriptlet it will not be possible. This is because it does not place the myArray object on the page. You can still
use pageContext.getAttribute() but that may not be a cleaner approach because it relies on the page
designer to correctly cast to object type. The TagExtraInfo can be used to make items stored in the
pageContext via setAttribute() method available to the scriptlet as shown below.
<html>
<myTag:addObjectsToArray name=”myArray” />
<%-- scriplet code %>
<% for(int i=0; i<myArray.length;i++){
html += <LI> + myArray[i] + </LI>;
%>
</html>
Validates the attributes passed to the Tag at translation time.
Example It can validate the myArray array list to have not more than 100 objects. The method used is:
boolean isValid(TagData data)
Q 38: What is the difference between custom JSP tags and JavaBeans? SF
A 38: In the context of a JSP page, both accomplish similar goals but the differences are:
Custom Tags JavaBeans
Can manipulate JSP content. Can‟t manipulate JSP content.
Custom tags can simplify the complex operations much Easier to set up.
better than the bean can. But require a bit more work to
set up.
Used only in JSPs in a relatively self-contained manner. Can be used in both Servlets and JSPs. You can define a bean in
one Servlet and use them in another Servlet or a JSP page.
JavaBeans declaration and usage example: CO
<jsp:useBean id="identifier" class="packageName.className"/> <jsp:setProperty
name="identifier" property="classField" value="someValue" />
<jsp:getProperty name="identifier" property="classField" /> <%=identifier.getclassField() %>
Q 39: Tell me about JSP best practices? BP
A 39:
Separate HTML code from the Java code: Combining HTML and Java code in the same source code can
make the code less readable. Mixing HTML and scriplet will make the code extremely difficult to read and
maintain. The display or behaviour logic can be implemented as a custom tags by the Java developers and
Web designers can use these Tags as the ordinary XHTML tags.
Place data access logic in JavaBeans: The code within the JavaBean is readily accessible to other JSPs
and Servlets.
Find more WWW.ThesisScientist.com
Enterprise Java 83
Factor shared behaviour out of Custom Tags into common JavaBeans classes: The custom tags are not
used outside JSPs. To avoid duplication of behaviour or business logic, move the logic into JavaBeans and
get the custom tags to utilize the beans.
Choose the right “include” mechanism: What are the differences between static and a dynamic include?
Using includes will improve code reuse and maintenance through modular design. Which one to use? Refer
Q31 in Enterprise section.
Use style sheets (e.g. css), template mechanism (e.g. struts tiles etc) and appropriate comments (both
hidden and output comments).
Q 40: How will you avoid scriptlet code in JSP? BP
A 40: Use JavaBeans or Custom Tags instead.
Enterprise - JDBC
Q 41: What is JDBC? How do you connect to a database? SF
A 41: JDBC stands for Java Database Connectivity. It is an API which provides easy connection to a wide range of
databases. To connect to a database we need to load the appropriate driver and then request for a connection
object. The Class.forName(….) will load the driver and register it with the DriverManager (Refer Q4 in Java section
for dynamic class loading).
Class.forName(“oracle.jdbc.driver.OracleDriver”);
String url = jdbc:oracle:thin:@hostname:1526:myDB;
Connection myConnection = DriverManager.getConnection(url, “username”, “password”);
The DataSource interface provides an alternative to the DriverManager for making a connection. DataSource
makes the code more portable than DriverManager because it work with JNDI and it is created, deployed and
managed separately from the application that uses it. If the DataSource location changes, then there is no need to
change the code but change the configuration properties in the server. This makes your application code easier to
maintain. DataSource allows the use of connection pooling and support for distributed transactions. A DataSource
is not only a database but also can be a file or a spreadsheet. A DataSource object can be bound to JNDI and an
application can retrieve and use it to make a connection to the database. J2EE application servers provide tools to
define your DataSource with a JNDI name. When the server starts it loads all the DataSources into the Application
Server‟s JNDI service.
DataSource configuration properties are shown below:
JNDI Name Æ jdbc/myDataSource
URL Æ jdbc:oracle:thin:@hostname:1526:myDB
UserName, Password
Implementation classname Æ oracle.jdbc.pool.OracleConnectionPoolDataSource
Classpath Æ ora_jdbc.jar
Connection pooling settings like Æ minimum pool size, maximum pool size, connection timeout, statement cache size etc.
Once the DataSource has been set up, then you can get the connection object as follows:
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("jdbc/myDataSource");
Connection myConnection = ds.getConnection(“username”,”password”);
In a basic implementation a Connection obtained from a DataSource and a DriverManager are identical. But,
DataSource is recommended because of its better portability.
Design Pattern: JDBC architecture decouples an abstraction from its implementation so that the implementation
can vary independent of the abstraction. This is an example of the bridge design pattern . The JDBC API
provides the abstraction and the JDBC drivers provide the implementation. New drivers can be plugged-in to the
JDBC API without changing the client code.
Q 42: What are JDBC Statements? What are different types of statements? How can you create them? SF
Find more WWW.ThesisScientist.com
84 Enterprise Java
A 42: A statement object is responsible for sending the SQL statements to the Database. Statement objects are created
from the connection object and then executed. CO
Statement stmt = myConnection.createStatement();
ResultSet rs = stmt.executeQuery(“SELECT id, name FROM myTable where id =1245”);// to read
Or
stmt.executeUpdate(“INSERT INTO (field1,field2) values (1,3)”);// to insert/update/delete/create table
The types of statements are:
Statement (regular statement as shown above)
PreparedStatement (more efficient than statement due to pre-compilation of SQL)
CallableStatement (to call stored procedures on the database)
To use prepared statement:
PreparedStatement prepStmt =
myConnection.prepareStatement("SELECT id, name FROM myTable where id = ? ");
prepStmt.setInt(1, 1245);
Callable statements are used for calling stored procedures.
CallableStatement calStmt = myConnection.prepareCall("{call PROC_SHOWMYBOOKS}");
ResultSet rs = cs.executeQuery();
Q 43: What is a Transaction? What does setAutoCommit do? TIPI
A 43: A transaction is a set of operations that should be completed as a unit. If one operation fails then all the other
operations fail as well. For example if you transfer funds between two accounts there will be two operations in the
set
Withdraw money from one account.
Deposit money into other account.
These two operations should be completed as a single unit. Otherwise your money will get lost if the withdrawal is
successful and the deposit fails. There are four characteristics (ACID properties) for a Transaction.
Atomicity Consistency Isolation Durability
All the individual The design of the Prevents data being corrupted by concurrent
operations should transaction should access by two different sources. It keeps
either complete or fail. update the database transactions isolated or separated from each
correctly. other until they are finished.
Ensures that the
database is definitely
updated once the
Transaction is completed.
Transactions maintain data integrity. A transaction has a beginning and an end like everything else in life. The
setAutocommit(….) , commit() and rollback() are used for marking the transactions (known as transaction
demarcation). When a connection is created, it is in auto-commit mode. This means that each individual SQL
statement is treated as a transaction and will be automatically committed immediately after it is executed. The way
to allow two or more statements to be grouped into a transaction is to disable auto-commit mode: CO
try{
Connection myConnection = dataSource.getConnection();
// set autoCommit to false myConnection
.setAutoCommit(false);
withdrawMoneyFromFirstAccount(.............); //operation 1
depositMoneyIntoSecondAccount(.............); //operation 2
myConnection .commit();
}
catch(Exception sqle){
try{
myConnection .rollback();
}catch( Exception e){}
}
finally{
try{if( conn != null) {conn.close();}} catch( Exception e) {}
}
Find more WWW.ThesisScientist.com
Enterprise Java 85
The above code ensures that both operation 1 and operation 2 succeed or fail as an atomic unit and consequently
leaves the database in a consistent state. Also turning auto-commit off will provide better performance.
Q 44: What is the difference between JDBC-1.0 and JDBC-2.0? What are Scrollable ResultSets, Updateable ResultSets,
RowSets, and Batch updates? SF
A 44: JDBC2.0 has the following additional features or functionality:
JDBC 1.0 JDBC 2.0
With JDBC-1.0 the With JDBC 2.0 ResultSets are updateable and also you can move forward and backward.
ResultSet functionality
was limited. There was no Example This example creates an updateable and scroll-sensitive ResultSet
support for updates of any
kind and scrolling through Statement stmt = myConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
the ResultSets was ResultSet.CONCUR_UPDATEABLE)
forward only (no going
back)
With JDBC-1.0 the With JDBC-2.0 statement objects can be grouped into a batch and executed at once. We call
statement objects submits addBatch() multiple times to create our batch and then we call executeBatch() to send the SQL
updates to the database statements off to database to be executed as a batch (this minimises the network overhead).
individually within same or
separate transactions. Example
This is very inefficient
large amounts of data Statement stmt = myConnection.createStatement();
need to be updated. stmt.addBatch(“INSERT INTO myTable1 VALUES (1,”ABC”)”);
stmt.addBatch(“INSERT INTO myTable1 VALUES (2,”DEF”)”);
stmt.addBatch(“INSERT INTO myTable1 VALUES (3,”XYZ”)”);
…
int[] countInserts = stmt.executeBatch();
- The JDBC-2.0 optional package provides a RowSet interface, which extends the ResultSet. One
of the implementations of the RowSet is the CachedRowSet, which can be considered as a
disconnected ResultSet.
Q 45: How to avoid the “running out of cursors” problem? DCPIMI
A 45: A database can run out of cursors if the connection is not closed properly or the DBA has not allocated enough
cursors. In a Java code it is essential that we close all the valuable resources in a try{} and finally{} block. The
finally{} block is always executed even if there is an exception thrown from the catch {} block. So the resources like
connections and statements should be closed in a finally {} block. CO
Try{} Finally {} blocks to close Exceptions
Wrong Approach - Right Approach -
Connections and statements will not be closed if there public void executeSQL() throws SQLException{
is an exception: try{
Connection con = DriverManager.getConnection(........);
public void executeSQL() throws SQLException{ .....
Statement stmt = con.createStatement();
Connection con = DriverManager.getConnection(........);
....
//line 20 where exception is thrown
..... ResultSet rs = stmt.executeQuery("SELECT * from myTable");
Statement stmt = con.createStatement(); .....
.... }
//line 20 where exception is thrown finally{
ResultSet rs = stmt.executeQuery("SELECT * from myTable"); try {
..... if(rs != null) rs.close();
rs.close(); if(stmt != null) stmt.close();
stmt.close(); if(con != null) con.close();
con.close(); }
} catch(Exception e){}
}
Note: if an exception is thrown at line 20 then the }
close() statements are never reached.
Note: if an exception is thrown at line 20 then the
finally clause is called before the exception is thrown to
the method.
Find more WWW.ThesisScientist.com
86 Enterprise Java
Q 46: What is the difference between statements and prepared statements? SFPISEBP
A 46:
Prepared statements offer better performance, as they are pre-compiled. Prepared statements reuse the
same execution plan for different arguments rather than creating a new execution plan every time. Prepared
statements use bind arguments, which are sent to the database engine. This allows mapping different
requests with same prepared statement but different arguments to execute the same execution plan.
Prepared statements are more secure because they use bind variables, which can prevent SQL injection
attack.
The most common type of SQL injection attack is SQL manipulation. The attacker attempts to modify the
SQL statement by adding elements to the WHERE clause or extending the SQL with the set operators like
UNION, INTERSECT etc.
Example Let us look at the following SQL:
SELECT * FROM users where username=‟bob‟ AND password=‟xyfdsw‟ ;
The attacker can manipulate the SQL as follows
SELECT * FROM users where username=‟bob‟ AND password=‟xyfdsw‟ OR „a‟ = „a‟ ;
The above “WHERE” clause is always true because of the operator precedence. The PreparedStatement
can prevent this by using bind variables:
String strSQL = SELECT * FROM users where username=? AND password=?);
PreparedStatement pstmt = myConnection.prepareStatement(strSQL);
pstmt.setString(1,”bob”);
pstmt.setString(2, “xyfdsw”);
pstmt.execute();
Q 47: Explain differences among java.util.Date, java.sql.Date, java.sql.Time, and java.sql.Timestamp? SF
A 47: As shown below all the sql Date classes extend the util Date class.
Java Date classes
java.util.Date
java.sql.Datejava.sql.Time java.sql.TimeStamp
java.util.Date - class supports both the Date (ie year/month/date etc) and the Time (hour, minute, second, and
millisecond) components.
java.sql.Date - class supports only the Date (ie year/month/date etc) component. The hours, minutes, seconds
and milliseconds of the Time component will be set to zero in the particular time zone with which the instance is
associated.
java.sql.Time - class supports only Time (ie hour, minute, second, and millisecond) component. The date
components should be set to the "zero epoch" value of January 1, 1970 and should not be accessed.
java.sql.TimeStamp – class supports both Date (ie year/month/date etc) and the Time (hour, minute, second,
millisecond and nanosecond) components.
Note: the subtle difference between java.util.Date and java.sql.Date.
Find more WWW.ThesisScientist.com
Enterprise Java 87
To keep track of time Java counts the number of milliseconds from January 1, 1970 and stores it as a long value in
java.util.Date class. The GregorianCalendar class provides us a way to represent an arbitrary date. The
GregorianCalendar class also provides methods for manipulating dates.
Enterprise – JNDI & LDAP
Q 48: What is JNDI? And what are the typical uses within a J2EE application? SF
A 48: JNDI stands for Java Naming and Directory Interface. It provides a generic interface to LDAP (Lightweight
Directory Access Protocol) and other directory services like NDS, DNS (Domain Name System) etc. It provides a
means for an application to locate components that exist in a name space according to certain attributes. A J2EE
application component uses JNDI interfaces to look up and reference system-provided and user-defined objects in
a component environment. JNDI is not specific to a particular naming or directory service. It can be used to access
many different kinds of systems including file systems.
The JNDI API enables applications to look up objects such as DataSources, EJBs, MailSessions and JMS by
name. The Objects can be loaded into the JNDI tree using a J2EE application server‟s administration console. To
load an object in a JNDI tree, choose a name under which you want the object to appear in a JNDI tree. J2EE
deployment descriptors indicate the placement of J2EE components in a JNDI tree.
J N D I T re e
In it ia lC o n t e x t
O b je c ts a n d /o r S e rv ic e
s u b - c o n t e x t
n a m e d o b je c t/s e rv ic
e re fe re n c e
n a m e d o b je c t/s e rv ic
e re fe re n c e
N o te : J N D I tre e liv e s in th e s e rv e r a s a c o lle c tio n o f n a m e d o b je c t o r s e rv ic e re fe re n c e s .
The parameters you have to define for JNDI service are as follows:
The name service provider class name (WsnInitialContext for Websphere).
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.ibm.websphere.naming.WsnInitialContextFactory");
The provider URL :
The name service hostname.
The name service port number.
env.put(Context. PROVIDER_URL, " iiop://localhost:1050");
Context ctx = new InitialContext(env);
JNDI is like a file system or a Database.
File System JNDI Database
File system starts with a mounted JNDI starts with an InitialContext. i.e. new Database instance
drive like c: InitialContext().
Find more WWW.ThesisScientist.com
88 Enterprise Java
Uses a subdirectory. C:subdir1 Navigate to a sub-context. e.g. Subcontext1 Tablespace
Access a subdirectory Drill down through other sub-contexts. e.g. Table
c:subdir1subdir2 subcontext1/subcontext2
Access a file. Access an object or a service. Data
C:subdir1subdir2myFile New InitialContext().lookup(“objectName”);
Example: Example: Example:
c:subdir1subdir2myFile iiop://myserver:2578/subcontext1.subcontext2.o Select * from demo.myTable
bjectName
Q 49: Explain the difference between the look up of “java:comp/env/ejb/MyBean” and “ejb/MyBean”? SF
A 49:
java:comp/env/ejb/MyBean ejb/MyBean
This is a logical reference, which will be used in your code. This is a physical reference where an object will be mapped to in
a JNDI tree.
The logical reference (or alias) java:comp/env/ejb/MyBean is the recommended approach because you cannot
guarantee that the physical JNDI location (ejb/MyBean) you specify in your code will be available. Your code will
break if the physical location is changed. The deployer will not be able to modify your code. Logical references
solve this problem by binding the logical name to the physical name in the application server. The logical names
will be declared in the deployment descriptors (web.xml and/or ejb-jar.xml) as follows and these will be mapped to
physical JNDI locations in the application server specific deployment descriptors.
To look up a JDBC resource from either WEB (web.xml) or EJB (ejb-jar.xml) tier, the deployment descriptor should
have the following entry:
<resource-ref>
<description>The DataSource</description> <res-
ref-name>jdbc/MyDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type> <res-
auth>Container</res-auth>
</resource-ref>
To use it:
Context ctx = new InitialContext();
Object ref = ctx.lookup(java:comp/env/jdbc/MyDataSource);
This will make full logical path to the
bean as:
java:comp/env/jdbc/MyDataSource
To look up EJBs from another EJB or a WEB module, the deployment descriptor should have the following entry:
<ejb-ref>
<description>myBean</description>
<ejb-ref-name>ejb/MyBean</ejb-ref-
name> <ejb-ref-type>Entity</ejb-ref-type>
<ejb-link>Region</ejb-link>
<home>com.MyBeanHome</home>
<remote>com.MyBean</remote>
</ejb-ref>
To use it:
Context ctx = new InitialContext();
Object ref = ctx.lookup(java:comp/env/ejb/MyBean);
This will make full logical path to the
bean as:
java:comp/env/ejb/MyBean
Q 50: What is a JNDI InitialContext? SF
A 50: All naming operations are relative to a context. The InitalContext implements the Context interface and provides
an entry point for the resolution of names.
Q 51: What is an LDAP server? And what is it used for in an enterprise environment? SFSE
A 51: LDAP stands for Lightweight Directory Access Protocol. This is an extensible open network protocol standard that
provides access to distributed directory services. LDAP is an Internet standard for directory services that run on
TCP/IP. Under OpenLDAP and related servers, there are two servers – slapd, the LDAP daemon where the
queries are sent to and slurpd, the replication daemon where data from one server is pushed to one or more
Find more WWW.ThesisScientist.com
Enterprise Java 89
slave servers. By having multiple servers hosting the same data, you can increase reliability, scalability, and
availability.
It defines the operations one may perform like search, add, delete, modify, change name
It defines how operations and data are conveyed.
LDAP has the potential to consolidate all the existing application specific information like user, company phone
and e-mail lists. This means that the change made on an LDAP server will take effect on every directory service
based application that uses this piece of user information. The variety of information about a new user can be
added through a single interface which will be made available to Unix account, NT account, e-mail server, Web
Server, Job specific news groups etc. When the user leaves his account can be disabled to all the services in a
single operation.
So LDAP is most useful to provide “white pages” (e.g. names, phone numbers, roles etc) and “yellow pages” (e.g.
location of printers, application servers etc) like services. Typically in a J2EE application environment it will be
used to authenticate and authorise users.
Why use LDAP when you can do the same with relational database (RDBMS)?
In general LDAP servers and RDBMS are designed to provide different types of services. LDAP is an open
standard access mechanism, so an RDBMS can talk LDAP. However the servers, which are built on LDAP, are
optimized for read access so likely to be much faster than RDBMS in providing read access. So in a nutshell,
LDAP is more useful when the information is often searched but rarely modified. (Another difference is that
RDBMS systems store information in rows of tables whereas LDAP uses object oriented hierarchies of entries.) .
Key LDAP Terms:
DIT: Directory Information Tree. Hierarchical structure of entries, those make up a directory.
DN: Distinguished Name. This uniquely identifies an entry in the directory. A DN is made up of relative DNs of
the entry and each of entry‟s parent entries up to the root of the tree. DN is read from right to left and commas
separate these names. For example „cn=Peter Smith, o=ACME, c=AUS‟.
objectClass: An objectClass is a formal definition of a specific kind of objects that can be stored in the directory.
An ObjectClass is a distinct, named set of attributes that represent something concrete such as a user, a
computer, or an application.
LDAP URL: This is a string that specifies the location of an LDAP resource. An LDAP URL consists of a server
host and a port, search scope, baseDN, filter, attributes and extensions. Refer to diagram below:
LD A P D irectory structure
ro o t
o b je c tC la s s F a c to ry = c o u n try
c = A U S c = U K
o b je c tC la s s F a c to ry = o rg a n iz a tio n
o = A C M E o = X Y Z R e ta il o = Q u ic k C o rp
o b je c tC la s s F a c to ry = u s e r
cn=Peter Sm ith
m ail=PSm ith@ N A B .com
phone=88888888
Find more WWW.ThesisScientist.com
90 Enterprise Java
So the complete distinguished name for bottom left entry (ie Peter Smith) is cn=Peter Smith, o=ACME, c=AUS.
Each entry must have at least one attribute that is used to name the entry. To manage the part of the LDAP
directory we should specify the highest level parent distinguished names in the server configuration. These
distinguished names are called suffixes. The server can access all the objects that are below the specified suffix
in the hierarchy. For example in the above diagram to answer queries about „Peter Smith‟ the server should have
the suffix of „o=ACME, c=AUS‟. So we can look for “Peter Smith” by using the following distinguished name:
cn=Peter Smith, o=ACME, c=AUS //where o=ACME, c=AUS is the suffix
LDAP schema: defines rules that specify the types of objects that a directory may contain and the required
optional attributes that entries of different types should have.
Filters: In LDAP the basic way to retrieve data is done with filters. There is a wide variety of operators that can be
used as follows: & (and), | (or), ! (not), ~= (approx equal), >= (greater than or equal), <= (less than or equal), *
(any) etc.
(& (uid=a*) (uid=*l) )
So where does JNDI fit into this LDAP? JNDI provides a standard API for interacting with naming and directory
services using a service provider interface (SPI), which is analogous to JDBC driver. To connect to an LDAP
server, you must obtain a reference to an object that implements the DirContext. In most applications, this is
done by using an IntialDirContext object that takes a Hashtable as an argument:
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, “com.sun.jndi.ldap.LdapCtxFactory”);
env.put(Context.PROVIDER_URL, “ldap://localhost:387”);
env.put(Context.SECURITY_AUTHENTICATION, “simple”);
env.put(Context.SECURITY_PRINCIPAL, “cn=Directory Manager”);
env.put(Context.SECURITY_CREDENTIALS, “myPassword”);
DirContext ctx = new InitialDirContext(env);
Enterprise - RMI
Q 52: Explain the RMI architecture? SF
A 52: Java Remote Method Invocation (RMI) provides a way for a Java program on one machine to communicate with
objects residing in different JVMs (or processes or address spaces). The important parts of the RMI architecture
are the stub class, object serialization and the skeleton class. RMI uses a layered architecture where each of the
layers can be enhanced without affecting the other layers. The layers can be summarised as follows:
Application Layer: The client and server program
Stub & Skeleton Layer: Intercepts method calls made by the client. Redirects these calls to a remote
RMI service.
Remote Reference Layer: Sets up connections to remote address spaces, manages connections, and
understands how to interpret and manage references made from clients to the remote service objects.
Transport layer: Based on TCP/IP connections between machines in a network. It provides basic connectivity,
as well as some firewall penetration strategies.
Design pattern: RMI stub classes provide a reference to a skeleton object located in a different address space on
the same or different machine. This is a typical example of a proxy design pattern (i.e. remote proxy), which
makes an object executing in another JVM appear like a local object. In JDK 5.0 and later, the RMI facility uses
dynamic proxies instead of generated stubs, which makes RMI easier to use. Refer Q11 in “How would you
about…” section for a more detailed discussion on proxy design pattern and dynamic proxies.
Find more WWW.ThesisScientist.com
Enterprise Java 91
R M I A rchitecture
C lie n t S e rv e r
C lient Process
C lie n t
b je c
ts Stub
R em ote R eference
M anager
2. look up Stub
3 . R eturn Stub Stub
4.
M etho d
call o n r
ser
5. S end re
em ote
ver O bjectssu
lts or Ex
ception
Server Process
R M I R egistry
(or JNDI Server) 1
.
L
o
R em ote a
d
S
O bjects t
b
u
s
Skeleton
RMITransportLayer R em ote R eference
M anager
RMI Transport Layer
N ote: Steps 4 & 5 are logical explanation only. N either the Stubs nor Skeletons use sockets
directly. The actual calls are m ade through the R em ote R eference M anager. The R em ote
R eference M anager handles the actual details of
com m unicating w ith the rem ote process. This extra layer m anages netw ork com m
unication and conserves scarce resources like sockets.
E x a m p le
Program 1 stub stub Program 2
skeleton skeleton
RMI runtime steps (as shown in the diagram above) involved are:
Step 1: Start RMI registry and then the RMI server. Bind the remote objects to the RMI registry.
Step 2: The client process will look up the remote object from the RMI registry.
Step 3: The lookup will return the stub to the client process from the server process.
Step 4: The client process will invoke method calls on the stub. The stub calls the skeleton on the server process
through the RMI reference manager.
Step 5: The skeleton will execute the actual method call on the remote object and return the result or an exception
to the client process via the RMI reference manager and the stub.
Q 53: What is a remote object? Why should we extend UnicastRemoteObject? SF
A 53: A remote object is one whose methods can be invoked from another JVM (or process). A remote object class must
implement the Remote interface. A RMI Server is an application that creates a number of remote objects.
An RMI Server is responsible for
Creating an instance of the remote object (e.g. CarImpl instance = new CarImpl()).
Exporting the remote object.
Binding the instance of the remote object to the RMI registry.
By exporting a remote object you make it available to accept incoming calls from the client. You can export the
remote object by either extending the java.rmi.server.UnicastRemoteObject or if your class is already extending
another class then you can use the static method
Find more WWW.ThesisScientist.com
92 Enterprise Java
UnicastRemoteObject.exportObject (this);
If the UnicastRemoteObject is not extended (ie if you use UnicastRemoteObject.exportObject(…) then the
implementation class is responsible for the correct implementations of the hashCode(), equals() and toString()
methods. A remote object is registered in the RMI registry using:
Naming.rebind(String serviceName, Remote remoteObj);
Remote Objects
java.rmi.Remote Remote interface java.rmi.server.RemoteServer
eg: public interface Car extends Remote{}
Implementation of Remote interface java.rmi.server.UnicastRemoteObject
eg: public class CarImpl extends UnicastRemoteObject implements Car{}
Compile Car &
CarImpl
use rmic to generate stubs & skeletons
rmic -d /classes CarImpl
d
g
entea
r er
e at
n e
e d
g
instantiated
stub class skeleton class
instantiated
instantiated
Client Object stub Object skeleton Object remote Object
instances instances instances instances
Q 54: What is the difference between RMI and CORBA? SF
A 54:
RMI CORBA
Java only solution. The interfaces, CORBA was made specifically for interoperability among various
implementations and the clients are all written languages. For example the server could be written in C++ and the
in Java. business logic can be in Java and the client can be written in COBOL.
RMI allows dynamic loading of classes at In a CORBA environment with multi-language support it is not possible to
runtime. have dynamic loading.
Q 55: What are the services provided by the RMI Object? SF
A 55: In addition to its remote object architecture RMI provides some basic object services, which can be used in a
distributed application. These services are
Object naming/registry service: RMI servers can provide services to clients by registering one or more
remote objects with its local RMI registry.
Object activation service: It provides a way for server (or remote) objects to be started on an as-needed
basis. Without the remote activation service, a server object has to be registered with the RMI registry service.
Distributed garbage collection: It is an automatic process where an object, which has no further remote
references, becomes a candidate for garbage collection.
Q 56: What are the differences between RMI and a socket? SF
A 56:
Find more WWW.ThesisScientist.com
Enterprise Java 93
Socket RMI
A socket is a transport mechanism. Sockets are like RMI uses sockets. RMI is object oriented. Methods can be
applying procedural networking to object oriented invoked on the remote objects running on a separate JVM.
environment.
Sockets-based network programming can be laborious. RMI provides a convenient abstraction over raw sockets. Can
send and receive any valid Java object utilizing underlying
object serialization without having to worry about using data
streams.
Q 57: How will you pass parameters in RMI? SF
A 57:
Primitive types are passed by value (e.g. int, char, boolean etc).
References to remote objects (i.e. objects which implements the Remote interface) are passed as remote
references that allows the client process to invoke methods on the remote objects.
Non-remote objects are passed by value using object serialization. These objects should allow them to be
serialized by implementing the java.io.Serializable interface.
Note: The client process initiates the invocation of the remote method by calling the method on the stub. The stub
(client side proxy of the remote object) has a reference to the remote object and forwards the call to the skeleton
(server side proxy of the remote object) through the reference manager by marshalling the method arguments.
During marshalling each object is checked to determine whether it implements java.rmi.Remote interface. If it does
then the remote reference is used as the marshalled data otherwise the object is serialized into byte streams and
sent to the remote process where it is deserialized into a copy of the local object. The skeleton converts this
request from the stub into the appropriate method call on the actual remote object by unmarshalling the method
arguments into local stubs on the server (if they are remote reference) or into local copy (if they are sent as
serialized objects).
Q 58: What is HTTP tunnelling or how do you make RMI calls across firewalls? SFSE
A 58: RMI transport layer generally opens direct sockets to the server. Many Intranets have firewalls that do not allow
this. To get through the firewall an RMI call can be embedded within the firewall-trusted HTTP protocol. To get
across firewalls, RMI makes use of HTTP tunnelling by encapsulating RMI calls within an HTTP POST request.
HTTP tunnelling
Proxy Server
Web Server
on port 80
HTTPe
ncapsu
latedR
MIcall
c
a
l
l
f
o
r
w
a
r
d
e
d
b
y
C
G
I
s
c
r
i
p
t
RMI Client
RMI Server
Firewall Firewall
When a firewall proxy server can forward HTTP requests only to a well-known HTTP port: The firewall proxy
server will forward the request to a HTTP server listening on port 80, and a CGI script will be executed to forward
the call to the target RMI server port on the same machine.
When a firewall proxy server can forward HTTP requests to any arbitrary port: The firewall proxy will forward
to any arbitrary port on the host machine and then it is forwarded directly to the port on which RMI Server is
listening.
The disadvantages of HTTP tunnelling are performance degradation, prevents RMI applications from using call-
backs, CGI script will redirect any incoming request to any port, which is a security loophole, RMI calls cannot be
multiplexed through a single connection since HTTP tunnelling follows a request/response protocol etc.
Find more WWW.ThesisScientist.com
94 Enterprise Java
Q 59: Why use RMI when we can achieve the same benefits from EJB? SF
A 59: EJBs are distributed components, which use the RMI framework for object distribution. An EJB application server
provides more services like transactions, object pooling, database connection-pooling etc, which RMI does not
provide. These extra services that are provided by the EJB server simplify the programming effort at the cost of
performance overhead compared to plain RMI. So if performance is important then pure RMI may be a better
solution (or under extreme situations Sockets can offer better performance than RMI).
Note: The decision to go for RMI or EJB or Sockets should be based on requirements such as maintainability, ease of coding,
extensibility, performance, scalability, availability of application servers, business requirements etc.
Enterprise – EJB 2.x
There are various persistence mechanisms available like EJB 2.x, Object-to-Relational (O/R) mapping tools like Hibernate, JDBC and
EJB 3.0 (new kid on the block) etc. You will have to evaluate the products based on the application you are building because each
product has its strengths and weaknesses. You will find yourself trading ease of use for scalability, standards with support for special
features like stored procedures, etc. Some factors will be more important to you than for others. There is no one size fits all solution.
Let‟s compare some of the persistence products:
EJB 2.x EJB 3.0 Hibernate JDBC
PROS: PROS: PROS: PROS:
ƒ Security is provided for free ƒ A lot less artefacts than EJB ƒ Simple to write CRUD ƒ You have complete control
for accessing the EJB. 2.x. Make use of annotations (create, retrieve, update, over the persistence
ƒ Provides declarative
or attributes based delete) operations. because this is the building
programming. blocks of nearly all other
transactions.
ƒ Narrows the gap between EJB
ƒ No container or application persistence technologies in
ƒ EJBs are pooled and
server is required and can be Java.
2.x and O/R mapping. plugged into an existing
ƒ Can call Stored Procedures.cached. EJB life cycles are
ƒ Do support OO concepts like
container.
managed by the container.
ƒ Tools are available to simplify ƒ Can manipulate relatively
ƒ Has remote access
inheritance.
mapping relational data to large data sets.
capabilities and can be objects and quick to develop.
clustered for scalability.
Cons: Cons: Cons: Cons:
ƒ Need to understand the ƒ Since it is new, might be too ƒ Little or no capabilities for ƒ You will have to write a lot
intricacies like rolling back early to use in commercial remote access and of code to perform a little.
a transaction, granularity projects. distributability. Easy to make mistakes in
etc, infrastructures like
ƒ It is still evolving. ƒ Mapping schemas can be
properly managing
session facades, business connections and can cause
delegates, value objects etc tedious and O/R mapping out of cursors issues.
and strategies like lazy has its tricks like using lazy
ƒ Harder to maintain becauseloading, dirty marker etc. initialization, eager loading
etc. What works for one may changes in schemas can
ƒ EJBs use lots of resources not work for another. cause lot of changes to your
and have lots of artifacts.
ƒ Limited clustering
code.
ƒ Does not support OO ƒ Records need to be lockedcapabilities.
concepts like inheritance. manually (e.g. select for
ƒ Large data sets can still update).
cause memory issues.
ƒ Support for security at a
database level only and no
support for role based
security without any add on
APIs like Aspect Oriented
Programming etc.
As a rule of thumb, suitable As a rule of thumb, suitable for Suitable for records in use Where possible stay away
for distributed and clustered distributed and clustered between 100 and 5000. Watch from using JDBC unless you
applications, which is heavily applications, which is heavily out for memory issues, when have compelling reason to
transaction based. Records transaction based. Records in using large data sets. use it for batch jobs where
in use say between 1 and 50. use say between 1 and 100. large amount of data need to
be transferred, records in use
greater than 5000, required
to use Stored Procedures
etc.
Find more WWW.ThesisScientist.com
Enterprise Java 95
The stateless session beans and message driven beans have wider acceptance in EJB 2.x compared to stateful session
beans and entity beans. Refer Emerging Technologies/Frameworks section for Hibernate and EJB 3.0.
Q 60: What is the role of EJB 2.x in J2EE? SF
A 60: EJB 2.x (Enterprise JavaBeans) is a widely adopted server side component architecture for J2EE.
EJB is a remote, distributed multi-tier system and supports protocols like JRMP, IIOP, and HTTP etc.
It enables rapid development of reusable, versatile, portable business components across middleware,
transactional and scalable applications.
EJB is a specification for J2EE servers. EJB components contain only business logic and system level
programming and services like transactions, security, instance pooling, threading, persistence etc are
managed by the EJB Container and hence simplify the programming effort.
Message driven EJBs have support for asynchronous communication.
Note: Having said that EJB 2.x is a widely adopted server side component, EJB 3.0 is taking ease of development
very seriously and has adjusted its model to offer the POJO (Plain Old Java Object) persistence and the new O/R
mapping model based on Hibernate. In EJB 3.0, all kinds of enterprise beans are just POJOs. EJB 3.0
extensively uses Java annotations, which replaces excessive XML, based configuration files and eliminates the
need for the rigid component model used in EJB 1.x, 2.x. Annotations can be used to define the bean‟s business
interface, O/R mapping information, resource references etc. Refer Q18 in Emerging Technologies/Frameworks
section. So, for future developments look out for EJB 3.0 and/or Hibernate framework. Refer Q14 – Q16 in
Emerging Technologies/Frameworks section for discussion on Hibernate framework.
EJB - Big Picture
Other J2EE
C++ application
Messaging Java Applet, HTTP Client
Systems Client Java stand-alone application (eg: Browser, Wireless etc)
HTTP
Web Services
(SOAP, UDDI, WSDL, ebXML)
Firewall
J2EE Server JSP
Servlets messaging
(use JavaBeans)
(use JavaBeans) IIOP RMI/IIOP
ServletsBusiness Delegate
(use JavaBeans) (use JavaBeans)
BusinessLogicprovidedby
EJB Container (Enterprise Java Beans are deployed)
SystemLevelServiceslike
transaction,Securityetc
EJB Session Bean EJB Message Driven Bean EJB Session Bean
EJB Entity Bean EJB Session Bean
EJB Session Bean
thedeveloperth
roughEJB
areprovided
bythecontaine
r
SQL SQL (fast Lane Reader)
Web Services
Connectors (JCA) (SOAP, UDDI, WSDL, ebXML)
proprietary protocol
Legacy System, Message Oriented Other J2EE
SystemsDatabase ERP System etc Middleware Topic
Q 61: What is the difference between EJB and JavaBeans? SF
A 61: Both EJB and JavaBeans have very similar names but this is where the similarities end.
JavaBeans Enterprise JavaBeans (EJB)
The components built based on JavaBeans live in a single The Enterprise JavaBeans are non-visual distributable
local JVM (or address space) and can be either visual (e.g. components, which can live across multiple JVMs (or address
GUI components like Button, List etc) or non-visual at spaces).
runtime.
Find more WWW.ThesisScientist.com
96 Enterprise Java
No explicit support exists for services like transactions etc. EJBs can be transactional and the EJB servers provide
transactional support.
JavaBeans are fine-grained components, which can be EJBs are coarse-grained components that can be deployed as
used to assemble coarse-grained components or an is or assembled with other components into larger
application. applications. EJBs must be deployed in a container that
provides services like instance pooling, multi-threading,
security, life-cycle management, transactions etc
Must conform to JavaBeans specification. Must conform to EJB specification.
Q 62: Explain EJB architecture? SF
A 62:
E J B A r c h ite c tu r e
E J B S e r v e r
EJBClientServlet,JSP,Standalonea
pplication,Appletetc)
E J B C o n ta in e r
E n te rp ris e J a v a B e a n s
s y n c h ro n o u s H o m e /L o c a lH o m e H o m e O b je c t /
S e s s io n B e a n s
In te r fa c e L o c a l H o m e O b je c t
s ta te fu l / s ta te le s s
E n tity B e a n s D a ta b a s e S e r v e r
s y n c h ro n o u s
R e m o te /L o c a l E J B O b je c t / C M P / B M P
In te r fa c e E J B L o c a lO b je c t
(e
g
E n te rp ris e J a v a B e a n s
J M S M e s s a g e - D r iv e n E IS S y s te m
J M S M e s s a g e B e a n sM e s s a g e
A s y n c h ro n o u s
P r o d u c e r L is te n e r In te r fa c e
(e g p u b lis h /
s u b s c rib e
T o p ic )
E n te r p r is e S e r v ic e s a n d A P I
J N D I J M S T ra n s a c tio n s S e c u rity P e r s is t e n c e
E J B C o n ta in e r
C lie n t
p
Bu
k
Uo
o T
L S
. t
e1 eg k
. o
2 v
()
.
In
te
3 a
re ()c
)d
n (
fi e
bv
o u
m t
e
es
r
n th
b
9.
in v
o
o k ee a n
m
eth o d s
J N D I
H o m e In te r fa c e
R e m o te In te r fa c e
ly
p
p
a
&t
p
sr e
c
ee
t c
in i
. v
4 r
e
s
H o m e O b je c t lyp
p
a
e &
t
w c p
e n e
n a c
t r
s e
5 n t
.
i ni
.
6
E J B O B je c t
7. Ref
er
D e p lo y m e n t d e s c rip to r
B e a n d e fin itio n
T ra n s a c tio n
S e c u rity e tc
8 . b ea n life - m
e jb
c yc l e
e t h oC re a te ( ) o r d s
e jb F in d ()
ods
s m ethes
etcsin
r()an bu
Po
we
1
0. be e
ge tH ors
E J B C o n te x t
b e a n in s ta n c e
S a m p le C o d e :
C o n te x t in itia lC tx = n e w In itia lC o n te x t( ) ; //In itia liz e th e J N D I c o n te x t . ie e n tr y p o in t .
C a r H o m e h o m e O b je c t = ( C a r H o m e ) in itia lC tx .lo o k u p ( e jb /M y E jb ) ; // S te p s 1 & 2 in th e a b o v e d ia g r a m
C a r c a r O b je c t = h o m e O b je c t.c r e a te ( ) ; // S te p s 3 - 8
c a r O b je c t .g e tH o r s e P o w e r ( ) ; // S te p s 9 - 1 0
N o te : A n E J B c lie n t s h o u ld n e v e r a c c e s s a n E n te rp r is e J a v a B e a n d ire c tly . A n y a c c e s s is d o n e th r o u g h th e
c o n ta in e r g e n e ra te d c la s s e s w h ic h in tu r n in v o k e b e a n m e th o d s . T h e c o n ta in e r g e n e r a te d c la s s e s in te rc e p t th e
re q u e s t a n d a p p ly s e rv ic e s lik e tr a n s a c tio n , s e c u rity e tc p rio r to in v o k in g th e a c tu a l m e th o d o n th e E n e te rp ris e J a v a B e a n s .
EJB Container : EJBs are software components, which run in an environment called an EJB container. An EJB
cannot function outside an EJB Container. The EJB container hosts and manages an Enterprise JavaBean in a
similar manner that a Web container hosts a servlet or a Web browser hosts a Java Applet. The EJB container
manages the following services so that the developer can concentrate on writing the business logic:
Transactions (refer Q71 – Q75 in Enterprise section)
Persistence
EJB instance pooling
Security (refer Q81 in Enterprise section)
Concurrent access (or multi-threading)
Remote access
Design pattern: EJBs use the proxy design pattern to make remote invocation (i.e. remote proxy) and to add
container managed services like security and transaction demarcation. Refer Q11 in “How would you about…”
section for a more detailed discussion on proxy design pattern and dynamic proxies.
Find more WWW.ThesisScientist.com
Enterprise Java 97
EJBContext: Every bean obtains an EJBContext object, which is a reference directly to the container. The EJB
can request information about its environment like the status of a transaction, a remote reference to itself (an EJB
cannot use „this‟ to reference itself) etc.
Deployment Descriptor: The container handles all the above mentioned services declaratively for an EJB based
on the XML deployment descriptor (ejb-jar.xml). When an EJB is deployed into a container the deployment
descriptor is read to find out how these services are handled. Refer to the J2EE deployment structure diagram in
Q6 in Enterprise section.
EJB: The EJB architecture defines 3 distinct types of Enterprise JavaBeans.
Session beans.
Entity beans.
Message-driven beans.
The session and entity beans are invoked synchronously by the client and message driven beans are invoked
asynchronously by a message container such as a publish/subscribe topic. Let‟s look at some of the EJB
container services in a bit more detail:
Instance pooling
EJBinstance pooling
Clie nt Application
home
stub
EJB Se rve r
1 . create()
EJB
Home
be an ins tance pool
4 . return EJB Object reference EJB 3. assign an instance
to client Object to EJB Object
Note :
1 The client looks up the stub f rom the jndi and invokes the create() method on the EJBHome object.
CarHome hom e Obje ct = (CarHome) initialCtx .lookup(ejb/MyEjb);
Car carObject = homeObject.create()
2-3 The EJbHome creates an EJBObject by invoking new Instance() and assigns a bean instance f rom the pool to the
EJBObject. Now the assigned bean instance becomes in ready state f rom the pooled state.
4 Now the EJBObject can service client requests and ref erence is returned to the client.
carObject .getHorsePow er();
Finally once the client is f inshed w ith EJBObject ref erence the bean instance is returned back to the pool to serve other clients
The above diagram shows how the EJB instances are pooled and assigned to EJB Object and then returned to
the pool. Let‟s look at in detail for different types of EJBs.
s ta tele ss s es s io n & e n tity b ea n p o o lin g
E JB S erv er N o te s :
C lie nt stub 1
E JB
T h e d ia g ra m o n th e le ft sh o w s th a t s in c e th e
A s ta te le s s s e s s io n b e a n s a n d e n tity b e a n s
O bje ct d o n o t m a in ta in a n y c lie n t s ta te th e b e a n
in s ta n c e A w a s firs tly a llo c a te d to c lie n t s tu b
b ean in stan ce p o o l 1 a n d la te r o n a llo ca te d to c lie n t s tu b 2 . S o if
th e re a re 1 0 0 0 c o n c u rre n t clie n ts th e n 3 0
E JB C D in s ta n c e s o f b e a n c a n s e rve th e m b y ta k in g
C lie nt stub 2 O bje ct
B
tu rn s .
T h is b e h a vio u r is n o t p o s s ib le w ith re g a rd s to
s ta te fu l s e s s io n b e a n s w h ic h m a in ta in th e
E JB S e rv er
clie n t s ta te . S o th e re w ill b e a d e d ic a te d
in s ta n c e o f th e b e a n fo r e a ch c lie n t s tu b . S o
C lie nt stub 1
E J B
B
if th e re a re 1 0 0 0 c lie n ts th e n th e re w ill b e
1 0 0 0 in s ta n c e s o f b e a n s . S o h o w d o w e
O b je c t
co n s e rve m e m o ry . T h is is d o n e b y a c tiva tio n
a n d p a s siva tio n . P a s s iva tio n is th e p ro c e s s
b ean in s tan ce p o o l w h e re th e b e a n in s ta n c e is s e ria lize d in to a
C D
p e rs is te n t s to re w h e n n o t u s e d to c o n s e rve
C lient stub 2
E J B m e m o ry a n d A c tiva tio n is p ro c e s s w h e re th e
O b je c t
A
se rilize d b e a n in s ta n ce is d e -s e ria lize d b a c k
in to m e m o ry to s e rve c lie n t re q u e s t. T h is
p ro c e s s a ffe c ts p e rfo rm a n c e .
Find more WWW.ThesisScientist.com
98 Enterprise Java
From the diagrams it is clear that bean instances can be reused for all the bean types except for the stateful
session bean where the client state is maintained. So we need a dedicated stateful session bean for each client.
M e s s a g e D riv e n B e a n (M D B ) p o o lin g
E J B S e rv e r
J M S C lie n t 1
m s g X fo r Q 1 E J B
M D B -1 b e a n in s ta n c e p o o l
A
fo r Q 1
O b je c t
B C
J M S C lie n t 2 m s
fo r Q 2 E J Bg Z
BO b je c t M D B -2 b e a n in s ta n c e p o o l
fo r Q 2
CJ M S C lie n t 3 m sg y fo r Q 2 E J B
AO b je c t
N o te : M D B a re lik e s ta te le s s s e s s io n b e a n s ,
T h e in s ta n c e p o o ls a re c re a te d fo r e a c h M D B a n d w ith in e a c h p o o l m u ltip le in s ta n c e s a re c re a te d . In te rm s o f
n u m b e r o f in s ta n c e s c re a te d in e a c h p o o l a re v e ry s im ila r to s ta te le s s s e s s io n b e a n s o r e n tity b e a n s (ie 3 in s ta n c e s
o f M D B -1 fo r Q 1 in s ta n c e p o o l c a n s e rv e 1 0 J M S c lie n ts fo r Q 1 ).
Concurrent access
The session beans do not support concurrent access. The stateful session beans are exclusively for a client so
there is no concurrent access. The stateless session beans do not maintain any state. It does not make any sense
to have concurrent access. The Entity beans represent data that is in the database table, which is shared between
the clients. So to make concurrent access possible the EJB container need to protect the data while allowing many
clients simultaneous access. When you try to share distributed objects you may have the following problem:
If 2 clients are using the same EJBObject, how do you keep one client from writing over the changes of the other?
Say for example
Client-1 reads a value x= 5
Client-2 modifies the value to x=7
Now the client-1‟s value is invalid.
The entity bean addresses this by prohibiting concurrent access to bean instances. Which means several clients
can be connected to one EJBObject but only one client can access the EJB instance at a time.
Persistence
Entity beans basically represent the data in a relational database. An Entity Bean is responsible for keeping its
state in sync with the database.
E n tity b ean s rep resen tin g d ata in th e d atab ase
instance for id = 1001
A c c o u n tB e a n
id = 1001 (p rim a ry-k e y)
bsb = 1234
account_ num ber = 98765432
instance for id = 1002
A c c o u n tB e a n
id = 1002 (p rim a ry-k e y)
bsb = 1234
account_ num ber = 12345678
Acco u n t T ab le
id b s b a c c o u n t_ n u m
1001 1234 98765432
1002 1234 12345678
d atab ase
Container-managed persistence (CMP) - The container is responsible for saving the bean‟s state with the help
of object-relational mapping tools.
Bean-managed persistence (BMP) – The Entity Bean is responsible for saving its own state.
Find more WWW.ThesisScientist.com
Enterprise Java 99
If entity beans performance is of concern then there are other persistence technologies and frameworks like
JDBC, JDO, Hibernate, OJB and Oracle TopLink (commercial product).
Q 63: What are the different kinds of enterprise beans? SF
A 63:
Session Bean: is a non-persistent object that implements some business logic running on the server. Session
beans do not survive system shut down. There are two types of session beans
Stateless session beans (each session bean can be reused by multiple EJB clients)
Stateful session beans (each session bean is associated with one EJB client)
Entity Bean: is a persistent object that represents object views of the data, usually a row in a database. They
have the primary key as a unique identifier. Multiple EJB clients can share each entity bean. Entity beans can
survive system shut shutdowns. Entity beans can have two types of persistence
Container-managed persistence (CMP) - The container is responsible for saving the bean‟s state.
Bean-managed persistence (BMP) – The Entity Bean is responsible for saving its own state.
Message-driven Bean: is integrated with the Java Message Service (JMS) to provide the ability to act as a
message consumer and perform asynchronous processing between the server and the message producer.
Q 64: What is the difference between session and entity beans? SF
A 64:
Session Beans Entity Beans
Use session beans for application logic. Use entity beans to develop persistent object model.
Expect little reuse of session beans. Insist on reuse of entity beans.
Session beans control the workflow and transactions of a Domain objects with a unique identity (ie-primary key) shared
group of entity beans. by multiple clients.
Life is limited to the life of a particular client. Handle Persist across multiple invocations. Handles database access
database access for a particular client. for multiple clients.
Do not survive system shut downs or server crashes. Do survive system shut downs or server crashes.
Q 65: What is the difference between stateful and stateless session beans? SF
A 65:
Stateless Session Beans Stateful Session Bean
Do not have an internal state. Can be reused by different Do have an internal state. Reused by the same client.
clients.
Need not be activated or passivated since the beans are Need to handle activation and passivation to conserve system
pooled and reused. memory since one session bean object per client.
Q 66: What is the difference between Container Managed Persistence (CMP) and Bean Managed Persistence (BMP)?
SF
A 66:
Container Managed Persistence (CMP) Bean Managed Persistence (BMP)
The container is responsible for persisting state of the bean. The bean is itself responsible for persisting its own state.
Container needs to generate database (SQL) calls. The bean needs to code its own database (SQL) calls.
The bean persistence is independent of its database (e.g. The bean persistence is hard coded and hence may not be
DB2, Oracle, Sybase etc). So it is portable from one data portable between different databases (e.g. DB2, Oracle etc).
source to another.
Q 67: Can an EJB client invoke a method on a bean directly? SF
A 67: An EJB client should never access an EJB directly. Any access is done through the container. The container will
intercept the client call and apply services like transaction, security etc prior to invoking the actual EJB. This
relationship between the EJB and the container is like “don‟t call us, we will call you”.
Q 68: How does an EJB interact with its container and what are the call-back methods in entity beans? SF
A 68: EJB interacts with its container through the following mechanisms
Find more WWW.ThesisScientist.com
100 Enterprise Java
Call-back Methods: Every EJB implements an interface (extends EnterpriseBean) which defines several
methods which alert the bean to various events in its lifecycle. A container is responsible for invoking these
methods. These methods notify the bean when it is about to be activated, to be persisted to the database, to
end a transaction, to remove the bean from the memory, etc. For example the entity bean has the following
call-back methods:
public interface javax.ejb.EntityBean {
public void setEntityContext(javax.ejb.EntityContext c);
public void unsetEntityContext();
public void ejbLoad(); public
void ejbStore(); public void
ejbActivate(); public void
ejbPassivate(); public void
ejbRemove();
}
EJBContext: provides methods for interacting with the container so that the bean can request information
about its environment like the identity of the caller, security, status of a transaction, obtains remote reference
to itself etc. e.g. isUserInRole(), getUserPrincipal(), isRollbackOnly(), etc
JNDI (Java Naming and Directory Interface): allows EJB to access resources like JDBC connections, JMS
topics and queues, other EJBs etc.
Q 69: What is the difference between EJB 1.1 and EJB 2.0? What is the difference between EJB 2.x and EJB 3.0? SF
A 69: EJB 2.0 has the following additional advantages over the EJB 1.1
Local interfaces: These are beans that can be used locally, that means by the same Java Virtual Machines,
so they do not required to be wrapped like remote beans, and arguments between those interfaces are
passed directly by reference instead of by value. This improves performance.
ejbHome methods: Entity beans can declare ejbHome methods that perform operations related to the EJB
component but that are not specific to a bean instance.
Message Driven Beans (MDB): is a completely new enterprise bean type, which is designed specifically to
handle incoming JMS messages.
New CMP Model. It is based on a new contract called the abstract persistence schema, which will allow to
the container to handle the persistence automatically at runtime.
EJB Query Language: It is a sql-based language that will allow the new persistence schema to implement
and execute finder methods.
Let‟s look at some of the new features on EJB 2.1
Container-managed timer service: The timer service provides coarse-grained, transactional, time-based
event notifications to enable enterprise beans to model and manage higher-level business processes.
Web service support: EJB 2.1 adds the ability of stateless session beans to implement a Web service
endpoint via a Web service endpoint interface.
EJB-QL: Enhanced EJB-QL includes support for aggregate functions and ordering of results.
Current EJB 2.x model is complex for a variety of reasons:
You need to create several component interfaces and implement several unnecessary call-back methods.
EJB deployment descriptors are complex and error prone.
EJB components are not truly object oriented, as they have restrictions for using inheritance and
polymorphism.
EJB modules cannot be tested outside an EJB container and debugging an EJB inside a container is very
difficult.
Find more WWW.ThesisScientist.com
Enterprise Java 101
Note: EJB 3.0 is taking ease of development very seriously and has adjusted its model to offer the POJO (Plain Old Java
Object) persistence and the new O/R mapping model based on Hibernate. In EJB 3.0, all kinds of enterprise beans are just
POJOs. EJB 3.0 extensively uses Java annotations, which replaces excessive XML based configuration files and eliminate
the need for rigid component model used in EJB 1.x, 2.x. Annotations can be used to define the bean‟s business interface, O/R
mapping information, resource references etc. Refer Q18 in Emerging Technologies/Frameworks section.
Q 70: What are the implicit services provide by an EJB container? SF
A 70:
Lifecycle Management: Individual enterprise beans do not need to explicitly manage process allocation,
thread management, object activation, or object destruction. The EJB container automatically manages the
object lifecycle on behalf of the enterprise bean.
State Management: Individual enterprise beans do not need to explicitly save or restore conversational
object state between method calls. The EJB container automatically manages object state on behalf of the
enterprise bean.
Security: Individual enterprise beans do not need to explicitly authenticate users or check authorisation
levels. The EJB container automatically performs all security checking on behalf of the enterprise bean.
Transactions: Individual enterprise beans do not need to explicitly specify transaction demarcation code to
participate in distributed transactions. The EJB container can automatically manage the start, enrolment,
commitment, and rollback of transactions on behalf of the enterprise bean.
Persistence: Individual enterprise beans do not need to explicitly retrieve or store persistent object data from
a database. The EJB container can automatically manage persistent data on behalf of the enterprise bean.
Q 71: What are transactional attributes? SFTI
A 71: EJB transactions are a set of mechanisms and concepts, which insures the integrity and consistency of the
database when multiple clients try to read/update the database simultaneously.
Transaction attributes are defined at different levels like EJB (or class), a method within a class or segment of a
code within a method. The attributes specified for a particular method take precedence over the attributes
specified for a particular EJB (or class). Transaction attributes are specified declaratively through EJB deployment
descriptors. Unless there is any compelling reason, the declarative approach is recommended over programmatic
approach where all the transactions are handled programmatically. With the declarative approach, the EJB
container will handle the transactions.
Transaction Description
Attributes
Required Methods executed within a transaction. If client provides a transaction, it is used. If not, a new transaction is
generated. Commit at end of method that started the transaction. Which means a method that has Required
attribute set, but was called when the transaction has already started will not commit at the method
completion. Well suited for EJB session beans.
Mandatory Client of this EJB must create a transaction in which this method operates, otherwise an error will be
reported. Well-suited for entity beans.
RequiresNew Methods executed within a transaction. If client provides a transaction, it is suspended. If not a new
transaction is generated, regardless. Commit at end of method.
Supports Transactions are optional.
NotSupported Transactions are not supported. If provided, ignored.
Never Code in the EJB responsible for explicit transaction control.
Q 72: What are isolation levels? SFTIPI
A 72: Isolation levels provide a degree of control of the effects one transaction can have on another concurrent
transaction. Since concurrent effects are determined by the precise ways in which, a particular relational database
handles locks and its drivers may handle these locks differently. The semantics of isolation mechanisms based on
these are not well defined. Nevertheless, certain defined or approximate properties can be specified as follows:
Isolation level Description
TRANSACTION_SERIALIZABLE Strongest level of isolation. Places a range lock on the data set, preventing other
users from updating or inserting rows into the data set until the transaction is
complete. Can produce deadlocks.
Find more WWW.ThesisScientist.com
102 Enterprise Java
TRANSACTION_REPEATABLE_READ Locks are placed on all data that is used in a query, preventing other users from
updating the data, but new phantom records can be inserted into the data set
by another user and are included in later reads in the current transaction.
TRANSACTION_READ_COMMITTED Can't read uncommitted data by another transaction. Shared locks are held while
the data is being read to avoid dirty reads, but the data can be changed before
the end of the transaction resulting in non-repeatable reads and phantom
records.
TRANSACTION_READ_UNCOMMITTED Can read uncommitted data (dirty read) by another transaction, and non-
repeatable reads and phantom records are possible. Least restrictive of all
isolation levels. No shared locks are issued and no exclusive locks are
honoured.
Isolation levels are not part of the EJB specification. They can only be set on the resource manager either
explicitly on the Connection (for bean managed persistence) or via the application server specific configuration.
The EJB specification indicates that isolation level is part of the Resource Manager.
As the transaction isolation level increases, likely performance degradation follows, as additional locks are
required to protect data integrity. If the underlying data does not require such a high degree of integrity, the
isolation level can be lowered to improve performance.
Q 73: What is a distributed transaction? What is a 2-phase commit? SFTI
A 73: A Transaction (Refer Q43 in Enterprise section) is a series of actions performed as a single unit of work in which
either all of the actions performed as a logical unit of work in which, either all of the actions are performed or none
of the actions. A transaction is often described by ACID properties (Atomic, Consistent, Isolated and Durable). A
distributed transaction is an ACID transaction between two or more independent transactional resources like
two separate databases. For the transaction to commit successfully, all of the individual resources must commit
successfully. If any of them are unsuccessful, the transaction must rollback in all of the resources. A 2-phase
commit is an approach for committing a distributed transaction in 2 phases.
Phase 1 is prepare: Each of the resources votes on whether it‟s ready to commit – usually by going ahead and
persisting the new data but not yet deleting the old data.
Phase 2 is committing: If all the resources are ready, they all commit – after which old data is deleted and
transaction can no longer roll back. 2-phase commit ensures that a distributed transaction can always be
committed or always rolled back if one of the databases crashes. The XA specification defines how an application
program uses a transaction manager to coordinate distributed transactions across multiple resource managers.
Any resource manager that adheres to XA specification can participate in a transaction coordinated by an XA-
compliant transaction manager.
Q 74: What is dooming a transaction? TI
A 74: A transaction can be doomed by the following method call CO
EJBContext.setRollbackOnly();
The above call will force transaction to rollback. The doomed transactions decrease scalability and if a transaction
is doomed why perform compute intensive operations? So we can detect a doomed transaction as shown below:
CO
public void doComputeIntensiveOperation() throws Exception {
If ( ejbContext.getRollbackOnly() ) {
return; //transaction is doomed so return (why unnecessarily perform compute intensive operation )
}
else {
performComplexOperation();
}
}
Q 75: How to design transactional conversations with session beans? SFTI
A 75: A stateful session bean is a resource which has an in memory state which can be rolled back in case of any
failure. It can participate in transactions by implementing SessionSynchronization. CO
Find more
WWW.ThesisScientist.com
Enterprise Java 103
SessionSynchronization
public class MyBean implements SessionBean,
SessionSynchronization{ public int oldVal ; public int val ;
public void ejbCreate(int val) throws
CreateException { this.val=val;
this.oldVal=val;
}
public void afterBegin() { this.oldVal =
this.val ;} public void beforeCompletion(){};
public void afterCompletion(boolean b) { if (b == false) this.val = this.oldVal ; }
.......................................
}
public interface javax.ejb.SessionSynchronization {
public void afterBegin();
public void beforeCompletion();
public void afterCompletion(boolean b);
}
The uses of SessionSynchronization are:
Enables the bean to act as a transactional resource and undo state changes on failure.
Enables you to cache database data to improve performance.
Q 76: Explain exception handling in EJB? SFEHCO
A 76: Java has two types of exceptions:
Checked exception: derived from java.lang.Exception but not java.lang.RuntimeException.
Unchecked exception: derived from java.lang.RuntimeException thrown by JVM.
System vs Application Exception
public void depositAmount() throws InsufficientFundException
{ if(this.amount <= 0) {
throw new InsufficientFundException ("Balance is <= 0");
}
try {
depositAmount();
} catch (SQLException e) { throw
new EJBException(e);
} catch (Exception e) {
throw new EJBException(e);
}
}
Application Exception
System Exception
EJB has two types of exceptions:
System Exception: is an unchecked exception derived from java.lang.RuntimeException.
Application Exception: is specific to an application and thrown because of violation of business rules.
A System Exception is thrown by the system and is not recoverable. For example EJB container losing
connection to the database server, failed remote method objects call etc. Because the System Exceptions are
unpredictable, the EJB container is the only one responsible for trapping the System Exceptions. The container
automatically wraps any RuntimeException in RemoteException, which subsequently gets thrown to the caller (or
client). In addition to intercepting System Exception the container may log the errors.
An Application Exception is specific to an application and is thrown because of violation of business rules. The
client should be able to determine how to handle an Application Exception. If the account balance is zero then an
Application Exception like InsufficientFundException can be thrown. If an Application Exception should be
treated as a System Exception (e.g. SQLException) it needs to be wrapped in an EJBException so that it can be
managed properly and propagated to the client.
Q 77: How do you rollback a container managed transaction in EJB? SFTIEH
Find more WWW.ThesisScientist.com
104 Enterprise Java
A 77: The way the exceptions are handled affects the way the transactions are managed. CO
Rolling back Container Managed Transactions
public void depositAmount() throws
InsufficientFundExceptiion { try {
depositAmount();
}catch (InsufficientFundException
e) ctx.setRollbackOnly();
throw new InsufficientFundExceptiion(e.getMessage()); }
catch (SQLException e) {
throw new EJBException(e);
} catch (Exception e) {
throw new EJBException(e);
}
}
Application Exception is thrown so the
transaction should be rolled back in
the code ctx.setRollbackOnly().
EJBException is a System
Exception so the container
will automatically roll back
the transaction.
When the container manages the transaction, it is automatically rolled back when a System Exception occurs.
This is possible because the container can intercept System Exception. However when an Application Exception
occurs, the container does not intercept it and therefore leaves it to the code to roll back using
ctx.setRollbackOnly().
Be aware that handling exceptions in EJB is different from handling exceptions in Java. The Exception handling
best practice tips are:
If you cannot recover from System Exception let the container handle it.
If a business rule is violated then throw an application exception.
Catch the Exceptions in a proper order.
It is a poor practice to catch java.lang.Exception because this is a big basket, which will catch all the
unhandled exceptions. It is shown in the above diagrams for illustration purpose only. You should avoid this
because if you add a new piece of code, which throws a new, checked exception, then the compiler won‟t pick
it up.
Q 78: What is the difference between optimistic and pessimistic concurrency control? TI
A 78:
Pessimistic Concurrency Optimistic Concurrency
A pessimistic design assumes conflicts will occur in the An optimistic approach assumes conflicts won‟t occur, and deal with
database tables and avoids them through exclusive them when they do occur.
locks etc.
EJB (also non-EJB) locks the source data until it EJB (also non-EJB) implements a strategy to detect whether a
completes its transaction. change has occurred. Locks are placed on the database only for a
ƒ Provides reliable access to data.
small portion of the time.
ƒ Suitable for short transactions. ƒ Suitable for long transactions.
ƒ Suitable for systems where concurrent access is ƒ Suitable for systems requiring frequent concurrent accesses.
rare.
The pessimistic locking imposes high locking The optimistic locking is used in the context of cursors. The
overheads on the server and lower concurrency. optimistic locking works as follows:
ƒ No locks are acquired as rows are read.
ƒ No locks are acquired while values in the current row are
changed.
ƒ When changes are saved, a copy of the row in the database is
read in the locked mode.
ƒ If the data was changed after it was read into the cursor, an error
is raised so that the transaction can be rolled back and retried.
Note: The testing for changes can be done by comparing the
values, timestamp or version numbers.
Q 79: How can we determine if the data is stale (for example when using optimistic locking)? TI
A 79: We can use the following strategy to determine if the data is stale:
Adding version numbers
Find more WWW.ThesisScientist.com
Enterprise Java 105
Add a version number (Integer) to the underlying table.
Carry the version number along with any data read into memory (through value object, entity bean etc).
Before performing any update compare the current version number with the database version number.
If the version numbers are equal update the data and increment the version number.
If the value object or entity bean is carrying an older version number, reject the update and throw
an exception.
Note: You can also do the version number check as part of the update by including the version column in the
where clause of the update without doing a prior select.
Adding a timestamp to the underlying database table.
Comparing the data values.
These techniques are also quite useful when implementing data caching to improve performance. Data caches
should regularly keep track of stale data to refresh the cache. These strategies are valid whether you use EJB or
other persistence mechanisms like JDBC, Hibernate etc.
Q 80: What are not allowed within the EJB container? SF
A 80: In order to develop reliable and portable EJB components, the following restrictions apply to EJB code
implementation:
Avoid using static non-final fields. Declaring all static fields in EJB component as final is recommended. This
enables the EJB container to distribute instances across multiple JVMs.
Avoid starting a new thread (conflicts with EJB container) or using thread synchronization (allow the EJB
container to distribute instances across multiple JVMs).
Avoid using AWT or Swing functionality. EJBs are server side business components.
Avoid using file access/java.io operations. EJB business components are meant to use resource managers
such as JDBC to store and retrieve application data. Also deployment descriptors can be used to store <env-
entry>.
Avoid accepting or listening to socket connections. EJB components are not meant to provide network socket
functionality. However the specification lets EJB components act as socket clients or RMI clients.
Avoid using the reflection API. This restriction enforces Java security.
Can‟t use custom class loaders.
Q 81: Discuss EJB container security? SFSE
A 81: EJB components operate inside a container environment and rely heavily on the container to provide security. The
four key services required for the security are:
Identification: In Java security APIs this identifier is known as a principal.
Authentication: To prove the identity one must present the credentials in the form of password, swipe card,
digital certificate, finger prints etc.
Authorisation (Access Control): Every secure system should limit access to particular users. The common
way to enforce access control is by maintaining security roles and privileges.
Data Confidentiality: This is maintained by encryption of some sort. It is no good to protect your data by
authentication if someone can read the password.
The EJB specification concerns itself exclusively with authorisation (access control). An application using EJB
can specify in an abstract (declarative) and portable way that is allowed to access business methods. The EJB
container handles the following actions:
Find out the Identity of the caller of a business method.
Find more WWW.ThesisScientist.com
106 Enterprise Java
Check the EJB deployment descriptor to see if the identity is a member of a security role that has been
granted the right to call this business method.
Throw java.rmi.RemoteException if the access is illegal.
Make the identity and the security role information available for a fine grained programmatic security check.
public void closeAccount() {
if (ejbContext.getCallerPrincipal().getName() = “SMITH”)
{ //…
}
if (!ejbContext .isCallerInRole(CORPORATE_ ACCOUNT_MANAGER))
{ throw new SecurityException(“Not authorized to close this account”);
}
}
Optionally log any illegal access.
There are two types of information the EJB developer has to provide through the deployment descriptor.
Security roles
Method permissions
Example:
<security-role>
<description>
Allowed to open and close accounts
</description> <role-
name>account_manager</role-name>
</security-role>
<security-role>
<description>
Allowed to read only
</description> <role-
name>teller</role-name>
</security-role>
There is a many-to-many relationship between the security roles and the method permissions.
<method-permission> <role-
name>teller</role-name>
<method>
<ejb-name>AccountProcessor</ejb-name>
<method-name>findByPrimaryKey</method-name>
</method>
</method-permission>
Just as we must declare the resources accessed in our code for other EJBs that we reference in our code we
should also declare the security role we access programmatically to have a fine grained control as shown below.
<security-role-ref>
<description>
Allowed to open and close accounts
</description> <role-
name>account_manager</role-name>
<role-link>executive</role-link>
</security-role-ref>
There is also many-to-many relationship between the EJB specific security roles that are in the deployment
descriptor and the application based target security system like LDAP etc. For example there might be more than
one group users and individual users that need to be mapped to a particular EJB security role „account_manager‟.
Q 82: What are EJB best practices? BP
A 82:
Use local interfaces that are available in EJB2.0 if you deploy both the EJB client and the EJB in the same
server. Use vendor specific pass-by-reference implementation to make EJB1.1 remote EJBs operate as local.
Find more WWW.ThesisScientist.com
Enterprise Java 107
[Extreme care should be taken not to affect the functionality by switching the application, which was written
and tested in pass-by-reference mode to pass-by-value without analysing the implications and re-testing the
functionality.
Wrap entity beans with session beans to reduce network calls (refer Q84 in Enterprise section) and promote
declarative transactions. Where possible use local entity beans and session beans can be either local or
remote. Apply the appropriate EJB design patterns as described in Q83 – Q87 in Enterprise section.
Cache ejbHome references to avoid JNDI look-up overhead using service locator pattern.
Handle exceptions appropriately (refer Q76, Q77 in Enterprise section).
Avoid transaction overhead for non-transactional methods of session beans by declaring transactional
attribute as „Supports‟.
Choose plain Java object over EJB if you do not want services like RMI/IIOP, transactions, security,
persistence, thread safety etc. There are alternative frameworks such as Hibernate, Spring etc.
Choose Servlet‟s HttpSession object rather than stateful session bean to maintain client state if you do not
require component architecture of a stateful bean.
Apply Lazy loading and Dirty marker strategies as described in Q88 in Enterprise section.
Session Bean Session Bean (stateful) Entity Bean
(stateless)
ƒ Tune the pool size to ƒ Tune the pool size to avoid ƒ Tune the pool size to avoid overhead of creation and
avoid overhead of overhead of creation and destruction.
creation and destruction. destruction.
ƒ Use setEntityContext(..) method to cache any bean
Use setSessionContext(..) ƒ Set proper time out to avoidƒ specific resources and unsetEntityContext() method to
or ejbCreate(..) method to resource congestion. release acquired resources.
cache any bean specific
ƒ Remove it explicitly from Use lazy-loading to avoid any unnecessary loading ofresources. ƒ
client using remove() dependent data. Use dirty marker to avoid unchanged
ƒ Release any acquired method. data update.
resources like Database
ƒ Use „transient‟ variable Commit the data after a transaction completes to reduceconnection etc in ƒ
ejbRemove() method where possible to avoid any database calls in between.
serialization overhead.
ƒ Where possible perform bulk updates, use CMP rather
than BMP, Use direct JDBC (Fast-lane-reader) instead
of entity beans, use of read-only entity beans etc.
Q 83: What is a business delegate? Why should you use a business delegate? DPPI
A 83: Questions Q83 – Q88 are very popular EJB questions.
Problem: When presentation tier components interact directly with the business services components like EJB,
the presentation components are vulnerable to changes in the implementation of business services components.
Solution: Use a Business Delegate to reduce the coupling between the presentation tier components and the
business services tier components. Business Delegate hides the underlying implementation details of the business
service, such as look-up and access details of the EJB architecture.
Business delegate is responsible for:
Invoking session beans in Session Facade.
Acting as a service locator and cache home stubs to improve performance.
Handling exceptions from the server side. (Unchecked exceptions get wrapped into the remote exception,
checked exceptions can be thrown as an application exception or wrapped in the remote exception.
unchecked exceptions do not have to be caught but can be caught and should not be used in the method
signature.)
Re-trying services for the client (For example when using optimistic locking business delegate will retry the
method call when there is a concurrent access.).
Find more
WWW.ThesisScientist.com
108 Enterprise Java
B u s i n e s s D e l e g a t e
C l i e n t 1 . u s e s B u s i n e s s D e l e g a t e 4 . u s e s
2 . u s e s
B u s i n e s s S e r v i c e E J B
E J B L o o k u p S e r v i c e
3 . lo o k u p / c r e a t e
Q 84: What is a session façade? DPPI
A 84: Problem: Too many method invocations between the client and the server will lead to network overhead, tight
coupling due to dependencies between the client and the server, misuse of server business methods due to fine
grained access etc.
Solution: Use a session bean as a façade to encapsulate the complexities between the client and the server
interactions. The Session Facade manages the business objects, and provides a uniform coarse-grained
service access layer to clients.
Session Facade
Without Session Facade With Session Facade
l 1
Entitity Bean 1
te cal
Session Bean
Servlet
remo
Servlet
remote call 2 Entitity Bean 2 remote call 1
(Stateless)
(client) (client) Session
network network Facadee
r mo
t
e c
a
ll
3
Entitity Bean 3
ll1 Entitity Bean 1
ac
l
a
c
lo
local call 2 Entitity Bean 2
lo
c
al
c
a
ll
3 Entitity Bean 3
Session façade is responsible for
Improving performance by minimising fine-grained method calls over the network.
Improving manageability by reducing coupling, exposing uniform interface and exposing fewer methods to
clients.
Managing transaction and security in a centralised manner.
Q 85: What is a value object pattern? DPPI
A 85: Problem: When a client makes a remote call to the server, there will be a process of network call and serialization
of data involved for the remote invocation. If you make fine grained calls there will be performance degradation.
Solution: Avoid fine-grained method calls by creating a value object, which will help the client, make a coarse-
grained call.
V a lu e O b je c t p a tte rn
W ith o u t V a lu e O b je c t W ith V a lu e O b je c t
S e s s io n B e a n
tNam e()
S e rv le t etFirsg
(c lie n t) g e tS u r n a m e ( )
g e tG
e n dg
et e r ()
A
ge
()
W ith o u t v a lu e o b je c t 4 re m o te c a lls a re
m a d e to g e t a ll th e re le v a n t in fo
S
e
r
v
l
e
t
(
c
l
i
e
n
P e r s o n
V a lu e
O b je c t
()e
m
)a
rn (
eu
tS m
e a
g tN )s (
e ir der
g tF n
e
)
tG
g
e
(
ge
tA
g
e
S e s s io n
B e a n
g e tP e rs o n In fo ()
t )
Find
more WWW.ThesisScientist.com
W ith v a lu e o b je c t 1 re m o te c a ll a n d 4 lo c a l
c a lls a re m a d e to g e t a ll th e re le v a n t in fo .
Find more WWW.ThesisScientist.com
Enterprise Java 109
Q 86: What is a fast-lane reader? DPPI
A 86: Problem: Using Entity beans to represent persistent, read only tabular data incurs performance cost at no benefit
(especially when large amount of data to be read).
Solution: Access the persistent data directly from the database using the DAO (Data Access Object) pattern
instead of using Entity beans. The Fast lane readers commonly use JDBC, Connectors etc to access the read-only
data from the data source. The main benefit of this pattern is the faster data retrieval.
Fast Lane Reader
J2EE Server
Web Container
EJB Container
eal lan
Session Bean Entity Bean norm
en
la
l
a
Servlet rm
no
(client) Fa stLan en
DataSource
a
e R
e ad
t L
er
s
a
Data Access Object F
Use Fast Lane Reader for read only access and the normal lane for read/write access to the DataSource.
Q 87: What is a Service Locator? DPPI
A 87: Problem: J2EE makes use of the JNDI interface to access different resources like JDBC, JMS, EJB etc. The client
looks up for these resources through the JNDI look-up. The JNDI look-up is expensive because the client needs to
get a network connection to the server first. So this look-up process is expensive and redundant.
Solution: To avoid this expensive and redundant process, service objects can be cached when a client performs
the JNDI look- up for the first time and reuse that service object from the cache for the subsequent look-ups. The
service locator pattern implements this technique. Refer to diagram below:
W ith o u t S e rv ic e L o c a to r
S e r v le t
(c lie n t - 1 ) lo
o k up
S e rv le t lookup
(c lie n t - 2 ) pu
lo k J N D I
o
S e rv le t
(c lie n t - 3 )
W ith o u t s e rv ic e lo c a to r lo o k u p e v e ry tim e
fro m th e J N D I
S e rv ic e L o c a to r
W ith S e rv ic e L o c a to r
S e rv le t (c
lie n t -1 )
lo
o
k p S e r vic e
u
S e rv le t look up L o c a to r lo o k u p firs t tim e o n ly
(c lie n t - 2 )
p
u
k
o
lo
S e rv le t
(c lie n t - 3 )
W ith s e rv ic e lo c a to r lo o k u p firs t tim e fro m
th e J N D I a n d s e c o n d tim e o n w a rd s lo o k u p
fro m th e c a c h e in th e s e rv ic e lo c a to r.
J N D I
Q 88: Explain lazy loading and dirty marker strategies? DPPI
A 88: Lazy Loading: Lazy loading means not creating an object until the first time it is accessed. This technique is
useful when you have large hierarchies of objects. You can lazy load some of the dependent objects. You only
create the dependent (subordinate) objects only when you need them.
If ( this.data = null)
{ //lazy load data
}
For a CMP bean the default scenario is set to no lazy loading and the finder method will execute a single SQL
select statement against the database. So, for example, with the findAllCustomers() method will retrieve all
customer objects with all the CMP fields in each customer object.
Find more WWW.ThesisScientist.com
110 Enterprise Java
If you turn on lazy loading then only the primary keys of the objects within the finder are returned. Only when you
access the object, the container uploads the actual object based on the primary key. You may want to turn on the
lazy loading feature if the number of objects that you are retrieving is so large that loading them all into local cache
would adversely affect the performance. (Note: The implementation of lazy loading strategy may vary from
container vendor to vendor).
Dirty Marker (Store optimisation): This strategy allows us to persist only the entity beans that have been
modified. The dependent objects need not be persisted if they have not been modified. This is achieved by using a
dirty flag to mark an object whose contents have been modified. The container will check every dependent object
and will persist only those objects that are dirty. Once it is persisted its dirty flag will be cleared. (Note: The
implementation of dirty marker strategy may vary from container vendor to vendor).
Note: If your job requires a very good understanding of EJB 2.x then following books are recommended:
Mastering Enterprise JavaBeans – by Ed Roman
EJB Design Patterns – by Floyd Marinescu
Enterprise - JMS
Q 89: What is Message Oriented Middleware? What is JMS? SF
A 89: Message Oriented Middleware (MOM) is generally defined as a software infrastructure that asynchronously
communicates with other disparate systems through the production and consumption of messages. A message
may be a request, a report, or an event sent from one part of an enterprise application to another.
Messaging enables loosely coupled distributed communication. A component sends a message to a destination,
and the recipient can retrieve the message from the destination. However, the sender and the receiver do not
have to be available at the same time in order to communicate and also they are not aware of each other. In fact,
the sender does not need to know anything about the receiver; nor does the receiver need to know anything about
the sender. The sender and the receiver need to know only what message format and what destination to use. In
this respect, messaging differs from tightly coupled technologies, such as Remote Method Invocation (RMI), which
requires an application to know a remote application's methods.
Message Oriented Middleware (MOM) systems like MQSeries, MQSonic, etc are proprietary systems. Java
Message Service (JMS) is a Java API that allows applications to create, send, receive, and read messages in a
standard way. Designed by Sun and several partner companies, the JMS API defines a common set of interfaces
and associated semantics that allow programs written in the Java programming language to communicate with
other messaging implementations (e.g. MQSonic, TIBCO etc). The JMS API minimises the set of concepts a
programmer must learn to use messaging products but provides enough features to support sophisticated
messaging applications. It also strives to maximise the portability of JMS applications across JMS providers.
Companies have spent decades developing their legacy systems. Rather than throwing these systems out, XML
can be used in a non-proprietary way to move data from legacy systems to distributed systems like J2EE over the
wire-using MOM and JMS.
How JMS is different from RPC?
Remote Procedure Call (e.g. RMI) JMS
Remote Procedure Call (RPC) technologies like RMI With the use of Message Oriented Middleware (MOM), problems
attempt to mimic the behaviour of system that runs in one with the availability of subsystems are less of an issue. A
process. When a remote procedure is invoked the caller is fundamental concept of MOM is that communications between
blocked until the procedure completes and returns control components is intended to be asynchronous in nature. Code that
to the caller. This is a synchronized model where process is written to connect the pieces together assumes that there is a
is performed sequentially ensuring that tasks are one-way message that requires no immediate response. In other
completed in a predefined order. The synchronized nature words, there is no blocking. Once a message is sent the sender
of RPC tightly couples the client (the software making the can move on to other tasks; it doesn't have to wait for a
call) to the server (the software servicing the call). The response. This is the major difference between RPC and
client can not proceed (its blocked) until the server asynchronous messaging and is critical to understanding the
responds. The tightly coupled nature of RPC creates advantages offered by MOM systems.
highly interdependent systems where a failure on one
system has an immediate impact on other systems. In an asynchronous messaging system each subsystem
(Customer, Account etc) is decoupled from the other systems.
They communicate through the messaging server, so that a
failure in one does not impact the operation of the others.
Find more
WWW.ThesisScientist.com
Enterprise Java 111
Client is blocked while it is being processed. Asynchronous messages also allows for parallel processing i.e.
client can continue processing while the previous request is
being satisfied.
Are messaging applications slow? While there is some overhead in all messaging systems, but this does not
mean that the applications that are using messaging are necessarily slow. Messaging systems can achieve a
throughput of 100 messages per second depending on the installation, messaging modes (synchronous versus
asynchronous, persistent versus non-persistent), and acknowledgment options such as auto mode, duplicates
okay mode, and client mode etc. The asynchronous mode can significantly boost performance by multi-tasking.
For example: In an Internet based shopping cart application, while a customer is adding items to his/her shopping
cart, your application can trigger an inventory checking component, and a customer data retrieval component to
execute concurrently.
Are messaging applications reliable? This is basically a trade-off between performance and reliability. If
reliability is more important then the:
Acknowledgment option should be set to automode where once only delivery is guaranteed
Message delivery mode should be set to persistent where the MOM writes the messages to a secure
storage like a database or a file system to insure that the message is not lost in transit due to a system
failure.
What are some of the key message characteristics defined in a message header?
Characteristic Explanation
JMSCorrelationID Used in request/response situations where a JMS client can use the JMSCorrelationID header to
associate one message with another. For example: a client request can be matched with a response
from a server based on the JMSCorrelationID.
JMSMessageID Uniquely identifies a message in the MOM environment.
JMSDeliveryMode This header field contains the delivery modes: PERSISTENT or NON_PERSISTENT.
JMSExpiration This contains the time-to-live value for a message. If it is set to zero, then a message will never expire.
JMSPriority Sets the message priority but the actual meaning of prioritization is MOM vendor dependent.
What are the different body types (aka payload types) supported for messages? All JMS messages are
read-only once posted to a queue or a topic.
Text message: body consists of java.lang.String.
Map message: body consists of key-value pairs.
Stream message: body consists of streams of Java primitive values, which are accessed sequentially.
XML documents make use of this type.
Object message: body consists of a Serializable Java object.
Byte message: body consists of arbitrary stream of bytes.
What is a message broker?
A message broker acts as a server in a MOM. A message broker performs the following operations on a message
it receives:
Processes message header information.
Performs security checks and encryption/decryption of a received message.
Handles errors and exceptions.
Routes message header and the payload (aka message body).
Invokes a method with the payload contained in the incoming message (e.g. calling onMessage(..) method
on a Message Driven Bean (MDB)).
Transforms the message to some other format. For example XML payload can be converted to other
formats like HTML etc with XSLT.
Q 90: What type of messaging is provided by JMS? SF
A 90: Point-to-Point: provides a traditional queue based mechanism where the client application sends a message
through a queue to typically one receiving client that receives messages sequentially. A JMS message queue is
Find more WWW.ThesisScientist.com
an administered object that represents the message destination for the sender and the message source for the
receiver.
Find more WWW.ThesisScientist.com
112 Enterprise Java
Publish/Subscribe: is a one-to-many publishing model where client applications publish messages to topics,
which are in turn subscribed by other interested clients. All subscribed clients will receive each message.
Q 91: Discuss some of the design decisions you need to make regarding your message delivery? SFDC
A 91:
During your design phase, you should carefully consider various options or modes like message acknowledgment
modes, transaction modes and delivery modes. For example: for a simple approach you would not be using
transactions and instead you would be using acknowledgment modes. If you need reliability then the delivery
mode should be set to persistent. This can adversely affect performance but reliability is increased.
Design Explanation
decision
Message Acknowledgement mode and transaction modes are used to determine if a message will be lost or
acknowledgm re-delivered on failure during message processing by the target application. Acknowledgment
ent options or modes are set when creating a JMS session.
modes.
InitialContext ic = new InitialContext(…);
QueueConnectionFactory qcf = (QueueConnectionFactory)ic.lookup(“AccountConnectionFactory”);
QueueConnection qc = qcf.createQueueConnection();
QueueSession session = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
the above code sample, the transaction mode is set to false and acknowledgment mode is set to auto
mode. Let us look at acknowledgment modes:
AUTO_ACKNOWLEDGE: The messages sent or received from the session are automatically
acknowledged. This mode also guarantees once only delivery. If a failure occurs while executing
onMessage() method of the destination MDB, then the message is re-delivered. A message is
automatically acknowledged when it successfully returns from the onMessage(…) method.
DUPS_OK_ACKNOWLEDGE: This is just like AUTO_ACKNOWLEDGE mode, but under rare
circumstances like during failure recovery messages might be delivered more than once. If a failure occurs
then the message is re-delivered. This mode has fewer overheads than AUTO_ACKNOWLEDGE mode.
CLIENT_ACKNOWLEDGE: The messages sent or received from sessions are not automatically
acknowledged. The destination application must acknowledge the message receipt. This mode gives an
application full control over message acknowledgment at the cost of increased complexity. This can be
acknowledged by invoking the acknowledge() method on javax.jms.Message class.
Transaction In JMS, a transaction organizes a message or a group of messages into an atomic processing unit. So, if a
modes message delivery is failed, then the failed message may be re-delivered. Calling the commit() method
commits all the messages the session receives and calling the rollback method rejects all the messages.
InitialContext ic = new InitialContext(…);
QueueConnectionFactory qcf = (QueueConnectionFactory)ic.lookup(“AccountConnectionFactory”);
QueueConnection qc = qcf.createQueueConnection();
QueueSession session = qc.createQueueSession(true, -1);
In the above code sample, the transaction mode is set to true and acknowledgment mode is set to -1,
which means acknowledgment mode has no use in this mode. Let us look at transaction modes:
Message Driven Bean (MDB) with container managed transaction demarcation: An MDB participates
in a container transaction by specifying the transaction attributes in its deployment descriptor. A transaction
automatically starts when the JMS provider removes the message from the destination and delivers it to
the MDB‟s onMessage(…) method. Transaction is committed on successful completion of the onMessage()
method. A MDB can notify the container that a transaction should be rolled back by setting the
MessageDrivenContext to setRollBackOnly(). When a transaction is rolled back, the message is re-
delivered.
public void onMessage(Message aMessage) {
…
If(someCondtionIsTrue) {
mdbContext.setRollbackOnly();
}
else{
//everything is good. Transaction will be committed automatically on completion of onMessage(..)
method.
}
}
Message Driven Bean (MDB) with bean managed transaction demarcation: A MDB chooses not to
Find more WWW.ThesisScientist.com
Enterprise Java 113
participate in a container managed transaction and the MDB programmer has to design and code
programmatic transactions. This is achieved by creating a UserTransaction object from the MDB‟s
MessageDrivenContext as shown below and then invoking the commit() and rollback() methods on this
UserTransaction object.
public void onMessage(Message aMessage) {
UserTransaction uT = mdbContext.getUserTransaction();
uT.begin();
….
If(someCondtionIsTrue) {
uT.rollback();
}
else{
uT.commit();
}
}
Transacted session: An application completely controls the message delivery by either committing or
rolling back the session. An application indicates successful message processing by invoking Session
class‟s commit() method. Also it can reject a message by invoking Session class‟s rollback() method. This
committing or rollback is applicable to all the messages received by the session.
public void process(Message aMessage, QueueSession qs) {
….
If(someCondtionIsTrue) {
qs.rollback();
}
else{
qs.commit();
}
…
}
What happens to rolled-back messages?
Rolled back messages are re-delivered based on the re-delivery count parameter set on the JMS
provider. The re-delivery count parameter is very important because some messages can never be
successful and this can eventually crash the system. When a message reaches its re-delivery count, the
JMS provider can either log the message or forward the message to an error destination. Usually it is not
advisable to retry delivering the message soon after it has been rolled-back because the target application
might still not be ready. So we can specify a time to re-deliver parameter to delay the re-delivery process
by certain amount of time. This time delay allows the JMS provider and the target application to recover to
a stable operational condition.
Care should be taken not to make use of a single transaction when using the JMS request/response
paradigm where a JMS message is sent, followed by the synchronous receipt of a reply to that message.
This is because a JMS message is not delivered to its destination until the transaction commits, and the
receipt of the reply will never take place within the same transaction.
Note: when you perform a JNDI lookup for administered objects like connection factories, topics and/or
queues, you should use the logical reference java:comp/env/jms as the environment subcontext. It is also
vital to release the JMS resources like connection factories, sessions, queues, topics etc when they are no
longer required in a try{} and finally{} block.
Message What happens, when the messages are with the JMS provider (i.e. MOM) and a catastrophic failure occurs
delivery prior to delivering the messages to the destination application? The messages will be lost if they are non-
options durable. The message‟s state whether they are lost or not does not depend on acknowledgment modes
or transaction modes discussed above. It depends on the delivery mode, which defines whether the
message can be durable (aka persistent) or non-durable (aka non-persistent). If you choose the durable
delivery mode then the message is stored into a database or a file system by the JMS server before
delivering it to the consumer. Durable messages have an adverse effect on performance, but ensure that
message delivery is guaranteed.
InitialContext ic = new InitialContext(…);
QueueConnectionFactory qcf = (QueueConnectionFactory)ic.lookup(“AccountConnectionFactory”);
QueueConnection qc = qcf.createQueueConnection();
QueueSession session = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
//senderQueue is an object of type javax.jms.Queue
QueueSender sender = session.createSender(senderQueue);
Sender.send(message, intDeliveryMode, intPriority, longTimeToLove );
Best practices ƒ A JMS connection represents a TCP/IP connection from the client to the JMS server. A connection is
Find more WWW.ThesisScientist.com
114 Enterprise Java
to improve a valuable resource, which should be opened at the appropriate time, should be used concurrently by
performance creating and using pool of sessions, and close the connection in a finally{} block when finished.
Optimize your JMS sessions with the appropriate acknowledgment mode and transaction mode as
discussed above and close your sessions when you are finished with them.
Choose your message type (text message, byte message, stream message etc) carefully because the
size of a message depends on its type and size can affect performance. For example byte messages
takes less space than text messages and for object messages you can reduce the serialization cost by
marking some of the variables which need not be sent over the network as transient.
Optimize your destinations like queues and topics as follows:
Choose a non-durable (aka non-persistent) delivery mode where appropriate.
Set time to live parameter appropriately after which the message expires.
Where applicable receive messages asynchronously (non-blocking call). If you want to receive
messages synchronously you can use one of the following methods on the message consumer:
receive(); Æ blocks the call until it receives the next message.
receive(long timeout); Æ blocks till a timeout occurs.
receiveNoWait();  never blocks.
Q 92: Give an example of a J2EE application using Message Driven Bean with JMS? SF
A 92:
Messgage Driven Beans
J2EE Server
Web Container
EJB Container EJB Container
Servlet
Session Bean Message
DrivenBean
(client)
)
r
s
r
s
r
i b
e
e
c
h
s
l
i v
e
b
s
Message
i
l
e
b
u
D e
s
u
Messagep
ht
(t
o
The MessageDrivenBean is the consumer
of the message.
Topic
Enterprise - XML
What is XML? And why is XML important? XML stands for eXtensible Markup Language. XML is a grammatical
system for constructing custom markup languages for describing business data, mathematical data, chemical data etc.
XML loosely couples disparate applications or systems utilizing JMS, Web services etc. XML uses the same
building blocks that HTML does: elements, attributes and values. Let‟s look at why XML is important.
Scalable: Since XML is not in a binary format you can create and edit files with anything and it‟s also easy to debug. XML
can be used to efficiently store small amounts of data like configuration files (web.xml, application.xml, struts-config.xml
etc) to large company wide data with the help of XML stored in the database.
Fast Access: XML documents benefit from their hierarchical structure. Hierarchical structures are generally faster to
access because you can drill down to the section you are interested in.
Easy to identify and use: XML not only displays the data but also tells you what kind of data you have. The mark up
tags identifies and groups the information so that different information can be identified by different application.
Find more WWW.ThesisScientist.com
Enterprise Java 115
Stylability: XML is style-free and whenever different styles of output are required the same XML can be used with
different style-sheets (XSL) to produce output in XHTML, PDF, TEXT, another XML format etc.
Linkability, in-line useability, universally accepted standard with free/inexpensive tools etc
Q 93: What is the difference between a SAX parser and a DOM parser? SFPIMI
A 93:
SAX parser DOM parser
A SAX (Simple API for XML) parser does not create any A DOM (Document Object Model) parser creates a tree
internal structure. Instead, it takes the occurrences of structure in memory from an input document and then waits
components of an input document as events (i.e., event for requests from client.
driven), and tells the client what it reads as it reads through
the input document.
A SAX parser serves the client application always only with A DOM parser always serves the client application with the
pieces of the document at any given time. entire document no matter how much is actually needed by the
client.
A SAX parser, however, is much more space efficient in A DOM parser is rich in functionality. It creates a DOM tree in
case of a big input document (because it creates no internal memory and allows you to access any part of the document
structure). What's more, it runs faster and is easier to learn repeatedly and allows you to modify the DOM tree. But it is
than DOM parser because its API is really simple. But from space inefficient when the document is huge, and it takes a
the functionality point of view, it provides a fewer functions, little bit longer to learn how to work with it.
which means that the users themselves have to take care of
more, such as creating their own data structures.
Use SAX parser when Use DOM when
ƒ Input document is too big for available memory. ƒ Your application has to access various parts of the
When only a part of the document is to be read and we
document and using your own structure is just as
ƒ complicated as the DOM tree.
create the data structures of our own.
ƒ Your application has to change the tree very frequently
If you use SAX, you are using much less memory andƒ and data has to be stored for a significant amount of time.
performing much less dynamic memory allocation.
SAX Parser example: Xerces, Crimson etc DOM Parser example: XercesDOM, SunDOM, OracleDOM
Use JAXP (Java API for XML Parsing) which enables
etc.
applications to parse and transform XML documents Use JAXP (Java API for XML Parsing) which enables
independent of the particular XML parser. Code can be applications to parse and transform XML documents
developed with one SAX parser in mind and later on can be independent of the particular XML parser. Code can be
changed to another SAX parser without changing the developed with one DOM parser in mind and later on can be
application code. changed to another DOM parser without changing the
application code.
Q 94: Which is better to store data as elements or as attributes? SF
A 94: A question arising in the mind of XML/DTD designers is whether to model and encode certain information using an
element, or alternatively, using an attribute. The answer to the above question is not clear-cut. But the general
guideline is:
Using an element: <book><title>Lord of the Rings</title>...</book>: If you consider the information in
question to be part of the essential material that is being expressed or communicated in the XML, put it in an
element
Using an attribute: <book title=" Lord of the Rings "/>: If you consider the information to be peripheral or
incidental to the main communication, or purely intended to help applications process the main
communication, use attributes.
The principle is data goes in elements and metadata goes in attributes. Elements are also useful when they
contain special characters like “<”, “>”, etc which are harder to use in attributes.
Q 95: What is XPATH? What is XSLT/XSL/XSL-FO/XSD/DTD etc? What is JAXB? What is JAXP? SF
A 95:
Find more WWW.ThesisScientist.com
116 Enterprise Java
What Explanation Example
is
XML XML stands for eXtensible Markup Language Sample.xml
<?xml version="1.0"?>
<note>
<to>Peter</to>
<from>Paul</from>
<title>Invite</title>
<content language=”English”>Not Much</content>
< content language=”Spanish”>No Mucho</content >
</note>
DTD DTD stands for Document Type Definition. XML provides Sample.dtd
an application independent way of sharing data. With a
DTD, independent groups of people can agree to use a <!ELEMENT note (to, from, title, content)>
common DTD for interchanging data. Your application can <!ELEMENT to (#PCDATA)>
use a standard DTD to verify that data that you receive <!ELEMENT from (#PCDATA)>
from the outside world is valid. You can also use a DTD to <!ELEMENT title (#PCDATA)>
verify your own data. So the DTD is the building blocks or <!ELEMENT content (#PCDATA)>
schema definition of the XML document. <!ATTLIST content language CDATA #Required>
XSD XSD stands for Xml Schema Definition, which is a Sample.xsd
successor of DTD. So XSD is a building block of an XML
document. <?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
If you have DTD then why use XSD you may ask? targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
XSD is more powerful and extensible than DTD. XSD has: elementFormDefault="qualified">
• Support for simple and complex data types. <xs:element name="note">
• Uses XML syntax. So XSD are extensible just like <xs:complexType>
XML because they are written in XML. <xs:sequence>
• Better data communication with the help of data <xs:element name="to" type="xs:string"/>
types. For example a date like 03-04-2005 will be <xs:element name="from" type="xs:string"/>
interpreted in some countries as 3
rd
of April 2005 and <xs:element name="title" type="xs:string"/>
in some other countries as 04
th
March 2005. <xs:element name="content" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:attribute name="language" type=”xs:string”
use=”Required” />
</xs:element>
</xs:schema>
XSL XSL stands for eXtensible Stylesheet Language. The XSL To convert the Sample.xml file to a XHTML file let us apply the
consists of 3 parts: following Sample.xsl through XALAN parser.
• XSLT: Language for transforming XML documents Sample.xsl
from one to another.
<?xml version="1.0"?>
• XPath: Language for defining the parts of an XML <xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
document. <xsl:template match="/">
<xsl:apply-templates select="note " />
• XSL-FO: Language for formatting XML documents. </xsl:template>
For example to convert an XML document to a PDF
<xsl:template match="note">document etc.
<html>
XSL can be thought of as a set of languages that can : <head>
<title><xsl:value-of
• Define parts of an XML select="content/@language">
• Transform an XML document to XHTML (eXtensible </title>
</head>Hyper Text Markup Language) document.
</html>• Convert an XML document to a PDF document.
</xsl:template>
• Filter and sort XML data.
</xsl:stylesheet>
You get the following output XHTML file:
Xalan (From Apache)XSLT processor example:
Sample.xhtml
<html>
PDF Processor example: FOP (Formatting Objects <head>
Processor from Apache) <title>English</title>
Find more WWW.ThesisScientist.com
Enterprise Java 117
</head>
</html>
Now to convert the Sample.xml into a PDF file apply the
following FO (Formatting Objects) file Through the FOP
processor.
Sample.fo
<?xml version="1.0" encoding="ISO-8859-1"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
<fo:layout-master-set>
<fo:simple-page-master master-name="A4">
</fo:simple-page-master>
</fo:layout-master-set>
<fo:page-sequence master-reference="A4">
<fo:flow flow-name="xsl-region-body">
<fo:block>
<xsl:value-of select="content[@language='English']">
</fo:block>
</fo:flow>
</fo:page-sequence>
</fo:root>
which gives a basic Sample.pdf which has the following line
Not Much
XPath Xml Path Language, a language for addressing parts of an As per Sample.xsl
XML document, designed to be used by both XSLT and
XPointer. We can write both the patterns (context-free) and <xsl:template match=”content[@language=‟English‟]”>
expressions using the XPATH Syntax. XPATH is also used ………
in XQuery. <td><xsl:value-of select=”content/@language” /></td>
JAXP Stands for Java API for XML Processing. This provides a DOM example using JAXP:
common interface for creating and using SAX, DOM, and
XSLT APIs in Java regardless of which vendor‟s DocumentBuilderFactory dbf =
implementation is actually being used (just like the JDBC, DocumentBuilderFactory.newInstance();
JNDI interfaces). JAXP has the following packages: DocumentBuilder db = dbf.newDocumentBuilder();
Document doc =
db.parse(new File("xml/Test.xml"));
NodeList nl = doc.getElementsByTagName("to");
Node n = nl.item(0);
System.out.println(n.getFirstChild().getNodeValue());
SAX example using JAXP:
SAXParserFactory spf =
SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
SAXExample se = new SAXExample();
sp.parse(new File("xml/Sample.xml"),se);
where SAXExample.Java code snippet
public class SAXExample extends DefaultHandler {
public void startElement(
String uri,
String localName,
String qName,
Attributes attr)
throws SAXException {
System.out.println("--->" + qName);
}
...
}
Find more WWW.ThesisScientist.com
118 Enterprise Java
JAXP
The DefaultHandler implements ContentHandler,
DTDHandler, EntityResolver, ErrorHandler
SAXParser implements XSLT example using JAXP:
Factory Content
StreamSource xml =
S
A
X
R
e
a
d
e
r
S
A
X
E
x
a
m
p
l
e
Handler
Error
new StreamSource(new File("/xml/Sample.xml"));
StreamSource xsl = new StreamSource(
HandlerSAXParser new File("xml/Sample.xsl"));
DTD StreamResult result =
XML
Handler new StreamResult(new File("xml/Sample.xhtml"));
Entity
Sample. TransformerFactory tf =
Resolver
xml TransformerFactory.newInstance();
Transformer t = tf.newTransformer(xsl);
t.transform(xml, result);
DocumentBuilder
This gives you Sample.xhtml
Factory
Document <html>
<head>
XML
(DOM)
Document
<title>English</title>
noteSample. </head>Builder
xml
to from
</html>
Transformer
Factory
Source
Transformer
Result
sample. sample.
xml xhtml
Transformation
instructions
sample.xsl
javax.xml.parsers  common interface for different
vendors of SAX, DOM parsers).
org.xml.sax  Defines basic SAX API.
org.w3c.dom  Defines Document Object Model and
its componenets.
javax.xml.transform  Defines the XSLT API which
allows you to transform XML into other forms like
PDF, XHTML etc.
Required JAR files are jaxp.jar, dom.jar,
xalan.jar, xercesImpl.jar.
JAXB Stands for Java API for XML Binding. This standard Lets look at some code:
defines a mechanism for writing out Java objects as XML
(marshalling) and for creating Java objects from For binding:
XMLstructures (unmarshalling). (You compile a class
description to create the Java classes, and use those xjc.sh –p com.binding sample.xsd –d work
classes in your application.)
-p identifies the package for the generated Java files (ie
*.Java)
-d option identifies the target.
Unmarshalling the XML document:
JAXBContext jc = JAXBContext.newInstance(
“com.binding”);
Unmarshaller um = jc.createUnmarshaller();
Object o = um.unMarshall(
new File(“/xml/”));
Find more
WWW.ThesisScientist.com
Enterprise Java 119
JAXB
XML
schema
Sample.xsd
r
g en i
c
l
i p
j d
x n mi
o
b c
Java files
(*.java interfaces
&
implementations)
c
a
v
a
j
Java
class files
*.class
u
s
e
Application Java content
XML unmarshall Objects
Sample. JAXB note
xml API
marshall
to from
Note n = (Note) n;
System.out.println(n.getFrom().getContent().get(0));
System.out.println(n.getTo().getContent().get(0));
Now to modify the in memory object content:
n. getFrom().getContent().set(0, “newValue”);
Marshalling the change back to different XML file:
Marshaller m = jc.createMarshaller();
FileOutputStream fos = new FileOutputStream( new
File(“/xml/SampleNew.xml”));
m.marshall(n, fos);
Enterprise – SQL, Tuning and O/R mapping
Q 96: Explain inner and outer joins? SF
A 96: Joins allow database users to combine data from one table with data from one or more other tables (or views, or
synonyms). Tables are joined two at a time making a new table containing all possible combinations of rows from
the original two tables. Lets take an example (syntax vary among RDBMS):
Joins and Set operations in Relational Databases
Inner join Left outer join Right outer join Full outer join
Find more WWW.ThesisScientist.com
120 Enterprise Java
Employees table
Id firstname Surname state
1001 John Darcy NSW
1002 Peter Smith NSW
1003 Paul Gregor NSW
1004 Sam Darcy VIC
Executives table
Id firstname Surname state
1001 John Darcy NSW
1002 Peter Smith NSW
1005 John Gregor WA
Inner joins: Chooses the join criteria using any column names that happen to match between the two tables. The
example below displays only the employees who are executives as well.
SELECT emp.firstname, exec.surname FROM employees emp, executives exec
WHERE emp.id = exec.id;
The output is:
Firstname surname
John Darcy
Peter Smith
Left Outer joins: A problem with the inner join is that only rows that match between tables are returned. The
example below will show all the employees and fill the null data for the executives.
SELECT emp.firstname, exec.surname FROM employees emp left join executives exec
ON emp.id = exec.id;
On oracle
SELECT emp.firstname, exec.surname FROM employees emp, executives
exec where emp.id = exec.id(+);
The output is:
Firstname surname
John Darcy
Peter Smith
Paul
Sam
Right Outer join: A problem with the inner join is that only rows that match between tables are returned. The
example below will show all the executives and fill the null data for the employees.
SELECT emp.firstname, exec.surname FROM employees emp right join executives exec
ON emp.id = exec.id;
On oracle
SELECT emp.firstname, exec.surname FROM employees emp, executives exec
WHERE emp.id(+) = exec.id;
The output is:
Firstname surname
John Darcy
Peter Smith
Gregor
Full outer join: To cause SQL to create both sides of the join
SELECT emp.firstname, exec.surname FROM employees emp full join executives exec
ON emp.id = exec.id;
On oracle
SELECT emp.firstname, exec.surname FROM employees emp, executives exec
WHERE emp.id = exec.id (+)
Find more WWW.ThesisScientist.com
Enterprise Java 121
UNION
SELECT emp.firstname, exec.surname FROM employees emp, executives exec
WHERE emp.id(+) = exec.id
Note: Oracle9i introduced the ANSI compliant join syntax. This new join syntax uses the new keywords inner join, left outer join,
right outer join, and full outer join, instead of the (+) operator.
The output is:
Firstname surname
John Darcy
Paul
Peter Smith
Sam
Gregor
Self join: A self-join is a join of a table to itself. If you want to find out all the employees who live in the same city
as employees whose first name starts with “Peter”, then one way is to use a sub-query as shown below:
SELECT emp.firstname, emp.surname FROM employees emp WHERE city
IN (SELECT city FROM employees where firstname like „Peter‟)
The sub-queries can degrade performance. So alternatively we can use a self-join to achieve the same results.
On oracle
SELECT emp.firstname, emp.surname FROM employees emp, employees emp2
WHERE emp.state = emp2.state
AND emp2.firstname LIKE 'Peter'
The output is:
Firstname Surname
John Darcy
Peter Smith
Paul Gregor
Q 97: Explain a sub-query? How does a sub-query impact on performance? SFPI
A 97: It is possible to embed a SQL statement within another. When this is done on the WHERE or the HAVING
statements, we have a subquery construct. What is subquery useful for? It is used to join tables and there are
cases where the only way to correlate two tables is through a subquery.
SELECT emp.firstname, emp.surname FROM employees emp WHERE
emp.id NOT IN (SELECT id FROM executives);
There are performance problems with sub-queries, which may return NULL values. The above sub-query can be
re-written as shown below by invoking a correlated sub-query:
SELECT emp.firstname, emp.surname FROM employees emp WHERE
emp.id NOT EXISTS (SELECT id FROM executives);
The above query can be re-written as an outer join for a faster performance as shown below:
SELECT emp.firstname, exec.surname FROM employees emp left join executives exec
on emp.id = exec.id AND exec.id IS NULL;
The above execution plan will be faster by eliminating the sub-query.
Q 98: What is normalization? When to denormalize? DCPI
A 98: Normalization is a design technique that is widely used as a guide in designing relational databases. Normalization
is essentially a two step process that puts data into tabular form by removing repeating groups and then removes
duplicated data from the relational tables (Additional reading recommended).
Redundant data wastes disk space and creates maintenance problems. If data that exists in more than one place
must be changed, the data must be changed in exactly the same way in all locations which is time consuming and
prone to errors. A change to a customer address is much easier to do if that data is stored only in the Customers
table and nowhere else in the database.
Find more WWW.ThesisScientist.com
122 Enterprise Java
Inconsistent dependency is a database design that makes certain assumptions about the location of data. For
example, while it is intuitive for a user to look in the Customers table for the address of a particular customer, it
may not make sense to look there for the salary of the employee who calls on that customer. The employee's
salary is related to, or dependent on, the employee and thus should be moved to the Employees table.
Inconsistent dependencies can make data difficult to access because the path to find the data may not be logical,
or may be missing or broken.
First normal form Second Normal Form Third Normal Form
A database is said to be in First A database is in Second Normal Form A database is in Third Normal Form when
Normal Form when all entities when it is in First Normal Form plus it is in Second Normal Form and each
have a unique identifier or key, every non-primary key column in the column that isn't part of the primary key
and when every column in every table must depend on the entire primary doesn't depend on another column that
table contains only a single value key, not just part of it, assuming that the isn't part of the primary key.
and doesn't contain a repeating primary key is made up of composite
group or composite field. columns.
When to denormalize? Normalize for accuracy and denormalize for performance.
Typically, transactional databases are highly normalized. This means that redundant data is eliminated and
replaced with keys in a one-to-many relationship. Data that is highly normalized is constrained by the primary
key/foreign key relationship, and thus has a high degree of data integrity. Denormalized data, on the other hand,
creates redundancies; this means that it's possible for denormalized data to lose track of some of the relationships
between atomic data items. However, since all the data for a query is (usually) stored in a single row in the table, it
is much faster to retrieve.
Q 99: How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables? SF
A 99: One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign
key relationships.
One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key
relationships.
Many-to-Many relationships are implemented using join table with the keys from both the tables forming
the composite primary key of the junction table.
Q 100: How can you performance tune your database? PI
A 100:
Denormalize your tables where appropriate.
Proper use of index columns: An index based on numeric fields is more efficient than an index based on
character columns.
Reduce the number of columns that make up a composite key.
Proper partitioning of tablespaces and create a special tablespace for special data types like CLOB,
BLOB etc.
Data access performance can be tuned by using stored procedures to crunch data in the database server
to reduce the network overhead and also caching data within your application to reduce the number of
accesses.
Q 101: How will you map objects to a relational database? How will you map class inheritance to relational data model?
DC
A 101: Due to impedance mismatch between object and relational technology you need to understand the process of
mapping classes (objects) and their relationships to tables and relationships between them in a database.
Classes represent both behaviour and data whereas relational database tables just implement data. Database
schemas have keys (primary keys to uniquely identify rows and foreign keys to maintain relationships between
rows) whereas object schema does not have keys and instead use references to implement relationships to
other objects. Let us look at some basic points on mapping:
Find more WWW.ThesisScientist.com
Enterprise Java 123
Object to Relational (O/R) mapping of class inheritance structure
Map class hierarchy to a single database table
Employee Employee
-EmployeeId (PK) -EmployeeId (PK)
-EmployeeType -IsPermanent
-Name -IsContractor
-Salary Refactored -IsSubContractor
-Rate -Name
Class diagram -Period -Salary
-Rate
-Period
Address
Employee
Employee Map each class to its own table
* 1 -name
-streetname -EmployeeId (PK)
-address
-Name
+getName()
Permanent Contractor Permanent Contractor
-salary -rate -EmployeeId (PK) -EmployeeId (PK)
+getSalary() +getRate() -Salary -Contract
SubContractor
SubContractor
-period
-EmployeeId (PK)
+calculateTotal()
-Period
Map each concrete class to its own table
ContractorPermanent
-EmployeeId (PK)-EmployeeId (PK)
-Name-Name
-Contract-Salary
SubContractor
-EmployeeId (PK)
-Name
-Period
Classes map to tables in a way but not always directly.
An attribute of a class can be mapped to zero or more columns in a database. Not all attributes are
persistent.
Some attributes of an object are objects itself. For example an Employee object has an Address object as
an attribute. This is basically an association relationship between two objects (i.e. Employee and
Address). This is a recursive relationship where at some point the attribute will be mapped to zero or
more columns. In this example attributes of the Address class will be mapped zero or more columns.
In its simple form an attribute maps to a single column whereas each has same type (ie attribute is a string and
column is a char, or both are dates etc). When you implement mapping with different types (attribute is a
currency and column is a float) then you will need to be able to convert them back and forth.
How do you map inheritance class structure to relational data model?
Relational databases do not support inheritance. Class inheritance can be mapped to relational tables as
follows:
Map class hierarchy to single database table: The whole class hierarchy can be stored in a single table by
adding an additional column named “EmployeeType”. The column “EmployeeType” will hold the values
“Permanent”, “Contract” and “SubContract”. New employee types can be added as required. Although this
approach is straightforward it tends to break when you have combinations like an employee is of type both
“Contractor” and “SubContractor”. So when you have combinations, you can use refactored table by replacing
type code column “EmployeeType” with boolean values such as isPermanent, isContractor and isSubContractor.
Map each class to its own table: You create one table per class. The data for a permanent employee is stored
in two tables (Employee and Permanent), therefore to retrieve this data you need to join these two tables. To
support additional employee type say a Contractor, add a new table.
Find more WWW.ThesisScientist.com
124 Enterprise Java
Map each concrete class to its own table: You create one table per concrete class. There are tables
corresponding to each class like Permanent, Contractor and SubContractor. So join is not required. To support
additional employee type, add a new table.
So which approach to use? Easiest approach is to have one table per hierarchy and easy to refactor. If you
need a “pure design approach” then use one table per class approach. Try to stay away from one table per
concrete class approach because it makes refactoring difficult by copying data back and forth between tables.
No approach is ideal for all situations.
Another option for mapping inheritance into relational database is to take a generic meta -data driven approach.
This approach supports all forms of mapping. In this approach, value of a single attribute will be stored as a row
in a table called “Value”. So, to store 5 attributes you need 5 rows in “Value” table. You will have a table called
“Class” where class names are stored, a table called “Inheritance” where subclass and superclass information is
stored, a table called “Attributes” where class attributes are stored and an “AttributeType” lookup table.
Q 102: What is a view? Why will you use a view? What is an aggregate function? Etc. SFPI
A 102:
Question Explanation
What is view? Why use a view? View is a precompiled SQL query, which is used to select data from one or more tables.
A view is like a table but it doesn‟t physically take any space (ie not materialised). Views
are used for
ƒ Providing inherent security by exposing only the data that is needed to be shown to
the end user.
ƒ Enabling re-use of SQL statements.
ƒ Allows changes to the underlying tables to be hidden from clients, aiding
maintenance of the database schema (i.e. encapsulation).
Views with multiple joins and filters can dramatically degrade performance because
views contain no data and any retrieval needs to be processed. The solution for this is to
use materialised views or create de-normalised tables to store data. This technique is
quite handy in overnight batch processes where a large chunk of data needs to be
processed. Normalised data can be read and inserted into some temporary de-
normalised table and processed with efficiency.
Explain aggregate SQL functions? SQL provides aggregate functions to assist with the summarisation of large volumes of
data.
We‟ll look at functions that allow us to add and average data, count records meeting
specific criteria and find the largest and smallest values in a table.
ORDERID FIRSTNAME SURNAME QTY UNITPRICE
1001 John Darcy 25 10.5
1002 Peter Smith 25 10.5
1003 Sam Gregory 25 10.5
SELECT SUM(QTY) AS Total FROM Orders;
The output is: Total = 75
SELECT AVG(UnitPrice * QTY) As AveragePrice FROM Orders;
The output is: AveragePrice = 262.50
If we inserted another row to the above table:
ORDERID FIRSTNAME SURNAME QTY UNITPRICE
1004 John Darcy 20 10.50
SELECT FIRSTNAME,SUM(QTY) FROM orders
GROUP BY FIRSTNAME
HAVING SUM(QTY)>25;
The output is: John 45
Explain INSERT, UPDATE, and INSERT statements can be carried out several ways:
DELETE statements?
INSERT INTO ORDERS values (1004, 'John', 'Darcy', 20, 10.50);
Find more WWW.ThesisScientist.com
Enterprise Java 125
The above statement is fine but the one below is recommended since it is less
ambiguous and less prone to errors.
INSERT INTO ORDERS (orderid, firstname, surname, qty, unitprice)
values (1005, 'John', 'Darcy', 20, 10.50);
We can also use INSERT with the SELECT statements as shown below
INSERT into NEW_ORDERS (orderid, firstname, surname, qty, unitprice)
SELECT orderid, firstname, surname, qty, unitprice
FROM orders WHERE orderid = 1004;
UPDATE statement allows you to update a single or multiple statements.
UPDATE ORDERS set firstname='Peter', surname='Piper'
WHERE orderid=1004;
Also can have more complex updates like
UPDATE supplier
SET supplier_name = ( SELECT customer.name
FROM customers
WHERE customers.customer_id = supplier.supplier_id)
WHERE EXISTS
(SELECT customer.name
FROM customers
WHERE customers.customer_id = supplier.supplier_id);
DELETE statements allow you to remove records from the database.
DELETE FROM ORDERS WHERE orderid=1004;
We can clear the entire table using
TRUNCATE TABLE employees;
When running UPDATE/DELETE care should be taken to include WHERE clause
otherwise you can inadvertently modify or delete records which you do not intend to
UPDATE/DELETE.
How can you compare a part of You can use wild card characters like:
the name rather than the entire
name? • * ( % in oracle)  Match any number of characters.
• ? ( _ in oracle)  Match a single character.
To find all the employees who has “au”:
SELECT * FROM employees emp
WHERE emp.firstname LIKE „%au%‟;
How do you get distinct entries The SELECT statement in conjunction with DISTINCT lets you select a set of distinct
from a table? values from a table in a database.
SELECT DISTINCT empname FROM emptable
How can you find the total number Use the COUNT key word:
of records in a table?
SELECT COUNT(*) FROM emp WHERE age>25
What's the difference between a Both primary key and unique key enforce uniqueness of the column on which they are
primary key and a unique key? defined. But by default primary key creates a clustered index on the column, whereas
unique creates a non-clustered index by default. Another major difference is that,
primary key doesn't allow NULLs, but unique key allows one NULL only.
What are constraints? Explain Constraints enable the RDBMS enforce the integrity of the database automatically,
different types of constraints. without needing you to create triggers, rule or defaults.
Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY
What is an index? What are the The books you read have indexes, which help you to go to a specific key word faster.
types of indexes? How many The database indexes are similar.
clustered indexes can be created
on a table? What are the Indexes are of two types. Clustered indexes and non-clustered indexes. When you
Find more WWW.ThesisScientist.com
126 Enterprise Java
advantages and disadvantages of create a clustered index on a table, all the rows in the table are stored in the order of the
creating separate index on each clustered index key. So, there can be only one clustered index per table. Non-clustered
column of a table? indexes have their own storage separate from the table data storage. The row located
could be the RowID or the clustered index key, depending up on the absence or
presence of clustered index on the table.
If you create an index on each column of a table, it improves the query performance, as
the query optimizer can choose from all the existing indexes to come up with an efficient
execution plan. At the same time, data modification operations (such as INSERT,
UPDATE, and DELETE) will become slow, as every time data changes in the table, all
the indexes need to be updated. Another disadvantage is that, indexes need disk space,
the more indexes you have, more disk space is used.
Enterprise - RUP & UML
Q 103: What is RUP? SD
A 103: Rational Unified Process (RUP) is a general framework that can be used to describe a development process. The
software development cycle has got 4 phases in the following order Inception, Elaboration, Construction, and
Transition.
R a tio n a l U n ifie d P ro c e s s
Disciplines(verticalaxis)
B u s in e s s M o d e llin g
R e q u ire m e n ts
A n a lys is & D e s ig n Im
p le m e n ta tio n T e s t D
e p lo ym e n t
C o n fig & C h a n g e m g m t
P ro je c t m g m t
E n v iro n m e n t
P H A S E S
In c e p tio n e la b o r a tio n c o n s tr u c tio n tr a n s itio n
In c e p tio n # 1 E la b # 1 E la b # 2 C o n C o n C o n T ra n s itio n # 1
# 1 # 2 # 3
IT E R A T IO N S
P H A S E S / IT E R A T IO N S (H o riz o n ta l a x is )
The core of the phases is state-based, and the state is determined by what fundamental questions you are trying
to answer:
Inception - do you and the customer have a shared understanding of the system?
Elaboration - do you have baseline architecture to be able to build the system?
Construction - are you developing a product?
Transition - are you trying to get the customer to take ownership of the system?
RUP is based on a few important philosophies and principles:
A software project team should plan ahead.
It should know where it is going.
It should capture project knowledge in a storable and extensible form.
The best practices of RUP involve the following major 5 properties:
Best practice property Description
Use case driven Interaction between the users and the system.
Architecture centric Based on architecture with clear relationships between architectural components.
Iterative The problem and the solution are divided into more manageable smaller pieces, where each
Find more WWW.ThesisScientist.com
Enterprise Java 127
iteration will be addressing one of those pieces.
Incremental Each iteration builds incrementally on the foundation built in the previous iteration.
Controlled Control with respect to process means you always know what to do next; control with respect to
management means that all deliverables, artifacts, and code are under configuration
management.
Q 104: Explain the 4 phases of RUP? SD
A 104:
RUP Phases
Construction
INCEPTION ELABORATION TRANSITION
Iter 1 Iter 2 Iter 3 Iter 4 Iter 5 Iter 6
Inception: During the inception phase, you work out the business case for the project. You also will be
making a rough cost estimate and return on investment. You should also outline the scope and size of the
project.
The fundamental question you ask at the end of this phase: do you and the customer have a shared
understanding of the system?
Elaboration: At this stage you have the go ahead of the project however only have vague requirements. So
at this stage you need to get a better understanding of the problem. Some of the steps involved are:
What is it you are actually going to build?
How are you going to build it?
What technology are you going to use?
Analysing and dealing with requirement risks, technological risks, skill risks, political risks etc.
Develop a domain model, use case model and a design model. The UML techniques can be used for
the model diagrams (e.g. class diagrams, sequence diagrams etc).
An important result of the elaboration phase is that you have a baseline architecture. This architecture
consists of:
A list of use cases depicting the requirements.
The domain model, which captures your understanding of the domain with the help of UML class
diagrams.
Selection of key implementation technology and how they fit together. For example: Java/J2EE with
JSP, Struts, EJB, XML, etc.
The fundamental question you ask at the end of this phase: do you have a baseline architecture to be
able to build the system?
Construction: In this phase you will be building the system in a series of iterations. Each iteration is a mini
project. You will be performing analysis, design, unit testing, coding, system testing, and integration testing for
the use cases assigned to each iteration. The iterations within the construction phase are incremental and
iterative. Each iteration builds on the use cases developed in the previous iterations. The each iteration will
involve code rewrite, refactoring, use of design patterns etc.
The basic documentation required during the construction phase is:
A class diagram and a sequence diagram.
Some text to pull the diagrams together.
Find more WWW.ThesisScientist.com
128 Enterprise Java
If a class has complex life cycle behaviour then a state diagram is required.
If a class has a complex computation then an activity diagram is required.
The fundamental question you ask at the end of this phase: do you have a developed product?
Transition: During this phase you will be delivering the finished code regularly. During this phase there is no
coding to add functionality unless it is small and essential. There will be bug fixes, code optimisation etc
during this phase. An example of a transition phase is that the time between the beta release and the final
release of a product.
The fundamental question you ask at the end of this phase: are you trying to get the customer to
take ownership of the developed product or system?
Q 105: What are the characteristics of RUP? Where can you use RUP? SD
A 105:
RUP is based on a few important philosophies and principles like planning ahead, knowing where the process
is heading and capturing the project in storable and extensible manner.
It is largely based on OO analysis and design, and use case driven etc.
Iterative and incremental development as oppose to waterfall approach, which hides problems.
Architecture centric approach.
RUP is more suited for larger teams of 50-100 people. RUP can also be used as an agile (i.e. lightweight)
process for smaller teams of 20-30 people, or as a heavy weight process for larger teams of 50-100 people.
Extreme Programming (XP) can be considered as a subset of RUP. At the time of writing, the agile (i.e
lightweight) software development process is gaining popularity and momentum across organizations.
Several methodologies fit under this agile development methodology banner. All these methodologies share
many characteristics like iterative and incremental development, test driven development, stand up
meetings to improve communication, automatic testing, build and continuous integration of code etc.
Refer Q136 in Enterprise Java section.
Q 106: Why is UML important? SDDC
A 106: The more complicated the underlying system, the more critical the communication among everyone involved in
developing and deploying the software. UML is a software blueprint language for analysts, designers and
developers. UML provides a common vocabulary for the business analysts, architects, developers etc.
UML is applicable to the Object Oriented problem solving. UML begins with a model; A model is an abstraction
of the underlying problem. The domain is the actual world from which the problem comes. The model consists of
objects. The objects interact with each other by sending and receiving messages. The objects are
characterised by attributes and operations (behaviours). The values of an object‟s attributes determine its
state. The classes are the blueprints (or like templates) for objects. A class wraps attributes and methods into
a single distinct entity. The objects are the instances of classes.
Q 107: What are the different types of UML diagrams? SDDC
A 107: Use case diagrams: Depicts the typical interaction between external users (actors) and the system. The
emphasis is on what a system does rather than how it does it. A use case is a summary of scenarios for a
single task or goal. An actor is responsible for initiating a task. The connection between actor and use case is a
communication association.
Capturing use cases is one of the primary tasks of the elaboration phase of RUP. In its simplest usage, you
capture a use case by talking to your users and discussing the various things they might want to do with the
system.
When to use „use case‟ diagrams?
Determining user requirements. New use cases often generate new requirements.
Communicating with clients. The simplicity of the diagram makes use case diagrams a good way for
designers and developers to communicate with clients.
Generating test cases. Each scenario for the use case may suggest a suite of test cases.
Find more WWW.ThesisScientist.com
Enterprise Java 129
U s e c a s e d i a g r a m
a s s o c i a t i o n
*
R e g i s t r a r
E n r o l l i n U n i v e r s i
< < i n c l u d e > >
E n r o l l i n s e m i n a r
t y
a s s o c i a t i o n
< < e x t e n d > >
S t u d e n t
p e r f o r m s e c u r i t y i n h e r i t a n c e E n r o l l f a m i l y
i n h e r i t a n c e
c h e c k m e m b e r s
N o t e :
< < e x t e n d > > r e l a t i o n s h i p i s c o n d i t i o n a l . Y o u d o
a s s o c i a t i o n n o t k n o w i f o r w h e n e x t e n d i n g u s e c a s e w i l l b e
i n v o k e d .
< < i n c l u d e > > r e l a t i o n s h i p i s s i m i l a r t o a
p r o c e d u r e c a l l .
i n h e r i t a n c e : e x t e n d s t h e b e h a v i o r o f t h e
I n t e r n a t i o n a l S t u d e n t
p a r e n t u s e c a s e o r a c t o r .
Class diagrams: Class diagram technique is vital within Object Oriented methods. Class diagrams describe the
types of objects in the system and the various static relationships among them. Class diagrams also show the
attributes and the methods. Class diagrams have the following possible relationships:
Association: A relationship between instances of 2 classes.
Aggregation: An association in which one class belongs to a collection (does not always have to be a
collection. You can also have cardinality of “1”). This is a part of a whole relationship where the part can
exist without the whole. For example: A line item is whole and the products are the parts. If a line item is
deleted then the products need not be deleted.
Composition: An association in which one class belongs to a collection (does not always have to be a
collection. You can also have cardinality of “1”). This is a part of a whole relationship where the part cannot
exist without the whole. If the whole is deleted then the parts are deleted. For example: An Order is a whole
and the line items are the parts. If an order is deleted then all the line items should be deleted as well (ie
cascade deletes).
Generalization: An inheritance link indicating that one class is a superclass of the other. The Generalization
expresses the “is a” relationship whereas the association, aggregation and composition express the “has a”
relationship.
Dependency: A dependency is a weak relationship where one class requires another class. The dependency
expresses the “uses” relationship. For example: A domain model class uses a utility class like Formatter etc.
C lass D iagram
a s s o c ia tio n
c o m p o s itio n d e p e n d e n c y
O rd e rD e ta ilC u s to m e r O rd e r
-LineId
-order : O rder 1 * -lineItem s : List 1 1 ..* -product : P roduct
+ o p e ra tio n 1 () -com m ents
g e n e ra liz a tio n
«utility» 1
F o rm a tte r a g g re g a tio n
S ta n d a rd O rd e r C u s to m O rd e r *
-specialD etails +form atD ecim al()
+form atC urrency() P ro d u c t
-productC ode
-productD esc
-unitP rice
When to use class diagrams?
Class diagrams are the backbone of Object Oriented methods. So they are used frequently.
Find more WWW.ThesisScientist.com
130 Enterprise Java
Class diagrams can have a conceptual perspective and an implementation perspective. During the analysis
draw the conceptual model and during implementation draw the implementation model.
Package diagrams: To simplify complex class diagrams you can group classes into packages.
P a c k a g e D i a g r a m
A c c o u n t i n g O r d e r i n g
d e p e n d e n c y
d e p e n d e n c y
C u s t o m e r
When to use package diagrams?
Package diagrams are vital for large projects.
Object diagrams: Object diagrams show instances instead of classes. They are useful for explaining some
complicated objects in detail about their recursive relationships etc.
O b je c t D ia g r a m
O b je c t D ia g r a m
C la s s D ia g r a m
o b je c t n a m ep h y s ic s M a th s : D e p a r tm e n t
C la s s n a m e
1
0 . . *
im p r o v e c la r ity p h y s ic s : D e p a rtm e n t m a th : D e p a r tm e n t
D e p a r t m e n t
p u r e M a th : D e p a rtm e n t a p p lie d M a th : D e p a rtm e n t
R e c u r s iv e c la s s
d ia g ra m d iffic u lt to fu lly
u n d e r s ta n d S h o w s th e d e ta ils o f th e r e c u rs iv e o b je c t re la tio n s h ip
When to use object diagrams?
Object diagrams are a vital for large projects.
They are useful for explaining structural relationships in detail for complex objects.
Sequence diagrams: Sequence diagrams are interaction diagrams which detail what messages are sent and
when. The sequence diagrams are organized according to time. The time progresses as you move from top to
bottom of the diagram. The objects involved in the diagram are shown from left to right according to when they
take part.
S e q u e n c e D ia g r a m
c lie n t a n O r d e r : O r d e r
a n E n tr y : O r d e r E n tr y
c h e c k if s u ffic ie n t d e ta ils
m a k e A n O r d e r ( ) m a k e A n O r d e r ( ) a r e a v a ila b le
fo r e a c h lin e I te m
it e r a t io n [ f o r e a c h ... ] ( )
h a s S u ffic ie n tD e ta ils ( )
c o n fir m : C o n f ir m a tio n
p r in tC o n fir m a tio n ( )
N o te : E a c h v e r t ic a l d o tt e d lin e is a
lin e a r e c a lle d t h e a c t iv a t io n b a r
lif e lin e . E a c h a r r o w is a m e s s a g e . T h e r e c t a n g u la r b o x e s o n t h e lif e w h ic h
r e p r e s e n ts t h e d u r a t io n o f e x e c u t io n o f m e s s a g e .
Find more WWW.ThesisScientist.com
Enterprise Java 131
Collaboration diagrams: Collaboration diagrams are also interaction diagrams. Collaboration diagrams convey
the same message as the sequence diagrams. But the collaboration diagrams focus on the object roles instead
of the times at which the messages are sent.
The collaboration diagrams use the decimal sequence numbers as shown in the diagram below to make it clear
which operation is calling which other operation, although it can be harder to see the overall sequence. The top-
level message is numbered 1. The messages at the same level have the same decimal prefix but different suffixes
of 1, 2 etc according to when they occur.
Collaboration Diagram
client object
1.1:makeAnOrder()
message
sequence
number
1.1.1: makeAnOrder() *
1.1.1.2 : hasSufficientDetails()
anOrder : Order anEntry : OrderEntry confirm : Confirmation
1
self-link
1.1.1.1: for each (iteration)
When to use interaction diagrams?
When you want to look at behaviour of several objects within a single use case. If you want to look at a single
object across multiple use cases then use statechart diagram as described below.
State chart diagrams: Objects have behaviour and state. The state of an object is depends on its current activity
or condition. This diagram shows the possible states of the object and the transitions that cause a change in its
state.
S ta te c h a r t D ia g r a m
/ g e t a n ite m
/ a ll ite m s a v a ila b le
C h e c k in g s ta te D is p a tc h in g s ta te
/ s o m e ite m s n o t in s to c k / d e liv e r
/ ite m s re c e iv e d
w a itin g s ta te D e liv e re d s ta te
When to use statechart diagram?
Statechart diagrams are good at describing the behaviour of an object across several use cases. But they are
not good at describing the interaction or collaboration between many objects. Use interaction and/or activity
diagrams in conjunction with a statechart diagram.
Use it only for classes that have complex state changes and behaviour. For example: the User Interface (UI)
control objects, Objects shared by multi-threaded programs etc.
Find more WWW.ThesisScientist.com
132 Enterprise Java
Activity diagram: This is really a fancy flow chart. The activity diagram and statechart diagrams are related in a
sense that statechart diagram focuses on object undergoing a transition process and an activity diagram focuses
on the flow of activities involved in a single transition process.
Activity Diagram
Order placement department dispatch department
swim lane
start
check next item get first item activity
join
/ All item s in stock
dispatch all items
/ som e item s not in stock
W ait for items to arrive in stock
place an order with the supplier
receive the order and enter into stock
In domain modelling it is imperative that the diagram conveys which object (or class) is responsible for each
activity. Activity diagrams can be divided into object swimlanes that determine which object is responsible for
which activity. The swimlanes are quite useful because they combine the activity diagram‟s depiction of logic with
the interaction diagram‟s depiction of responsibility. A single transition comes out of each activity, connecting to
the next activity. A transition may join or fork.
When to use activity diagrams?
The activity and statechart diagrams are generally useful to express complex operations. The great strength of
activity diagrams is that they support and encourage parallel behaviour. The activity and statechart diagrams are
beneficial for workflow modelling with multi-threaded programming.
Component and Deployment diagrams: A component is a code module. Component diagrams are physical
diagrams analogous to a class diagram. The deployment diagrams show the physical configuration of software
and hardware components. The physical hardware is made up of nodes. Each component belongs to a node.
Component and Deployment Diagram
Ratailer J2EE Server Wholesaler J2EE application server
Order Component Dispatch Component Order Component
OrderIF DispathIF OrderIF
Find more WWW.ThesisScientist.com
Enterprise Java 133
Q 108: What is the difference between aggregation and composition? SD DC
A 108:
Aggregation Composition
Aggregation: An association in which one class Composition: An association in which one class belongs to
belongs to another class or a collection. This is a part another class a collection. This is a part of a whole relationship
of a whole relationship where the part can exist where the part cannot exist without the whole. If the whole is
without the whole. For example: A line item is whole deleted then the parts are deleted. For example: An Order is a
a line item is deletedand the products are the parts. If whole and the line items are the parts. If an order is deleted then all
then the products need not be deleted. (no cascade the line items should be deleted as well (i.e. cascade deletes in
delete in database terms) database terms).
Aggregations are not allowed to be circular. In a garbage-collected language like Java, The whole has the
responsibility of preventing the garbage collector to prematurely
collect the part by holding reference to it.
Q 109: What is the difference between a collaboration diagram and a sequence diagram? SD DC
A 109: You can automatically generate one from the other.
Sequence Diagram Collaboration Diagram
The emphasis is on the sequence. The emphasis is on the object roles
Reference: The above section on RUP & UML is based on the book UML Distilled by Martin Fowler and Kendall Scott. If you
would like to have a good understanding of UML & RUP, then this book is recommended.
Enterprise - Struts
Struts is a Web-based user interface framework, which has been around for a few years. It is a matured and proven framework, which
has been used in many J2EE projects. While Struts has been demonstrating its popularity, there is an emerging framework called
JavaServer Faces (JSF) gaining lots of momentum and popularity. Like Struts, JSF provides Web application life cycle management
through a controller servlet, and like Swing, JSF provides a rich component model complete with event handling and component
rendering. So JSF can be considered as a combination of Struts frame work and Java Swing user interface framework. Refer Q19 – Q20
in Emerging Technologies/Frameworks section for JSF.
Q 110: Give an overview of Struts? SFDP
A 110: Struts is a framework with set of cooperating classes, servlets and JSP tags that make up a reusable MVC 2
design.
S T R U T S O v e r v ie w
t
s
e
u
q
e
r
P
T
T
.H
1
C l i e n t
( B R O W S E R )
6 .
H
T
T
Pre
s
p
o
n
s
e
F r o n t
C o n tr o l l e r 2. D i
(S e rvle t ) sp atc h
s t r u t s -
c o n f ig .x m l
Foprward4.
V i e w 5 . g e t th r o u g h T a g
( JS P )
A c ti o n
(c a lls b u s in e s s lo g ic )
SetInstantiate/
3.
M o d e l
( F o r m b e a n s )
Client (Browser): A request from the client browser creates an HTTP request. The Web container will
respond to the request with an HTTP response, which gets displayed on the browser.
Find more WWW.ThesisScientist.com
134 Enterprise Java
Controller (ActionServlet class and Request Processor class): The controller receives the request from
the browser, and makes the decision where to send the request based on the struts-config.xml. Design
pattern: Struts controller uses the command design pattern by calling the Action classes based on the
configuration file struts-config.xml and the RequestProcessor class‟s process() method uses template
method design pattern (Refer Q11 in How would you go about … section) by calling a sequence of methods
like:
processPath(request, response) Æ read the request URI to determine path element.
processMapping(request,response) Æ use the path information to get the action mapping
processRoles(request,respose,mapping) Æ Struts Web application security which provides an
authorization scheme. By default calls request.isUserInRole(). For example allow /addCustomer action if
the role is executive.
<action path=”/addCustomer” roles=”executive”>
processValidate(request,response,form,mapping) Æ calls the vaildate() method of the ActionForm.
processActionCreate(request,response,mapping)Æ gets the name of the action class from the “type”
attribute of the <action> element.
processActionPerform(req,res,action,form,mapping) Æ This method calls the execute method of the
Action class which is where business logic is written.
Business Logic (Action class): The Servlet dispatches the request to Action classes, which act as a thin
wrapper to the business logic (The actual business logic is carried out by either EJB session beans and/or
plain Java classes). The action class helps control the workflow of the application. (Note: The Action class
should only control the workflow and not the business logic of the application). The Action class uses the
Adapter design pattern (Refer Q11 in How would you go about … section).
ActionForm class: Java representation of HTTP input data. They can carry data over from one request to
another, but actually represent the data submitted with the request.
View (JSP): The view is a JSP file. There is no business or flow logic and no state information. The JSP
should just have tags to represent the data on the browser.
ActionServlet class is the controller part of the MVC implementation and is the core of the framework. It
processes user requests, determines what the user is trying to achieve according to the request, pulls data from
the model (if necessary) to be given to the appropriate view, and selects the proper view to respond to the user.
As discussed above ActionServlet class delegates the grunt of the work to the RequestProcessor and Action
classes.
The ActionForm class maintains the state for the Web application. ActionForm is an abstract class, which is
subclassed for every input form model. The struts-config.xml file controls, which HTML form request maps to
which ActionForm.
The Action class is a wrapper around the business logic. The purpose of the Action class is to translate the
HttpServletRequest to the business logic. To use the Action class, subclass and overwrite the execute() method.
The actual business logic should be in a separate package or EJB to allow reuse of business logic in protocol
independent manner (ie the business logic should be used not only by HTTP clients but also by WAP clients,
EJB clients, Applet clients etc).
The ExceptionHandler can be defined to execute when the Action class‟s execute() method throws an Exception.
For example
<global-exceptions>
<exception key="my.key" type="java.io.IOException" handler="my.ExceptionHandler"/>
</global-exceptions>
When an IOException is thrown then it will be handled by the execute() method of the my.ExceptionHandler class.
The struts-config.xml configuration information is translated into ActionMapping, which are put into the
ActionMappings collection.
Further reading is recommended for more detailed understanding.
Find more WWW.ThesisScientist.com
Enterprise Java 135
Q 111: What is a synchronizer token pattern in Struts or how will you protect your Web against multiple submissions?
DC DP
A 111: Web designers often face the situation where a form submission must be protected against duplicate or multiple
submissions. This situation typically occurs when the user clicks on submit button more than once before the
response is sent back or client access a page by returning to the previously book marked page.
The simplest solution that some sites use is that displaying a warning message “Wait for a response after
submitting and do not submit twice.
In the client only strategy, a flag is set on the first submission and from then onwards the submit button is
disabled based on this flag. Useful in some situations but this strategy is coupled to the browser type and
version etc.
For a server-based solution the J2EE pattern synchroniser token pattern can be applied. The basic
idea is to:
Set a token in a session variable on the server side before sending the transactional page back to
the client.
The token is set on the page as a hidden field. On submission of the page first check for the
presence of a valid token by comparing the request parameter in the hidden field to the token stored
in the session. If the token is valid continue processing otherwise take other alternative action. After
testing the token must be reset to null.
The synchroniser token pattern is implemented in Struts. How do we implement the alternate course of action
when the second clicks on submit button will cancel the response from the first click. The thread for the first click
still runs but has no means of sending the response back to the browser. This means the transaction might have
gone through without notifying the user. The user might get the impression that transaction has not gone
through.
Struts support for synchronisation comes in the form of:
ActionServlet.saveToken(HttpRequest) and ActionServlet.isTokenValid(HttpRequest) etc
Q 112: How do you upload a file in Struts? SF
A 112: In JSP page set the code as shown below: CO
<html:form action="upload.do" enctype="multipart/form-data" name="fileForm"
type="FileForm" scope="session">
Please select the file that you would like to upload:
<html:file property="file" />
<html:submit />
</html:form>
In the FormBean set the code as shown below:
public class FileForm extends ActionForm {
private FormFile file;
public void setFile(FormFile file){
this.file = file;
}
public FormFile
getFile(){ return file;
}
}
Q 113: Are Struts action classes thread-safe? SFCI
A 113: No. Struts action classes are not thread-safe. Struts action classes are cached and reused for performance
optimization at the cost of having to implement the action classes in a thread-safe manner.
Find more WWW.ThesisScientist.com
136 Enterprise Java
Q 114: How do you implement internationalization in Struts? SF
A 114: Internationalization is built into Struts framework. In the JSP page set the code as shown below: CO
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html:html
locale="true"> <head>
<title>i18n</title>
</head>
<body>
<h2><bean:message
key="page.title"/></h2> </body>
</html:html>
Now we need to create an application resource file named ApplicationResource.properties.
page.title=Thank you for visiting!
Now in Italian, create an application resource file named ApplicationResource_it.properties.
page.title=Grazie per la vostra visita!
Finally, add reference to the appropriate resource file in the struts-config.xml.
Q 115: What is an action mapping in Struts? How will you extend Struts? SF
A 115: An action mapping is a configuration file (struts-config.xml) entry that, in general, associates an action name
with an action. An action mapping can contain a reference to a form bean that the action can use, and can
additionally define a list of local forwards that is visible only to this action.
How will you extend Struts?
Struts is not only a powerful framework but also very extensible. You can extend Struts in one or more of the
following ways:
PlugIn: Define your own PlugIn class if you want to execute some init() and destroy() methods during the
application startup and shutdown respectively. Some services like loading configuration files, initialising
applications like logging, auditing, etc can be carried out in the init() method.
RequestProcessor: You can create your own RequestProcessor by extending the Struts RequestProcessor.
For example you can override the processRoles(req, res, mapping) in your extended class if you want to query
the LDAP server for the security authorization etc.
ActionServlet: You can extend the ActionServlet class if you want to execute your business logic at the
application startup or shutdown or during individual request processing. You should take this approach only
when the above mentioned approaches are not feasible.
Q 116: What design patterns are used in Struts? DP
A 116: Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command
design pattern (Refer Q11 in How would you go about section) and the action classes use the adapter design
pattern. The process() method of the RequestProcessor uses the template method design pattern (Refer Q11
in How would you go about section). Struts also implement the following J2EE design patterns
Service to Worker (Refer Q25 in Enterprise section).
Dispatcher View (Refer Q25 in Enterprise section).
Composite View (Struts Tiles) (Refer Q25 in Enterprise section)
Front Controller (Refer Q24 in Enterprise section).
View Helper (Refer Q25 in Enterprise section).
Synchronizer Token (Refer Q111 in Enterprise section).
Find more WWW.ThesisScientist.com
Enterprise Java 137
Enterprise - Web and Application servers
Q 117: What application servers, Web servers, LDAP servers, and Database servers have you used?
A 117:
Web Servers Apache, Microsoft IIS, Netscape, Domino etc
Application Servers IBM Websphere, BEA Weblogic, Apache Tomcat, Borland Enterprise Server, Fujitsu
Interstage, JBoss, ATG Dynamo etc
LDAP Servers IPlanet‟s directory server, SiemensDirX etc
Database Servers IBM DB2, Oracle, SQL Server, Sybase, Informix
Q 118: What is the difference between a Web server and an application server? SF
A 118: In general, an application server prepares data for a Web server -- for example, gathering data from databases,
applying relevant business rules, processing security checks, and/or storing the state of a user‟s session. The
term application server may be misleading since the functionality isn‟t limited to applications. Its role is more as
retriever and manager of data and processes used by anything running on a Web server. In the coming age of
Web services, application servers will probably have an even more important role in managing service oriented
components. One of the reasons for using an application server is to improve performance by off-loading tasks
from a Web server. When heavy traffic has more users, more transactions, more data, and more security checks
then more likely a Web server becomes a bottleneck.
Web Server Application Server
Supports HTTP protocol. When a Web server receives an Exposes business logic and dynamic content to a client
HTTP request, it responds with an HTTP response, such through various protocols such as HTTP, TCP/IP, IIOP, JRMP
as sending back an HTML page (static content) or etc.
delegates the dynamic response generation to some other
program such as CGI scripts or Servlets or JSPs in an
application server.
Uses various scalability and fault-tolerance techniques. Uses various scalability and fault-tolerance techniques. In
addition provides resource pooling, component life cycle
management, transaction management, messaging, security
etc.
Q 119: What is a virtual host? SF
A 119: The term virtual host refers to the practice of maintaining more than one server on one machine. They are
differentiated by their host names. You can have name based virtual hosts and IP address based virtual hosts.
For example
A name-based "virtual host" has a unique domain name, but the same IP address. For example,
www.company1.com and www.company2.com can have the same IP address 192.168.0.10 and share the same
Web server. We can configure the Web server as follows:
NameVirtualHost 192.168.0.10
<VirtualHost 192.168.0.10>
ServerName www.company1.com
DocumentRoot /web/company1
</VirtualHost>
<VirtualHost 192.168.0.10>
ServerName www.company2.com
DocumentRoot /web/company2
</VirtualHost>
In this scenario, both www.company1.com and www.company2.com are registered with the standard domain
name service (DNS) registry as having the IP address 192.168.0.10. A user types in the URL
http://www.company1.com/hello.jsp in their browser. The user's computer resolves the name
Find more WWW.ThesisScientist.com
138 Enterprise Java
www.company1.com to the IP address 192.168.0.10. The Web server on the machine that has the IP address
192.168.0.10, so it receives the request. The Web server determines which virtual host to use by matching the
request URL It gets from an HTTP header submitted by the browser with the “ServerName” parameter in the
configuration file shown above.
Name-based virtual hosting is usually easier, since you have to only configure your DNS server to map each
hostname to a single IP address and then configure the Web server to recognize the different hostnames as
discussed in the previous paragraph. Name-based virtual hosting also eases the demand for scarce IP
addresses limited by physical network connections [but modern operation systems supports use of virtual
interfaces, which are also known as IP aliases]. Therefore you should use name-based virtual hosting unless
there is a specific reason to choose IP-based virtual hosting. Some reasons why you might consider using IP-
based virtual hosting:
Name-based virtual hosting cannot be used with SSL based secure servers because of the nature of the
SSL protocol.
Some operating systems and network equipment implement bandwidth management techniques that cannot
differentiate between hosts unless they are on separate IP addresses.
IP based virtual hosts are useful, when you want to manage more than one site (like live, demo, staging etc)
on the same server where hosts inherit the characteristics defined by your main host. But when using SSL
for example, a unique IP address is necessary.
For example in development environment when using the test client and the server on the same machine we can
define the host file as shown below:
UNIX user: /etc/hosts
Windows user: C:WINDOWSSYSTEM32DRIVERSETCHOSTS
localhost
www.company1.com
www.company2.com
[Reference: http://httpd.apache.org/docs/1.3/vhosts/]
Q 120: What is application server clustering? SI
A 120: An application server cluster consists of a number of application servers loosely coupled on a network. The
server cluster or server group is generally distributed over a number of machines or nodes. The important point
to note is that the cluster appears as a single server to its clients.
The goals of application server clustering are:
Scalability: should be able to add new servers on the existing node or add new additional nodes to
enable the server to handle increasing loads without performance degradation, and in a manner
transparent to the end users.
Load balancing: Each server in the cluster should process a fair share of client load, in proportion to its
processing power, to avoid overloading of some and under utilization of other server resources. Load
distribution should remain balanced even as load changes with time.
High availability: Clients should be able to access the server at almost all times. Server usage should be
transparent to hardware and software failures. If a server or node fails, its workload should be moved
over to other servers, automatically as fast as possible and the application should continue to run
uninterrupted. This method provides a fair degree of application system fault-tolerance. After failure, the
entire load should be redistributed equally among working servers of the system.
[Good read: Uncover the hood of J2EE clustering by Wang Yu on http://www.theserverside.com ]
Q 121: Explain Java Management Extensions (JMX)? SF
A 121: JMX framework can improve the manageability of your application by
Find more WWW.ThesisScientist.com
Enterprise Java 139
Monitoring your application for performance problems, critical events, error condition statistics, etc. For
example you can be notified if there is a sudden increase in traffic or sudden drop in performance of your
website.
Making your application more controllable and configurable at runtime by directly exposing application API
and parameters. For example you could switch your database connection to an alternate server. You can
also change the level of debugging and logging within the application without stopping the server.
By interfacing JMX to your hardware, database server and application server, health checks can be
performed of your infrastructure.
Q 122: Explain some of the portability issues between different application servers? SI
A 122: Transaction isolation levels, lazy loading and dirty marker strategies for EJB, class loading visibility etc.
Enterprise - Best practices and performance considerations
Q 123: Give some tips on J2EE application server performance tuning? PI
A 123:
Set the Web container threads, which will be used to process incoming HTTP requests. The minimum
size should be tuned to handle the average load of the container and maximum should be tuned to
handle the peak load. The maximum size should be less than or equal to the number of threads in your
Web server.
When an EJB is called from a servlet or another EJB within the same JVM (i.e. same application server)
then performance can be improved by running EJBs in pass-by-reference mode as oppose to pass-by-
value which is the default mode. Care should be taken to test the application properly before going into
production because some valid applications may not work correctly when pass-by-reference setting is
switched on.
Application servers maintain a pool of JDBC resources so that a new connection does not need to be
created for each transaction. Application servers can also cache your prepared statements to improve
performance. So you can tune the minimum and maximum size of these pools.
Tune your initial heap size for the JVM so that the garbage collector runs at a suitable interval so that it
does not cause any unnecessary overhead. Adjust the value as required to improve performance.
Set the session manager settings appropriately based on following guidelines:
Set the appropriate value for in memory session count.
Reduce the session size.
Don‟t enable session persistence unless required by your application.
Invalidate your sessions when you are finished with them by setting appropriate session timeout.
Calls to EJB from a separate JVM are handled by ORB (Object Request Broker). ORB uses a pool of
threads to handle these requests. The thread pool size should be set appropriately to handle average
and peak loads.
If a servlet or JSP file is called frequently with identical URL parameters then they can be dynamically
cached to improve performance.
Turn the application server tracing off unless required for debugging.
Some application servers support lazy loading and dirty marker strategies with EJB to improve
performance.
Q 124: Explain some of the J2EE best practices? BP
A 124:
Find more WWW.ThesisScientist.com
140 Enterprise Java
Recycle your valuable resources by either pooling or caching. You should create a limited number of
resources and share them from a common pool (e.g. pool of threads, pool of database connections, pool of
objects etc). Caching is simply another type of pooling where instead of pooling a connection or object, you
are pooling remote data (database data) and placing it in the memory (using Hashtable etc).
Avoid embedding business logic in a protocol dependent manner like in JSPs, HttpServlets, Struts
action classes etc. This is because your business logic should be not only executed by your Web clients but
also required to be shared by various GUI clients like Swing based stand alone application, WAP clients etc.
Automate the build process with tools like Ant, CruiseControl, and Maven etc. In an enterprise application
the build process can become quite complex and confusing.
Build test cases first (i.e. Test Driven Development (TDD), refer section Emerging Technologies) using
tools like JUnit. Automate the testing process and integrate it with build process.
Separate HTML code from the Java code: Combining HTML and Java code in the same source code can
make the code less readable. Mixing HTML and scriplet will make the code extremely difficult to read and
maintain. The display or behaviour logic can be implemented as a custom tags by the Java developers and
Web designers can use these Tags as the ordinary XHTML tags.
It is best practice to use multi-threading and stay away from single threaded model of the servlet unless
otherwise there is a compelling reason for it. Shared resources can be synchronized or used in read-only
manner or shared values can be stored in a database table. Single threaded model can adversely affect
performance.
Apply the following JSP best practices:
Place data access logic in JavaBeans: The code within the JavaBean is readily accessible to other
JSPs and Servlets.
Factor shared behaviour out of Custom Tags into common JavaBeans classes: The custom tags
are not used outside JSPs. To avoid duplication of behaviour or business logic, move the logic into
JavaBeans and get the custom tags to utilize the beans.
Choose the right “include” mechanism: What are the differences between static and a dynamic
include? Using includes will improve code reuse and maintenance through modular design. Which one
to use? Refer Q31 in Enterprise section.
Use style sheets (e.g. css), template mechanism (e.g. struts tiles etc) and appropriate comments
(both hidden and output comments).
If you are using EJBs apply the EJB best practices as described in Q82 in Enterprise section.
Use the J2EE standard packaging specification to improve portability across Application Servers.
Use proven frameworks like Struts, Spring, Hibernate, JSF etc.
Apply appropriate proven J2EE design patterns to improve performance and minimise network
communications cost (Session façade pattern, Value Object pattern etc).
Batch database requests to improve performance. For example
Connection con = DriverManager.getConnection(……).
Statement stmt = con.createStatement().
stmt.addBatch(“INSERT INTO Address…………”);
stmt.addBatch(“INSERT INTO Contact…………”);
stmt.addBatch(“INSERT INTO Personal”);
int[] countUpdates = stmt.executeBatch();
Use “PreparedStatements” instead of ordinary “Statements” for repeated reads.
Avoid resource leaks by
Closing all database connections after you have used them.
Clean up objects after you have finished with them especially when an object having a long life cycle
refers to a number of objects with short life cycles (you have the potential for memory leak).
Find more WWW.ThesisScientist.com
Enterprise Java 141
Poor exception handling where the connections do not get closed properly and clean up code that
never gets called. You should put clean up code in a finally {} block.
Handle and propagate exceptions correctly. Decide between checked and unchecked (i.e RunTime
exceptions) exceptions.
Q 125: Explain some of the J2EE best practices to improve performance? BPPI
A 125: In short manage valuable resources wisely and recycle them where possible, minimise network overheads and
serialization cost, and optimise all your database operations.
Manage and recycle your valuable resources by either pooling or caching. You should create a limited
number of resources and share them from a common pool (e.g. pool of threads, pool of database
connections, pool of objects etc). Caching is simply another type of pooling where instead of pooling a
connection or object, you are pooling remote data (database data), and placing it in memory (using
Hashtable etc). Unused stateful session beans must be removed explicitly and appropriate idle timeout
should be set to control stateful session bean life cycle.
Use effective design patterns to minimise network overheads (Session facade, Value Object etc Refer
Q84, Q85 in Enterprise section), use of fast-lane reader pattern for database access (Refer Q86 in
Enterprise section). Caching of retrieved JNDI InitialContexts, factory objects (e.g. EJB homes) etc. using
the service locator design pattern, which reduces expensive JNDI access with the help of caching
strategies.
Minimise serialization costs by marking references (like file handles, database connections etc), which do
not required serialization by declaring them „transient‟ (Refer Q19 in Java section). Use pass-by-reference
where possible as opposed to pass by value.
Set appropriate timeouts: for the HttpSession objects, after which the session expires, set idle timeout for
stateful session beans etc.
Improve the performance of database operations with the following tips:
Database connections should be released when not needed anymore, otherwise there will be potential
resource leakage problems.
Apply least restrictive but valid transaction isolation level.
Use JDBC prepared statements for overall database efficiency and for batching repetitive inserts and
updates. Also batch database requests to improve performance.
When you first establish a connection with a database by default it is in auto-commit mode. For better
performance turn auto-commit off by calling the connection.setAutoCommit(false) method.
Where appropriate (you are loading 100 objects into memory but use only 5 objects) lazy load your
data to avoid loading the whole database into memory using the virtual proxy pattern. Virtual proxy is
an object, which looks like an object but actually contain no fields until when one of its methods is
called does it load the correct object from the database.
Where appropriate eager load your data to avoid frequently accessing the database every time over
the network.
Enterprise – Logging, testing and deployment
Q 126: Give an overview of log4J? SF
A 126: Log4j is a logging framework for Java. Log4J is designed to be fast and flexible. Log4J has 3 main components
which work together to enable developers to log messages:
Loggers [was called Category prior to version 1.2]
Appenders
Layout
Find more WWW.ThesisScientist.com
142 Enterprise Java
Logger: The foremost advantage of any logging API like log4J, apache commons logging etc over plain
System.out.println is its ability to disable certain log statements while allowing others to print unhindered.
Loggers are hierarchical. The root logger exists at the top of the hierarchy. The root logger always exists and it
cannot be retrieved by name. The hierarchical nature of the logger is denoted by “.” notation. For example the
logger “java.util” is the parent of child logger “java.util.Vector” and so on. Loggers may be assigned priorities
such as DEBUG, INFO, WARN, ERROR and FATAL. If a given logger is not assigned a priority, then it inherits
the priority from its closest ancestor. The logging requests are made by invoking one of the following printing
methods of the logger instance: debug(), info(), warn(), error(), fatal().
Appenders and Layouts: In addition to selectively enabling and disabling logging requests based on the logger,
the log4J allows logging requests to multiple destinations. In log4J terms the output destination is an appender.
There are appenders for console, files, remote sockets, JMS, etc. One logger can have more than one
appender. A logging request for a given logger will be forwarded to all the appenders in that logger plus the other
appenders higher in the hierarchy. In addition to the output destination the output format can be categorised as
well. This is accomplished by associating layout with an appender. The layout is responsible for formatting the
logging request according to user‟s settings.
Sample configuration file:
#set the root logger priority to DEBUG and its appender to App1
log4j.rootLogger=DEBUG, App1
#App1 is set to a console appender
log4j.appender.App1=org.apache.log4j.ConsoleAppender
#appender App1 uses a pattern layout
log4j.appender.App1.layout=org.apache.log4j.PatternLayout.
log4j.appender.App1.layout.ConversionPattern=%-4r [%t] %-5p %c %x -%m%n
# Print only messages of priority WARN or above in the package com.myapp
log4j.Logger.com.myapp=WARN
XML configuration for log4j is available, and is usually the best practise.
Q 127: How do you initialize and use Log4J? SFCO
A 127:
public class MyApp {
//Logger is a utility wrapper class to be written with appropriate printing
methods static Logger log = Logger.getLogger (MyApp.class.getName());
public void my method() {
if(log.isDebugEnabled())
log.debug(“This line is reached………………………..” + var1 + “-” + var2);
)
}
}
Q 128: What is the hidden cost of parameter construction when using Log4J? SFPI
A 128:
Do not use in frequently accessed methods or loops: CO
log.debug (“Line number” + intVal + “ is less than ” + String.valueOf(array[i]));
The above construction has a performance cost in frequently accessed methods and loops in constructing
the message parameter, concatenating the String etc regardless of whether the message will be logged or not.
Do use in frequently accessed methods or loops: CO
If (log.isDebugEnabled()) {
log.debug (“Line number” + intVal + “ is less than ” + String.valueOf(array[i]));
}
Find more WWW.ThesisScientist.com
Enterprise Java 143
The above construction will avoid the parameter construction cost by only constructing the message parameter
when you are in debug mode. But it is not a best practise to place log.isDebugEnabled() around all debug code.
Q 129: What is the test phases and cycles? SD
A 129:
Unit tests (e.g. JUnit etc, carried out by developers).
There are two popular approaches to testing server-side classes: mock objects, which test classes by
simulating the server container, and in-container testing, which tests classes running in the actual server
container. If you are using Struts framework, StrutsTestCase for JUnit allows you to use either approach,
with very minimal impact on your actual unit test code.
System tests or functional tests (carried out by business analysts and/or testers).
Integration tests (carried out by business analysts, testers, developers etc).
Regression tests (carried out by business analysts and testers).
Stress volume tests or load tests (carried out by technical staff).
User acceptance tests (UAT – carried out by end users).
Each of the above test phases will be carried out in cycles. Refer Q13 in How would you go about… section for
JUnit, which is an open source unit-testing framework.
Q 130: Brief on deployment environments you are familiar with?
A 130: Differ from project team to project team [Hint] :
Application environments where “ear” files get deployed.
Development box: can have the following instances of environments in the same machine (need not be
clustered).
Development environment Æ used by developers.
System testing environment Æ used by business analysts.
Staging box: can have the following instances of environments in the same machine (preferably clustered
servers with load balancing)
Integration testing environment Æ used for integration testing, user acceptance testing etc.
Pre-prod environment Æ used for user acceptance testing, regression testing, and load testing or stress
volume testing (SVT). [This environment should be exactly same as the production environment].
Production box:
Production environment Æ live site used by actual users.
Data environments (Database)
Note: Separate boxes [not the same boxes as where applications (i.e. ear files) are deployed]
Development box (database).
Used by applications on development and system testing environments. Separate instances can be
created on the same box for separate environments like development and system testing.
Staging Box (database)
Used by applications on integration testing and user acceptance testing environments. Separate
instances can be created on the same box for separate environments.
Production Box (database)
Live data used by actual users of the system.
Find more WWW.ThesisScientist.com
144 Enterprise Java
Enterprise - Personal
Q 131: Tell me about yourself or about some of the recent projects you have worked with? What do you consider your
most significant achievement? Why do you think you are qualified for this position? Why should we hire you and
what kind of contributions will you make?
A 131: [Hint:] Pick your recent projects and give a brief overview of it. Also it is imperative that during your briefing that
you demonstrate how you applied your skills and knowledge in some of the following key areas and fixed any
issues.
Design Concepts: Refer Q02, Q03, Q19, Q20, Q21, Q91, Q98, and Q101.
Design Patterns: Refer Q03, Q24, Q25, Q83, Q84, Q85, Q86, Q87, Q88 and Q111.
Performance issues: Refer Q10, Q16, Q45, Q46, Q97, Q98, Q100, Q123, and Q125.
Memory issues: Refer Q45 and Q93
Multi-threading (Concurrency issues): Refer Q16, Q34, and Q113
Exception Handling: Refer Q76 and Q77
Transactional issues: Refer Q43, Q71, Q72, Q73, Q74, Q75 and Q77.
Security issues: Refer Q23, Q58, and Q81
Scalability issues: Refer Q20, Q21, Q120 and Q122.
Best practices: Refer Q10, Q16, Q39, Q40, Q46, Q82, Q124, and Q125
Refer Q66 – Q72 in Java section for frequently asked non-technical questions.
Q 132: Have you used any load testing tools?
A 132: Rational Robot, JMeter, LoadRunner, etc.
Q 133: What source control systems have you used? SD
A 133: CVS, VSS (Visual Source Safe), Rational clear case etc. Refer Q13 in How would you go about section…. for
CVS.
Q 134: What operating systems are you comfortable with? SD
A 134: NT, Unix, Linux, Solaris etc
Q 135: Which on-line technical resources do you use to resolve any design and/or development issues?
A 135: http://www.theserverside.com, http://www.javaworld.com, http://www-136.ibm.com/developerworks/Java/,
http://java.sun.com/, www.javaperformancetuning.com etc
Enterprise – Software development process
Q 136: What software development processes/principles are you familiar with? SD
A 136: Agile (i.e. lightweight) software development process is gaining popularity and momentum across
organizations.
Agile software development manifesto Æ [Good read: http://www.agilemanifesto.org/principles.html].
Highest priority is to satisfy the customer.
Welcome requirement changes even late in development life cycle.
Business people and developers should work collaboratively.
Form teams with motivated individuals who produce best designs and architectures.
Find more WWW.ThesisScientist.com
Enterprise Java 145
Teams should be pro-active on how to become more effective without becoming complacent.
Quality working software is the primary measure of progress.
Why is iterative development with vertical slicing used in agile development? Your overall software quality
can be improved through iterative development, which provides you with constant feedback.
Traditional Vs Agile approach
Traditional approach
scop
e
1
2
Business Layer
technica
l
mileston
e
milestone
Data Layer Data Layer
project time
Agile (light w eight )approach
Present Presentatio
sc
op
e
ation
1
n Layer 2Layer
tech
nical
Busines
iterat
ion
Business
iteratio
n
s layesr Data L ayer
layesr
Data
Layer
project time
Presentation Layer
Business Layer
Data Layer
Presentation Layer
Business Layer
Data Layer
milestone3iteration3
With the tradional approach, Say for example
w e have a fundamental flaw in the data layer,
if this flaw gets only picked up after the
milestone 3, then there w ill be lot of rew ork to
be done to the business and the presentation
layer. This is the major draw back w ith the
traditional development approach w here there
is no vertical slicing.
As you can see w ith the agileiterative
approach, a vertical slice is built for each
iteration. So any fundamental flaw in design or
coding can be picked up early and rectified.
Even deployment and testing w ill be carried
out in vertical slices.
Several methodologies fit under this agile development methodology banner. All these methodologies share
many characteristics like iterative and incremental development, test driven development, stand up
meetings to improve communication, automatic testing, build and continuous integration of code etc.
Among all the agile methodologies XP is the one which has got the most attention. Different companies use
different flavours of agile methodologies by using different combinations of methodologies.
How does vertical slicing influence customer perception? With the iterative and incremental approach,
customer will be comfortable with the progress of the development as opposed to traditional big bang approach.
TradionalVsAgileperceivedfunctionality
As far as the developer is concerned As far as the developer is concerned
65% of coding has been completed and
Traditional
65% of coding has been completed but
Agile from the customer's view 65% of the
from the customer's view only 20% of
functionality has been completed. So
the functionality has been completed
the customer is happy.
Presentation Layer PresentationLayer
BusinessLayer BusinessLayer
DataLayer DataLayer
EXtreme Programming [XP] Æ simple design, pair programming, unit testing, refactoring, collective code
ownership, coding standards, etc. Refer Q10 in “How would you go about…” section. XP has four key
values: Communication, Feedback, Simplicity and Courage. It then builds up some tried and tested
practices and techniques. XP has a strong emphasis on testing where tests are integrated into continuous
integration and build process, which yields a highly stable platform. XP is designed for smaller teams of 20
– 30 people.
RUP (Rational Unified Process) Æ Model driven architecture, design and development; customizable
frameworks for scalable process; iterative development methodology; Re-use of architecture, code,
component, framework, patterns etc. RUP can be used as an agile process for smaller teams of 20-30
Find more WWW.ThesisScientist.com
146 Enterprise Java
people, or as a heavy weight process for larger teams of 50-100 people. Refer Q103 – Q105 in Enterprise
section.
Feature Driven Development [FDD] Æ Jeff De Luca and long time OO guru Peter Coad developed feature
Driven Development (FDD). Like the other adaptive methodologies, it focuses on short iterations that
deliver tangible functionality. FDD was originally designed for larger project teams of around 50 people. In
FDD's case the iterations are two weeks long. FDD has five processes. The first three are done at the
beginning of the project. The last two are done within each iteration.
Develop an Overall Model
Build a Features List
Plan by Feature
Design by Feature
Build by Feature
The developers come in two kinds: class owners and chief programmers. The chief programmers are the
most experienced developers. They are assigned features to be built. However they don't build them alone.
Instead the chief programmer identifies which classes are involved in implementing the feature and gathers
their class owners together to form a feature team for developing that feature. The chief programmer acts
as the coordinator, lead designer, and mentor while the class owners do much of the coding of the feature.
Test Driven Development [TDD] Æ TDD is an iterative software development process where you first write
the test with the idea that it must fail. Refer Q1 in Emerging Technologies/Frameworks section…
Scrum Æ Scrum divides a project into sprints (aka iterations) of 30 days. Before you begin a sprint you
define the functionality required for that sprint and leave the team to deliver it. But every day the team holds
a short (10 – 15 minute) meeting, called a scrum where the team runs through what it will achieve in the
next day. Some of the questions asked in the scrum meetings are:
What did you do since the last scrum meetings?
Do you have any obstacles?
What will you do before next meeting?
This is very similar to stand-up meetings in XP and iterative development process in RUP.
Enterprise – Key Points
J2EE is a 3-tier (or n-tier) system. Each tier is logically separated and loosely coupled from each other, and may be
distributed.
J2EE applications are developed using MVC architecture, which divides the functionality of displaying and
maintaining of the data to minimise the degree of coupling between enterprise components.
J2EE modules are deployed as ear, war and jar files, which are standard application deployment archive files.
HTTP is a stateless protocol and state can be maintained between client requests using HttpSession, URL rewriting,
hidden fields and cookies. HttpSession is the recommended approach.
Servlets and JSPs are by default multi-threaded, and care should be taken in declaring instance variables and
accessing shared resources. It is possible to have a single threaded model of a servlet or a JSP but this can
adversely affect performance.
Clustering promotes high availability and scalability. The considerations for servlet clustering are:
Objects stored in the session should be serializable.
Design for idempotence.
Avoid using instance and static variables in read and write mode.
Avoid storing values in the ServletContext.
Avoid using java.io.* and use getResourceAsStream() instead.
Find more WWW.ThesisScientist.com
Enterprise Java 147
JSPs have a translation or a compilation process where the JSP engine translates and compiles a JSP file into a
JSP servlet.
JSPs have 4 different scope values: page, request, session and application. JSPs can be included statically, where
all the included JSP pages are compiled into a single servlet during the translation or compilation phase or included
dynamically, where included JSPs are compiled into separate servlets and the content generated by these servlets
are included at runtime in the JSP response.
Avoid scriptlet code in your JSPs and use JavaBeans or custom tags (e.g. Struts tags, JSTL tags, JSF tags etc)
instead.
Databases can run out cursors if the connections are not closed properly. The valuable resources like connections
and statements should be enclosed in a try{} and finally{} block.
Prepared statements offer better performance as opposed to statements, as they are precompiled and reuse the
same execution plan with different arguments. Prepared statements are also more secure because they use bind
variables, which can prevent SQL injection attacks.
JNDI provides a generic interface to LDAP and other directory services like NDS, DNS etc.
In your code always make use of a logical JNDI reference (java:comp/env/ejb/MyBean) as opposed to physical
JNDI reference (ejb/MyBean) because you cannot guarantee that the physical JNDI location you specify in your
code will be available. Your code will break if the physical location is changed.
LDAP servers are typically used in J2EE applications to authenticate and authorise users. LDAP servers are
hierarchical and are optimized for read access, so likely to be faster than database in providing read access.
RMI facilitates object method calls between JVMs. JVMs can be located on separate host machines, still one JVM
can invoke methods belonging to an object residing in another JVM (i.e. address space). RMI uses object
serialization to marshal and unmarshal parameters. The remote objects should extend the UnicastRemoteObject.
To go through a firewall, the RMI protocol can be embedded within the firewall trusted HTTP protocol, which is called
HTTP tunnelling.
EJB (i.e. 2.x) is a remote, distributed multi-tier system, which supports protocols like JRMP, IIOP, and HTTP etc. EJB
components contain business logic and system level supports like security, transaction, instance pooling, multi-
threading, object life-cycles etc are managed by the EJB container and hence simplify the programming effort.
Having said this, there are emerging technologies like:
Hibernate, which is an open source object-to-relational (O/R) mapping framework.
EJB 3.0, which is taking ease of development very seriously and has adjusted its model to offer the plain old
Java objects (i.e. POJOs) based persistence and the new O/R mapping model based on hibernate.
Refer Q14 – Q18 in Emerging technologies / Frameworks section for brief discussion on hibernate and EJB 3.0.
EJB transaction attributes (like Required, Mandatory, RequiresNew, Supports etc) are specified declaratively through
EJB deployment descriptors. Isolation levels are not part of the EJB 2.x specification. So the isolation levels can be
set on the resource manager either explicitly on the Connection or via the application server specific configuration.
A transaction is often described by ACID (Atomic, Consistent, Isolated and Durable) properties. A distributed
transaction is an ACID transaction between two or more independent transactional resources like two separate
databases. A 2-phase commit is an approach for committing a distributed transaction in 2 phases.
EJB 2.x has two types of exceptions:
System exception: is an unchecked exception derived from java.lang.RuntimeException. It is thrown by the
system and is not recoverable.
Application exception: is specific to an application and is thrown because of violation of business rules.
EJB container managed transactions are automatically rolled back when a system exception occurs. This is possible
because the container can intercept system exceptions. However when an application exception occurs, the
container does not intercept and leaves it to the code to roll back using ctx.setRollbackOnly() method.
EJB containers can make use of lazy loading (i.e. not creating an object until it is accessed) and dirty marker (ie
persist only the entity beans that have bean modified) strategies to improve entity beans performance.
Find more WWW.ThesisScientist.com
148 Enterprise Java
Message Oriented Middleware (MOM) is a software infrastructure that asynchronously communicates with other
disparate systems through the production and consumption of messages. Messaging enables loosely coupled
distributed communication. Java Messaging Service (JMS) is a Java API that allows applications to create, send,
receive read messages in a standard way, hence improves portability.
Some of the design decisions you need to make in JMS are message acknowledgement modes, transaction modes,
delivery modes etc, synchronous vs. asynchronous paradigm, message body types, setting appropriate timeouts etc.
XML documents can be processed in your Java/J2EE application either using a SAX parser, which is event driven or
a DOM parser, which creates a tree structure in memory. The other XML related technologies are DTD, XSD, XSL,
XPath, etc and Java and XML based technologies are JAXP, JAXB etc.
There is an impedance mismatch between object and relational technology. Classes represent both data and
behaviour whereas relational database tables just implement data. Inheritance class structure can be mapped to
relational data model in one of the following ways:
Map class hierarchy to single database table.
Map each class to its own table.
Map each concrete class to its own table
Generic meta-data driven approach.
Normalize data in your database for accuracy and denormalize data in your database for performance.
RUP (Rational Unified Process) has 4 phases in the following order Inception, Elaboration, Construction, and
Transition. Agile (i.e. lightweight) software development process is gaining popularity and momentum across
organizations. Several methodologies like XP, RUP, Scrum, FDD, TDD etc fit under this agile development
methodology banner. All these methodologies share many characteristics like iterative and incremental development,
stand-up meetings to improve communication, automatic build, testing and continuous integration etc.
UML is applicable to the object oriented (OO) problem solving. There are different types of UML diagrams like use
case diagrams, class diagrams, sequence diagrams, collaboration diagrams, state chart diagrams, activity diagrams,
component diagrams, deployment diagrams etc.
Class diagrams are vital within OO methods. Class diagrams have the following possible relationships, association,
aggregation, composition, generalization, and dependency.
Struts is an MVC framework. Struts action classes are not thread-safe and care should be taken in declaring instance
variables or accessing other shared resources. JSF is another Web UI framework like Struts gaining popularity and
momentum.
Log4j has three main components: loggers, appenders and layouts. Logger is a utility wrapper class. JUnit is an open
source unit-testing framework.
You can improve the performance of a J2EE application as follows :
Manage and recycle your valuable resources like connections, threads etc by either pooling or caching.
Use effective design patterns like session façade, value object, fast lane reader etc to minimise network
overheads.
Set appropriate timeouts for HttpSession objects.
Use JDBC prepared statements as opposed to statements.
Release database connections in a finally {} block when finished.
Apply least restrictive but valid transaction isolation level.
Batch database requests.
Minimise serialization costs by marking references like file handles, database connections, etc which do not
require serialization by declaring them transient.
Some of the J2EE best practices are:
Recycle your valuable resources by either pooling or caching.
Automate your build process with tools like Ant, CruiseControl, and Maven etc, and continuously integrate your
code into your build process.
Build test cases first using tools like JUnit.
Use standard J2EE packaging to improve portability.
Apply appropriate proven design patterns.
Find more WWW.ThesisScientist.com
Enterprise Java 149
Use proven frameworks like Struts, Spring, Hibernate, JSF, JUnit, Log4J, etc.
Handle and propagate exceptions correctly.
Avoid resource leaks by closing all database connections after you have used them.
The goals of application server clustering are to achieve scalability, load balancing, and high availability.
Java Management Extension (JMX) framework can improve the manageability of your application, for performance
problems, critical events, error conditions etc and perform health checks on your hardware, database server etc.
You can also configure and control your application at runtime.
Finally get familiarised with some of the key Java & J2EE design patterns like:
MVC design pattern: J2EE uses this design pattern or architecture.
Chain of responsibility design pattern: Servlet filters use a slightly modified version of chain of responsibility
design pattern.
Front controller J2EE design pattern: provides a centralized access point for HTTP request handling to
support the integration system services like security, data validation etc. This is a popular J2EE design pattern.
Composite view J2EE design pattern: creates an aggregate view from atomic sub-views.
View helper J2EE design pattern: avoids duplication of code. The helper classes are JavaBeans and custom
tags (e.g. Struts tags, JSF tags, JSTL tags etc).
Service to worker and dispatcher view J2EE design pattern: These two patterns are a combination of front
controller and view helper patterns with a dispatcher component. These two patterns differ in the way they
suggest different division of responsibility among components.
Bridge design pattern: Java Data Base Connectivity (JDBC) uses the bridge design pattern. The JDBC API
provides an abstraction and the JDBC drivers provide the implementation.
Proxy design pattern: RMI & EJB uses the proxy design pattern. A popular design pattern.
Business delegate J2EE design pattern: used to reduce the coupling between the presentation tier and the
business services tier components.
Session façade J2EE design pattern: too many fine-grained method calls between the client and the server
will lead to network overhead and tight coupling. Use a session bean as a façade to provide a coarse-grained
service access layer to clients.
Value object J2EE design pattern: avoid fine-grained method calls by creating a value object, which will help
the client, make a coarse-grained call.
Fast-lane reader J2EE design pattern: access the persistence layer directly using a DAO (Data Access
Object) pattern instead of using entity beans.
Service locator J2EE design pattern: expensive and redundant JNDI lookups can be avoided by caching
and reusing the already looked up service objects.
Recommended reading on J2EE design patterns:
Core J2EE Patterns: Best Practices and Design Strategies, Second Edition (Hardcover) by Deepak Alur, Dan Malks,
John Crupi.
Find more WWW.ThesisScientist.com
150 Enterprise Java
Let us put all together
in the next section
LF DC CI PI SE EH SD
DP SF MI SI TI BP CO
Find more WWW.ThesisScientist.com
How would you go about…? 151
SECTION THREE
How would you go about…?
This section basically assesses your knowledge of how to perform certain tasks
like documenting your project, identifying any potential performance, memory,
transactional, and/or design issues etc.
It also assesses if you have performed any of these tasks before. If you have
not done a particular task, you can demonstrate that you know how to go
about it if the task is assigned to you.
This section also recaps some of the key considerations discussed in the Java
and Enterprise sections. Question numbers are used for cross-referencing
with Java and Enterprise sections.
Q11 & Q13 are discussed in more detail and can be used as a quick reference
guide in a software project. All the other questions excluding Q11 & Q13 can
be read just before an interview.
Find more WWW.ThesisScientist.com
152 How would you go about…?
Q 01: How would you go about documenting your Java/J2EE application?
A 01: To be successful with a Java/J2EE project, proper documentation is vital.
Before embarking on coding get the business requirements down. Build a complete list of requested features,
sample screen shots (if available), use case diagrams, business rules etc as a functional specification
document. This is the phase where business analysts and developers will be asking questions about user
interface requirements, data tier integration requirements, use cases etc. Also prioritize the features based on
the business goals, lead-times and iterations required for implementation.
Prepare a technical specification document based on the functional specification. The technical
specification document should cover:
Purpose of the document: This document will emphasise the customer service functionality …
Overview: This section basically covers background information, scope, any inclusions and/or
exclusions, referenced documents etc.
Basic architecture: discusses or references baseline architecture document. Answers questions like
Will it scale? Can this performance be improved? Is it extendable and/or maintainable? Are there any
security issues? Describe the vertical slices to be used in the early iterations, and the concepts to be
proved by each slice. Etc. For example which MVC [model-1, model-2 etc] paradigms (Refer Q3 in
Enterprise section for MVC) should we use? Should we use Struts, JSF, Spring etc or build our own
framework? Should we use a business delegate (Refer Q83 in Enterprise section for business delegate)
to decouple middle tier with the client tier? Should we use AOP (Aspect Oriented Programming) (Refer
Q3 in Emerging Technologies/Frameworks)? Should we use dependency injection? Should we use
annotations? Do we require internationalization? Etc.
Assumptions, Dependencies, Risks and Issues: highlight all the assumptions, dependencies, risks
and issues. For example list all the risks you can identify.
Design alternatives for each key functional requirement. Also discuss why a particular design
alternative was chosen over the others. This process will encourage developers analyse the possible
design alternatives without having to jump at the obvious solution, which might not always be the best
one.
Processing logic: discuss the processing logic for the client tier, middle tier and the data tier. Where
required add process flow diagrams. Add any pre-process conditions and/or post-process conditions.
(Refer Q9 in Java section for design by contract).
UML diagrams to communicate the design to the fellow developers, solution designers, architects etc.
Usually class diagrams and sequence diagrams are required. The other diagrams may be added for any
special cases like (Refer Q107 in Enterprise section):
State chart diagram: useful to describe behaviour of an object across several usecases.
Activity diagram: useful to express complex operations. Supports and encourages parallel
behaviour. Activity and statechart diagrams are beneficial for workflow modelling with multi
threaded programming.
Collaboration and Sequence diagrams: Use a collaboration or sequence diagram when you
want to look at behaviour of several objects within a single use case. If you want to look at a single
object across multiple use cases then use statechart.
Object diagrams: The Object diagrams show instances instead of classes. They are useful for
explaining some complicated objects in detail such as highlighting recursive relationships etc.
List the package names, class names, database names and table names with a brief description of
their responsibility in a tabular form.
Prepare a coding standards document for the whole team to promote consistency and efficiency. Some
coding practices can degrade performance for example:
Inappropriate use of String class. Use StringBuffer instead of String for compute intensive mutations
(Refer Q17 in Java section).
Find more WWW.ThesisScientist.com
How would you go about…? 153
Code in terms of interface. For example you might decide the LinkedList is the best choice for some
application, but then later decide ArrayList might be a better choice. (Refer Q15 in Java section)
Wrong approach  ArrayList list = new ArrayList();
Right approach  List list = new ArrayList(100)
Set the initial capacity of a collection appropriately (e.g. ArrayList, HashMap etc). (Refer Q15 in Java
section).
To promote consistency define standards for variable names, method names, use of logging, curly
bracket positions etc.
Prepare a code review document and templates for the whole team. Let us look at some of the elements the
code review should cover:
Proper variable declaration: e.g. instance versus static variables, constants etc.
Performance issues: e.g. Use ArrayList, HashMap etc instead of Vector, Hashtable when there is
no thread-safety issue.
Memory issues: e.g. Improper instantiation of objects instead of object reuse and object pooling, not
closing valuable resource in a finally block etc.
Thread-safety issues: e.g. Java API classes like SimpleDateFormat, Calendar, DecimalFormat etc
are not thread safe, declaring variables in JSP is not thread safe, storing state information in Struts
action class or multi-threaded servlet is not thread safe.
Error handling: e.g. Re-throwing exception without nesting original exception, EJB methods not
throwing EJB exception for system exceptions, etc.
Use of coding standards: e.g. not using frameworks, System.out is used instead of log4j etc.
Design issues: No re-use of code, no clear separation of responsibility, invalid use of inheritance to
get method reuse, servlets performing JDBC direct access instead of using DAO (Data Access
Objects) classes, HTML code in Struts action or servlet classes, servlets used as utility classes
rather than as a flow controller etc.
Documentation of code: e.g. No comments, no header files etc
Bugs: e.g. Calling setAutoCommit within container-managed transaction, binary OR “|” used instead
of logical OR “||”, relying on pass-by-reference in EJB remote calls, ResultSet not being closed on
exceptions, EJB methods not throwing EJBException for system exceptions etc (Refer Q76 & Q77 in
Enterprise section)
Prepare additional optional guideline documents as per requirements to be shared by the team. This will
promote consistency and standards. For example:
Guidelines to setting up J2EE development environment.
Guidelines to version control system (CVS, VSS etc).
Guidelines to deployment steps, environment settings, ant targets etc.
Guidelines for the data modelling (any company standards).
Guidelines for error handling (Refer Q34, Q35 in Java section & Q76, Q77 in Enterprise section).
Guidelines for user interface design.
Project overview document.
Software development process document etc.
Some of the above mentioned documents, which are shared by the whole team, can be published in an internal
website like Wiki. Wiki is a piece of server software that allows users to freely create and edit Web page content
using any Web browser.
Q 02: How would you go about designing a Java/J2EE application?
Find more WWW.ThesisScientist.com
154
A 02:
How would you go about…?
Design should be specific to a problem but also should be general enough to address future requirements.
Designing reusable object oriented software involves decomposing the business use cases into relevant objects
and converting objects into classes.
Create a tiered architecture: client tier, business tier and data tier. Each tier can be further logically divided
into layers (Refer Q2, Q3 on Enterprise section). Use MVC (Model View Controller architecture for the J2EE
and Java based GUI applications).
Create a data model: A data model is a detailed specification of data oriented structures. This is different
from the class modelling because it focuses solely on data whereas class models allow you to define both
data and behaviour. Conceptual data models (aka domain models) are used to explore domain concepts
with project stakeholders. Logical data models are used to explore the domain concepts, and their
relationships. Logical data models depict entity types, data attributes end entity relationships (with Entity
Relationship (ER) diagrams). Physical data models are used to design the internal schema of a database
depicting the tables, columns, and the relationships between the tables. Data models can be created by
performing the following tasks:
Identify entity types, attributes and relationships: use entity relationship (E-R) diagrams.
Apply naming conventions (e.g. for tables, attributes, indices, constraints etc): Your organization
should have standards and guidelines applicable to data modelling.
Assign keys: surrogate keys (e.g. assigned by the database like Oracle sequences etc, max()+1,
universally unique identifiers UUIDs, etc), natural keys (e.g. Tax File Numbers, Social Security Numbers
etc), and composite keys.
Normalize to reduce data redundancy and denormalize to improve performance: Normalized data
have the advantage of information being stored in one place only, reducing the possibility of inconsistent
data. Furthermore, highly normalized data are loosely coupled. But normalization comes at a
performance cost because to determine a piece of information you have to join multiple tables whereas
in a denormalized approach the same piece of information can be retrieved from a single row of a table.
Denormalization should be used only when performance testing shows that you need to improve
database access time for some of your tables.
Note: Creating a data model (logical, physical etc) before design model is a matter of preference, but many OO methodologies
are based on creating the data model from the object design model (i.e. you may need to do some work to create an explicit
data model but only after you have a complete OO domain and design model ). In many cases when using ORM tools like
Hibernate, you do not create the data model at all.
Create a design model: A design model is a detailed specification of the objects and relationships between
the objects as well as their behaviour. (Refer Q107 on Enterprise section)
Class diagram: contains the implementation view of the entities in the design model. The design model
also contains core business classes and non-core business classes like persistent storage, security
management, utility classes etc. The class diagrams also describe the structural relationships between
the objects.
Use case realizations: are described in sequence and collaboration diagrams.
Design considerations when decomposing business use cases into relevant classes: designing
reusable and flexible design models requires the following considerations:
Granularity of the objects (fine-grained, coarse-grained etc): Can we minimise the network trip by
passing a coarse-grained value object instead of making 4 network trips with fine-grained parameters?
(Refer Q85 in Enterprise section). Should we use method level (coarse-grained) or code level (fine-
grained) thread synchronization? (Refer Q40 in Java section). Should we use a page level access
security or a fine-grained programmatic security?
Coupling between objects (loosely coupled versus strongly coupled). Should we use business
delegate pattern to loosely couple client and business tier? (Refer Q83 in Enterprise section) or Should
we use dependency injection? (Refer Q09 in Emerging Technologies/Frameworks).
Network overheads for remote objects like EJB, RMI etc: Should we use the session façade, value
object patterns? (Refer Q84 & Q85 in Enterprise section).
Find more WWW.ThesisScientist.com
How would you go about…? 155
Definition of class interfaces and inheritance hierarchy: Should we use an abstract class or an
interface? Is there any common functionality that we can move to the super class (or parent class)?
Should we use interface inheritance with object composition for code reuse as opposed to
implementation inheritance? Etc. (Refer Q8, Q10 in Java section).
Establishing key relationships (aggregation, composition, association etc): Should we use
aggregation or composition? [composition may require cascade delete] (Refer Q107, Q108 in Enterprise
section – under class diagrams). Should we use an “is a” (generalization) relationship or a “has a”
(composition) relationship? (Refer Q7 in Java section).
Applying polymorphism and encapsulation: Should we hide the member variables to improve
integrity and security? (Refer Q8 in Java section). Can we get a polymorphic behaviour so that we can
easily add new classes in the future? (Refer Q8 in Java section).
Applying well-proven design patterns (like Gang of four design patterns, J2EE design patterns, EJB
design patterns etc) help designers to base new designs on prior experience. Design patterns also help
you to choose design alternatives (Refer Q11 in How would you go about…).
Scalability of the system: Vertical scaling is achieved by increasing the number of servers running on
a single machine. Horizontal scaling is achieved by increasing the number of machines in the cluster.
Horizontal scaling is more reliable than the vertical scaling because there are multiple machines
involved in the cluster. In vertical scaling the number of server instances that can be run on one machine
are determined by the CPU usage and the JVM heap memory.
How do we replicate the session state? Should we use stateful session beans or HTTP session?
Should we serialize this object so that it can be replicated?
Internationalization requirements for multi-language support: Should we support other languages?
Should we support multi-byte characters in the database?
Vertical slicing: Getting the reusable and flexible design the first time is impossible. By developing the initial
vertical slice of your design you eliminate any nasty integration issues later in your project. Also get the
design patterns right early on by building the vertical slice. It will give you experience with what does work and
what does not work with Java/J2EE. Once you are happy with the initial vertical slice then you can apply it
across the application. The initial vertical slice should be based on a typical business use case. Refer Q136 in
Enterprise section.
Ensure the system is configurable through property files, xml descriptor files, annotations etc. This will
improve flexibility and maintainability. Avoid hard coding any values. Use a constant class for values, which
rarely change and use property files, xml descriptor files, annotations etc for values, which can change more
frequently (e.g. process flow steps etc) and/or environment related configurations(e.g. server name, server
port, LDAP server location etc).
Design considerations during design, development and deployment phases: designing a fast, secured,
reliable, robust, reusable and flexible system require considerations in the following key areas:
Performance issues (network overheads, quality of the code etc): Can I make a single coarse-grained
network call to my remote object instead of 3 fine-grained calls?
Concurrency issues (multi-threading etc): What if two threads access my object simultaneously will it
corrupt the state of my object?
Transactional issues (ACID properties): What if two clients access the same data simultaneously?
What if one part of the transaction fails, do we rollback the whole transaction? What if the client
resubmits the same transactional page again?
Security issues: Are there any potential security holes for SQL injection or URL injection by hackers?
Memory issues: Is there any potential memory leak problems? Have we allocated enough heap size for
the JVM? Have we got enough perm space allocated since we are using 3
rd
party libraries, which
generate classes dynamically? (e.g. JAXB, XSLT, JasperReports etc)
Scalability issues: Will this application scale vertically and horizontally if the load increases? Should
this object be serializable? Does this object get stored in the HttpSession?
Find more WWW.ThesisScientist.com
156 How would you go about…?
Maintainability, reuse, extensibility etc: How can we make the software reusable, maintainable and
extensible? What design patterns can we use? How often do we have to refactor our code?
Logging and auditing if something goes wrong can we look at the logs to determine the root cause of
the problem?
Object life cycles: Can the objects within the server be created, destroyed, activated or passivated
depending on the memory usage on the server? (e.g. EJB).
Resource pooling: Creating and destroying valuable resources like database connections, threads etc
can be expensive. So if a client is not using a resource can it be returned to a pool to be reused when
other clients connect? What is the optimum pool size?
Caching can we save network trips by storing the data in the server‟s memory? How often do we have
to clear the cache to prevent the in memory data from becoming stale?
Load balancing: Can we redirect the users to a server with the lightest load if the other server is
overloaded?
Transparent fail over: If one server crashes can the clients be routed to another server without any
interruptions?
Clustering: What if the server maintains a state when it crashes? Is this state replicated across the
other servers?
Back-end integration: How do we connect to the databases and/or legacy systems?
Clean shutdown: Can we shut down the server without affecting the clients who are currently using the
system?
Systems management: In the event of a catastrophic system failure who is monitoring the system? Any
alerts or alarms? Should we use JMX? Should we use any performance monitoring tools like Tivoli etc?
Dynamic redeployment: How do we perform the software deployment while the site is running? (Mainly
for mission critical applications 24hrs X 7days).
Portability issues: Can I port this application to a different server 2 years from now?
Q 03: How would you go about identifying performance and/or memory issues in your Java/J2EE application?
A 03: Profiling can be used to identify any performance issues or memory leaks. Profiling can identify what lines of code
the program is spending the most time in? What call or invocation paths are used to reach at these lines? What
kinds of objects are sitting in the heap? Where is the memory leak? Etc.
There are many tools available for the optimization of Java code like JProfiler, Borland OptimizeIt etc.
These tools are very powerful and easy to use. They also produce various reports with graphs.
Optimizeit™ Request Analyzer provides advanced profiling techniques that allow developers to analyse the
performance behaviour of code across J2EE application tiers. Developers can efficiently prioritize the
performance of Web requests, JDBC, JMS, JNDI, JSP, RMI, and EJB so that trouble spots can be
proactively isolated earlier in the development lifecycle.
Thread Debugger tools can be used to identify threading issues like thread starvation and contention issues
that can lead to system crash.
Code coverage tools can assist developers with identifying and removing any dead code from the
applications.
Hprof which comes with JDK for free. Simple tool.
Java –Xprof myClass
java -Xrunhprof:[help]|[<option>=<value>]
java -Xrunhprof:cpu=samples, depth=6, heap=sites
Find more WWW.ThesisScientist.com
How would you go about…? 157
Use operating system process monitors like NT/XP Task Manager on PCs and commands like ps, iostat,
netstat, vmstat, uptime, nfsstat etc on UNIX machines.
Write your own wrapper MemoryLogger and/or PerformanceLogger utility classes with the help of
totalMemory() and freeMemory() methods in the Java Runtime class for memory usage and
System.currentTimeMillis() method for performance. You can place these MemoryLogger and
PerformanceLogger calls strategically in your code. Even better approach than utility classes is using Aspect
Oriented Programming (AOP) for pre and post memory and/or performance recording where you have the
control of activating memory/performance measurement only when needed. (Refer Q3 – Q5 in Emerging
Technologies/Frameworks section).
Q 04: How would you go about minimising memory leaks in your Java/J2EE application?
A 04: Java‟s‟ memory management (i.e. Garbage Collection) prevents lost references and dangling references but it is
still possible to create memory leaks in other ways. If the application runs with memory leaks for a long duration
you will get the error java.lang.OutOfMemoryError.
In Java, typically the memory leak occurs when an object of a longer lifecycle has a reference to the objects
of a short life cycle. This prevents the objects with short life cycle being garbage collected. The developer must
remember to remove the reference to the short-lived objects from the long-lived objects. Objects with the same life
cycle do not cause any problem because the garbage collector is smart enough to deal with the circular references
(Refer Q33 in Java section).
Java collection classes like Hashtable, ArrayList etc maintain references to other objects. So having a long life
cycle ArrayList pointing to many short-life cycle objects can cause memory leaks.
Commonly used singleton design pattern (Refer Q45 in Java section) can cause memory leaks. Singletons
typically have a long life cycle. If a singleton has an ArrayList or a Hashtable then there is a potential for
memory leaks.
Java programming language includes a finalize method that allows an object to free system resources, in
other words, to clean up after itself. However using finalize doesn't guarantee that a class will clean up
resources expediently. A better approach for cleaning up resources involves the finally method and an explicit
close statement. So freeing up the valuable resource in the finalize method or try {} block instead of finally {}
block can cause memory leaks (Refer Q45 in Enterprise section).
Q 05: How would you go about improving performance in your Java/J2EE application?
A 05: The performance bottlenecks can be attributed to one or more of the following:
Performance optimization considerations
¾ Application design.
Application level ¾ Application Server tuning. ¾ Application coding.
¾ Drivers etc.
¾ Database partitioning, tuning etc
Java
infrastructure
System
level
JVM selection
JVM tuning (min & max heap size, perm size etc
Network I/O, Disk I/O etc
Operating System
System configuration, topology etc
Hardware (CPU, memory, I/O etc)
Let us discuss some of the aspects in detail:
Java/J2EE application code related performance bottlenecks:
Refer Q63 in Java section.
Find more WWW.ThesisScientist.com
158 How would you go about…?
Refer Q123, Q125 in Enterprise section.
Java/J2EE design related performance bottlenecks. Application design is one of the most important
considerations for performance. A well-designed application will not only avoid many performance pitfalls but
will also be easier to maintain and modify during the performance-testing phase of the project.
Use proper design patterns to minimise network trips (session facade, value object Refer etc Q83-Q87
in Enterprise section).
Minimise serialization cost by implementing session beans with remote interfaces and entity beans
with local interfaces (applicable to EJB 2.x) or even the session beans can be implemented with local
interfaces sharing the same JVM with the Web tier components. For EJB1.x some EJB containers can
be configured to use pass-by-reference instead of pass-by-value (pass-by-value requires serialization)
Refer Q69, Q82 in Enterprise section.
Use of multi-threading from a thread-pool (say 10 – 50 threads). Using a large number of threads
adversely affects performance by consuming memory through thread stacks and CPU by context
switching.
Database related performance bottlenecks.
Use proper database indexes. Numeric indices are more efficient than character based indices. Minimise
the number of columns in your composite keys. Performing a number of “INSERT” operations is more
efficient when fewer columns are indexed and “SELECT” operations are more efficient when, adequately
indexed based on columns frequently used in your “WHERE” clause. So it is a trade-off between
“SELECT” and “INSERT” operations.
Minimise use of composite keys or use fewer columns in your composite keys.
Partition the database for performance based on the most frequently accessed data and least frequently
accessed data.
Identify and optimise your SQL queries causing performance problems (Refer Q97 in Enterprise
section).
De-normalise your tables where necessary for performance (Refer Q98 in Enterprise section).
Close database connections in your Java code in the finally block to avoid any „open cursors‟ problem
(Refer Q45 in Enterprise section).
Use optimistic concurrency as opposed to pessimistic concurrency where appropriate (Refer Q78 in
Enterprise section).
Application Server, JVM, Operating System, and/or hardware related performance bottlenecks.
Application Server: Configure the application server for optimum performance (Refer Q88, Q123 in
Enterprise section).
Operating System: Check for any other processes clogging up the system resources, maximum
number of processes it can support or connect, optimise operating system etc.
Hardware: Insufficient memory, insufficient CPU, insufficient I/O, limitation of hardware configurations,
network constraints like bandwidth, message rates etc.
Q 06: How would you go about identifying any potential thread-safety issues in your Java/J2EE application?
A 06: When you are writing graphical programs like Swing or Internet programs using servlets or JSPs multi-threading is
a necessity for all but some special and/or trivial programs.
An application program or a process can have multiple threads like multiple processes that can run on one
computer. The multiple threads appear to be doing their work in parallel. When implemented on a multi-processor
machine, they can actually work in parallel.
Find more WWW.ThesisScientist.com
How would you go about…? 159
Unlike processes, threads share the same address space (Refer Q36 in Java section) which means they can read
and write the same variables and data structures. So care should be taken to avoid one thread disturbing the work
of another thread. Let us look at some of the common situations where care should be taken:
Swing components can only be accessed by one thread at a time. A few operations are guaranteed to be
thread safe but the most others are not. Generally the Swing components should be accessed through an
event-dispatching thread. (Refer Q53 in Java section).
A typical Servlet life cycle creates a single instance of each servlet and creates multiple threads to handle the
service() method. The multi-threading aids efficiency but the servlet code must be coded in a thread
safe manner. The shared resources (e.g. instance variable) should be appropriately synchronized or should
only use variables in a read-only manner. (Refer Q16 in Enterprise section).
The declaration of variables in JSP is not thread-safe, because the declared variables end up in the
generated servlet as an instance variable, not within the body of the _jspservice() method. (Refer Q34 in
Enterprise section).
Struts framework action classes are not thread-safe. (Refer Q113 in Enterprise section).
Some Java collection classes like Hashmap, ArrayList etc are not thread-safe. (Refer Q13 in Java section).
Some of the Java core library classes are not thread safe. For e.g. java.util.SimpleDateFormat,
java.util.Locale etc.
Q 07: How would you go about identifying any potential transactional issues in your Java/J2EE application?
A 07:
When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is
treated as a transaction and will be automatically committed immediately after it is executed. The way to
allow two or more statements to be grouped into a transaction is to disable auto-commit mode. (Refer Q43
in Enterprise section). Disabling auto-commit mode can improve performance by minimising number of times
it accesses the database.
A transaction is often described by ACID properties (Atomic, Consistent, Isolated and Durable). A
distributed transaction is an ACID transaction between two or more independent transactional resources
like two separate databases. For a transaction to commit successfully, all of the individual resources must
commit successfully. If any of them are unsuccessful, the transaction must rollback in all of the resources. A
2-phase commit is an approach for committing a distributed transaction in 2 phases. Refer Q73 in
Enterprise section.
Isolation levels provide a degree of control of the effects one transaction can have on another concurrent
transaction. Concurrent effects are determined by the precise ways in which, a particular relational database
handles locks and its drivers may handle these locks differently. Isolation levels are used to overcome
transactional problems like lost update, uncommitted data (aka dirty reads), inconsistent data (aka. phantom
update), and phantom insert. Higher isolation levels can adversely affect performance at the expense of data
accuracy. Refer Q72 in Enterprise section.
Isolation Level Lost Update Uncommitted Data Inconsistent Data Phantom Insert
Read Uncommitted Prevented by DBMS Can happen Can happen Can happen
Read Committed Prevented by DBMS Prevented by DBMS Can happen Can happen
Repeatable Read Prevented by DBMS Prevented by DBMS Prevented by DBMS Can happen
Serializable Prevented by DBMS Prevented by DBMS Prevented by DBMS Prevented by DBMS
Decide between optimistic and pessimistic concurrency control. (Refer Q78 in Enterprise section).
Evaluate a strategy to determine if the data is stale when using strategies to cache data. (Refer Q79 in
Enterprise section).
EJB related transactional issues:
Set the appropriate transactional attributes for the EJBs. (Refer Q71 in Enterprise section).
Set the appropriate isolation level for the EJB. The isolation level should not be any more restrictive than it
has to be. Higher isolation levels can adversely affect performance. (Refer Q72 in Enterprise section).
Isolation levels are application server specific and not part of the standard EJB configuration.
Find more WWW.ThesisScientist.com
160 How would you go about…?
In EJB 2.x, transactions are rolled back by the container when a system exception is thrown. When an
application exception is thrown then the transactions are not rolled back by the container. So the developer
has to roll it back using ctx.setRollbackOnly() call. (Refer Q76, Q77 in Enterprise section).
Detect doomed transactions to avoid performing any unnecessary compute intensive operations. (Refer Q72
in Enterprise section).
Q 08: How would you go about applying the Object Oriented (OO) design concepts in your Java/J2EE application?
A 08:
Question Answer
What are the key A true object oriented language should support the following 3 characteristics:
characteristics of
™ Encapsulation (aka information hiding): implements information hiding and modularityan OO language
like Java? (abstraction).
™ Polymorphism: The same message sent to different objects, results in behaviour that is dependent
on the nature of the object receiving the message.
™ Inheritance: Encourages code reuse and code organisation by defining the new class based on the
existing class.
What is dynamic binding?
Dynamic binding (aka late binding): The dynamic binding is used to implement polymorphism. Objects
could come from local process or from across the network from a remote process. We should be able to
send messages to objects without having to know their types at the time of writing the code. Dynamic
binding provides maximum flexibility at the execution time. Usually dynamic binding or late binding takes
a small performance hit.
Refer Q8 in Java section.
Let us take an example to illustrate dynamic binding through polymorphic behaviour:
Say you have a method in Java
void draw(Shape s) {
s.erase();
// ...
s.draw();
}
The above method will talk to any shape, so it is independent of the specific type of object it is
erasing and drawing. Now let us look at some other program, which is making use of this
draw(Shape s) method:
Circle cir = new Circle();
Square sq = new Square();
draw(cir);
draw(sq);
So the interesting thing is that the method call to draw(Shape s) will cause different code to be
executed. So you send a message to an object even though you don‟t know what specific type it is
and the right thing happens. This is called dynamic binding, which gives you polymorphic behaviour.
How will you ™ Abstract Class: Often in a design, you want the base class to present only an interface for its
decide whether to derived classes. That is, you don‟t want anyone to actually create an object of the base class, only
use an interface or to upcast to it so that its interface can be used. This is accomplished by making that class abstract
an abstract class? using the abstract key word. If anyone tries to make an object of an abstract class, the compiler
prevents them. This is a tool to enforce a particular design.
™ Interface: The interface key word takes the concept of an abstract class one step further by
preventing any function definitions at all. An interface is a very useful and commonly used tool, as it
provides the perfect separation of interface and implementation. In addition, you can combine many
interfaces together, if you wish. (You cannot inherit from more than one regular class or abstract
class.)
Now the design decision…
Find more WWW.ThesisScientist.com
How would you go about…? 161
When to use an Abstract Class: Abstract classes are excellent candidates inside of application
frameworks. Abstract classes let you define some default behaviour and force subclasses to provide
any specific behaviour.
When to use an Interface: If you need to change your design frequently, I prefer using interface to
abstract. For example, the strategy pattern lets you swap new algorithms and processes into your
program without altering the objects that use them. Example: Strategy Design Pattern.
Another justification of interfaces is that they solved the „diamond problem‟ of traditional multiple
inheritance. Java does not support multiple inheritances. Java only supports multiple interface
inheritance. Interface will solve all the ambiguities caused by this „diamond problem‟. Refer Q10 in
Java section.
Interface inheritance vs. Implementation inheritance: Prefer interface inheritance to implementation
inheritance because it promotes the design concept of coding to an interface and reduces
coupling. Interface inheritance can achieve code reuse with the help of object composition. Refer
Q08 in Java section.
Why abstraction is The software you develop should optimally cater for the current requirements and problems and also
important in Object should be flexible enough to easily handle future changes.
Oriented
programming? Abstraction is an important OO concept. The ability for a program to ignore some aspects of the
information that it is manipulating, ie. Ability to focus on the essential. Each object in the system serves
as a model of an abstract "actor" that can perform work, report on and change its state, and
"communicate" with other objects in the system, without revealing how these features are implemented.
Abstraction is the process where ideas are distanced from the concrete implementation of the objects.
The concrete implementation will change but the abstract layer will remain the same.
Let us look at an analogy:
When you drive your car you do not have to be concerned with the exact internal working of your car
(unless you are a mechanic). What you are concerned with is interacting with your car via its interfaces
like steering wheel, brake pedal, accelerator pedal etc. Over the years a car‟s engine has improved a lot
but its basic interface has not changed (ie you still use steering wheel, brake pedal, accelerator pedal etc
to interact with your car). This means that the implementation has changed over the years but the
interface remains the same. Hence the knowledge you have of your car is abstract.
Explain black-box Black-box reuse is when a class uses another class without knowing the internal contents of it. The
reuse and white- black-box reuses are:
box reuse? Should
™ Dependency is the weakest type of black-box reuse.you favour
Inheritance (white- ™ Association is when one object knows about or has a relationship with the other objects.
box reuse) or ™ Aggregation is the whole part relationship where one object contains one or more of the other
aggregation objects.
(black-box reuse)? ™ Composition is a stronger whole part relationship
Refer Q107, Q108 in Enterprise section
White-box reuse is when a class knows internal contents of another class. E.g. inheritance is used to
modify implementation for reusability.
Aggregation (Black-box reuse) Inheritance (White-box reuse)
Defined dynamically or at run time via object Inheritance is defined statically or at compile time.
references. Since only interfaces are used, it has Inheritance allows an easy way to modify
the advantage of maintaining the integrity (ie implementation for reusability.
encapsulation).
Disadvantage of aggregation is that it increases A disadvantage of inheritance is that it breaks
the number of objects and relationships. encapsulation, which implies implementation
dependency. This means when you want to carry
out the redesign the super class (ie parent class)
has to be modified or replaced which is more likely
to affect the subclasses as well. In general it will
affect the whole inheritance hierarchy.
Verdict: So the tendency is to favour aggregation
over inheritance.
Find more WWW.ThesisScientist.com
162 How would you go about…?
What is your Aspect-Oriented Programming (AOP) complements OO programming by allowing developers to
understanding on dynamically modify the static OO model to create a system that can grow to meet new requirements.
Aspect Oriented
Programming AOP allows us to dynamically modify our static model to include the code required to fulfil the secondary
(AOP)? requirements (like auditing, logging, security, exception handling etc) without having to modify the
original static model (in fact, we don't even need to have the original code). Better still, we can often keep
this additional code in a single location rather than having to scatter it across the existing model, as we
would have to if we were using OO on its own. (Refer Q3 –Q5 in Emerging Technologies/Frameworks
section.)
A typical Web application will require a servlet to bind the HTTP request to an object andFor example
then passes to the business handler object to be processed and finally return the response back to the
user. So initially only a minimum amount of code is required. But once you start adding all the other
additional secondary requirements (aka crosscutting concerns) like logging, auditing, security,
exception-handling etc the code will inflate to 2-4 times its original size. This is where AOP can help.
Q 09: How would you go about applying the UML diagrams in your Java/J2EE project?
A 09:
Question Answer
Explain the key Refer Q107 in Enterprise section. Use case has 4 types of relationships:
relationships in the
use case diagrams? Between actor and use case
™ Association: Between actor and use case. May be navigable in both directions according to
the initiator of the communication between the actor and the usecase.
Between use cases
™ Extends: This is an optional extended behaviour of a use case. This behaviour is executed only
under certain conditions such as performing a security check etc.
™ Includes: This specifies that the base use case needs an additional use case to fully describe
its process. It is mainly used to show common functionality that is shared by several use cases.
™ Inheritance (or generalization): Child use case inherits the behaviour of its parent. The child
may override or add to the behaviour of the parent.
U s e c a s e d i a g r a m
a s s o c i a t i o n
*
R e g i s t r a r
E n r o l l i n U n i v e r s i
< < i n c l u d e > >
E n r o l l i n s e m i n a rt y
a s s o c i a t i o n
< < e x t e n d > >
S t u d e n t
p e r f o r m s e c u r i t y i n h e r i t a n c e E n r o l l f a m i l y
i n h e r i t a n c e
c h e c k m e m b e r s
N o t e :
< < e x t e n d > > r e l a t i o n s h i p i s c o n d i t i o n a l . Y o u d o
a s s o c i a t i o n n o t k n o w i f o r w h e n e x t e n d i n g u s e c a s e w i l l b e
i n v o k e d .
< < i n c l u d e > > r e l a t i o n s h i p i s s i m i l a r t o a
p r o c e d u r e c a l l .
i n h e r i t a n c e : e x t e n d s t h e b e h a v i o r o f t h e
I n t e r n a t i o n a l S t u d e n t
p a r e n t u s e c a s e o r a c t o r .
What is the main Refer Q107 in Enterprise section:
difference between the
collaboration diagram Collaboration diagrams convey the same message as sequence diagrams but the collaboration
and the sequence diagrams focus on object roles instead of times in which the messages are sent. The sequence
diagram? diagram is time line driven.
When to use various Refer Q107 in Enterprise section.
UML diagrams?
™ Use case diagrams:
ƒ Determining the user requirements. New use cases often generate new requirements.
ƒ Communicating with clients. The simplicity of the diagram makes use case diagrams a
good way for designers and developers to communicate with clients.
ƒ Generating test cases. Each scenario for the use case may suggest a suite of test
Find more WWW.ThesisScientist.com
How would you go about…? 163
cases.
Class diagrams:
Class diagrams are the backbone of Object Oriented methods. So they are used
frequently.
Class diagrams can have a conceptual perspective and an implementation perspective.
During the analysis draw the conceptual model and during implementation draw the
implementation model.
Interaction diagrams (Sequence and/or Collaboration diagrams):
When you want to look at behaviour of several objects within a single use case. If
you want to look at a single object across multiple use cases then use statechart
diagram as described below.
State chart diagrams:
Statechart diagrams are good at describing the behaviour of an object across several
use cases. But they are not good at describing the interaction or collaboration between
many objects. Use interaction and/or activity diagrams in conjunction with the statechart
diagram to communicate complex operations involving multi-threaded programs etc.
Use it only for classes that have complex state changes and behaviour. For example:
the User Interface (UI) control objects, Objects shared by multi-threaded programs etc.
Activity diagram:
Activity and Statechart diagrams are generally useful to express complex operations.
The great strength of activity diagrams is that they support and encourage parallel
behaviour. An activity and statechart diagrams are beneficial for workflow modelling with
multi threaded programming.
Q 10: How would you go about describing the software development processes you are familiar with?
A 10: In addition to technical questions one should also have a good understanding of the software development
process.
Question Answer
What is the key Refer Q103 – Q105 in Enterprise section
difference between the
waterfall approach and Waterfall approach is sequential in nature. The iterative approach is non-sequential and
the iterative approach incremental. The iterative and incremental approach has been developed based on the following:
to software
development? How to • You can't express all your needs up front. It is usually not feasible to define in detail (that is,
decide which one to before starting full-scale development) the operational capabilities and functional characteristics
use? of the entire system. These usually evolve over time as development progresses.
• Technology changes over time. Some development lifecycle spans a long period of time
during which, given the pace at which technology evolves, significant technological shifts may
occur.
• Complex systems. This means it is difficult to cope with them adequately unless you have an
approach for mastering complexity.
How to decide which one to use?
Waterfall approach is more suitable in the following circumstances:
• Have a small number of unknowns and risks. That is if
• It has a known domain.
• The team is experienced in current process and technology.
• There is no new technology.
• There is a pre-existing architecture baseline.
• Is of short duration (two to three months).
• Is an evolution of an existing system?
The iterative approach is more suitable (Refer Q136 in Enterprise Section)
Have a large number of unknowns and risks. So it pays to design, develop and test a
vertical slice iteratively and then replicate it through other iterations. That is if
Find more WWW.ThesisScientist.com
164 How would you go about…?
• Integrating with new systems.
• New technology and/or architecture.
• The team is fairly keen to adapt to this new process.
• Is of large duration (longer than 3 months).
• Is a new system?
Have you used Extreme Programming (or XP) is a set of values, principles and practices for rapidly developing high-
extreme programming quality software that provides the highest value for the customer in the fastest way possible. XP is a
techniques? Explain? minimal instance of RUP. XP is extreme in the sense that it takes 12 well-known software
development "best practices" to their logical extremes.
The 12 core practices of XP are:
1. The Planning Game: Business and development cooperate to produce the maximum
business value as rapidly as possible. The planning game happens at various scales, but the
basic rules are always the same:
ƒ Business comes up with a list of desired features for the system. Each feature is written
out as a user story (or PowerPoint screen shots with changes highlighted), which gives
the feature a name, and describes in broad strokes what is required. User stories are
typically written on 4x6 cards.
ƒ Development team estimates how much effort each story will take, and how much effort
the team can produce in a given time interval (i.e. the iteration).
ƒ Business then decides which stories to implement in what order, as well as when and how
often to produce production releases of the system.
2. Small releases: Start with the smallest useful feature set. Release early and often, adding a
few features each time.
3. System metaphor: Each project has an organising metaphor, which provides an easy to
remember naming convention.
4. Simple design: Always use the simplest possible design that gets the job done. The
requirements will change tomorrow, so only do what's needed to meet today's requirements.
5. Continuous testing: Before programmers add a feature, they write a test for it. Tests in XP
come in two basic flavours.
ƒ Unit tests are automated tests written by the developers to test functionality as they write
it. Each unit test typically tests only a single class, or a small cluster of classes. Unit tests
are typically written using a unit-testing framework, such as JUnit.
ƒ Customer to test that the overall system is functioning as specified, defines
acceptance tests (aka Functional tests). Acceptance tests typically test the entire
system, or some large chunk of it. When all the acceptance tests pass for a given user
story, that story is considered complete. At the very least, an acceptance test could
consist of a script of user interface actions and expected results that a human can run.
Ideally acceptance tests should be automated using frameworks like Canoo Web test,
Selenium Web test etc.
6. Refactoring: Refactor out any duplicate code generated in a coding session. You can do this
with confidence that you didn't break anything because you have the tests.
7. Pair Programming: All production code is written by two programmers sitting at one machine.
Essentially, all code is reviewed as it is written.
8. Collective code ownership: No single person "owns" a module. Any developer is expected to
be able to work on any part of codebase at any time.
9. Continuous integration: All changes are integrated into codebase at least daily. The tests
have to run 100% both before and after integration. You can use tools like Ant, CruiseControl,
and Maven etc to continuously build and integrate your code.
10. 40-Hour Workweek: Programmers go home on time. In crunch mode, up to one week of
overtime is allowed. But multiple consecutive weeks of overtime are treated as a sign that
something is very wrong with the process.
11. On-site customer: Development team has continuous access to a real live customer or
business owner, that is, someone who will actually be using the system. For commercial
software with lots of customers, a customer proxy (usually the product manager, Business
Find more WWW.ThesisScientist.com
How would you go about…? 165
Analyst etc) is used instead.
12. Coding standards: Everyone codes to the same standards. Ideally, you shouldn't be able to
tell by looking at it, which developer on the team has touched a specific piece of code.
A typical extreme programming project will have:
• All the programmers in a room together usually sitting around a large table.
• Fixed number of iterations where each iteration takes 1-3 weeks. At the beginning of each
iteration get together with the customer.
• Pair-programming.
• Writing test cases first (i.e. TDD).
• Delivery of a functional system at the end of 1-3 week iteration.
Have you used agile Agile (i.e. lightweight) software development process is gaining popularity and momentum
(i.e. Lightweight) across organizations. Several methodologies fit under this agile development methodology banner.
software development All these methodologies share many characteristics like iterative and incremental development,
methodologies? test driven development (i.e. TDD), stand up meetings to improve communication, automatic
testing, build and continuous integration of code etc. Among all the agile methodologies XP is
the one which has got the most attention. Different companies use different flavours of agile
methodologies by using different combinations of methodologies (e.g. primarily XP with other
methodologies like Scrum, FDD, TDD etc). Refer Q136 in Enterprise section.
Q 11: How would you go about applying the design patterns in your Java/J2EE application?
A 11: It is really worth reading books and articles on design patterns. It is sometimes hard to remember the design
patterns, which you do not use regularly. So if you do not know a particular design pattern you can always honestly say
that you have not used it and subsequently suggest that you can explain another design pattern, which you have used
recently or more often. It is always challenging to decide, which design pattern to use when? How do you improve your
design pattern skills? Practice, practice, practice. I have listed some of the design patterns below with scenarios and
examples:
Note: To keep it simple, System.out.println(…) is used. In real practice, use logging frameworks like log4j. Also package constructs are not
shown. In real practice, each class should be stored in their relevant packages like com.items etc. Feel free to try these code samples by typing
them into a Java editor of your choice and run the main class Shopping. Also constants should be declared in a typesafe manner as shown
below:
/**
* use typesafe enum pattern as shown below if you are using below JDK 1.5 or use “enum” if you are using JDK 1.5
*/
public class ItemType {
private final String name;
public static final ItemType Book = new ItemType("book");
public static final ItemType CD = new ItemType("cd");
public static final ItemType COSMETICS = new ItemType("cosmetics");
public static final ItemType CD_IMPORTED = new ItemType("cd_imported");
private ItemType(String name) {this.name =
name;} public String toString() {return name;}
//add compareTo(), readResolve() methods etc as required ...
}

Java Interview Questions Answers Guide Section 2

  • 1.
    Find more WWW.ThesisScientist.com 1 Java/J2EEJob Interview Companion Section 2
  • 2.
    Find more WWW.ThesisScientist.com 3 60Enterprise Java Enterprise - J2EE Q 01: What is J2EE? What are J2EE components and services? SF A 01: J2EE (Java 2 Enterprise Edition) is an environment for developing and deploying enterprise applications. The J2EE platform consists of J2EE components, services, Application Programming Interfaces (APIs) and protocols that provide the functionality for developing multi-tiered and distributed Web based applications. J 2 E E P h y s ic a l T ie r s , C o n ta in e r s , C o m p o n e n ts , S e r v ic e s & A P Is C lie n t C lie n t T ie r F ir e w a ll D M Z F ir e w a ll in te rn e t W e b S e r v e r A p p lic a tio n S e r v e r A p p lic a tio n T ie r (M id d le T ie r ) D a ta b a s e S e r v e r D a ta (E IS ) T ie r ( X ) H T M L , H T T P ( S )X M L ( B r o w s e r ) A p p le t H T T P ( S ) C lie n t A p p lic a tio n (s ta n d a lo n e J a v a p r o g r a m ) W e b J 2 E E A p p lic a tio n S e r v e r S e r v e r W e b C o n ta in e r J D B C H T M L T a g lib r a ry S e rv le ts J S P J avaM a C S S R M I / I I O P JN DI JTA JDBC JMS JavaMail JAF R M I P OI I / I M R J M S E J B C o n ta in e r R M I/IIO P IIO P S e s s io n B e a n s E n tity B e a n s M e s s a g e d riv e n b e a n s R M I / I I O P J N D I JTA JDB C J M S JavaM ail JAF J N D I O th e r S e r v ic e s + A P I s p r o v id e d b y s e r v e r / c o n ta in e r : S e c u r ity (S S L , A C L , J A A S ,X .5 0 9 ) tr a n s a c tio n s , th r e a d in g , R e s o u r c e p o o lin g (E g : C o n n e c tio n p o o lin g ) e tc ,F a u lt T o le r a n c e , L o a d B a la n c in g , c lu s te r in g M o n ito r in g , A u d itin g , L o g g in g e tc m o r e ............... R D B M S il J a v a A p p lic a tio n M e s s a g in g C o r b a S e r v e r D ir e c t o r y S e r v ic e 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: Component type Components Packaged as Applet applets JAR (Java ARchive) Application client Client side Java codes. JAR (Java ARchive) Web component JSP, Servlet WAR (Web ARchive) Enterprise JavaBeans Session beans, Entity beans, Message driven beans JAR (EJB Archive) Enterprise application WAR, JAR, etc EAR (Enterprise ARchive) Resource adapters Resource adapters RAR (Resource Adapter ARchive)
  • 3.
    Find more WWW.ThesisScientist.com Sowhat is the difference between a component and a service you may ask? A component is an application level software unit as shown in the table above. All the J2EE components depend on the container for the system level support like transactions, security, pooling, life cycle management, threading etc. A service is a component
  • 4.
    Find more WWW.ThesisScientist.com EnterpriseJava 61 that can be used remotely through a remote interface either synchronously or asynchronously (e.g. Web service, messaging system, sockets, RPC etc). Containers (Web & EJB containers) are the interface between a J2EE component and the low level platform specific functionality that supports J2EE components. Before a Web, enterprise bean (EJB), or application client component can be executed, it must be assembled into a J2EE module (jar, war, and/or ear) and deployed into its container. A J2EE server provides system level support services such us security, transaction management, JNDI (Java Naming and Directory Interface) lookups, remote access etc. J2EE architecture provides configurable and non- configurable services. The configurable service enables the J2EE components within the same J2EE application to behave differently based on where they are deployed. For example the security settings can be different for the same J2EE application in two different production environments. The non-configurable services include enterprise bean (EJB) and servlet life cycle management, resource pooling etc. Protocols are used for access to Internet services. J2EE platform supports HTTP (HyperText Transfer Protocol), TCP/IP (Transmission Control Protocol / Internet Protocol), RMI (Remote Method Invocation), SOAP (Simple Object Access Protocol) and SSL (Secured Socket Layer) protocol. The J2EE API can be summarised as follows: J2EE technology category API (Application Program Interface) Component model technology Java Servlet, JavaServer Pages(JSP), Enterprise JavaBeans(EJB). JAXP (Java API for XML Processing), JAXR (Java API for XML Registries), SAAJ (SOAP Web services technology with attachment API for Java), JAX-RPC (Java API for XML-based RPC), JAX-WS (Java API for XML-based Web Services). JDBC (Java Database Connectivity), JNDI (Java Naming and Directory Interface), JMS Other (Java Messaging Service), JCA (J2EE Connector Architecture), JTA (Java Transaction API), JavaMail, JAF (JavaBeans Activation Framework – used by JavaMail), JAAS (Java Authentication and Authorization Service), JMX (Java Management eXtenstions). Q 02: Explain the J2EE 3-tier or n-tier architecture? SFDC A 02: This is a very commonly asked question. Be prepared to draw some diagrams on the board. The J2EE platform is a multi-tiered system. A tier is a logical or functional partitioning of a system. 2 – tier system 3 – tier system 2 -T ier (C lien t/S erv er) C lien t M /C 1 C lien t M /C 2 U s e rIn te rfa c e U serInterface /display Logic /display Logic B usiness B usiness logic logic D atabase D atabase logic logic B usiness Logic D atabase logic D ata D atabase When the developers are not disciplined, The display logic, business logic and database logic are muddled up and/or duplicated in a 2- tier client server system. 3-T ier (or n -tier) Client M /C 1 Client M /C 2 U s e rIn te rfa c e U serInterface /display logic /display logic M iddle-tier server B usiness Logic D atabase Logic Data D atabase The advantages of the multi-tier architecture are: Forced separation of user interface logic and business logic. Business logic sits on small number of centralized machines (may be just one). Easy to maintain, to manage, to scale, loosely coupled etc. Each tier is assigned a unique responsibility in a 3-tier system. Each tier is logically separated and loosely coupled from each other, and may be distributed.
  • 5.
    Find more WWW.ThesisScientist.com 62Enterprise Java Client tier represents Web browser, a Java or other application, Applet, WAP phone etc. The client tier makes requests to the Web server who will be serving the request by either returning static content if it is present in the Web server or forwards the request to either Servlet or JSP in the application server for either static or dynamic content. Presentation tier encapsulates the presentation logic required to serve clients. A Servlet or JSP in the presentation tier intercepts client requests, manages logons, sessions, accesses the business services, and finally constructs a response, which gets delivered to client. Business tier provides the business services. This tier contains the business logic and the business data. All the business logic is centralised into this tier as opposed to 2-tier systems where the business logic is scattered between the front end and the backend. The benefit of having a centralised business tier is that same business logic can support different types of clients like browser, WAP, other stand-alone applications etc. Integration tier is responsible for communicating with external resources such as databases, legacy systems, ERP systems, messaging systems like MQSeries etc. The components in this tier use JDBC, JMS, J2EE Connector Architecture (JCA) and some proprietary middleware to access the resource tier. Resource tier is the external resource such as a database, ERP system, Mainframe system etc responsible for storing the data. This tier is also known as Data Tier or EIS (Enterprise Information System) Tier. H i g h L e v e l T i e r s C l i e n t T i e r C l i e n t M i d d l e T i e r W e b S e r v e r A p p lic a t i o n S e r v e r J 2 E E T i e r s L o g i c a l o r F u n c t i o n a l T i e r s C l i e n t T i e r A p p le t s , H T M L , W M L , J a v a S c r ip t , A p p lic a t io n C lie n t s e t c P r e s e n t a t i o n T i e r H T M L , C S S , G I F F ile s e t c ( s t a t ic c o n t e n t ) J S P , S e r v le t s , T a g lib r a r y a n d o t h e r U I e le m e n t s ( C S S , G I F , e t c ) B u s i n e s s T i e r E J B , J a v a C la s s e s , B u s in e s s O b je c t s e t c I n t e g r a t i o n T i e r J M S , J D B C , C o n n e c t o r s ( J C A ) , a n d L e g a c y y l p p a s n r e t t a p E E 2 J D a t a T i e r X M L R D B M S R e s o u r c e T i e r D a t a b a s e s , E R P & C R M s y s t e m s , L e g a c y S y s t e m s e t c Note: On a high level J2EE can be construed as a 3-tier system consisting of Client Tier, Middle Tier (or Application Tier) and Data Tier. But logically or functionally J2EE is a multi-tier (or n-tier) platform. The advantages of a 3-tiered or n-tiered application: 3-tier or multi-tier architectures force separation among presentation logic, business logic and database logic. Let us look at some of the key benefits: Manageability: Each tier can be monitored, tuned and upgraded independently and different people can have clearly defined responsibilities.
  • 6.
    Find more WWW.ThesisScientist.com EnterpriseJava 63 Scalability: More hardware can be added and allows clustering (i.e. horizontal scaling). Maintainability: Changes and upgrades can be performed without affecting other components. Availability: Clustering and load balancing can provide availability. Extensibility: Additional features can be easily added. Q 03: Explain MVC architecture relating to J2EE? DCDP A 03: This is also a very popular interview question. MVC stands for Model-View-Controller architecture. It divides the functionality of displaying and maintaining of the data to minimise the degree of coupling (i.e. promotes loose coupling) between components. J2E E M V C (M odel-V iew -C ontroller) p la y is d to a ta D t g e M odel (E ntitiy B eans (E JB ), S ession B eans (E JB ), P lain Java C lasses ) E ncapsulates business logic and application state . s t a t e c h a n g e V iew (JS P , JavaB eans, S W IN G , C usto m Tag s, etc ) R enders the m odel & has only display logic. S ends user actions to the controller A llow s controller to select a view . U ser A ctio n (eg: subm itting a form , clicking a button etc) V iew selection (eg: selecting the next JS P page to display as a response ) C ontroller (S ervlet, S truts A ction etc) controls application behaviour M aps user actions to m odel. selects view for response . usually one for each functionality. Browser C on troller 1 . R e q u e s t 2S ervlet . i t n s c a re t t i n i d a t re e . s 4 V iew M od el 3. read/update 5 E JB or P lain Java database6 . R espo nse data JS P class C lient Tier M iddleTier (A pplication Tier) D ata Tier N ote: T ypical M V C architecture is show n above. V ariations are possible (eg: M odel 1 vs M odel 2 M V C ) A model represents the core business logic and state. A model commonly maps to data in the database and will also contain core business logic. A View renders the contents of a model. A view accesses the data from the model and adds display logic to present the data. A Controller acts as the glue between a model and a view. A controller delegates the request to the model for application logic and state and also centralises the logic for dispatching the request to the next view based on the input parameters from the client and the application state. A controller also decouples JSP pages and the Servlet by handling the view selection.
  • 7.
    Find more WWW.ThesisScientist.com 64Enterprise Java Q 04: How to package a module, which is, shared by both the WEB and the EJB modules? SF A 04: Package the modules shared by both WEB and EJB modules as dependency jar files. Define the Class-Path: property in the MANIFEST.MF file in the EJB jar and the Web war files to refer to the shared modules. [Refer Q7 in Enterprise section for diagram: J2EE deployment structure]. The MANIFEST.MF files in the EJB jar and WEB war modules should look like: Manifest-Version: 1.0 Created-By: Apache Ant 1.5 Class-Path: myAppsUtil.jar Q 05: Why use design patterns in a J2EE application? DP A 05: They have been proven. Patterns reflect the experience and knowledge of developers who have successfully used these patterns in their own work. It lets you leverage the collective experience of the development community. Example Session facade and value object patterns evolved from performance problems experienced due to multiple network calls to the EJB tier from the WEB tier. Fast lane reader and Data Access Object patterns exist for improving database access performance. The flyweight pattern improves application performance through object reuse (which minimises the overhead such as memory allocation, garbage collection etc). They provide common vocabulary. Patterns provide software designers with a common vocabulary. Ideas can be conveyed to developers using this common vocabulary and format. Example Should we use a Data Access Object (DAO)? How about using a Business Delegate? Should we use Value Objects to reduce network overhead? Etc. Q 06: What is the difference between a Web server and an application server? SF A 06: Web Server Application Server Supports HTTP protocol. When the Web server receives Exposes business logic and dynamic content to the client an HTTP request, it responds with an HTTP response, through various protocols such as HTTP, TCP/IP, IIOP, JRMP etc. such as sending back an HTML page (static content) or delegates the dynamic response generation to some other program such as CGI scripts or Servlets or JSPs in the application server. Uses various scalability and fault-tolerance techniques. Uses various scalability and fault-tolerance techniques. In addition provides resource pooling, component life cycle management, transaction management, messaging, security etc. Provides services for components like Web container for servlet components and EJB container for EJB components. With the advent of XML Web services the line between application servers and Web servers is not clear-cut. By passing XML documents between request and response the Web server can behave like an application server. Q 07: What are ear, war and jar files? What are J2EE Deployment Descriptors? SF A 07: ear, war and jar are standard application deployment archive files. Since they are a standard, any application server (at least in theory) will know how to unpack and deploy them. 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. JAR files can‟t have other JAR files. But EAR and WAR (Web ARchive) files can have JAR files. An EAR file contains all the JARs and WARs belonging to an application. JAR files contain the EJB classes and WAR files contain the Web components (JSPs, static content (HTML, CSS, GIF etc), Servlets etc.). The J2EE application client's class files are also stored in a JAR file. EARs, JARs, and WARs all contain an XML-based deployment descriptor.
  • 8.
    Find more WWW.ThesisScientist.com EnterpriseJava 65 J2EE deployment structure (ear, war, jar ) MyApps.ear MANIFEST.MF Manifest-Version: 1.0 META-INF Craeted-By: Apache Ant application.xml deployment descriptor log4j.jar (3rd party jars) class files, properties files,configuration files etc MyAppsCommon.jar , MyAppsUtil.jar class files, properties files,configuration files etc (shared by both EJB and Web modules) MyAppsEJB.jar MANIFEST.MF class-path: log4j.jar MyAppsCommon.jar MyAppsUtil.jar META-INF ejb-jar.xml deployment descriptor ejb classes , non-ejb class etc MyAppsWeb.war JSP, HTML, CSS, GIF (can have public sub-folders) directory (document root) META-INF WEB-INF private lib directory classes MANIFEST.MF class-path: log4j.jar MyAppsCommon.jar MyAppsUtil.jar web.xml deployment descriptor struts.jar, crimson.jar 3rd party jar files class files Deployment Descriptors A deployment descriptor is an XML based text file with a “.xml” extension that describes a component's deployment settings. A J2EE application and each of its modules has its own deployment descriptor. Pay attention to elements marked in bold in the sample deployment descriptor files shown below. application.xml: is a standard J2EE deployment descriptor, which includes the following structural information: EJB jar modules, WEB war modules, <security-role> etc. Also since EJB jar modules are packaged as jars the same way dependency libraries like log4j.jar, commonUtil.jar etc are packaged, the application.xml descriptor will distinguish between these two jar files by explicitly specifying the EJB jar modules. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE application PUBLIC "-//Sun Microsystems, Inc.//DTD J2EE Application 1.2//EN" "http://java.sun.com/j2ee/dtds/application_1_2.dtd"> <application id="Application_ID"> <display-name>MyApps</display-name> <module id="EjbModule_1"> <ejb>MyAppsEJB.jar</ejb> </module> <module id="WebModule_1"> <web>
  • 9.
    Find more WWW.ThesisScientist.com 66Enterprise Java <web-uri>MyAppsWeb.war</web-uri> <context-root>myAppsWeb</context-root> </web> </module> <security-role id="SecurityRole_1"> <description>Management position</description> <role-name>managger</role-name> </security-role> </application> ejb-jar.xml: is a standard deployment descriptor for an EJB module. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN" "http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd"> <ejb-jar id="ejb-jar_ID"> <display- name>MyAppsEJB</display-name> <enterprise-beans> <session id="ContentService"> <ejb- name>ContentService</ejb-name> <home>ejb.ContentServiceHome</home> <remote>ejb.ContentService</remote> <ejb-class>ejb.ContentServiceBean</ejb-class> <session-type>Stateless</session-type> <transaction-type>Bean</transaction-type> </session> <entity> <ejb-name>Bid</ejb- name> <home>ejb.BidHome</home> <remote>ejb.Bid</remote> <ejb- class>ejb.BidBean</ejb-class> <persistence-type>Container</persistence-type> <prim- key-class>ejb.BidPK</prim-key-class> <reentrant>False</reentrant> <cmp-field><field- name>bid</field-name></cmp-field> <cmp-field><field- name>bidder</field-name></cmp-field> <cmp-field><field- name>bidDate</field-name></cmp-field> <cmp- field><field-name>id</field-name></cmp-field> </entity> </enterprise-beans> <!-- OPTIONAL --> <assembly-descriptor> <!-- OPTIONAL, can be many -- > <security-role> <description> Employee is allowed to ... </description> <role- name>employee</role-name> </security-role> <!-- OPTIONAL. Can be many --> <method-permission> <!-- Define role name in "security-role" -- > <!-- Must be one or more --> <role- name>employee</role-name> <!-- Must be one or more --> <method> <ejb-name>ContentService</ejb- name> <!-- * = all methods --> <method-name>*</method-name> </method> <method> <ejb- name>Bid</ejb-name> <method-name>findByPrimaryKey</method- name> </method> </method-permission>
  • 10.
    Find more WWW.ThesisScientist.com EnterpriseJava 67 <!-- OPTIONAL, can be many. How the container is to manage transactions when calling an EJB's business methods --> <container-transaction> <!-- Can specify many methods at once here --> <method> <ejb-name>Bid</ejb-name> <method-name>*</method-name> </method> <!-- NotSupported|Supports|Required|RequiresNew|Mandatory|Never -- > <trans-attribute>Required</trans-attribute> </container-transaction> </assembly-descriptor> </ejb-jar> web.xml: is a standard deployment descriptor for a WEB module. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app> <display- name>myWebApplication</display-name> <context-param> <param-name>GlobalContext.ClassName</param-name> <param-value>web.GlobalContext</param-value> </context-param> <servlet> <servlet- name>MyWebController</servlet-name> <servlet-class>web.MyWebController</servlet- class> <init-param> <param-name>config</param-name> <param-value>/WEB- INF/config/myConfig.xml</param-value> </init-param> <load-on- startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet- name>MyWebController</servlet-name> <url- pattern>/execute/*</url-pattern> </servlet-mapping> <error-page> <error- code>400</error-code> <location>/WEB- INF/jsp/errors/myError.jsp</location> </error-page> <taglib> <taglib-uri>/WEB-INF/struts- bean.tld</taglib-uri> <taglib-location>/WEB-INF/lib/taglib/struts/struts-bean.tld</taglib- location> </taglib> <security-constraint> <web-resource-collection> <web-resource-name>Employer</web-resource-name> <description></description> <url- pattern>/execute/employ</url-pattern> <http- method>POST</http-method> <http- method>GET</http-method> <http-method>PUT</http- method> </web-resource-collection> <auth-constraint> <description></description> <role-name>advisor</role-name> </auth-constraint> </security-constraint> <login-config> <auth- method>FORM</auth-method> <realm-name>FBA</realm-name> <form-login-config> <form-login-page>/execute/MyLogon</form-login-page>
  • 11.
    Find more WWW.ThesisScientist.com 68Enterprise Java <form-error-page>/execute/MyError</form-error- page> </form-login-config> </login-config> <security-role> <description>Advisor</description> <role-name>advisor</role-name> </security-role> </web-app> Q 08: Explain J2EE class loaders? SF A 08: J2EE application server sample class loader hierarchy is shown below. (Also refer to Q4 in Java section). As per the diagram the J2EE application specific class loaders are children of the “ System –classpath” class loader. When the parent class loader is above the “System –Classpath” class loader in the hierarchy as shown in the diagram (i.e. bootstrap class loader or extensions class loader) then child class loaders implicitly have visibility to the classes loaded by its parents. When a parent class loader is below a “System -Classpath” class loader then the child class loaders will only have visibility into the classes loaded by its parents only if they are explicitly specified in a manifest file (MANIFEST.MF) of the child class loader. Example As per the diagram, if the EJB module MyAppsEJB.jar wants to refer to MyAppsCommon.jar and MyAppsUtil.jar we need to add the following entry in the MyAppsEJB.jar‟s manifest file MANIFEST.MF. class-path: MyAppsCommon.jar MyAppsUtil.jar J 2 E E a p p lic a tio n se rv e r s a m p le cla s s lo a d e r h ie ra rc h y M yA p p s .e a rB oo t st r a p ( JV M ) (rt.jar, i1 8 .ja r) M yA p p s U til.ja r E x te n sio n s(JV M ) (lib/ e xt) M yA p p s C o m m o n .ja r S y stem (JV M ) M yA p p s E JB .ja r (- clas sp ath) M yA p p s W e b .w a r A pp lica tio n c la ss A p p lic atio n clas s E a ch E A R ge ts its lo ad e r (E A R ) loa de r (E A R ) o w n in sta nc e of c la s s loa d e r E JB c la ss lo a de r W A R c la ss W A R clas s lo ad e r loa de r E JB c la ss loa d er W A R c las s lo ad e r All the E JB ja rs in a e ar file s h are th e s am e EJ B cla ss lo a de r. E a ch W A R g e ts its o w n ins ta nc e o f cla ss loa d er. Th e W E B -IN F /lib libra ries a re s pe c ific to e ac h W A R N o te : A p p lic atio n ve n d o r's S e rve r c la s s lo ad e r h ie ra rc h y m ig h t s lig h tly va ry . This is because the application (EAR) class loader loads the MyAppsCommon.jar and MyAppsUtil.jar. The EJB class loader loads the MyAppsEJB.jar, which is the child class loader of the application class loader. The WAR class loader loads the MyAppsWeb.war. Every J2EE application or EAR gets its own instance of the application class loader. This class loader is responsible for loading all the dependency jar files, which are shared by both WEB and EJB modules. For example third party libraries like log4j, utility classes, shared classes or common classes (Exception thrown by an EJB module should be caught by a WEB module) etc. The key difference between the EJB and WAR class loader is that all the EJB jars in the application share the same EJB class loader whereas WAR files get their own class loader. This is because the EJBs have inherent relationship between one another (ie EJB-EJB communication between EJBs in different applications but hosted on the same JVM) but the Web modules do not. Every WAR file should be able to have its own WEB-INF/lib third party libraries and need to be able to load its own version of converted logon.jsp Servlet so each WEB module is isolated in its own class loader.
  • 12.
    Find more WWW.ThesisScientist.com EnterpriseJava 69 So if two different WEB modules want to use two different versions of the same EJB then we need to have two different ear files. As was discussed in the Q4 in Java section the class loaders use a delegation model where the child class loaders delegate the loading up the hierarchy to their parent before trying to load it itself only if the parent can‟t load it. But with regards to WAR class loaders, some application servers provide a setting to turn this behaviour off (DelegationMode=false). This delegation mode is recommended in the Servlet 2.3 specification. As a general rule classes should not be deployed higher in the hierarchy than they are supposed to exist. This is because if you move one class up the hierarchy then you will have to move other classes up the hierarchy as well. This is because classes loaded by the parent class loader can‟t see the classes loaded by its child class loaders (uni-directional bottom-up visibility). Enterprise - Servlet Q 09: What is the difference between CGI and Servlet? SF Q 09: Traditional CGI Java Servlet (Common Gateway Interface) Traditional CGI creates a heavy weight process to handle each Spawns a lightweight Java thread to handle each http http request. N number of copies of the same traditional CGI request. Single copy of a type of servlet but N number of programs is copied into memory to serve N number of threads (thread sizes can be configured in an application requests. server). In the Model 2 MVC architecture, servlets process requests and select JSP views. So servlets act as controller. Servlets intercept the incoming HTTP requests from the client (browser) and then dispatch the request to the business logic model (e.g. EJB, POJO - Plain Old Java Object, JavaBeans etc). Then select the next JSP view for display and deliver the view to client as the presentation (response). It is the best practice to use Web tier UI frameworks like Struts, JavaServer Faces etc, which uses proven and tested design patterns. Q 10: HTTP is a stateless protocol, so how do you maintain state? How do you store user data between requests? SF PIBP A 10: This is a commonly asked question as well. You can retain the state information between different page requests as follows: HTTP Sessions are the recommended approach. A session identifies the requests that originate from the same browser during the period of conversation. All the servlets can share the same session. The JSESSIONID is generated by the server and can be passed to client through cookies, URL re-writing (if cookies are turned off) or built-in SSL mechanism. Care should be taken to minimize size of objects stored in session and objects stored in session should be serializable. In a Java servlet the session can be obtained as follows: CO HttpSession session = request.getSession(); //returns current session or a new session Sessions can be timed out (configured in web.xml) or manually invalidated. Session Management ServerClient (Browser) A new session is created on the Server 1. Initial Request[No session] side with JSESSIONID where JSESSIONID Name Value state can be maintained as xsder12345 Firstname Peter 2. JSESSIONID is passed to client with name/value pair. e xsder12345 LastName Smith the response through onfor thati rm fo cookies or URL re-writing dstate in NIDre IO e sto S S v SE trie ed J re 3. Client uses the JSESSIONID pli sup for subsequent requests
  • 13.
    Find more WWW.ThesisScientist.com 70Enterprise Java Hidden Fields on the pages can maintain state and they are not visible on the browser. The server treats both hidden and non-hidden fields the same way. <INPUT type=”hidden” name=”Firstname” value=”Peter”> <INPUT type=”hidden” name=”Lastname” value=”Smith”> The disadvantage of hidden fields is that they may expose sensitive or private information to others. URL re-writing will append the state information as a query string to the URL. This should not be used to maintain private or sensitive information. Http://MyServer:8080/MyServlet?Firstname=Peter&Lastname=Smith Cookies: A cookie is a piece of text that a Web server can store on a user‟s hard disk. Cookies allow a website to store information on a user‟s machine and later retrieve it. These pieces of information are stored as name-value pairs. The cookie data moves in the following manner: If you type the URL of a website into your browser, your browser sends the request to the Web server. When the browser does this it looks on your machine for a cookie file that URL has set. If it finds it, your browser will send all of the name-value pairs along with the URL. If it does not find a cookie file, it sends no cookie data. The URL‟s Web server receives the cookie data and requests for a page. If name-value pairs are received, the server can use them. If no name-value pairs are received, the server can create a new ID and then sends name-value pairs to your machine in the header for the Web page it sends. Your machine stores the name value pairs on your hard disk. Cookies can be used to determine how many visitors visit your site. It can also determine how many are new versus repeated visitors. The way it does this is by using a database. The first time a visitor arrives, the site creates a new ID in the database and sends the ID as a cookie. The next time the same user comes back, the site can increment a counter associated with that ID in the database and know how many times that visitor returns. The sites can also store user preferences so that site can look different for each visitor. Which mechanism to choose? Session Description mechanism HttpSession ƒ There is no limit on the size of the session data kept. ƒ The performance is good. ƒ This is the preferred way of maintaining state. If we use the HTTP session with the application server‟s persistence mechanism (server converts the session object into BLOB type and stores it in the Database) then the performance will be moderate to poor. When using HttpSession mechanism you need to take care of the following points:Note: ƒ Remove session explicitly when you no longer require it. ƒ Set the session timeout value. ƒ Your application server may serialize session objects after crossing a certain memory limit. This is expensive and affects performance. So decide carefully what you want to store in a session. Hidden fields ƒ There is no limit on size of the session data. ƒ May expose sensitive or private information to others (So not good for sensitive information). ƒ The performance is moderate. URL rewriting ƒ There is a limit on the size of the session data. ƒ Should not be used for sensitive or private information. ƒ The performance is moderate. Cookies ƒ There is a limit for cookie size. ƒ The browser may turn off cookies. ƒ The performance is moderate. The benefit of the cookies is that state information can be stored regardless of which server the client talks to and even if all servers go down. Also, if required, state information can be retained across sessions. Q 11: Explain the life cycle methods of a servlet? SF A 11: The Web container is responsible for managing the servlet‟s life cycle. The Web container creates an instance of the servlet and then the container calls the init() method. At the completion of the init() method the servlet is in
  • 14.
    Find more WWW.ThesisScientist.com EnterpriseJava 71 ready state to service requests from clients. The container calls the servlet‟s service() method for handling each request by spawning a new thread for each request from the Web container‟s thread pool [It is also possible to have a single threaded Servlet, refer Q16 in Enterprise section]. Before destroying the instance the container will call the destroy() method. After destroy() the servlet becomes the potential candidate for garbage collection. Note on servlet reloading: Most servers can reload a servlet after its class file has been modified provided the servlets are deployed to $server_root/servlets directory. This is achieved with the help of a custom class loader. This feature is handy for development and test phases. This is not recommended for production since it can degrade performance because of timestamp comparison for each request to determine if a class file has changed. So for production it is recommended to move the servlet to server‟s class path ie $server_root/classes. When a server dispatches a request to a servlet, the server first checks if the servlet's class file has changed on disk. If it has changed, the server abandons the class loader used to load the old version and creates a new instance of the custom class loader to load the new version. Old servlet versions can stay in memory indefinitely (so the effect is the other classes can still hold references to the old servlet instances, causing odd side effects, but the old versions are not used to handle any more requests. Servlet reloading is not performed for classes found in the server's classpath because the core, primordial class loader, loads those classes. These classes are loaded once and retained in memory even when their class files change. Servlet Life Cycle called once thread 1 : client request thread 2 : client request thread 3 : client request called once ins tan tiate & call init() init() ready to serve requests handle m ultiple servic e() requests and send response. destroy() Q 12: Explain the directory structure of a WEB application? SFSE A 12: Refer Q7 in Enterprise section for diagram: J2EE deployment structure and explanation in this section where MyAppsWeb.war is depicting the Web application directory structure. The directory structure of a Web application consists of two parts: A public resource directory (document root): The document root is where JSP pages, client-side classes and archives, and static Web resources are stored. A private directory called WEB-INF: which contains following files and directories: web.xml : Web application deployment descriptor. *.tld : Tag library descriptor files. classes : A directory that contains server side classes like servlets, utility classes, JavaBeans etc. lib : A directory where JAR (archive files of tag libraries, utility libraries used by the server side classes) files are stored. Note: JSP resources usually reside directly or under subdirectories of the document root, which are directly accessible to the user through the URL. If you want to protect your Web resources then hiding the JSP files behind the WEB-INF directory can protect the JSP files from direct access. Refer Q35 in Enterprise section. Q 13: What is the difference between doGet () and doPost () or GET and POST? SFSE
  • 15.
    Find more WWW.ThesisScientist.com 72Enterprise Java A 13: GET or doGet() POST or doPost() The request parameters are transmitted as a query string The request parameters are passed with the body of the appended to the request. Allows browser bookmarks but not request. appropriate for transmitting private or sensitive information. More secured.http://MyServer/MyServlet?name=paul This is a security risk. GET was originally intended for static resource retrieval. POST was intended for input data submits where the results are expected to change. GET is not appropriate when large amounts of input data are being transferred. Q 14: What are the ServletContext and ServletConfig objects? What are Servlet environment objects? SF A 14: The Servlet Engine uses both objects. ServletConfig The ServletConfig parameters are for a particular Servlet. The parameters are specified in the web.xml (ie deployment descriptor). ServletContext The ServletContext parameters are specified for the entire Web application. The parameters are specified in the web.xml (ie deployment descriptor). Servlet Environment Objects Servlet Engine Web App1 init param for ServletContext web.xml (Deployment Descriptor) snippets the web app <web-app> <context-param> <param-name>GlobalClassName</param-name> <param-value>MyWebAppClass</param-value> </context-param> MyServlet1 config <servlet> <servlet-name>MyServlet1</servlet-name> <servlet-class>com.MyServlet</servlet-class> <init-param> MyServlet2 config <param-name>config</param-name> <param-value>/WEB-INF/config/config.xml</param-value> </init-param> ServletConfig objects init <load-on-startup>1</load-on-startup> </servlet> params set for eachSevlet </web-app> Web App2 ............ ........ Q 15: What is the difference between HttpServlet and GenericServlet? SF A 15: GenericServlet HttpServlet A GenericServlet has a service() method to The HttpServlet extends GenericServlet and adds support for HTTP handle requests. protocol based methods like doGet(), doPost(), doHead() etc. Protocol independent. Protocol dependent. Q 16: How do you make a Servlet thread safe? What do you need to be concerned about with storing data in Servlet instance fields? CIPIBP A 16: As shown in the figure Servlet Life Cycle in Q11 in Enterprise section, a typical (or default) Servlet life cycle creates a single instance of each servlet and creates multiple threads to handle the service() method. The multi- threading aids efficiency but the servlet code must be coded in a thread safe manner. The shared resources (e.g. instance variables, utility or helper objects etc) should be appropriately synchronized or should only use variables in a read-only manner. Having large chunks of code in synchronized blocks in your service methods can adversely affect performance and makes the code more complex.
  • 16.
    Find more WWW.ThesisScientist.com EnterpriseJava 73 Alternatively it is possible to have a single threaded model of a servlet by implementing the marker or null interface javax.servlet.SingleThreadedModel. The container will use one of the following approaches to ensure thread safety: Instance pooling where container maintains a pool of servlets. Sequential processing where new requests will wait while the current request is being processed. Best practice: It is best practice to use multi-threading and stay away from the single threaded model of the servlet unless otherwise there is a compelling reason for it. Shared resources can be synchronized or used in read-only manner or shared values can be stored in a database table. The single threaded model can adversely affect performance. Q 17: What is pre-initialization of a Servlet? LF A 17: By default the container does not initialize the servlets as soon as it starts up. It initializes a servlet when it receives a request for the first time for that servlet. This is called lazy loading. The servlet deployment descriptor (web.xml) defines the <load-on-startup> element, which can be configured to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called pre-loading or pre-initializing a servlet. We can also specify the order in which the servlets are initialized. <load-on-startup>2</load-on-startup> Q 18: What is a RequestDispatcher? What object do you use to forward a request? LFCO A 18: A Servlet can obtain its RequestDispatcher object from its ServletContext. //…inside the doGet() method ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); forwards the control to another servlet or JSP to generate response. This method allows one servlet to do preliminary //processing of a request and another resource to generate the response rd.forward(request,response); or includes the content of the resource such as Servlet, JSP, HTML, Images etc into the calling Servlet‟s response. rd.include(request, response); Q 19: What is the difference between forwarding a request and redirecting a request? LFDC A 19: Both methods redirect you to a new resource like Servlet, JSP etc. But redirecting - sendRedirect() forward Sends a header back to the browser, which contains the name of Forward action takes place within the server without the resource to be redirected to. The browser will make a fresh the knowledge of the browser. request from this header information. Need to provide absolute URL path. Has an overhead of extra remote trip but has the advantage of No extra network trip. being able to refer to any resource on the same or different domain and also allows book marking of the page. Q 20: What are the considerations for servlet clustering? DCSI A 20: The clustering promotes high availability and scalability. The considerations for servlet clustering are: Objects stored in a session should be serializable to support in-memory replication of sessions. Also consider the overhead of serializing very large objects. Test the performance to make sure it is acceptable. Design for idempotence. Failure of a request or impatient users clicking again can result in duplicate requests being submitted. So the Servlets should be able to tolerate duplicate requests. Avoid using instance and static variables in read and write mode because different instances may exist on different JVMs. Any state should be held in an external resource such as a database. Avoid storing values in a ServletContext. A ServletContext is not serializable and also the different instances may exist in different JVMs. Avoid using java.io.* because the files may not exist on all backend machines. Instead use getResourceAsStream().
  • 17.
    Find more WWW.ThesisScientist.com 74Enterprise Java Q 21: If an object is stored in a session and subsequently you change the state of the object, will this state change replicated to all the other distributed sessions in the cluster? DCSI A 21: No. Session replication is the term that is used when your current service state is being replicated across multiple application instances. Session replication occurs when we replicate the information (ie session attributes) that are stored in your HttpSession. The container propagates the changes only when you call the setAttribute(……) method. So mutating the objects in a session and then by-passing the setAttribute(………..) will not replicate the state change. CO Example If you have an ArrayList in the session representing shopping cart objects and if you just call getAttribute() to retrieve the ArrayList and then add or change something without calling the setAttribute(……………) then the container may not know that you have added or changed something in the ArrayList. So the session will not be replicated. Q 22: What is a filter, and how does it work? LFDP A 22: A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses but typically do not themselves create responses. Filters can also be used to transform the response from the Servlet or JSP before sending it back to client. Filters improve reusability by placing recurring tasks in the filter as a reusable unit. A good way to think of Servlet filters is as a chain of steps that a request and response must go through before reaching a Servlet, JSP, or static resource such as an HTML page in a Web application. F i l t e r W e b C o n ta in e r S e r v le t, J S P , H T M L F ilte r 3 Requ est F ilte r 2 Respon se F ilte r 1 C lie n t The filters can be used for caching and compressing content, logging and auditing, image conversions (scaling up or down etc), authenticating incoming requests, XSL transformation of XML content, localization of the request and the response, site hit count etc. The filters are configured through the web.xml file as follows: <web-app> <filter> <filter-name>HitCounterFilter</filter-name> <filter-class>myPkg.HitCounterFilter</filter-class> </filter> <filter-mapping> <filter- name>HitCounterFilter</filter-name> <url- pattern>/usersection/*</url-pattern> </filter-mapping> ... </web-app> The HitCounterFilter will intercept the requests from the URL pattern /usersection followed by any resource name. Design Pattern: Servlet filters use the slightly modified version of the chain of responsibility design pattern. Unlike the classic (only one object in the chain handle the request) chain of responsibility where filters allow multiple objects (filters) in a chain to handle the request. If you want to modify the request or the response in the chain you can use the decorator pattern (Refer Q11 in How would you go about… section). Q 23: Explain declarative security for WEB applications? SE
  • 18.
    Find more WWW.ThesisScientist.com EnterpriseJava 75 A 23: Servlet containers implement declarative security. The administration is done through the deployment descriptor web.xml file. With declarative security the Servlets and JSP pages will be free from any security aware code. You can protect your URLs through web.xml as shown below: web-app> <security- constraint> <web-resource-collection> <web-resource- name>PrivateAndSensitive</web-resource-name> <url-pattern>/private/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>executive</role-name> <role-name>admin</role-name> </auth-constraint> </security-constraint> <!-- form based authorization -- > <login-config> <auth-method>FORM</auth- method> <form-login-config> <form-login-page>/login.jsp</form-login-page> <form-error-page>/error.jsp</form-error-page> </form-login- config> </login- config> </web-app> The user will be prompted for the configured login.jsp when restricted resources are accessed. The container also keeps track of which users have been previously authenticated. Benefits: Very little coding is required and developers can concentrate on the application they are building and system administrators can administer the security settings without or with minimal developer intervention. Let‟s look at a sample programmatic security in a Web module like a servlet: CO User user = new User(); Principal principal = request.getUserPrincipal(); if (request.isUserInRole("boss")) user.setRole(user.BOSS_ROLE); Q 24: Explain the Front Controller design pattern or explain J2EE design patterns? DP A 24: Problem: A J2EE system requires a centralized access point for HTTP request handling to support the integration of system services like security, data validation etc, content retrieval, view management, and dispatching. When the user accesses the view directly without going through a centralized mechanism, two problems may occur: Each view is required to provide its own system services often resulting in duplicate code. View navigation is left to the views. This may result in shared code for view content and view navigation. Distributed control is more difficult to maintain, since changes will often need to be made in numerous places. Solution: Generally you write specific servlets for specific request handling. These servlets are responsible for data validation, error handling, invoking business services and finally forwarding the request to a specific JSP view to display the results to the user. J 2 E E F ro n t C o n tro lle r p a tte rn d is p a tc h e s V ie w c lie n t C lie n t r e q u e s t F r o n tC o n tr o lle r d e le g a te s A p p lic a tio n F lo w C o n tr o lle r C o m m a n d (e g : S T R U T S A c tio n ) in v o k e s < < s e rv le t> > F ro n tC o n tro lle rS e rv le t < < J S P > > F ro n tC o n tro lle rJ S P
  • 19.
    Find more WWW.ThesisScientist.com 76Enterprise Java The Front Controller suggests that we only have one Servlet (instead of having specific Servlet for each specific request) centralising the handling of all the requests and delegating the functions like validation, invoking business services etc to a command or a helper component. For example Struts framework uses the command design pattern to delegate the business services to an action class. Benefits Avoid duplicating the control logic like security check, flow control etc. Apply the common logic, which is shared by multiple requests in the Front controller. Separate the system processing logic from the view processing logic. Provides a controlled and centralized access point for your system. Q 25: Briefly discuss the following patterns Composite view, View helper, Dispatcher view and Service to worker? Or explain J2EE design patterns? DP A 25: Composite View: Creates an aggregate view from atomic sub-views. The Composite View entirely focuses on the View. The View is typically a JSP page, which has the HTML, JSP Tags etc. The JSP display pages mostly have a side bar, header, footer and main content area. These are the sub-views of the view. The sub- views can be either static or dynamic. The best practice is to have these sub-views as separate JSP pages and include them in the whole view. This will enable reuse of JSP sub-views and improves maintainability by having to change them at one place only. Composite View BasicView 1 View Com positeView View Helper: When processing logic is embedded inside the controller or view it causes code duplication in all the pages. This causes maintenance problems, as any change to piece of logic has to be done in all the views. In the view helper pattern the view delegates its processing responsibilities to its helper classes. The helper classes JavaBeans: used to compute and store the presentation data and Custom Tags: used for computation of logic and displaying them iteratively complement each other. Benefits Avoids embedding programming logic in the views and facilitates division of labour between Java developers and Web page designers. Service to Worker and Dispatcher View: These two patterns are a combination of Front Controller and View Helper patterns with a dispatcher component. One of the responsibilities of a Front Controller is choosing a view and dispatching the request to an appropriate view. This behaviour can be partitioned into a separate component known as a dispatcher. But these two patterns differ in the way they suggest different division of responsibility among the components. Service to Worker Dispatcher View Combines the front controller (Refer Q24 in Enterprise This pattern is structurally similar to the service to worker section) and dispatcher, with views and view helpers (refer but the emphasis is on a different usage pattern. This Q25 in Enterprise section) to handle client requests and combines the Front controller and the dispatcher with the dynamically prepares the response. view helpers but ƒ Controllers delegate the content retrieval to the view ƒ Controller does not delegate content retrieval to helpers, which populates the intermediate model view helpers because this activity is deferred to content for the view. view processing. ƒ Dispatcher is responsible for the view management ƒ Dispatcher is responsible for the view management and view navigation. and view navigation.
  • 20.
    Find more WWW.ThesisScientist.com EnterpriseJava 77 Promotes more up-front work by the front controller Relatively has a lightweight front controller and and dispatcher for the authentication, authorization, dispatcher with minimum functionality and most of the content retrieval, validation, view management and work is done by the view. navigation. Q 26: Explain Servlet URL mapping? SF Q 26: S ervlet U R L m ap p in g W ith o u t M ap p in g in w eb .xm l U R L h ttp ://< h o s tn a m e :p o rt> /< w e b a p p n a m e > /se rvle t /< p a th n a m e > /< re s o u rce n a m e > U R L eg h ttp ://lo ca lh o s t:8 0 8 0 /m yA p p s / se rvlet/m y P a th /M yS e rvle t F ile S E R V E R _ H O M E W e b A p p s m yA p p sW E B -IN F C la s s e s m y P a th M y S e rv le t S e rv e r R o o t D o c u m e n t ro o t W ith M ap p in g in w eb .xm l d ep lo ym en t d e scrip to r file W e ca n d e fin e th e s e rvle t m a p p in g in th e w e b .x m l d e p lo y m n e t d e scrip to r file a s sh o w n b e lo w : w e b -a p p > se rvle t> se rvle t-n a m e > M y S e rv le t< /s e rvle t-n a m e > se rvle t-cla ss> m y P a th .M y S e rv le t< /se rv le t-cla s s> /se rv le t> se rvle t-m a p p in g > se rvle t-n a m e > M y S e rv le t< /se rv le t-n a m e > u rl-p a tte rn > m in e /*.d o < /u rl-p a tte rn > /se rv le t-m a p p in g > w e b -a p p > U R L after m ap p in g h ttp ://lo c a lh o s t:8 0 8 0 /m y A p p s /m in e /te s t.d o N o te : W h ich m e a n s e v e ry re q u e st w h ich h a s a p a tte rn o f h ttp ://lo c a lh o s t:8 0 8 0 /m y A p p s / m in e /*.d o w ill b e h a n d le d b y th e m y P a th .M y S e rv le t c la ss . (* d e n o te s w ild ch a ra cte r fo r a n y a lp h a n u m e ric n a m e ). A ls o p o ssib le to m a p M yS e rvle t to th e p a tte rn o f /m in e /* , th e * in d ica te s a n y re so u rce n a m e fo llo w e d b y /m in e . H o w d o w e g et th e w eb ap p n a m e "m yA p p s" T h e w e b a p p n a m e is d e fin e d in th e a p p lic a tio n .x m l d e p lo y m e n t d e scrip to r file . T h e < co n te xt-ro o t > d e n o te s th e w e b a p p n a m e a s sh o w n b e lo w a p p lic a tio n > ............ m o d u le id = "W e b M o d u le _ 1 "> w e b > w e b -u ri> m y A p p sW e b .w a r< /w e b -u ri> c o n te xt-ro o t> m y A p p s < /c o n te xt-ro o t> /w e b > /m o d u le > ........ m o d u le id = "E jb M o d u le _ 1 "> e jb > m yE JB .ja r< /e jb > /m o d u le > ..... < /a p p lica tio n > Enterprise - JSP Q 27: What is a JSP? What is it used for? What do you understand by the term JSP translation phase or compilation phase? SF A 27: JSP (Java ServerPages) is an extension of the Java Servlet technology. JSP is commonly used as the presentation layer for combining HTML and Java code. While Java Servlet technology is capable of generating HTML with out.println(“<html>….. </html>”) statements, where out is a PrintWriter. This process of embedding HTML code with escape characters is cumbersome and hard to maintain. The JSP technology solves this by providing a level of abstraction so that the developer can use custom tags and action elements, which can speed up Web development and are easier to maintain.
  • 21.
    Find more WWW.ThesisScientist.com 78Enterprise Java As shown in the figure the JSPs have a translation or a compilation process where the JSP engine translates and compiles a JSP file into a JSP Servlet. The translated and compiled JSP Servlet moves to the execution phase (run time) where they can handle requests and send response. Unless explicitly compiled ahead of time, JSP files are compiled the first time they are accessed. On large production sites, or in situations involving complicated JSP files, compilation may cause unacceptable delays to users first accessing the JSP page. The JSPs can be compiled ahead of time (ie precompiled) using application server tools/settings or by writing your own script. J S P m o v in g p a rts A p p lic a tio n S e rv e r W e b C o n ta in e r H T T P (Browser)CLIE NT re q u e s t E n g i n e S e r v l e t E n g i n e J S P S e r v e r W e b S e rvle ts J S P s J S P S e rvle ts H T T P re s p o n s e s ta tic d o c s (H T M L ,C S S e tc ) Q 28: Explain the life cycle methods of a JSP? SF A 28: Pre-translated: Before the JSP file has been translated and compiled into the Servlet. Translated: The JSP file has been translated and compiled as a Servlet. Initialized: Prior to handling the requests in the service method the container calls the jspInit() to initialize the Servlet. Called only once per Servlet instance. Servicing: Services the client requests. Container calls this method for each request. Out of service: The Servlet instance is out of service. The container calls the jspDestroy() method. Q 29: What are the main elements of JSP? What are scriplets? What are expressions? SF A 29: There are two types of data in a JSP page. Static part (ie HTML, CSS etc), which gets copied directly to the response by the JSP Engine. Dynamic part, which contains anything that can be translated and compiled by the JSP Engine. There are three types of dynamic elements. (TIP: remember SAD as an abbreviation for Scripting, Action and Directive elements). Scripting Elements: A JSP element that provides embedded Java statements. There are three types of scripting elements. Declaration Element: is the embedded Java declaration statement, which gets inserted at the Servlet class level. <%! Calendar c = Calendar.getInstance(); %> Important: declaring variables via this element is not thread-safe, because this variable ends up in the generated Servlet as an instance variable, not within the body of the _jspservice() method. Ensure their access is either read-only or synchronized. Expression Element: is the embedded Java expression, which gets evaluated by the service method. <%= new Date()>
  • 22.
    Find more WWW.ThesisScientist.com EnterpriseJava 79 Scriptlet Elements: are the embedded Java statements, which get executed as part of the service method. (Note: Not recommended to use Scriptlet elements because they don‟t provide reusability and maintainability. Use custom tags (like JSTL, JSF tags, etc) or beans instead). <% //Java codes String userName=null; userName=request.getParameter("userName"); %> Action Elements: A JSP element that provides information for execution phase. <jsp:useBean id="object_name" class="class_name"/> <jsp:include page="scripts/login.jsp" /> Directive Elements: A JSP element that provides global information for the translation phase. <%@ page import=”java.util.Date” %> <%@ include file=”myJSP” %> <%@ taglib uri=”tagliburi” prefix=”myTag”%> Q 30: What are the different scope values or what are the different scope values for <jsp:usebean> ? SF A 30: Scope Object Comment Page PageContext Available to the handling JSP page only. Request Request Available to the handling JSP page or Servlet and forwarded JSP page or Servlet. Session Session Available to any JSP Page or Servlet within the same session. Application Application Available to all the JSP pages and Servlets within the same Web Application. Q 31: What are the differences between static and a dynamic include? SF DC A 31: Static include <%@ include %> Dynamic include <jsp:include …..> During the translation or compilation phase all the The dynamically included JSP is compiled into a separate Servlet. included JSP pages are compiled into a single Servlet. It is a separate resource, which gets to process the request, and the content generated by this resource is included in the JSP response. No run time performance overhead. Has run time performance overhead. Which one to use: Use “static includes” when a JSP page does not change very often. For the pages, which change frequently, use dynamic includes. JVM has a 64kb limit on the size of the method and the entire JSP page is rendered as a single method. If a JSP page is greater than 64kb, this probably indicates poor implementation. When this method reaches its limit of 64kb it throws an error. This error can be overcome by splitting the JSP files and including them dynamically (i.e. using <jsp:include…….>) because the dynamic includes generate separate JSP Servlet for each included file. Note: The “dynamic include” (jsp:include) has a flush attribute. This attribute indicates whether the buffer should be flushed before including the new content. In JSP 1.1 you will get an error if you omit this attribute. In JSP 1.2 you can omit this attribute because the flush attribute defaults to false. Q 32: What are implicit objects and list them? SF A 32: Implicit objects are the objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated Servlet. The implicit objects are: Implicit object Scope comment request Request request response Page response pageContext Page page environment session Session session application Application same as ServletContext out Page writing to the outputstream config Page same as ServletConfig page Page this page‟s Servlet exception Page exception created on this page.
  • 23.
    Find more WWW.ThesisScientist.com 80Enterprise Java Note: Care should be taken not to name your objects the same name as the implicit objects. If you have your own object with the same name, then the implicit objects take precedence over your own object. Q 33: Explain hidden and output comments? SF A 33: An output comment is a comment that is sent to the client where it is viewable in the browser‟s source. CO <!--This is a comment which is sent to the client--> A hidden comment documents a JSP page but does not get sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. <%-- This comment will not be visible to the client --%> Q 34: Is JSP variable declaration thread safe? CI A 34: No. The declaration of variables in JSP is not thread-safe, because the declared variables end up in the generated Servlet as an instance variable, not within the body of the _jspservice() method. The following declaration is not thread safe: because these are declarations, and will only be evaluated once when the page is loaded <%! int a = 5 %> The following declaration is thread safe: because the variables declared inside the scriplets have the local scope and not shared. <% int a = 5 %> Q 35: Explain JSP URL mapping? What is URL hiding or protecting the JSP page? SFSE A 35: As shown in the figure, the JSP resources usually reside directly or under subdirectories (e.g. myPath) of the document root, which are directly accessible to the user through the URL. If you want to protect your Web resources then hiding the JSP files behind the WEB-INF directory can protect the JSP files, css (cascading style sheets) files, Java Script files, pdf files, image files, html files etc from direct access. The request should be made to a servlet who is responsible for authenticating and authorising the user before returning the protected JSP page or its resources. JSP URL Mapping URL http://<hostnam e:port>/<webapp name><pathname>/<resourcename> URL eg http://localhost:8080/myApps/myPath/myPage.jsp File SERVER_HOMEW ebAppsmyAppsmyPathmyPage.jsp Server Root Unhidden URL Document root Hidden URL myPage.jsp is dircetly accessible through URL myPage.jsp is hidden or protected. cannot be MyApps directly accessed through URL MyApps myPath myPage.jsp W EB-INF W EB-INF myPath myPage.jsp lib lib classes classes
  • 24.
    Find more WWW.ThesisScientist.com EnterpriseJava 81 Q 36: What are custom tags? Explain how to build custom tags? SF A 36: Custom JSP tag is a tag you define. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. So basically it is a reusable and extensible JSP only solution. The pre-built tags also can speed up Web development. CO STEP: 1 Construct the Tag handler class that defines the behaviour. T ag E valu atio n P ro cess start C all setX X X () m eth o ds on the Tag d oS tartTag () evaluate body of the T ag loop doA fterB ody() doE ndT ag() release() S am p le co d e u sin g o n ly d o S atartT ag () pack age m yT agP k g; public class M yT ag extends T agS upport { int attr = null; public int setA ttr(int attr){this .attr = attr} public int getA ttr(){return attr;} public int doS tartT ag() throw s JspE xception { ....... return S K IP _ B O D Y ; } public void release(){.....} } STEP: 2 The Tag library descriptor file (*.tld) maps the XML element names to the tag implementations. The code sample MyTagDesc.tld is shown below: <taglib> <tag> <name>tag1</name> <tagclass>myTagPkg.MyTag</tagclass> <bodycontent>empty</bodycontent> <attribute> <name>attr</name> <required>false</required> <rtexprvalue>false</rtexprvalue> </attribute> </tag> </taglib> STEP: 3 The web.xml deployment descriptor maps the URI to the location of the *.tld (Tag Library Descriptor) file. The code sample web.xml file is shown below: <web-app> <taglib> <taglib-uri>/WEB-INF/MyTagURI</taglib-uri> <taglib- location>/WEB-INF/tags/MyTagDesc.tld</taglib-location> </taglib> </web-app> STEP: 4 The JSP file declares and then uses the tag library as shown below: <%@ taglib uri="/WEB-INF/ MyTagURI" prefix="myTag" %> < myTag:tag1 attr=”abc”></ myTag:tag1> or < myTag:tag1 attr=”abc” />
  • 25.
    Find more WWW.ThesisScientist.com 82Enterprise Java Q 37: What is a TagExtraInfo class? SF A 37: A TagExtraInfo class provides extra information about tag attributes to the JSP container at translation time. Returns information about the scripting variables that the tag makes available to the rest of the JSP page to use. The method used is: VariableInfo[] getVariableInfo(TagData td) Example <html> <myTag:addObjectsToArray name=”myArray” /> <myTag:displayArray name=”myArray” /> </html> Without the use of TagExtraInfo, if you want to manipulate the attribute myArray in the above code in a scriptlet it will not be possible. This is because it does not place the myArray object on the page. You can still use pageContext.getAttribute() but that may not be a cleaner approach because it relies on the page designer to correctly cast to object type. The TagExtraInfo can be used to make items stored in the pageContext via setAttribute() method available to the scriptlet as shown below. <html> <myTag:addObjectsToArray name=”myArray” /> <%-- scriplet code %> <% for(int i=0; i<myArray.length;i++){ html += <LI> + myArray[i] + </LI>; %> </html> Validates the attributes passed to the Tag at translation time. Example It can validate the myArray array list to have not more than 100 objects. The method used is: boolean isValid(TagData data) Q 38: What is the difference between custom JSP tags and JavaBeans? SF A 38: In the context of a JSP page, both accomplish similar goals but the differences are: Custom Tags JavaBeans Can manipulate JSP content. Can‟t manipulate JSP content. Custom tags can simplify the complex operations much Easier to set up. better than the bean can. But require a bit more work to set up. Used only in JSPs in a relatively self-contained manner. Can be used in both Servlets and JSPs. You can define a bean in one Servlet and use them in another Servlet or a JSP page. JavaBeans declaration and usage example: CO <jsp:useBean id="identifier" class="packageName.className"/> <jsp:setProperty name="identifier" property="classField" value="someValue" /> <jsp:getProperty name="identifier" property="classField" /> <%=identifier.getclassField() %> Q 39: Tell me about JSP best practices? BP A 39: Separate HTML code from the Java code: Combining HTML and Java code in the same source code can make the code less readable. Mixing HTML and scriplet will make the code extremely difficult to read and maintain. The display or behaviour logic can be implemented as a custom tags by the Java developers and Web designers can use these Tags as the ordinary XHTML tags. Place data access logic in JavaBeans: The code within the JavaBean is readily accessible to other JSPs and Servlets.
  • 26.
    Find more WWW.ThesisScientist.com EnterpriseJava 83 Factor shared behaviour out of Custom Tags into common JavaBeans classes: The custom tags are not used outside JSPs. To avoid duplication of behaviour or business logic, move the logic into JavaBeans and get the custom tags to utilize the beans. Choose the right “include” mechanism: What are the differences between static and a dynamic include? Using includes will improve code reuse and maintenance through modular design. Which one to use? Refer Q31 in Enterprise section. Use style sheets (e.g. css), template mechanism (e.g. struts tiles etc) and appropriate comments (both hidden and output comments). Q 40: How will you avoid scriptlet code in JSP? BP A 40: Use JavaBeans or Custom Tags instead. Enterprise - JDBC Q 41: What is JDBC? How do you connect to a database? SF A 41: JDBC stands for Java Database Connectivity. It is an API which provides easy connection to a wide range of databases. To connect to a database we need to load the appropriate driver and then request for a connection object. The Class.forName(….) will load the driver and register it with the DriverManager (Refer Q4 in Java section for dynamic class loading). Class.forName(“oracle.jdbc.driver.OracleDriver”); String url = jdbc:oracle:thin:@hostname:1526:myDB; Connection myConnection = DriverManager.getConnection(url, “username”, “password”); The DataSource interface provides an alternative to the DriverManager for making a connection. DataSource makes the code more portable than DriverManager because it work with JNDI and it is created, deployed and managed separately from the application that uses it. If the DataSource location changes, then there is no need to change the code but change the configuration properties in the server. This makes your application code easier to maintain. DataSource allows the use of connection pooling and support for distributed transactions. A DataSource is not only a database but also can be a file or a spreadsheet. A DataSource object can be bound to JNDI and an application can retrieve and use it to make a connection to the database. J2EE application servers provide tools to define your DataSource with a JNDI name. When the server starts it loads all the DataSources into the Application Server‟s JNDI service. DataSource configuration properties are shown below: JNDI Name Æ jdbc/myDataSource URL Æ jdbc:oracle:thin:@hostname:1526:myDB UserName, Password Implementation classname Æ oracle.jdbc.pool.OracleConnectionPoolDataSource Classpath Æ ora_jdbc.jar Connection pooling settings like Æ minimum pool size, maximum pool size, connection timeout, statement cache size etc. Once the DataSource has been set up, then you can get the connection object as follows: Context ctx = new InitialContext(); DataSource ds = (DataSource)ctx.lookup("jdbc/myDataSource"); Connection myConnection = ds.getConnection(“username”,”password”); In a basic implementation a Connection obtained from a DataSource and a DriverManager are identical. But, DataSource is recommended because of its better portability. Design Pattern: JDBC architecture decouples an abstraction from its implementation so that the implementation can vary independent of the abstraction. This is an example of the bridge design pattern . The JDBC API provides the abstraction and the JDBC drivers provide the implementation. New drivers can be plugged-in to the JDBC API without changing the client code. Q 42: What are JDBC Statements? What are different types of statements? How can you create them? SF
  • 27.
    Find more WWW.ThesisScientist.com 84Enterprise Java A 42: A statement object is responsible for sending the SQL statements to the Database. Statement objects are created from the connection object and then executed. CO Statement stmt = myConnection.createStatement(); ResultSet rs = stmt.executeQuery(“SELECT id, name FROM myTable where id =1245”);// to read Or stmt.executeUpdate(“INSERT INTO (field1,field2) values (1,3)”);// to insert/update/delete/create table The types of statements are: Statement (regular statement as shown above) PreparedStatement (more efficient than statement due to pre-compilation of SQL) CallableStatement (to call stored procedures on the database) To use prepared statement: PreparedStatement prepStmt = myConnection.prepareStatement("SELECT id, name FROM myTable where id = ? "); prepStmt.setInt(1, 1245); Callable statements are used for calling stored procedures. CallableStatement calStmt = myConnection.prepareCall("{call PROC_SHOWMYBOOKS}"); ResultSet rs = cs.executeQuery(); Q 43: What is a Transaction? What does setAutoCommit do? TIPI A 43: A transaction is a set of operations that should be completed as a unit. If one operation fails then all the other operations fail as well. For example if you transfer funds between two accounts there will be two operations in the set Withdraw money from one account. Deposit money into other account. These two operations should be completed as a single unit. Otherwise your money will get lost if the withdrawal is successful and the deposit fails. There are four characteristics (ACID properties) for a Transaction. Atomicity Consistency Isolation Durability All the individual The design of the Prevents data being corrupted by concurrent operations should transaction should access by two different sources. It keeps either complete or fail. update the database transactions isolated or separated from each correctly. other until they are finished. Ensures that the database is definitely updated once the Transaction is completed. Transactions maintain data integrity. A transaction has a beginning and an end like everything else in life. The setAutocommit(….) , commit() and rollback() are used for marking the transactions (known as transaction demarcation). When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed immediately after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode: CO try{ Connection myConnection = dataSource.getConnection(); // set autoCommit to false myConnection .setAutoCommit(false); withdrawMoneyFromFirstAccount(.............); //operation 1 depositMoneyIntoSecondAccount(.............); //operation 2 myConnection .commit(); } catch(Exception sqle){ try{ myConnection .rollback(); }catch( Exception e){} } finally{ try{if( conn != null) {conn.close();}} catch( Exception e) {} }
  • 28.
    Find more WWW.ThesisScientist.com EnterpriseJava 85 The above code ensures that both operation 1 and operation 2 succeed or fail as an atomic unit and consequently leaves the database in a consistent state. Also turning auto-commit off will provide better performance. Q 44: What is the difference between JDBC-1.0 and JDBC-2.0? What are Scrollable ResultSets, Updateable ResultSets, RowSets, and Batch updates? SF A 44: JDBC2.0 has the following additional features or functionality: JDBC 1.0 JDBC 2.0 With JDBC-1.0 the With JDBC 2.0 ResultSets are updateable and also you can move forward and backward. ResultSet functionality was limited. There was no Example This example creates an updateable and scroll-sensitive ResultSet support for updates of any kind and scrolling through Statement stmt = myConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, the ResultSets was ResultSet.CONCUR_UPDATEABLE) forward only (no going back) With JDBC-1.0 the With JDBC-2.0 statement objects can be grouped into a batch and executed at once. We call statement objects submits addBatch() multiple times to create our batch and then we call executeBatch() to send the SQL updates to the database statements off to database to be executed as a batch (this minimises the network overhead). individually within same or separate transactions. Example This is very inefficient large amounts of data Statement stmt = myConnection.createStatement(); need to be updated. stmt.addBatch(“INSERT INTO myTable1 VALUES (1,”ABC”)”); stmt.addBatch(“INSERT INTO myTable1 VALUES (2,”DEF”)”); stmt.addBatch(“INSERT INTO myTable1 VALUES (3,”XYZ”)”); … int[] countInserts = stmt.executeBatch(); - The JDBC-2.0 optional package provides a RowSet interface, which extends the ResultSet. One of the implementations of the RowSet is the CachedRowSet, which can be considered as a disconnected ResultSet. Q 45: How to avoid the “running out of cursors” problem? DCPIMI A 45: A database can run out of cursors if the connection is not closed properly or the DBA has not allocated enough cursors. In a Java code it is essential that we close all the valuable resources in a try{} and finally{} block. The finally{} block is always executed even if there is an exception thrown from the catch {} block. So the resources like connections and statements should be closed in a finally {} block. CO Try{} Finally {} blocks to close Exceptions Wrong Approach - Right Approach - Connections and statements will not be closed if there public void executeSQL() throws SQLException{ is an exception: try{ Connection con = DriverManager.getConnection(........); public void executeSQL() throws SQLException{ ..... Statement stmt = con.createStatement(); Connection con = DriverManager.getConnection(........); .... //line 20 where exception is thrown ..... ResultSet rs = stmt.executeQuery("SELECT * from myTable"); Statement stmt = con.createStatement(); ..... .... } //line 20 where exception is thrown finally{ ResultSet rs = stmt.executeQuery("SELECT * from myTable"); try { ..... if(rs != null) rs.close(); rs.close(); if(stmt != null) stmt.close(); stmt.close(); if(con != null) con.close(); con.close(); } } catch(Exception e){} } Note: if an exception is thrown at line 20 then the } close() statements are never reached. Note: if an exception is thrown at line 20 then the finally clause is called before the exception is thrown to the method.
  • 29.
    Find more WWW.ThesisScientist.com 86Enterprise Java Q 46: What is the difference between statements and prepared statements? SFPISEBP A 46: Prepared statements offer better performance, as they are pre-compiled. Prepared statements reuse the same execution plan for different arguments rather than creating a new execution plan every time. Prepared statements use bind arguments, which are sent to the database engine. This allows mapping different requests with same prepared statement but different arguments to execute the same execution plan. Prepared statements are more secure because they use bind variables, which can prevent SQL injection attack. The most common type of SQL injection attack is SQL manipulation. The attacker attempts to modify the SQL statement by adding elements to the WHERE clause or extending the SQL with the set operators like UNION, INTERSECT etc. Example Let us look at the following SQL: SELECT * FROM users where username=‟bob‟ AND password=‟xyfdsw‟ ; The attacker can manipulate the SQL as follows SELECT * FROM users where username=‟bob‟ AND password=‟xyfdsw‟ OR „a‟ = „a‟ ; The above “WHERE” clause is always true because of the operator precedence. The PreparedStatement can prevent this by using bind variables: String strSQL = SELECT * FROM users where username=? AND password=?); PreparedStatement pstmt = myConnection.prepareStatement(strSQL); pstmt.setString(1,”bob”); pstmt.setString(2, “xyfdsw”); pstmt.execute(); Q 47: Explain differences among java.util.Date, java.sql.Date, java.sql.Time, and java.sql.Timestamp? SF A 47: As shown below all the sql Date classes extend the util Date class. Java Date classes java.util.Date java.sql.Datejava.sql.Time java.sql.TimeStamp java.util.Date - class supports both the Date (ie year/month/date etc) and the Time (hour, minute, second, and millisecond) components. java.sql.Date - class supports only the Date (ie year/month/date etc) component. The hours, minutes, seconds and milliseconds of the Time component will be set to zero in the particular time zone with which the instance is associated. java.sql.Time - class supports only Time (ie hour, minute, second, and millisecond) component. The date components should be set to the "zero epoch" value of January 1, 1970 and should not be accessed. java.sql.TimeStamp – class supports both Date (ie year/month/date etc) and the Time (hour, minute, second, millisecond and nanosecond) components. Note: the subtle difference between java.util.Date and java.sql.Date.
  • 30.
    Find more WWW.ThesisScientist.com EnterpriseJava 87 To keep track of time Java counts the number of milliseconds from January 1, 1970 and stores it as a long value in java.util.Date class. The GregorianCalendar class provides us a way to represent an arbitrary date. The GregorianCalendar class also provides methods for manipulating dates. Enterprise – JNDI & LDAP Q 48: What is JNDI? And what are the typical uses within a J2EE application? SF A 48: JNDI stands for Java Naming and Directory Interface. It provides a generic interface to LDAP (Lightweight Directory Access Protocol) and other directory services like NDS, DNS (Domain Name System) etc. It provides a means for an application to locate components that exist in a name space according to certain attributes. A J2EE application component uses JNDI interfaces to look up and reference system-provided and user-defined objects in a component environment. JNDI is not specific to a particular naming or directory service. It can be used to access many different kinds of systems including file systems. The JNDI API enables applications to look up objects such as DataSources, EJBs, MailSessions and JMS by name. The Objects can be loaded into the JNDI tree using a J2EE application server‟s administration console. To load an object in a JNDI tree, choose a name under which you want the object to appear in a JNDI tree. J2EE deployment descriptors indicate the placement of J2EE components in a JNDI tree. J N D I T re e In it ia lC o n t e x t O b je c ts a n d /o r S e rv ic e s u b - c o n t e x t n a m e d o b je c t/s e rv ic e re fe re n c e n a m e d o b je c t/s e rv ic e re fe re n c e N o te : J N D I tre e liv e s in th e s e rv e r a s a c o lle c tio n o f n a m e d o b je c t o r s e rv ic e re fe re n c e s . The parameters you have to define for JNDI service are as follows: The name service provider class name (WsnInitialContext for Websphere). Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.ibm.websphere.naming.WsnInitialContextFactory"); The provider URL : The name service hostname. The name service port number. env.put(Context. PROVIDER_URL, " iiop://localhost:1050"); Context ctx = new InitialContext(env); JNDI is like a file system or a Database. File System JNDI Database File system starts with a mounted JNDI starts with an InitialContext. i.e. new Database instance drive like c: InitialContext().
  • 31.
    Find more WWW.ThesisScientist.com 88Enterprise Java Uses a subdirectory. C:subdir1 Navigate to a sub-context. e.g. Subcontext1 Tablespace Access a subdirectory Drill down through other sub-contexts. e.g. Table c:subdir1subdir2 subcontext1/subcontext2 Access a file. Access an object or a service. Data C:subdir1subdir2myFile New InitialContext().lookup(“objectName”); Example: Example: Example: c:subdir1subdir2myFile iiop://myserver:2578/subcontext1.subcontext2.o Select * from demo.myTable bjectName Q 49: Explain the difference between the look up of “java:comp/env/ejb/MyBean” and “ejb/MyBean”? SF A 49: java:comp/env/ejb/MyBean ejb/MyBean This is a logical reference, which will be used in your code. This is a physical reference where an object will be mapped to in a JNDI tree. The logical reference (or alias) java:comp/env/ejb/MyBean is the recommended approach because you cannot guarantee that the physical JNDI location (ejb/MyBean) you specify in your code will be available. Your code will break if the physical location is changed. The deployer will not be able to modify your code. Logical references solve this problem by binding the logical name to the physical name in the application server. The logical names will be declared in the deployment descriptors (web.xml and/or ejb-jar.xml) as follows and these will be mapped to physical JNDI locations in the application server specific deployment descriptors. To look up a JDBC resource from either WEB (web.xml) or EJB (ejb-jar.xml) tier, the deployment descriptor should have the following entry: <resource-ref> <description>The DataSource</description> <res- ref-name>jdbc/MyDataSource</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res- auth>Container</res-auth> </resource-ref> To use it: Context ctx = new InitialContext(); Object ref = ctx.lookup(java:comp/env/jdbc/MyDataSource); This will make full logical path to the bean as: java:comp/env/jdbc/MyDataSource To look up EJBs from another EJB or a WEB module, the deployment descriptor should have the following entry: <ejb-ref> <description>myBean</description> <ejb-ref-name>ejb/MyBean</ejb-ref- name> <ejb-ref-type>Entity</ejb-ref-type> <ejb-link>Region</ejb-link> <home>com.MyBeanHome</home> <remote>com.MyBean</remote> </ejb-ref> To use it: Context ctx = new InitialContext(); Object ref = ctx.lookup(java:comp/env/ejb/MyBean); This will make full logical path to the bean as: java:comp/env/ejb/MyBean Q 50: What is a JNDI InitialContext? SF A 50: All naming operations are relative to a context. The InitalContext implements the Context interface and provides an entry point for the resolution of names. Q 51: What is an LDAP server? And what is it used for in an enterprise environment? SFSE A 51: LDAP stands for Lightweight Directory Access Protocol. This is an extensible open network protocol standard that provides access to distributed directory services. LDAP is an Internet standard for directory services that run on TCP/IP. Under OpenLDAP and related servers, there are two servers – slapd, the LDAP daemon where the queries are sent to and slurpd, the replication daemon where data from one server is pushed to one or more
  • 32.
    Find more WWW.ThesisScientist.com EnterpriseJava 89 slave servers. By having multiple servers hosting the same data, you can increase reliability, scalability, and availability. It defines the operations one may perform like search, add, delete, modify, change name It defines how operations and data are conveyed. LDAP has the potential to consolidate all the existing application specific information like user, company phone and e-mail lists. This means that the change made on an LDAP server will take effect on every directory service based application that uses this piece of user information. The variety of information about a new user can be added through a single interface which will be made available to Unix account, NT account, e-mail server, Web Server, Job specific news groups etc. When the user leaves his account can be disabled to all the services in a single operation. So LDAP is most useful to provide “white pages” (e.g. names, phone numbers, roles etc) and “yellow pages” (e.g. location of printers, application servers etc) like services. Typically in a J2EE application environment it will be used to authenticate and authorise users. Why use LDAP when you can do the same with relational database (RDBMS)? In general LDAP servers and RDBMS are designed to provide different types of services. LDAP is an open standard access mechanism, so an RDBMS can talk LDAP. However the servers, which are built on LDAP, are optimized for read access so likely to be much faster than RDBMS in providing read access. So in a nutshell, LDAP is more useful when the information is often searched but rarely modified. (Another difference is that RDBMS systems store information in rows of tables whereas LDAP uses object oriented hierarchies of entries.) . Key LDAP Terms: DIT: Directory Information Tree. Hierarchical structure of entries, those make up a directory. DN: Distinguished Name. This uniquely identifies an entry in the directory. A DN is made up of relative DNs of the entry and each of entry‟s parent entries up to the root of the tree. DN is read from right to left and commas separate these names. For example „cn=Peter Smith, o=ACME, c=AUS‟. objectClass: An objectClass is a formal definition of a specific kind of objects that can be stored in the directory. An ObjectClass is a distinct, named set of attributes that represent something concrete such as a user, a computer, or an application. LDAP URL: This is a string that specifies the location of an LDAP resource. An LDAP URL consists of a server host and a port, search scope, baseDN, filter, attributes and extensions. Refer to diagram below: LD A P D irectory structure ro o t o b je c tC la s s F a c to ry = c o u n try c = A U S c = U K o b je c tC la s s F a c to ry = o rg a n iz a tio n o = A C M E o = X Y Z R e ta il o = Q u ic k C o rp o b je c tC la s s F a c to ry = u s e r cn=Peter Sm ith m ail=PSm ith@ N A B .com phone=88888888
  • 33.
    Find more WWW.ThesisScientist.com 90Enterprise Java So the complete distinguished name for bottom left entry (ie Peter Smith) is cn=Peter Smith, o=ACME, c=AUS. Each entry must have at least one attribute that is used to name the entry. To manage the part of the LDAP directory we should specify the highest level parent distinguished names in the server configuration. These distinguished names are called suffixes. The server can access all the objects that are below the specified suffix in the hierarchy. For example in the above diagram to answer queries about „Peter Smith‟ the server should have the suffix of „o=ACME, c=AUS‟. So we can look for “Peter Smith” by using the following distinguished name: cn=Peter Smith, o=ACME, c=AUS //where o=ACME, c=AUS is the suffix LDAP schema: defines rules that specify the types of objects that a directory may contain and the required optional attributes that entries of different types should have. Filters: In LDAP the basic way to retrieve data is done with filters. There is a wide variety of operators that can be used as follows: & (and), | (or), ! (not), ~= (approx equal), >= (greater than or equal), <= (less than or equal), * (any) etc. (& (uid=a*) (uid=*l) ) So where does JNDI fit into this LDAP? JNDI provides a standard API for interacting with naming and directory services using a service provider interface (SPI), which is analogous to JDBC driver. To connect to an LDAP server, you must obtain a reference to an object that implements the DirContext. In most applications, this is done by using an IntialDirContext object that takes a Hashtable as an argument: Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, “com.sun.jndi.ldap.LdapCtxFactory”); env.put(Context.PROVIDER_URL, “ldap://localhost:387”); env.put(Context.SECURITY_AUTHENTICATION, “simple”); env.put(Context.SECURITY_PRINCIPAL, “cn=Directory Manager”); env.put(Context.SECURITY_CREDENTIALS, “myPassword”); DirContext ctx = new InitialDirContext(env); Enterprise - RMI Q 52: Explain the RMI architecture? SF A 52: Java Remote Method Invocation (RMI) provides a way for a Java program on one machine to communicate with objects residing in different JVMs (or processes or address spaces). The important parts of the RMI architecture are the stub class, object serialization and the skeleton class. RMI uses a layered architecture where each of the layers can be enhanced without affecting the other layers. The layers can be summarised as follows: Application Layer: The client and server program Stub & Skeleton Layer: Intercepts method calls made by the client. Redirects these calls to a remote RMI service. Remote Reference Layer: Sets up connections to remote address spaces, manages connections, and understands how to interpret and manage references made from clients to the remote service objects. Transport layer: Based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies. Design pattern: RMI stub classes provide a reference to a skeleton object located in a different address space on the same or different machine. This is a typical example of a proxy design pattern (i.e. remote proxy), which makes an object executing in another JVM appear like a local object. In JDK 5.0 and later, the RMI facility uses dynamic proxies instead of generated stubs, which makes RMI easier to use. Refer Q11 in “How would you about…” section for a more detailed discussion on proxy design pattern and dynamic proxies.
  • 34.
    Find more WWW.ThesisScientist.com EnterpriseJava 91 R M I A rchitecture C lie n t S e rv e r C lient Process C lie n t b je c ts Stub R em ote R eference M anager 2. look up Stub 3 . R eturn Stub Stub 4. M etho d call o n r ser 5. S end re em ote ver O bjectssu lts or Ex ception Server Process R M I R egistry (or JNDI Server) 1 . L o R em ote a d S O bjects t b u s Skeleton RMITransportLayer R em ote R eference M anager RMI Transport Layer N ote: Steps 4 & 5 are logical explanation only. N either the Stubs nor Skeletons use sockets directly. The actual calls are m ade through the R em ote R eference M anager. The R em ote R eference M anager handles the actual details of com m unicating w ith the rem ote process. This extra layer m anages netw ork com m unication and conserves scarce resources like sockets. E x a m p le Program 1 stub stub Program 2 skeleton skeleton RMI runtime steps (as shown in the diagram above) involved are: Step 1: Start RMI registry and then the RMI server. Bind the remote objects to the RMI registry. Step 2: The client process will look up the remote object from the RMI registry. Step 3: The lookup will return the stub to the client process from the server process. Step 4: The client process will invoke method calls on the stub. The stub calls the skeleton on the server process through the RMI reference manager. Step 5: The skeleton will execute the actual method call on the remote object and return the result or an exception to the client process via the RMI reference manager and the stub. Q 53: What is a remote object? Why should we extend UnicastRemoteObject? SF A 53: A remote object is one whose methods can be invoked from another JVM (or process). A remote object class must implement the Remote interface. A RMI Server is an application that creates a number of remote objects. An RMI Server is responsible for Creating an instance of the remote object (e.g. CarImpl instance = new CarImpl()). Exporting the remote object. Binding the instance of the remote object to the RMI registry. By exporting a remote object you make it available to accept incoming calls from the client. You can export the remote object by either extending the java.rmi.server.UnicastRemoteObject or if your class is already extending another class then you can use the static method
  • 35.
    Find more WWW.ThesisScientist.com 92Enterprise Java UnicastRemoteObject.exportObject (this); If the UnicastRemoteObject is not extended (ie if you use UnicastRemoteObject.exportObject(…) then the implementation class is responsible for the correct implementations of the hashCode(), equals() and toString() methods. A remote object is registered in the RMI registry using: Naming.rebind(String serviceName, Remote remoteObj); Remote Objects java.rmi.Remote Remote interface java.rmi.server.RemoteServer eg: public interface Car extends Remote{} Implementation of Remote interface java.rmi.server.UnicastRemoteObject eg: public class CarImpl extends UnicastRemoteObject implements Car{} Compile Car & CarImpl use rmic to generate stubs & skeletons rmic -d /classes CarImpl d g entea r er e at n e e d g instantiated stub class skeleton class instantiated instantiated Client Object stub Object skeleton Object remote Object instances instances instances instances Q 54: What is the difference between RMI and CORBA? SF A 54: RMI CORBA Java only solution. The interfaces, CORBA was made specifically for interoperability among various implementations and the clients are all written languages. For example the server could be written in C++ and the in Java. business logic can be in Java and the client can be written in COBOL. RMI allows dynamic loading of classes at In a CORBA environment with multi-language support it is not possible to runtime. have dynamic loading. Q 55: What are the services provided by the RMI Object? SF A 55: In addition to its remote object architecture RMI provides some basic object services, which can be used in a distributed application. These services are Object naming/registry service: RMI servers can provide services to clients by registering one or more remote objects with its local RMI registry. Object activation service: It provides a way for server (or remote) objects to be started on an as-needed basis. Without the remote activation service, a server object has to be registered with the RMI registry service. Distributed garbage collection: It is an automatic process where an object, which has no further remote references, becomes a candidate for garbage collection. Q 56: What are the differences between RMI and a socket? SF A 56:
  • 36.
    Find more WWW.ThesisScientist.com EnterpriseJava 93 Socket RMI A socket is a transport mechanism. Sockets are like RMI uses sockets. RMI is object oriented. Methods can be applying procedural networking to object oriented invoked on the remote objects running on a separate JVM. environment. Sockets-based network programming can be laborious. RMI provides a convenient abstraction over raw sockets. Can send and receive any valid Java object utilizing underlying object serialization without having to worry about using data streams. Q 57: How will you pass parameters in RMI? SF A 57: Primitive types are passed by value (e.g. int, char, boolean etc). References to remote objects (i.e. objects which implements the Remote interface) are passed as remote references that allows the client process to invoke methods on the remote objects. Non-remote objects are passed by value using object serialization. These objects should allow them to be serialized by implementing the java.io.Serializable interface. Note: The client process initiates the invocation of the remote method by calling the method on the stub. The stub (client side proxy of the remote object) has a reference to the remote object and forwards the call to the skeleton (server side proxy of the remote object) through the reference manager by marshalling the method arguments. During marshalling each object is checked to determine whether it implements java.rmi.Remote interface. If it does then the remote reference is used as the marshalled data otherwise the object is serialized into byte streams and sent to the remote process where it is deserialized into a copy of the local object. The skeleton converts this request from the stub into the appropriate method call on the actual remote object by unmarshalling the method arguments into local stubs on the server (if they are remote reference) or into local copy (if they are sent as serialized objects). Q 58: What is HTTP tunnelling or how do you make RMI calls across firewalls? SFSE A 58: RMI transport layer generally opens direct sockets to the server. Many Intranets have firewalls that do not allow this. To get through the firewall an RMI call can be embedded within the firewall-trusted HTTP protocol. To get across firewalls, RMI makes use of HTTP tunnelling by encapsulating RMI calls within an HTTP POST request. HTTP tunnelling Proxy Server Web Server on port 80 HTTPe ncapsu latedR MIcall c a l l f o r w a r d e d b y C G I s c r i p t RMI Client RMI Server Firewall Firewall When a firewall proxy server can forward HTTP requests only to a well-known HTTP port: The firewall proxy server will forward the request to a HTTP server listening on port 80, and a CGI script will be executed to forward the call to the target RMI server port on the same machine. When a firewall proxy server can forward HTTP requests to any arbitrary port: The firewall proxy will forward to any arbitrary port on the host machine and then it is forwarded directly to the port on which RMI Server is listening. The disadvantages of HTTP tunnelling are performance degradation, prevents RMI applications from using call- backs, CGI script will redirect any incoming request to any port, which is a security loophole, RMI calls cannot be multiplexed through a single connection since HTTP tunnelling follows a request/response protocol etc.
  • 37.
    Find more WWW.ThesisScientist.com 94Enterprise Java Q 59: Why use RMI when we can achieve the same benefits from EJB? SF A 59: EJBs are distributed components, which use the RMI framework for object distribution. An EJB application server provides more services like transactions, object pooling, database connection-pooling etc, which RMI does not provide. These extra services that are provided by the EJB server simplify the programming effort at the cost of performance overhead compared to plain RMI. So if performance is important then pure RMI may be a better solution (or under extreme situations Sockets can offer better performance than RMI). Note: The decision to go for RMI or EJB or Sockets should be based on requirements such as maintainability, ease of coding, extensibility, performance, scalability, availability of application servers, business requirements etc. Enterprise – EJB 2.x There are various persistence mechanisms available like EJB 2.x, Object-to-Relational (O/R) mapping tools like Hibernate, JDBC and EJB 3.0 (new kid on the block) etc. You will have to evaluate the products based on the application you are building because each product has its strengths and weaknesses. You will find yourself trading ease of use for scalability, standards with support for special features like stored procedures, etc. Some factors will be more important to you than for others. There is no one size fits all solution. Let‟s compare some of the persistence products: EJB 2.x EJB 3.0 Hibernate JDBC PROS: PROS: PROS: PROS: ƒ Security is provided for free ƒ A lot less artefacts than EJB ƒ Simple to write CRUD ƒ You have complete control for accessing the EJB. 2.x. Make use of annotations (create, retrieve, update, over the persistence ƒ Provides declarative or attributes based delete) operations. because this is the building programming. blocks of nearly all other transactions. ƒ Narrows the gap between EJB ƒ No container or application persistence technologies in ƒ EJBs are pooled and server is required and can be Java. 2.x and O/R mapping. plugged into an existing ƒ Can call Stored Procedures.cached. EJB life cycles are ƒ Do support OO concepts like container. managed by the container. ƒ Tools are available to simplify ƒ Can manipulate relatively ƒ Has remote access inheritance. mapping relational data to large data sets. capabilities and can be objects and quick to develop. clustered for scalability. Cons: Cons: Cons: Cons: ƒ Need to understand the ƒ Since it is new, might be too ƒ Little or no capabilities for ƒ You will have to write a lot intricacies like rolling back early to use in commercial remote access and of code to perform a little. a transaction, granularity projects. distributability. Easy to make mistakes in etc, infrastructures like ƒ It is still evolving. ƒ Mapping schemas can be properly managing session facades, business connections and can cause delegates, value objects etc tedious and O/R mapping out of cursors issues. and strategies like lazy has its tricks like using lazy ƒ Harder to maintain becauseloading, dirty marker etc. initialization, eager loading etc. What works for one may changes in schemas can ƒ EJBs use lots of resources not work for another. cause lot of changes to your and have lots of artifacts. ƒ Limited clustering code. ƒ Does not support OO ƒ Records need to be lockedcapabilities. concepts like inheritance. manually (e.g. select for ƒ Large data sets can still update). cause memory issues. ƒ Support for security at a database level only and no support for role based security without any add on APIs like Aspect Oriented Programming etc. As a rule of thumb, suitable As a rule of thumb, suitable for Suitable for records in use Where possible stay away for distributed and clustered distributed and clustered between 100 and 5000. Watch from using JDBC unless you applications, which is heavily applications, which is heavily out for memory issues, when have compelling reason to transaction based. Records transaction based. Records in using large data sets. use it for batch jobs where in use say between 1 and 50. use say between 1 and 100. large amount of data need to be transferred, records in use greater than 5000, required to use Stored Procedures etc.
  • 38.
    Find more WWW.ThesisScientist.com EnterpriseJava 95 The stateless session beans and message driven beans have wider acceptance in EJB 2.x compared to stateful session beans and entity beans. Refer Emerging Technologies/Frameworks section for Hibernate and EJB 3.0. Q 60: What is the role of EJB 2.x in J2EE? SF A 60: EJB 2.x (Enterprise JavaBeans) is a widely adopted server side component architecture for J2EE. EJB is a remote, distributed multi-tier system and supports protocols like JRMP, IIOP, and HTTP etc. It enables rapid development of reusable, versatile, portable business components across middleware, transactional and scalable applications. EJB is a specification for J2EE servers. EJB components contain only business logic and system level programming and services like transactions, security, instance pooling, threading, persistence etc are managed by the EJB Container and hence simplify the programming effort. Message driven EJBs have support for asynchronous communication. Note: Having said that EJB 2.x is a widely adopted server side component, EJB 3.0 is taking ease of development very seriously and has adjusted its model to offer the POJO (Plain Old Java Object) persistence and the new O/R mapping model based on Hibernate. In EJB 3.0, all kinds of enterprise beans are just POJOs. EJB 3.0 extensively uses Java annotations, which replaces excessive XML, based configuration files and eliminates the need for the rigid component model used in EJB 1.x, 2.x. Annotations can be used to define the bean‟s business interface, O/R mapping information, resource references etc. Refer Q18 in Emerging Technologies/Frameworks section. So, for future developments look out for EJB 3.0 and/or Hibernate framework. Refer Q14 – Q16 in Emerging Technologies/Frameworks section for discussion on Hibernate framework. EJB - Big Picture Other J2EE C++ application Messaging Java Applet, HTTP Client Systems Client Java stand-alone application (eg: Browser, Wireless etc) HTTP Web Services (SOAP, UDDI, WSDL, ebXML) Firewall J2EE Server JSP Servlets messaging (use JavaBeans) (use JavaBeans) IIOP RMI/IIOP ServletsBusiness Delegate (use JavaBeans) (use JavaBeans) BusinessLogicprovidedby EJB Container (Enterprise Java Beans are deployed) SystemLevelServiceslike transaction,Securityetc EJB Session Bean EJB Message Driven Bean EJB Session Bean EJB Entity Bean EJB Session Bean EJB Session Bean thedeveloperth roughEJB areprovided bythecontaine r SQL SQL (fast Lane Reader) Web Services Connectors (JCA) (SOAP, UDDI, WSDL, ebXML) proprietary protocol Legacy System, Message Oriented Other J2EE SystemsDatabase ERP System etc Middleware Topic Q 61: What is the difference between EJB and JavaBeans? SF A 61: Both EJB and JavaBeans have very similar names but this is where the similarities end. JavaBeans Enterprise JavaBeans (EJB) The components built based on JavaBeans live in a single The Enterprise JavaBeans are non-visual distributable local JVM (or address space) and can be either visual (e.g. components, which can live across multiple JVMs (or address GUI components like Button, List etc) or non-visual at spaces). runtime.
  • 39.
    Find more WWW.ThesisScientist.com 96Enterprise Java No explicit support exists for services like transactions etc. EJBs can be transactional and the EJB servers provide transactional support. JavaBeans are fine-grained components, which can be EJBs are coarse-grained components that can be deployed as used to assemble coarse-grained components or an is or assembled with other components into larger application. applications. EJBs must be deployed in a container that provides services like instance pooling, multi-threading, security, life-cycle management, transactions etc Must conform to JavaBeans specification. Must conform to EJB specification. Q 62: Explain EJB architecture? SF A 62: E J B A r c h ite c tu r e E J B S e r v e r EJBClientServlet,JSP,Standalonea pplication,Appletetc) E J B C o n ta in e r E n te rp ris e J a v a B e a n s s y n c h ro n o u s H o m e /L o c a lH o m e H o m e O b je c t / S e s s io n B e a n s In te r fa c e L o c a l H o m e O b je c t s ta te fu l / s ta te le s s E n tity B e a n s D a ta b a s e S e r v e r s y n c h ro n o u s R e m o te /L o c a l E J B O b je c t / C M P / B M P In te r fa c e E J B L o c a lO b je c t (e g E n te rp ris e J a v a B e a n s J M S M e s s a g e - D r iv e n E IS S y s te m J M S M e s s a g e B e a n sM e s s a g e A s y n c h ro n o u s P r o d u c e r L is te n e r In te r fa c e (e g p u b lis h / s u b s c rib e T o p ic ) E n te r p r is e S e r v ic e s a n d A P I J N D I J M S T ra n s a c tio n s S e c u rity P e r s is t e n c e E J B C o n ta in e r C lie n t p Bu k Uo o T L S . t e1 eg k . o 2 v () . In te 3 a re ()c )d n ( fi e bv o u m t e es r n th b 9. in v o o k ee a n m eth o d s J N D I H o m e In te r fa c e R e m o te In te r fa c e ly p p a &t p sr e c ee t c in i . v 4 r e s H o m e O b je c t lyp p a e & t w c p e n e n a c t r s e 5 n t . i ni . 6 E J B O B je c t 7. Ref er D e p lo y m e n t d e s c rip to r B e a n d e fin itio n T ra n s a c tio n S e c u rity e tc 8 . b ea n life - m e jb c yc l e e t h oC re a te ( ) o r d s e jb F in d () ods s m ethes etcsin r()an bu Po we 1 0. be e ge tH ors E J B C o n te x t b e a n in s ta n c e S a m p le C o d e : C o n te x t in itia lC tx = n e w In itia lC o n te x t( ) ; //In itia liz e th e J N D I c o n te x t . ie e n tr y p o in t . C a r H o m e h o m e O b je c t = ( C a r H o m e ) in itia lC tx .lo o k u p ( e jb /M y E jb ) ; // S te p s 1 & 2 in th e a b o v e d ia g r a m C a r c a r O b je c t = h o m e O b je c t.c r e a te ( ) ; // S te p s 3 - 8 c a r O b je c t .g e tH o r s e P o w e r ( ) ; // S te p s 9 - 1 0 N o te : A n E J B c lie n t s h o u ld n e v e r a c c e s s a n E n te rp r is e J a v a B e a n d ire c tly . A n y a c c e s s is d o n e th r o u g h th e c o n ta in e r g e n e ra te d c la s s e s w h ic h in tu r n in v o k e b e a n m e th o d s . T h e c o n ta in e r g e n e r a te d c la s s e s in te rc e p t th e re q u e s t a n d a p p ly s e rv ic e s lik e tr a n s a c tio n , s e c u rity e tc p rio r to in v o k in g th e a c tu a l m e th o d o n th e E n e te rp ris e J a v a B e a n s . EJB Container : EJBs are software components, which run in an environment called an EJB container. An EJB cannot function outside an EJB Container. The EJB container hosts and manages an Enterprise JavaBean in a similar manner that a Web container hosts a servlet or a Web browser hosts a Java Applet. The EJB container manages the following services so that the developer can concentrate on writing the business logic: Transactions (refer Q71 – Q75 in Enterprise section) Persistence EJB instance pooling Security (refer Q81 in Enterprise section) Concurrent access (or multi-threading) Remote access Design pattern: EJBs use the proxy design pattern to make remote invocation (i.e. remote proxy) and to add container managed services like security and transaction demarcation. Refer Q11 in “How would you about…” section for a more detailed discussion on proxy design pattern and dynamic proxies.
  • 40.
    Find more WWW.ThesisScientist.com EnterpriseJava 97 EJBContext: Every bean obtains an EJBContext object, which is a reference directly to the container. The EJB can request information about its environment like the status of a transaction, a remote reference to itself (an EJB cannot use „this‟ to reference itself) etc. Deployment Descriptor: The container handles all the above mentioned services declaratively for an EJB based on the XML deployment descriptor (ejb-jar.xml). When an EJB is deployed into a container the deployment descriptor is read to find out how these services are handled. Refer to the J2EE deployment structure diagram in Q6 in Enterprise section. EJB: The EJB architecture defines 3 distinct types of Enterprise JavaBeans. Session beans. Entity beans. Message-driven beans. The session and entity beans are invoked synchronously by the client and message driven beans are invoked asynchronously by a message container such as a publish/subscribe topic. Let‟s look at some of the EJB container services in a bit more detail: Instance pooling EJBinstance pooling Clie nt Application home stub EJB Se rve r 1 . create() EJB Home be an ins tance pool 4 . return EJB Object reference EJB 3. assign an instance to client Object to EJB Object Note : 1 The client looks up the stub f rom the jndi and invokes the create() method on the EJBHome object. CarHome hom e Obje ct = (CarHome) initialCtx .lookup(ejb/MyEjb); Car carObject = homeObject.create() 2-3 The EJbHome creates an EJBObject by invoking new Instance() and assigns a bean instance f rom the pool to the EJBObject. Now the assigned bean instance becomes in ready state f rom the pooled state. 4 Now the EJBObject can service client requests and ref erence is returned to the client. carObject .getHorsePow er(); Finally once the client is f inshed w ith EJBObject ref erence the bean instance is returned back to the pool to serve other clients The above diagram shows how the EJB instances are pooled and assigned to EJB Object and then returned to the pool. Let‟s look at in detail for different types of EJBs. s ta tele ss s es s io n & e n tity b ea n p o o lin g E JB S erv er N o te s : C lie nt stub 1 E JB T h e d ia g ra m o n th e le ft sh o w s th a t s in c e th e A s ta te le s s s e s s io n b e a n s a n d e n tity b e a n s O bje ct d o n o t m a in ta in a n y c lie n t s ta te th e b e a n in s ta n c e A w a s firs tly a llo c a te d to c lie n t s tu b b ean in stan ce p o o l 1 a n d la te r o n a llo ca te d to c lie n t s tu b 2 . S o if th e re a re 1 0 0 0 c o n c u rre n t clie n ts th e n 3 0 E JB C D in s ta n c e s o f b e a n c a n s e rve th e m b y ta k in g C lie nt stub 2 O bje ct B tu rn s . T h is b e h a vio u r is n o t p o s s ib le w ith re g a rd s to s ta te fu l s e s s io n b e a n s w h ic h m a in ta in th e E JB S e rv er clie n t s ta te . S o th e re w ill b e a d e d ic a te d in s ta n c e o f th e b e a n fo r e a ch c lie n t s tu b . S o C lie nt stub 1 E J B B if th e re a re 1 0 0 0 c lie n ts th e n th e re w ill b e 1 0 0 0 in s ta n c e s o f b e a n s . S o h o w d o w e O b je c t co n s e rve m e m o ry . T h is is d o n e b y a c tiva tio n a n d p a s siva tio n . P a s s iva tio n is th e p ro c e s s b ean in s tan ce p o o l w h e re th e b e a n in s ta n c e is s e ria lize d in to a C D p e rs is te n t s to re w h e n n o t u s e d to c o n s e rve C lient stub 2 E J B m e m o ry a n d A c tiva tio n is p ro c e s s w h e re th e O b je c t A se rilize d b e a n in s ta n ce is d e -s e ria lize d b a c k in to m e m o ry to s e rve c lie n t re q u e s t. T h is p ro c e s s a ffe c ts p e rfo rm a n c e .
  • 41.
    Find more WWW.ThesisScientist.com 98Enterprise Java From the diagrams it is clear that bean instances can be reused for all the bean types except for the stateful session bean where the client state is maintained. So we need a dedicated stateful session bean for each client. M e s s a g e D riv e n B e a n (M D B ) p o o lin g E J B S e rv e r J M S C lie n t 1 m s g X fo r Q 1 E J B M D B -1 b e a n in s ta n c e p o o l A fo r Q 1 O b je c t B C J M S C lie n t 2 m s fo r Q 2 E J Bg Z BO b je c t M D B -2 b e a n in s ta n c e p o o l fo r Q 2 CJ M S C lie n t 3 m sg y fo r Q 2 E J B AO b je c t N o te : M D B a re lik e s ta te le s s s e s s io n b e a n s , T h e in s ta n c e p o o ls a re c re a te d fo r e a c h M D B a n d w ith in e a c h p o o l m u ltip le in s ta n c e s a re c re a te d . In te rm s o f n u m b e r o f in s ta n c e s c re a te d in e a c h p o o l a re v e ry s im ila r to s ta te le s s s e s s io n b e a n s o r e n tity b e a n s (ie 3 in s ta n c e s o f M D B -1 fo r Q 1 in s ta n c e p o o l c a n s e rv e 1 0 J M S c lie n ts fo r Q 1 ). Concurrent access The session beans do not support concurrent access. The stateful session beans are exclusively for a client so there is no concurrent access. The stateless session beans do not maintain any state. It does not make any sense to have concurrent access. The Entity beans represent data that is in the database table, which is shared between the clients. So to make concurrent access possible the EJB container need to protect the data while allowing many clients simultaneous access. When you try to share distributed objects you may have the following problem: If 2 clients are using the same EJBObject, how do you keep one client from writing over the changes of the other? Say for example Client-1 reads a value x= 5 Client-2 modifies the value to x=7 Now the client-1‟s value is invalid. The entity bean addresses this by prohibiting concurrent access to bean instances. Which means several clients can be connected to one EJBObject but only one client can access the EJB instance at a time. Persistence Entity beans basically represent the data in a relational database. An Entity Bean is responsible for keeping its state in sync with the database. E n tity b ean s rep resen tin g d ata in th e d atab ase instance for id = 1001 A c c o u n tB e a n id = 1001 (p rim a ry-k e y) bsb = 1234 account_ num ber = 98765432 instance for id = 1002 A c c o u n tB e a n id = 1002 (p rim a ry-k e y) bsb = 1234 account_ num ber = 12345678 Acco u n t T ab le id b s b a c c o u n t_ n u m 1001 1234 98765432 1002 1234 12345678 d atab ase Container-managed persistence (CMP) - The container is responsible for saving the bean‟s state with the help of object-relational mapping tools. Bean-managed persistence (BMP) – The Entity Bean is responsible for saving its own state.
  • 42.
    Find more WWW.ThesisScientist.com EnterpriseJava 99 If entity beans performance is of concern then there are other persistence technologies and frameworks like JDBC, JDO, Hibernate, OJB and Oracle TopLink (commercial product). Q 63: What are the different kinds of enterprise beans? SF A 63: Session Bean: is a non-persistent object that implements some business logic running on the server. Session beans do not survive system shut down. There are two types of session beans Stateless session beans (each session bean can be reused by multiple EJB clients) Stateful session beans (each session bean is associated with one EJB client) Entity Bean: is a persistent object that represents object views of the data, usually a row in a database. They have the primary key as a unique identifier. Multiple EJB clients can share each entity bean. Entity beans can survive system shut shutdowns. Entity beans can have two types of persistence Container-managed persistence (CMP) - The container is responsible for saving the bean‟s state. Bean-managed persistence (BMP) – The Entity Bean is responsible for saving its own state. Message-driven Bean: is integrated with the Java Message Service (JMS) to provide the ability to act as a message consumer and perform asynchronous processing between the server and the message producer. Q 64: What is the difference between session and entity beans? SF A 64: Session Beans Entity Beans Use session beans for application logic. Use entity beans to develop persistent object model. Expect little reuse of session beans. Insist on reuse of entity beans. Session beans control the workflow and transactions of a Domain objects with a unique identity (ie-primary key) shared group of entity beans. by multiple clients. Life is limited to the life of a particular client. Handle Persist across multiple invocations. Handles database access database access for a particular client. for multiple clients. Do not survive system shut downs or server crashes. Do survive system shut downs or server crashes. Q 65: What is the difference between stateful and stateless session beans? SF A 65: Stateless Session Beans Stateful Session Bean Do not have an internal state. Can be reused by different Do have an internal state. Reused by the same client. clients. Need not be activated or passivated since the beans are Need to handle activation and passivation to conserve system pooled and reused. memory since one session bean object per client. Q 66: What is the difference between Container Managed Persistence (CMP) and Bean Managed Persistence (BMP)? SF A 66: Container Managed Persistence (CMP) Bean Managed Persistence (BMP) The container is responsible for persisting state of the bean. The bean is itself responsible for persisting its own state. Container needs to generate database (SQL) calls. The bean needs to code its own database (SQL) calls. The bean persistence is independent of its database (e.g. The bean persistence is hard coded and hence may not be DB2, Oracle, Sybase etc). So it is portable from one data portable between different databases (e.g. DB2, Oracle etc). source to another. Q 67: Can an EJB client invoke a method on a bean directly? SF A 67: An EJB client should never access an EJB directly. Any access is done through the container. The container will intercept the client call and apply services like transaction, security etc prior to invoking the actual EJB. This relationship between the EJB and the container is like “don‟t call us, we will call you”. Q 68: How does an EJB interact with its container and what are the call-back methods in entity beans? SF A 68: EJB interacts with its container through the following mechanisms
  • 43.
    Find more WWW.ThesisScientist.com 100Enterprise Java Call-back Methods: Every EJB implements an interface (extends EnterpriseBean) which defines several methods which alert the bean to various events in its lifecycle. A container is responsible for invoking these methods. These methods notify the bean when it is about to be activated, to be persisted to the database, to end a transaction, to remove the bean from the memory, etc. For example the entity bean has the following call-back methods: public interface javax.ejb.EntityBean { public void setEntityContext(javax.ejb.EntityContext c); public void unsetEntityContext(); public void ejbLoad(); public void ejbStore(); public void ejbActivate(); public void ejbPassivate(); public void ejbRemove(); } EJBContext: provides methods for interacting with the container so that the bean can request information about its environment like the identity of the caller, security, status of a transaction, obtains remote reference to itself etc. e.g. isUserInRole(), getUserPrincipal(), isRollbackOnly(), etc JNDI (Java Naming and Directory Interface): allows EJB to access resources like JDBC connections, JMS topics and queues, other EJBs etc. Q 69: What is the difference between EJB 1.1 and EJB 2.0? What is the difference between EJB 2.x and EJB 3.0? SF A 69: EJB 2.0 has the following additional advantages over the EJB 1.1 Local interfaces: These are beans that can be used locally, that means by the same Java Virtual Machines, so they do not required to be wrapped like remote beans, and arguments between those interfaces are passed directly by reference instead of by value. This improves performance. ejbHome methods: Entity beans can declare ejbHome methods that perform operations related to the EJB component but that are not specific to a bean instance. Message Driven Beans (MDB): is a completely new enterprise bean type, which is designed specifically to handle incoming JMS messages. New CMP Model. It is based on a new contract called the abstract persistence schema, which will allow to the container to handle the persistence automatically at runtime. EJB Query Language: It is a sql-based language that will allow the new persistence schema to implement and execute finder methods. Let‟s look at some of the new features on EJB 2.1 Container-managed timer service: The timer service provides coarse-grained, transactional, time-based event notifications to enable enterprise beans to model and manage higher-level business processes. Web service support: EJB 2.1 adds the ability of stateless session beans to implement a Web service endpoint via a Web service endpoint interface. EJB-QL: Enhanced EJB-QL includes support for aggregate functions and ordering of results. Current EJB 2.x model is complex for a variety of reasons: You need to create several component interfaces and implement several unnecessary call-back methods. EJB deployment descriptors are complex and error prone. EJB components are not truly object oriented, as they have restrictions for using inheritance and polymorphism. EJB modules cannot be tested outside an EJB container and debugging an EJB inside a container is very difficult.
  • 44.
    Find more WWW.ThesisScientist.com EnterpriseJava 101 Note: EJB 3.0 is taking ease of development very seriously and has adjusted its model to offer the POJO (Plain Old Java Object) persistence and the new O/R mapping model based on Hibernate. In EJB 3.0, all kinds of enterprise beans are just POJOs. EJB 3.0 extensively uses Java annotations, which replaces excessive XML based configuration files and eliminate the need for rigid component model used in EJB 1.x, 2.x. Annotations can be used to define the bean‟s business interface, O/R mapping information, resource references etc. Refer Q18 in Emerging Technologies/Frameworks section. Q 70: What are the implicit services provide by an EJB container? SF A 70: Lifecycle Management: Individual enterprise beans do not need to explicitly manage process allocation, thread management, object activation, or object destruction. The EJB container automatically manages the object lifecycle on behalf of the enterprise bean. State Management: Individual enterprise beans do not need to explicitly save or restore conversational object state between method calls. The EJB container automatically manages object state on behalf of the enterprise bean. Security: Individual enterprise beans do not need to explicitly authenticate users or check authorisation levels. The EJB container automatically performs all security checking on behalf of the enterprise bean. Transactions: Individual enterprise beans do not need to explicitly specify transaction demarcation code to participate in distributed transactions. The EJB container can automatically manage the start, enrolment, commitment, and rollback of transactions on behalf of the enterprise bean. Persistence: Individual enterprise beans do not need to explicitly retrieve or store persistent object data from a database. The EJB container can automatically manage persistent data on behalf of the enterprise bean. Q 71: What are transactional attributes? SFTI A 71: EJB transactions are a set of mechanisms and concepts, which insures the integrity and consistency of the database when multiple clients try to read/update the database simultaneously. Transaction attributes are defined at different levels like EJB (or class), a method within a class or segment of a code within a method. The attributes specified for a particular method take precedence over the attributes specified for a particular EJB (or class). Transaction attributes are specified declaratively through EJB deployment descriptors. Unless there is any compelling reason, the declarative approach is recommended over programmatic approach where all the transactions are handled programmatically. With the declarative approach, the EJB container will handle the transactions. Transaction Description Attributes Required Methods executed within a transaction. If client provides a transaction, it is used. If not, a new transaction is generated. Commit at end of method that started the transaction. Which means a method that has Required attribute set, but was called when the transaction has already started will not commit at the method completion. Well suited for EJB session beans. Mandatory Client of this EJB must create a transaction in which this method operates, otherwise an error will be reported. Well-suited for entity beans. RequiresNew Methods executed within a transaction. If client provides a transaction, it is suspended. If not a new transaction is generated, regardless. Commit at end of method. Supports Transactions are optional. NotSupported Transactions are not supported. If provided, ignored. Never Code in the EJB responsible for explicit transaction control. Q 72: What are isolation levels? SFTIPI A 72: Isolation levels provide a degree of control of the effects one transaction can have on another concurrent transaction. Since concurrent effects are determined by the precise ways in which, a particular relational database handles locks and its drivers may handle these locks differently. The semantics of isolation mechanisms based on these are not well defined. Nevertheless, certain defined or approximate properties can be specified as follows: Isolation level Description TRANSACTION_SERIALIZABLE Strongest level of isolation. Places a range lock on the data set, preventing other users from updating or inserting rows into the data set until the transaction is complete. Can produce deadlocks.
  • 45.
    Find more WWW.ThesisScientist.com 102Enterprise Java TRANSACTION_REPEATABLE_READ Locks are placed on all data that is used in a query, preventing other users from updating the data, but new phantom records can be inserted into the data set by another user and are included in later reads in the current transaction. TRANSACTION_READ_COMMITTED Can't read uncommitted data by another transaction. Shared locks are held while the data is being read to avoid dirty reads, but the data can be changed before the end of the transaction resulting in non-repeatable reads and phantom records. TRANSACTION_READ_UNCOMMITTED Can read uncommitted data (dirty read) by another transaction, and non- repeatable reads and phantom records are possible. Least restrictive of all isolation levels. No shared locks are issued and no exclusive locks are honoured. Isolation levels are not part of the EJB specification. They can only be set on the resource manager either explicitly on the Connection (for bean managed persistence) or via the application server specific configuration. The EJB specification indicates that isolation level is part of the Resource Manager. As the transaction isolation level increases, likely performance degradation follows, as additional locks are required to protect data integrity. If the underlying data does not require such a high degree of integrity, the isolation level can be lowered to improve performance. Q 73: What is a distributed transaction? What is a 2-phase commit? SFTI A 73: A Transaction (Refer Q43 in Enterprise section) is a series of actions performed as a single unit of work in which either all of the actions performed as a logical unit of work in which, either all of the actions are performed or none of the actions. A transaction is often described by ACID properties (Atomic, Consistent, Isolated and Durable). A distributed transaction is an ACID transaction between two or more independent transactional resources like two separate databases. For the transaction to commit successfully, all of the individual resources must commit successfully. If any of them are unsuccessful, the transaction must rollback in all of the resources. A 2-phase commit is an approach for committing a distributed transaction in 2 phases. Phase 1 is prepare: Each of the resources votes on whether it‟s ready to commit – usually by going ahead and persisting the new data but not yet deleting the old data. Phase 2 is committing: If all the resources are ready, they all commit – after which old data is deleted and transaction can no longer roll back. 2-phase commit ensures that a distributed transaction can always be committed or always rolled back if one of the databases crashes. The XA specification defines how an application program uses a transaction manager to coordinate distributed transactions across multiple resource managers. Any resource manager that adheres to XA specification can participate in a transaction coordinated by an XA- compliant transaction manager. Q 74: What is dooming a transaction? TI A 74: A transaction can be doomed by the following method call CO EJBContext.setRollbackOnly(); The above call will force transaction to rollback. The doomed transactions decrease scalability and if a transaction is doomed why perform compute intensive operations? So we can detect a doomed transaction as shown below: CO public void doComputeIntensiveOperation() throws Exception { If ( ejbContext.getRollbackOnly() ) { return; //transaction is doomed so return (why unnecessarily perform compute intensive operation ) } else { performComplexOperation(); } } Q 75: How to design transactional conversations with session beans? SFTI A 75: A stateful session bean is a resource which has an in memory state which can be rolled back in case of any failure. It can participate in transactions by implementing SessionSynchronization. CO
  • 46.
    Find more WWW.ThesisScientist.com Enterprise Java103 SessionSynchronization public class MyBean implements SessionBean, SessionSynchronization{ public int oldVal ; public int val ; public void ejbCreate(int val) throws CreateException { this.val=val; this.oldVal=val; } public void afterBegin() { this.oldVal = this.val ;} public void beforeCompletion(){}; public void afterCompletion(boolean b) { if (b == false) this.val = this.oldVal ; } ....................................... } public interface javax.ejb.SessionSynchronization { public void afterBegin(); public void beforeCompletion(); public void afterCompletion(boolean b); } The uses of SessionSynchronization are: Enables the bean to act as a transactional resource and undo state changes on failure. Enables you to cache database data to improve performance. Q 76: Explain exception handling in EJB? SFEHCO A 76: Java has two types of exceptions: Checked exception: derived from java.lang.Exception but not java.lang.RuntimeException. Unchecked exception: derived from java.lang.RuntimeException thrown by JVM. System vs Application Exception public void depositAmount() throws InsufficientFundException { if(this.amount <= 0) { throw new InsufficientFundException ("Balance is <= 0"); } try { depositAmount(); } catch (SQLException e) { throw new EJBException(e); } catch (Exception e) { throw new EJBException(e); } } Application Exception System Exception EJB has two types of exceptions: System Exception: is an unchecked exception derived from java.lang.RuntimeException. Application Exception: is specific to an application and thrown because of violation of business rules. A System Exception is thrown by the system and is not recoverable. For example EJB container losing connection to the database server, failed remote method objects call etc. Because the System Exceptions are unpredictable, the EJB container is the only one responsible for trapping the System Exceptions. The container automatically wraps any RuntimeException in RemoteException, which subsequently gets thrown to the caller (or client). In addition to intercepting System Exception the container may log the errors. An Application Exception is specific to an application and is thrown because of violation of business rules. The client should be able to determine how to handle an Application Exception. If the account balance is zero then an Application Exception like InsufficientFundException can be thrown. If an Application Exception should be treated as a System Exception (e.g. SQLException) it needs to be wrapped in an EJBException so that it can be managed properly and propagated to the client. Q 77: How do you rollback a container managed transaction in EJB? SFTIEH
  • 47.
    Find more WWW.ThesisScientist.com 104Enterprise Java A 77: The way the exceptions are handled affects the way the transactions are managed. CO Rolling back Container Managed Transactions public void depositAmount() throws InsufficientFundExceptiion { try { depositAmount(); }catch (InsufficientFundException e) ctx.setRollbackOnly(); throw new InsufficientFundExceptiion(e.getMessage()); } catch (SQLException e) { throw new EJBException(e); } catch (Exception e) { throw new EJBException(e); } } Application Exception is thrown so the transaction should be rolled back in the code ctx.setRollbackOnly(). EJBException is a System Exception so the container will automatically roll back the transaction. When the container manages the transaction, it is automatically rolled back when a System Exception occurs. This is possible because the container can intercept System Exception. However when an Application Exception occurs, the container does not intercept it and therefore leaves it to the code to roll back using ctx.setRollbackOnly(). Be aware that handling exceptions in EJB is different from handling exceptions in Java. The Exception handling best practice tips are: If you cannot recover from System Exception let the container handle it. If a business rule is violated then throw an application exception. Catch the Exceptions in a proper order. It is a poor practice to catch java.lang.Exception because this is a big basket, which will catch all the unhandled exceptions. It is shown in the above diagrams for illustration purpose only. You should avoid this because if you add a new piece of code, which throws a new, checked exception, then the compiler won‟t pick it up. Q 78: What is the difference between optimistic and pessimistic concurrency control? TI A 78: Pessimistic Concurrency Optimistic Concurrency A pessimistic design assumes conflicts will occur in the An optimistic approach assumes conflicts won‟t occur, and deal with database tables and avoids them through exclusive them when they do occur. locks etc. EJB (also non-EJB) locks the source data until it EJB (also non-EJB) implements a strategy to detect whether a completes its transaction. change has occurred. Locks are placed on the database only for a ƒ Provides reliable access to data. small portion of the time. ƒ Suitable for short transactions. ƒ Suitable for long transactions. ƒ Suitable for systems where concurrent access is ƒ Suitable for systems requiring frequent concurrent accesses. rare. The pessimistic locking imposes high locking The optimistic locking is used in the context of cursors. The overheads on the server and lower concurrency. optimistic locking works as follows: ƒ No locks are acquired as rows are read. ƒ No locks are acquired while values in the current row are changed. ƒ When changes are saved, a copy of the row in the database is read in the locked mode. ƒ If the data was changed after it was read into the cursor, an error is raised so that the transaction can be rolled back and retried. Note: The testing for changes can be done by comparing the values, timestamp or version numbers. Q 79: How can we determine if the data is stale (for example when using optimistic locking)? TI A 79: We can use the following strategy to determine if the data is stale: Adding version numbers
  • 48.
    Find more WWW.ThesisScientist.com EnterpriseJava 105 Add a version number (Integer) to the underlying table. Carry the version number along with any data read into memory (through value object, entity bean etc). Before performing any update compare the current version number with the database version number. If the version numbers are equal update the data and increment the version number. If the value object or entity bean is carrying an older version number, reject the update and throw an exception. Note: You can also do the version number check as part of the update by including the version column in the where clause of the update without doing a prior select. Adding a timestamp to the underlying database table. Comparing the data values. These techniques are also quite useful when implementing data caching to improve performance. Data caches should regularly keep track of stale data to refresh the cache. These strategies are valid whether you use EJB or other persistence mechanisms like JDBC, Hibernate etc. Q 80: What are not allowed within the EJB container? SF A 80: In order to develop reliable and portable EJB components, the following restrictions apply to EJB code implementation: Avoid using static non-final fields. Declaring all static fields in EJB component as final is recommended. This enables the EJB container to distribute instances across multiple JVMs. Avoid starting a new thread (conflicts with EJB container) or using thread synchronization (allow the EJB container to distribute instances across multiple JVMs). Avoid using AWT or Swing functionality. EJBs are server side business components. Avoid using file access/java.io operations. EJB business components are meant to use resource managers such as JDBC to store and retrieve application data. Also deployment descriptors can be used to store <env- entry>. Avoid accepting or listening to socket connections. EJB components are not meant to provide network socket functionality. However the specification lets EJB components act as socket clients or RMI clients. Avoid using the reflection API. This restriction enforces Java security. Can‟t use custom class loaders. Q 81: Discuss EJB container security? SFSE A 81: EJB components operate inside a container environment and rely heavily on the container to provide security. The four key services required for the security are: Identification: In Java security APIs this identifier is known as a principal. Authentication: To prove the identity one must present the credentials in the form of password, swipe card, digital certificate, finger prints etc. Authorisation (Access Control): Every secure system should limit access to particular users. The common way to enforce access control is by maintaining security roles and privileges. Data Confidentiality: This is maintained by encryption of some sort. It is no good to protect your data by authentication if someone can read the password. The EJB specification concerns itself exclusively with authorisation (access control). An application using EJB can specify in an abstract (declarative) and portable way that is allowed to access business methods. The EJB container handles the following actions: Find out the Identity of the caller of a business method.
  • 49.
    Find more WWW.ThesisScientist.com 106Enterprise Java Check the EJB deployment descriptor to see if the identity is a member of a security role that has been granted the right to call this business method. Throw java.rmi.RemoteException if the access is illegal. Make the identity and the security role information available for a fine grained programmatic security check. public void closeAccount() { if (ejbContext.getCallerPrincipal().getName() = “SMITH”) { //… } if (!ejbContext .isCallerInRole(CORPORATE_ ACCOUNT_MANAGER)) { throw new SecurityException(“Not authorized to close this account”); } } Optionally log any illegal access. There are two types of information the EJB developer has to provide through the deployment descriptor. Security roles Method permissions Example: <security-role> <description> Allowed to open and close accounts </description> <role- name>account_manager</role-name> </security-role> <security-role> <description> Allowed to read only </description> <role- name>teller</role-name> </security-role> There is a many-to-many relationship between the security roles and the method permissions. <method-permission> <role- name>teller</role-name> <method> <ejb-name>AccountProcessor</ejb-name> <method-name>findByPrimaryKey</method-name> </method> </method-permission> Just as we must declare the resources accessed in our code for other EJBs that we reference in our code we should also declare the security role we access programmatically to have a fine grained control as shown below. <security-role-ref> <description> Allowed to open and close accounts </description> <role- name>account_manager</role-name> <role-link>executive</role-link> </security-role-ref> There is also many-to-many relationship between the EJB specific security roles that are in the deployment descriptor and the application based target security system like LDAP etc. For example there might be more than one group users and individual users that need to be mapped to a particular EJB security role „account_manager‟. Q 82: What are EJB best practices? BP A 82: Use local interfaces that are available in EJB2.0 if you deploy both the EJB client and the EJB in the same server. Use vendor specific pass-by-reference implementation to make EJB1.1 remote EJBs operate as local.
  • 50.
    Find more WWW.ThesisScientist.com EnterpriseJava 107 [Extreme care should be taken not to affect the functionality by switching the application, which was written and tested in pass-by-reference mode to pass-by-value without analysing the implications and re-testing the functionality. Wrap entity beans with session beans to reduce network calls (refer Q84 in Enterprise section) and promote declarative transactions. Where possible use local entity beans and session beans can be either local or remote. Apply the appropriate EJB design patterns as described in Q83 – Q87 in Enterprise section. Cache ejbHome references to avoid JNDI look-up overhead using service locator pattern. Handle exceptions appropriately (refer Q76, Q77 in Enterprise section). Avoid transaction overhead for non-transactional methods of session beans by declaring transactional attribute as „Supports‟. Choose plain Java object over EJB if you do not want services like RMI/IIOP, transactions, security, persistence, thread safety etc. There are alternative frameworks such as Hibernate, Spring etc. Choose Servlet‟s HttpSession object rather than stateful session bean to maintain client state if you do not require component architecture of a stateful bean. Apply Lazy loading and Dirty marker strategies as described in Q88 in Enterprise section. Session Bean Session Bean (stateful) Entity Bean (stateless) ƒ Tune the pool size to ƒ Tune the pool size to avoid ƒ Tune the pool size to avoid overhead of creation and avoid overhead of overhead of creation and destruction. creation and destruction. destruction. ƒ Use setEntityContext(..) method to cache any bean Use setSessionContext(..) ƒ Set proper time out to avoidƒ specific resources and unsetEntityContext() method to or ejbCreate(..) method to resource congestion. release acquired resources. cache any bean specific ƒ Remove it explicitly from Use lazy-loading to avoid any unnecessary loading ofresources. ƒ client using remove() dependent data. Use dirty marker to avoid unchanged ƒ Release any acquired method. data update. resources like Database ƒ Use „transient‟ variable Commit the data after a transaction completes to reduceconnection etc in ƒ ejbRemove() method where possible to avoid any database calls in between. serialization overhead. ƒ Where possible perform bulk updates, use CMP rather than BMP, Use direct JDBC (Fast-lane-reader) instead of entity beans, use of read-only entity beans etc. Q 83: What is a business delegate? Why should you use a business delegate? DPPI A 83: Questions Q83 – Q88 are very popular EJB questions. Problem: When presentation tier components interact directly with the business services components like EJB, the presentation components are vulnerable to changes in the implementation of business services components. Solution: Use a Business Delegate to reduce the coupling between the presentation tier components and the business services tier components. Business Delegate hides the underlying implementation details of the business service, such as look-up and access details of the EJB architecture. Business delegate is responsible for: Invoking session beans in Session Facade. Acting as a service locator and cache home stubs to improve performance. Handling exceptions from the server side. (Unchecked exceptions get wrapped into the remote exception, checked exceptions can be thrown as an application exception or wrapped in the remote exception. unchecked exceptions do not have to be caught but can be caught and should not be used in the method signature.) Re-trying services for the client (For example when using optimistic locking business delegate will retry the method call when there is a concurrent access.).
  • 51.
    Find more WWW.ThesisScientist.com 108 EnterpriseJava B u s i n e s s D e l e g a t e C l i e n t 1 . u s e s B u s i n e s s D e l e g a t e 4 . u s e s 2 . u s e s B u s i n e s s S e r v i c e E J B E J B L o o k u p S e r v i c e 3 . lo o k u p / c r e a t e Q 84: What is a session façade? DPPI A 84: Problem: Too many method invocations between the client and the server will lead to network overhead, tight coupling due to dependencies between the client and the server, misuse of server business methods due to fine grained access etc. Solution: Use a session bean as a façade to encapsulate the complexities between the client and the server interactions. The Session Facade manages the business objects, and provides a uniform coarse-grained service access layer to clients. Session Facade Without Session Facade With Session Facade l 1 Entitity Bean 1 te cal Session Bean Servlet remo Servlet remote call 2 Entitity Bean 2 remote call 1 (Stateless) (client) (client) Session network network Facadee r mo t e c a ll 3 Entitity Bean 3 ll1 Entitity Bean 1 ac l a c lo local call 2 Entitity Bean 2 lo c al c a ll 3 Entitity Bean 3 Session façade is responsible for Improving performance by minimising fine-grained method calls over the network. Improving manageability by reducing coupling, exposing uniform interface and exposing fewer methods to clients. Managing transaction and security in a centralised manner. Q 85: What is a value object pattern? DPPI A 85: Problem: When a client makes a remote call to the server, there will be a process of network call and serialization of data involved for the remote invocation. If you make fine grained calls there will be performance degradation. Solution: Avoid fine-grained method calls by creating a value object, which will help the client, make a coarse- grained call. V a lu e O b je c t p a tte rn W ith o u t V a lu e O b je c t W ith V a lu e O b je c t S e s s io n B e a n tNam e() S e rv le t etFirsg (c lie n t) g e tS u r n a m e ( ) g e tG e n dg et e r () A ge () W ith o u t v a lu e o b je c t 4 re m o te c a lls a re m a d e to g e t a ll th e re le v a n t in fo S e r v l e t ( c l i e n P e r s o n V a lu e O b je c t ()e m )a rn ( eu tS m e a g tN )s ( e ir der g tF n e ) tG g e ( ge tA g e S e s s io n B e a n g e tP e rs o n In fo () t )
  • 52.
    Find more WWW.ThesisScientist.com W ithv a lu e o b je c t 1 re m o te c a ll a n d 4 lo c a l c a lls a re m a d e to g e t a ll th e re le v a n t in fo .
  • 53.
    Find more WWW.ThesisScientist.com EnterpriseJava 109 Q 86: What is a fast-lane reader? DPPI A 86: Problem: Using Entity beans to represent persistent, read only tabular data incurs performance cost at no benefit (especially when large amount of data to be read). Solution: Access the persistent data directly from the database using the DAO (Data Access Object) pattern instead of using Entity beans. The Fast lane readers commonly use JDBC, Connectors etc to access the read-only data from the data source. The main benefit of this pattern is the faster data retrieval. Fast Lane Reader J2EE Server Web Container EJB Container eal lan Session Bean Entity Bean norm en la l a Servlet rm no (client) Fa stLan en DataSource a e R e ad t L er s a Data Access Object F Use Fast Lane Reader for read only access and the normal lane for read/write access to the DataSource. Q 87: What is a Service Locator? DPPI A 87: Problem: J2EE makes use of the JNDI interface to access different resources like JDBC, JMS, EJB etc. The client looks up for these resources through the JNDI look-up. The JNDI look-up is expensive because the client needs to get a network connection to the server first. So this look-up process is expensive and redundant. Solution: To avoid this expensive and redundant process, service objects can be cached when a client performs the JNDI look- up for the first time and reuse that service object from the cache for the subsequent look-ups. The service locator pattern implements this technique. Refer to diagram below: W ith o u t S e rv ic e L o c a to r S e r v le t (c lie n t - 1 ) lo o k up S e rv le t lookup (c lie n t - 2 ) pu lo k J N D I o S e rv le t (c lie n t - 3 ) W ith o u t s e rv ic e lo c a to r lo o k u p e v e ry tim e fro m th e J N D I S e rv ic e L o c a to r W ith S e rv ic e L o c a to r S e rv le t (c lie n t -1 ) lo o k p S e r vic e u S e rv le t look up L o c a to r lo o k u p firs t tim e o n ly (c lie n t - 2 ) p u k o lo S e rv le t (c lie n t - 3 ) W ith s e rv ic e lo c a to r lo o k u p firs t tim e fro m th e J N D I a n d s e c o n d tim e o n w a rd s lo o k u p fro m th e c a c h e in th e s e rv ic e lo c a to r. J N D I Q 88: Explain lazy loading and dirty marker strategies? DPPI A 88: Lazy Loading: Lazy loading means not creating an object until the first time it is accessed. This technique is useful when you have large hierarchies of objects. You can lazy load some of the dependent objects. You only create the dependent (subordinate) objects only when you need them. If ( this.data = null) { //lazy load data } For a CMP bean the default scenario is set to no lazy loading and the finder method will execute a single SQL select statement against the database. So, for example, with the findAllCustomers() method will retrieve all customer objects with all the CMP fields in each customer object.
  • 54.
    Find more WWW.ThesisScientist.com 110Enterprise Java If you turn on lazy loading then only the primary keys of the objects within the finder are returned. Only when you access the object, the container uploads the actual object based on the primary key. You may want to turn on the lazy loading feature if the number of objects that you are retrieving is so large that loading them all into local cache would adversely affect the performance. (Note: The implementation of lazy loading strategy may vary from container vendor to vendor). Dirty Marker (Store optimisation): This strategy allows us to persist only the entity beans that have been modified. The dependent objects need not be persisted if they have not been modified. This is achieved by using a dirty flag to mark an object whose contents have been modified. The container will check every dependent object and will persist only those objects that are dirty. Once it is persisted its dirty flag will be cleared. (Note: The implementation of dirty marker strategy may vary from container vendor to vendor). Note: If your job requires a very good understanding of EJB 2.x then following books are recommended: Mastering Enterprise JavaBeans – by Ed Roman EJB Design Patterns – by Floyd Marinescu Enterprise - JMS Q 89: What is Message Oriented Middleware? What is JMS? SF A 89: Message Oriented Middleware (MOM) is generally defined as a software infrastructure that asynchronously communicates with other disparate systems through the production and consumption of messages. A message may be a request, a report, or an event sent from one part of an enterprise application to another. Messaging enables loosely coupled distributed communication. A component sends a message to a destination, and the recipient can retrieve the message from the destination. However, the sender and the receiver do not have to be available at the same time in order to communicate and also they are not aware of each other. In fact, the sender does not need to know anything about the receiver; nor does the receiver need to know anything about the sender. The sender and the receiver need to know only what message format and what destination to use. In this respect, messaging differs from tightly coupled technologies, such as Remote Method Invocation (RMI), which requires an application to know a remote application's methods. Message Oriented Middleware (MOM) systems like MQSeries, MQSonic, etc are proprietary systems. Java Message Service (JMS) is a Java API that allows applications to create, send, receive, and read messages in a standard way. Designed by Sun and several partner companies, the JMS API defines a common set of interfaces and associated semantics that allow programs written in the Java programming language to communicate with other messaging implementations (e.g. MQSonic, TIBCO etc). The JMS API minimises the set of concepts a programmer must learn to use messaging products but provides enough features to support sophisticated messaging applications. It also strives to maximise the portability of JMS applications across JMS providers. Companies have spent decades developing their legacy systems. Rather than throwing these systems out, XML can be used in a non-proprietary way to move data from legacy systems to distributed systems like J2EE over the wire-using MOM and JMS. How JMS is different from RPC? Remote Procedure Call (e.g. RMI) JMS Remote Procedure Call (RPC) technologies like RMI With the use of Message Oriented Middleware (MOM), problems attempt to mimic the behaviour of system that runs in one with the availability of subsystems are less of an issue. A process. When a remote procedure is invoked the caller is fundamental concept of MOM is that communications between blocked until the procedure completes and returns control components is intended to be asynchronous in nature. Code that to the caller. This is a synchronized model where process is written to connect the pieces together assumes that there is a is performed sequentially ensuring that tasks are one-way message that requires no immediate response. In other completed in a predefined order. The synchronized nature words, there is no blocking. Once a message is sent the sender of RPC tightly couples the client (the software making the can move on to other tasks; it doesn't have to wait for a call) to the server (the software servicing the call). The response. This is the major difference between RPC and client can not proceed (its blocked) until the server asynchronous messaging and is critical to understanding the responds. The tightly coupled nature of RPC creates advantages offered by MOM systems. highly interdependent systems where a failure on one system has an immediate impact on other systems. In an asynchronous messaging system each subsystem (Customer, Account etc) is decoupled from the other systems. They communicate through the messaging server, so that a failure in one does not impact the operation of the others.
  • 55.
    Find more WWW.ThesisScientist.com Enterprise Java111 Client is blocked while it is being processed. Asynchronous messages also allows for parallel processing i.e. client can continue processing while the previous request is being satisfied. Are messaging applications slow? While there is some overhead in all messaging systems, but this does not mean that the applications that are using messaging are necessarily slow. Messaging systems can achieve a throughput of 100 messages per second depending on the installation, messaging modes (synchronous versus asynchronous, persistent versus non-persistent), and acknowledgment options such as auto mode, duplicates okay mode, and client mode etc. The asynchronous mode can significantly boost performance by multi-tasking. For example: In an Internet based shopping cart application, while a customer is adding items to his/her shopping cart, your application can trigger an inventory checking component, and a customer data retrieval component to execute concurrently. Are messaging applications reliable? This is basically a trade-off between performance and reliability. If reliability is more important then the: Acknowledgment option should be set to automode where once only delivery is guaranteed Message delivery mode should be set to persistent where the MOM writes the messages to a secure storage like a database or a file system to insure that the message is not lost in transit due to a system failure. What are some of the key message characteristics defined in a message header? Characteristic Explanation JMSCorrelationID Used in request/response situations where a JMS client can use the JMSCorrelationID header to associate one message with another. For example: a client request can be matched with a response from a server based on the JMSCorrelationID. JMSMessageID Uniquely identifies a message in the MOM environment. JMSDeliveryMode This header field contains the delivery modes: PERSISTENT or NON_PERSISTENT. JMSExpiration This contains the time-to-live value for a message. If it is set to zero, then a message will never expire. JMSPriority Sets the message priority but the actual meaning of prioritization is MOM vendor dependent. What are the different body types (aka payload types) supported for messages? All JMS messages are read-only once posted to a queue or a topic. Text message: body consists of java.lang.String. Map message: body consists of key-value pairs. Stream message: body consists of streams of Java primitive values, which are accessed sequentially. XML documents make use of this type. Object message: body consists of a Serializable Java object. Byte message: body consists of arbitrary stream of bytes. What is a message broker? A message broker acts as a server in a MOM. A message broker performs the following operations on a message it receives: Processes message header information. Performs security checks and encryption/decryption of a received message. Handles errors and exceptions. Routes message header and the payload (aka message body). Invokes a method with the payload contained in the incoming message (e.g. calling onMessage(..) method on a Message Driven Bean (MDB)). Transforms the message to some other format. For example XML payload can be converted to other formats like HTML etc with XSLT. Q 90: What type of messaging is provided by JMS? SF A 90: Point-to-Point: provides a traditional queue based mechanism where the client application sends a message through a queue to typically one receiving client that receives messages sequentially. A JMS message queue is
  • 56.
    Find more WWW.ThesisScientist.com anadministered object that represents the message destination for the sender and the message source for the receiver.
  • 57.
    Find more WWW.ThesisScientist.com 112Enterprise Java Publish/Subscribe: is a one-to-many publishing model where client applications publish messages to topics, which are in turn subscribed by other interested clients. All subscribed clients will receive each message. Q 91: Discuss some of the design decisions you need to make regarding your message delivery? SFDC A 91: During your design phase, you should carefully consider various options or modes like message acknowledgment modes, transaction modes and delivery modes. For example: for a simple approach you would not be using transactions and instead you would be using acknowledgment modes. If you need reliability then the delivery mode should be set to persistent. This can adversely affect performance but reliability is increased. Design Explanation decision Message Acknowledgement mode and transaction modes are used to determine if a message will be lost or acknowledgm re-delivered on failure during message processing by the target application. Acknowledgment ent options or modes are set when creating a JMS session. modes. InitialContext ic = new InitialContext(…); QueueConnectionFactory qcf = (QueueConnectionFactory)ic.lookup(“AccountConnectionFactory”); QueueConnection qc = qcf.createQueueConnection(); QueueSession session = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); the above code sample, the transaction mode is set to false and acknowledgment mode is set to auto mode. Let us look at acknowledgment modes: AUTO_ACKNOWLEDGE: The messages sent or received from the session are automatically acknowledged. This mode also guarantees once only delivery. If a failure occurs while executing onMessage() method of the destination MDB, then the message is re-delivered. A message is automatically acknowledged when it successfully returns from the onMessage(…) method. DUPS_OK_ACKNOWLEDGE: This is just like AUTO_ACKNOWLEDGE mode, but under rare circumstances like during failure recovery messages might be delivered more than once. If a failure occurs then the message is re-delivered. This mode has fewer overheads than AUTO_ACKNOWLEDGE mode. CLIENT_ACKNOWLEDGE: The messages sent or received from sessions are not automatically acknowledged. The destination application must acknowledge the message receipt. This mode gives an application full control over message acknowledgment at the cost of increased complexity. This can be acknowledged by invoking the acknowledge() method on javax.jms.Message class. Transaction In JMS, a transaction organizes a message or a group of messages into an atomic processing unit. So, if a modes message delivery is failed, then the failed message may be re-delivered. Calling the commit() method commits all the messages the session receives and calling the rollback method rejects all the messages. InitialContext ic = new InitialContext(…); QueueConnectionFactory qcf = (QueueConnectionFactory)ic.lookup(“AccountConnectionFactory”); QueueConnection qc = qcf.createQueueConnection(); QueueSession session = qc.createQueueSession(true, -1); In the above code sample, the transaction mode is set to true and acknowledgment mode is set to -1, which means acknowledgment mode has no use in this mode. Let us look at transaction modes: Message Driven Bean (MDB) with container managed transaction demarcation: An MDB participates in a container transaction by specifying the transaction attributes in its deployment descriptor. A transaction automatically starts when the JMS provider removes the message from the destination and delivers it to the MDB‟s onMessage(…) method. Transaction is committed on successful completion of the onMessage() method. A MDB can notify the container that a transaction should be rolled back by setting the MessageDrivenContext to setRollBackOnly(). When a transaction is rolled back, the message is re- delivered. public void onMessage(Message aMessage) { … If(someCondtionIsTrue) { mdbContext.setRollbackOnly(); } else{ //everything is good. Transaction will be committed automatically on completion of onMessage(..) method. } } Message Driven Bean (MDB) with bean managed transaction demarcation: A MDB chooses not to
  • 58.
    Find more WWW.ThesisScientist.com EnterpriseJava 113 participate in a container managed transaction and the MDB programmer has to design and code programmatic transactions. This is achieved by creating a UserTransaction object from the MDB‟s MessageDrivenContext as shown below and then invoking the commit() and rollback() methods on this UserTransaction object. public void onMessage(Message aMessage) { UserTransaction uT = mdbContext.getUserTransaction(); uT.begin(); …. If(someCondtionIsTrue) { uT.rollback(); } else{ uT.commit(); } } Transacted session: An application completely controls the message delivery by either committing or rolling back the session. An application indicates successful message processing by invoking Session class‟s commit() method. Also it can reject a message by invoking Session class‟s rollback() method. This committing or rollback is applicable to all the messages received by the session. public void process(Message aMessage, QueueSession qs) { …. If(someCondtionIsTrue) { qs.rollback(); } else{ qs.commit(); } … } What happens to rolled-back messages? Rolled back messages are re-delivered based on the re-delivery count parameter set on the JMS provider. The re-delivery count parameter is very important because some messages can never be successful and this can eventually crash the system. When a message reaches its re-delivery count, the JMS provider can either log the message or forward the message to an error destination. Usually it is not advisable to retry delivering the message soon after it has been rolled-back because the target application might still not be ready. So we can specify a time to re-deliver parameter to delay the re-delivery process by certain amount of time. This time delay allows the JMS provider and the target application to recover to a stable operational condition. Care should be taken not to make use of a single transaction when using the JMS request/response paradigm where a JMS message is sent, followed by the synchronous receipt of a reply to that message. This is because a JMS message is not delivered to its destination until the transaction commits, and the receipt of the reply will never take place within the same transaction. Note: when you perform a JNDI lookup for administered objects like connection factories, topics and/or queues, you should use the logical reference java:comp/env/jms as the environment subcontext. It is also vital to release the JMS resources like connection factories, sessions, queues, topics etc when they are no longer required in a try{} and finally{} block. Message What happens, when the messages are with the JMS provider (i.e. MOM) and a catastrophic failure occurs delivery prior to delivering the messages to the destination application? The messages will be lost if they are non- options durable. The message‟s state whether they are lost or not does not depend on acknowledgment modes or transaction modes discussed above. It depends on the delivery mode, which defines whether the message can be durable (aka persistent) or non-durable (aka non-persistent). If you choose the durable delivery mode then the message is stored into a database or a file system by the JMS server before delivering it to the consumer. Durable messages have an adverse effect on performance, but ensure that message delivery is guaranteed. InitialContext ic = new InitialContext(…); QueueConnectionFactory qcf = (QueueConnectionFactory)ic.lookup(“AccountConnectionFactory”); QueueConnection qc = qcf.createQueueConnection(); QueueSession session = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); //senderQueue is an object of type javax.jms.Queue QueueSender sender = session.createSender(senderQueue); Sender.send(message, intDeliveryMode, intPriority, longTimeToLove ); Best practices ƒ A JMS connection represents a TCP/IP connection from the client to the JMS server. A connection is
  • 59.
    Find more WWW.ThesisScientist.com 114Enterprise Java to improve a valuable resource, which should be opened at the appropriate time, should be used concurrently by performance creating and using pool of sessions, and close the connection in a finally{} block when finished. Optimize your JMS sessions with the appropriate acknowledgment mode and transaction mode as discussed above and close your sessions when you are finished with them. Choose your message type (text message, byte message, stream message etc) carefully because the size of a message depends on its type and size can affect performance. For example byte messages takes less space than text messages and for object messages you can reduce the serialization cost by marking some of the variables which need not be sent over the network as transient. Optimize your destinations like queues and topics as follows: Choose a non-durable (aka non-persistent) delivery mode where appropriate. Set time to live parameter appropriately after which the message expires. Where applicable receive messages asynchronously (non-blocking call). If you want to receive messages synchronously you can use one of the following methods on the message consumer: receive(); Æ blocks the call until it receives the next message. receive(long timeout); Æ blocks till a timeout occurs. receiveNoWait();  never blocks. Q 92: Give an example of a J2EE application using Message Driven Bean with JMS? SF A 92: Messgage Driven Beans J2EE Server Web Container EJB Container EJB Container Servlet Session Bean Message DrivenBean (client) ) r s r s r i b e e c h s l i v e b s Message i l e b u D e s u Messagep ht (t o The MessageDrivenBean is the consumer of the message. Topic Enterprise - XML What is XML? And why is XML important? XML stands for eXtensible Markup Language. XML is a grammatical system for constructing custom markup languages for describing business data, mathematical data, chemical data etc. XML loosely couples disparate applications or systems utilizing JMS, Web services etc. XML uses the same building blocks that HTML does: elements, attributes and values. Let‟s look at why XML is important. Scalable: Since XML is not in a binary format you can create and edit files with anything and it‟s also easy to debug. XML can be used to efficiently store small amounts of data like configuration files (web.xml, application.xml, struts-config.xml etc) to large company wide data with the help of XML stored in the database. Fast Access: XML documents benefit from their hierarchical structure. Hierarchical structures are generally faster to access because you can drill down to the section you are interested in. Easy to identify and use: XML not only displays the data but also tells you what kind of data you have. The mark up tags identifies and groups the information so that different information can be identified by different application.
  • 60.
    Find more WWW.ThesisScientist.com EnterpriseJava 115 Stylability: XML is style-free and whenever different styles of output are required the same XML can be used with different style-sheets (XSL) to produce output in XHTML, PDF, TEXT, another XML format etc. Linkability, in-line useability, universally accepted standard with free/inexpensive tools etc Q 93: What is the difference between a SAX parser and a DOM parser? SFPIMI A 93: SAX parser DOM parser A SAX (Simple API for XML) parser does not create any A DOM (Document Object Model) parser creates a tree internal structure. Instead, it takes the occurrences of structure in memory from an input document and then waits components of an input document as events (i.e., event for requests from client. driven), and tells the client what it reads as it reads through the input document. A SAX parser serves the client application always only with A DOM parser always serves the client application with the pieces of the document at any given time. entire document no matter how much is actually needed by the client. A SAX parser, however, is much more space efficient in A DOM parser is rich in functionality. It creates a DOM tree in case of a big input document (because it creates no internal memory and allows you to access any part of the document structure). What's more, it runs faster and is easier to learn repeatedly and allows you to modify the DOM tree. But it is than DOM parser because its API is really simple. But from space inefficient when the document is huge, and it takes a the functionality point of view, it provides a fewer functions, little bit longer to learn how to work with it. which means that the users themselves have to take care of more, such as creating their own data structures. Use SAX parser when Use DOM when ƒ Input document is too big for available memory. ƒ Your application has to access various parts of the When only a part of the document is to be read and we document and using your own structure is just as ƒ complicated as the DOM tree. create the data structures of our own. ƒ Your application has to change the tree very frequently If you use SAX, you are using much less memory andƒ and data has to be stored for a significant amount of time. performing much less dynamic memory allocation. SAX Parser example: Xerces, Crimson etc DOM Parser example: XercesDOM, SunDOM, OracleDOM Use JAXP (Java API for XML Parsing) which enables etc. applications to parse and transform XML documents Use JAXP (Java API for XML Parsing) which enables independent of the particular XML parser. Code can be applications to parse and transform XML documents developed with one SAX parser in mind and later on can be independent of the particular XML parser. Code can be changed to another SAX parser without changing the developed with one DOM parser in mind and later on can be application code. changed to another DOM parser without changing the application code. Q 94: Which is better to store data as elements or as attributes? SF A 94: A question arising in the mind of XML/DTD designers is whether to model and encode certain information using an element, or alternatively, using an attribute. The answer to the above question is not clear-cut. But the general guideline is: Using an element: <book><title>Lord of the Rings</title>...</book>: If you consider the information in question to be part of the essential material that is being expressed or communicated in the XML, put it in an element Using an attribute: <book title=" Lord of the Rings "/>: If you consider the information to be peripheral or incidental to the main communication, or purely intended to help applications process the main communication, use attributes. The principle is data goes in elements and metadata goes in attributes. Elements are also useful when they contain special characters like “<”, “>”, etc which are harder to use in attributes. Q 95: What is XPATH? What is XSLT/XSL/XSL-FO/XSD/DTD etc? What is JAXB? What is JAXP? SF A 95:
  • 61.
    Find more WWW.ThesisScientist.com 116Enterprise Java What Explanation Example is XML XML stands for eXtensible Markup Language Sample.xml <?xml version="1.0"?> <note> <to>Peter</to> <from>Paul</from> <title>Invite</title> <content language=”English”>Not Much</content> < content language=”Spanish”>No Mucho</content > </note> DTD DTD stands for Document Type Definition. XML provides Sample.dtd an application independent way of sharing data. With a DTD, independent groups of people can agree to use a <!ELEMENT note (to, from, title, content)> common DTD for interchanging data. Your application can <!ELEMENT to (#PCDATA)> use a standard DTD to verify that data that you receive <!ELEMENT from (#PCDATA)> from the outside world is valid. You can also use a DTD to <!ELEMENT title (#PCDATA)> verify your own data. So the DTD is the building blocks or <!ELEMENT content (#PCDATA)> schema definition of the XML document. <!ATTLIST content language CDATA #Required> XSD XSD stands for Xml Schema Definition, which is a Sample.xsd successor of DTD. So XSD is a building block of an XML document. <?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" If you have DTD then why use XSD you may ask? targetNamespace="http://www.w3schools.com" xmlns="http://www.w3schools.com" XSD is more powerful and extensible than DTD. XSD has: elementFormDefault="qualified"> • Support for simple and complex data types. <xs:element name="note"> • Uses XML syntax. So XSD are extensible just like <xs:complexType> XML because they are written in XML. <xs:sequence> • Better data communication with the help of data <xs:element name="to" type="xs:string"/> types. For example a date like 03-04-2005 will be <xs:element name="from" type="xs:string"/> interpreted in some countries as 3 rd of April 2005 and <xs:element name="title" type="xs:string"/> in some other countries as 04 th March 2005. <xs:element name="content" type="xs:string"/> </xs:sequence> </xs:complexType> <xs:attribute name="language" type=”xs:string” use=”Required” /> </xs:element> </xs:schema> XSL XSL stands for eXtensible Stylesheet Language. The XSL To convert the Sample.xml file to a XHTML file let us apply the consists of 3 parts: following Sample.xsl through XALAN parser. • XSLT: Language for transforming XML documents Sample.xsl from one to another. <?xml version="1.0"?> • XPath: Language for defining the parts of an XML <xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl"> document. <xsl:template match="/"> <xsl:apply-templates select="note " /> • XSL-FO: Language for formatting XML documents. </xsl:template> For example to convert an XML document to a PDF <xsl:template match="note">document etc. <html> XSL can be thought of as a set of languages that can : <head> <title><xsl:value-of • Define parts of an XML select="content/@language"> • Transform an XML document to XHTML (eXtensible </title> </head>Hyper Text Markup Language) document. </html>• Convert an XML document to a PDF document. </xsl:template> • Filter and sort XML data. </xsl:stylesheet> You get the following output XHTML file: Xalan (From Apache)XSLT processor example: Sample.xhtml <html> PDF Processor example: FOP (Formatting Objects <head> Processor from Apache) <title>English</title>
  • 62.
    Find more WWW.ThesisScientist.com EnterpriseJava 117 </head> </html> Now to convert the Sample.xml into a PDF file apply the following FO (Formatting Objects) file Through the FOP processor. Sample.fo <?xml version="1.0" encoding="ISO-8859-1"?> <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format"> <fo:layout-master-set> <fo:simple-page-master master-name="A4"> </fo:simple-page-master> </fo:layout-master-set> <fo:page-sequence master-reference="A4"> <fo:flow flow-name="xsl-region-body"> <fo:block> <xsl:value-of select="content[@language='English']"> </fo:block> </fo:flow> </fo:page-sequence> </fo:root> which gives a basic Sample.pdf which has the following line Not Much XPath Xml Path Language, a language for addressing parts of an As per Sample.xsl XML document, designed to be used by both XSLT and XPointer. We can write both the patterns (context-free) and <xsl:template match=”content[@language=‟English‟]”> expressions using the XPATH Syntax. XPATH is also used ……… in XQuery. <td><xsl:value-of select=”content/@language” /></td> JAXP Stands for Java API for XML Processing. This provides a DOM example using JAXP: common interface for creating and using SAX, DOM, and XSLT APIs in Java regardless of which vendor‟s DocumentBuilderFactory dbf = implementation is actually being used (just like the JDBC, DocumentBuilderFactory.newInstance(); JNDI interfaces). JAXP has the following packages: DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new File("xml/Test.xml")); NodeList nl = doc.getElementsByTagName("to"); Node n = nl.item(0); System.out.println(n.getFirstChild().getNodeValue()); SAX example using JAXP: SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); SAXExample se = new SAXExample(); sp.parse(new File("xml/Sample.xml"),se); where SAXExample.Java code snippet public class SAXExample extends DefaultHandler { public void startElement( String uri, String localName, String qName, Attributes attr) throws SAXException { System.out.println("--->" + qName); } ... }
  • 63.
    Find more WWW.ThesisScientist.com 118Enterprise Java JAXP The DefaultHandler implements ContentHandler, DTDHandler, EntityResolver, ErrorHandler SAXParser implements XSLT example using JAXP: Factory Content StreamSource xml = S A X R e a d e r S A X E x a m p l e Handler Error new StreamSource(new File("/xml/Sample.xml")); StreamSource xsl = new StreamSource( HandlerSAXParser new File("xml/Sample.xsl")); DTD StreamResult result = XML Handler new StreamResult(new File("xml/Sample.xhtml")); Entity Sample. TransformerFactory tf = Resolver xml TransformerFactory.newInstance(); Transformer t = tf.newTransformer(xsl); t.transform(xml, result); DocumentBuilder This gives you Sample.xhtml Factory Document <html> <head> XML (DOM) Document <title>English</title> noteSample. </head>Builder xml to from </html> Transformer Factory Source Transformer Result sample. sample. xml xhtml Transformation instructions sample.xsl javax.xml.parsers  common interface for different vendors of SAX, DOM parsers). org.xml.sax  Defines basic SAX API. org.w3c.dom  Defines Document Object Model and its componenets. javax.xml.transform  Defines the XSLT API which allows you to transform XML into other forms like PDF, XHTML etc. Required JAR files are jaxp.jar, dom.jar, xalan.jar, xercesImpl.jar. JAXB Stands for Java API for XML Binding. This standard Lets look at some code: defines a mechanism for writing out Java objects as XML (marshalling) and for creating Java objects from For binding: XMLstructures (unmarshalling). (You compile a class description to create the Java classes, and use those xjc.sh –p com.binding sample.xsd –d work classes in your application.) -p identifies the package for the generated Java files (ie *.Java) -d option identifies the target. Unmarshalling the XML document: JAXBContext jc = JAXBContext.newInstance( “com.binding”); Unmarshaller um = jc.createUnmarshaller(); Object o = um.unMarshall( new File(“/xml/”));
  • 64.
    Find more WWW.ThesisScientist.com Enterprise Java119 JAXB XML schema Sample.xsd r g en i c l i p j d x n mi o b c Java files (*.java interfaces & implementations) c a v a j Java class files *.class u s e Application Java content XML unmarshall Objects Sample. JAXB note xml API marshall to from Note n = (Note) n; System.out.println(n.getFrom().getContent().get(0)); System.out.println(n.getTo().getContent().get(0)); Now to modify the in memory object content: n. getFrom().getContent().set(0, “newValue”); Marshalling the change back to different XML file: Marshaller m = jc.createMarshaller(); FileOutputStream fos = new FileOutputStream( new File(“/xml/SampleNew.xml”)); m.marshall(n, fos); Enterprise – SQL, Tuning and O/R mapping Q 96: Explain inner and outer joins? SF A 96: Joins allow database users to combine data from one table with data from one or more other tables (or views, or synonyms). Tables are joined two at a time making a new table containing all possible combinations of rows from the original two tables. Lets take an example (syntax vary among RDBMS): Joins and Set operations in Relational Databases Inner join Left outer join Right outer join Full outer join
  • 65.
    Find more WWW.ThesisScientist.com 120Enterprise Java Employees table Id firstname Surname state 1001 John Darcy NSW 1002 Peter Smith NSW 1003 Paul Gregor NSW 1004 Sam Darcy VIC Executives table Id firstname Surname state 1001 John Darcy NSW 1002 Peter Smith NSW 1005 John Gregor WA Inner joins: Chooses the join criteria using any column names that happen to match between the two tables. The example below displays only the employees who are executives as well. SELECT emp.firstname, exec.surname FROM employees emp, executives exec WHERE emp.id = exec.id; The output is: Firstname surname John Darcy Peter Smith Left Outer joins: A problem with the inner join is that only rows that match between tables are returned. The example below will show all the employees and fill the null data for the executives. SELECT emp.firstname, exec.surname FROM employees emp left join executives exec ON emp.id = exec.id; On oracle SELECT emp.firstname, exec.surname FROM employees emp, executives exec where emp.id = exec.id(+); The output is: Firstname surname John Darcy Peter Smith Paul Sam Right Outer join: A problem with the inner join is that only rows that match between tables are returned. The example below will show all the executives and fill the null data for the employees. SELECT emp.firstname, exec.surname FROM employees emp right join executives exec ON emp.id = exec.id; On oracle SELECT emp.firstname, exec.surname FROM employees emp, executives exec WHERE emp.id(+) = exec.id; The output is: Firstname surname John Darcy Peter Smith Gregor Full outer join: To cause SQL to create both sides of the join SELECT emp.firstname, exec.surname FROM employees emp full join executives exec ON emp.id = exec.id; On oracle SELECT emp.firstname, exec.surname FROM employees emp, executives exec WHERE emp.id = exec.id (+)
  • 66.
    Find more WWW.ThesisScientist.com EnterpriseJava 121 UNION SELECT emp.firstname, exec.surname FROM employees emp, executives exec WHERE emp.id(+) = exec.id Note: Oracle9i introduced the ANSI compliant join syntax. This new join syntax uses the new keywords inner join, left outer join, right outer join, and full outer join, instead of the (+) operator. The output is: Firstname surname John Darcy Paul Peter Smith Sam Gregor Self join: A self-join is a join of a table to itself. If you want to find out all the employees who live in the same city as employees whose first name starts with “Peter”, then one way is to use a sub-query as shown below: SELECT emp.firstname, emp.surname FROM employees emp WHERE city IN (SELECT city FROM employees where firstname like „Peter‟) The sub-queries can degrade performance. So alternatively we can use a self-join to achieve the same results. On oracle SELECT emp.firstname, emp.surname FROM employees emp, employees emp2 WHERE emp.state = emp2.state AND emp2.firstname LIKE 'Peter' The output is: Firstname Surname John Darcy Peter Smith Paul Gregor Q 97: Explain a sub-query? How does a sub-query impact on performance? SFPI A 97: It is possible to embed a SQL statement within another. When this is done on the WHERE or the HAVING statements, we have a subquery construct. What is subquery useful for? It is used to join tables and there are cases where the only way to correlate two tables is through a subquery. SELECT emp.firstname, emp.surname FROM employees emp WHERE emp.id NOT IN (SELECT id FROM executives); There are performance problems with sub-queries, which may return NULL values. The above sub-query can be re-written as shown below by invoking a correlated sub-query: SELECT emp.firstname, emp.surname FROM employees emp WHERE emp.id NOT EXISTS (SELECT id FROM executives); The above query can be re-written as an outer join for a faster performance as shown below: SELECT emp.firstname, exec.surname FROM employees emp left join executives exec on emp.id = exec.id AND exec.id IS NULL; The above execution plan will be faster by eliminating the sub-query. Q 98: What is normalization? When to denormalize? DCPI A 98: Normalization is a design technique that is widely used as a guide in designing relational databases. Normalization is essentially a two step process that puts data into tabular form by removing repeating groups and then removes duplicated data from the relational tables (Additional reading recommended). Redundant data wastes disk space and creates maintenance problems. If data that exists in more than one place must be changed, the data must be changed in exactly the same way in all locations which is time consuming and prone to errors. A change to a customer address is much easier to do if that data is stored only in the Customers table and nowhere else in the database.
  • 67.
    Find more WWW.ThesisScientist.com 122Enterprise Java Inconsistent dependency is a database design that makes certain assumptions about the location of data. For example, while it is intuitive for a user to look in the Customers table for the address of a particular customer, it may not make sense to look there for the salary of the employee who calls on that customer. The employee's salary is related to, or dependent on, the employee and thus should be moved to the Employees table. Inconsistent dependencies can make data difficult to access because the path to find the data may not be logical, or may be missing or broken. First normal form Second Normal Form Third Normal Form A database is said to be in First A database is in Second Normal Form A database is in Third Normal Form when Normal Form when all entities when it is in First Normal Form plus it is in Second Normal Form and each have a unique identifier or key, every non-primary key column in the column that isn't part of the primary key and when every column in every table must depend on the entire primary doesn't depend on another column that table contains only a single value key, not just part of it, assuming that the isn't part of the primary key. and doesn't contain a repeating primary key is made up of composite group or composite field. columns. When to denormalize? Normalize for accuracy and denormalize for performance. Typically, transactional databases are highly normalized. This means that redundant data is eliminated and replaced with keys in a one-to-many relationship. Data that is highly normalized is constrained by the primary key/foreign key relationship, and thus has a high degree of data integrity. Denormalized data, on the other hand, creates redundancies; this means that it's possible for denormalized data to lose track of some of the relationships between atomic data items. However, since all the data for a query is (usually) stored in a single row in the table, it is much faster to retrieve. Q 99: How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables? SF A 99: One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Many-to-Many relationships are implemented using join table with the keys from both the tables forming the composite primary key of the junction table. Q 100: How can you performance tune your database? PI A 100: Denormalize your tables where appropriate. Proper use of index columns: An index based on numeric fields is more efficient than an index based on character columns. Reduce the number of columns that make up a composite key. Proper partitioning of tablespaces and create a special tablespace for special data types like CLOB, BLOB etc. Data access performance can be tuned by using stored procedures to crunch data in the database server to reduce the network overhead and also caching data within your application to reduce the number of accesses. Q 101: How will you map objects to a relational database? How will you map class inheritance to relational data model? DC A 101: Due to impedance mismatch between object and relational technology you need to understand the process of mapping classes (objects) and their relationships to tables and relationships between them in a database. Classes represent both behaviour and data whereas relational database tables just implement data. Database schemas have keys (primary keys to uniquely identify rows and foreign keys to maintain relationships between rows) whereas object schema does not have keys and instead use references to implement relationships to other objects. Let us look at some basic points on mapping:
  • 68.
    Find more WWW.ThesisScientist.com EnterpriseJava 123 Object to Relational (O/R) mapping of class inheritance structure Map class hierarchy to a single database table Employee Employee -EmployeeId (PK) -EmployeeId (PK) -EmployeeType -IsPermanent -Name -IsContractor -Salary Refactored -IsSubContractor -Rate -Name Class diagram -Period -Salary -Rate -Period Address Employee Employee Map each class to its own table * 1 -name -streetname -EmployeeId (PK) -address -Name +getName() Permanent Contractor Permanent Contractor -salary -rate -EmployeeId (PK) -EmployeeId (PK) +getSalary() +getRate() -Salary -Contract SubContractor SubContractor -period -EmployeeId (PK) +calculateTotal() -Period Map each concrete class to its own table ContractorPermanent -EmployeeId (PK)-EmployeeId (PK) -Name-Name -Contract-Salary SubContractor -EmployeeId (PK) -Name -Period Classes map to tables in a way but not always directly. An attribute of a class can be mapped to zero or more columns in a database. Not all attributes are persistent. Some attributes of an object are objects itself. For example an Employee object has an Address object as an attribute. This is basically an association relationship between two objects (i.e. Employee and Address). This is a recursive relationship where at some point the attribute will be mapped to zero or more columns. In this example attributes of the Address class will be mapped zero or more columns. In its simple form an attribute maps to a single column whereas each has same type (ie attribute is a string and column is a char, or both are dates etc). When you implement mapping with different types (attribute is a currency and column is a float) then you will need to be able to convert them back and forth. How do you map inheritance class structure to relational data model? Relational databases do not support inheritance. Class inheritance can be mapped to relational tables as follows: Map class hierarchy to single database table: The whole class hierarchy can be stored in a single table by adding an additional column named “EmployeeType”. The column “EmployeeType” will hold the values “Permanent”, “Contract” and “SubContract”. New employee types can be added as required. Although this approach is straightforward it tends to break when you have combinations like an employee is of type both “Contractor” and “SubContractor”. So when you have combinations, you can use refactored table by replacing type code column “EmployeeType” with boolean values such as isPermanent, isContractor and isSubContractor. Map each class to its own table: You create one table per class. The data for a permanent employee is stored in two tables (Employee and Permanent), therefore to retrieve this data you need to join these two tables. To support additional employee type say a Contractor, add a new table.
  • 69.
    Find more WWW.ThesisScientist.com 124Enterprise Java Map each concrete class to its own table: You create one table per concrete class. There are tables corresponding to each class like Permanent, Contractor and SubContractor. So join is not required. To support additional employee type, add a new table. So which approach to use? Easiest approach is to have one table per hierarchy and easy to refactor. If you need a “pure design approach” then use one table per class approach. Try to stay away from one table per concrete class approach because it makes refactoring difficult by copying data back and forth between tables. No approach is ideal for all situations. Another option for mapping inheritance into relational database is to take a generic meta -data driven approach. This approach supports all forms of mapping. In this approach, value of a single attribute will be stored as a row in a table called “Value”. So, to store 5 attributes you need 5 rows in “Value” table. You will have a table called “Class” where class names are stored, a table called “Inheritance” where subclass and superclass information is stored, a table called “Attributes” where class attributes are stored and an “AttributeType” lookup table. Q 102: What is a view? Why will you use a view? What is an aggregate function? Etc. SFPI A 102: Question Explanation What is view? Why use a view? View is a precompiled SQL query, which is used to select data from one or more tables. A view is like a table but it doesn‟t physically take any space (ie not materialised). Views are used for ƒ Providing inherent security by exposing only the data that is needed to be shown to the end user. ƒ Enabling re-use of SQL statements. ƒ Allows changes to the underlying tables to be hidden from clients, aiding maintenance of the database schema (i.e. encapsulation). Views with multiple joins and filters can dramatically degrade performance because views contain no data and any retrieval needs to be processed. The solution for this is to use materialised views or create de-normalised tables to store data. This technique is quite handy in overnight batch processes where a large chunk of data needs to be processed. Normalised data can be read and inserted into some temporary de- normalised table and processed with efficiency. Explain aggregate SQL functions? SQL provides aggregate functions to assist with the summarisation of large volumes of data. We‟ll look at functions that allow us to add and average data, count records meeting specific criteria and find the largest and smallest values in a table. ORDERID FIRSTNAME SURNAME QTY UNITPRICE 1001 John Darcy 25 10.5 1002 Peter Smith 25 10.5 1003 Sam Gregory 25 10.5 SELECT SUM(QTY) AS Total FROM Orders; The output is: Total = 75 SELECT AVG(UnitPrice * QTY) As AveragePrice FROM Orders; The output is: AveragePrice = 262.50 If we inserted another row to the above table: ORDERID FIRSTNAME SURNAME QTY UNITPRICE 1004 John Darcy 20 10.50 SELECT FIRSTNAME,SUM(QTY) FROM orders GROUP BY FIRSTNAME HAVING SUM(QTY)>25; The output is: John 45 Explain INSERT, UPDATE, and INSERT statements can be carried out several ways: DELETE statements? INSERT INTO ORDERS values (1004, 'John', 'Darcy', 20, 10.50);
  • 70.
    Find more WWW.ThesisScientist.com EnterpriseJava 125 The above statement is fine but the one below is recommended since it is less ambiguous and less prone to errors. INSERT INTO ORDERS (orderid, firstname, surname, qty, unitprice) values (1005, 'John', 'Darcy', 20, 10.50); We can also use INSERT with the SELECT statements as shown below INSERT into NEW_ORDERS (orderid, firstname, surname, qty, unitprice) SELECT orderid, firstname, surname, qty, unitprice FROM orders WHERE orderid = 1004; UPDATE statement allows you to update a single or multiple statements. UPDATE ORDERS set firstname='Peter', surname='Piper' WHERE orderid=1004; Also can have more complex updates like UPDATE supplier SET supplier_name = ( SELECT customer.name FROM customers WHERE customers.customer_id = supplier.supplier_id) WHERE EXISTS (SELECT customer.name FROM customers WHERE customers.customer_id = supplier.supplier_id); DELETE statements allow you to remove records from the database. DELETE FROM ORDERS WHERE orderid=1004; We can clear the entire table using TRUNCATE TABLE employees; When running UPDATE/DELETE care should be taken to include WHERE clause otherwise you can inadvertently modify or delete records which you do not intend to UPDATE/DELETE. How can you compare a part of You can use wild card characters like: the name rather than the entire name? • * ( % in oracle)  Match any number of characters. • ? ( _ in oracle)  Match a single character. To find all the employees who has “au”: SELECT * FROM employees emp WHERE emp.firstname LIKE „%au%‟; How do you get distinct entries The SELECT statement in conjunction with DISTINCT lets you select a set of distinct from a table? values from a table in a database. SELECT DISTINCT empname FROM emptable How can you find the total number Use the COUNT key word: of records in a table? SELECT COUNT(*) FROM emp WHERE age>25 What's the difference between a Both primary key and unique key enforce uniqueness of the column on which they are primary key and a unique key? defined. But by default primary key creates a clustered index on the column, whereas unique creates a non-clustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only. What are constraints? Explain Constraints enable the RDBMS enforce the integrity of the database automatically, different types of constraints. without needing you to create triggers, rule or defaults. Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY What is an index? What are the The books you read have indexes, which help you to go to a specific key word faster. types of indexes? How many The database indexes are similar. clustered indexes can be created on a table? What are the Indexes are of two types. Clustered indexes and non-clustered indexes. When you
  • 71.
    Find more WWW.ThesisScientist.com 126Enterprise Java advantages and disadvantages of create a clustered index on a table, all the rows in the table are stored in the order of the creating separate index on each clustered index key. So, there can be only one clustered index per table. Non-clustered column of a table? indexes have their own storage separate from the table data storage. The row located could be the RowID or the clustered index key, depending up on the absence or presence of clustered index on the table. If you create an index on each column of a table, it improves the query performance, as the query optimizer can choose from all the existing indexes to come up with an efficient execution plan. At the same time, data modification operations (such as INSERT, UPDATE, and DELETE) will become slow, as every time data changes in the table, all the indexes need to be updated. Another disadvantage is that, indexes need disk space, the more indexes you have, more disk space is used. Enterprise - RUP & UML Q 103: What is RUP? SD A 103: Rational Unified Process (RUP) is a general framework that can be used to describe a development process. The software development cycle has got 4 phases in the following order Inception, Elaboration, Construction, and Transition. R a tio n a l U n ifie d P ro c e s s Disciplines(verticalaxis) B u s in e s s M o d e llin g R e q u ire m e n ts A n a lys is & D e s ig n Im p le m e n ta tio n T e s t D e p lo ym e n t C o n fig & C h a n g e m g m t P ro je c t m g m t E n v iro n m e n t P H A S E S In c e p tio n e la b o r a tio n c o n s tr u c tio n tr a n s itio n In c e p tio n # 1 E la b # 1 E la b # 2 C o n C o n C o n T ra n s itio n # 1 # 1 # 2 # 3 IT E R A T IO N S P H A S E S / IT E R A T IO N S (H o riz o n ta l a x is ) The core of the phases is state-based, and the state is determined by what fundamental questions you are trying to answer: Inception - do you and the customer have a shared understanding of the system? Elaboration - do you have baseline architecture to be able to build the system? Construction - are you developing a product? Transition - are you trying to get the customer to take ownership of the system? RUP is based on a few important philosophies and principles: A software project team should plan ahead. It should know where it is going. It should capture project knowledge in a storable and extensible form. The best practices of RUP involve the following major 5 properties: Best practice property Description Use case driven Interaction between the users and the system. Architecture centric Based on architecture with clear relationships between architectural components. Iterative The problem and the solution are divided into more manageable smaller pieces, where each
  • 72.
    Find more WWW.ThesisScientist.com EnterpriseJava 127 iteration will be addressing one of those pieces. Incremental Each iteration builds incrementally on the foundation built in the previous iteration. Controlled Control with respect to process means you always know what to do next; control with respect to management means that all deliverables, artifacts, and code are under configuration management. Q 104: Explain the 4 phases of RUP? SD A 104: RUP Phases Construction INCEPTION ELABORATION TRANSITION Iter 1 Iter 2 Iter 3 Iter 4 Iter 5 Iter 6 Inception: During the inception phase, you work out the business case for the project. You also will be making a rough cost estimate and return on investment. You should also outline the scope and size of the project. The fundamental question you ask at the end of this phase: do you and the customer have a shared understanding of the system? Elaboration: At this stage you have the go ahead of the project however only have vague requirements. So at this stage you need to get a better understanding of the problem. Some of the steps involved are: What is it you are actually going to build? How are you going to build it? What technology are you going to use? Analysing and dealing with requirement risks, technological risks, skill risks, political risks etc. Develop a domain model, use case model and a design model. The UML techniques can be used for the model diagrams (e.g. class diagrams, sequence diagrams etc). An important result of the elaboration phase is that you have a baseline architecture. This architecture consists of: A list of use cases depicting the requirements. The domain model, which captures your understanding of the domain with the help of UML class diagrams. Selection of key implementation technology and how they fit together. For example: Java/J2EE with JSP, Struts, EJB, XML, etc. The fundamental question you ask at the end of this phase: do you have a baseline architecture to be able to build the system? Construction: In this phase you will be building the system in a series of iterations. Each iteration is a mini project. You will be performing analysis, design, unit testing, coding, system testing, and integration testing for the use cases assigned to each iteration. The iterations within the construction phase are incremental and iterative. Each iteration builds on the use cases developed in the previous iterations. The each iteration will involve code rewrite, refactoring, use of design patterns etc. The basic documentation required during the construction phase is: A class diagram and a sequence diagram. Some text to pull the diagrams together.
  • 73.
    Find more WWW.ThesisScientist.com 128Enterprise Java If a class has complex life cycle behaviour then a state diagram is required. If a class has a complex computation then an activity diagram is required. The fundamental question you ask at the end of this phase: do you have a developed product? Transition: During this phase you will be delivering the finished code regularly. During this phase there is no coding to add functionality unless it is small and essential. There will be bug fixes, code optimisation etc during this phase. An example of a transition phase is that the time between the beta release and the final release of a product. The fundamental question you ask at the end of this phase: are you trying to get the customer to take ownership of the developed product or system? Q 105: What are the characteristics of RUP? Where can you use RUP? SD A 105: RUP is based on a few important philosophies and principles like planning ahead, knowing where the process is heading and capturing the project in storable and extensible manner. It is largely based on OO analysis and design, and use case driven etc. Iterative and incremental development as oppose to waterfall approach, which hides problems. Architecture centric approach. RUP is more suited for larger teams of 50-100 people. RUP can also be used as an agile (i.e. lightweight) process for smaller teams of 20-30 people, or as a heavy weight process for larger teams of 50-100 people. Extreme Programming (XP) can be considered as a subset of RUP. At the time of writing, the agile (i.e lightweight) software development process is gaining popularity and momentum across organizations. Several methodologies fit under this agile development methodology banner. All these methodologies share many characteristics like iterative and incremental development, test driven development, stand up meetings to improve communication, automatic testing, build and continuous integration of code etc. Refer Q136 in Enterprise Java section. Q 106: Why is UML important? SDDC A 106: The more complicated the underlying system, the more critical the communication among everyone involved in developing and deploying the software. UML is a software blueprint language for analysts, designers and developers. UML provides a common vocabulary for the business analysts, architects, developers etc. UML is applicable to the Object Oriented problem solving. UML begins with a model; A model is an abstraction of the underlying problem. The domain is the actual world from which the problem comes. The model consists of objects. The objects interact with each other by sending and receiving messages. The objects are characterised by attributes and operations (behaviours). The values of an object‟s attributes determine its state. The classes are the blueprints (or like templates) for objects. A class wraps attributes and methods into a single distinct entity. The objects are the instances of classes. Q 107: What are the different types of UML diagrams? SDDC A 107: Use case diagrams: Depicts the typical interaction between external users (actors) and the system. The emphasis is on what a system does rather than how it does it. A use case is a summary of scenarios for a single task or goal. An actor is responsible for initiating a task. The connection between actor and use case is a communication association. Capturing use cases is one of the primary tasks of the elaboration phase of RUP. In its simplest usage, you capture a use case by talking to your users and discussing the various things they might want to do with the system. When to use „use case‟ diagrams? Determining user requirements. New use cases often generate new requirements. Communicating with clients. The simplicity of the diagram makes use case diagrams a good way for designers and developers to communicate with clients. Generating test cases. Each scenario for the use case may suggest a suite of test cases.
  • 74.
    Find more WWW.ThesisScientist.com EnterpriseJava 129 U s e c a s e d i a g r a m a s s o c i a t i o n * R e g i s t r a r E n r o l l i n U n i v e r s i < < i n c l u d e > > E n r o l l i n s e m i n a r t y a s s o c i a t i o n < < e x t e n d > > S t u d e n t p e r f o r m s e c u r i t y i n h e r i t a n c e E n r o l l f a m i l y i n h e r i t a n c e c h e c k m e m b e r s N o t e : < < e x t e n d > > r e l a t i o n s h i p i s c o n d i t i o n a l . Y o u d o a s s o c i a t i o n n o t k n o w i f o r w h e n e x t e n d i n g u s e c a s e w i l l b e i n v o k e d . < < i n c l u d e > > r e l a t i o n s h i p i s s i m i l a r t o a p r o c e d u r e c a l l . i n h e r i t a n c e : e x t e n d s t h e b e h a v i o r o f t h e I n t e r n a t i o n a l S t u d e n t p a r e n t u s e c a s e o r a c t o r . Class diagrams: Class diagram technique is vital within Object Oriented methods. Class diagrams describe the types of objects in the system and the various static relationships among them. Class diagrams also show the attributes and the methods. Class diagrams have the following possible relationships: Association: A relationship between instances of 2 classes. Aggregation: An association in which one class belongs to a collection (does not always have to be a collection. You can also have cardinality of “1”). This is a part of a whole relationship where the part can exist without the whole. For example: A line item is whole and the products are the parts. If a line item is deleted then the products need not be deleted. Composition: An association in which one class belongs to a collection (does not always have to be a collection. You can also have cardinality of “1”). This is a part of a whole relationship where the part cannot exist without the whole. If the whole is deleted then the parts are deleted. For example: An Order is a whole and the line items are the parts. If an order is deleted then all the line items should be deleted as well (ie cascade deletes). Generalization: An inheritance link indicating that one class is a superclass of the other. The Generalization expresses the “is a” relationship whereas the association, aggregation and composition express the “has a” relationship. Dependency: A dependency is a weak relationship where one class requires another class. The dependency expresses the “uses” relationship. For example: A domain model class uses a utility class like Formatter etc. C lass D iagram a s s o c ia tio n c o m p o s itio n d e p e n d e n c y O rd e rD e ta ilC u s to m e r O rd e r -LineId -order : O rder 1 * -lineItem s : List 1 1 ..* -product : P roduct + o p e ra tio n 1 () -com m ents g e n e ra liz a tio n «utility» 1 F o rm a tte r a g g re g a tio n S ta n d a rd O rd e r C u s to m O rd e r * -specialD etails +form atD ecim al() +form atC urrency() P ro d u c t -productC ode -productD esc -unitP rice When to use class diagrams? Class diagrams are the backbone of Object Oriented methods. So they are used frequently.
  • 75.
    Find more WWW.ThesisScientist.com 130Enterprise Java Class diagrams can have a conceptual perspective and an implementation perspective. During the analysis draw the conceptual model and during implementation draw the implementation model. Package diagrams: To simplify complex class diagrams you can group classes into packages. P a c k a g e D i a g r a m A c c o u n t i n g O r d e r i n g d e p e n d e n c y d e p e n d e n c y C u s t o m e r When to use package diagrams? Package diagrams are vital for large projects. Object diagrams: Object diagrams show instances instead of classes. They are useful for explaining some complicated objects in detail about their recursive relationships etc. O b je c t D ia g r a m O b je c t D ia g r a m C la s s D ia g r a m o b je c t n a m ep h y s ic s M a th s : D e p a r tm e n t C la s s n a m e 1 0 . . * im p r o v e c la r ity p h y s ic s : D e p a rtm e n t m a th : D e p a r tm e n t D e p a r t m e n t p u r e M a th : D e p a rtm e n t a p p lie d M a th : D e p a rtm e n t R e c u r s iv e c la s s d ia g ra m d iffic u lt to fu lly u n d e r s ta n d S h o w s th e d e ta ils o f th e r e c u rs iv e o b je c t re la tio n s h ip When to use object diagrams? Object diagrams are a vital for large projects. They are useful for explaining structural relationships in detail for complex objects. Sequence diagrams: Sequence diagrams are interaction diagrams which detail what messages are sent and when. The sequence diagrams are organized according to time. The time progresses as you move from top to bottom of the diagram. The objects involved in the diagram are shown from left to right according to when they take part. S e q u e n c e D ia g r a m c lie n t a n O r d e r : O r d e r a n E n tr y : O r d e r E n tr y c h e c k if s u ffic ie n t d e ta ils m a k e A n O r d e r ( ) m a k e A n O r d e r ( ) a r e a v a ila b le fo r e a c h lin e I te m it e r a t io n [ f o r e a c h ... ] ( ) h a s S u ffic ie n tD e ta ils ( ) c o n fir m : C o n f ir m a tio n p r in tC o n fir m a tio n ( ) N o te : E a c h v e r t ic a l d o tt e d lin e is a lin e a r e c a lle d t h e a c t iv a t io n b a r lif e lin e . E a c h a r r o w is a m e s s a g e . T h e r e c t a n g u la r b o x e s o n t h e lif e w h ic h r e p r e s e n ts t h e d u r a t io n o f e x e c u t io n o f m e s s a g e .
  • 76.
    Find more WWW.ThesisScientist.com EnterpriseJava 131 Collaboration diagrams: Collaboration diagrams are also interaction diagrams. Collaboration diagrams convey the same message as the sequence diagrams. But the collaboration diagrams focus on the object roles instead of the times at which the messages are sent. The collaboration diagrams use the decimal sequence numbers as shown in the diagram below to make it clear which operation is calling which other operation, although it can be harder to see the overall sequence. The top- level message is numbered 1. The messages at the same level have the same decimal prefix but different suffixes of 1, 2 etc according to when they occur. Collaboration Diagram client object 1.1:makeAnOrder() message sequence number 1.1.1: makeAnOrder() * 1.1.1.2 : hasSufficientDetails() anOrder : Order anEntry : OrderEntry confirm : Confirmation 1 self-link 1.1.1.1: for each (iteration) When to use interaction diagrams? When you want to look at behaviour of several objects within a single use case. If you want to look at a single object across multiple use cases then use statechart diagram as described below. State chart diagrams: Objects have behaviour and state. The state of an object is depends on its current activity or condition. This diagram shows the possible states of the object and the transitions that cause a change in its state. S ta te c h a r t D ia g r a m / g e t a n ite m / a ll ite m s a v a ila b le C h e c k in g s ta te D is p a tc h in g s ta te / s o m e ite m s n o t in s to c k / d e liv e r / ite m s re c e iv e d w a itin g s ta te D e liv e re d s ta te When to use statechart diagram? Statechart diagrams are good at describing the behaviour of an object across several use cases. But they are not good at describing the interaction or collaboration between many objects. Use interaction and/or activity diagrams in conjunction with a statechart diagram. Use it only for classes that have complex state changes and behaviour. For example: the User Interface (UI) control objects, Objects shared by multi-threaded programs etc.
  • 77.
    Find more WWW.ThesisScientist.com 132Enterprise Java Activity diagram: This is really a fancy flow chart. The activity diagram and statechart diagrams are related in a sense that statechart diagram focuses on object undergoing a transition process and an activity diagram focuses on the flow of activities involved in a single transition process. Activity Diagram Order placement department dispatch department swim lane start check next item get first item activity join / All item s in stock dispatch all items / som e item s not in stock W ait for items to arrive in stock place an order with the supplier receive the order and enter into stock In domain modelling it is imperative that the diagram conveys which object (or class) is responsible for each activity. Activity diagrams can be divided into object swimlanes that determine which object is responsible for which activity. The swimlanes are quite useful because they combine the activity diagram‟s depiction of logic with the interaction diagram‟s depiction of responsibility. A single transition comes out of each activity, connecting to the next activity. A transition may join or fork. When to use activity diagrams? The activity and statechart diagrams are generally useful to express complex operations. The great strength of activity diagrams is that they support and encourage parallel behaviour. The activity and statechart diagrams are beneficial for workflow modelling with multi-threaded programming. Component and Deployment diagrams: A component is a code module. Component diagrams are physical diagrams analogous to a class diagram. The deployment diagrams show the physical configuration of software and hardware components. The physical hardware is made up of nodes. Each component belongs to a node. Component and Deployment Diagram Ratailer J2EE Server Wholesaler J2EE application server Order Component Dispatch Component Order Component OrderIF DispathIF OrderIF
  • 78.
    Find more WWW.ThesisScientist.com EnterpriseJava 133 Q 108: What is the difference between aggregation and composition? SD DC A 108: Aggregation Composition Aggregation: An association in which one class Composition: An association in which one class belongs to belongs to another class or a collection. This is a part another class a collection. This is a part of a whole relationship of a whole relationship where the part can exist where the part cannot exist without the whole. If the whole is without the whole. For example: A line item is whole deleted then the parts are deleted. For example: An Order is a a line item is deletedand the products are the parts. If whole and the line items are the parts. If an order is deleted then all then the products need not be deleted. (no cascade the line items should be deleted as well (i.e. cascade deletes in delete in database terms) database terms). Aggregations are not allowed to be circular. In a garbage-collected language like Java, The whole has the responsibility of preventing the garbage collector to prematurely collect the part by holding reference to it. Q 109: What is the difference between a collaboration diagram and a sequence diagram? SD DC A 109: You can automatically generate one from the other. Sequence Diagram Collaboration Diagram The emphasis is on the sequence. The emphasis is on the object roles Reference: The above section on RUP & UML is based on the book UML Distilled by Martin Fowler and Kendall Scott. If you would like to have a good understanding of UML & RUP, then this book is recommended. Enterprise - Struts Struts is a Web-based user interface framework, which has been around for a few years. It is a matured and proven framework, which has been used in many J2EE projects. While Struts has been demonstrating its popularity, there is an emerging framework called JavaServer Faces (JSF) gaining lots of momentum and popularity. Like Struts, JSF provides Web application life cycle management through a controller servlet, and like Swing, JSF provides a rich component model complete with event handling and component rendering. So JSF can be considered as a combination of Struts frame work and Java Swing user interface framework. Refer Q19 – Q20 in Emerging Technologies/Frameworks section for JSF. Q 110: Give an overview of Struts? SFDP A 110: Struts is a framework with set of cooperating classes, servlets and JSP tags that make up a reusable MVC 2 design. S T R U T S O v e r v ie w t s e u q e r P T T .H 1 C l i e n t ( B R O W S E R ) 6 . H T T Pre s p o n s e F r o n t C o n tr o l l e r 2. D i (S e rvle t ) sp atc h s t r u t s - c o n f ig .x m l Foprward4. V i e w 5 . g e t th r o u g h T a g ( JS P ) A c ti o n (c a lls b u s in e s s lo g ic ) SetInstantiate/ 3. M o d e l ( F o r m b e a n s ) Client (Browser): A request from the client browser creates an HTTP request. The Web container will respond to the request with an HTTP response, which gets displayed on the browser.
  • 79.
    Find more WWW.ThesisScientist.com 134Enterprise Java Controller (ActionServlet class and Request Processor class): The controller receives the request from the browser, and makes the decision where to send the request based on the struts-config.xml. Design pattern: Struts controller uses the command design pattern by calling the Action classes based on the configuration file struts-config.xml and the RequestProcessor class‟s process() method uses template method design pattern (Refer Q11 in How would you go about … section) by calling a sequence of methods like: processPath(request, response) Æ read the request URI to determine path element. processMapping(request,response) Æ use the path information to get the action mapping processRoles(request,respose,mapping) Æ Struts Web application security which provides an authorization scheme. By default calls request.isUserInRole(). For example allow /addCustomer action if the role is executive. <action path=”/addCustomer” roles=”executive”> processValidate(request,response,form,mapping) Æ calls the vaildate() method of the ActionForm. processActionCreate(request,response,mapping)Æ gets the name of the action class from the “type” attribute of the <action> element. processActionPerform(req,res,action,form,mapping) Æ This method calls the execute method of the Action class which is where business logic is written. Business Logic (Action class): The Servlet dispatches the request to Action classes, which act as a thin wrapper to the business logic (The actual business logic is carried out by either EJB session beans and/or plain Java classes). The action class helps control the workflow of the application. (Note: The Action class should only control the workflow and not the business logic of the application). The Action class uses the Adapter design pattern (Refer Q11 in How would you go about … section). ActionForm class: Java representation of HTTP input data. They can carry data over from one request to another, but actually represent the data submitted with the request. View (JSP): The view is a JSP file. There is no business or flow logic and no state information. The JSP should just have tags to represent the data on the browser. ActionServlet class is the controller part of the MVC implementation and is the core of the framework. It processes user requests, determines what the user is trying to achieve according to the request, pulls data from the model (if necessary) to be given to the appropriate view, and selects the proper view to respond to the user. As discussed above ActionServlet class delegates the grunt of the work to the RequestProcessor and Action classes. The ActionForm class maintains the state for the Web application. ActionForm is an abstract class, which is subclassed for every input form model. The struts-config.xml file controls, which HTML form request maps to which ActionForm. The Action class is a wrapper around the business logic. The purpose of the Action class is to translate the HttpServletRequest to the business logic. To use the Action class, subclass and overwrite the execute() method. The actual business logic should be in a separate package or EJB to allow reuse of business logic in protocol independent manner (ie the business logic should be used not only by HTTP clients but also by WAP clients, EJB clients, Applet clients etc). The ExceptionHandler can be defined to execute when the Action class‟s execute() method throws an Exception. For example <global-exceptions> <exception key="my.key" type="java.io.IOException" handler="my.ExceptionHandler"/> </global-exceptions> When an IOException is thrown then it will be handled by the execute() method of the my.ExceptionHandler class. The struts-config.xml configuration information is translated into ActionMapping, which are put into the ActionMappings collection. Further reading is recommended for more detailed understanding.
  • 80.
    Find more WWW.ThesisScientist.com EnterpriseJava 135 Q 111: What is a synchronizer token pattern in Struts or how will you protect your Web against multiple submissions? DC DP A 111: Web designers often face the situation where a form submission must be protected against duplicate or multiple submissions. This situation typically occurs when the user clicks on submit button more than once before the response is sent back or client access a page by returning to the previously book marked page. The simplest solution that some sites use is that displaying a warning message “Wait for a response after submitting and do not submit twice. In the client only strategy, a flag is set on the first submission and from then onwards the submit button is disabled based on this flag. Useful in some situations but this strategy is coupled to the browser type and version etc. For a server-based solution the J2EE pattern synchroniser token pattern can be applied. The basic idea is to: Set a token in a session variable on the server side before sending the transactional page back to the client. The token is set on the page as a hidden field. On submission of the page first check for the presence of a valid token by comparing the request parameter in the hidden field to the token stored in the session. If the token is valid continue processing otherwise take other alternative action. After testing the token must be reset to null. The synchroniser token pattern is implemented in Struts. How do we implement the alternate course of action when the second clicks on submit button will cancel the response from the first click. The thread for the first click still runs but has no means of sending the response back to the browser. This means the transaction might have gone through without notifying the user. The user might get the impression that transaction has not gone through. Struts support for synchronisation comes in the form of: ActionServlet.saveToken(HttpRequest) and ActionServlet.isTokenValid(HttpRequest) etc Q 112: How do you upload a file in Struts? SF A 112: In JSP page set the code as shown below: CO <html:form action="upload.do" enctype="multipart/form-data" name="fileForm" type="FileForm" scope="session"> Please select the file that you would like to upload: <html:file property="file" /> <html:submit /> </html:form> In the FormBean set the code as shown below: public class FileForm extends ActionForm { private FormFile file; public void setFile(FormFile file){ this.file = file; } public FormFile getFile(){ return file; } } Q 113: Are Struts action classes thread-safe? SFCI A 113: No. Struts action classes are not thread-safe. Struts action classes are cached and reused for performance optimization at the cost of having to implement the action classes in a thread-safe manner.
  • 81.
    Find more WWW.ThesisScientist.com 136Enterprise Java Q 114: How do you implement internationalization in Struts? SF A 114: Internationalization is built into Struts framework. In the JSP page set the code as shown below: CO <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %> <html:html locale="true"> <head> <title>i18n</title> </head> <body> <h2><bean:message key="page.title"/></h2> </body> </html:html> Now we need to create an application resource file named ApplicationResource.properties. page.title=Thank you for visiting! Now in Italian, create an application resource file named ApplicationResource_it.properties. page.title=Grazie per la vostra visita! Finally, add reference to the appropriate resource file in the struts-config.xml. Q 115: What is an action mapping in Struts? How will you extend Struts? SF A 115: An action mapping is a configuration file (struts-config.xml) entry that, in general, associates an action name with an action. An action mapping can contain a reference to a form bean that the action can use, and can additionally define a list of local forwards that is visible only to this action. How will you extend Struts? Struts is not only a powerful framework but also very extensible. You can extend Struts in one or more of the following ways: PlugIn: Define your own PlugIn class if you want to execute some init() and destroy() methods during the application startup and shutdown respectively. Some services like loading configuration files, initialising applications like logging, auditing, etc can be carried out in the init() method. RequestProcessor: You can create your own RequestProcessor by extending the Struts RequestProcessor. For example you can override the processRoles(req, res, mapping) in your extended class if you want to query the LDAP server for the security authorization etc. ActionServlet: You can extend the ActionServlet class if you want to execute your business logic at the application startup or shutdown or during individual request processing. You should take this approach only when the above mentioned approaches are not feasible. Q 116: What design patterns are used in Struts? DP A 116: Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command design pattern (Refer Q11 in How would you go about section) and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern (Refer Q11 in How would you go about section). Struts also implement the following J2EE design patterns Service to Worker (Refer Q25 in Enterprise section). Dispatcher View (Refer Q25 in Enterprise section). Composite View (Struts Tiles) (Refer Q25 in Enterprise section) Front Controller (Refer Q24 in Enterprise section). View Helper (Refer Q25 in Enterprise section). Synchronizer Token (Refer Q111 in Enterprise section).
  • 82.
    Find more WWW.ThesisScientist.com EnterpriseJava 137 Enterprise - Web and Application servers Q 117: What application servers, Web servers, LDAP servers, and Database servers have you used? A 117: Web Servers Apache, Microsoft IIS, Netscape, Domino etc Application Servers IBM Websphere, BEA Weblogic, Apache Tomcat, Borland Enterprise Server, Fujitsu Interstage, JBoss, ATG Dynamo etc LDAP Servers IPlanet‟s directory server, SiemensDirX etc Database Servers IBM DB2, Oracle, SQL Server, Sybase, Informix Q 118: What is the difference between a Web server and an application server? SF A 118: In general, an application server prepares data for a Web server -- for example, gathering data from databases, applying relevant business rules, processing security checks, and/or storing the state of a user‟s session. The term application server may be misleading since the functionality isn‟t limited to applications. Its role is more as retriever and manager of data and processes used by anything running on a Web server. In the coming age of Web services, application servers will probably have an even more important role in managing service oriented components. One of the reasons for using an application server is to improve performance by off-loading tasks from a Web server. When heavy traffic has more users, more transactions, more data, and more security checks then more likely a Web server becomes a bottleneck. Web Server Application Server Supports HTTP protocol. When a Web server receives an Exposes business logic and dynamic content to a client HTTP request, it responds with an HTTP response, such through various protocols such as HTTP, TCP/IP, IIOP, JRMP as sending back an HTML page (static content) or etc. delegates the dynamic response generation to some other program such as CGI scripts or Servlets or JSPs in an application server. Uses various scalability and fault-tolerance techniques. Uses various scalability and fault-tolerance techniques. In addition provides resource pooling, component life cycle management, transaction management, messaging, security etc. Q 119: What is a virtual host? SF A 119: The term virtual host refers to the practice of maintaining more than one server on one machine. They are differentiated by their host names. You can have name based virtual hosts and IP address based virtual hosts. For example A name-based "virtual host" has a unique domain name, but the same IP address. For example, www.company1.com and www.company2.com can have the same IP address 192.168.0.10 and share the same Web server. We can configure the Web server as follows: NameVirtualHost 192.168.0.10 <VirtualHost 192.168.0.10> ServerName www.company1.com DocumentRoot /web/company1 </VirtualHost> <VirtualHost 192.168.0.10> ServerName www.company2.com DocumentRoot /web/company2 </VirtualHost> In this scenario, both www.company1.com and www.company2.com are registered with the standard domain name service (DNS) registry as having the IP address 192.168.0.10. A user types in the URL http://www.company1.com/hello.jsp in their browser. The user's computer resolves the name
  • 83.
    Find more WWW.ThesisScientist.com 138Enterprise Java www.company1.com to the IP address 192.168.0.10. The Web server on the machine that has the IP address 192.168.0.10, so it receives the request. The Web server determines which virtual host to use by matching the request URL It gets from an HTTP header submitted by the browser with the “ServerName” parameter in the configuration file shown above. Name-based virtual hosting is usually easier, since you have to only configure your DNS server to map each hostname to a single IP address and then configure the Web server to recognize the different hostnames as discussed in the previous paragraph. Name-based virtual hosting also eases the demand for scarce IP addresses limited by physical network connections [but modern operation systems supports use of virtual interfaces, which are also known as IP aliases]. Therefore you should use name-based virtual hosting unless there is a specific reason to choose IP-based virtual hosting. Some reasons why you might consider using IP- based virtual hosting: Name-based virtual hosting cannot be used with SSL based secure servers because of the nature of the SSL protocol. Some operating systems and network equipment implement bandwidth management techniques that cannot differentiate between hosts unless they are on separate IP addresses. IP based virtual hosts are useful, when you want to manage more than one site (like live, demo, staging etc) on the same server where hosts inherit the characteristics defined by your main host. But when using SSL for example, a unique IP address is necessary. For example in development environment when using the test client and the server on the same machine we can define the host file as shown below: UNIX user: /etc/hosts Windows user: C:WINDOWSSYSTEM32DRIVERSETCHOSTS localhost www.company1.com www.company2.com [Reference: http://httpd.apache.org/docs/1.3/vhosts/] Q 120: What is application server clustering? SI A 120: An application server cluster consists of a number of application servers loosely coupled on a network. The server cluster or server group is generally distributed over a number of machines or nodes. The important point to note is that the cluster appears as a single server to its clients. The goals of application server clustering are: Scalability: should be able to add new servers on the existing node or add new additional nodes to enable the server to handle increasing loads without performance degradation, and in a manner transparent to the end users. Load balancing: Each server in the cluster should process a fair share of client load, in proportion to its processing power, to avoid overloading of some and under utilization of other server resources. Load distribution should remain balanced even as load changes with time. High availability: Clients should be able to access the server at almost all times. Server usage should be transparent to hardware and software failures. If a server or node fails, its workload should be moved over to other servers, automatically as fast as possible and the application should continue to run uninterrupted. This method provides a fair degree of application system fault-tolerance. After failure, the entire load should be redistributed equally among working servers of the system. [Good read: Uncover the hood of J2EE clustering by Wang Yu on http://www.theserverside.com ] Q 121: Explain Java Management Extensions (JMX)? SF A 121: JMX framework can improve the manageability of your application by
  • 84.
    Find more WWW.ThesisScientist.com EnterpriseJava 139 Monitoring your application for performance problems, critical events, error condition statistics, etc. For example you can be notified if there is a sudden increase in traffic or sudden drop in performance of your website. Making your application more controllable and configurable at runtime by directly exposing application API and parameters. For example you could switch your database connection to an alternate server. You can also change the level of debugging and logging within the application without stopping the server. By interfacing JMX to your hardware, database server and application server, health checks can be performed of your infrastructure. Q 122: Explain some of the portability issues between different application servers? SI A 122: Transaction isolation levels, lazy loading and dirty marker strategies for EJB, class loading visibility etc. Enterprise - Best practices and performance considerations Q 123: Give some tips on J2EE application server performance tuning? PI A 123: Set the Web container threads, which will be used to process incoming HTTP requests. The minimum size should be tuned to handle the average load of the container and maximum should be tuned to handle the peak load. The maximum size should be less than or equal to the number of threads in your Web server. When an EJB is called from a servlet or another EJB within the same JVM (i.e. same application server) then performance can be improved by running EJBs in pass-by-reference mode as oppose to pass-by- value which is the default mode. Care should be taken to test the application properly before going into production because some valid applications may not work correctly when pass-by-reference setting is switched on. Application servers maintain a pool of JDBC resources so that a new connection does not need to be created for each transaction. Application servers can also cache your prepared statements to improve performance. So you can tune the minimum and maximum size of these pools. Tune your initial heap size for the JVM so that the garbage collector runs at a suitable interval so that it does not cause any unnecessary overhead. Adjust the value as required to improve performance. Set the session manager settings appropriately based on following guidelines: Set the appropriate value for in memory session count. Reduce the session size. Don‟t enable session persistence unless required by your application. Invalidate your sessions when you are finished with them by setting appropriate session timeout. Calls to EJB from a separate JVM are handled by ORB (Object Request Broker). ORB uses a pool of threads to handle these requests. The thread pool size should be set appropriately to handle average and peak loads. If a servlet or JSP file is called frequently with identical URL parameters then they can be dynamically cached to improve performance. Turn the application server tracing off unless required for debugging. Some application servers support lazy loading and dirty marker strategies with EJB to improve performance. Q 124: Explain some of the J2EE best practices? BP A 124:
  • 85.
    Find more WWW.ThesisScientist.com 140Enterprise Java Recycle your valuable resources by either pooling or caching. You should create a limited number of resources and share them from a common pool (e.g. pool of threads, pool of database connections, pool of objects etc). Caching is simply another type of pooling where instead of pooling a connection or object, you are pooling remote data (database data) and placing it in the memory (using Hashtable etc). Avoid embedding business logic in a protocol dependent manner like in JSPs, HttpServlets, Struts action classes etc. This is because your business logic should be not only executed by your Web clients but also required to be shared by various GUI clients like Swing based stand alone application, WAP clients etc. Automate the build process with tools like Ant, CruiseControl, and Maven etc. In an enterprise application the build process can become quite complex and confusing. Build test cases first (i.e. Test Driven Development (TDD), refer section Emerging Technologies) using tools like JUnit. Automate the testing process and integrate it with build process. Separate HTML code from the Java code: Combining HTML and Java code in the same source code can make the code less readable. Mixing HTML and scriplet will make the code extremely difficult to read and maintain. The display or behaviour logic can be implemented as a custom tags by the Java developers and Web designers can use these Tags as the ordinary XHTML tags. It is best practice to use multi-threading and stay away from single threaded model of the servlet unless otherwise there is a compelling reason for it. Shared resources can be synchronized or used in read-only manner or shared values can be stored in a database table. Single threaded model can adversely affect performance. Apply the following JSP best practices: Place data access logic in JavaBeans: The code within the JavaBean is readily accessible to other JSPs and Servlets. Factor shared behaviour out of Custom Tags into common JavaBeans classes: The custom tags are not used outside JSPs. To avoid duplication of behaviour or business logic, move the logic into JavaBeans and get the custom tags to utilize the beans. Choose the right “include” mechanism: What are the differences between static and a dynamic include? Using includes will improve code reuse and maintenance through modular design. Which one to use? Refer Q31 in Enterprise section. Use style sheets (e.g. css), template mechanism (e.g. struts tiles etc) and appropriate comments (both hidden and output comments). If you are using EJBs apply the EJB best practices as described in Q82 in Enterprise section. Use the J2EE standard packaging specification to improve portability across Application Servers. Use proven frameworks like Struts, Spring, Hibernate, JSF etc. Apply appropriate proven J2EE design patterns to improve performance and minimise network communications cost (Session façade pattern, Value Object pattern etc). Batch database requests to improve performance. For example Connection con = DriverManager.getConnection(……). Statement stmt = con.createStatement(). stmt.addBatch(“INSERT INTO Address…………”); stmt.addBatch(“INSERT INTO Contact…………”); stmt.addBatch(“INSERT INTO Personal”); int[] countUpdates = stmt.executeBatch(); Use “PreparedStatements” instead of ordinary “Statements” for repeated reads. Avoid resource leaks by Closing all database connections after you have used them. Clean up objects after you have finished with them especially when an object having a long life cycle refers to a number of objects with short life cycles (you have the potential for memory leak).
  • 86.
    Find more WWW.ThesisScientist.com EnterpriseJava 141 Poor exception handling where the connections do not get closed properly and clean up code that never gets called. You should put clean up code in a finally {} block. Handle and propagate exceptions correctly. Decide between checked and unchecked (i.e RunTime exceptions) exceptions. Q 125: Explain some of the J2EE best practices to improve performance? BPPI A 125: In short manage valuable resources wisely and recycle them where possible, minimise network overheads and serialization cost, and optimise all your database operations. Manage and recycle your valuable resources by either pooling or caching. You should create a limited number of resources and share them from a common pool (e.g. pool of threads, pool of database connections, pool of objects etc). Caching is simply another type of pooling where instead of pooling a connection or object, you are pooling remote data (database data), and placing it in memory (using Hashtable etc). Unused stateful session beans must be removed explicitly and appropriate idle timeout should be set to control stateful session bean life cycle. Use effective design patterns to minimise network overheads (Session facade, Value Object etc Refer Q84, Q85 in Enterprise section), use of fast-lane reader pattern for database access (Refer Q86 in Enterprise section). Caching of retrieved JNDI InitialContexts, factory objects (e.g. EJB homes) etc. using the service locator design pattern, which reduces expensive JNDI access with the help of caching strategies. Minimise serialization costs by marking references (like file handles, database connections etc), which do not required serialization by declaring them „transient‟ (Refer Q19 in Java section). Use pass-by-reference where possible as opposed to pass by value. Set appropriate timeouts: for the HttpSession objects, after which the session expires, set idle timeout for stateful session beans etc. Improve the performance of database operations with the following tips: Database connections should be released when not needed anymore, otherwise there will be potential resource leakage problems. Apply least restrictive but valid transaction isolation level. Use JDBC prepared statements for overall database efficiency and for batching repetitive inserts and updates. Also batch database requests to improve performance. When you first establish a connection with a database by default it is in auto-commit mode. For better performance turn auto-commit off by calling the connection.setAutoCommit(false) method. Where appropriate (you are loading 100 objects into memory but use only 5 objects) lazy load your data to avoid loading the whole database into memory using the virtual proxy pattern. Virtual proxy is an object, which looks like an object but actually contain no fields until when one of its methods is called does it load the correct object from the database. Where appropriate eager load your data to avoid frequently accessing the database every time over the network. Enterprise – Logging, testing and deployment Q 126: Give an overview of log4J? SF A 126: Log4j is a logging framework for Java. Log4J is designed to be fast and flexible. Log4J has 3 main components which work together to enable developers to log messages: Loggers [was called Category prior to version 1.2] Appenders Layout
  • 87.
    Find more WWW.ThesisScientist.com 142Enterprise Java Logger: The foremost advantage of any logging API like log4J, apache commons logging etc over plain System.out.println is its ability to disable certain log statements while allowing others to print unhindered. Loggers are hierarchical. The root logger exists at the top of the hierarchy. The root logger always exists and it cannot be retrieved by name. The hierarchical nature of the logger is denoted by “.” notation. For example the logger “java.util” is the parent of child logger “java.util.Vector” and so on. Loggers may be assigned priorities such as DEBUG, INFO, WARN, ERROR and FATAL. If a given logger is not assigned a priority, then it inherits the priority from its closest ancestor. The logging requests are made by invoking one of the following printing methods of the logger instance: debug(), info(), warn(), error(), fatal(). Appenders and Layouts: In addition to selectively enabling and disabling logging requests based on the logger, the log4J allows logging requests to multiple destinations. In log4J terms the output destination is an appender. There are appenders for console, files, remote sockets, JMS, etc. One logger can have more than one appender. A logging request for a given logger will be forwarded to all the appenders in that logger plus the other appenders higher in the hierarchy. In addition to the output destination the output format can be categorised as well. This is accomplished by associating layout with an appender. The layout is responsible for formatting the logging request according to user‟s settings. Sample configuration file: #set the root logger priority to DEBUG and its appender to App1 log4j.rootLogger=DEBUG, App1 #App1 is set to a console appender log4j.appender.App1=org.apache.log4j.ConsoleAppender #appender App1 uses a pattern layout log4j.appender.App1.layout=org.apache.log4j.PatternLayout. log4j.appender.App1.layout.ConversionPattern=%-4r [%t] %-5p %c %x -%m%n # Print only messages of priority WARN or above in the package com.myapp log4j.Logger.com.myapp=WARN XML configuration for log4j is available, and is usually the best practise. Q 127: How do you initialize and use Log4J? SFCO A 127: public class MyApp { //Logger is a utility wrapper class to be written with appropriate printing methods static Logger log = Logger.getLogger (MyApp.class.getName()); public void my method() { if(log.isDebugEnabled()) log.debug(“This line is reached………………………..” + var1 + “-” + var2); ) } } Q 128: What is the hidden cost of parameter construction when using Log4J? SFPI A 128: Do not use in frequently accessed methods or loops: CO log.debug (“Line number” + intVal + “ is less than ” + String.valueOf(array[i])); The above construction has a performance cost in frequently accessed methods and loops in constructing the message parameter, concatenating the String etc regardless of whether the message will be logged or not. Do use in frequently accessed methods or loops: CO If (log.isDebugEnabled()) { log.debug (“Line number” + intVal + “ is less than ” + String.valueOf(array[i])); }
  • 88.
    Find more WWW.ThesisScientist.com EnterpriseJava 143 The above construction will avoid the parameter construction cost by only constructing the message parameter when you are in debug mode. But it is not a best practise to place log.isDebugEnabled() around all debug code. Q 129: What is the test phases and cycles? SD A 129: Unit tests (e.g. JUnit etc, carried out by developers). There are two popular approaches to testing server-side classes: mock objects, which test classes by simulating the server container, and in-container testing, which tests classes running in the actual server container. If you are using Struts framework, StrutsTestCase for JUnit allows you to use either approach, with very minimal impact on your actual unit test code. System tests or functional tests (carried out by business analysts and/or testers). Integration tests (carried out by business analysts, testers, developers etc). Regression tests (carried out by business analysts and testers). Stress volume tests or load tests (carried out by technical staff). User acceptance tests (UAT – carried out by end users). Each of the above test phases will be carried out in cycles. Refer Q13 in How would you go about… section for JUnit, which is an open source unit-testing framework. Q 130: Brief on deployment environments you are familiar with? A 130: Differ from project team to project team [Hint] : Application environments where “ear” files get deployed. Development box: can have the following instances of environments in the same machine (need not be clustered). Development environment Æ used by developers. System testing environment Æ used by business analysts. Staging box: can have the following instances of environments in the same machine (preferably clustered servers with load balancing) Integration testing environment Æ used for integration testing, user acceptance testing etc. Pre-prod environment Æ used for user acceptance testing, regression testing, and load testing or stress volume testing (SVT). [This environment should be exactly same as the production environment]. Production box: Production environment Æ live site used by actual users. Data environments (Database) Note: Separate boxes [not the same boxes as where applications (i.e. ear files) are deployed] Development box (database). Used by applications on development and system testing environments. Separate instances can be created on the same box for separate environments like development and system testing. Staging Box (database) Used by applications on integration testing and user acceptance testing environments. Separate instances can be created on the same box for separate environments. Production Box (database) Live data used by actual users of the system.
  • 89.
    Find more WWW.ThesisScientist.com 144Enterprise Java Enterprise - Personal Q 131: Tell me about yourself or about some of the recent projects you have worked with? What do you consider your most significant achievement? Why do you think you are qualified for this position? Why should we hire you and what kind of contributions will you make? A 131: [Hint:] Pick your recent projects and give a brief overview of it. Also it is imperative that during your briefing that you demonstrate how you applied your skills and knowledge in some of the following key areas and fixed any issues. Design Concepts: Refer Q02, Q03, Q19, Q20, Q21, Q91, Q98, and Q101. Design Patterns: Refer Q03, Q24, Q25, Q83, Q84, Q85, Q86, Q87, Q88 and Q111. Performance issues: Refer Q10, Q16, Q45, Q46, Q97, Q98, Q100, Q123, and Q125. Memory issues: Refer Q45 and Q93 Multi-threading (Concurrency issues): Refer Q16, Q34, and Q113 Exception Handling: Refer Q76 and Q77 Transactional issues: Refer Q43, Q71, Q72, Q73, Q74, Q75 and Q77. Security issues: Refer Q23, Q58, and Q81 Scalability issues: Refer Q20, Q21, Q120 and Q122. Best practices: Refer Q10, Q16, Q39, Q40, Q46, Q82, Q124, and Q125 Refer Q66 – Q72 in Java section for frequently asked non-technical questions. Q 132: Have you used any load testing tools? A 132: Rational Robot, JMeter, LoadRunner, etc. Q 133: What source control systems have you used? SD A 133: CVS, VSS (Visual Source Safe), Rational clear case etc. Refer Q13 in How would you go about section…. for CVS. Q 134: What operating systems are you comfortable with? SD A 134: NT, Unix, Linux, Solaris etc Q 135: Which on-line technical resources do you use to resolve any design and/or development issues? A 135: http://www.theserverside.com, http://www.javaworld.com, http://www-136.ibm.com/developerworks/Java/, http://java.sun.com/, www.javaperformancetuning.com etc Enterprise – Software development process Q 136: What software development processes/principles are you familiar with? SD A 136: Agile (i.e. lightweight) software development process is gaining popularity and momentum across organizations. Agile software development manifesto Æ [Good read: http://www.agilemanifesto.org/principles.html]. Highest priority is to satisfy the customer. Welcome requirement changes even late in development life cycle. Business people and developers should work collaboratively. Form teams with motivated individuals who produce best designs and architectures.
  • 90.
    Find more WWW.ThesisScientist.com EnterpriseJava 145 Teams should be pro-active on how to become more effective without becoming complacent. Quality working software is the primary measure of progress. Why is iterative development with vertical slicing used in agile development? Your overall software quality can be improved through iterative development, which provides you with constant feedback. Traditional Vs Agile approach Traditional approach scop e 1 2 Business Layer technica l mileston e milestone Data Layer Data Layer project time Agile (light w eight )approach Present Presentatio sc op e ation 1 n Layer 2Layer tech nical Busines iterat ion Business iteratio n s layesr Data L ayer layesr Data Layer project time Presentation Layer Business Layer Data Layer Presentation Layer Business Layer Data Layer milestone3iteration3 With the tradional approach, Say for example w e have a fundamental flaw in the data layer, if this flaw gets only picked up after the milestone 3, then there w ill be lot of rew ork to be done to the business and the presentation layer. This is the major draw back w ith the traditional development approach w here there is no vertical slicing. As you can see w ith the agileiterative approach, a vertical slice is built for each iteration. So any fundamental flaw in design or coding can be picked up early and rectified. Even deployment and testing w ill be carried out in vertical slices. Several methodologies fit under this agile development methodology banner. All these methodologies share many characteristics like iterative and incremental development, test driven development, stand up meetings to improve communication, automatic testing, build and continuous integration of code etc. Among all the agile methodologies XP is the one which has got the most attention. Different companies use different flavours of agile methodologies by using different combinations of methodologies. How does vertical slicing influence customer perception? With the iterative and incremental approach, customer will be comfortable with the progress of the development as opposed to traditional big bang approach. TradionalVsAgileperceivedfunctionality As far as the developer is concerned As far as the developer is concerned 65% of coding has been completed and Traditional 65% of coding has been completed but Agile from the customer's view 65% of the from the customer's view only 20% of functionality has been completed. So the functionality has been completed the customer is happy. Presentation Layer PresentationLayer BusinessLayer BusinessLayer DataLayer DataLayer EXtreme Programming [XP] Æ simple design, pair programming, unit testing, refactoring, collective code ownership, coding standards, etc. Refer Q10 in “How would you go about…” section. XP has four key values: Communication, Feedback, Simplicity and Courage. It then builds up some tried and tested practices and techniques. XP has a strong emphasis on testing where tests are integrated into continuous integration and build process, which yields a highly stable platform. XP is designed for smaller teams of 20 – 30 people. RUP (Rational Unified Process) Æ Model driven architecture, design and development; customizable frameworks for scalable process; iterative development methodology; Re-use of architecture, code, component, framework, patterns etc. RUP can be used as an agile process for smaller teams of 20-30
  • 91.
    Find more WWW.ThesisScientist.com 146Enterprise Java people, or as a heavy weight process for larger teams of 50-100 people. Refer Q103 – Q105 in Enterprise section. Feature Driven Development [FDD] Æ Jeff De Luca and long time OO guru Peter Coad developed feature Driven Development (FDD). Like the other adaptive methodologies, it focuses on short iterations that deliver tangible functionality. FDD was originally designed for larger project teams of around 50 people. In FDD's case the iterations are two weeks long. FDD has five processes. The first three are done at the beginning of the project. The last two are done within each iteration. Develop an Overall Model Build a Features List Plan by Feature Design by Feature Build by Feature The developers come in two kinds: class owners and chief programmers. The chief programmers are the most experienced developers. They are assigned features to be built. However they don't build them alone. Instead the chief programmer identifies which classes are involved in implementing the feature and gathers their class owners together to form a feature team for developing that feature. The chief programmer acts as the coordinator, lead designer, and mentor while the class owners do much of the coding of the feature. Test Driven Development [TDD] Æ TDD is an iterative software development process where you first write the test with the idea that it must fail. Refer Q1 in Emerging Technologies/Frameworks section… Scrum Æ Scrum divides a project into sprints (aka iterations) of 30 days. Before you begin a sprint you define the functionality required for that sprint and leave the team to deliver it. But every day the team holds a short (10 – 15 minute) meeting, called a scrum where the team runs through what it will achieve in the next day. Some of the questions asked in the scrum meetings are: What did you do since the last scrum meetings? Do you have any obstacles? What will you do before next meeting? This is very similar to stand-up meetings in XP and iterative development process in RUP. Enterprise – Key Points J2EE is a 3-tier (or n-tier) system. Each tier is logically separated and loosely coupled from each other, and may be distributed. J2EE applications are developed using MVC architecture, which divides the functionality of displaying and maintaining of the data to minimise the degree of coupling between enterprise components. J2EE modules are deployed as ear, war and jar files, which are standard application deployment archive files. HTTP is a stateless protocol and state can be maintained between client requests using HttpSession, URL rewriting, hidden fields and cookies. HttpSession is the recommended approach. Servlets and JSPs are by default multi-threaded, and care should be taken in declaring instance variables and accessing shared resources. It is possible to have a single threaded model of a servlet or a JSP but this can adversely affect performance. Clustering promotes high availability and scalability. The considerations for servlet clustering are: Objects stored in the session should be serializable. Design for idempotence. Avoid using instance and static variables in read and write mode. Avoid storing values in the ServletContext. Avoid using java.io.* and use getResourceAsStream() instead.
  • 92.
    Find more WWW.ThesisScientist.com EnterpriseJava 147 JSPs have a translation or a compilation process where the JSP engine translates and compiles a JSP file into a JSP servlet. JSPs have 4 different scope values: page, request, session and application. JSPs can be included statically, where all the included JSP pages are compiled into a single servlet during the translation or compilation phase or included dynamically, where included JSPs are compiled into separate servlets and the content generated by these servlets are included at runtime in the JSP response. Avoid scriptlet code in your JSPs and use JavaBeans or custom tags (e.g. Struts tags, JSTL tags, JSF tags etc) instead. Databases can run out cursors if the connections are not closed properly. The valuable resources like connections and statements should be enclosed in a try{} and finally{} block. Prepared statements offer better performance as opposed to statements, as they are precompiled and reuse the same execution plan with different arguments. Prepared statements are also more secure because they use bind variables, which can prevent SQL injection attacks. JNDI provides a generic interface to LDAP and other directory services like NDS, DNS etc. In your code always make use of a logical JNDI reference (java:comp/env/ejb/MyBean) as opposed to physical JNDI reference (ejb/MyBean) because you cannot guarantee that the physical JNDI location you specify in your code will be available. Your code will break if the physical location is changed. LDAP servers are typically used in J2EE applications to authenticate and authorise users. LDAP servers are hierarchical and are optimized for read access, so likely to be faster than database in providing read access. RMI facilitates object method calls between JVMs. JVMs can be located on separate host machines, still one JVM can invoke methods belonging to an object residing in another JVM (i.e. address space). RMI uses object serialization to marshal and unmarshal parameters. The remote objects should extend the UnicastRemoteObject. To go through a firewall, the RMI protocol can be embedded within the firewall trusted HTTP protocol, which is called HTTP tunnelling. EJB (i.e. 2.x) is a remote, distributed multi-tier system, which supports protocols like JRMP, IIOP, and HTTP etc. EJB components contain business logic and system level supports like security, transaction, instance pooling, multi- threading, object life-cycles etc are managed by the EJB container and hence simplify the programming effort. Having said this, there are emerging technologies like: Hibernate, which is an open source object-to-relational (O/R) mapping framework. EJB 3.0, which is taking ease of development very seriously and has adjusted its model to offer the plain old Java objects (i.e. POJOs) based persistence and the new O/R mapping model based on hibernate. Refer Q14 – Q18 in Emerging technologies / Frameworks section for brief discussion on hibernate and EJB 3.0. EJB transaction attributes (like Required, Mandatory, RequiresNew, Supports etc) are specified declaratively through EJB deployment descriptors. Isolation levels are not part of the EJB 2.x specification. So the isolation levels can be set on the resource manager either explicitly on the Connection or via the application server specific configuration. A transaction is often described by ACID (Atomic, Consistent, Isolated and Durable) properties. A distributed transaction is an ACID transaction between two or more independent transactional resources like two separate databases. A 2-phase commit is an approach for committing a distributed transaction in 2 phases. EJB 2.x has two types of exceptions: System exception: is an unchecked exception derived from java.lang.RuntimeException. It is thrown by the system and is not recoverable. Application exception: is specific to an application and is thrown because of violation of business rules. EJB container managed transactions are automatically rolled back when a system exception occurs. This is possible because the container can intercept system exceptions. However when an application exception occurs, the container does not intercept and leaves it to the code to roll back using ctx.setRollbackOnly() method. EJB containers can make use of lazy loading (i.e. not creating an object until it is accessed) and dirty marker (ie persist only the entity beans that have bean modified) strategies to improve entity beans performance.
  • 93.
    Find more WWW.ThesisScientist.com 148Enterprise Java Message Oriented Middleware (MOM) is a software infrastructure that asynchronously communicates with other disparate systems through the production and consumption of messages. Messaging enables loosely coupled distributed communication. Java Messaging Service (JMS) is a Java API that allows applications to create, send, receive read messages in a standard way, hence improves portability. Some of the design decisions you need to make in JMS are message acknowledgement modes, transaction modes, delivery modes etc, synchronous vs. asynchronous paradigm, message body types, setting appropriate timeouts etc. XML documents can be processed in your Java/J2EE application either using a SAX parser, which is event driven or a DOM parser, which creates a tree structure in memory. The other XML related technologies are DTD, XSD, XSL, XPath, etc and Java and XML based technologies are JAXP, JAXB etc. There is an impedance mismatch between object and relational technology. Classes represent both data and behaviour whereas relational database tables just implement data. Inheritance class structure can be mapped to relational data model in one of the following ways: Map class hierarchy to single database table. Map each class to its own table. Map each concrete class to its own table Generic meta-data driven approach. Normalize data in your database for accuracy and denormalize data in your database for performance. RUP (Rational Unified Process) has 4 phases in the following order Inception, Elaboration, Construction, and Transition. Agile (i.e. lightweight) software development process is gaining popularity and momentum across organizations. Several methodologies like XP, RUP, Scrum, FDD, TDD etc fit under this agile development methodology banner. All these methodologies share many characteristics like iterative and incremental development, stand-up meetings to improve communication, automatic build, testing and continuous integration etc. UML is applicable to the object oriented (OO) problem solving. There are different types of UML diagrams like use case diagrams, class diagrams, sequence diagrams, collaboration diagrams, state chart diagrams, activity diagrams, component diagrams, deployment diagrams etc. Class diagrams are vital within OO methods. Class diagrams have the following possible relationships, association, aggregation, composition, generalization, and dependency. Struts is an MVC framework. Struts action classes are not thread-safe and care should be taken in declaring instance variables or accessing other shared resources. JSF is another Web UI framework like Struts gaining popularity and momentum. Log4j has three main components: loggers, appenders and layouts. Logger is a utility wrapper class. JUnit is an open source unit-testing framework. You can improve the performance of a J2EE application as follows : Manage and recycle your valuable resources like connections, threads etc by either pooling or caching. Use effective design patterns like session façade, value object, fast lane reader etc to minimise network overheads. Set appropriate timeouts for HttpSession objects. Use JDBC prepared statements as opposed to statements. Release database connections in a finally {} block when finished. Apply least restrictive but valid transaction isolation level. Batch database requests. Minimise serialization costs by marking references like file handles, database connections, etc which do not require serialization by declaring them transient. Some of the J2EE best practices are: Recycle your valuable resources by either pooling or caching. Automate your build process with tools like Ant, CruiseControl, and Maven etc, and continuously integrate your code into your build process. Build test cases first using tools like JUnit. Use standard J2EE packaging to improve portability. Apply appropriate proven design patterns.
  • 94.
    Find more WWW.ThesisScientist.com EnterpriseJava 149 Use proven frameworks like Struts, Spring, Hibernate, JSF, JUnit, Log4J, etc. Handle and propagate exceptions correctly. Avoid resource leaks by closing all database connections after you have used them. The goals of application server clustering are to achieve scalability, load balancing, and high availability. Java Management Extension (JMX) framework can improve the manageability of your application, for performance problems, critical events, error conditions etc and perform health checks on your hardware, database server etc. You can also configure and control your application at runtime. Finally get familiarised with some of the key Java & J2EE design patterns like: MVC design pattern: J2EE uses this design pattern or architecture. Chain of responsibility design pattern: Servlet filters use a slightly modified version of chain of responsibility design pattern. Front controller J2EE design pattern: provides a centralized access point for HTTP request handling to support the integration system services like security, data validation etc. This is a popular J2EE design pattern. Composite view J2EE design pattern: creates an aggregate view from atomic sub-views. View helper J2EE design pattern: avoids duplication of code. The helper classes are JavaBeans and custom tags (e.g. Struts tags, JSF tags, JSTL tags etc). Service to worker and dispatcher view J2EE design pattern: These two patterns are a combination of front controller and view helper patterns with a dispatcher component. These two patterns differ in the way they suggest different division of responsibility among components. Bridge design pattern: Java Data Base Connectivity (JDBC) uses the bridge design pattern. The JDBC API provides an abstraction and the JDBC drivers provide the implementation. Proxy design pattern: RMI & EJB uses the proxy design pattern. A popular design pattern. Business delegate J2EE design pattern: used to reduce the coupling between the presentation tier and the business services tier components. Session façade J2EE design pattern: too many fine-grained method calls between the client and the server will lead to network overhead and tight coupling. Use a session bean as a façade to provide a coarse-grained service access layer to clients. Value object J2EE design pattern: avoid fine-grained method calls by creating a value object, which will help the client, make a coarse-grained call. Fast-lane reader J2EE design pattern: access the persistence layer directly using a DAO (Data Access Object) pattern instead of using entity beans. Service locator J2EE design pattern: expensive and redundant JNDI lookups can be avoided by caching and reusing the already looked up service objects. Recommended reading on J2EE design patterns: Core J2EE Patterns: Best Practices and Design Strategies, Second Edition (Hardcover) by Deepak Alur, Dan Malks, John Crupi.
  • 95.
    Find more WWW.ThesisScientist.com 150Enterprise Java Let us put all together in the next section LF DC CI PI SE EH SD DP SF MI SI TI BP CO
  • 96.
    Find more WWW.ThesisScientist.com Howwould you go about…? 151 SECTION THREE How would you go about…? This section basically assesses your knowledge of how to perform certain tasks like documenting your project, identifying any potential performance, memory, transactional, and/or design issues etc. It also assesses if you have performed any of these tasks before. If you have not done a particular task, you can demonstrate that you know how to go about it if the task is assigned to you. This section also recaps some of the key considerations discussed in the Java and Enterprise sections. Question numbers are used for cross-referencing with Java and Enterprise sections. Q11 & Q13 are discussed in more detail and can be used as a quick reference guide in a software project. All the other questions excluding Q11 & Q13 can be read just before an interview.
  • 97.
    Find more WWW.ThesisScientist.com 152How would you go about…? Q 01: How would you go about documenting your Java/J2EE application? A 01: To be successful with a Java/J2EE project, proper documentation is vital. Before embarking on coding get the business requirements down. Build a complete list of requested features, sample screen shots (if available), use case diagrams, business rules etc as a functional specification document. This is the phase where business analysts and developers will be asking questions about user interface requirements, data tier integration requirements, use cases etc. Also prioritize the features based on the business goals, lead-times and iterations required for implementation. Prepare a technical specification document based on the functional specification. The technical specification document should cover: Purpose of the document: This document will emphasise the customer service functionality … Overview: This section basically covers background information, scope, any inclusions and/or exclusions, referenced documents etc. Basic architecture: discusses or references baseline architecture document. Answers questions like Will it scale? Can this performance be improved? Is it extendable and/or maintainable? Are there any security issues? Describe the vertical slices to be used in the early iterations, and the concepts to be proved by each slice. Etc. For example which MVC [model-1, model-2 etc] paradigms (Refer Q3 in Enterprise section for MVC) should we use? Should we use Struts, JSF, Spring etc or build our own framework? Should we use a business delegate (Refer Q83 in Enterprise section for business delegate) to decouple middle tier with the client tier? Should we use AOP (Aspect Oriented Programming) (Refer Q3 in Emerging Technologies/Frameworks)? Should we use dependency injection? Should we use annotations? Do we require internationalization? Etc. Assumptions, Dependencies, Risks and Issues: highlight all the assumptions, dependencies, risks and issues. For example list all the risks you can identify. Design alternatives for each key functional requirement. Also discuss why a particular design alternative was chosen over the others. This process will encourage developers analyse the possible design alternatives without having to jump at the obvious solution, which might not always be the best one. Processing logic: discuss the processing logic for the client tier, middle tier and the data tier. Where required add process flow diagrams. Add any pre-process conditions and/or post-process conditions. (Refer Q9 in Java section for design by contract). UML diagrams to communicate the design to the fellow developers, solution designers, architects etc. Usually class diagrams and sequence diagrams are required. The other diagrams may be added for any special cases like (Refer Q107 in Enterprise section): State chart diagram: useful to describe behaviour of an object across several usecases. Activity diagram: useful to express complex operations. Supports and encourages parallel behaviour. Activity and statechart diagrams are beneficial for workflow modelling with multi threaded programming. Collaboration and Sequence diagrams: Use a collaboration or sequence diagram when you want to look at behaviour of several objects within a single use case. If you want to look at a single object across multiple use cases then use statechart. Object diagrams: The Object diagrams show instances instead of classes. They are useful for explaining some complicated objects in detail such as highlighting recursive relationships etc. List the package names, class names, database names and table names with a brief description of their responsibility in a tabular form. Prepare a coding standards document for the whole team to promote consistency and efficiency. Some coding practices can degrade performance for example: Inappropriate use of String class. Use StringBuffer instead of String for compute intensive mutations (Refer Q17 in Java section).
  • 98.
    Find more WWW.ThesisScientist.com Howwould you go about…? 153 Code in terms of interface. For example you might decide the LinkedList is the best choice for some application, but then later decide ArrayList might be a better choice. (Refer Q15 in Java section) Wrong approach  ArrayList list = new ArrayList(); Right approach  List list = new ArrayList(100) Set the initial capacity of a collection appropriately (e.g. ArrayList, HashMap etc). (Refer Q15 in Java section). To promote consistency define standards for variable names, method names, use of logging, curly bracket positions etc. Prepare a code review document and templates for the whole team. Let us look at some of the elements the code review should cover: Proper variable declaration: e.g. instance versus static variables, constants etc. Performance issues: e.g. Use ArrayList, HashMap etc instead of Vector, Hashtable when there is no thread-safety issue. Memory issues: e.g. Improper instantiation of objects instead of object reuse and object pooling, not closing valuable resource in a finally block etc. Thread-safety issues: e.g. Java API classes like SimpleDateFormat, Calendar, DecimalFormat etc are not thread safe, declaring variables in JSP is not thread safe, storing state information in Struts action class or multi-threaded servlet is not thread safe. Error handling: e.g. Re-throwing exception without nesting original exception, EJB methods not throwing EJB exception for system exceptions, etc. Use of coding standards: e.g. not using frameworks, System.out is used instead of log4j etc. Design issues: No re-use of code, no clear separation of responsibility, invalid use of inheritance to get method reuse, servlets performing JDBC direct access instead of using DAO (Data Access Objects) classes, HTML code in Struts action or servlet classes, servlets used as utility classes rather than as a flow controller etc. Documentation of code: e.g. No comments, no header files etc Bugs: e.g. Calling setAutoCommit within container-managed transaction, binary OR “|” used instead of logical OR “||”, relying on pass-by-reference in EJB remote calls, ResultSet not being closed on exceptions, EJB methods not throwing EJBException for system exceptions etc (Refer Q76 & Q77 in Enterprise section) Prepare additional optional guideline documents as per requirements to be shared by the team. This will promote consistency and standards. For example: Guidelines to setting up J2EE development environment. Guidelines to version control system (CVS, VSS etc). Guidelines to deployment steps, environment settings, ant targets etc. Guidelines for the data modelling (any company standards). Guidelines for error handling (Refer Q34, Q35 in Java section & Q76, Q77 in Enterprise section). Guidelines for user interface design. Project overview document. Software development process document etc. Some of the above mentioned documents, which are shared by the whole team, can be published in an internal website like Wiki. Wiki is a piece of server software that allows users to freely create and edit Web page content using any Web browser. Q 02: How would you go about designing a Java/J2EE application?
  • 99.
    Find more WWW.ThesisScientist.com 154 A02: How would you go about…? Design should be specific to a problem but also should be general enough to address future requirements. Designing reusable object oriented software involves decomposing the business use cases into relevant objects and converting objects into classes. Create a tiered architecture: client tier, business tier and data tier. Each tier can be further logically divided into layers (Refer Q2, Q3 on Enterprise section). Use MVC (Model View Controller architecture for the J2EE and Java based GUI applications). Create a data model: A data model is a detailed specification of data oriented structures. This is different from the class modelling because it focuses solely on data whereas class models allow you to define both data and behaviour. Conceptual data models (aka domain models) are used to explore domain concepts with project stakeholders. Logical data models are used to explore the domain concepts, and their relationships. Logical data models depict entity types, data attributes end entity relationships (with Entity Relationship (ER) diagrams). Physical data models are used to design the internal schema of a database depicting the tables, columns, and the relationships between the tables. Data models can be created by performing the following tasks: Identify entity types, attributes and relationships: use entity relationship (E-R) diagrams. Apply naming conventions (e.g. for tables, attributes, indices, constraints etc): Your organization should have standards and guidelines applicable to data modelling. Assign keys: surrogate keys (e.g. assigned by the database like Oracle sequences etc, max()+1, universally unique identifiers UUIDs, etc), natural keys (e.g. Tax File Numbers, Social Security Numbers etc), and composite keys. Normalize to reduce data redundancy and denormalize to improve performance: Normalized data have the advantage of information being stored in one place only, reducing the possibility of inconsistent data. Furthermore, highly normalized data are loosely coupled. But normalization comes at a performance cost because to determine a piece of information you have to join multiple tables whereas in a denormalized approach the same piece of information can be retrieved from a single row of a table. Denormalization should be used only when performance testing shows that you need to improve database access time for some of your tables. Note: Creating a data model (logical, physical etc) before design model is a matter of preference, but many OO methodologies are based on creating the data model from the object design model (i.e. you may need to do some work to create an explicit data model but only after you have a complete OO domain and design model ). In many cases when using ORM tools like Hibernate, you do not create the data model at all. Create a design model: A design model is a detailed specification of the objects and relationships between the objects as well as their behaviour. (Refer Q107 on Enterprise section) Class diagram: contains the implementation view of the entities in the design model. The design model also contains core business classes and non-core business classes like persistent storage, security management, utility classes etc. The class diagrams also describe the structural relationships between the objects. Use case realizations: are described in sequence and collaboration diagrams. Design considerations when decomposing business use cases into relevant classes: designing reusable and flexible design models requires the following considerations: Granularity of the objects (fine-grained, coarse-grained etc): Can we minimise the network trip by passing a coarse-grained value object instead of making 4 network trips with fine-grained parameters? (Refer Q85 in Enterprise section). Should we use method level (coarse-grained) or code level (fine- grained) thread synchronization? (Refer Q40 in Java section). Should we use a page level access security or a fine-grained programmatic security? Coupling between objects (loosely coupled versus strongly coupled). Should we use business delegate pattern to loosely couple client and business tier? (Refer Q83 in Enterprise section) or Should we use dependency injection? (Refer Q09 in Emerging Technologies/Frameworks). Network overheads for remote objects like EJB, RMI etc: Should we use the session façade, value object patterns? (Refer Q84 & Q85 in Enterprise section).
  • 100.
    Find more WWW.ThesisScientist.com Howwould you go about…? 155 Definition of class interfaces and inheritance hierarchy: Should we use an abstract class or an interface? Is there any common functionality that we can move to the super class (or parent class)? Should we use interface inheritance with object composition for code reuse as opposed to implementation inheritance? Etc. (Refer Q8, Q10 in Java section). Establishing key relationships (aggregation, composition, association etc): Should we use aggregation or composition? [composition may require cascade delete] (Refer Q107, Q108 in Enterprise section – under class diagrams). Should we use an “is a” (generalization) relationship or a “has a” (composition) relationship? (Refer Q7 in Java section). Applying polymorphism and encapsulation: Should we hide the member variables to improve integrity and security? (Refer Q8 in Java section). Can we get a polymorphic behaviour so that we can easily add new classes in the future? (Refer Q8 in Java section). Applying well-proven design patterns (like Gang of four design patterns, J2EE design patterns, EJB design patterns etc) help designers to base new designs on prior experience. Design patterns also help you to choose design alternatives (Refer Q11 in How would you go about…). Scalability of the system: Vertical scaling is achieved by increasing the number of servers running on a single machine. Horizontal scaling is achieved by increasing the number of machines in the cluster. Horizontal scaling is more reliable than the vertical scaling because there are multiple machines involved in the cluster. In vertical scaling the number of server instances that can be run on one machine are determined by the CPU usage and the JVM heap memory. How do we replicate the session state? Should we use stateful session beans or HTTP session? Should we serialize this object so that it can be replicated? Internationalization requirements for multi-language support: Should we support other languages? Should we support multi-byte characters in the database? Vertical slicing: Getting the reusable and flexible design the first time is impossible. By developing the initial vertical slice of your design you eliminate any nasty integration issues later in your project. Also get the design patterns right early on by building the vertical slice. It will give you experience with what does work and what does not work with Java/J2EE. Once you are happy with the initial vertical slice then you can apply it across the application. The initial vertical slice should be based on a typical business use case. Refer Q136 in Enterprise section. Ensure the system is configurable through property files, xml descriptor files, annotations etc. This will improve flexibility and maintainability. Avoid hard coding any values. Use a constant class for values, which rarely change and use property files, xml descriptor files, annotations etc for values, which can change more frequently (e.g. process flow steps etc) and/or environment related configurations(e.g. server name, server port, LDAP server location etc). Design considerations during design, development and deployment phases: designing a fast, secured, reliable, robust, reusable and flexible system require considerations in the following key areas: Performance issues (network overheads, quality of the code etc): Can I make a single coarse-grained network call to my remote object instead of 3 fine-grained calls? Concurrency issues (multi-threading etc): What if two threads access my object simultaneously will it corrupt the state of my object? Transactional issues (ACID properties): What if two clients access the same data simultaneously? What if one part of the transaction fails, do we rollback the whole transaction? What if the client resubmits the same transactional page again? Security issues: Are there any potential security holes for SQL injection or URL injection by hackers? Memory issues: Is there any potential memory leak problems? Have we allocated enough heap size for the JVM? Have we got enough perm space allocated since we are using 3 rd party libraries, which generate classes dynamically? (e.g. JAXB, XSLT, JasperReports etc) Scalability issues: Will this application scale vertically and horizontally if the load increases? Should this object be serializable? Does this object get stored in the HttpSession?
  • 101.
    Find more WWW.ThesisScientist.com 156How would you go about…? Maintainability, reuse, extensibility etc: How can we make the software reusable, maintainable and extensible? What design patterns can we use? How often do we have to refactor our code? Logging and auditing if something goes wrong can we look at the logs to determine the root cause of the problem? Object life cycles: Can the objects within the server be created, destroyed, activated or passivated depending on the memory usage on the server? (e.g. EJB). Resource pooling: Creating and destroying valuable resources like database connections, threads etc can be expensive. So if a client is not using a resource can it be returned to a pool to be reused when other clients connect? What is the optimum pool size? Caching can we save network trips by storing the data in the server‟s memory? How often do we have to clear the cache to prevent the in memory data from becoming stale? Load balancing: Can we redirect the users to a server with the lightest load if the other server is overloaded? Transparent fail over: If one server crashes can the clients be routed to another server without any interruptions? Clustering: What if the server maintains a state when it crashes? Is this state replicated across the other servers? Back-end integration: How do we connect to the databases and/or legacy systems? Clean shutdown: Can we shut down the server without affecting the clients who are currently using the system? Systems management: In the event of a catastrophic system failure who is monitoring the system? Any alerts or alarms? Should we use JMX? Should we use any performance monitoring tools like Tivoli etc? Dynamic redeployment: How do we perform the software deployment while the site is running? (Mainly for mission critical applications 24hrs X 7days). Portability issues: Can I port this application to a different server 2 years from now? Q 03: How would you go about identifying performance and/or memory issues in your Java/J2EE application? A 03: Profiling can be used to identify any performance issues or memory leaks. Profiling can identify what lines of code the program is spending the most time in? What call or invocation paths are used to reach at these lines? What kinds of objects are sitting in the heap? Where is the memory leak? Etc. There are many tools available for the optimization of Java code like JProfiler, Borland OptimizeIt etc. These tools are very powerful and easy to use. They also produce various reports with graphs. Optimizeit™ Request Analyzer provides advanced profiling techniques that allow developers to analyse the performance behaviour of code across J2EE application tiers. Developers can efficiently prioritize the performance of Web requests, JDBC, JMS, JNDI, JSP, RMI, and EJB so that trouble spots can be proactively isolated earlier in the development lifecycle. Thread Debugger tools can be used to identify threading issues like thread starvation and contention issues that can lead to system crash. Code coverage tools can assist developers with identifying and removing any dead code from the applications. Hprof which comes with JDK for free. Simple tool. Java –Xprof myClass java -Xrunhprof:[help]|[<option>=<value>] java -Xrunhprof:cpu=samples, depth=6, heap=sites
  • 102.
    Find more WWW.ThesisScientist.com Howwould you go about…? 157 Use operating system process monitors like NT/XP Task Manager on PCs and commands like ps, iostat, netstat, vmstat, uptime, nfsstat etc on UNIX machines. Write your own wrapper MemoryLogger and/or PerformanceLogger utility classes with the help of totalMemory() and freeMemory() methods in the Java Runtime class for memory usage and System.currentTimeMillis() method for performance. You can place these MemoryLogger and PerformanceLogger calls strategically in your code. Even better approach than utility classes is using Aspect Oriented Programming (AOP) for pre and post memory and/or performance recording where you have the control of activating memory/performance measurement only when needed. (Refer Q3 – Q5 in Emerging Technologies/Frameworks section). Q 04: How would you go about minimising memory leaks in your Java/J2EE application? A 04: Java‟s‟ memory management (i.e. Garbage Collection) prevents lost references and dangling references but it is still possible to create memory leaks in other ways. If the application runs with memory leaks for a long duration you will get the error java.lang.OutOfMemoryError. In Java, typically the memory leak occurs when an object of a longer lifecycle has a reference to the objects of a short life cycle. This prevents the objects with short life cycle being garbage collected. The developer must remember to remove the reference to the short-lived objects from the long-lived objects. Objects with the same life cycle do not cause any problem because the garbage collector is smart enough to deal with the circular references (Refer Q33 in Java section). Java collection classes like Hashtable, ArrayList etc maintain references to other objects. So having a long life cycle ArrayList pointing to many short-life cycle objects can cause memory leaks. Commonly used singleton design pattern (Refer Q45 in Java section) can cause memory leaks. Singletons typically have a long life cycle. If a singleton has an ArrayList or a Hashtable then there is a potential for memory leaks. Java programming language includes a finalize method that allows an object to free system resources, in other words, to clean up after itself. However using finalize doesn't guarantee that a class will clean up resources expediently. A better approach for cleaning up resources involves the finally method and an explicit close statement. So freeing up the valuable resource in the finalize method or try {} block instead of finally {} block can cause memory leaks (Refer Q45 in Enterprise section). Q 05: How would you go about improving performance in your Java/J2EE application? A 05: The performance bottlenecks can be attributed to one or more of the following: Performance optimization considerations ¾ Application design. Application level ¾ Application Server tuning. ¾ Application coding. ¾ Drivers etc. ¾ Database partitioning, tuning etc Java infrastructure System level JVM selection JVM tuning (min & max heap size, perm size etc Network I/O, Disk I/O etc Operating System System configuration, topology etc Hardware (CPU, memory, I/O etc) Let us discuss some of the aspects in detail: Java/J2EE application code related performance bottlenecks: Refer Q63 in Java section.
  • 103.
    Find more WWW.ThesisScientist.com 158How would you go about…? Refer Q123, Q125 in Enterprise section. Java/J2EE design related performance bottlenecks. Application design is one of the most important considerations for performance. A well-designed application will not only avoid many performance pitfalls but will also be easier to maintain and modify during the performance-testing phase of the project. Use proper design patterns to minimise network trips (session facade, value object Refer etc Q83-Q87 in Enterprise section). Minimise serialization cost by implementing session beans with remote interfaces and entity beans with local interfaces (applicable to EJB 2.x) or even the session beans can be implemented with local interfaces sharing the same JVM with the Web tier components. For EJB1.x some EJB containers can be configured to use pass-by-reference instead of pass-by-value (pass-by-value requires serialization) Refer Q69, Q82 in Enterprise section. Use of multi-threading from a thread-pool (say 10 – 50 threads). Using a large number of threads adversely affects performance by consuming memory through thread stacks and CPU by context switching. Database related performance bottlenecks. Use proper database indexes. Numeric indices are more efficient than character based indices. Minimise the number of columns in your composite keys. Performing a number of “INSERT” operations is more efficient when fewer columns are indexed and “SELECT” operations are more efficient when, adequately indexed based on columns frequently used in your “WHERE” clause. So it is a trade-off between “SELECT” and “INSERT” operations. Minimise use of composite keys or use fewer columns in your composite keys. Partition the database for performance based on the most frequently accessed data and least frequently accessed data. Identify and optimise your SQL queries causing performance problems (Refer Q97 in Enterprise section). De-normalise your tables where necessary for performance (Refer Q98 in Enterprise section). Close database connections in your Java code in the finally block to avoid any „open cursors‟ problem (Refer Q45 in Enterprise section). Use optimistic concurrency as opposed to pessimistic concurrency where appropriate (Refer Q78 in Enterprise section). Application Server, JVM, Operating System, and/or hardware related performance bottlenecks. Application Server: Configure the application server for optimum performance (Refer Q88, Q123 in Enterprise section). Operating System: Check for any other processes clogging up the system resources, maximum number of processes it can support or connect, optimise operating system etc. Hardware: Insufficient memory, insufficient CPU, insufficient I/O, limitation of hardware configurations, network constraints like bandwidth, message rates etc. Q 06: How would you go about identifying any potential thread-safety issues in your Java/J2EE application? A 06: When you are writing graphical programs like Swing or Internet programs using servlets or JSPs multi-threading is a necessity for all but some special and/or trivial programs. An application program or a process can have multiple threads like multiple processes that can run on one computer. The multiple threads appear to be doing their work in parallel. When implemented on a multi-processor machine, they can actually work in parallel.
  • 104.
    Find more WWW.ThesisScientist.com Howwould you go about…? 159 Unlike processes, threads share the same address space (Refer Q36 in Java section) which means they can read and write the same variables and data structures. So care should be taken to avoid one thread disturbing the work of another thread. Let us look at some of the common situations where care should be taken: Swing components can only be accessed by one thread at a time. A few operations are guaranteed to be thread safe but the most others are not. Generally the Swing components should be accessed through an event-dispatching thread. (Refer Q53 in Java section). A typical Servlet life cycle creates a single instance of each servlet and creates multiple threads to handle the service() method. The multi-threading aids efficiency but the servlet code must be coded in a thread safe manner. The shared resources (e.g. instance variable) should be appropriately synchronized or should only use variables in a read-only manner. (Refer Q16 in Enterprise section). The declaration of variables in JSP is not thread-safe, because the declared variables end up in the generated servlet as an instance variable, not within the body of the _jspservice() method. (Refer Q34 in Enterprise section). Struts framework action classes are not thread-safe. (Refer Q113 in Enterprise section). Some Java collection classes like Hashmap, ArrayList etc are not thread-safe. (Refer Q13 in Java section). Some of the Java core library classes are not thread safe. For e.g. java.util.SimpleDateFormat, java.util.Locale etc. Q 07: How would you go about identifying any potential transactional issues in your Java/J2EE application? A 07: When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed immediately after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode. (Refer Q43 in Enterprise section). Disabling auto-commit mode can improve performance by minimising number of times it accesses the database. A transaction is often described by ACID properties (Atomic, Consistent, Isolated and Durable). A distributed transaction is an ACID transaction between two or more independent transactional resources like two separate databases. For a transaction to commit successfully, all of the individual resources must commit successfully. If any of them are unsuccessful, the transaction must rollback in all of the resources. A 2-phase commit is an approach for committing a distributed transaction in 2 phases. Refer Q73 in Enterprise section. Isolation levels provide a degree of control of the effects one transaction can have on another concurrent transaction. Concurrent effects are determined by the precise ways in which, a particular relational database handles locks and its drivers may handle these locks differently. Isolation levels are used to overcome transactional problems like lost update, uncommitted data (aka dirty reads), inconsistent data (aka. phantom update), and phantom insert. Higher isolation levels can adversely affect performance at the expense of data accuracy. Refer Q72 in Enterprise section. Isolation Level Lost Update Uncommitted Data Inconsistent Data Phantom Insert Read Uncommitted Prevented by DBMS Can happen Can happen Can happen Read Committed Prevented by DBMS Prevented by DBMS Can happen Can happen Repeatable Read Prevented by DBMS Prevented by DBMS Prevented by DBMS Can happen Serializable Prevented by DBMS Prevented by DBMS Prevented by DBMS Prevented by DBMS Decide between optimistic and pessimistic concurrency control. (Refer Q78 in Enterprise section). Evaluate a strategy to determine if the data is stale when using strategies to cache data. (Refer Q79 in Enterprise section). EJB related transactional issues: Set the appropriate transactional attributes for the EJBs. (Refer Q71 in Enterprise section). Set the appropriate isolation level for the EJB. The isolation level should not be any more restrictive than it has to be. Higher isolation levels can adversely affect performance. (Refer Q72 in Enterprise section). Isolation levels are application server specific and not part of the standard EJB configuration.
  • 105.
    Find more WWW.ThesisScientist.com 160How would you go about…? In EJB 2.x, transactions are rolled back by the container when a system exception is thrown. When an application exception is thrown then the transactions are not rolled back by the container. So the developer has to roll it back using ctx.setRollbackOnly() call. (Refer Q76, Q77 in Enterprise section). Detect doomed transactions to avoid performing any unnecessary compute intensive operations. (Refer Q72 in Enterprise section). Q 08: How would you go about applying the Object Oriented (OO) design concepts in your Java/J2EE application? A 08: Question Answer What are the key A true object oriented language should support the following 3 characteristics: characteristics of ™ Encapsulation (aka information hiding): implements information hiding and modularityan OO language like Java? (abstraction). ™ Polymorphism: The same message sent to different objects, results in behaviour that is dependent on the nature of the object receiving the message. ™ Inheritance: Encourages code reuse and code organisation by defining the new class based on the existing class. What is dynamic binding? Dynamic binding (aka late binding): The dynamic binding is used to implement polymorphism. Objects could come from local process or from across the network from a remote process. We should be able to send messages to objects without having to know their types at the time of writing the code. Dynamic binding provides maximum flexibility at the execution time. Usually dynamic binding or late binding takes a small performance hit. Refer Q8 in Java section. Let us take an example to illustrate dynamic binding through polymorphic behaviour: Say you have a method in Java void draw(Shape s) { s.erase(); // ... s.draw(); } The above method will talk to any shape, so it is independent of the specific type of object it is erasing and drawing. Now let us look at some other program, which is making use of this draw(Shape s) method: Circle cir = new Circle(); Square sq = new Square(); draw(cir); draw(sq); So the interesting thing is that the method call to draw(Shape s) will cause different code to be executed. So you send a message to an object even though you don‟t know what specific type it is and the right thing happens. This is called dynamic binding, which gives you polymorphic behaviour. How will you ™ Abstract Class: Often in a design, you want the base class to present only an interface for its decide whether to derived classes. That is, you don‟t want anyone to actually create an object of the base class, only use an interface or to upcast to it so that its interface can be used. This is accomplished by making that class abstract an abstract class? using the abstract key word. If anyone tries to make an object of an abstract class, the compiler prevents them. This is a tool to enforce a particular design. ™ Interface: The interface key word takes the concept of an abstract class one step further by preventing any function definitions at all. An interface is a very useful and commonly used tool, as it provides the perfect separation of interface and implementation. In addition, you can combine many interfaces together, if you wish. (You cannot inherit from more than one regular class or abstract class.) Now the design decision…
  • 106.
    Find more WWW.ThesisScientist.com Howwould you go about…? 161 When to use an Abstract Class: Abstract classes are excellent candidates inside of application frameworks. Abstract classes let you define some default behaviour and force subclasses to provide any specific behaviour. When to use an Interface: If you need to change your design frequently, I prefer using interface to abstract. For example, the strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. Example: Strategy Design Pattern. Another justification of interfaces is that they solved the „diamond problem‟ of traditional multiple inheritance. Java does not support multiple inheritances. Java only supports multiple interface inheritance. Interface will solve all the ambiguities caused by this „diamond problem‟. Refer Q10 in Java section. Interface inheritance vs. Implementation inheritance: Prefer interface inheritance to implementation inheritance because it promotes the design concept of coding to an interface and reduces coupling. Interface inheritance can achieve code reuse with the help of object composition. Refer Q08 in Java section. Why abstraction is The software you develop should optimally cater for the current requirements and problems and also important in Object should be flexible enough to easily handle future changes. Oriented programming? Abstraction is an important OO concept. The ability for a program to ignore some aspects of the information that it is manipulating, ie. Ability to focus on the essential. Each object in the system serves as a model of an abstract "actor" that can perform work, report on and change its state, and "communicate" with other objects in the system, without revealing how these features are implemented. Abstraction is the process where ideas are distanced from the concrete implementation of the objects. The concrete implementation will change but the abstract layer will remain the same. Let us look at an analogy: When you drive your car you do not have to be concerned with the exact internal working of your car (unless you are a mechanic). What you are concerned with is interacting with your car via its interfaces like steering wheel, brake pedal, accelerator pedal etc. Over the years a car‟s engine has improved a lot but its basic interface has not changed (ie you still use steering wheel, brake pedal, accelerator pedal etc to interact with your car). This means that the implementation has changed over the years but the interface remains the same. Hence the knowledge you have of your car is abstract. Explain black-box Black-box reuse is when a class uses another class without knowing the internal contents of it. The reuse and white- black-box reuses are: box reuse? Should ™ Dependency is the weakest type of black-box reuse.you favour Inheritance (white- ™ Association is when one object knows about or has a relationship with the other objects. box reuse) or ™ Aggregation is the whole part relationship where one object contains one or more of the other aggregation objects. (black-box reuse)? ™ Composition is a stronger whole part relationship Refer Q107, Q108 in Enterprise section White-box reuse is when a class knows internal contents of another class. E.g. inheritance is used to modify implementation for reusability. Aggregation (Black-box reuse) Inheritance (White-box reuse) Defined dynamically or at run time via object Inheritance is defined statically or at compile time. references. Since only interfaces are used, it has Inheritance allows an easy way to modify the advantage of maintaining the integrity (ie implementation for reusability. encapsulation). Disadvantage of aggregation is that it increases A disadvantage of inheritance is that it breaks the number of objects and relationships. encapsulation, which implies implementation dependency. This means when you want to carry out the redesign the super class (ie parent class) has to be modified or replaced which is more likely to affect the subclasses as well. In general it will affect the whole inheritance hierarchy. Verdict: So the tendency is to favour aggregation over inheritance.
  • 107.
    Find more WWW.ThesisScientist.com 162How would you go about…? What is your Aspect-Oriented Programming (AOP) complements OO programming by allowing developers to understanding on dynamically modify the static OO model to create a system that can grow to meet new requirements. Aspect Oriented Programming AOP allows us to dynamically modify our static model to include the code required to fulfil the secondary (AOP)? requirements (like auditing, logging, security, exception handling etc) without having to modify the original static model (in fact, we don't even need to have the original code). Better still, we can often keep this additional code in a single location rather than having to scatter it across the existing model, as we would have to if we were using OO on its own. (Refer Q3 –Q5 in Emerging Technologies/Frameworks section.) A typical Web application will require a servlet to bind the HTTP request to an object andFor example then passes to the business handler object to be processed and finally return the response back to the user. So initially only a minimum amount of code is required. But once you start adding all the other additional secondary requirements (aka crosscutting concerns) like logging, auditing, security, exception-handling etc the code will inflate to 2-4 times its original size. This is where AOP can help. Q 09: How would you go about applying the UML diagrams in your Java/J2EE project? A 09: Question Answer Explain the key Refer Q107 in Enterprise section. Use case has 4 types of relationships: relationships in the use case diagrams? Between actor and use case ™ Association: Between actor and use case. May be navigable in both directions according to the initiator of the communication between the actor and the usecase. Between use cases ™ Extends: This is an optional extended behaviour of a use case. This behaviour is executed only under certain conditions such as performing a security check etc. ™ Includes: This specifies that the base use case needs an additional use case to fully describe its process. It is mainly used to show common functionality that is shared by several use cases. ™ Inheritance (or generalization): Child use case inherits the behaviour of its parent. The child may override or add to the behaviour of the parent. U s e c a s e d i a g r a m a s s o c i a t i o n * R e g i s t r a r E n r o l l i n U n i v e r s i < < i n c l u d e > > E n r o l l i n s e m i n a rt y a s s o c i a t i o n < < e x t e n d > > S t u d e n t p e r f o r m s e c u r i t y i n h e r i t a n c e E n r o l l f a m i l y i n h e r i t a n c e c h e c k m e m b e r s N o t e : < < e x t e n d > > r e l a t i o n s h i p i s c o n d i t i o n a l . Y o u d o a s s o c i a t i o n n o t k n o w i f o r w h e n e x t e n d i n g u s e c a s e w i l l b e i n v o k e d . < < i n c l u d e > > r e l a t i o n s h i p i s s i m i l a r t o a p r o c e d u r e c a l l . i n h e r i t a n c e : e x t e n d s t h e b e h a v i o r o f t h e I n t e r n a t i o n a l S t u d e n t p a r e n t u s e c a s e o r a c t o r . What is the main Refer Q107 in Enterprise section: difference between the collaboration diagram Collaboration diagrams convey the same message as sequence diagrams but the collaboration and the sequence diagrams focus on object roles instead of times in which the messages are sent. The sequence diagram? diagram is time line driven. When to use various Refer Q107 in Enterprise section. UML diagrams? ™ Use case diagrams: ƒ Determining the user requirements. New use cases often generate new requirements. ƒ Communicating with clients. The simplicity of the diagram makes use case diagrams a good way for designers and developers to communicate with clients. ƒ Generating test cases. Each scenario for the use case may suggest a suite of test
  • 108.
    Find more WWW.ThesisScientist.com Howwould you go about…? 163 cases. Class diagrams: Class diagrams are the backbone of Object Oriented methods. So they are used frequently. Class diagrams can have a conceptual perspective and an implementation perspective. During the analysis draw the conceptual model and during implementation draw the implementation model. Interaction diagrams (Sequence and/or Collaboration diagrams): When you want to look at behaviour of several objects within a single use case. If you want to look at a single object across multiple use cases then use statechart diagram as described below. State chart diagrams: Statechart diagrams are good at describing the behaviour of an object across several use cases. But they are not good at describing the interaction or collaboration between many objects. Use interaction and/or activity diagrams in conjunction with the statechart diagram to communicate complex operations involving multi-threaded programs etc. Use it only for classes that have complex state changes and behaviour. For example: the User Interface (UI) control objects, Objects shared by multi-threaded programs etc. Activity diagram: Activity and Statechart diagrams are generally useful to express complex operations. The great strength of activity diagrams is that they support and encourage parallel behaviour. An activity and statechart diagrams are beneficial for workflow modelling with multi threaded programming. Q 10: How would you go about describing the software development processes you are familiar with? A 10: In addition to technical questions one should also have a good understanding of the software development process. Question Answer What is the key Refer Q103 – Q105 in Enterprise section difference between the waterfall approach and Waterfall approach is sequential in nature. The iterative approach is non-sequential and the iterative approach incremental. The iterative and incremental approach has been developed based on the following: to software development? How to • You can't express all your needs up front. It is usually not feasible to define in detail (that is, decide which one to before starting full-scale development) the operational capabilities and functional characteristics use? of the entire system. These usually evolve over time as development progresses. • Technology changes over time. Some development lifecycle spans a long period of time during which, given the pace at which technology evolves, significant technological shifts may occur. • Complex systems. This means it is difficult to cope with them adequately unless you have an approach for mastering complexity. How to decide which one to use? Waterfall approach is more suitable in the following circumstances: • Have a small number of unknowns and risks. That is if • It has a known domain. • The team is experienced in current process and technology. • There is no new technology. • There is a pre-existing architecture baseline. • Is of short duration (two to three months). • Is an evolution of an existing system? The iterative approach is more suitable (Refer Q136 in Enterprise Section) Have a large number of unknowns and risks. So it pays to design, develop and test a vertical slice iteratively and then replicate it through other iterations. That is if
  • 109.
    Find more WWW.ThesisScientist.com 164How would you go about…? • Integrating with new systems. • New technology and/or architecture. • The team is fairly keen to adapt to this new process. • Is of large duration (longer than 3 months). • Is a new system? Have you used Extreme Programming (or XP) is a set of values, principles and practices for rapidly developing high- extreme programming quality software that provides the highest value for the customer in the fastest way possible. XP is a techniques? Explain? minimal instance of RUP. XP is extreme in the sense that it takes 12 well-known software development "best practices" to their logical extremes. The 12 core practices of XP are: 1. The Planning Game: Business and development cooperate to produce the maximum business value as rapidly as possible. The planning game happens at various scales, but the basic rules are always the same: ƒ Business comes up with a list of desired features for the system. Each feature is written out as a user story (or PowerPoint screen shots with changes highlighted), which gives the feature a name, and describes in broad strokes what is required. User stories are typically written on 4x6 cards. ƒ Development team estimates how much effort each story will take, and how much effort the team can produce in a given time interval (i.e. the iteration). ƒ Business then decides which stories to implement in what order, as well as when and how often to produce production releases of the system. 2. Small releases: Start with the smallest useful feature set. Release early and often, adding a few features each time. 3. System metaphor: Each project has an organising metaphor, which provides an easy to remember naming convention. 4. Simple design: Always use the simplest possible design that gets the job done. The requirements will change tomorrow, so only do what's needed to meet today's requirements. 5. Continuous testing: Before programmers add a feature, they write a test for it. Tests in XP come in two basic flavours. ƒ Unit tests are automated tests written by the developers to test functionality as they write it. Each unit test typically tests only a single class, or a small cluster of classes. Unit tests are typically written using a unit-testing framework, such as JUnit. ƒ Customer to test that the overall system is functioning as specified, defines acceptance tests (aka Functional tests). Acceptance tests typically test the entire system, or some large chunk of it. When all the acceptance tests pass for a given user story, that story is considered complete. At the very least, an acceptance test could consist of a script of user interface actions and expected results that a human can run. Ideally acceptance tests should be automated using frameworks like Canoo Web test, Selenium Web test etc. 6. Refactoring: Refactor out any duplicate code generated in a coding session. You can do this with confidence that you didn't break anything because you have the tests. 7. Pair Programming: All production code is written by two programmers sitting at one machine. Essentially, all code is reviewed as it is written. 8. Collective code ownership: No single person "owns" a module. Any developer is expected to be able to work on any part of codebase at any time. 9. Continuous integration: All changes are integrated into codebase at least daily. The tests have to run 100% both before and after integration. You can use tools like Ant, CruiseControl, and Maven etc to continuously build and integrate your code. 10. 40-Hour Workweek: Programmers go home on time. In crunch mode, up to one week of overtime is allowed. But multiple consecutive weeks of overtime are treated as a sign that something is very wrong with the process. 11. On-site customer: Development team has continuous access to a real live customer or business owner, that is, someone who will actually be using the system. For commercial software with lots of customers, a customer proxy (usually the product manager, Business
  • 110.
    Find more WWW.ThesisScientist.com Howwould you go about…? 165 Analyst etc) is used instead. 12. Coding standards: Everyone codes to the same standards. Ideally, you shouldn't be able to tell by looking at it, which developer on the team has touched a specific piece of code. A typical extreme programming project will have: • All the programmers in a room together usually sitting around a large table. • Fixed number of iterations where each iteration takes 1-3 weeks. At the beginning of each iteration get together with the customer. • Pair-programming. • Writing test cases first (i.e. TDD). • Delivery of a functional system at the end of 1-3 week iteration. Have you used agile Agile (i.e. lightweight) software development process is gaining popularity and momentum (i.e. Lightweight) across organizations. Several methodologies fit under this agile development methodology banner. software development All these methodologies share many characteristics like iterative and incremental development, methodologies? test driven development (i.e. TDD), stand up meetings to improve communication, automatic testing, build and continuous integration of code etc. Among all the agile methodologies XP is the one which has got the most attention. Different companies use different flavours of agile methodologies by using different combinations of methodologies (e.g. primarily XP with other methodologies like Scrum, FDD, TDD etc). Refer Q136 in Enterprise section. Q 11: How would you go about applying the design patterns in your Java/J2EE application? A 11: It is really worth reading books and articles on design patterns. It is sometimes hard to remember the design patterns, which you do not use regularly. So if you do not know a particular design pattern you can always honestly say that you have not used it and subsequently suggest that you can explain another design pattern, which you have used recently or more often. It is always challenging to decide, which design pattern to use when? How do you improve your design pattern skills? Practice, practice, practice. I have listed some of the design patterns below with scenarios and examples: Note: To keep it simple, System.out.println(…) is used. In real practice, use logging frameworks like log4j. Also package constructs are not shown. In real practice, each class should be stored in their relevant packages like com.items etc. Feel free to try these code samples by typing them into a Java editor of your choice and run the main class Shopping. Also constants should be declared in a typesafe manner as shown below: /** * use typesafe enum pattern as shown below if you are using below JDK 1.5 or use “enum” if you are using JDK 1.5 */ public class ItemType { private final String name; public static final ItemType Book = new ItemType("book"); public static final ItemType CD = new ItemType("cd"); public static final ItemType COSMETICS = new ItemType("cosmetics"); public static final ItemType CD_IMPORTED = new ItemType("cd_imported"); private ItemType(String name) {this.name = name;} public String toString() {return name;} //add compareTo(), readResolve() methods etc as required ... }