Saturday, March 03, 2007

JAVA 認證心得 -- SCBCD (15)

Responsiability
##CONTINUE##

Bean Provider

  • It is the responsibility of the Bean Provider to implement ejbRemove() method in the CMP entity bean class
  • It is mandatory for the Bean Provider to declare environment entries in the deployment descriptor if the enterprise bean is coded to access environment entries at runtime.
  • The bean provider is typically responsible for specifying finder and select queries in the bean’s deployment descriptor
  • The bean provider is typically responsible for declaring the resource connection factory references in the deployment descriptor
  • A Bean Provider can use following resource managers:

    1. javax.sql.DataSource for obtaining JDBC connections

    2.javax.jms.QueueConnectionFactory/javax.jms.TopicConnectionFactory for obtaining JMS connections.

    3. javax.mail.Session for obtaining JavaMail connections

    4. java.net.URL for obtaining URL connections.

  • The Bean Provider must specify a primary key class in the deployment descriptor. The primary key type must be a legal Value Type in RMI-IIOP. The class must provide suitable implementation of the hashCode() and equals(Object otherObject) methods to simplify the management of the primary keys by the Container.
  • Assign the abstract schema name of the EJB.
  • Bean Provider is responsible for deciding whether the message-driven bean will be associated with a Queue or Topic in the target environment
  • The Enterprise Bean Provider is typically an application domain expert. The Bean Provider develops reusable enterprise beans that typically implement business tasks or business entities.

Deployer

  • Deployer is responsible for assigning security principals to the security roles.
  • Assign principals and/or groups of principals used for managing security in the operational environment to the security roles defined in the security-role elements of the DD
  • Application assembler and deployer should typically define the appropriate security policies for an application.
  • Assigning the security domain to the application
  • Bind a resource manager connection factory reference used by a bean to actual resource factory.
  • [MDB] The Deployer must guarantee that the bean is associated with a specific queue or topic

Application assembler

  • Application assembler and deployer should typically define the appropriate security policies for an application.
  • Linking security role reference to security roles

System Admin

  • Security domain administration
  • System Administrator is Monitor Databases

Container Provider

  • Container Provider is responsible for providing the security infrastructure
  • The EJB 2.0 complaint containers MUST be able to publish remote home references in a CORBA CosNaming service.
  • EJB containers are required to be able to publish EJBHome object references in a CORBA CosNaming service. The CosNaming service must implement the IDL interfaces in the CosNaming module defined in and allow clients to invoke the resolve and list operations over IIOP.
  • The CosNaming service must follow the requirements in the CORBA Interoperable Name Service specification for providing the host, port, and object key for its root NamingContext object. The Cos-Naming service must be able to service IIOP invocations on the root NamingContext at the advertised host, port, and object key.
  • The EJB container needs to ensure that all the EJB invocations received through the home and component interfaces are associated with some principal. The container must never return null from the getCallerPrincipal() method.
  • The container is required to enforce the security policies given by Deployer, but may or may not use the Java programming language security for that purpose.
  • The container provides a security domain and multiple principal realms to the enterprise beans, but is not required to support multiple security or principal realms.

Friday, March 02, 2007

JAVA 認證心得 -- SCBCD (14)

Security Management

##CONTINUE##

  • All the role names used by a bean must be specified in security-role-ref tags.

! ELEMENT resource-ref (description?, role-name,

-- the role name such as 'admin' used in the bean code. For example, ejbContext.isCallerInRole("admin");

role-link -- this is used by the deployer or the assembler to map the role name used by the bean to an actual role that exists in the system. )

The following is a sample usage:

enterprise-beans
session
ejb-nameBonusCalc/ejb-name
security-role-ref BP
descriptionsystem admins have higher bonus rates. /description
role-nameadmin/role-name -- This is given by the bean provider.
!-- deployer adds the following line because she knows that the role name

of system administrators is configured in her system as 'sysadmin'; --
role-linksysadmin/role-link AA
/security-role-ref
/session
/enterprise-beans

  • If the client is in a different security domain than the target enterprise bean, the System Admin is responsible for mapping the principals used by the client to the principals defined for the EJB. The result of this mapping is available to the Deployer
  • The exclude-list element is used to indicate the set of methods that should not be called. Within assembly-descriptor , should be specified by the Application Assembler.

    exclude-list

    description></description

    method

    ejb-name></ejb-name

    method-name></method-name

    /method

    /exclude-list

  • The AA links each security role reference to a security role using the role-link element.
  • The security roles defined in the deployment descriptor apply to all the enterprise beans declared in the same ejb-jar file.
  • Security roles make the task of Deployer easy to secure the enterprise bean application
  • The run-as identity doesn't change the security identity of its caller. The security identity of the caller remains the same and is checked to know its access to invoke methods of the enterprise bean.
  • The Bean Provider declares security role references in the deployment descriptor. Security role references declared in the deployment descriptor are scoped to the enterprise bean which contains the security-role-ref deployment descriptor element
  • It is the responsibility of the Application Assembler to define method-permission deployment descriptor element.
  • method-permission deployment descriptor element identifies methods of home and component interface of enterprise beans that can be invoked by a security role
  • specifies a relation between two ejbs ejb-relation
  • specifies the relationships that exist in an application relationships
  • 1. security-role-ref: This is the name used by the bean code to refer to a security role. Since it is used inside the bean code, the provider specifies it in the deployment descriptor.
    2. security-role: These are the logical roles that are available to the application. Since these are application specific, these are specified by the application assembler in the deployment descriptor. Also, since these are provided by the application assembler, the application assembler also has the responsibility of mapping security-role-ref to the security-role. Further, since the application assembler knows the business logic, she also specifies which bean methods can be called by which role using the
    method-permission tags.
    3. The deployer makes sure that the roles required by the application assembler are avaible in the target system. The Deployer's job is to map the security view that was specified by the Application Assembler to the mechanisms and policies used by the security domain in the target operational environment. The output of the Deployer's work includes an application security policy descriptor that is specific to the operational environment. The format of this descriptor and the information stored in the descriptor are specific to the EJB Container.
    The Deployer is also responsible for assigning the security domain and principal realm to an enterprise bean application.
  • Java.security.Principal is the type of the object by the method of the javax.ejb.EntityContext interface that retrieves the principal of the client that called the bean.
  • role-link link security-role-ref to security-role

JAVA 認證心得 -- SCBCD (13)

Exceptions

##CONTINUE##

  • For remote clients, container should wrap unrecoverable checked exception in a java.rmi.RemoteException.









  • javax.ejb.NoSuchObjectLocalException is thrown when a local client invokes methods on a session bean, which does not exist. java.rmi.NoSuchObjectException remote client.
  • The javax.ejb.ObjectNotFoundException is thrown by a finder method to indicate that the specified EJB object does not exit. [single-row or single EJB object] ONLY
  • javax.transaction.NotSupportedException and javax.transaction.RollbackException are predefined application exceptions. javax.ejb.AccessLocalException (subclass of javax.ejb.EJBException) and javax.transaction.InvalidTransactionException (subclass of java.rmi.RemoteException) are system exceptions
  • The javax.transaction.TransactionRolledbackException exception is not thrown when the session bean's business method calls setRollbackOnly() method of javax.ejb.EJBContext.
  • The container is responsible for rolling back the transaction associated with the method that has thrown system exception
  • The Bean Provider must catch checked system exceptions and re-throw as EJBException.
  • a session bean instance may be removed from the container while in the passivated state. This may occur when the client remains inactive for a long period and the Deployer-specified time-out for the session bean instance is reached or if the container crashes while the bean is in a passivated state. If the client becomes active after the session bean has been removed from the container then any attempt by the client to invoke business methods on the session bean will result in java.rmi.NoSuchObjectException which is a subclass of java.rmi.RemoteException (if the client is a remote client) or javax.ejb.NoSuchObjectLocalException (if the client is a local client). The ejbActivate() method may never be called on a passivated bean

JAVA 認證心得 -- SCBCD (12)

EJB-QL

##CONTINUE##

  • In an EJB QL query path expressions may appear in either FROM,SELECT or WHERE clause.

  • EJB QL path expressions

    1. (.) is considered the navigation operator

    2. Path expressions can terminate with either cmr-field or cmp-field

    3. A path expression can end with a single value or a collection value

  • The IS EMPTY operator allows an EJB-QL query to test if a collection-valued path expression contains elements or not

  • EJB-QL is a standard query language for declaring the behavior of find methods and select methods.

  • For finder method queries, the return type of the SELECT clause is the abstract schema type of the entity bean that defines the finder method.

  • For select method queries, the return type of the SELECT clause may be one of the following

    1. the abstract schema of the entity bean that contains the select method

    2. the abstract schema of a related entity bean

    3. a persistent field

  • CMP fields can’t be decomposed and navigated through path expressions.

  • query
    query-method
    method-namefindByCustomer/method-name
    method-params
    method-paramint/method-param
    /method-params
    /query-method
    ejb-qlselect distinct object(a) from Address a where a.cid=?1/ejb-ql
    /query

  • The following built-in functions are available to EJBQL queries:
    String Functions
    CONCAT( String, String) returns a String
    SUBSTRING( String, start, length) returns a String
    LOCATE( String, String [, start]) returns an int
    LENGTH( String) returns an int
    Arithmetic Functions:
    ABS( number) returns a number (int, float, or double)
    SQRT( double) returns a double

  • IN can be used only for a set containing String literals. Eg. SELECT Object(s) FROM Student s WHERE s.name NOT IN ('robert', 'michael')

  • The abstract-schema-name deployment descriptor is used to specified the name of the abstract schema type of an entity bean. Used in EJB-QL queries.

  • EJB-QL allows SELECT clauses to return any CMP or single CMR field.

JAVA 認證心得 -- SCBCD (11)

Transactions

##CONTINUE##

  • When using BMT demarcation, message-driven beans and stateless session beans must commit a transaction before the method that initiated the transaction returns

  • Only Session and Message driven bean can implement bean managed transactions

  • javax.transaction.UserTransaction

  • container-transaction element specifies a list of methods and their transaction attributes.

  • transaction-typeContainer/Bean/transaction-type is used only in session and message-driven beans because it is mandatory for entity beans to use container-managed transaction demarcation.

  • trans-attributeRequired/RequiresNew/Mandatory/Never/Supports/NotSupported/trans-attribute

  • Container throws java.lang.IllegalStateException if the enterprise bean using container-managed transaction demarcation invokes setRollbackOnly or getRollbackOnly of EJBContext interface from its methods with transaction attribute NotSupported, Supports or Never.

  • These are the methods you must mark with an attribute

    1. Session beans: ONLY business methods in the component interface

    2. Entity beans: business methods in the component interface. Remove(), remove(Object pk), remove(Handle h)

    3. Message-driven beans: onMessage()

  • Providing the transaction attributes for an enterprise bean is an optional requirement for the Application Assembler, because, for a given enterprise bean, the Application Assembler must either specify a value of the transaction attribute for all the methods for which a transaction attribute must be specified, or the Assembler must specify none. If the transaction attributes are not specified for the methods of an enterprise bean, the Deployer will have to specify them.

  • Only a stateful session bean is permitted to start a transaction in a method and not commit or rollback the transaction before returning.

  • CMT session beans and CMT message-driven beans will the different ejbCreate methods run within an unspecified transaction context.

  • A transaction may span multiple method calls on entity bean instance, CMT stateful session instance, BMT stateful session bean instance.

JAVA 認證心得 -- SCBCD (10)

Message-Driven Bean Component Contract
##CONTINUE##

  • setMessageDrivenContext(),onMessage() can take an argument, only two methods in javax.ejb.MessageDrivenBean interface.
  • All calls to a MDB instance must be serialized
  • A message-driven bean must not be coded as reentrant
  • Only onMessage method maybe called with a specified transaction context.
  • The message-driven bean’s lifecycle is newInstance() -> setMessageDrivenContext() -> ejbCreate() -> onMessage()
  • onMessage() is able to access other enterprise beans, with BMT able to access resource managers
  • [MDB] For BMT beans, the Container uses the acknowledge-mode DD elements
  • A Message Driven Bean can only have Required and NotSupported as its transaction attribue.
  • MDB classes should not define a finialize() method.
  • MDB classes must define one ejbCreate() method, which must not take any argument. It is invoked only once in the life of the bean instance
  • MDB classes are allowed to have instance variables, which can contain state across the handling of client messages.
  • MDB can’t be accessed using the Java RMI API. And they are stateless
  • A message driven class must be defined public and must not be defined final or abstract.
  • The getRollbackOnly(),setRollbackOnly() method called from a message-driven bean with container-managed transaction demarcation will not throw any system exception
  • The ejbRemove() method invoked on a message-driven bean with container-managed transaction demarcation will not throw any system exception.
  • javax.ejb.EJBContext's methods which throw java.lang.IllegalStateException from a message-driven bean with container-managed transaction demarcation are getCallerIdentity(), getCallerPrincipal(), getEJBLocalHome() and getEJBHome().
  • A message-driven bean is required to provide no argument public constructor and a no argument ejbCreate method
  • The message-driven bean instance continues to exist from the client's perspective. The container actually discards(transition to 'does not exist' state) the bean instance which has thrown the java.lang.RuntimeException.
  • The code written in the onMessage(javax.jms.Message) method must take care of out of sequence messages. The message-driven bean instance may receive messages that are out of sequence.
  • In which of the following cases a message will be redelivered to the message-driven bean instance if the transaction rolls back?

    The message-driven bean uses container-managed transaction demarcation and Required transaction attribute is specified for the onMessage(javax.jms.Message) method

  • A MessageDrivenBean must implement ejbCreate and ejbRemove methods. Implementing multiple ejbCreate() is not an error but the container will only call the no-args ejbCreate() method, which the bean must have.
  • onMessage() is declared in javax.jms.MessageListener interface, which must be implemented by every MDB.
  • MessageDrivenBean interface has only two methods: ejbRemove() and setMessageDrivenContext.
  • An important point to remember here is that only the sending of the message is a part of the transaction. Whether the MDB receives the message or consumes it does not affect Bean's transaction. Further, the client's transaction context is never passed to a MDB. The container creates a new transaction context for a MDB if it requires a transaction. So, if the MDB rolls back its transaction, it does not affect the message sender's transaction.
    The second point is that if an MDB does not throw any exception while processing the message (Note: It can only throw Runtime or EJBExceptions from onMessage()), the message is considered to be consumed. On the other hand, if the onMessage() method throws an exception, the exception is logged, the MDB instance is discarded, and the transaction is rolled back. The message is redelivered (to a different MDB instance). How many times a message can be redelivered depends on the container.
  • The message-driven bean class must define one ejbCreate() method whose signature must follow these rules:

    1. The method name must be ejbCreate.

    2. The method must be declared as public.

    3. The method must not be declared as final or static.

    4. The return type must be void.

    5. The method must have no arguments.

    6. The throws clause must not define any application exceptions.

  • The onMessage() method may contain method calls to other private methods of the bean.
  • As any method of a message-driven bean class must not throw any application exception.
  • A message-driven bean can receive messages asynchronously but it sends messages synchronously.
  • From the client's perspective a message-driven is shared between multiple clients
  • MDB doesn’t complete transaction before the end of the onMessage method

    1. Log application error

    2. roll back

3. discard instance of the bean

JAVA 認證心得 -- SCBCD (9)

Client View of a Session Bean
##CONTINUE##



  • import javax.ejb.* , java.rmi.RemoteException
  • A client can pass a remote home object reference to another application. A client can pass a local home object reference to another application through its local interface.
  • Invocation of remove (Object primaryKey) method on the session bean's remote home interface results in javax.ejb.RemoveException (assume that session bean instance exists in the container).

JAVA 認證心得 -- SCBCD (8)

Session Bean Component Contract
##CONTINUE##

  • The isIdentical(...) method of stateless session bean's component interface always returns true when used to compare session objects of the same stateless session bean within the same home.True if the stubs refer to two entities with the same primary key.
  • A stateful session bean is about to be passivated, these below can remain assign to non-transient fields of the session bean class
    1. null -> of course
    2. A reference to the javax.ejb.SessionContext object (even it is not serialize) -> the EJB container must ensure that the Session Context object will be serialize properly.
    3. A serialize object -> The Java Serialization protocol determines dynamically if an object is serializable or not based on its runtime type
  • The return type of ejbCreate() method of a session bean should be void. Can throw application exception or CreateException
  • A bean’s conversational state may contain primitive values, serializable objects and certain special types like SessionContext. The remote reference to other bean are also preserved by the container, if present in the conversational state.
  • The afterBegin method notifies a session Bean instance that a new transaction has started, and that the subsequest business methods on the instance will be invoked in the context of the transaction.
  • The state of a stateful session bean instance is maintained by the session bean's instance variables. The conversational state is maintained by the instance variables of the stateful session bean instance
  • The conversational state of a stateful session bean instance is not written to a persistent store
  • A stateful session bean instance can have open resources such as sockets and database connections as part of the conversational state of the session bean instance. These open resources must be closed when the stateful session bean instance is passivated and must be re-opened when the bean instance is activated
  • EJB supports distributed transactions
  • The container is responsible for preserving the following objects across passivation and activation:
    1. reference to javax.ejb.SessionContext
    2. reference to component and home interface
    3. reference to the environment naming context or any of its sub-context (i.e., javax.naming.Context)
    4. reference to javax.transaction.UserTransaction
    5. reference to resource connection factory and any other serializable object. (i.e., javax.sql.DataSource)
  • The getEJBLocalObject() method of javax.ejb.SessionContext is used to obtain the session bean's local component interface
  • The javax.ejb.SessionBean interface defines methods which can be called only by the container in which the session bean is deployed. The methods defined by the SessionBean interface are ejbCreate, ejbRemove, ejbActivate and ejbPassivate.
  • The container doesn't preserve the value of a transient variable across passivation and activation of a stateful session bean even if it references UserTransaction or SessionContext interface.
  • Here are the rules for a create method in the bean class.
    1. Its signature must be like:
    public void ejbCreate<method>(...);
    2. It can throw any exception except java.rmi.RemoteException. It may even choose not to throw any exception.
    3. It must not be final or static.
    Note that, in the home interface (Local or Remote), the create method signature MUST throw javax.ejb.CreateException but the bean class's corresponding ejbCreate() method signature may or may not declare CreateException in its throws clause depending on whether the method code throws CreateException or not.
  • An ejb acquires resources in ejbCreate() and ejbActivate() methods and it releases the same resources in ejbRemove() and ejbPassivate() method.
  • non-transient fields would already have been given the value that they had before passivation. So there is no need to initialize them
  • Since the transient fields are not preserved while serialization-deserialization process, you need initialize such fields to appropriate values in ejbActivate() method
  • Remember the following point about the ejbCreate methods:
    1. The method name must have ejbCreate as its prefix.
    2. The method must be declared as public.
    3. The method must not be declared as final or static.
    4. The return type must be void.
    5. The method arguments must be legal types for RMI/IIOP if there is a create<METHOD>(...) corresponding to the ejbCreate< METHOD>(...) method on the session bean's remote home interface.
    6. The throws clause may define arbitrary application exceptions, possibly including the javax.ejb.CreateException.
  • The session bean instance must not reset it's state in the beforeCompletion() method because the outcome of the transaction (commit or rollback) is not known at the time beforeCompletion() method is invoked.
  • the conversational state of a stateful session bean is not transactional i.e. it is not automatically reset to its initial state if the transaction in which it was manipulated is rolled back.
  • The session bean instance can reset it's state in the afterCompletion(boolean) method

JAVA 認證心得 -- SCBCD (7)

Session Bean Lifecycle
##CONTINUE##

  • The ejbRemove() method may not be called on a stateful session bean instance in the following cases:
    1. The EJB Container crashes
    2. A system exception is thrown from the instance’s method
    3. The bean times out while in passivated state
  • In session beans it is mandatory to specify transaction attributes for the business methods defined in the component interface. Transaction attribute must not be specified for methods defined in javax.ejb.EJBObject and javax.ejb.EJBLocalObject interface.
  • It is required that the object returned from the getEJBObject method of SessionContext interface must be cast to the session bean's remote component interface using Java language cast. It is not required to use PortableRemoteObject's narrow (...) method on the object returned by the getEJBObject method of SessionContext interface
  • A stateful session bean instance cannot be removed while the instance is associated with a transaction
  • Each create method defined in the remote home interface must have a matching method with the same name, number and type of arguments but the return type is different. The return type of create methods defined in the remote home interface is the stateful session bean's remote component interface but the return type of ejbCreate methods is void.

JAVA 認證心得 -- SCBCD (6)

Client View of an Entity
##CONTINUE##

  • Javax.ejb.NoSuchEntityException is the exception thrown if a remote client attempts to access an entity bean object, which has already been removed. Maybe thrown by the bean component business methods , and by the ejbLoad() and ejbStore()


  • Entity bean allow shared access from multiple users.
  • Entity bean can expose a remote interface to serve remote clients, a local interface to serve local clients or both.
  • The remote home interface can be used to create, remove and find entity objects
  • The create<METHOD> methods in the entity bean's home interface must return the component interface type and must include javax.ejb.CreateException in their throws clause. Because the interface is the local home interface, therefore, create<METHOD> methods defined in it must not throw java.rmi.RemoteException.
  • A remote client can be in the same or different JVM as the entity bean instance. When the remote client and entity bean instance are in the same JVM even then the client accesses entity bean instance as it is remotely located.
  • Javax.ejb.HomeHandle interface must be implement by an entity bean’s home handle class.
  • A handle class for a remote component interface of an entity bean must implement the Java.io.Serializable interface and the javax.ejb.Handle interface

JAVA 認證心得 -- SCBCD (5)

CMP Entity Bean Lifecycle
##CONTINUE##

  • The ejbStore method in CMP entity beans is invoked before the instance's persistent state is synchronized.
  • The ejbLoad method in CMP entity beans is invoked after the instance's persistent state is loaded from the persistent store
  • The container associates appropriate EntityContext to the bean before calling any other method. This entity context contains the primary key information for the entity bean. This information can be retrieved using the getPrimaryKey() method of EntityContext interface.
  • Every <ejb-relation> element has two <ejb-relation-role> elements.
  • The implementation of the Bean Provider’s ejbCreate<METHOD> methods of a CMP entity bean should always return null, even though the method is declared to return the primary key type
  • Each ejbSelect method must have a corresponding <query> element specified in the deployment descriptor
  • The ejbSelect methods can return container-managed relationship and persistent fields and a entity bean's component interface or its collection
  • The Bean Provider is responsible for providing the implementation of ejbHome methods in entity beans with container-managed persistence
  • An entity bean class may declare 0 or more ejbHome methods that must be prefixed with “ejbHome”. Must be public, it must not contain the static modifier. Its arguments and return values must be legal RMI-IIOP types. Its throws cluse may contain arbitrary application exceptions ,but not the java.rmi.RemoteException.
  • ejbCreate sets primary key fields. ejbPostCreate sets bean relationship fields. ejbHome[method] Used to implement methods that do not require a bean identity.
  • <cmp-field> <field-name>age</field-name> </cmp-field>
  • It is possible for an Entity Bean not to have any create methods.
  • As per EJB Specification 2.0 10.3.8 (Page 155) It is the responsibility of the Container to raise the java.lang.IllegalArgumentException if the Bean Provider attempts to assign null as the value of a collection-valued cmr-field by means of the set accessor method.
  • A client program must use the PortableRemoteObject. narrow(...) method to convert the objects contained in the collections returned by a finder method on the entity bean's remote home interface to the end
    Collection students = theHome.findByName("john"); Student first = (Student) PortableRemoteObject.narrow(students.get(0), Student.class);
  • findByPrimaryKey is the method that must always be declared in the (local or remote) home interface of an entity bean.
  • If a finder method is defined to return a single entity object (i.e object implementing entity bean's component interface) and the corresponding query deployment descriptor element results in returning multiple entity objects (i.e objects implementing entity bean's component interface) then the container throws javax.ejb.FinderException.
  • In ejbActivate() method Bean Provider cannot use set accessor methods for abstract persistence schema to initialize the container-managed relationship or persistent fields.
  • A cascade-delete enabled bean is automatically removed when any “multiplicity of one” bean with which it is related is removed.

JAVA 認證心得 -- SCBCD (4)

Entity Beans
##CONTINUE##

  • An Entity beans can only have Required, RequiresNew, and Mandatory as its transaction attribute.
  • The primary key type in CMP entity beans must be a legal Value Type in RMI-IIOP.
  • The primary key class must be public, and must have a public constructor with no parameters.
  • The return type of findByPrimaryKey(...) method in the CMP entity bean's home interface is the entity bean's component interface.
  • The finder methods defined in the home interface of CMP entity beans must return Entity bean's component interface or its collection.
  • The Bean Provider does not provide any ejbFind<METHOD> method corresponding to finder method in the home interface of the CMP entity bean.
  • The Container throws javax.ejb.ObjectNotFoundException only during single-entity finder methods.
  • A entity bean using CMP to create persistent relationships
    1. A local interface is required to have a bidirectional relationship with another entity bean.
    2. Relationships can be one-to-one, one-to-many, or many-to-many
    3. A get method return type can use Collection and Set
  • The bean’s primary key class must provide a suitable implementation of the hashCode and equals methods
  • Instead of defining separate primary key classes, CMP entity beans can share the same primary key class
  • Use equals() on a primary key class to determine if two keys refer to the same entity
  • The <primkey-field> element is used to specify the name of the primary key field for an entity with container-managed persistence.
  • The <primkey-field> must be one of the fields declared in the <cmp-field> element, and the type of the field must be the same as the primary key type.
  • The <primkey-field> element is not used if the primary key maps to multiple container-managed fields (i.e. the key is a compound key). In this case, the fields of the primary key class must be public, and their names must correspond to the field names of the entity bean class that comprise the key.
  • The prim-key-class element contains the fully-qualified name of an entity bean’s primary key class.
    If the definition of the primary key class is deferred to deployment time, the prim-key-class element should specify java.lang.Object.

    Used in: entity
    Examples:
    <prim-key-class>java.lang.String</prim-key-class>
    <prim-key-class>com.wombat.empl.EmployeeID</prim-key-class>
    <prim-key-class>java.lang.Object</prim-key-class>
  • A entity bean does survive the server crash
  • Finder methods throw the FinderException also application specific exceptions. All ejbFind<METHOD>() methods except the ejbFindByPrimaryKey() method need to be specified in the query DD element for the entity.
  • The names of the fields in the primary key class must be a subset of the names of the container-managed fields.
  • getCallerPrincipal() method of javax.ejb.EntityContext interface can be used by a CMP entity bean instance to obtain the invoker of its component interface. It returns the java.security.Principal that identifies the invoker of entity bean's component interface.
  • getEJBObject() returns the remote component interface of the entity bean instance.
  • An entity bean is associated with an object identity only when it is in ready state.
  • A CMP entity bean class must be abstract , provide abstract getters and setters for all persistent fields. Implement ejbCreate methods for all create methods declared in its home interface. All the finder methods are implemented by the container
  • Helper classes used by the bean class and Bean's local home and local component interfaces must be in an ejb-jar.
  • create method Must return a component interface type.
  • finder method May return a component interface type or return a collection of component interface types.
  • remove method Must return void
  • findByPrimaryKey method Must return a component interface type.
  • Session beans do not have an identity. Only Entity beans have an identity, which can be retrieved using EntityContext.getPrimaryKey().
  • Primary Key Class for an entity bean must follow these rules: 1. must implement the java.io.Serializable interface. 2. all its fields have to be made public, to allow the container to use the Relfection API during the synchronization with the database. 3. when using CMP Entity Beans, the fields of the Primary Key class must also be present in the Bean class, to allow the container to set the values using Reflection API. Although not necessary, it should also override the hashCode() and equals() methods to allow the class to be better handled inside Collections.
    public class MyKey implements java.io.Serializable {
    public String a, b;
    public String getA(){ return a;}
    public void setA(String pA){ a = pA; }
    public String getB(){ return b;}
    public void setB(String pB){ b = pB; }
    }
  • Once a bean is removed, the bean does not exist. Therefore, the primary can be used to create a new bean.
  • Rules for a primary key class: 1. The primary key class must be public, and must have a public constructor with no parameters. 2. All fields in the primary key class must be declared as public. 3. The names of the fields in the primary key class must be a subset of the names of the container-managed fields.(This allows the container to extract the primary key fields from an instance's container-managed fields, and vice versa.)
  • EntityContext interface extends from EJBContext interface and declares only three additional methods.
    1. EJBLocalObject getEJBLocalObject() Obtain a reference to the EJB local object that is currently associated with the instance.
    2. EJBObject getEJBObject() Obtain a reference to the EJB object that is currently associated with the instance.
    3. java.lang.Object getPrimaryKey() Obtain the primary key of the EJB object that is currently associated with this instance.
    Methods inherited from interface javax.ejb.EJBContext: getCallerPrincipal, getEJBHome, getEJBLocalHome, getRollbackOnly, getUserTransaction, isCallerInRole, setRollbackOnly
  • ths <prim-key-class> element contains the fully-quified runtime type of the primary key class

Thursday, March 01, 2007

JAVA 認證心得 -- SCBCD (3)

Component Contract for Container-Managed Persistence (CMP)
##CONTINUE##

  • The <cmr-field-type> element is used for collection-valued container-managed relationship(CMR) fields only. It’s specifies the type of the collection that is used. Java.util.Collection and java.util.Set. It’s in <cmr-field>
  • The bean provider must not expose the following through the remote interface
    1. Container-managed collection classes, which are used for relationship
    2. Local interface types or local home interface types
    3. Get and set methods for CMR fields
    4. Persistent Collection classes used in container-managed relationships (ps. Accessor methods for the persistent fields is legal but not good!)
  • CMP and CMR fields are not defined in the bean class. These are virtual fields and their implementation is also the container’s responsibility.
  • Container-managed relationships are defined in terms of the local interfaces of the related beans.
  • Each entity-to-entity relationship is defined in a <ejb-relation> element within the <relationships> element
  • The CMP entity bean class must implement the EntityBean interface. It may, but is not required to implement the component interface. However, if the class does implement the component interface, the class must provide implementations of the methods defined by that interface.
  • The container-managed persistent and relationship fields must not be defined in the entity bean class. The container-managed persistent and relationship fields are defined in the abstract persistence schema (specified in the deployment descriptor) of the entity bean.
  • The accessor methods for container-managed persistent and relationship fields must be defined in the entity bean class. The abstract accessor methods defined in the entity bean class are implemented by the container.The container-managed relationship fields can't be initialized in the ejbCreate<METHOD> method but they can be initialized in the corresponding ejbPostCreate<METHOD> method. The ejbPostCreate<METHOD> is responsible for initializing the container-managed relationship fields.

JAVA 認證心得 -- SCBCD (2)

Enterprise Java Beans (EJB) Overview
##CONTINUE##

  • A session or entity bean can be redeployed multiple times in the EJB container and each redeployed bean will have a distinct home.
  • Each enterprise bean defines its own set of environment entries. All instances of an enterprise bean within the same home share the same environment entries.
  • Environment entry values of an enterprise bean are not shared with other enterprise beans. Enterprise bean instances are not allowed to modify the bean’s environment at runtime.
  • EJBs are not allowed to make use of java.io package.
  • An EJB container is required to allow synchronized access to multiple users of an entity bean. The bean developer need not worry about the synchronization herself.

JAVA 認證心得 -- SCBCD (1)

Enterprise Bean Environment
##CONTINUE##

  • The java:comp/env JNDI naming context refers to enterprise bean's private namespace. it is not shared with other enterprise beans
  • Within a single EJB 2.0 container, an EJB can have multiple sets of environment entries. Environment entry values may only Strings and Wrappers.
  • The bean provider must declare all the resource manager connection factory references in the deployment descriptor using the <resource-ref> element
  • The bean provider uses the <res-auth> DD element to indicate which authentication approach is to be used for resource manager access.
  • The <ejb-ref> DD element is used for the declaration of a reference to an enterprise bean’s home
  • EJB reference's scope is within the enterprise bean that container the <ejb-ref> or <ejb-local-ref> deployment descriptor element. So the EJB reference cannot be shared among enterprise beans and there is no name conflict even if other enterprise beans define <ejb-ref> or <ejb-local-ref> with the same <ejb-ref-name> element.
  • The resource manager connection factory references are scoped to the enterprise bean that contains the <resource-ref> element. The resource manager connection factory references can't be shared between enterprise beans but the connections obtained from the resource manager connection factory can be shared among enterprise beans.
  • [Scope] Enterprise bean that contains the deployment descriptor element<env-entry><ejb-ref><resource-ref><resource-env-ref><security-role-ref>
  • [Scope] EJB-JAR file i.e all the enterprise beans in the same EJB-JAR file <security-role>
  • The <ejb-link> element must not refer to the enterprise beans in a different EAR file i.e the <ejb-link> can refer to enterprise beans only in the same EAR file, which may reside in a different ejb-jar file.
  • <! ELEMENT resource-ref (description?, res-ref-name, res-type, res-auth, res-sharing-scope?) >
  • An EJB container must support propagation the caller's principal from one component to another
  • EJB defines "Local interfaces" which can be used by local clients. As opposed to Remote interfaces, local interfaces provide a lightweight access to enterprise javabeans.
  • EJBs have only a read-only access to their environment. It will throw a javax.naming.OperationNotSupported exception. Eg.ctx.rebind("java:comp/env/locale", actuallocale);
  • The ejb-jar file producer can create an ejb-client JAR file for the ejb-jar file. The ejb-client JAR file contains all the class files that a client program needs to use the client view of the enterprise beans that are contained in the ejb-jar file. If this option is used, it is the responsibility of the Application Assembler to include all the classes necessary to comprise the client view of an enterprise bean in the ejb-client JAR file. The ejb-client JAR file is specified in the deployment descriptor of the ejb-jar file using the optional ejb-client-jar element. The value of the ejb-client-jar element is the path name specifying the location of the ejb-client JAR file in the containing J2EE Enterprise Application Archive (.ear) file. The path name is relative to the location of the referencing ejb-jar file.
  • An EJB container must support the following APIs:
    1. Java 2 Platform, Standard Edition v1.3 (J2SE) APIs
    2. EJB 2.0 APIs
    3. JNDI 1.2
    4. JTA 1.0.1, the UserTransaction interface only
    5. JDBC 2.0
    6. JMS 1.0.2
    7. JavaMail 1.1, sending mail only
    8. JAXP 1.0. includes SAX and DOM parsers. Parse XML.
  • No enterprise bean needs to be prepared to handle simultaneous client requests. The container ensures that only one request is being processed by a bean instance at a time.
  • Java:comp/UserTransaction
  • <env-entry-type>Wappers and java.lang.String

JAVA 認證心得 -- SCBCD

Sun Certified Business Component Developer for Java 2 Platform, Enterprise Edition 1.3

此門考試的內容有

  • Enterprise Bean Environment
  • Enterprise Java Beans (EJB) Overview
  • Component Contract for Container-Managed Persistence (CMP)
  • Entity Beans
  • CMP Entity Bean Lifecycle
  • Client View of an Entity
  • Session Bean Lifecycle
  • Session Bean Component Contract
  • Client View of a Session Bean
  • Message-Driven Bean Component Contract
  • Transactions
  • EJB-QL
  • Exceptions
  • Security Management
  • Responsiability
  • Other
接下來幾篇是我當初準備 SCBCD 認證的心得筆記

Tuesday, February 27, 2007

Introduction to Oracle9i: SQL (14)

Other
##CONTINUE##

  • If subqueries are nested to more than 6 levels the performance level generally comes down. So usage of cursors is recommended under these circumstances.
  • BACKUP ANY TABLE system privilege may be granted to a role.
  • SELECT part_id_seq.NEXTVAL FROM SYS.DUAL;
  • The size of a table does not need to be specified.
  • System privileges :
    - Creating new users
    - Removing users
    - CREATE TABLE
    - Removing tables
    - Backing up tables
    - CREATE SESSION
    - CREATE SEQUENCE
    - CREATE VIEW
    - CREATE PROCEDURE
    - GRANT
  • Object Privilege
    - UPDATE EXECUTE
    - DELETE INDEX
    - INSERT REFERENCES
    - SELECT ALTER
  • VARCHAR2 is the only datatype that is variable in length. When creating a column with a VARCHAR2 datatype a length must be specified. CHAR default length of 1 is used.
  • Dual is a Dummy table which resides in ‘SYS’ Schema. It has only one column and one row. By Default, all users have privileges to access this table.

Introduction to Oracle9i: SQL (13)

Creating and managing tables
##CONTINUE##

  • Constraints created on views are not enforced; hence they are called declarative constraints.
  • Row_Num pseudocolumn is used for performing Top-‘N’ analysis.
  • While updating data through a join view only one of the base tables can be updated with one DML statement.
  • Views are masks placed upon tables. Views are used to restrict the access of the user to the data of the base tables they are also referred to as masks on the table.
  • Synonyms are simply a way of accessing table through a shortcut name.
  • Triggers are functions that execute automatically when a specified action takes place on the database.
  • CHAR (20 BYTE), VARCHAR (20 BYTE)

Introduction to Oracle9i: SQL (12)

Creating other database objects
##CONTINUE##

  • TIMESTAMP, INTERVAL YEAR TO MONTH, INTERVAL DAY TO SECOND, TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE
  • To look on the view definition you need to query the USER_VIEWS data dictionary view. Can’t use DESC.
  • USER_SOURCE data dictionary view is used to store system objects definitions only.
  • USER_OBJECTS data dictionary view is used to find record about view
  • The ROWID datatype stores information related to the disk location of table rows. They also uniquely identify the rows in your table. The ROWID datatype is stored as a hexadecimal string.
  • Create index may require a temporary segment.
  • Table is a Database object which has many key columns dependent on the key column of same or other object. Cursor is not a database object which forms a memory area independent of whether the query fetches data or not. A SEQUENCE is an automatic number generator and does not require a segment. View is a database object dependent on one or more tables or views.
  • After create a sequence it is first necessary to issue the ‘Select seq.nextval from dual’
  • Row Share, Row Exclusive, Share Row Exclusive are valid DML locks in ORACLE.
  • ON DELETE CASCADE clause allows you to delete child records if parent records are deleted.
    DELETE FROM dept WHERE depe=10 ON DELETE CASCADE;
  • Build_index(Btree=>’abc’,Bitmap=>’efg’) è Build_index(‘abc’,’efg’)
  • Bitmaps work well in multiple indexes rather than single indexes. Bitmaps do not support row-level locking. Bitmap indexes are suitable for low-cardinality columns. Bitmap indexes are useful for datawarehousing. Updates to key columns in a bitmap index is very expensive.
  • B-tree indexes work well as a single index. B-tree indexes are useful for OLTP. B-tree indexes are suitable for retrieval of a small number of rows.

Introduction to Oracle9i: SQL (11)

Including constraints
##CONTINUE##

  • In order to view Null values as some other character the command ‘Set Null ’ has to be specified before execution of the select statement. Eq. SET NULL #.
  • Constraints have functions to enforce rules at the view and table levels and to prevent the deletion of data if dependencies exist between tables. Constraints are used to put dependences on data.
  • ‘Disable Constraint’ disables the constraint, drop the index on the table and does not allow any DML operation on the table.
  • Oracle creates a profile named DEFAULT when the database is created. Profile cannot be renamed. Default is a valid name for a profile resource. When a database is created all resources associated with the default profile is unlimited.

Introduction to Oracle9i: SQL (10)

Producing readable output with iSQL *Plus
##CONTINUE##

  • iSQL*Plus commands can be abbreviated. Like DESCRIBE as DESC. iSQL*Plus is the ORACLE proprietary interface for executing SQL statement.
  • SQL statements manipulate data and table definitions in the database.
  • If you set Environment Variables in LOGIN.SQL file, every time you login, this file runs automatically.
  • Ttitle, connect, define, undefined, prompt are iSQL plus commands.
  • START dela
    It runs the DELA.SQL script file.
  • SQL*Plus DEL command deletes the current line from the buffer. And DEL 4 5 command deletes lines 4 & 5 of the buffer.
  • Using REM, /**/, - -.

Introduction to Oracle9i: SQL (9)

Restricting and sorting data
##CONTINUE##

  • Only one privilege can be assigned to a user at any point of time.
  • PASSWORD_REUSE_TIME sets the maximum number of days before the password can be reused.
  • PASSWORD_LOCK_TIME sets the number of days after which the password will be unlocked.
  • PASSWORD_REUSE_MAX sets the maximum number of password changes before which the password can be reused.
  • PASSWORD_LIFE_TIME sets the number of days the password will remain valid.
  • Create role, Alter role, set role.
  • (Syntax)
    REVOKE {privilege [, privilege….] ALL} ON object
    FROM {user [, user…] role PUBLIC}
    [CASCADE CONSTRAINTS];

    REVOKE select, insert ON departments FROM scott;

Introduction to Oracle9i: SQL (8)

Creating Views
##CONTINUE##

  • Percentile_Cont is used for obtaining the median value of an ordered group. Regr_Avgx takes in a pair of list of values and then calculates the average of the second list after eliminating all the Nulls.
  • Minimum, Count and Variance are valid summary operations.
  • A view can be created as a join on two or more tables. This type of view is called complex view.
  • (Syntax)
    CREATE [OR REPLACE] [FORCE NOFORCE]
    VIEW [schema.]view [(alias [,alias]...)]
    AS subquery
    [WITH CHECK OPTION [CONSTRAINT constraint]]
    [WITH READ ONLY [CONSTRAINT constraint]] ;
  • You cannot remove a row if the view contains the following:
  • You cannot modify data in a view if it contains:
  • You cannot add data through a view if the view includes:
    - Grouping functions
    - A GROUP BY clause
    - The DISTINCT keyword
    - The pseudocolumn ROWNUM keyword

    - Columns defined by expressions
    - NOT NULL columns in the base tables that are not selected by the view.
  • The name and definition of the view is stored in the data dictionary ‘user_view’
  • A table is key preserved if every key of the table can also be a key of the result of the join. So, a key-preserved table has its keys preserved through a join.
  • DROP VIEW trans_view;
  • A view can be created if the base table does not exist but constraints cannot be defined on the view without the DISABLE NOVALIDATE clause.
  • TABLE PRIVILEGES data dictionary view gives the information of the all OBJECT privileges granted to the user.
  • USER_OBJECTS : Information of all the objects created by the user.
  • USER_COL_PRIVS_RECD : Privileges granted to the users on the specific columns of the table.
  • USER_TAB_PRIVS : Privileges granted to the users on the specific tables.
  • We cannot index a view
  • (Syntax)
    INSERT INTO managerid(id, name, salary, hiredate)
    SELECT empno, ename, sal, hiredate
    FROM emp WHERE job=’MANAGER’;