Saturday, 14 May 2011

SCEA Part I Exam CX-310-052 Notes

These are some points which are noted when I was preparing for the SCEA Part I CX-310-052 exam and hope that these are helpful for the people who are preparing for the exam. Below points are gathered from various books, topics and articles.

Experience in my exam:
There were good number of questions on patterns (both GOF and Core J2EE Patterns) and I couldn't see any question from UML in my exam.
Some questions were on Security and most of them are scenarios based which are quite bit lengthy.

Given a situation what would be the best in case, these kind of questions will definitely take some time to answer. 

For few Security based questions where all answers seems to be right 

Some how I successfully completed Oracle Certified Enterprise Architect Part I. This exam is of very vast syllabus. Before this exam, I know J2EE (few topics were less focused) and Java 1.4 but once I started preparing for this exam I got to know many things, most of the concepts atleast, not in detail but atleast each and every corner of the JEE 5 it has made me to go through.

I want to thank java ranch forum and javachamp.com for helping me in clearing Part I.

I started preparing for this exam by starting with GoF Design Patterns.

Books and references:
Head First Design Patterns
 

Core J2EE Design Patterns

Mark Cade's second edition
Mastering EJB3 fourth edition
 
SCEA study guide of Mikalia Zaikin 

Sun Certified Enterprise Architect for JavaEE Study Guide 2ndEd

UML 

Notes:
n tier Architecture:
Validation of the common fields should be written in a common script so that browser downloads the script only once and it need not load the script for every page. Most of the pages which are having common fields can be validated using the same common script.

Browser validation logic will duplicate some server-side validation logic. The EJB and EIS tiers should validate data regardless of what client does.

Data that can be stored in Cookie is at most 4 KB.

With URL rewriting network will be consumed more as encoded session id and at the server again it is decoded for every request and response.

Server has to maintain the session of the user to keep track of the client it has to use a key to identify the client and get its session.


Preparing an application client for java web start deployment involves distributing its jar with a JNLP (java network launching protocol) file.

MIDlet clients are small applications programmed to the Mobile Information Device Profile(MIDP), a set of java API's which together with the CLDC(Connected Limited Device Configuration), provides a complete J2ME runtime environment for cellular phones.

Java client (client of rich client). When a list is requested by both the java client and browser based client. web based client has to load all the data including the presentation logic but in case of java client it loads only the data required for the client. java client(like swing application) consumes less bandwidth.

Java clients can be programmed to make fewer connections than a browser to a server.

LEB client is not always possible. First, only appliet and application clients may connect as EKB clients
(MIDlets cannot connect to the EJB tier because RMI is not a native component of MIDP).

JSF is a server side user interface component framework for java technology based web applications.

Services provided by the EJB container like security, connection pooling and transactions will be available by lightweight IOC (Inversion of Control, which is an event based programming model) containers like Spring, without the overhead and complexity of EJB.


Design Patterns from Head First series:

   Principles:
   Identify the aspects of your application that vary and seperate them from what stays the same.
   Program to an interface, not an implementation.
   Favor composition over inheritance.
   Strive for loosely coupled design between objects that interact.
   Classes should be open for extension but closed for modification.
   Depend upon abstractions. Do not depend upon concrete classes.
   Principle of Least Knowledge - talk only to your immediate friends.
   Don't call us, we will call you.
   A class should have only one reason to change.
 
   Cohension is a term to measure how closely a clas or a module supports a single purpose or responsibility. High cohesion when it is designed around a set of related functions and we say it has loow cohesion when it is desinged around a set of unrelated functions.
  
   Cohesion is a more general concept than the Single responsibility principle, but the two are closely related. Classes that adhere to the principle tend to have high cohesion and are more maintainable than classes that take on multiple responisibilities and have low cohesion.

    Pattern definition:
    Strategy Pattern defines a family of algorithm, encapsulate each one and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
   
    Observer Pattern defines one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and update automatically.
   
    Decorator attaches additional responsibiities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
   
    Factory method pattern defines an interface for creating an object, let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.
   
    Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.
   
    Singleton Pattern ensures a class has only one instance and provides a global point of access to it.
   
    Command pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.
   
    NoCommand object is an example of null object. A null objet is useful when you don't have a meaningful object to return, and yet you want to remove the responsibility of handling null from the client.
   
    Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
   
    Facade pattern provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easier to use.
   
    Template Method defines skeleton of the algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine cetain steps of an algorithm without changing the algorithm's structure. Template method defines the steps of an algorithm and allows subclasses to provide the implementation for one or more steps.
   
    The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.   

    Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
   
Core J2ee Patterns:   
   
DAO Pattern
    Use DAO to abstract and encapsulate all access to the data source. The DAO manages the connection with the data source to obtain and store data.
   
    When the underlying storage is not subject to change from one implementation to another Factory for Data Access Objects strategy can be implemented to produce a number of DAOs needed by the application.
   
    When the underlying storage is subject to change from one implementation to another, Abstract Factory pattern for DAO strategy may be implemented using the Abstract Factory pattern. The Abstract Factory can in turn build on and use the Factory Method implementation.

Transfer Object Pattern
    Use a Transfer Object to encapsulate the business data. A single method call is used to send and retrieve the Transfer Object. When the client requests the enterprise bean for the business data, the enterprise bean can construct the Transfer Object, populate it with its attribute values, and pass it by value to the client.

Because the Transfer Object is passed by value to the client, all calls to the Transfer Object instance are local calls instead of remote method invocations.   

    A Transfer Object class may provide a constructor that accepts all the required attributes to create the Transfer Object. The constructor may accept all entity bean attribute values that the Transfer Object is designed to hold. Typically, the members in the Transfer Object are defined as public, thus eliminating the need for get and set methods. If some protection is necessary, then the members could be defined as protected or private, and methods are provided to get the values. By offering no methods to set the values, a Transfer Object is protected from modification after its creation. If only a few members are allowed to be modified to facilitate updates, then methods to set the values can be provided.    
   
     Updatable Transfer Object
     Instead of providing fine-grained set methods for each attribute, which results in network overhead, the BusinessObject can expose a coarse-grained setData() method that accepts a Transfer Object as an argument. The Transfer Object passed to this method holds the updated values from the client. Since the Transfer Object has to be mutable, the Transfer Object class has to provide set methods for each attribute that can be modified by the client. The set methods for the Transfer Object can include field level validations and integrity checks as needed.
   
     Multiple Transfer Objects Strategy
     For instance, when the business object is implemented as a session bean, typically applying the Session Facade pattern, the bean may interact with numerous other business components to provide the service. The session bean produces its Transfer Object from different sources. Similarly, when the BusinessObject is implemented as a coarse-grained entity bean, typically applying the Composite Entity pattern, the entity bean will have complex relationships with a number of dependent objects. In both these cases, it is good practice to provide mechanisms to produce Transfer Objects that actually represent parts of the underlying coarse-grained components.
   
     Entity Inherits Transfer Object Strategy
   
     Transfer Object Factory strategy
   
Transfer Object Assembler
    ValueObject is created using the business data from various beans like entity bean, session bean and DAO, it fetches data from these business objects and creates a single Value Object (Transfer Object) and the built transfer object is used by the transfer object assembler.
   
   
Service Activator
    Provides Asynchronous Processing for any Enterprise Beans
In the EJB 2.0 specification, the message-driven bean is a stateless session bean. Using the Service Activator pattern, it is possible to provide asynchronous invocation on all types of enterprise beans, including stateless session beans, stateful session beans, and entity beans. As previously explained, since the Service Activator is implemented in its own right, without any limitations of the message-driven bean, the Service Activator can perform asynchronous invocations on any type of business service. Thus, this pattern provides a way to enable asynchronous processing for clients that either have no need to wait for the results or do not want to wait for processing to complete. The processing can be deferred and performed at a later time, enabling the client to complete the service in less time
   
Service Locator
        Use a Service Locator object to abstract all JNDI usage and to hide the complexities of initial context creation, EJB home object lookup, and EJB object re-creation. Multiple clients can reuse the Service Locator object to reduce code complexity, provide a single point of control, and improve performance by providing a caching facility.

       JMS Queue Service Locator Strategy
        This strategy is applicable to point-to-point messaging requirements. The Service Locator for JMS components uses QueueConnectionFactory objects in the role of the ServiceFactory. The QueueConnectionFactory is looked up using its JNDI name. The QueueConnectionFactory can be cached by the ServiceLocator for future use. This avoids repeated JNDI calls to look it up when the client needs it again. The ServiceLocator may otherwise hand over the QueueConnectionFactory to the client. The Client can then use it to create a QueueConnection. A QueueConnection is necessary in order to obtain a QueueSession or to create a Message, a QueueSender (to send messages to the queue), or a QueueReceiver (to receive messages from a queue). The class diagram for the JMS Queue Service Locator strategy is shown in Figure 8.35. In this diagram, the Queue is a JMS Destination object registered as a JNDI-administered object representing the queue. The Queue object can be directly obtained from the context by looking it up using its JNDI name.
       
Session Facade
    Use a session bean as a facade to encapsulate the complexity of interactions between the business objects participating in a workflow. The Session Facade manages the business objects, and provides a uniform coarse-grained service access layer to clients.
   
    Stateless Session Facade Strategy
    A business process that needs only one method call to complete the service is a nonconversational business process. Such processes are suitably implemented using a stateless session bean.

    Stateful Session Facade Strategy
    A business process that needs multiple method calls to complete the service is a conversational business process. The conversational state must be saved between each client method invocation. In this scenario, a stateful session bean may be a more suitable approach for implementing the Session Facade.

       
   
EJB 3
 Message beans cannot be accessed by web service clients.
 Web service client can invoke the business methods of a stateless session bean.
 A web service client accesses a stateless session bean through the bean's web service endpoint implementation class. Only business methods annotated as a @WebMethod may be invoked by a web service client.

 Tight or loose coupling of related beans: Tightly coupled beans depend on one another. For example, a completed sales order must email the customer a confirmation message upon completion of the order. If the SalesOrder stateful session bean, which contains the business logic of an ordering application, calls the CustomerContact  stateless session bean to email the order confirmation to the customer, these session beans would be described as tightly coupled. Tightly coupled beans are good candidates for local access. Because they fit together as a logical unit, they typically call each other often and would benefit from the increased performance that is possible with local access.

 The parameters of remote calls are more isolated than those of local calls. With remote calls, the client and bean operate on different copies of a parameter object. If the client changes the value of the object, the value of the copy in the bean does not change. This layer of isolation can help protect the bean if the client accidentally modifies the data.

In a local call, both the client and the bean can modify the same parameter object. In general, you should not rely on this side effect of local calls. Perhaps someday you will want to distribute your components, replacing the local calls with remote ones.

 . The client initiates the life cycle by obtaining a reference to a stateful session bean. The container performs any dependency injection and then invokes the method annotated with @PostConstruct, if any.

 The client initiates the life cycle by obtaining a reference to a stateless session bean.

 The EJB container usually creates a pool of message-driven bean instances.

 The business interface is a local interface unless it is annotated with the javax.ejb.Remote annotation; the javax.ejb.Local annotation is optional in this case.

 The bean class may implement more than one interface. If the bean class implements more than one interface, the bean class's business interfaces must be explicitly annotated either @Local or @Remote.

 # javax.annotation.PostConstruct
# javax.annotation.PreDestroy
# javax.ejb.PostActivate
# javax.ejb.PrePassivate

There is no Home interface in EJB3.

the bean provider can designate the business interface as a remote busines interfface or local business interface or both. Whereas the mthods on a remote business interface can throw arbitarray application exceptions they are not allowed to throw java.rmi.RemoteException,

Deployment descriptor can be annoted in the bean or deployment descriptor can be mentioned in the xml. If a transaction attribute is mentioned in the bean class and the deployment descriptor, value described in the DD will override the value mentioned in the bean.

If there is no deployment descriptor mentioned by the bean developer then container will generate its specific DD for the bean.

for the remote interface if nothing is declared has remote or local, by default container will treat it has local interface.

If the bean implementation has more than one interface to implement then every interface has to mention whether its remote or local and its mandatory.

Bean class if it implements more than one business then it has to be mention local or remote for every interface it implements.

local interface need not throw RemoteException

Java  Persistence API

Entity
To add new entity to the persistence context we need to call the Entity Manager's persist() method. The entity is now scehduled for synchronization with the database and will get written to disk when the transaction commits. This state in the entity's life cycle is called the managed state. It will end either persistence context ends or commits

detached state: when the transaction is committed or rolls back. the connection between persistence context and all managed entities and entity manager is removed, entities state is changed to detached state.

There are two options for client code that needs to use an EntityManager
container managed Entity Manager. container injects the Entity Manager when we used @PersistenceContext annotation and it can also be obtained from the SesionContext using its lookup()

application-managed Entity Manager, the app is responsible for creating an EntityManager instance itself using EntityManagerFactory.

Entity life cycle

new instance is created but not yet associated with persistence context. not yet synchronized in the database.

managed entity has persistent identity in the database and is currently associated with a persistence context.


detached, removed
Persistence Context
A persistence context is a set of managed entity instances that exist in a particular data store. The EntityManager interface defines the methods that are used to interact with the persistence context.

Container-Managed Entity Managers

@PersistenceContext
EntityManager em;

Application-Managed Entity Managers

@PersistenceUnit
EntityManagerFactory emf;
EntityManager em = emf.createEntityManager();

Persisting Entity Instances
New entity instances become managed and persistent by invoking its persist method. This means the entity's data is stored to the database when the transaction associated with the persist operation is completed. If the entity is already managed, the persist operation is ignored. If persist is called on a removed entity instance, it becomes managed. If the entity is detached, persist will throw an IllegalArgumentException, or the transaction commit will fail.

Managing an Entity Instance's Lifecycle

You manage entity instances by invoking operations on the entity via an EntityManager instance. Entity instances are in one of four states: new, managed, detached, or removed.

New entity instances have no persistent identity and are not yet associated with a persistence context.

Managed entity instances have a persistent identity and are associated with a persistence context.

Detached entity instances have a persistent identify and are not currently associated with a persistence context.

Removed entity instances have a persistent identity, are associated with a persistent context, and are scheduled for removal from the data store.

Interface                                POINT TO POINT                          PUBLISH/SUBSCRIBE
ConnectionFactory                QueueConnectionFactory                  TopicConnctionFactory
Connection                            QueueConnection                             TopicConnection
Destination                             Queue                                              Topic
Session                                  QueueSession                                   TopicSession
MessageProducer                  QueueSender                                    TopicPublisher
MessageConsumer                QueueReceiver, QueueBrowser         TopicSubscriber

Message drive beans are single threaded. There is no need to synchronization code in the bean class. It is the container's responsibility to provide concurrent message consumption by pooling multiple mdb instances.

messages from a queue are delivered only to one consumer, the queue can have multiple messages processed concurrently by different servers in a cluster.

since messages from a topic can be consumed by more than one client, each mdb container that binds to a given topic will receive each msg.

poison msg is a msg that is continually retransmitted by a jms destination to the consumer because the consumer continuously fails to acknowledge the sonsumption of the msg.


Security:

Automatic Memory Management
Garbage Collection
Range checking on arrays and Strings
Compiler and Byte code verifier ensures only legitimate byte code is executed
Trusted applet run in local then in sandbox , unsigned applet still run in sandbox.

Deployment Descriptors for Declarative Security
  EJB uses ejb-jar.xml
  webservices jaxrpc-mapping-info.
  web application web.xml
 
Annotations enable a declarative style of programming, and so encompass both the declarative and programmatic security concepts.

a realm is a complete database of users and groups that identify valid users of a Web application.

the file, admin-realm, and certificate realms.

In the file realm, the server stores user credentials locally in a file named keyfile. File realm authenticates all the clients but https and certificate based clients are not authenticated.

certificate realm, the authentication service verifies an X.509 certificate.

The admin-realm is also a FileRealm and stores administrator user credentials locally in a file named admin-keyfile.
Security policy domain (also known as security domain or realm)

@DeclareRoles annotation (preferred) or the security-role-ref elements of the deployment descriptor

<assembly-descriptor>
<security-role>
          <description>
               This role includes the employees of the payroll
               department. The role is allowed to view and
               update the payroll entry for any employee.
          </description>
          <role-name>payroll-department</role-name>
     </security-role>
</assembly-descriptor>

<enterprise-beans>
     ...
     <session>
          <ejb-name>AardvarkPayroll</ejb-name>
          <ejb-class>com.aardvark.payroll.PayrollBean</ejb-class>
          ...
          <security-role-ref>
               <description>
                    This role should be assigned to the
                    employees of the payroll department.
                    Members of this role have access to
                    anyone's payroll record.
                    The role has been linked to the
                    payroll-department role.
               </description>
               <role-name>payroll</role-name>
               <role-link>payroll-department</role-link>
          </security-role-ref>
          ...
     </session>
     ...
</enterprise-beans>


@RolesAllowed
This is accomplished by adding the <login-config> element to the runtime deployment descriptor, sun-ejb-jar.xml.

Method permissions in the deployment descriptor using the method-permission el

RunAs annotation @RunAs("admin")

<enterprise-beans>
    ...
    <session>
      <ejb-name>EmployeeService</ejb-name>
      ...
      <security-identity>
        <run-as>
          <role-name>admin</role-name>
        </run-as>
      </security-identity>
      ...
    </session>
    ...
  </enterprise-beans>
 
  # Alternately, you can use the use-caller-identity element to indicate that you want to use the identity of the original caller, as shown in the code below:

<security-identity>
  <use-caller-identity />
</security-identity>

Securing Application Clients

Using Login Modules

An application client can use the Java Authentication and Authorization Service (JAAS) to create login modules for authentication. A JAAS-based application implements the javax.security.auth.callback.CallbackHandler interface so that it can interact with users to enter specific authentication data, such as user names or passwords, or to display error and warning messages.

Securing EIS Applications

Container-Managed Sign-On

In container-managed sign-on, an application component does not have to pass any sign-on security information to the getConnection() method. The security information is supplied by the container, as shown in the following example.

// Business method in an application component
Context initctx = new InitialContext();
// Perform JNDI lookup to obtain a connection factory
javax.resource.cci.ConnectionFactory cxf =
     (javax.resource.cci.ConnectionFactory)initctx.lookup(
      "java:comp/env/eis/MainframeCxFactory");
// Invoke factory to obtain a connection. The security
// information is not passed in the getConnection method
javax.resource.cci.Connection cx = cxf.getConnection();


Component-Managed Sign-On

In component-managed sign-on, an application component is responsible for passing the needed sign-on security information to the resource to the getConnection() method. For example, security information might be a user name and password, as shown here:

// Method in an application component
Context initctx = new InitialContext();
// Perform JNDI lookup to obtain a connection factory
javax.resource.cci.ConnectionFactory cxf =
     (javax.resource.cci.ConnectionFactory)initctx.lookup(
       "java:comp/env/eis/MainframeCxFactory");
// Get a new ConnectionSpec
com.myeis.ConnectionSpecImpl properties = //..
// Invoke factory to obtain a connection
properties.setUserName("...");
properties.setPassword("...");
javax.resource.cci.Connection cx =
  cxf.getConnection(properties);

  Specifying @DeclareRoles("employee") is equivalent to defining the following in the web.xml:

<security-role>
  <role-name>employee</role-name>
</security-role>


Nandhikanti Naresh Kumar.
sceaexam@gmail.com


3 comments:

  1. Sir ,
    Its a wonderful blog ..Impressed and i too start preparaing for SCEA exam. Please keep posting ..Thanks you sir,
    God bless you.

    Thanks,
    Prabhu V

    ReplyDelete
  2. Thank you for your comments on my blog. Will definitely try to post more things.

    ReplyDelete
  3. Good Blog Naresh.. it has lot of information. it really helps the people who are preparing for the exam.

    manikya

    ReplyDelete