Topic ... SCEA--- PART I INDEX

advertisement
SCEA--- PART I
INDEX
Topic
Page Number
----------------------------------------------------------------------------------------------------------------------1. Questions
1
2. Common Architectures
28
3. Design Patterns
32
4.EJB
37
5.Internationalisation
62
6.Legacy
74
7. Protocols
78
8. Security
85
Questions
1)A developer successfully creating and tests a
stateful bean following deployment, intermittent
"NullpointerException" begin to occur, particularly
when the server is hardly loaded. What most likely to
related problem.
a) setSessionContext
b) ejbCreate
c) ejbPassivate
d) beforeCompletion
e) ejbLoad
2)2 example implementations os Proxy are RMI & EJb
3)If an RMI parameter implements java.rmi.Remote, how is
it passed "on-the-wire?"
Choice 1
It can never be passed.
Choice 2
It is passed by value.
Choice 3
1
It cannot be passed because it implements
java.rmi.Remote.
Choice 4
It cannot be passed unless it ALSO implements
java.io.Serializable.
Choice 5
It is passed by reference.
ans)2
----------------4)public synchronized void txTest(int i) {
System.out.println("Integer is: " + i);
}
What is the outcome of attempting to compile and
execute the method above, assuming it is implemented
in a stateful session bean?
Choice 1
Run-time error when bean is created
Choice 2
The method will run, violating the EJB specification.
Choice 3
Compile-time error for bean implementation class
Choice 4
Compile-time error for remote interface
Choice 5
Run-time error when the method is executed
ans)2
------------------5)What is the CORBA naming service equivalent of JNDI?
Choice 1
Interface Definition Language
Choice 2
COS Naming
Choice 3
Lightweight Directory Access Protocol
Choice 4
Interoperable Inter-Orb Protocol
Choice 5
Computer Naming Service
ans)2
2
----------------------6)InitialContext ic = new InitialContext();
TestHome th = (TestHome)
ic.lookup("testBean/TestBean");
TestRemote beanA = th.create();
TestRemote beanB = th.create();
TestRemote beanC = th.create();
beanC.remove();
TestRemote beanD = th.create();
TestRemote beanE = th.create();
beanC = th.create();
Given the above code, container passivates which
bean instance first if the container limited the bean
pool size to four beans and used a
"least-recently-used" algorithm to passivate?
Choice 1
Bean A
Choice 2
Bean B
Choice 3
Bean C
Choice 4
Bean D
Choice 5
Bean E
------------------------7)Which one of the following phenomena is NOT addressed
by
read-consistency?
a Phantom read
b Cached read
c Dirty read
d Non-repeatable read
e Fuzzy read
ans)b,e
-------------------------8)Which one of the following methods is generally called
in both
ejbLoad() and ejbStore()?
a getEJBObject()
3
b getHandle()
c remove()
d getEJBHome()
e getPrimaryKey()
ans)e
----------------------------9)public void ejbCreate(int i) {
System.out.println("ejbCreate(i)");
}
Given a currently working stateless session bean, what
will be the outcome
upon deploying and executing the bean if you added the
above unique method
to the implementation class of a stateless session
bean (and made no other
changes)?
a Compile time error during stub/skeleton generation
b Compile time error for home interface
c Code will compile without errors.
d Compile time error for remote interface
e Compile time error for bean implementation
ans)a
---------------------------------10)Given the above code in your stateless session bean
business method
implementation, and the transaction is
container-managed with a Transaction
Attribute of TX_SUPPORTS, which one of the following
is the first error
generated?
a Error when compiling home interface
b Error while generating stubs and skeletons
c NullPointerException during deployment
d Runtime error
e Compile-time error for the bean implementation
ans)b
----------------------------------
4
11)Which one of the following is the result of attempting
to deploy a
stateless session bean and execute one of the method M
when the bean
implementation contains the method M NOT defined in
the remote interface?
a Compile time error for remote interface
b Compile time error for bean implementation
c Compile time error during stub/skeleton generation
d Code will compile without errors.
e Compile time error for home interface
ans)d
-----------------------------12)Which one of the following characteristics is NOT true
of RMI and
Enterprise Java Beans?
a They must execute within the confines of a Java
virtual machine (JVM).
b They serialize objects for distribution.
c They require .class files to generate stubs and
skeletons.
d They do not require IDL.
e They specify the use of the IIOP wire protocol for
distribution.
ans)a
13. Which one of the following is the result of attempting to deploy a
stateless session bean and execute one of the method M when the bean
implementation contains the method M NOT defined in the remote interface?
a Compile time error for remote interface
b Compile time error for bean implementation
c Compile time error during stub/skeleton generation
d Code will compile without errors.
e Compile time error for home interface
14. If a unique constraint for primary keys is not enabled in a database,
multiple rows of data with the same primary key could exist in a table.
Entity beans that represent the data from the table described above are
likely to throw which exception?
a NoSuchEntityException
b FinderException
5
c ObjectNotFoundException
d RemoveException
e NullPointerException
15. A developer needs to deploy an Enterprise Java Bean, specifically an
entity bean, but is unsure if the bean container is able to create and
provide a transaction context.
Which attribute below will allow successful deployment of the bean?
a BeanManaged
b RequiresNew
c Mandatory
d Required
e Supports
16. What is the outcome of attempting to compile and execute the method
above, assuming it is implemented in a stateful session bean?
a Compile-time error for remote interface
b Run-time error when bean is created
c Compile-time error for bean implementation class
d The method will run, violating the EJB specification.
e Run-time error when the method is executed
17. Which one of the following is the result of attempting to deploy a
stateless session bean and execute one of the method M when the bean
implementation contains the method M NOT defined in the remote interface?
a Compile time error for remote interface
b Compile time error for bean implementation
c Compile time error during stub/skeleton generation
d Code will compile without errors.
e Compile time error for home interface
18. If a unique constraint for primary keys is not enabled in a database,
multiple rows of data with the same primary key could exist in a table.
Entity beans that represent the data from the table described above are
likely to throw which exception?
a NoSuchEntityException
b FinderException
c ObjectNotFoundException
d RemoveException
e NullPointerException
19. There are two Enterprise Java Beans, A and B. A method in "A" named
"Am" begins execution, reads a value v from the database and sets a variable
"X" to value v, which is one hundred. "Am" adds fifty to the variable X and
6
updates the database with the new value of X. "Am" calls "Bm", which is a
method in B. "Bm" begins executing. "Bm" reads an additional value from the
database. Based on the value, "Bm" determines that a business rule has been
violated and aborts the transaction. Control is returned to "Am".
Requirement:
If "Bm" aborts the transaction, it is imperative that the original value be
read from the database and stored in variable X.
Given the scenario above, which Transaction Attributes will most likely meet
the requirements stated?
a A-RequiresNew, B-Mandatory
b A-Mandatory, B-RequiresNew
c A-RequiresNew, B-Supports
d A-NotSupported, B-RequiresNew
e A-RequiresNew, B-RequiresNew
If an RMI parameter implements java.rmi.Remote, how is
it passed "on-the-wire?"
Choice 1
It can never be passed.
Choice 2
It is passed by value.
Choice 3
It cannot be passed because it implements
java.rmi.Remote.
Choice 4 (Correct)
It cannot be passed unless it ALSO implements
java.io.Serializable.
Choice 5
It is passed by reference.
----------------public synchronized void txTest(int i) {
System.out.println("Integer is: " + i);
}
What is the outcome of attempting to compile and
execute the method above, assuming it is implemented
in a stateful session bean?
Choice 1
Run-time error when bean is created
Choice 2
The method will run, violating the EJB specification.
7
Choice 3 (Correct)
Compile-time error for bean implementation class
Choice 4
Compile-time error for remote interface
Choice 5
Run-time error when the method is executed
------------------What is the CORBA naming service equivalent of JNDI?
Choice 1
Interface Definition Language
Choice 2 (Correct)
COS Naming
Choice 3
Lightweight Directory Access Protocol
Choice 4
Interoperable Inter-Orb Protocol
Choice 5
Computer Naming Service
----------------------InitialContext ic = new InitialContext();
TestHome th = (TestHome)
ic.lookup("testBean/TestBean");
TestRemote beanA = th.create();
TestRemote beanB = th.create();
TestRemote beanC = th.create();
beanC.remove();
TestRemote beanD = th.create();
TestRemote beanE = th.create();
beanC = th.create();
Given the above code, container passivates which
bean instance first if the container limited the bean
pool size to four beans and used a
"least-recently-used" algorithm to passivate?
Choice 1
Bean A
Choice 2
Bean B
Choice 3
Bean C
Choice 4 (Correct, Since only Statefull session bean and Entity Bean can be passivated, and Entitybean can
not call as
8
th.create() normally, I take it as statefull session bean)
Bean D
Choice 5
Bean E
------------------------Which one of the following phenomena is NOT addressed
by
read-consistency?
a Phantom read (Correct)
b Cached read
c Dirty read
d Non-repeatable read
e Fuzzy read
-------------------------Which one of the following methods is generally called
in both
ejbLoad() and ejbStore()?
a getEJBObject()
b getHandle()
c remove()
d getEJBHome()
e getPrimaryKey() (Correct)
----------------------------public void ejbCreate(int i) {
System.out.println("ejbCreate(i)");
}
Given a currently working stateless session bean, what
will be the outcome
upon deploying and executing the bean if you added the
above unique method
to the implementation class of a stateless session
bean (and made no other
changes)?
a Compile time error during stub/skeleton generation (Correct)
b Compile time error for home interface
c Code will compile without errors.
d Compile time error for remote interface
e Compile time error for bean implementation
9
---------------------------------Given the above code in your stateless session bean
business method
implementation, and the transaction is
container-managed with a Transaction
Attribute of TX_SUPPORTS, which one of the following
is the first error
generated?
a Error when compiling home interface
b Error while generating stubs and skeletons (Correct)
c NullPointerException during deployment
d Runtime error
e Compile-time error for the bean implementation
---------------------------------Which one of the following is the result of attempting
to deploy a
stateless session bean and execute one of the method M
when the bean
implementation contains the method M NOT defined in
the remote interface?
a Compile time error for remote interface
b Compile time error for bean implementation
c Compile time error during stub/skeleton generation
d Code will compile without errors. (Correct)
e Compile time error for home interface
-----------------------------Which one of the following characteristics is NOT true
of RMI and
Enterprise Java Beans?
a They must execute within the confines of a Java
virtual machine (JVM).
b They serialize objects for distribution.
c They require .class files to generate stubs and
skeletons.
d They do not require IDL.
e They specify the use of the IIOP wire protocol for
distribution. (InCorrect)
1
Scheduling project activities such as functional increments and test
10
case development, which one of the following OOAD artifacts is the
MOST useful?
a) Use cases
b) Interaction diagrams
c) Activity diagrams
d) Package diagrams
e) Class Diagrams
Single Select - Please select the best answer (one and only one
choice must be selected).
2)
When using OOAD artifacts to organize and assign team
responsibilities on a project, it is BEST to:
a)
evenly distribute use cases among team members and have them work as
independently as possible in order to minimize code dependencies
b)
designate one team for implementing interaction diagrams related to
the "common code path" and another team for implementing interaction
diagrams related to "code path variations" (for example ? conditional
or error paths)
c)
divide teams according to package diagram dependencies and utilize
use cases to schedule the work for the individual team members
d)
divide teams according to the layers in the software architecture and
have them work as independently as possible in order to minimize
dependencies between the layers}
Single Select - Please select the best answer (one and only one
choice must be selected).
3)
To MOST effectively manage teams working on different packages within
a large project, which one of the following should be true?
a)
One technical lead should control the project details and communicate
decisions to the different teams.
b)
Type of database ( DB2 UDB, Oracle, Sybase, or InstantDB )
c)
The team leads should focus on quality designs for the internals of
their packages, mentoring their team members.
d)
Communications between the teams should be minimized to reduce
overhead burdens while they work on separate, independent use cases
for their packages.
11
Single Select - Please select the best answer (one and only one
choice must be selected).
4) http://certify.torolab.ibm.com/figures/test486F3.gif
What is wrong with the following analysis use case?
a)
There are design details intermixed with the requirements.
b)
The actor's actions and system responses are not separated.
c)
"Sell goods" is too broad to be a use case.
d)
There is nothing wrong with this use case.
Single Select - Please select the best answer (one and only one
choice must be selected).
5) http://certify.torolab.ibm.com/figures/test486F5.gif
When creating the use cases related to the "Prepare for an Event"
scenario in the Figure ChefScenario, which one of the following BEST
represents the type of terminology that the use cases should contain?
a)
chef, menu, recipes, ingredients
b)
end user, bill of fare, cooking specifications, food contents
c)
chef object, menu object, recipe object, ingredient object
d)
person record, menu print stream, recipe container, ingredient array
Single Select - Please select the best answer (one and only one
choice must be selected).
6) http://certify.torolab.ibm.com/figures/test486F4.gif
Which one of the following is the BEST set of potential use cases for
the "Prepare for an Event" scenario in Figure ChefScenario?
a)
Prepare for party, Display menu, Generate shopping list, Exclude
ingredients on hand, Generate utensil list, Generate to do list
b)
Prepare for party, Display menu, Generate shopping list, Generate
utensil list, Pack utensils, Generate to do list
12
c)
Display menu, Generate shopping list, Generate utensil list, Generate
to do list
d)
Display menu, Generate shopping list, Exclude ingredients on hand,
Generate utensil list, Generate to do list
e)
Generate shopping list, Exclude ingredients on hand, Generate utensil
list, Generate to do list, Check utensil list
Single Select - Please select the best answer (one and only one
choice must be selected).
7)
Which of the following are recommended when developing an OO system?
a)
Write a description of the concept that a class represents whenever a
new class is declared.
b)
Use interfaces for types or roles that objects may play, independent
of their location in the class hierarchy.
c)
Apply design patterns where applicable in the system.
d)
Name classes based on their design specifics, such as "array"
or "queue".
Multiple Select - Please select all of the correct answers (this
question has 3 correct choices).
8)
Which one of the following is a good strategy for resolving class
name collisions that occur during OO analysis?
a)
Allow each team member to choose a preferred name.
b)
Create a class for each domain name, passing on requests to the one
class that implements the behavior for all of them to share.
c)
Discover better names for different concepts that are referred by the
same term.
Single Select - Please select the best answer (one and only one
choice must be selected).
13
9) http://certify.torolab.ibm.com/figures/test486F12.gif
Referring to the partial class diagram in Figure Qualified
Association, which of the following BEST describes the relationship?
a)
Access to SalesLineItems is by Product. A SalesTransaction can have
multiple SalesLineItems for one Product.
b)
Access to Products is by SalesLineItem. A SalesTransaction has zero
or more SalesLineItems for one Product.
c)
SalesTransactions contain Products, which are listed by one or more
SalesLineItems.
d)
SalesLineItems are for a quantity of one or more Products for a
particular SalesTransaction.
Single Select - Please select the best answer (one and only one
choice must be selected).
10) http://certify.torolab.ibm.com/figures/test486F9.gif
Refer to the Figure Sample 1. Consider the scenario that eStore.com
sells small appliances over the Internet. Currently, the store's
catalog includes over 50 appliances from 10 different suppliers. A
partial class diagram is shown in Figure Sample 1. If there is a new
requirement to restock the warehouse automatically as products are
sold, how is the new requirement BEST handled?
a)
Add "reorderLevel" and "reorderQuantity" attributes used by a new
deplete() method in the Inventory class. Use these to generate new
orders as InventoryProducts are sold.
b)
Add "reorderLevel" and "reorderQuantity" attributes used by a new
deplete() method in the InventoryProduct class. Use these to generate
new orders as InventoryProducts are sold.
c)
Add a deliver() method to the Supplier class that uses the
InventoryProduct's amountOnHand attribute to maintain the
InventoryProducts in the warehouse.
d)
Add "reorderLevel" and "reorderQuantity" to InventoryProduct. Create
a Warehouse class that monitors the
InventoryProducts' "amountOnHand", generating an order as levels drop
below a "reorderQuantity".
14
Single Select - Please select the best answer (one and only one
choice must be selected).
11) http://certify.torolab.ibm.com/figures/test486F18.gif
What is the BEST model change for the following new requirements in
the mortgage processing system?
a)
Add an updateAssessedValue( newValue ) method to the Mortgage class,
which uses newValue in collaboration with the Property's tax rates to
provide tax amounts.
b)
Add an updateAssessedValue( newValue ) method to the Property class,
which uses newValue in collaboration with the TaxingAuthority's tax
rates to provide tax amounts.
c)
Add an updateAssessedValue( newValue ) method to the TaxingAuthority
class, which uses its tax rates to provide tax amounts.
d)
Add an updateAssessedValue( newValue ) method to the Property class,
which uses its tax notes to provide tax amounts.
Single Select - Please select the best answer (one and only one
choice must be selected).
12)
Which of the following details are required in OO diagrams?
a)
Show navigability of associations in conceptual class diagrams.
b)
Show different scenario of a use case on the same interaction diagram
for clear understanding.
c)
Show message sequence numbers in collaboration diagrams.
d)
If asynchronous messages exist in a scenario, show them in
interaction diagrams.
Multiple Select - Please select all of the correct answers (this
question has 2 correct choices).
13) http://certify.torolab.ibm.com/figures/test486F16.gif
Refer to the state diagram in Figure State for MortgageApplication.
Suppose that there is a requirement to add state transitions to
15
a "Cancelled" state from any states except "Closed". Which of the
following are valid ways to add the "Cancelled" state?
a)
Funnel all cancellations from only one of the other states.
b)
Add a "Cancelled" superstate to the diagram.
c)
Add transitions from "Submitted" and "Qualified" to a new "Cancelled"
state.
d)
Add an "Active" superstate that handles the transition
to "Cancelled".
Multiple Select - Please select all of the correct answers (this
question has 2 correct choices).
14) http://certify.torolab.ibm.com/figures/test486F19.gif
Which of the following is the BEST description of the sequence
diagram in Figure Interaction? When an instance of a:
a)
Person is asked for its assets, it sums the balances of each of its
asset Accounts.
b)
Customer is asked for its assets, it sums the balances of each of its
asset Accounts.
c)
Person is asked for its assets, it returns the balance of its asset
Account.
d)
Customer is asked for its assets, it returns the balance of its asset
Account.
Single Select - Please select the best answer (one and only one
choice must be selected).
15)
Software entropy is a phenomenon wherein programs begin with well
designed state, but as new functionalities are added, they lose their
structure. Refactoring of classes is done to avoid software entropy.
What are good practices to follow during refactoring?
a)
Renaming a method and moving a field from one class to another should
be done in small steps, testing changes as required.
b)
Break down classes that are heavily loaded with responsibilities into
16
smaller classes and distribute the responsibilities among them
effectively.
c)
Consolidate similar methods from different classes in the same type
hierarchy into a common super class wherever possible.
d)
Add functionality and refactor simultaneously in order to obtain an
efficient and effective design.
Multiple Select - Please select all of the correct answers (this
question has 3 correct choices).
16)
Which of the following are good practices to use while designing for
reuse?
a)
Define a persistence framework that provides services for persisting
objects.
b)
Use design patterns, wherein complete solutions are already defined.
c)
Use controller objects to control the flow of processes in the
system.
d)
Assign responsibilities to classes such that coupling between them
remains low.
e)
Design classes with low cohesion.
Multiple Select - Please select all of the correct answers (this
question has 2 correct choices).
17) http://certify.torolab.ibm.com/figures/test486F22.gif
A partial class diagram of a college course management application is
shown in Figure studentInstructor. A student knows all of the
instructors he is registered with. Similarly, an instructor also
knows all the students who are registered with him. A new requirement
is added which specifies that an instructor can also be a student for
some courses. What is the BEST partial application redesign shown in
the Figure?
a)
Design 'A'
b)
Design 'B'
17
c)
Design 'C'
d)
Design 'D'
e)
Design 'E'
Single Select - Please select the best answer (one and only one
choice must be selected).
18)
When using OOAD artifacts to organize and assign team
responsibilities on a project, it is BEST to:
a)
evenly distribute use cases among team members and have them work as
independently as possible in order to minimize code dependencies
b)
designate one team for implementing interaction diagrams related to
the "common code path" and another team for implementing interaction
diagrams related to "code path variations" (for example ? conditional
or error paths)
c)
divide teams according to package diagram dependencies and utilize
use cases to schedule the work for the individual team members
d)
divide teams according to the layers in the software architecture and
have them work as independently as possible in order to minimize
dependencies between the layers}
Single Select - Please select the best answer (one and only one
choice must be selected).
19) An iterative development process:
a)
represents a structured methodology, which includes functional
decomposition.
b)
is a technique for managing complexity and plans for change during
software development.
c)
is a top-down approach without the dataflow diagrams.
d)
is equivalent to an incremental development process.
Single Select - Please select the best answer (one and only one
18
choice must be selected).
20)
If a use case had a requirement "Calculate account balance," which
OOAD artifact would be the BEST source for determining the name of
the public method used to invoke the operation?
a)
Use case
b)
Interaction diagram
c)
Class diagram
d)
Activity diagram
Single Select - Please select the best answer (one and only one
choice must be selected).
21) http://certify.torolab.ibm.com/figures/test486F4.gif
When creating the use cases related to the "Prepare for an Event"
scenario in the Figure ChefScenario, which one of the following BEST
represents the type of terminology that the use cases should contain
a)
chef, menu, recipes, ingredients
b)
end user, bill of fare, cooking specifications, food contents
c)
chef object, menu object, recipe object, ingredient object
d)
person record, menu print stream, recipe container, ingredient array
Single Select - Please select the best answer (one and only one
choice must be selected).
22) http://certify.torolab.ibm.com/figures/test486F1.gif
What are the system's actors in the diagram, Figure Use Case ?
a)
Clerk, Manager
b)
Clerk, Manager, Customer
c)
Clerk, Manager, Bank network
d)
19
Clerk, Manager, Bank network, Customer
Single Select - Please select the best answer (one and only one
choice must be selected).
23)
When designing the user interface for an application, if it is
unclear what skill level the end user of an application will possess,
which of the following is the BEST approach to take?
a)
Define the level of skill that will be required by the end user and
make the necessary arrangements for educating the users.
b)
Define the level of skill that will be required by the end user and
provide detailed on-line help that can be accessed by the users when
needed.
c)
Prototype portions of the user interface and perform some usability
tests to identify any problem areas. Document any issues in the
product readme and have the users read it before using the product.
d)
Prototype portions of the user interface and perform some usability
tests to determine the users level of satisfaction. Make any
necessary changes and repeat the process.}
Single Select - Please select the best answer (one and only one
choice must be selected).
24)
Which of the following is true about a deployment diagram?
a)
Since there is always some kind of response to a message, the
dependencies are two-way between deployment components.
b)
Dependencies between deployment components tend to be the same as the
package dependencies.
c)
Deployment diagrams are NOT to be used to show physical modules of
code.
d)
Deployment diagrams do NOT show physical distribution of a system
across computers
Single Select - Please select the best answer (one and only one
20
choice must be selected).
25) http://certify.torolab.ibm.com/figures/test486F13.gif
Referring to the diagram in Figure Interface, which of the following
are true?
a)
Classes "X" and "Y" are subclasses of Mortgageable.
b)
Instances of "X" and "Y" can be passed as parameters declared as type
Mortgageable.
c)
"X" and "Y" must implement a getAppraisedValue() method.
d)
There are instances of Mortgageable in the production system.
Multiple Select - Please select all of the correct answers (this
question has 2 correct choices).
26) A resulting benefit of using polymorphism is reduction of:
a) methods in the associated classes
b) subclasses needed to accomplish the same functionality
c) case statements and conditionals
d) coupling between classes in the system
Single Select - Please select the best answer (one and only one
choice must be selected).
27 http://certify.torolab.ibm.com/figures/test486F20.gif
eStore.com sells small appliances over the Internet. Currently, the
store's catalog includes over 50 appliances from 10 different
suppliers. A partial class diagram is shown in Figure Sample 1. There
are two new requirements for eStore.com: discounts for damaged goods,
and searches by size and color. Using Figure Sample 2, which of the
following is the BEST way to extend the class diagram to handle these
requirements?
a) Extend the InventoryProduct class to handle the new
requirements.
b) Create a new class "PhysicalProduct" that represents an actual
product in the warehouse. Associate the PhysicalProduct with its
related InventoryProduct.
c) Add new capabilities to the Inventory class for the management of
its Products.
d) No changes are needed due to these requirements.
21
Single Select - Please select the best answer (one and only one
choice must be selected).
28) When creating a subclass, the:
a) selected superclass should be chosen because it has some methods
the subclass can reuse, even if others do not apply.
b) class name should normally be a qualification of its superclass'
name
c) subclass should be of the same type as all of its superclasses
d) superclass should be marked as abstract
Multiple Select - Please select all of the correct answers (this
question has 2 correct choices).
29) http://certify.torolab.ibm.com/figures/test486F14.gif
Given the requirement statement, which of the following public
methods would be used in a related sequence diagram?
a) aBalance.subtract( anAmount )
b) anAmortizationTable.calculateInterestUsing( aPayment )
c) anAmortizationTable.apply( aPayment )
d) aMortgage.apply( aPayment )
Multiple Select - Please select all of the correct answers (this
question has 2 correct choices).
30) http://certify.torolab.ibm.com/figures/test486F18.gif
What is the BEST model change for the following new requirements in
the mortgage processing system?
a) Add an updateAssessedValue( newValue ) method to the Mortgage
class, which uses newValue in collaboration with the Property's tax
rates to provide tax amounts.
b) Add an updateAssessedValue( newValue ) method to the Property
class, which uses newValue in collaboration with the
TaxingAuthority's tax rates to provide tax amounts.
c) Add an updateAssessedValue( newValue ) method to the
TaxingAuthority class, which uses its tax rates to provide tax
amounts.
d) Add an updateAssessedValue( newValue ) method to the Property
class, which uses its tax notes to provide tax amounts.
22
Single Select - Please select the best answer (one and only one
choice must be selected).
1. Which two are the most interested for an Architect?
a. Scalability
b. Availability
c. Manageability
d. Reliability
e. Maintainability
f. Extensibility
2. Which can do more complicated mapping?
CMP or BMP?
_________________________________________________________________
XML
See ,there are the following rules for xml declaration:
1.The document type declaration must be placed between the XML
declaration and the first element (root element) in the document.
2.The keyword DOCTYPE must be followed by the name of the root
element in the XML document.
3. The keyword DOCTYPE must be in upper case.
Note the following rules for mixed content
1.(#PCDATA) must come first in the mixed content declaration.
2.The operator (*) must follow the mixed content declaration if
children elements are included.
As all these rules are fullfilled by conditions (a) and (c) so answer
is......... a ,c.
______________________________________________________________________
3. Which of the following code is valid?
a)<!DOCTYPE test [ <!ELEMENT test (#PCDATA)]
b)<!DOCTYPE test [ <!ELEMENT test.dtd (elm1|elm2|#PCDATA) ]
c)<!DOCTYPE test [ <!ELEMENT test.dtd (#PCDATA|elm1|elm2)* ]
<!ELEMENT elm1 (#PCDATA)
<!ELEMENT elm2 (#PCDATA)
d)<!DOCTYPE test [ <!ELEMENT test test (#PCDATA)]
23
e)<!DOCTYPE test [ <!ELEMENT test "test" (#PCDATA)]
Answer is a) and c). But I think a) is the only
correct choice, because the declaration should start from the
root element test.
If an RMI parameter implements java.rmi.Remote, how is
it passed "on-the-wire?"
Choice 1
It can never be passed.
Choice 2
It is passed by value.
Choice 3
It cannot be passed because it implements
java.rmi.Remote.
Choice 4 (Correct)
It cannot be passed unless it ALSO implements
java.io.Serializable.
Choice 5
It is passed by reference.
----------------public synchronized void txTest(int i) {
System.out.println("Integer is: " + i);
}
What is the outcome of attempting to compile and
execute the method above, assuming it is implemented
in a stateful session bean?
Choice 1
Run-time error when bean is created
Choice 2
The method will run, violating the EJB specification.
Choice 3 (Correct)
Compile-time error for bean implementation class
Choice 4
Compile-time error for remote interface
Choice 5
Run-time error when the method is executed
------------------What is the CORBA naming service equivalent of JNDI?
Choice 1
24
Interface Definition Language
Choice 2 (Correct)
COS Naming
Choice 3
Lightweight Directory Access Protocol
Choice 4
Interoperable Inter-Orb Protocol
Choice 5
Computer Naming Service
----------------------InitialContext ic = new InitialContext();
TestHome th = (TestHome)
ic.lookup("testBean/TestBean");
TestRemote beanA = th.create();
TestRemote beanB = th.create();
TestRemote beanC = th.create();
beanC.remove();
TestRemote beanD = th.create();
TestRemote beanE = th.create();
beanC = th.create();
Given the above code, container passivates which
bean instance first if the container limited the bean
pool size to four beans and used a
"least-recently-used" algorithm to passivate?
Choice 1
Bean A
Choice 2
Bean B
Choice 3
Bean C
Choice 4 (Correct, Since only Statefull session bean and Entity
Bean can be
passivated, and Entitybean can not call as th.create() normally,
I take it
as statefull session bean)
Bean D
Choice 5
Bean E
------------------------Which one of the following phenomena is NOT addressed
by
read-consistency?
25
a Phantom read (Correct)
b Cached read
c Dirty read
d Non-repeatable read
e Fuzzy read
-------------------------Which one of the following methods is generally called
in both
ejbLoad() and ejbStore()?
a getEJBObject()
b getHandle()
c remove()
d getEJBHome()
e getPrimaryKey() (Correct)
----------------------------public void ejbCreate(int i) {
System.out.println("ejbCreate(i)");
}
Given a currently working stateless session bean, what
will be the outcome
upon deploying and executing the bean if you added the
above unique method
to the implementation class of a stateless session
bean (and made no other
changes)?
a Compile time error during stub/skeleton generation (Correct)
b Compile time error for home interface
c Code will compile without errors.
d Compile time error for remote interface
e Compile time error for bean implementation
---------------------------------Given the above code in your stateless session bean
business method
implementation, and the transaction is
container-managed with a Transaction
Attribute of TX_SUPPORTS, which one of the following
is the first error
generated?
a Error when compiling home interface
26
b Error while generating stubs and skeletons (Correct)
c NullPointerException during deployment
d Runtime error
e Compile-time error for the bean implementation
---------------------------------Which one of the following is the result of attempting
to deploy a
stateless session bean and execute one of the method M
when the bean
implementation contains the method M NOT defined in
the remote interface?
a Compile time error for remote interface
b Compile time error for bean implementation
c Compile time error during stub/skeleton generation
d Code will compile without errors. (Correct)
e Compile time error for home interface
-----------------------------Which one of the following characteristics is NOT true
of RMI and
Enterprise Java Beans?
a They must execute within the confines of a Java
virtual machine (JVM).
b They serialize objects for distribution.
c They require .class files to generate stubs and
skeletons.
d They do not require IDL.
e They specify the use of the IIOP wire protocol for
distribution. (InCorrect)
-----------------end
SSL is used to encrypt
a) All data
b) Data of IP layer, no header
c) Data of Physical layer, no header
d) Data TCP/IP physical Layer, no header
Which is correct?
27
what features of firewalls can interfere with IIOP.
1) Port filtering
2) Load balancing
3) Address filtering
4) Network Address Translation
[two rights in total].
1 and 3. Firewalls do not do Load balancing, nor dns functions.
Common Architectures
Scalability
Scalability is the ability to economically support the required quality of service as the load increases.
Two types: Vertical and Horizontal
Vertical:
Achieved by adding capacity (memory, CPUs, etc.) to existing servers.
Requires few to no changes to the architecture of a system.
Increases: Capacity, Manageability
Decreases: Reliability, Availability (single failure is more likely to lead to system failure)
Vertical scalability is usually cheaper than horizontal scalability.
J2EE supports vertical scaling because of automatic lifecycle management. Adding more capacity to a
server allows it to
manage more components (EJBs, etc.).
Horizontal:
Achieved by adding servers to the system.
Increases the complexity of the system architecture.
Increases: Reliability, Availability, Capacity, Performance (depends on load balancing), Flexibility
Decreases: Manageability (more elements in the physical architecture)
J2EE supports horiz. scaling because the container and server handle clustering and load-balancing.
Availability and reliability are obtained through scalability.
Scalability affects capacity. The more scalable the system is the more capacity it can support. This must be
traded-off
against the complexity & manageability costs.
Maintainability
28
How related is this to Flexibility?
Flexibility is the ability to change the architecture to meet new requirements in a cost-efficient manner.
A flexible system should be more maintainable in the face of changes to the environment and/or to the
application itself.
Flexibility improves: Availability, Reliability, Scalability
Flexibility slightly decreases: Performance, Manageability
Flexibility is achieved via code that can be distributed across servers with load balancing that prevents one
system from
being overburdened. The use of a multi-tier architecture also helps achieve flexibility.
Reliability
The ability to ensure the integrity and consistency of the application and all of its transactions.
You increase reliability through the use of horizontal scalability, i.e., by adding more servers. This only
works up to a
certain point, though.
When you increase reliability you increase availability.
Availability
Availability is about assuring that services are available to the required number of users for the required
proportion of
time.
Extensibility
The ability to modify or add functionality without impacting the existing functionality.
The key to an extensible design is to make an effective OO design. Extensibility pays the most towards the
font end of a
system.
Some rough guidelines:
More than 25 top-level classes will lead to problems
Every use case should be able to be implemented using domain model methods
29
J2EE supports extensibility because it is component-based and allows you to separate the roles of an app.
JSPs can handle
presentation. Servlets can handle routing, and EJBs can handle business logic.
Performance
Architectural performance is concerned with creating an architecture that forces end-to-end performance.
The purpose of an architecture that ensures performance is to control expensive calls and to identify
bottlenecks.
If you know the boundaries of the various parts of the system, the technologies, and the capabilities of the
technologies you
can do a good job of controlling performance.
You want to minimize the number of network calls your distributed app makes – make a few “large” calls
that get a lot of data
vs. lots of calls that get small amounts of data.
Try to minimize process-to-process calls because they are expensive.
Use resource pooling to reduce the number of expensive resources that need to be created like network
connections, database
connections, etc.
Manageability
Manageability refers to the ability to manage a system to ensure the health of the system.
A single tier or monolithic app would be more manageable from a management perspective than a multi-tier
system but this must
be weighed against the possibility of a change rippling through a monolithic app.
A simple architecture may not be as flexible or available as a more complex system but the amount of effort
required to keep
the system up & functioning will be less.
A component-based architecture like J2EE offsets some of the manageability problems caused by a multitier system.
Security
30
Security ensures that info is neither modified nor disclosed except in accordance with the security policy.
Tradeoffs: personal privacy, ease of use, and expense.
A highly secure system is:
More costly
Harder to define and develop
Requires more watchdog activities
Principles of Security:
Identity – The user is correctly ID’d thru an authentication mechanism
Authority – The user can perform only allowed activities
Integrity – Data can only be modified in allowed ways
Privacy – Data is disclosed to authorized entities in authorized ways
Auditability – The system maintains logs of actions taken for later analysis
Design Patterns
1) State the benefits of using design patterns.
Improves communication between designers by use of pattern names vs. the details of the patterns.
Captures experience of solving a type of problem.
Provide a way of reusing design.
Provide a mechanism for making designs more reusable.
Provides a mechanism for systematizing the reuse of things that have been seen before.
Can be used to teach good design.
2) From a list, select the most appropriate design pattern for a given scenario.
3) State the name of a GOF design pattern given the UML diagram and/or a brief description of the pattern’s
functionality.
4) Select from a list benefits of a specified GOF pattern. Identify the GOF pattern associated with a
specified J2EE feature.
J2EE Essential Patterns
31
Abstract Factory
Creational
Provide an interface for creating families of related or dependent objects (products) without specifying their
concrete
classes.
J2EE technology uses this pattern for the EJB Home interface, which creates new EJB objects.
It isolates concrete classes.
It makes exchanging product families easy.
It promotes consistency among products.
Supporting new kinds of products is difficult.
Decorator
Structural
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to
subclassing for
extending functionality.
In J2EE technology, The EJB object is a decorator for the bean because the bean’s functionality is expanded
to include remote
dehavior.
Factory Method (Virtual Constructor)
Creational
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory
Method lets a class
defer instantiation to subclasses.
J2EE technology uses this pattern for the EJB Home interface, which creates new EJB objects.
Eliminates the need to bind application-specific classes into your code.
Gives subclasses a hook for providing an extended version of an object being constructed.
Proxy
Structural
Provide a surrogate or placeholder for another object to control access to it.
The EJB’s remote interface acts as a proxy for the bean. Proxy is also used in RMI.
Other J2EE patterns
32
Façade
Structural
Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that
makes the
subsystem easier to use.
Can use to achieve runtime binding without using inheritance. The Session Entity Façade pattern is a
derivation of Façade
that uses a Session bean as a façade for multiple Entity beans.
Command
Behavioral
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or
log requests,
and support undoable operations.
The Command pattern can be used to provide pluggable behavior which enforces client access to services.
Strategy
Behavioral
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the
algorithm vary
independently from clients that use it.
The Strategy pattern can be used to provide pluggable behavior which enforces client access to services.
Types of patterns
Creational: Involved with the process of object creation.
Structural: Deals with the composition of classes or objects.
Behavioral: Characterize the ways in which classes or objects interact and distribute responsibility.
Other GOF Patterns
Builder
Creational
Separate the construction of a complex object from its representation so that the same construction process
can create
different representations.
Lets you vary a product’s internal representation.
33
Isolates code for construction and representation.
Gives you finer control over the construction process.
Prototype
Creational
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this
prototype.
Hides the concrete product classes from the client.
Allows adding and removing products at run-time.
Can specify new object by varying the values of an object’s variables.
Singleton
Creational
Ensure a class only has one instance, and provide a global point of access to it.
Provides controlled access to a sole instance of a class.
It avoids polluting the name space with global variables that store sole instances.
Permits a variable number of instances.
More flexible than static methods.
Adapter
Structural
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that
couldn’t
otherwise because of incompatible interfaces.
Permits you to use an existing class that has an interface that does not match the one you need.
You want to create a reusable class that cooperates with unrelated or unforeseen classes.
The Object Adapter pattern can be used when you need to use several existing subclasses but it is
impractical to adapt their
interface by subclassing every one.
Bridge
Structural
Decouple an abstraction from its implementation so that the two can vary independently.
Use when you want to avoid a permanent binding between an abstraction and its implementation.
Use when both the abstractions and the implementations should be extensible by subclassing.
Changes in the implementation should not impact clients.
Composite
Structural
34
Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients treat
individual objects and
compositions of objects uniformly.
Pattern defines hierarchies consisting of primitive objects and composite objects.
Allows clients to treat composite structures and individual objects uniformly.
Makes it easier to add new kinds of components.
A disadvantage is that it can make a design overly general.
Flyweight
Structural
Use sharing to support large numbers of fine-grained objects efficiently.
Chain of Responsibility
Behavioral
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the
request. Chain
the receiving objects and pass the request along the chain until an object handles it.
Interpreter
Behavioral
Given a language, define a representation for its grammar along with an interpreter that uses the
representation to interpret
sentences in the language.
Iterator
Behavioral
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying
representation.
Mediator
Behavioral
Define an object that encapsulates how a set of objects interacts. Mediator promotes loose coupling by
keeping objects from
referring to each other explicitly, and it lets you vary their interaction independently.
Memento
Behavioral
Without violating encapsulation, capture and externalize an object’s internal state so that the object can be
restored to
35
this state later.
Observer
Behavioral
Define a one-to-many dependency between objects so that when one object changes state, all its dependents
are notified and
updated automatically.
State
Behavioral
Allow an object to alter its behavior when its internal state changes. The object will appear to change its
class.
Template Method
Behavioral
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method
lets subclasses
redefine certain steps of an algorithm without changing the algorithm’s structure.
Visitor
Behavioral
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new
operation
without changing the classes of the elements on which it operates.
Sun Certified Enterprise Architect for Java 2
Study Notes
Topic: EJB (Enterprise JavaBeans)
Objectives:
1. List the required classes/interfaces that must be provided for an EJB.
2. Distinguish stateful and stateless Session beans
3. Distinguish Session and Entity beans
4. Recognize appropriate uses for Entity, Stateful Session, and Stateless Session beans
5. State benefits and costs of Container Managed Persistence
6. State the transactional behavior in a given scenario for an enterprise bean method with a specified
transactional
attribute as defined in the deployment descriptor
36
7. Given a requirement specification detailing security and flexibility needs, identify architectures that
would fulfill
those requirements
8. Identify costs and benefits of using an intermediate data-access object between an entity bean and the data
resource
9. State the benefits of bean pooling in an EJB container
10. State the benefits of passivation in an EJB container
11. State the benefit of monitoring of resources in an EJB container
12. Explain how the EJB container does lifecycle management and has the capability to increase scalability
References:
Symbol: Reference:
JENS Java Enterprise In a Nutshell, Flanagan, Farley, Crawford, & Magnusson, O’Reilly, 1999.
MEJB Mastering Enterprise JavaBeans, Ed Roman, Wiley, 1999
EJB Enterprise JavaBeans 2nd Edition, Monson-Haefel, O’Reilly, 2000
Details:
OBJECTIVE #1: List the required classes/interfaces that must be provided for an EJB.
SOLUTION:
For all types of EJBs, you need to provide three Java interfaces/classes to fully describe the EJB to an EJB
container:
1. The HOME INTERFACE which takes the form:
import javax.ejb.*;
import java.rmi.RemoteException;
public interface MyHomeInterface extends EJBHome
{
public MyRemoteInterface create()
throws RemoteException;
....
}
2. The REMOTE INTERFACE which takes the form:
import javax.ejb.*;
import java.rmi.RemoteException;
public interface MyRemoteInterface extends EJBObject
{
37
// business method definitions – all of which can throw
// a RemoteException
}
3. The BEAN CLASS itself, which takes two forms:
For Session Beans:
import javax.ejb.*;
import java.rmi.RemoteException;
public class MyBean implements SessionBean
{
// required methods
public void ejbCreate() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext() {}
// business method implementations
}
For Entity Beans:
import javax.ejb.*;
import java.rmi.RemoteException;
public class MyBean implements EntityBean
{
// entity bean methods – see EJNS p.199 for details
}
4. Additionally, for ENTITY BEANS, you must also provide a PRIMARY KEY CLASS, which takes the
form:
import javax.ejb.*;
public class MyBeanPK implements java.io.Serializable
{
public String someFieldToUseAsPK;
public MyBeanPK() { someFieldToUseAsPK = null; }
public MyBeanPK(String s) { someFieldToUseAsPK = s; }
}
38
The primary key can only be guaranteed to return the same entity if it is used within the container that
produced the key. If
two EJB objects have the same home and same PK they are considered identical.
A primary key must implement the Serializable interface.
EJB 1.1 requires that the hashCode and equals methods be overridden.
EJB 1.1 allows the PK to be defined by the bean developer or its definition can be deferred until
deployment.
A default (no-arguments) PK constructor is required for CMP. When a new bean is created the container
automatically
instantiates the PK, and populates it from the bean class’s CMP fields.
All fields in the PK class must be declared public.
The String class and the wrapper classes for the primitive data types can also be used as PKs. In this case
there is no
explicit PK class. However, there must still be an identifiable primary key within the bean class itself.
(there are some special rules for this primary key class when using container managed persistence. See
EJNS p.197)
OBJECTIVE #2: Distinguish stateful and stateless Session beans
SOLUTION:
Session beans can be either stateless of stateful.
Stateless Session beans do not maintain state across method calls. The Session bean returns to the same state
after each
successive call to one of its methods from a client. This makes a stateless Session bean poolable for
performance and
accessible from multiple clients (one at a time) without fear of conflict. Stateless Session beans are never
passivated, but
just destroyed (or removed from the pool) when no longer needed. Stateless beans cannot participate in any
transaction
39
synchronization (e.g. implement interface SessionSynchronization). A stateless session bean is only
dedicated to an EJB
object for the duration of the method.
Stateful Session beans maintain a state that can be accessed and changed across multiple client interactions
with the bean’s
methods. Stateful Session beans are accessed by only a single client and can be passivated by the container.
At deployment time, you indicate to the container whether a Session bean is stateful or stateless with an
identifier in the
deployment descriptor.
OBJECTIVE #3: Distinguish Session and Entity beans
SOLUTION:
There are two types of beans in the EJB specification, Session and Entity beans.
Session beans represent business logic, rules, and workflow. They perform some sort of work for the client
that is calling
them. Important features of Session beans:
1. Two types, stateful and stateless (see last objective above)
2. Never used by more than one client at a time
3. Lifetime is roughly the same as the period during which the client interacts with the bean
Entity beans represent data that is stored in a database or some persistent storage. Important features of
Entity beans:
1. Persistent across client sessions and the lifetime of the server
2. Have a unique identity used for lookup
3. Multiple clients can access at once – the container manages this concurrency.
4. Persistence of the data the bean represents is either “container” or “bean” - managed
OBJECTIVE #4: Recognize appropriate uses for Entity, Stateful Session, and Stateless Session beans
SOLUTION:
Entity beans do not contain business process logic; they model data. Examples of persistent data include
things like
“account”, “customer”, “order line”, etc.
40
Session beans model business processes such as performing a credit card verification, reserving a room, etc.
Some processes
require a single method call (stateless) to complete, while other processes may require repeated calls that
require storing
state information across these calls (stateful). An example of a stateful process would be a bean that tracks
an on-line
shopper’s cart, the contents of which must be maintained across multiple calls to the bean. Code that
represents a bank
teller interacting with a customer might also need to track account balance or credit limit across multiple
banking
transactions in a single interaction with the customer.
Recognizing the type of bean to use begins by asking, “is this a process or a persistent thing I’m working
with” (session
versus entity) and if it is a process, asking “is this a single method call with no need to reference prior state
or do I
need multiple transactions with a stored state to accomplish this process?” (stateless versus stateful).
OBJECTIVE #5: State benefits and costs of Container Managed Persistence
SOLUTION:
Container Managed Persistence (CMP) refers to an EJB container providing automatic persistence for Entity
beans. The
container performs all aspects of data access for the entity bean, including saving, loading, and finding
components of the
data.
Stated Benefits: (nets out to: rapid application dev and portability)
Database Independence - No need to hard code against a specific database API to accomplish these things
Code Reduction – CMP performs all data access logic without the need to write any JDBC code, reducing
the amount of code
needed and hence development time for the bean.
41
Enhances Software Quality – JDBC code is not “type-safe” and is frequently buggy because it cannot be
verified until runtime.
The developer who wrote the container likely writes better data access code than you do and usually
provides contained tools
that allow detecting of errors at compile time. The better the container, the more your Entity bean code
improves in quality.
Real Life Costs: (nets out to: limits flexibility, portability not 100%)
Not all containers require you to write absolutely zero persistence code. Most containers at least require you
to navigate a
wizard to specify persistent fields and that you specify the logic for your finder methods.
If there is a bug, it is hard to see what database operations the container is actually executing in order to
troubleshoot
the problem.
Some containers may not support mapping of complex field types to underlying storage. Example: your
entity bean class has a
vector as a persistent member field. You may have to convert this vector to some other type that the
container can persist
for you.
Portability across databases is not yet perfect. Specifying persistence semantics is not standardized yet and
what BEA
requires you to do to map your objects to relational fields may be inconsistent with another container
vendor. If mapping
your objects to relational tables is not 1:1 or you need complicated SQL joins in finder methods, some
containers lack the
ability to handle this.
May require sophisticated mapping tools to define how the bean’s fields map to the database.
EJB 1.1 allows the CMP fields to include remote references to EJB objects (remote interface types) and EJB
homes (home
interface types). EJB 1.0 only allowed Java primitives and serializable types.
42
Data Aliasing
Eager State Loading
OBJECTIVE #6: State the transactional behavior in a given scenario for an enterprise bean method with a
specified
transactional attribute as defined in the deployment descriptor
SOLUTION:
Transactional attributes of bean methods are specified in the deployment descriptor. Here are the attributes
and what they
mean (MEJB p.706):
TX_BEAN_MANAGED The bean programmatically controls it’s own tx
EJB 1.0 Only boundaries via JTA.
NotSupported The bean CANNOT be involved in a
transaction at all. When a bean method is called, any existing tx is suspended.
Required The bean must ALWAYS run in a transaction. If a tx is already running, the bean joins in that tx.
If not, the
container starts a tx for you.
RequiresNew The bean must ALWAYS run in a NEW transaction. Any current tx is suspended.
Supports If a transaction is underway, the bean joins in that tx, otherwise runs with no tx at all.
Mandatory Mandates that a transaction must already be running when the bean method is called or an
exception is thrown back
to the caller.
Never If a tx is underway the bean will throw a
EJB 1.1 Only RemoteException, otherwise the method
Runs normally without a tx.
OBJECTIVE #7: Given a requirement specification detailing security and flexibility needs, identify
architectures that would
fulfill those requirements.
43
SOLUTION:
Security: EJB servers can provide up to three types of security service:
1. Authentication – validates the identity of the user – usually via JNDI
A client using JNDI can provide authenticating information using the JNDI API to access a server or
resources in the server.
2. Access Control – validates what the user can and cannot do. EJB 1.1 changed authorization to be based
on
java.security.Principal types rather than Identity types and to be role-driven rather than method-driven.
Deployment descriptors include tags that declare which logical roles are allowed to access which bean
methods at runtime.
Security roles are mapped to real-world user groups and users when the bean is deployed. Once the securityrole tags are
declared they can be associated with methods in the bean using method-permission tags.
3. Secure Communication – client server communication channels can be secured by physical isolation or
encrypting the
conversation - usually via SSL. Encryption usually involves the exchange of keys to decode the encrypted
data.
Most EJB servers address Secure Communications through SSL encryption and also provide some
mechanism such as JNDI for
Authentication. The EJB 1.1 Specification only addresses Access Control on the server side.
For a complete discussion of J2EE security services and topics like Role-Driven versus Method-Driven
access control, see EJB
Chap 3: Security (p.71).
OBJECTIVE #8: Identify costs and benefits of using an intermediate data-access object between an entity
bean and the data
resource.
SOLUTION:
44
EJBs are remote objects that consume significant system resources and network bandwidth. You can use
Data Access Objects to
encapsulate the logic required to access databases.
Data Access Objects:
Allow EJBs to delegate responsibility for database access and free them from complex data access routines.
Make code more maintainable.
Provide an easier migration path to CMP
Allow you to adapt data access to different schemas and different databases.
OBJECTIVE #9: State the benefits of bean pooling in an EJB container.
SOLUTION:
EJB clients interact with remote interfaces that are implemented by EJB Object instances. This indirect
access to the bean
instance means that there is no fundamental reason to keep a separate copy of each bean for each client. The
server can keep
a much smaller number of beans instantiated in a “pool” that serves a large number of clients. The container
simply copies
data into or out of these “pooled instances” as necessary. Benefit: greatly reduces the server resources
required to server
the same number of clients.
OBJECTIVE #10: State the benefits of passivation in an EJB container.
SOLUTION:
An EJB container can choose to temporarily serialize a bean and store it to the server filesystem or other
persistent store
so that it can optimally manage resources. This is called passivation. The benefit of passivation is to allow
the EJB
container to make the best possible use of server resources by passivating a bean to free up resources and
then re-activating
45
it when resources are available.
Note: A session bean can be passivated only between transactions, and not within a transaction.
OBJECTIVE #11: State the benefit of monitoring of resources in an EJB container.
SOLUTION:
An EJB container can achieve greater levels of performance and scalability by monitoring server resources
and using
techniques to share resources (such as instance pooling and activation/passivation) and also techniques to
synchronize object
interactions (such as managing concurrency, and transactional control) to optimally serve remote objects to
clients.
OBJECTIVE #12: Explain how the EJB container does lifecycle management and has the capability to
increase scalability.
SOLUTION:
The EJB container uses two fundamental strategies to perform lifecycle management, instance pooling and
passivation/activation.
Instance pooling reduces the number of component instances, and therefore resources, needed to service
client requests. In
addition, it is less expensive to reuse pooled instances than to frequently create and destroy instances. Since
clients never
access beans directly there’s no real reason to keep a separate copy of each bean for each client.
EJB Containers implement instance pooling (a significant performance and scalability strategy) by
managing the lifecycle of
beans.
An entity bean exists in one of three states:
1. No State (has not been instantiated yet)
2. Pooled State (instantiated by not associated with the EJB Object)
3. Ready State (instantiated and associated).
46
If a client request is received and no entity bean instance is associated with the EJB Object connected to the
client, an
instance is retrieved from the pool and assigned to the EJB Object. Once an instance is assigned to an EJB
object the
ejbActivate method is called. This is called instance swapping. Instances are selected based on the vendor’s
choice of a FIFO
or LILO strategy. The container can manage the number of instances in the pool and hence control
performance.
When an entity bean instance is activated, transient fields contain arbitrary values and must be reset in the
ejbActivate
method.
For a CMP bean the CMP fields are automatically synchronized with the database after ejbActivate has been
invoked. In BMP
after ejbActivate has completed you use the ejbLoad method to synchronize fields.
Entity beans can be passivated at any time provided the instance is not currently executing a method.
Passivation of an entity bean is simply a notification that the instance is about to be disassociated from the
EJB object.
Stateful Session Beans maintain a conversational state between method invocations. The container must
maintain this
conversational state for the life of the bean’s service to the client. Stateful Session beans do not participate
in instance
pooling but rather the container may choose to evict a stateful Session bean from memory to conserve
resources. The bean is
passivated (i.e. has it’s “state” serialized to disk) and disassociated with the EJB Object. The client is
completely unaware
of this performance move on the part of the container. When the client invokes another method on the
EJBObject, a new
instance is created and populated with the passivated state (called “activation”).
47
The ejbPassivate method is called immediately prior to passivation of a bean instance. The ejbActivation
method is called
immediately following the successful activation of a bean instance.
Additional Notes
The EJB architecture is an architecture for component-based distributed computing. EJBs are components of
distributed
transaction-oriented enterprise applications.
Enterprise beans are intended to be relatively coarse-grained business objects (purchase order, employee
record).
Fine-grained objects (line item on a purchase order, employee’s address) should not be modeled as
enterprise bean components.
Stateful Session
Note: Sun’s EJB 1.1 spec states “Session beans are intended to be stateful. The EJB specification also
defines a stateless
Session bean as a special case of a Session Bean. There are minor differences in the API between stateful
(normal) Session
benas and stateless Session beans.”
A typical (stateful) session object has the following characteristics:
Executes on behalf of a single client. It is not shared among multiple clients.
Do not support concurrent access.
Can be transaction-aware
Updates shared data in an underlying database
Does NOT represent directly shared data in the database, although it may
Access and update that data
Is relatively short-lived
Is removed when the EJB container crashes. The client has to re-establish
a new session object to continue computation
By definition, a session bean instance is an extension of the client that creates it:
Its fields contain a conversational state on behalf of the session object’s client.
It typical reads and updates data in a database on behalf of the client. Within a
transaction, some of this data may be cached in the instance.
48
Its lifetime is controlled by the client.
Find methods are not used in session beans.
When a remove method is called on a session bean it ends the bean’s service to the client. The remote
reference becomes
invalid and any conversational state maintained by the bean is lost.
As soon as the server removes a stateful session bean its handle is invalid and will throw a
RemoteException when its
getEJBObject() method is invoked.
A stateful session object has a unique identity that is assigned by the container at create time. This identity,
in general,
does not survive a crash and restart of the container, although a high-end container impl can mask container
and server
crashes from the client. Session objects appear to be anonymous to a client.
If a timeout occurs the ejbRemove() method is not called. A stateful session bean cannot time out while a
transaction is in
progress. A session bean can timeout while it is passivated.
A stateful session bean cannot be removed while it is involved in a transaction.
The home interface allows a client to obtain a handle for the home interface. The home handle can be
serialized and written
to storage. Later, possibly in a different JVM, the handle can be de-serialized from storage and used to
obtain a reference
to the home interface.
When the handle is later de-serialized, the session object it returns will work as long as the session object
still exists on
the server. (An earlier timeout or server crash may have destroyed the session object. In this case the handle
is useless.)
Typically, a session object’s conversational state is not written to the database. A session bean developer
stores it in the
49
session bean instance’s fields and assumes its value is retained for the lifetime of the instance. On the other
hand, the
session bean must explicitly manage cached database data. (It can do this when participating in a
transaction.)
A session object’s conversational state may contain open resources, such as open sockets and open database
cursors. A
container cannot retain such open resources when a session bean instance is passivated. A developer of such
a session bean
must close and open the resources in the ejbPassivate and ejbActivate methods. As an example, the
ejbPassivate method must
close all JDBC connections and assign the instance’s fields that store these connections to null.
In EJB 1.1 when a bean is passivated the following types may be saved as part of the conversational state:
JNDI ENC (javax.naming.Context, but only when it references the JNDI ENC)
references to SessionContext,
refs to other beans (home & remote i/fs)
the JTA UserTransaction type.
The container must maintain any instance fields that reference objects of these types as part of the
conversational state
even if they are not serializable. Primitive types and serializable objects can also be part of the
conversational state.
In EJB, transient fields are not necessarily set back to their initial values but can maintain their original
values, or any
arbitrary value, after being activated. Care should be taken when using transient fields, since their state
following
activation is implementation independent. The ejbActivate method is called following the successful
activation of a bean
instance and can be used to reset transient field values.
If the EJB container crashes, or a system exception is thrown by a method to the container, or a timeout
occurs while the the
bean is passivated then ejbRemove will not be invoked. This means any allocated resources will not be
released.
50
A session object’s conversational state is not transactional. It is not automatically rolled back to its initial
state if the
transaction in which the object has participated rolls back. The developer must use the afterCompletion
method to manually
reset the state.
Only a stateful session bean with container-managed transaction demarcation may implement the
SessionSynchronization
interface. This means that the bean can cache database data across several method calls before making an
update.
Clients are not allowed to make concurrent calls to a session object. This will cause a remote exception to be
thrown to the
second client.
A RuntimeException thrown from any method of a stateful session bean results in a transition to the “does
not exist” state.
From the client perspective, the corresponding stateful session object does not exist anymore. Subsequent
calls through the
remote interface will result in NoSuchObjectExceptions.
Calls to a session bean that has had ejbRemove invoked on it will result in NoSuchObjectExceptions.
Calls to a session bean that has timed out will result in NoSuchObjectExceptions.
Stateless Session
Stateless session beans have no conversational state.
All stateless session bean instances are equivalent when they are not involved in serving a client-invoked
method.
The home interface of all stateless session beans contains one create() method with no arguments. This is a
requirement of
the EJB spec. This means that the bean class only has one ejbCreate() method. (The ejbCreate method is not
actually invoked
by the create method.)
51
A timeout or remove operation simply invalidates the remote reference for the client. The bean instance is
not destroyed and
is free to service other client requests.
The term “stateless” signifies that an instance has no state for a specific client. However, the instance
variables of the
instance can contain state across client-invoked calls. An example is a database connection.
Everything that a stateless session bean needs to know to perform an operation has to be passed via the
method’s parameters.
Calling getPrimaryKey on a stateless session bean will cause a RemoteException to be thrown.
Calling remove(primaryKey) on a stateless (or stateful) session bean will cause a RemoteException to be
thrown.
Passivation and Activation are not needed for stateless session beans.
All session objects of the same stateless session bean within the same home have the same object identity
that is assigned by
the container.
Applications that use stateless session beans may scale somewhat better than those using stateful session
beans. However,
this benefit may be offset by the increased complexity of the client application that uses stateless beans.
A stateless session bean must not implement the SessionSynchronization interface.
A RuntimeException thrown from any method of a stateless session bean results in a transition to the “does
not exist” state.
From the client perspective, the stateless session object continues to exist. The client can continue accessing
the session
object because the container can delegate the client’s requests to another instance.
Entity
A typical entity object has the following characteristics:
52
Provides an object view of data in the database
Allows shared access from multiple users
Can be long-lived (lives as long as the data in the database)
The entity, its primary key, and its remote reference survive the crash of the EJB
container. If the state of an entity was being updated by a transaction at the time the container crashed, the
entity’s state
is automatically reset to the state of the last committed transaction. The crash is not fully transparent to the
client – the
client may receive an exception if it calls an entity in a container that has had a crash.
A good rule of thumb is that entity beans model business concepts that can be expressed as nouns. They are
usually persistent
records in a database.
Constructors should never be defined in the bean class. The default ctor must be available to the container.
(It is
automatically generated for a class if no ctors are provided.)
In EJB 1.1 the ejbCreate() method always returns the primary key type. With CMP this method returns null.
It is the
container’s responsibility to create the primary key.
The findByPrimaryKey() method is not defined for CMP entity beans. With CMP you do not explicitly
declare find methods in the
bean class. The EJB container generates the find methods automatically at deployment time. In CMP any
find method included in
the home interface must be explained to the container.
With BMP entity beans find methods must be defined in the bean class.
When a remove method is invoked on an entity bean, the remote reference becomes invalid and any data
that it represents is
deleted from the database.
The entity bean’s persistence can be implemented directly in the entity bean class or in one or more helper
classes (Data
Access Objects) provided with the entity bean class (BMP) or it can be delegated to the container (CMP).
53
Directly coding the data access calls in the entity bean class may make it more difficult to adapt the entity
bean to work
with a database that has a different schema or with a different type of database. Use of a DAO could allow
adapting the data
access to different schemas or databases.
The advantage of using CMP is that the entity bean can be largely independent from the data source in
which the entity is
stored. CMP does not make use of DAOs (obviously).
For CMP the data access components are generated at deployment time by the container tools. An entity
bean using CMP must not
have explicit data access. The Bean Provider is responsible for using the cmp-field elements of the
deployment descriptor to
declare the instance’s fields that the container must load and store at defined times. The fields must be
defined in the
entity bean class as public and must not be defined as transient.
The types that can be assigned to a container-managed field are: Java primitives, Java serializable types, and
references of
EJBs remote or home interfaces.
CMP has the following limitations:
Data Aliasing - An update of a data item done through a container-managed field of one entity bean may not
be visible to
another entity bean in the same transaction if the other entity bean maps to the same data item.
Eager Loading of State – The container loads the entire object stateinto the container-managed fields before
invoking the
ejbLoad method.
An entity bean instance is always in one of the following three states:
Does not exist
No instance of the bean exists.
54
Pooled
An instance in pooled state is not associated with any particular entity object identity.
Until it is requested the bean instance remains inactive unless it is used to service a find
request. Bean instances in the Pooled state typically service find requests since they
aren’t busy and find methods do not depend on the instance’s state.
Ready
An instance in the ready state is assigned an entity object identity.
A bean enters the Ready state via calls to ejbCreate/ejbPostCreate or ejbActivate.
Once in the ready state the container can call ejbLoad or ejbStore on the bean zero or
more times.
Each entity bean has its own pool of instances. All instances in the pool are considered equivalent, and
therefore any
instance can be assigned by the container to any entity object identity at the transition to the ready state. The
instance
does not move to the ready state during the execution of a finder method.
The container can passivate an entity bean instance within a transaction. Passivating an entity bean causes
the ejbStore
method to be invoked and the ejbPassivate method returns the instance to the pooled state.
When a find method is executed, each bean found will be realized by transitioning an instance from the
Pooled state to the
Ready state.
A RuntimeException thrown from any method of the entity bean class results in the transition to the “does
not exist” state.
From the client perspective, the corresponding entity object continues to exist. The client can continue
accessing the entity
object through its remote interface because the container can use a different instance to delegate the client’s
requests.
The container is not required to maintain a pool of instances in the pooled state. The pooling approach is an
example of a
possible implementation, but it is not required.
55
An instance of an entity bean with BMP can cache the entity object’s state between business method
invocations. An instance
may choose to cache the entire entity object’s state, part of the state, or no state at all.
When the container invokes ejbStore the instance must push all cached updates of the entity’s state to the
database.
When the container invokes ejbLoad the instance must discard any cached entity object’s state. The instance
may, but is not
required to, refresh the cached state by reloading it from the database.
The use of the ejbLoad and ejbStore methods for caching an entity object’s state in the instance works well
only if the
container can use transaction boundaries to drive the methods. Therefore, these methods are “unreliable” if
the transaction
attribute is set to Not Supported for the method or the bean.
The container will ensure appropriate synchronization for entity objects that are accessed concurrently from
multiple
transactions.
If an instance of a non-reentrant entity bean executes a client request in a given transaction context and
another request
with the same transaction context arrives for the same entity object, the container will throw a
RemoteException to the
second client. This allows a bean to be written as single-threaded and non-reentrant. It is not recommended
to write
reentrant entity beans.
Deployment Descriptor
Deployment descriptors contain the following kinds of information:
EJB name
Class names of the home if, remote if, and the bean
Primary key class name
Persistence type (BMP vs CMP)
Reentrant
56
Field names of CMP fields
Environmental or property entries
References to other beans (using the home & remote if names)
References to external resources like database connections
Security roles for accessing the bean/bean methods
Method permissions that map security roles to the methods they may invoke
Transactional attributes of the beans methods
In container-transaction elements specific method declarations override more general declarations.
The following methods must be assigned tx attributes for each bean in the DD:
Entity:
All business methods in the remote if (and superinterfaces)
Create methods in the home if
Find methods in the home if
Remove methods in the home (EJBHome) and remote (EJBObject) ifs
Session:
All business methods defined in the remore if (and superinterfaces)
In EJB 1.1 the bean deployer declares the timeout in a vendor-dependent manner. Timeouts are no longer
included in the
deployment descriptior.
Named properties can be declared in a bean’s deployment descriptor. They can be Strings or wrapper types.
Transaction Management
Dirty Read:
A dirty read occurs when the first transaction reads uncommitted changes made by a second transaction. If
the second
transaction is rolled back, the data read by the first transaction becomes invalid because the rollback undoes
the changes.
Repeatable Read:
A repeatable read is when the data read is guaranteed to look the same if read again during the same
transaction.
57
Phantom Read:
Phantom reads occur when new records added to the database are detectable by transactions that started
prior to the insert.
Queries will include records added by other transactions after their transaction has started.
Isolation levels are commonly used in database systems to describe how locking is applied to data within a
transaction.
Read Uncommitted:
The transaction can read uncommitted data. Dirty reads, nonrepeatable reads, and phantom reads can occur.
Read Committed:
The transaction cannot read uncommitted data. Dirty reads are prevented; nonrepeatable reads and phantom
reads can occur.
Bean methods with this isolation level cannot read uncommitted data.
Repeatable Read:
The tx cannot change data that is being read by a different tx. Dirty reads and nonrepeatable reads are
prevented; phantom
reads can occur. Bean methods with this isolation level have the same restrictions as Read Committed and
can only execute
repeatable reads.
Serializable:
The transaction has exclusive read and update privileges to data; different transactions can neither read nor
write the same
data. Dirty reads, nonrepeatable reads, and phantom reads are prevented. Most restrictive isolation level.
In EJB 1.1 isolation levels are not controlled through declarative attributes as was the case in EJB 1.0. In
EJB 1.1, the
deployer sets transaction isolation levels if the container manages the transaction. The bean developer sets
the transaction
isolation level if the bean manages the transaction.
As the isolation levels become more restrictive the performance of the system decreases because more
restrictive isolation
levels prevent transactions from accessing the same data.
58
Different EJB servers allow different levels of granularity for setting isolation levels; some servers defer this
responsibility to the database. In some servers, you may be able to set different isolation levels for different
methods,
while other products may require the same isolation level for all methods in a bean, or possibly even all
beans in the
container.
Bean managed txs in stateful session beans, however, allow the bean developer to specify the transaction
isolation level
using the API of the resource providing persistent storage.
For stateless session beans transactions that are managed using the UserTransaction must be started and
completed within the
same method.
For stateful session beans a tx can begin in one method and be committed in another because a stateful
session bean is only
used by one client.
General
The remote interface for an enterprise bean defines the bean’s business methods. It also has a method for
removing the bean.
Remote interfaces extend the javax.ejb.EJBObject interface.
The home interface defines the bean’s life cycle methods (creating, removing, finding). Home interfaces
extend the
javax.ejb.EJBHome interface. Find methods are only used by entity beans.
The bean class actually implements the bean’s business methods.
The primary key is a simple class that provides a pointer into the database and is only needed by entity
beans.
There is a standard mapping of the EJB architecture client-view contract to the CORBA protocols. The EJBto-CORBA mapping not
59
only enables on-the-wire interoperability among different impls of the EJB container but also allows nonJava clients to
access EJBs through standard CORBA APIs.
The bean class must define a default constructor.
The bean class must not define the finalize method.
The ejbCreate method for an entity bean using BMP returns a PK instance.
The ejbCreate method for a CMP entity bean returns a null for the PK instance.
The ejbCreate method for a session bean returns void.
EJB 1.1 doesn’t use the JARs manifest. The first thing reading the JAR is the deployment descriptor. EJB
1.1 deployment
descriptors are implemented in XML.
Having a client interact directly with entity beans is a common but bad design approach. Using a session
bean between a
client and an entity bean is a better approach. Session beans, if used properly, can substantially reduce
network traffic by
limiting the number of requests over the network to perform a task. Session beans can also reduce the
number of network
connections needed by the client.
Conceptually, an EJB server may have many containers, each of which may contain one or more types of
enterprise beans.
EJB, by default, prohibits concurrent access to bean instances. In other words, several clients can be
connected to one EJB
object, but only one client thread can access the bean instance at a time.
The EJB specification prohibits use of the synchronized keyword.
EJB prohibits beans from creating their own threads.
In EJB 1.1 all beans have a default JNDI context called the environment naming context (ENC). The default
context exists in
60
the namespace (directory) called “java:comp/env” and its subdirectories. When a bean is deployed any
beans it uses are mapped
into the directory “java:comp/env/ejb” so that the bean references can be obtained at runtime through a
simple and consistent
use of the JNDI ENC. This eliminates network and implementation specific use of JNDI to obtain bean
references.
EJB 1.1 provides a new object called a HomeHandle. The HomeHandle can be obtained from EJBObject. It
allows a remote home
reference to be stored and used later.
There is also a Handle object. A Handle is a serializable reference to the EJB object. A Handle allows an
EJB object remote
reference that points to the same type of session bean or the same unique entity bean that the handle came
from to be
recreated.
It might appear that Handle and the primary key do the same thing but they are different. Using the primary
key requires you
to have the correct EJB home – if you no longer have a reference to the EJB home you must use JNDI to get
a new home.
The Handle object is easier to use because it encapsulates the details of doing a JNDI lookup on the
container. With the
Handle the correct EJB object can be obtained in one method call rather than three. A handle can be used
with either type of
EJB. A handle allows you to work with a stateful session bean, deactivate the bean, and then reactivate it
later using the
handle.
The Handle is less stable than the PK because it relies on the networking configuration and naming to
remain stable.
Java RMI requires that all parameters and return values be either Java primitive types or objects that
implement the
Serializable interface. Serializable objects are passed by copy (passed by value).
61
Sun Certified Enterprise Architect for Java 2
Study Notes for Internationalization
General
An internationalized program has the following characteristics:
With the addition of localization data, the same executable can run worldwide.
Textual elements, such as status messages and the GUI component labels, are not hard-coded in
the program. Instead they are stored outside the source code and retrieved dynamically.
Support for new languages does not require recompilation.
Culturally-dependent data, such as dates and currencies, appear in formats that conform to the end
user's region and language.
It can be localized quickly.
Localization is the process of adapting a program for use in a specific locale. A locale is a geographic or
political region
that shares the same language and customs. Localization includes the translation of text such as GUI labels,
error messages,
and online help. It also includes the culture-specific formatting of data items such as monetary values, times,
dates, and
numbers.
Objectives
1) State three aspects of any application that might need to be varied or customized in different deployment
locales.
There are many types of data that vary with region or language. Examples of this data are:
Messages
Labels on GUI components
Online help
Sounds
Colors
Graphics
Icons
62
Dates
Times
Numbers
Currencies
Measurements
Phone numbers
Honorifics and personal titles
Postal addresses
Page layouts
2) Match the following features of the Java 2 platform with descriptions of their functionality, purpose or
typical uses:
Properties, Locale, ResourceBundle, Unicode, java.text package, InputStreamReader and
OutputStreamWriter.
Properties:
The java.util.Properties class represents a persistent set of properties. The Properties can be saved to a
stream or loaded
from a stream. Each key and its corresponding value in the property list is a string.. A properties file stores
information
about the characteristics of a program or environment including internationalization/localization
information.
By creating a Properties object and using the load method a program can read a properties file. The program
can then access
the values by using the key as follows:
Properties props = new Properties();
props.load(new BufferedInputStream(new FileInputStream(“filename”);
String value = System.getProperty(“key”);
If the key is not found getProperty returns null.
Locale:
A java.util.Locale object represents a specific geographical, political, or cultural region. An operation that
requires a
Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For
example,
63
displaying a number is a locale-sensitive operation--the number should be formatted according to the
customs/conventions of
the user's native country, region, or culture.
Because a Locale object is just an identifier for a region, no validity check is performed when you construct
a Locale. If
you want to see whether particular resources are available for the Locale you construct, you must query
those resources. For
example, ask the NumberFormat for the locales it supports using its getAvailableLocales method.
Note: When you ask for a resource for a particular locale, you get back the best available match, not
necessarily precisely
what you asked for. For more information, refer to the ResourceBundle section.
The Locale class provides a number of convenient constants that you can use to create Locale objects for
commonly used
locales. For example, the following creates a Locale object for the United States:
Locale.US
Once you've created a Locale you can query it for information about itself. Use getCountry to get the ISO
Country Code and
getLanguage to get the ISO Language Code. You can use getDisplayCountry to get the name of the country
suitable for
displaying to the user. Similarly, you can use getDisplayLanguage to get the name of the language suitable
for displaying to
the user. Interestingly, the getDisplayXXX methods are themselves locale-sensitive and have two versions:
one that uses the
default locale and one that uses the locale specified in the argument.
ResourceBundle:
Resource bundles contain locale-specific objects. When your program needs a locale-specific resource, a
String for example,
your program can load it from the resource bundle that is appropriate for the current user's locale. In this
way, you can
write program code that is largely independent of the user's locale isolating most, if not all, of the localespecific
information in resource bundles.
This allows you to write programs that can:
64
· be easily localized, or translated, into different languages
· handle multiple locales at once
· be easily modified later to support even more locales
One resource bundle is, conceptually, a set of related classes that inherit from ResourceBundle. Each related
subclass of
ResourceBundle has the same base name plus an additional component that identifies its locale. For
example, suppose your
resource bundle is named MyResources. The first class you are likely to write is the default resource bundle
which simply has
the same name as its family--MyResources. You can also provide as many related locale-specific classes as
you need: for
example, perhaps you would provide a German one named MyResources_de.
Each related subclass of ResourceBundle contains the same items, but the items have been translated for the
locale
represented by that ResourceBundle subclass. For example, both MyResources and MyResources_de may
have a String that's used
on a button for canceling operations. In MyResources the String may contain Cancel and in
MyResources_de it may contain
Abbrechen.
If there are different resources for different countries, you can make specializations: for example,
MyResources_de_CH is the
German language (de) in Switzerland (CH). If you want to only modify some of the resources in the
specialization, you can do
so.
When your program needs a locale-specific object, it loads the ResourceBundle class using the getBundle
method:
ResourceBundle myResources =
ResourceBundle.getBundle("MyResources", currentLocale);
The first argument specifies the family name of the resource bundle that contains the object in question. The
second argument
indicates the desired locale. getBundle uses these two arguments to construct the name of the
ResourceBundle subclass it
should load as follows.
65
The resource bundle lookup searches for classes with various suffixes on the basis of (1) the desired locale
and (2) the
current default locale as returned by Locale.getDefault(), and (3) the root resource bundle (baseclass), in the
following
order from lower-level (more specific) to parent-level (less specific):
baseclass + "_" + language1 + "_" + country1 + "_" + variant1
baseclass + "_" + language1 + "_" + country1 + "_" + variant1 + ".properties"
baseclass + "_" + language1 + "_" + country1
baseclass + "_" + language1 + "_" + country1 + ".properties"
baseclass + "_" + language1
baseclass + "_" + language1 + ".properties"
baseclass + "_" + language2 + "_" + country2 + "_" + variant2
baseclass + "_" + language2 + "_" + country2 + "_" + variant2 + ".properties"
baseclass + "_" + language2 + "_" + country2
baseclass + "_" + language2 + "_" + country2 + ".properties"
baseclass + "_" + language2
baseclass + "_" + language2 + ".properties"
baseclass
baseclass + ".properties"
For example, if the current default locale is en_US, the locale the caller is interested in is fr_CH, and the
resource bundle
name is MyResources, resource bundle lookup will search for the following classes, in order:
MyResources_fr_CH
MyResources_fr
MyResources_en_US
MyResources_en
MyResources
The result of the lookup is a class, but that class may be backed by a properties file on disk. That is, if
getBundle does
not find a class of a given name, it appends ".properties" to the class name and searches for a properties file
of that name.
If it finds such a file, it creates a new PropertyResourceBundle object to hold it. Following on the previous
example, it
will return classes and and files giving preference as follows: (class) MyResources_fr_CH (file)
MyResources_fr_CH.properties
(class) MyResources_fr (file) MyResources_fr.properties (class) MyResources_en_US (file)
MyResources_en_US.properties (class)
66
MyResources_en (file) MyResources_en.properties (class) MyResources (file) MyResources.properties If a
lookup fails,
getBundle() throws a MissingResourceException.
The baseclass must be fully qualified (for example, myPackage.MyResources, not just MyResources). It
must also be accessable
by your code; it cannot be a class that is private to the package where ResourceBundle.getBundle is called.
Note: ResourceBundles are used internally in accessing NumberFormats, Collations, and so on. The lookup
strategy is the same.
Resource bundles contain key/value pairs. The keys uniquely identify a locale-specific object in the bundle.
Here's an
example of a ListResourceBundle that contains two key/value pairs:
class MyResource extends ListResourceBundle {
public Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
// LOCALIZE THIS
{"OkKey", "OK"},
{"CancelKey", "Cancel"},
// END OF MATERIAL TO LOCALIZE
};
}
Keys are always Strings. In this example, the keys are OkKey and CancelKey. In the above example, the
values are also
Strings--OK and Cancel--but they don't have to be. The values can be any type of object.
You retrieve an object from resource bundle using the appropriate getter method. Because OkKey and
CancelKey are both
strings, you would use getString to retrieve them:
button1 = new Button(myResourceBundle.getString("OkKey"));
button2 = new Button(myResourceBundle.getString("CancelKey"));
The getter methods all require the key as an argument and return the object if found. If the object is not
found, the getter
method throws a MissingResourceException.
Besides getString; ResourceBundle supports a number of other methods for getting different types of objects
such as
67
getStringArray. If you don't have an object that matches one of these methods, you can use getObject and
cast the result to
the appropriate type. For example:
int[] myIntegers = (int[]) myResources.getObject("intList");
NOTE: You should always supply a baseclass with no suffixes. This will be the class of "last resort", if a
locale is
requested that does not exist. In fact, you must provide all of the classes in any given inheritance chain that
you provide a
resource for. For example, if you provide MyResources_fr_BE, you must provide both MyResources and
MyResources_fr or the
resource bundle lookup won't work right.
The Java 2 platform provides two subclasses of ResourceBundle, ListResourceBundle and
PropertyResourceBundle, that provide a
fairly simple way to create resources. (Once serialization is fully integrated, we will provide another way.)
As you saw
briefly in a previous example, ListResourceBundle manages its resource as a List of key/value pairs.
PropertyResourceBundle
uses a properties file to manage its resources.
If ListResourceBundle or PropertyResourceBundle do not suit your needs, you can write your own
ResourceBundle subclass. Your
subclasses must override two methods: handleGetObject and getKeys().
The following is a very simple example of a ResourceBundle subclass, MyResources, that manages two
resources (for a larger
number of resources you would probably use a Hashtable). Notice that if the key is not found,
handleGetObject must return
null. If the key is null, a NullPointerException should be thrown. Notice also that you don't need to supply a
value if a
"parent-level" ResourceBundle handles the same key with the same value (as in United Kingdom below).
Also notice that because
you specify an en_GB resource bundle, you also have to provide a default en resource bundle even though it
inherits all its
data from the root resource bundle.
68
Example:
// default (English language, United States)
abstract class MyResources extends ResourceBundle {
public Object handleGetObject(String key) {
if (key.equals("okKey")) return "Ok";
if (key.equals("cancelKey")) return "Cancel";
return null;
}
}
// German language
public class MyResources_de extends MyResources {
public Object handleGetObject(String key) {
// don't need okKey, since parent level handles it.
if (key.equals("cancelKey")) return "Abbrechen";
return null;
}
}
You do not have to restrict yourself to using a single family of ResourceBundles. For example, you could
have a set of
bundles for exception messages, ExceptionResources (ExceptionResources_fr, ExceptionResources_de, ...),
and one for widgets,
WidgetResource (WidgetResources_fr, WidgetResources_de, ...); breaking up the resources however you
like.
Unicode:
Unicode is an international effort to provide a single character set that everyone can use.
Java uses the Unicode 2.0 (or 2.1) character encoding standard. In Unicode, every character occupies two
bytes. Ranges of
character encodings represent different writing systems or other special symbols. For example, Unicode
characters in the
range 0x0000 through 0x007F represent the basic Latin alphabet, and characters in the range 0xAC00
through 0x9FFF represent
the Han characters used in China, Japan, Korea, Taiwan, and Vietnam.
UTF is a multibyte encoding format, which stores some characters as one byte and others as two or three
bytes. If most of
69
your data is ASCII characters, it is more compact than Unicode, but in the worst case, a UTF string can be
50 percent larger
than thecorresponding Unicode string. Overall, it is fairly efficient.
Despite the advantages of Unicode, there are some drawbacks: Unicode support is limited on many
platforms because of the lack
of fonts capable of displaying all the Unicode characters.
java.text:
This package provides classes and interfaces for handling text, dates, numbers, and messages in ways that
are independent of
natural languages. This allows programs to be written in a language-independent manner and relies on
separate, dynamically
linked localized resources.
These classes are capable of formatting dates, numbers, and messages, parsing; searching and sorting
strings; and iterating
over characters, words, sentences, and line breaks. This package contains three main groups of classes and
interfaces:
Classes for iteration over text
Classes for formatting and parsing
Classes for string collation
Some of the classes in the java.text package are:
Annotation
An Annotation object is used as a wrapper for a text attribute value if the attribute has annotation
characteristics. These
characteristics are:
The text range that the attribute is applied to is critical to the semantics of the range. That means, the
attribute cannot
be applied to subranges of the text range that it applies to, and, if two adjacent text ranges have the same
value for this
attribute, the attribute still cannot be applied to the combined range as a whole with this value.
70
The attribute or its value usually no longer applies if the underlying text is changed.
An example is grammatical information attached to a sentence: For the previous sentence, you can say that
"an example" is the
subject, but you cannot say the same about "an", "example", or "exam". When the text is changed, the
grammatical information
typically becomes invalid. Another example is Japanese reading information (yomi).
Wrapping the attribute value into an Annotation object guarantees that adjacent text runs don't get merged
even if the
attribute values are equal, and indicates to text containers that the attribute should be discarded if the
underlying text is
modified.
CollationKey
A CollationKey represents a String under the rules of a specific Collator object. Comparing two
CollationKeys returns the relative order of the Strings they represent. Using CollationKeys to compare
Strings is generally faster than using Collator.compare. Thus, when the Strings must be compared multiple
times, for example when sorting a list of Strings. It's more efficient to use CollationKeys.
You can not create CollationKeys directly. Rather, generate them by calling Collator.getCollationKey. You
can only compare CollationKeys generated from the same Collator object.
Generating a CollationKey for a String involves examining the entire String and converting it to series of
bits that can be
compared bitwise. This allows fast comparisons once the keys are generated. The cost of generating keys is
recouped in faster
comparisons when Strings need to be compared many times. On the other hand, the result of a comparison is
often determined by
the first couple of characters of each String. Collator.compare examines only as many characters as it needs
which allows it
to be faster when doing single comparisons.
Collator
The Collator class performs locale-sensitive String comparison. You use this class to build searching and
sorting routines
for natural language text.
71
Collator is an abstract base class. Subclasses implement specific collation strategies. You can use the static
factory
method, getInstance, to obtain the appropriate Collator object for a given locale.
Format
Format is an abstract base class for formatting locale-sensitive information such as dates, messages, and
numbers.
Format defines the programming interface for formatting locale-sensitive objects into Strings (the format
method) and for
parsing Strings back into objects (the parseObject method). Any String formatted by format is guaranteed to
be parseable by
parseObject.
Format has three subclasses: DateFormat, MessageFormat, NumberFormat
InputStreamReader:
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and translates them
into characters
according to a specified character encoding. The encoding that it uses may be specified by name, or the
platform's default
encoding may be accepted.
The class has two constructors: one that uses the platform’s default encoding and one that takes an encoding
(as a String).
Encodings can be represented by their ISO numbers, i.e., ISO 8859-9 is represented by “8859_9”.
There is no easy way to determine which encodings are supported. You can use the getEncoding() method
to get the name of the
encoding being used by the Reader.
Characters that do not exist in a specific character set produce a substitution character, usually a question
mark.
OutputStreamReader:
72
An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are
translated into bytes
according to a specified character encoding. The encoding that it uses may be specified by name, or the
platform's default
encoding may be accepted.
Each invocation of a write() method causes the encoding converter to be invoked on the given character(s).
The resulting
bytes are accumulated in a buffer before being written to the underlying output stream. The size of this
buffer may be
specified, but by default it is large enough for most purposes. Note that the characters passed to the write()
methods are
not buffered.
The class has two constructors: one that uses the platform’s default encoding and one that takes an encoding
(as a String).
Encodings can be represented by their ISO numbers, i.e., ISO 8859-9 is represented by “8859_9”.
There is no easy way to determine which encodings are supported. You can use the getEncoding() method
to get the name of the
encoding being used by the Writer.
Characters that do not exist in a specific character set produce a substitution character, usually a question
mark.
References:
Java 2 API http://java.sun.com/j2se/1.3/docs/api/index.html
Java I/O E. R. Harold, O’Reilly, 1999
IP: Logged
John Wetherbie
bartender posted July 17, 2001 07:53 AM
--------------------------------------------------------------------------------
73
Legacy Connectivity
Distinguish appropriate from inappropriate techniques for providing access to a legacy system from Java
code given an outline
description of that legacy system.
Upgrading Client-Tier GUIs
In cases where the GUI is loosely coupled to the other legacy tiers you can use an applet or a small
application to replace
the GUI.
Applets can communicate with the other tiers via TCP sockets. The applet can be signed and trusted, if
necessary to access
resources.
Applets can also communicate with COM and CORBA objects (using bridge or Java IDL).
Screen Scrapers
Screen scrapers may be used to integrate applet (or other) interface with an existing system. They are
particularly useful
when the client interface is tightly coupled to the other tiers of the system.
A screen scraper is an application that translates an existing client interface into a set of objects.
Screen scrapers usually function as a terminal emulator on one end and an object interface on the other. The
screen scraper
is configured to read data from terminal fields of the legacy interface and make them available via objects.
Screen scrapers have the following advantages:
Provides a low-level object-based interface to the legacy app.
Allows you to build a new GUI over the existing client interface.
Disadvantages of screen scrapers:
Any changes to the legacy interface can break the new GUI.
Prone to causing errors in the new GUI because of unexpected outputs from the legacy interface.
Prone to causing the new GUI to “freeze” when the legacy interface is expecting input that the screen
scraper in unaware of.
74
Object Mapping Tools
Object mapping tools can be used if you choose to ignore the existing legacy interface and access the
underlying tiers
directly.
These tools are used to create proxy objects that access legacy system functions and make them available in
an
object-oriented form.
Object mapping tools are usually more effective than screen scrappers because they are not dependent on
the format generated
by the existing legacy interface.
Upgrading Application Business Logic
Java servlets provide a capability to make existing applications available via an intranet or the Internet.
Clients (browsers and/or applets) access servlets via HTTP or HTTPS. The servlets take the requests and
communicate with the
legacy system.
EJBs provide a component-based approach to upgrading legacy applications.
Java’s support for CORBA enables CORBA objects to be accessed from Java and Java objects to be
accessed as CORBA objects.
Microsoft’s JVM provides (or used to provide) a bridge between Java and COM objects.
JNI may be used to write custom code to interface new business logic with an existing legacy system.
Upgrading the Data Storage Tier
JDBC may be used to access relational databases in a legacy system.
In many cases the legacy database will not support a pure JDBC driver. If the database provides ODBC
support the JDBC-ODBC
bridge can be used.
If the existing legacy database is hierarchical or flat-file then it may be able to be imported into an RDBMS.
75
Securing Legacy System Components
Retrofitting a system with security is generally more expensive and less productive the redesigning and
redeveloping the
system to operate in a secure manner. However, budget constraints may prevent this.
Legacy systems may be isolated from threats by placing them behind a firewall.
Access control to legacy systems can be controlled by requiring users and external applicationsto
authenticate themselves
with the firewall before they can access the legacy system. Auditing features of the legacy system should be
used to
determine who is accessing the legacy system and when.
A VPN may be used to secure all communications with a legacy system.
IP: Logged
John Wetherbie
bartender posted July 17, 2001 07:55 AM
-------------------------------------------------------------------------------JMS
Messaging
Identify scenarios that are appropriate to implementation using messaging, EJB, or both.
The current EJB spec (1.1) defines beans that are invoked synchronously via method calls from EJB clients.
JMS provides client interfaces that can interface with point-to-point and publish-subscribe systems.
In the future (EJB 2.0) will add a form of asynchronous bean that is invoked when a JMS client sends it a
message.
List benefits of synchronous and asynchronous messaging.
Select scenarios from a list that are appropriate to implementation using synchronous and asynchronous
messaging.
Asynchronous messaging
76
Loose coupling between sender and receiver
Does not block sender
Network does not need to be available, messages can be queued
Least demanding on comm. mechanisms
Good for publish-subscribe
Must use messaging to get reliability (?)
Synchronous messaging
Tight coupling between sender and receiver
Blocks sender until receiver is finished processing
Network must be available
More demanding on comm. Mechanisms
Good for transaction processing
Fail-safe comm.
Coping with error situations
Java Messaging Service (JMS)
JMS provides a common way for Java programs to create, send, receive and read an enterprise messaging
system’s messages.
JMS defines a set of message interfaces.
JMS provides client interfaces for point-to-point (PTP) and publish-subscribe systems.
PTP
built around the concept of message queues
each message is addressed to a specific queue; clients get messages from the queue(s) created to
hold their messages
Publish-Subscribe
Publishers address messages to a node or address
System distributes the messages arriving from a publisher to the subscribers of that publisher
Nothing prevents a JMS application from combining PTP and publish-subscribe but JMS focuses on
applications that use one
approach or the other.
JMS does NOT include the following:
77
Load balancing/fault tolerance
Error/advisory notification
Administration
Security
Wire protocol
Message Type Repository
IP: Logged
John Wetherbie
bartender posted July 17, 2001 07:56 AM
-------------------------------------------------------------------------------Protocols
Objectives:
Given a scenario description, distinguish appropriate from
inappropriate protocols to implement that scenario.
Identify a protocol, given a list of some of its features, where the
protocol is one of the following:
HTTP
HTTPS
IIOP
JRMP
HTTP Properties
Client-Server Architecture
The HTTP protocol is based on a request/response paradigm. The communication generally takes place over
a TCP/IP connection
on the Internet. The default port is 80, but other ports can be used. This does not preclude the HTTP/1.0
protocol from being
implemented on top of any other protocol on the Internet, so long as reliability can be guaranteed.
The HTTP protocol is connectionless and stateless After the server has responded to the client's request, the
connection
between client and server is dropped and forgotten. There is no "memory" between client connections. The
pure HTTP server
78
implementation treats every request as if it was brand-new, i.e. without context.
An extensible and open representation for data types HTTP uses Internet Media Types (formerly referred to
as MIME
Content-Types) to provide open and extensible data typing and type negotiation. When the HTTP Server
transmits information
back to the client, it includes a MIME-like (Multipart Internet Mail Extension) header to inform the client
what kind of data
follows the header. Translation then depends on the client possessing the appropriate utility (image viewer,
movie player,
etc.) corresponding to that data type.
HTTPS(Secure Hypertext Transfer Protocol)
HTTPS (Secure Hypertext Transfer Protocol) is a Web protocol developed by Netscape and built into its
browser that encrypts
and decrypts user page requests as well as the pages that are returned by the Web server. HTTPS is really
just the use of
Netscape's Secure Socket Layer (SSL) as a sublayer under its regular HTTP application layer. (HTTPS uses
port 443 instead of
HTTP port 80 in its interactions with the lower layer, TCP/IP.) SSL uses a 40 or 128-bit key size for the
RC4 stream
encryption algorithm, which is considered an adequate degree of encryption for commercial exchange.
Suppose you use a Netscape browser to visit a Web site such as NetPlaza (http://www.netplaza.com) and
view their catalog.
When you're ready to order, you will be given a Web page order form with a URL that starts with https://.
When you click
"Send," to send the page back to the catalog retailer, your browser's HTTPS layer will encrypt it. The
acknowledgement you
receive from the server will also travel in encrypted form, arrive with an https:// URL, and be decrypted for
you by your
browser's HTTPS sublayer.
79
HTTPS and SSL support the use of X.509 digital certificates from the server so that, if necessary, a user can
authenticate
the sender. SSL is an open, nonproprietary protocol that Netscape has proposed as a standard to the World
Wide Consortium
(W3C). HTTPS is not to be confused with SHTTP, a security-enhanced version of HTTP developed and
proposed as a standard by
EIT.
Resource:
Whatis.com/https.htm
IIOP
CORBA and IIOP assume the client/server model of computing in which a client program always makes
requests and a server
program waits to receive requests from clients. When writing a program, you use an interface called the
General Inter-ORB
Protocol (GIOP). The GIOP is implemented in specialized mappings for one or more network transport
layers. Undoubtedly, the
most important specialized mapping of GIOP is IIOP, which passes requests or receives replies through the
Internet's
transport layer using the Transmission Control Protocol (TCP). Other possible transport layers would
include IBM's Systems
Network Architecture (SNA) and Novell's IPX.
For a client to make a request of a program somewhere in a network, it must have an address for the
program. This address is
known as the Interoperable Object Reference (IOR). Using IIOP, part of the address is based on the server's
port number and
Internet Protocol (IP) address. In the client's computer, a table can be created to map IORs to proxy names
that are easier
80
to use. The GIOP lets the program make a connection with an IOR and then send requests to it (and lets
servers send replies).
A Common Data Representation (CDR) provides a way to encode and decode data so that it can be
exchanged in a standard way.
CORBA is not the only architecture that uses IIOP. Because a TCP/IP-based proxy is usable on almost any
machine that runs
today, more parties now use IIOP. When another architecture is IIOP-compliant, it not only establishes a
well-proven
communication transport for its use, but it also can communicate with any ORB implementation that is
IIOP-compliant. The
possibilities are endless.
reference: http://www.blackmagic.com/people/gabe/iiop.html
JRMP
The Transport layer employs JRMP, also known as the RMI Wire Protocol, to send method invocations and
associated parameters
and to return values and exceptions from one Java virtual machine (JVM) to another. JRMP is a simple
protocol consisting of
five messages, plus an extra five for multiplexing flow control.
All JRMP sessions consist of a header followed by one or more messages. The header contains just the
ASCII codes for the
characters JRMI , the protocol version, and the "subprotocol" to be used. There are three subprotocols:
SingleOpProtocol,
StreamProtocol, and MultiplexProtocol. SingleOpProtocol signifies that only one message follows a header
before the end of a
session (i.e., the connection closes). StreamProtocol and MultiplexProtocol can transfer one or more
messages. The latter is
used when multiplexing calls from both client and server on a single socket, as described below.
81
Communicating clients and servers typically each open a socket to the other (i.e., both systems connect and
listen for
connections). The client's socket typically invokes methods on server-side objects, and the server's socket
calls client-side
objects (e.g., callbacks). The figure shows a hypothetical StreamProtocol situation. The client sends the Call
message to
invoke a server object's method; the server then invokes this method and replies with a Return containing
any results.
Assuming that a remote object is returned, the client then sends a DgcAck message to let the server's
garbage collector know
that it has received the remote object. On another socket, the server sends a Ping to find out whether the
client is alive,
which replies with a PingAck.
Default applet security restrictions deny applets the right to open sockets back to any server other than their
originating
host; they also block any attempt to listen for socket connections. This being the case, how do clients listen
for server
connections?
Enter the MultiplexProtocol and its group of five messages: Open , Close , CloseAck , Request, and
Transmit. They allow
client and server to simulate the StreamProtocol's two-way communication using a single socket. In the
current
implementation, up to 256 virtual connections can be opened, each identified by a unique ID.
Unfortunately, connecting via a socket back to the server is not always possible for applets running behind
firewalls (e.g.,
on a corporate intranet), which typically block any attempt to open a socket back to the Internet. Should it
fail to open a
connection, an RMI client wraps its method invocation inside the body of an HTTP request (which is the
protocol browsers use
to communicate with Web servers), and the RMI server sends any results as an HTTP response.
82
This workaround is a smart solution, since HTTP is a firewall-trusted protocol. Still, performance takes a hit
due to the
time needed to convert messages to HTTP requests. In addition, no multiplexing of invocations can be
accomplished, because
keeping the connection open between client and server is not part of HTTP 1.0. The primary reason for
SingleOpProtocol's
existence is to encapsulate RMI through HTTP.
Reference: http://www.byte.com/art/9802/sec4/art3.htm
Who they talk to
HTTP HTML forms based client interacts with the servlet on the server. Server interacts with the business
layer and business
layer interacts with the persistence layer. RMI This is a possible if the objects in the user interface and the
business
layers are all Java objects. The persistence layer is mostly accessed through JDBC. Other relational object
mapping of the
data layer is also possible. Advantage of RMI Object are passed by value. The server/ client can reconstitute
the objects
easily. Data type can be any Java objects. Any Java objects can be passed as arguments. Arguments has to
implement the
serializable interface Disadvantage of RMI Heterogeneous objects are not supported. Corba If the objects in
the client layer
and the business layer are heterogeneous, i.e. the objects are implemented in C, C++ Java, Smalltalk then
Corba is most
suitable. Advantage of Corba Heterogeneous objects are supported. Disadvantage of Corba Objects are not
passed by value, only
the argument data is passed. The server/ client has to reconstitute the objects with the data. Only commonly
accepted data
types can be passed as arguments. Dcom This works best in windows environment. Distributed Object
Communication
83
Advantages Disadvantages
HTTP Simple, Established Has to communicate to a Servlet, Java Server pages Cannot communicate to a
Java class directly
RMI Object are passed by value. The server/ client can reconstitute the objects easily. Object are passed by
reference Data
type can be any Java objects. Any Java objects can be passed as arguments. Arguments has to implement the
Serializable
interface Heterogeneous objects are not supported.
Corba Heterogeneous objects are supported. Objects are not passed by value, only the argument data is
passed. The server/
client has to reconstitute the objects with the data. Only commonly accepted data types can be passed as
arguments
Dcom If windows is the deployment platform suits well with the operating system This works in windows
environment at best
Distributed Object Frameworks Distributed Object Frameworks are RMI, Corba, Dcom, EJB. Basic ThreeTier Java Technology
Architecture The three-Tier Java Technology Architectureis achieved by HTML, Applet, Java Application
on the client. Servlet,
Java Server Pages on the Middle Tier. JDBC communication to the persistence or Database layer
Client C to M comm. Middle M to P comm. Persistence
HTML HTML with applet HTTP Servlet Java Server Pages JDBC RDBMS Legacy File
Java Application JRMP RMI Server JDBC RDBMS Legacy File
Java Application RMI- II0P EJB JDBC RDBMS Legacy File
Java Application ( Not a Java 3 tier) IIOP Corba JDBC RDBMS Legacy File
Conclusions:
HTTP and HTTPS are very similar protocols with only the fact that HTTPS provides a layer of security(the
SSL). They are both
capable of passing a variety of data types but there is no logic, objects may only be executed if there's
another protocol to
handle them. HTTP is the lowest layer of logic and can only be used as a delivery mechanism for other
protocols. JRMP is a
robust object server that communicates well when working with JAVA based objects. It is capable of
passing objects refrences
84
rather than just values that have to be reconstituted so that the object may be executed by the client rather
than the
server. In the even that the server is secure or cannot communicate in the most efficient manner JRMP falls
back to HTTP.
JRMP is only capable of passing JAVA objects. IIOP is the most flexible of the transport mechanisms, it
can communicate
objects created in C, C++, JAVA, and smalltalk but only passes data by value requiring the server to do all
the work and
requiring that only common data types be passed as arguments making it more restrictive than JRMP which
allows any JAVA data
type.
IP: Logged
John Wetherbie
bartender posted July 17, 2001 07:57 AM
-------------------------------------------------------------------------------Security
Select from a list security restrictions that Java 2 environments normally impose on applets running in a
browser.
The Java 2 security model is policy-based and has superseded the sandbox/trusted approach of Java 1.1.
In Java 1.1 remote code (applets, for example) that was not trusted was constrained to the sandbox. If the
remote code was
signed and trusted then it could access local resources.
Code Source:
A combination of a set of signers (certificates) and a code base URL
By default, Java 2 uses a policy file to associate permissions with code sources
Security Policy File:
A permission is the right to access a protected resource or guarded object
For Java 2 permissions are specified in the security policy file
Only one policy is in effect at a time
A policy file consists of a number of grant entries
Each grant entry describes the permissions (one or multiple) granted to a code source
Policy class
85
You can use java.security.Policy to create your own security policy.
java.security package
The following are some of the classes in the java.security package:
CodeSource – This class extends the concept of a codebase to encapsulate not only the location (URL) but
also the
certificate(s) that were used to verify signed code originating from that location.
KeyStore – This class represents an in-memory collection of keys and certificates. It manages keys and
trusted certificates.
MessageDigest – The MessageDigest class provides applications the functionality of a message digest
algorithm, such as MD5 or
SHA.
Permission – Abstract class for representing access to a system resource.
Policy – This is an abstract class for representing the system security policy for a Java application
environment (specifying
which permissions are available for code from various sources).
ProtectionDomain – The ProtectionDomain class encapulates the characteristics of a domain, which
encloses a set of classes
whose instances are granted the same set of permissions.
Security – Centralizes all security properties and common security methods.
Given an architectural system specification, identify appropriate locations for implementation of specified
security
features, and select suitable technologies for implementation of those features.
Exposure to threats can be mitigated by using:
Authentication
Authorization (ACLs)
Protecting Messages
Auditing
Web tier authentication (This is the usual location for this)
86
Basic HTTP – the web server authenticates a principal with user name & password from Web client
Form-based – lets developers customize the authentication user
HTTPS mutual authentication – the client and server use X.509 certificates to establish identity over a SSL
channel.
EJB/EIS tier authentication
For EJBs can use protection domains. Thus the EJB tier could entrust the web tier to vouch for the identity
of users.
Put a protected web resource in front of a protected EJB resource
Have every web resource that calls an EJB resource route through a protected web resource
For access to EIS tier resources authentication is usually carried out by the component accessing the EIS
resource.
You can have the container manage the EIS resource authentication or have the app do this itself.
Authorization
In J2EE a container serves as an authorization boundary between callers and its components. The
authorization boundary is
inside the authentication boundary so authorization occurs within the context of successful authentication.
For component to component invocations inside the container the calling component must make its
credentials available to the
called component.
You can have file-based & code-based security in J2EE.
Access control policy is set a deployment time.
Controlling access to resources in the container (deployment descriptor)
To control access to web resources, specify constraint in the deployment descriptor.
To control access to EJB, specify roles in the deployment descriptor.
You can specify methods of the remote & home interface that each security role is allowed to invoke
Protecting Messages
87
To ensure message integrity you can use:
Message signature – a enciphered digest of the message contents (costly in terms of CPU cycles)
Message confounder – ensures message authentication is useful only once
A deployer must configure the containers involved in a call to implement integrity mechanisms either
because the call will
traverse open or unprotected networks or because the call will be made between components that do not
trust each other.
Auditing
When security is breached it is usually more important to know who has been allowed access than who has
not.
Audit records need to be well protected – tapes or logging to a printer vs disk drive
88
Download