Friday 29 May 2009

4-How to setup a JMS queue with also JTA processing

WEBLOGIC JMS queue setup

1- I build the EJB outside the Jdev environment, at C:\JTAdistrib with build.xml
The output goes to C:\ JTAdistrib\ deploy\ JTAdis. jar

2- Then I deployed the EJB with WebLogic Console
Deployments->lock-edit->install
Path: C:\ JTAdistrib\ deploy\ JTAdis. Jar

3- Services->Messaging->JMSservers -> Lock-Edit -> new
Name: RegistrarQ
Targets: DefaultServer

4- Services->Messaging->JMSmodules -> Lock-Edit -> new
Name: jms/QCF

Summary of resources

Name………….…
Type…………………..JNDI Name ……….Subdeployment…………………..Targets
jms/QCF…………Connection Factory…ConnectionFactory…Default Targetting……………….DefaultServer
jms/RegistrarQ..Queue………………RegistrarQ……….jms/RegistrarQsubDeploy…..RegistrarQ



Name: jms/RegistrarQ
Subdeployment: jms/RegistrarQsubdeploy
Destination: RegistrarQ
Monitoring: jms/QCF!jms/RegistrarQ (This is only an output field – I put it here for for checking)
Control: jms/QCF!jms/RegistrarQ (This is only an output field – I put it here for for checking)

Name: jms/QCF
JNDI name: ConnectionFactory
Target: DefaultServer

Do not play with the WebLogic – console parameters. If you need you may change the logging parameters to see more info. But TINTPB’s this example works almost fine specially with the ejb-jar xml files, you just have to make the jms setup work. Please note the sequence of the definitions made with weblogic console. Be carefull about the JNDI names also. Avoid giving the same name to different things, give a unique name to every different thing.

javax.naming.NameNotFoundException: While trying to lookup 'javax.jms.Queue.class' didn't find subcontext 'Queue'.

This error is given when the queue destination has not been made. It looks as if it is a JNDI error but actually the object that the JNDI is supposed to point at does not exist. It gives the same error message to both.

The output to the program is below:

<May 28, 2009 10:45:54 PM EEST> <Notice> <Stdout> <BEA-000000> <Connecting to JDBC data store...>
<May 28, 2009 10:45:54 PM EEST> <Notice> <Stdout> <BEA-000000> <Begin JTA distributed transaction. . .>
<May 28, 2009 10:45:54 PM EEST> <Notice> <Stdout> <BEA-000000> <Trying to drop table StudentCourse...>
<May 28, 2009 10:45:54 PM EEST> <Notice> <Stdout> <BEA-000000> <Table StudentCourse dropped successfully...>
<May 28, 2009 10:45:54 PM EEST> <Notice> <Stdout> <BEA-000000> <Created new StudentCourse table.>
<May 28, 2009 10:45:54 PM EEST> <Notice> <Stdout> <BEA-000000> <A new record is inserted into table StudentCourse. . .>
<May 28, 2009 10:45:54 PM EEST> <Notice> <Stdout> <BEA-000000> <Connecting to JMS destination...>
<May 28, 2009 10:45:54 PM EEST> <Notice> <Stdout> <BEA-000000> <Notify registration...>
<May 28, 2009 10:45:56 PM EEST> <Notice> <Stdout> <BEA-000000> <Message sent: Student id=1 is enrolled in course=CS310>
<May 28, 2009 10:45:57 PM EEST> <Notice> <Stdout> <BEA-000000> <Committing the transaction. . .>
<May 28, 2009 10:46:09 PM EEST> <Warning> <JMSPool> <BEA-169817> <The JMS connection factory resource ConnectionFactory declared in the EJB "RegistrarMDB" as part of application "JTAdis" does not support XA. It cannot be used inside a transaction context.>

Please note that in order to see this output you must have set up the sensitivity of the defaultserver’s logging to the notice level.

With this example I have completed tinptB ‘s Blog: EJB in 21 Days: which includes almost all aspects of EJB programming. My gratitude goes to him/her. I would be happy if I could contribute just a bit by providing the solutions to all of his open end questions by the way.

Cheers.

Ali R+ SARAL

3-How to setup a JMS queue with also JTA processing

FILE: Client.java
import javax.naming.*;
import javax.rmi.PortableRemoteObject;

import jtadistrib.UserManager;
import jtadistrib.UserManagerHome;

public class Client {
public static void main(String argv[]) {
// A simple client deligates the UserManager session bean
// to perform a JTA transaction. The JTA transaction will
// be started in one method, then the context will be
// propagated to other methods of the bean. Multiple resources:
// a JDBC and a JMS resource manager are invloved in the
// same distributed transaction.
System.out.print("Demonstration the use of JTA \n");
try {
InitialContext ctx = new InitialContext();
Object obj = ctx.lookup("jtadistrib/UserManagerHome");
UserManagerHome userHome = (UserManagerHome)
PortableRemoteObject.narrow(obj, UserManagerHome.class);
UserManager user = userHome.create();
// Delegate a UserManager to start a JTA transaction
System.out.println("\nStart global transaction...");
user.connectUserManager();
// Connect to a JDBC DataSource and add the enrolled course
System.out.println("Adding courses to database...");
user.addCourse(1, "CS310");
// Connect to a JMS destination and send a message
System.out.println("Notifying registrar queue...");
user.notifyRegistrar(1, "CS310");
// Commit the JTA transaction and release resources
Thread.sleep(1000);
System.out.println("Committing transaction...");
user.disconnectUserManager();
} catch(Exception e) {
System.err.println(e.toString());
}
}
}

FILE: jndi.properties
java.naming.factory.initial=weblogic.jndi.WLInitialContextFactory
java.naming.factory.url.pkgs=weblogic.jndi.factories:weblogic.corba.j2ee.naming.url:weblogic.corba.client.naming
java.naming.provider.url=t3://localhost:7101
java.naming.security.principal=weblogic
java.naming.security.credentials=weblogic

FILE: build.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="EJB3 Tutorial" basedir="." default="deploy">

<property name="deploy.dir" value="C:/JTAdistrib/deploy" />
<property name="sourcedir" value="${basedir}/src"/>
<property name="targetdir" value="${basedir}/build"/>
<property name="librarydir" value="${basedir}/lib"/>

<path id="libraries">
<fileset dir="${librarydir}">
<include name="*.jar"/>
</fileset>
</path>

<target name="clean">
<delete dir="${targetdir}"/>
<mkdir dir="${targetdir}"/>
</target>

<target name="compile" depends="copy-resources">
<javac srcdir="${sourcedir}"
destdir="${targetdir}"
classpathref="libraries"
debug="on">
<compilerarg value="-Xlint"/>
</javac>
</target>
<target name="copy-resources">
<copy todir="${targetdir}">
<fileset dir="${sourcedir}">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>

<target name="deploy" description="JARs the Task" depends="clean,copy-resources,compile">
<jar destfile="${deploy.dir}/JTAdis.jar">
<metainf dir="${sourcedir}/META-INF" />
<fileset dir="${targetdir}">
<include name="**/*.class" />
</fileset>
</jar>
</target>

<target name="undeploy" description="Undeploy jar from server">
<delete file="${deploy.dir}/JTAdis.jar" />
</target>

<target name="run" depends="compile">
<java classname="Client" classpathref="libraries">
<classpath path="${targetdir}"/>
<jvmarg value="-Djava.library.path=./lib"/>
</java>
</target>
</project>

2- How to setup a JMS queue with also JTA processing

FILE: ejb-jar.xml
<?xml version="1.0"?>

<!DOCTYPE ejb-jar PUBLIC
'-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN'
'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>

<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>UserManager</ejb-name>
<home>jtadistrib.UserManagerHome</home>
<remote>jtadistrib.UserManager</remote>
<ejb-class>jtadistrib.UserManagerBean</ejb-class>
<session-type>Stateful</session-type>
<transaction-type>Bean</transaction-type>
<resource-env-ref>
<resource-env-ref-name>styejbDB</resource-env-ref-name>
<resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>
<resource-env-ref>
<resource-env-ref-name>jms/RegistrarQ</resource-env-ref-name>
<resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>
</resource-env-ref>
</session>
<message-driven>
<ejb-name>RegistrarMDB</ejb-name>
<ejb-class>jtadistrib.RegistrarMDB</ejb-class>
<transaction-type>Container</transaction-type>
<message-driven-destination>
<destination-type>javax.jms.Queue</destination-type>
</message-driven-destination>
<resource-ref>
<res-ref-name>jms/QCF</res-ref-name>
<res-type>javax.jms.QueueConnectionFactory</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</message-driven>
</enterprise-beans>
</ejb-jar>

FILE: weblogic-ejb-jar.xml
<?xml version="1.0"?>
<!DOCTYPE weblogic-ejb-jar PUBLIC
'-//BEA Systems, Inc.//DTD WebLogic 6.0.0 EJB//EN'
'http://www.bea.com/servers/wls600/dtd/weblogic-ejb-jar.dtd'>

<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>UserManager</ejb-name>
<reference-descriptor>
<resource-env-description>
<res-env-ref-name>styejbDB</res-env-ref-name>
<jndi-name>styejbDB</jndi-name>
</resource-env-description>
<resource-env-description>
<res-env-ref-name>jms/RegistrarQ</res-env-ref-name>
<jndi-name>RegistrarQ</jndi-name>
</resource-env-description>
</reference-descriptor>
<jndi-name>jtadistrib/UserManagerHome</jndi-name>
</weblogic-enterprise-bean>
<weblogic-enterprise-bean>
<ejb-name>RegistrarMDB</ejb-name>
<message-driven-descriptor>
<pool>
<max-beans-in-free-pool>5</max-beans-in-free-pool>
<initial-beans-in-free-pool>1</initial-beans-in-free-pool>
</pool>
<destination-jndi-name>RegistrarQ</destination-jndi-name>
</message-driven-descriptor>
<reference-descriptor>
<resource-description>
<res-ref-name>jms/QCF</res-ref-name>
<jndi-name>ConnectionFactory</jndi-name>
</resource-description>
</reference-descriptor>
<jndi-name>RegistrarQ</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>

1- How to setup a JMS queue with also JTA processing

This note is about setting up a JMS queue… It is based on Understanding J2EE Transactions example of tinptB ‘s Blog: EJB in 21 Days: http://ejbvn.wordpress.com/ I appreciate her excellent English, which makes a soothing effect while trying to break through difficulties.

TINPTB’s work for the 16th Day includes all files that is necessary for this example but misses tha JMS setup part naturally, because it changes according to the application server you use. In addition to his work I added the home and interface files to his RegistrarMDB. You can find the JMS setup at the bottom.

Without any further aloboration, follows my solution below full and completely working with: Jdeveloper 11g(only the client not the deployment), WebLogic10.3, wlfullclient5, apache-ant-1.7.1 and mysql-essential-5.1.30-win32, mysql-connector-java-5.0.8 and Toad for MySQL 4.1 Freeware.

FILE: RegistrarHome.java
package jtadistrib;

import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;

public interface RegistrarHome extends EJBHome{
Registrar create() throws CreateException, RemoteException;
}

FILE: Registrar.java
package jtadistrib;

import java.rmi.RemoteException;

public interface Registrar extends javax.ejb.EJBObject{
}

FILE: RegistrarMDB.java
package jtadistrib;

import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.ejb.EJBException;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class RegistrarMDB implements MessageDrivenBean, MessageListener{
private MessageDrivenContext mctx =null;
public void setMessageDrivenContext(MessageDrivenContext ctx) {mctx = ctx;}
public void ejbCreate() {
System.out.println("Instance of RegistrarMDB is created...");
}
public void ejbRemove() {}

public void onMessage(Message message) {
System.out.println("RegistrarMDB.onMessage: started..");
try {
TextMessage msg = (TextMessage)message;
System.out.println("RegistrarMDB: Registrar received message: " +
msg.getText());
} catch(JMSException e) {
e.printStackTrace();
}
}
}

Thursday 21 May 2009

6-How to Develop Message-Driven Beans

Weblogic JMS setup follows:

For deploying EJB:
You first run ANT in the MDBentity directory – namely you run the build.xml
You have the output in the C:\MDBentity\deploy directory.
You select Deployments in the Domain Structure section on the left…
You select install and it goes on from there….
If you can not do this, please refere to my WLST script tha you can find in the other EJB entries
in this blog.

To define the JMS:
Select Services in the Domain Structure Section on the left…
Select messaging
Select JMS Servers
Select new Name:styejbJMS target:DefaultServer


DO NOT PLAY WITH THE PARAMETERS – Use MINIMUM CHANGES.

To define the Topic:
Select Services in the Domain Structure Section on the left…
Select messaging
Select JMS Modules
Select new
Name:OrderVerifierARS
Summary of Resources: Name:OrderVerifierTopic JNDIName:OrderVerifierTopic
SubDeployment: styejbJMS

WARNING: 1- I had some problems in running the example. It seemed as if onMessage did not work… Also, as if, I must start the MDB manually just after the DefaultServer startup??? But at the end it worked without really being aware of how it happened really. I also changed to
String connectionFactoryJndiName = "weblogic.jms.ConnectionFactory"; from the older
javax.jms.TopicConnectionFactory…

2- Playing with the console setups related to logging can be helpful in seeing more information in the logs.
The System.out.println commands in the EJBs are printed into the Running - server log which you can switch to from the Running - application log simply at the bottom right section of the Jdev.

3- There is also the monitoring options at the top of the DefaultDomain – Deployments window.
You can select your EJB and select monitoring and see its status – very useful.

The outputs of the logs follows:
Default Server LOG

<May 21, 2009 2:59:50 PM EEST> <Notice> <Stdout> <BEA-000000> <setEntityContext called>
<May 21, 2009 2:59:50 PM EEST> <Notice> <Stdout> <BEA-000000> <ejbPostCreate() called.>
<May 21, 2009 2:59:50 PM EEST> <Notice> <Stdout> <BEA-000000> <ejbCreate() called.>
<May 21, 2009 2:59:50 PM EEST> <Notice> <Stdout> <BEA-000000> <ejbStore() called.>
<May 21, 2009 2:59:51 PM EEST> <Notice> <Stdout> <BEA-000000> <ejbLoad() called.>
<May 21, 2009 2:59:51 PM EEST> <Notice> <Stdout> <BEA-000000> <ejbStore() called.>
<May 21, 2009 2:59:51 PM EEST> <Notice> <Stdout> <BEA-000000> <************ Order Information ************>
<May 21, 2009 2:59:51 PM EEST> <Notice> <Stdout> <BEA-000000> <****ARSSSSSSSSSSssssssss Order Id is : 1242907190421>
<May 21, 2009 2:59:51 PM EEST> <Notice> <Stdout> <BEA-000000> <************ Order Information Ends ************>
<May 21, 2009 2:59:56 PM EEST> <Notice> <Stdout> <BEA-000000> <ejbLoad() called.>
<May 21, 2009 2:59:56 PM EEST> <Notice> <Stdout> <BEA-000000> <ejbStore() called.>
<May 21, 2009 3:00:56 PM EEST> <Error> <JDBC> <BEA-001112> <Test "select count(*) from SYSTABLES" set up for pool "myJDBCDataSource" failed with exception: "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'testars.systables' doesn't exist".>
<May 21, 2009 3:00:56 PM EEST> <Info> <JDBC> <BEA-001128> <Connection for pool "myJDBCDataSource" closed.>
<May 21, 2009 3:00:57 PM EEST> <Info> <JDBC> <BEA-001067> <Connection for pool "myJDBCDataSource" refreshed.>


Running mdbex.jpr log
C:\Oracle\Middleware\jdk160_05\bin\javaw.exe -client -classpath C:\JDeveloper\mywork\EJB3\MDBex\classes;C:\JDeveloper\mywork\EJB3\lib\wlfullclient5.jar Client
Starting Client . . .
Looking up the JMS destination(Topic) via JNDI.
Locating connection factory.
Creating a connection and establishing a session.
Creating an order with status:Submitted
Order id 1242908873140 is created
Creating a text message with order id and publishing it.
Sleeping for 5 sec.
Now the order status is:Verified
Process exited with exit code 0.

5-How to Develop Message-Driven Beans

Files located in the src directory
FILE: Client.java
import javax.jms.*;

import javax.naming.*;

import javax.ejb.*;

import java.util.*;

import mdbex.OrderARSHome;
import mdbex.OrderARS;
import weblogic.jms.*;

public class Client {
public static void main(String[] args) {
print("Starting Client . . .");
try {
String orderVerifierJndiName = "OrderVerifierTopic"; //args[0]; mdbex/OrderVerifier
String connectionFactoryJndiName = "weblogic.jms.ConnectionFactory";
// javax.jms.TopicConnectionFactory
// javax.jms.QueueConnectionFactory
// ?weblogic.jms.ConnectionFactory
// ?weblogic.jms.XAConnectionFactory

print("Looking up the JMS destination(Topic) via JNDI.");
Context context = new InitialContext();
Topic topic = (Topic)context.lookup(orderVerifierJndiName);

print("Locating connection factory.");
TopicConnectionFactory connectionFactory =
(TopicConnectionFactory)context.lookup(connectionFactoryJndiName);
print("Creating a connection and establishing a session.");
TopicConnection connection =
connectionFactory.createTopicConnection();
TopicSession session =
connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TopicPublisher publisher = session.createPublisher(topic);

print("Creating an order with status:Submitted");
Context initialContext = new InitialContext();
Object object = initialContext.lookup("mdbex/OrderARS");
OrderARSHome orderHome =
(OrderARSHome)javax.rmi.PortableRemoteObject.narrow(object,
OrderARSHome.class);
OrderARS order = (OrderARS)orderHome.create("1", "Submitted", 100);
String orderId = order.getOrderId();
print("Order id " + orderId + " is created");
print("Creating a text message with order id and publishing it.");
TextMessage tm = session.createTextMessage();
tm.setText(orderId);
publisher.publish(tm);

print("Sleeping for 5 sec.");
Thread.sleep(5000);
print("Now the order status is:" + order.getStatus());
} catch (Exception ex) {
System.err.println(ex);
ex.printStackTrace();
}
}

static void print(String s) {
System.out.println(s);
}

}

FILE: jndi.properties
java.naming.factory.initial=weblogic.jndi.WLInitialContextFactory
java.naming.factory.url.pkgs=weblogic.jndi.factories:weblogic.corba.j2ee.naming.url:weblogic.corba.client.naming
java.naming.provider.url=t3://localhost:7101
java.naming.security.principal=weblogic
java.naming.security.credentials=weblogic

Located in the MDBentity library( ../src)
FILE: build.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="EJB3 Tutorial" basedir="." default="deploy">

<property name="deploy.dir" value="C:/MDBentity/deploy" />
<property name="sourcedir" value="${basedir}/src"/>
<property name="targetdir" value="${basedir}/build"/>
<property name="librarydir" value="${basedir}/lib"/>

<path id="libraries">
<fileset dir="${librarydir}">
<include name="*.jar"/>
</fileset>
</path>

<target name="clean">
<delete dir="${targetdir}"/>
<mkdir dir="${targetdir}"/>
</target>

<target name="compile" depends="copy-resources">
<javac srcdir="${sourcedir}"
destdir="${targetdir}"
classpathref="libraries"
debug="on">
<compilerarg value="-Xlint"/>
</javac>
</target>
<target name="copy-resources">
<copy todir="${targetdir}">
<fileset dir="${sourcedir}">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>

<target name="deploy" description="JARs the Task" depends="clean,copy-resources,compile">
<jar destfile="${deploy.dir}/MDBent.jar">
<metainf dir="${sourcedir}/META-INF" />
<fileset dir="${targetdir}">
<include name="**/*.class" />
</fileset>
</jar>
</target>

<target name="undeploy" description="Undeploy jar from server">
<delete file="${deploy.dir}/MDBent.jar" />
</target>

<target name="run" depends="compile">
<java classname="Client" classpathref="libraries">
<classpath path="${targetdir}"/>
<jvmarg value="-Djava.library.path=./lib"/>
</java>
</target>
</project>


4-How to Develop Message-Driven Beans

XML files locates in the src/META-INF directory;
FILE: ejb-jar.xml

<!DOCTYPE ejb-jar PUBLIC
"-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN"
"http://java.sun.com/dtd/ejb-jar_2_0.dtd">

<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>OrderARSEJB</ejb-name>
<home>mdbex.OrderARSHome</home>
<remote>mdbex.OrderARS</remote>
<ejb-class>mdbex.OrderARSEJB</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>OrderARS</abstract-schema-name>
<cmp-field>
<field-name>orderId</field-name>
</cmp-field>
<cmp-field>
<field-name>studentId</field-name>
</cmp-field>
<cmp-field>
<field-name>orderDate</field-name>
</cmp-field>
<cmp-field>
<field-name>status</field-name>
</cmp-field>
<cmp-field>
<field-name>amount</field-name>
</cmp-field>
<primkey-field>orderId</primkey-field>
<query>
<query-method>
<method-name>findByStatus</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>
<![CDATA[SELECT OBJECT(o) FROM OrderARS AS o
WHERE o.status = ?1]]>
</ejb-ql>
</query>
<query>
<query-method>
<method-name>ejbSelectAllOrderAmounts</method-name>
<method-params>
</method-params>
</query-method>
<ejb-ql>
<![CDATA[SELECT o.amount FROM OrderARS AS o
WHERE o.orderId IS NOT NULL]]>
</ejb-ql>
</query>
</entity>
<message-driven>
<ejb-name>OrderVerifierMDB</ejb-name>
<ejb-class>mdbex.OrderVerifierMDB</ejb-class>
<transaction-type>Container</transaction-type>
<message-driven-destination>
<destination-type>javax.jms.Topic</destination-type>
<subscription-durability>NonDurable</subscription-durability>
</message-driven-destination>
</message-driven>
</enterprise-beans>
</ejb-jar>

FILE: weblogic-ejb-jar.xml
<?xml version="1.0"?>
<!DOCTYPE weblogic-ejb-jar PUBLIC
'-//BEA Systems, Inc.//DTD WebLogic 7.0.0 EJB//EN'
'http://www.bea.com/servers/wls700/dtd/weblogic-ejb-jar.dtd'>
<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>OrderARSEJB</ejb-name>
<entity-descriptor>

<persistence>
<persistence-use>
<type-identifier>WebLogic_CMP_RDBMS</type-identifier>
<type-version>6.0</type-version>
<type-storage>META-INF/weblogic-cmp-rdbms-jar.xml</type-storage>
</persistence-use>
</persistence>

</entity-descriptor>
<jndi-name>mdbex/OrderARS</jndi-name>
</weblogic-enterprise-bean>
<weblogic-enterprise-bean>
<ejb-name>OrderVerifierMDB</ejb-name>
<message-driven-descriptor>
<pool>
<max-beans-in-free-pool>20</max-beans-in-free-pool>
<initial-beans-in-free-pool>5</initial-beans-in-free-pool>
</pool>
<destination-jndi-name>OrderVerifierTopic</destination-jndi-name>
</message-driven-descriptor>
<jndi-name>mdbex/OrderVerifier</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>

FILE: weblogic-rdbms-jar.xml
<!DOCTYPE weblogic-rdbms-jar PUBLIC
'-//BEA Systems, Inc.//DTD WebLogic 7.0.0 EJB RDBMS Persistence//EN'
'http://www.bea.com/servers/wls700/dtd/weblogic-rdbms20-persistence-700.dtd'>
<weblogic-rdbms-jar>
<weblogic-rdbms-bean>
<ejb-name>OrderARSEJB</ejb-name>
<data-source-name>styejbDB</data-source-name>
<table-map>
<table-name>orders</table-name>
<field-map>
<cmp-field>orderId</cmp-field>
<dbms-column>order_id</dbms-column>
</field-map>
<field-map>
<cmp-field>studentId</cmp-field>
<dbms-column>student_id</dbms-column>
</field-map>
<field-map>
<cmp-field>orderDate</cmp-field>
<dbms-column>order_date</dbms-column>
</field-map>
<field-map>
<cmp-field>status</cmp-field>
<dbms-column>status</dbms-column>
</field-map>
<field-map>
<cmp-field>amount</cmp-field>
<dbms-column>amount</dbms-column>
</field-map>
</table-map>
</weblogic-rdbms-bean>
</weblogic-rdbms-jar>

3-How to Develop Message-Driven Beans

Files located in the package src/mdbex;
FILE : OrderVerifierHome.java
package mdbex;

import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;

public interface OrderVerifierHome extends EJBHome{
OrderVerifier create() throws CreateException, RemoteException;
}

FILE: OrderVerifier.java
package mdbex;

import java.rmi.RemoteException;

public interface OrderVerifier extends javax.ejb.EJBObject{
}

FILE: OrderVerifierMDB.java
package mdbex;

import java.util.*;
import java.io.*;
import java.rmi.*;
import javax.naming.*;
import javax.ejb.*;

import javax.jms.MessageListener;

import javax.ejb.CreateException;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import javax.naming.InitialContext;
import javax.naming.NamingException;

public class OrderVerifierMDB implements MessageDrivenBean, MessageListener
{

private MessageDrivenContext mdbContext;

/**
* this method is invoked by the container. it gives the MDB instance a reference to its context.
* this can be empty also.
* @param ctx MessageDrivenContext for this instance
*/
public void setMessageDrivenContext(MessageDrivenContext ctx) {
mdbContext = ctx;
}

/**
* @exception javax.ejb.CreateException if there is
* a communications or systems failure
*/
public void ejbCreate () throws CreateException {
System.out.println("****ARSSSSSSSSSSssssssss********");
}

/**
*/
public void ejbRemove() {
mdbContext = null;
}

// Implementation of MessageListener
/**
*@param msg The Message from the JMS-Server
*/
public void onMessage(Message msg) {
TextMessage orderMessage = (TextMessage) msg;
try {
String orderId = orderMessage.getText();

System.out.println("************ Order Information ************");
System.out.println("****ARSSSSSSSSSSssssssss Order Id is : "+orderId);
System.out.println("************ Order Information Ends ************");
System.out.println();

try {
System.out.println("Creating an order with status:Submitted");
Context initialContext = new InitialContext();
Object object = initialContext.lookup("mdbex/OrderARS");
OrderARSHome orderHome =
(OrderARSHome)javax.rmi.PortableRemoteObject.narrow(object,
OrderARSHome.class);
// OrderARS order = (OrderARS)orderHome.create("1", "Submitted", 100);
OrderARS order = orderHome.findByPrimaryKey(orderId);
order.setStatus("Verified");

} catch (Exception ex) {
System.err.println(ex);
ex.printStackTrace();
}
}
catch(JMSException ex) {
ex.printStackTrace();
}
}

//
// Implementation of MessageListener
/////
}

2-How to Develop Message-Driven Beans

Files located in the package src/mdbex:
FILE : OrderARSHome.java
package mdbex;

import java.util.*;
import java.rmi.*;
import javax.ejb.*;

public interface OrderARSHome extends EJBHome {
/* Create methods */
public OrderARS create(String studentId,
String status, double amount) throws CreateException, RemoteException;
/* Finder methods */
public OrderARS findByPrimaryKey(String key)
throws FinderException, RemoteException;
public Collection findByStatus(String status)
throws FinderException, RemoteException;
/* Home methods */
public double getTotalAmountOfAllOrders()
throws FinderException, RemoteException;
}

FILE: OrderARS.java
package mdbex;

import java.rmi.*;
import javax.ejb.*;

public interface OrderARS extends EJBObject {
public String getOrderId()
throws RemoteException;
public String getStudentId()
throws RemoteException;
public void setStudentId(String studentId)
throws RemoteException;
public double getAmount()
throws RemoteException;
public void setAmount(double amount)
throws RemoteException;
public java.sql.Timestamp getOrderDate()
throws RemoteException;
public void setOrderDate(java.sql.Timestamp date)
throws RemoteException;
public String getStatus()
throws RemoteException;
public void setStatus(String status)
throws RemoteException;
}

FILE: OrderARSEJB.java
package mdbex;

import java.util.*;
import java.io.*;
import java.rmi.*;
import javax.naming.*;
import javax.ejb.*;

public abstract class OrderARSEJB implements EntityBean
{
protected EntityContext ctx;
public abstract String getOrderId();
public abstract void setOrderId(String orderId);
public abstract String getStudentId();
public abstract void setStudentId(String studentid);
public abstract java.sql.Timestamp getOrderDate();
public abstract void setOrderDate(java.sql.Timestamp timestamp);
public abstract String getStatus();
public abstract void setStatus(String status);
public abstract double getAmount();
public abstract void setAmount(double amount);
/* Callback methods */
public void setEntityContext(EntityContext ctx) {
print("setEntityContext called");
this.ctx = ctx;
}
public void unsetEntityContext() {
print("unsetEntityContext called.\n");
this.ctx = null;
}
public void ejbActivate() {
print("ejbActivate() called.\n");
}
public void ejbPassivate() {
print("ejbPassivate() called.\n");
}
public void ejbStore() {
print("ejbStore() called.\n");
}
public void ejbLoad() {
print("ejbLoad() called.\n");
}
public void ejbRemove() throws RemoveException {
print("ejbRemove() called.\n");
}
public String ejbCreate( String studentId,
String status, double amount) throws CreateException {
print("ejbCreate() called.\n");
String orderId = getUniqueId();
setOrderId(orderId);
setStudentId(studentId);
setStatus(status);
setAmount(amount);
setOrderDate(new java.sql.Timestamp(System.currentTimeMillis()));
return null;
}
public void ejbPostCreate(String studentId,
String courseId, double amount) throws CreateException {
print("ejbPostCreate() called.\n");
}
/* Home methods */
public double ejbHomeGetTotalAmountOfAllOrders()
throws FinderException {
double totalAmount = 0.0;
Collection col = ejbSelectAllOrderAmounts();
Enumeration amounts=Collections.enumeration(col);
while( amounts.hasMoreElements() ) {
Double amount= (Double)amounts.nextElement();
totalAmount += amount.doubleValue();
}
return totalAmount;
}
/* select methods. */
public abstract Collection ejbSelectAllOrderAmounts()
throws FinderException ;

void print(String s) {
System.out.println(s);
}
String getUniqueId(){
return new Long(System.currentTimeMillis()).toString();
}
}

1-How to Develop Message-Driven Beans



This article is about how I managed to build MDB Beans using the Developing Message-Driven Beans example of tinptB ‘s Blog: EJB in 21 Days: http://ejbvn.wordpress.com/ I appreciate her excellent English, which makes a soothing effect while trying to break through difficulties.

TINPTB’s work for the 14th Day misses a number of items which he did not even mention. It misses the Order bean of which name must be changed to OrderXXX because it gets mixed with a key word. It misses the jndi.properties as in te previous examples. It misses the OrderVerifierMDB completely although TINPTB describes it throughly. The procedures to setup the JMS and Topic belong to an older version of WebLogic. I will provide the data to setup WebLogic 10.3. I will also provide the ANT task to create the EJBs to be deployed. Please feel free to contact me at arsaral (at) yahoo.com for further assistance.

Without any further aloboration, follows my solution below full and completely working with: Jdeveloper 11g – 11.1.1.0.2 (only the client not the deployment), WebLogic10.3, wlfullclient5, apache-ant-1.7.1 and mysql-essential-5.1.30-win32, mysql-connector-java-5.0.8 and Toad for MySQL 4.1 Freeware.

The directories and files:

MDBentity includes
Src…………..lib………………..deploy………build.xml
Mdbex……… wlfullclient5.jar…. MDBent.jar
META-INF
Client.java
Jndi.properties

Mdbex includes
OrderARSXXX.java
OrderVerifierXXX.java
(XXX is a wildcard)

META-INF includes
Ejb-jar.xml
Weblogic-ejb-jar.xml
Weblogic-cmp-rdbms-jar.xml

Tuesday 12 May 2009

8-How to Develop Container-Managed-Relationships


Unable to deploy EJB: OrderARSLineItemEJB from CMRent.jar:

[EJB:011076]Unable to deploy the EJB 'OrderARSLineItemEJB' because the database
table 'orderlineitems' is not accessible. Please ensure that this table exists a
nd is accessible.

This killed me.. I had put an extra ‘ ‘ before the name of my MySQL table orders…
………………………………………..
[EJB:011019]While reading META-INF/weblogic-cmp-rdbms-jar.xml, the persistence l
ayer of the Entity EJB failed to deploy. The error was:
Error in descriptor line 50: Error parsing file at line: 50 column: 25. org.xm
l.sax.SAXParseException: The content of element type "weblogic-rdbms-bean" must
match "(ejb-name,data-source-name,table-map+,field-group*,relationship-caching*,
weblogic-query*,delay-database-insert-until?,use-select-for-update?,lock-order?,
automatic-key-generation?,check-exists-on-method?)"..

You get this message if you play with certain field and delete them from
weblogic-cmp-rdbms-jar.xml
……………………………………..
C:\CMRentity>ant run
Buildfile: build.xml

copy-resources:

compile:

run:
[java] JVM args ignored when same JVM is used.
[java] Starting Client . . .

[java] Looking up the order home via JNDI.

[java] Created a new order:1242066381187 .

[java] Adding some line items to the order.

[java] Retrieving line items of the order.

[java] java.rmi.RemoteException: BEA1-001045C3303C9E472B1E; nested exceptio
n is:
[java] javax.transaction.HeuristicMixedException: (weblogic.jdbc.wrappe
r.JTSXAResourceImpl, HeuristicHazard, (javax.transaction.xa.XAException: Connect
ion has been administratively destroyed. Reconnect.))
...
The first time I ran the final program it gave these messages. When I ran it again
İt was OK, it may be related to two extra records in the ordrs table which did not have any
Line items???
………………………………………………….
C:\CMRentity>ant run
Buildfile: build.xml

copy-resources:

compile:

run:
[java] JVM args ignored when same JVM is used.
[java] Starting Client . . .

[java] Looking up the order home via JNDI.

[java] Created a new order:1242067364140 .

[java] Adding some line items to the order.

[java] Retrieving line items of the order.

[java] Item id:1242067364578 Course id:3 Fee:300.0
[java] Item id:1242067364312 Course id:1 Fee:200.0
[java] Item id:1242067364484 Course id:2 Fee:300.0
[java] Removing order:1242067364140 .


BUILD SUCCESSFUL
Total time: 8 seconds
C:\CMRentity>
This was the final output of my program, an instance of TINTPB’s.
My appreciations go to her.

7-How to Develop Container-Managed-Relationships

Some problems that I have met during this task follows together with their solutions:
…………………………………………………
Unable to deploy EJB: OrderARSEJB from CMPent.jar:

[EJB:011028]The DataSource with the JNDI name: myJDBCDataSource could not be loc
ated. Please ensure that the DataSource has been deployed successfully and that
the JNDI name in your EJB Deployment descriptor is correct.

You have to put the JNDI name in the place for Data-Source-Name in weblogic-rdbms-jar.xml
………………………………..
[java] JVM args ignored when same JVM is used.
[java] Starting Client . . .

[java] Looking up the order home via JNDI.

[java] javax.naming.NoInitialContextException: Need to specify class name i
n environment or system property, or as an applet parameter, or in an applicatio
n resource file: java.naming.factory.initial

I had forgotten to create the jndi.properties file.
…………………………………………
compile:
[javac] Compiling 10 source files to C:\CMRentity\build
[javac] Note: C:\CMRentity\src\cmrex\OrderEJB.java uses unchecked or unsafe
operations.
[javac] Note: Recompile with -Xlint:unchecked for details.
Solution is below:

<target name="compile" depends="copy-resources">
<javac srcdir="${sourcedir}"
destdir="${targetdir}"
classpathref="libraries"
source="1.5"
debug="on">
<compilerarg value="-Xlint"/>
</javac>
</target>
……………………………………………….
Unable to deploy EJB: OrderLineItemEJB from CMRent.jar:

[EJB:011019]While reading META-INF/weblogic-cmp-rdbms-jar.xml, the persistence l
ayer of the Entity EJB failed to deploy. The error was:
Error in descriptor line 38: Error parsing file at line: 38 column: 21. org.xm
l.sax.SAXParseException: Element type "field-name" must be declared..

I made a mistake in weblogic-rdbms-bean.xml
Solution is below:
<field-map>
<cmp-field>fee</cmp-field>
<dbms-column>fee</dbms-column>
</field-map>
</table-map>
</weblogic-rdbms-bean>
………………………………………….
Unable to deploy EJB: OrderLineItemEJB from CMRent.jar:

[EJB:011017]Error while reading 'META-INF/weblogic-cmp-rdbms-jar.xml'. The error
was:


There are 1 nested errors:

Query:
EJB Name: OrderEJB
Method Name: findByPrimaryKey
Parameter Types: (java.lang.String)


SELECT OBJECT(bean) FROM Order =>> AS <<= bean WHERE ( bean.orderId = 1 )


EJB QL Parser Error.

32: unexpected token: AS

Note: 'Order' is a Reserved Keyword.

Error in FROM clause.

Check that the Range Variable Declarations and the Collection Member Declaratio
ns are correct
and that no EJB QL keywords are being used as:

...
The keyword ORDER gets mixed with the EJB name, I changed all Order instances to OrderARS.

6-How to Develop Container-Managed-Relationships

FILE jndi.properties
java.naming.factory.initial=weblogic.jndi.WLInitialContextFactory
java.naming.factory.url.pkgs=weblogic.jndi.factories:weblogic.corba.j2ee.naming.url:weblogic.corba.client.naming
java.naming.provider.url=t3://localhost:7101
java.naming.security.principal=weblogic
java.naming.security.credentials=weblogic

FILE MySQL DDLs
CREATE TABLE `orders` (
`order_id` varchar(64) DEFAULT NULL,
`student_id` varchar(64) DEFAULT NULL,
`order_date` date DEFAULT NULL,
`status` varchar(64) DEFAULT NULL,
`amount` double(12,2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


CREATE TABLE `orderlineitems` (
`orderLineItem_id` varchar(64) DEFAULT NULL,
`course_id` varchar(64) DEFAULT NULL,
`fee` double(12,2) DEFAULT NULL,
`order_id` varchar(64) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

FILE build.xml for ANT
<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="EJB3 Tutorial" basedir="." default="deploy">

<property name="deploy.dir" value="C:/CMRentity/deploy" />
<property name="sourcedir" value="${basedir}/src"/>
<property name="targetdir" value="${basedir}/build"/>
<property name="librarydir" value="${basedir}/lib"/>

<path id="libraries">
<fileset dir="${librarydir}">
<include name="*.jar"/>
</fileset>
</path>

<target name="clean">
<delete dir="${targetdir}"/>
<mkdir dir="${targetdir}"/>
</target>

<target name="compile" depends="copy-resources">
<javac srcdir="${sourcedir}"
destdir="${targetdir}"
classpathref="libraries"
source="1.5"
debug="on">
<compilerarg value="-Xlint"/>
</javac>
</target>
<target name="copy-resources">
<copy todir="${targetdir}">
<fileset dir="${sourcedir}">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>

<target name="deploy" description="JARs the Task" depends="clean,copy-resources,compile">
<jar destfile="${deploy.dir}/CMRent.jar">
<metainf dir="${sourcedir}/META-INF" />
<fileset dir="${targetdir}">
<include name="**/*.class" />
</fileset>
</jar>
</target>

<target name="undeploy" description="Undeploy jar from server">
<delete file="${deploy.dir}/CMRent.jar" />
</target>

<target name="run" depends="compile">
<java classname="Client" classpathref="libraries">
<classpath path="${targetdir}"/>
<jvmarg value="-Djava.library.path=./lib"/>
</java>
</target>
</project>

Please refer to
http://tekne-techne.blogspot.com/2009/05/5-how-to-develop-container-managed.html
for the WLST Data source definition commands.
You can also find the FILE WebLogic Default Server config file and its –jdbc.xml extention
there.

For deployment to WebLogic:http://tekne-techne.blogspot.com/2009/05/6-how-to-develop-container-managed.html

5-How to Develop Container-Managed-Relationships

FILE ejb-jar.xml
<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC
'-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN'
'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>OrderARSEJB</ejb-name>
<home>cmrex.OrderARSHome</home>
<remote>cmrex.OrderARS</remote>
<local-home>cmrex.OrderARSLocalHome</local-home>
<local>cmrex.OrderARSLocal</local>
<ejb-class>cmrex.OrderARSEJB</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>OrderARS</abstract-schema-name>
<cmp-field>
<field-name>orderId</field-name>
</cmp-field>
<cmp-field>
<field-name>studentId</field-name>
</cmp-field>
<cmp-field>
<field-name>orderDate</field-name>
</cmp-field>
<cmp-field>
<field-name>status</field-name>
</cmp-field>
<cmp-field>
<field-name>amount</field-name>
</cmp-field>
<primkey-field>orderId</primkey-field>
</entity>
<entity>
<ejb-name>OrderARSLineItemEJB</ejb-name>
<local-home>cmrex.OrderARSLineItemLocalHome</local-home>
<local>cmrex.OrderARSLineItemLocal</local>
<ejb-class>cmrex.OrderARSLineItemEJB</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>OrderARSLineitem</abstract-schema-name>
<cmp-field>
<field-name>orderLineItemId</field-name>
</cmp-field>
<cmp-field>
<field-name>courseId</field-name>
</cmp-field>
<cmp-field>
<field-name>fee</field-name>
</cmp-field>
<primkey-field>orderLineItemId</primkey-field>
</entity>
</enterprise-beans>
<relationships>
<ejb-relation>
<ejb-relation-name>Order-LineItems</ejb-relation-name>
<ejb-relationship-role>
<ejb-relationship-role-name>Order-has-lineitems</ejb-relationship-role-name>
<multiplicity>One</multiplicity>
<relationship-role-source>
<ejb-name>OrderARSEJB</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>lineItems</cmr-field-name>
<cmr-field-type>java.util.Collection</cmr-field-type>
</cmr-field>
</ejb-relationship-role>
<ejb-relationship-role>
<ejb-relationship-role-name>lineItem-belongsto-Order </ejb-relationship-role-name>
<multiplicity>Many</multiplicity>
<cascade-delete/>
<relationship-role-source>
<ejb-name>OrderARSLineItemEJB</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>order</cmr-field-name>
</cmr-field>
</ejb-relationship-role>
</ejb-relation>
</relationships>
</ejb-jar>
*******************************************************************************

FILE weblogic-ejb-jar.xml
<?xml version="1.0"?>
<!DOCTYPE weblogic-ejb-jar PUBLIC
'-//BEA Systems, Inc.//DTD WebLogic 7.0.0 EJB//EN'
'http://www.bea.com/servers/wls700/dtd/weblogic-ejb-jar.dtd'>
<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>OrderARSEJB</ejb-name>
<entity-descriptor>
<persistence>
<persistence-use>
<type-identifier>WebLogic_CMP_RDBMS</type-identifier>
<type-version>6.0</type-version>
<type-storage>META-INF/weblogic-cmp-rdbms-jar.xml</type-storage>
</persistence-use>
</persistence>
</entity-descriptor>
<jndi-name>cmrex/OrderARS</jndi-name>
<local-jndi-name>cmrex/OrderARSLocal</local-jndi-name>
</weblogic-enterprise-bean>
<weblogic-enterprise-bean>
<ejb-name>OrderARSLineItemEJB</ejb-name>
<entity-descriptor>
<persistence>
<persistence-use>
<type-identifier>WebLogic_CMP_RDBMS</type-identifier>
<type-version>6.0</type-version>
<type-storage>META-INF/weblogic-cmp-rdbms-jar.xml</type-storage>
</persistence-use>
</persistence>
</entity-descriptor>
<local-jndi-name>cmrex/OrderARSLineItemLocal</local-jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
************************************************************************************
FILE weblogic-rdbms-jar.xml
<!DOCTYPE weblogic-rdbms-jar PUBLIC
'-//BEA Systems, Inc.//DTD WebLogic 7.0.0 EJB RDBMS Persistence//EN'
'http://www.bea.com/servers/wls700/dtd/weblogic-rdbms20-persistence-700.dtd'>
<weblogic-rdbms-jar>
<weblogic-rdbms-bean>
<ejb-name>OrderARSEJB</ejb-name>
<data-source-name>styejbDB</data-source-name>
<table-map>
<table-name>orders</table-name>
<field-map>
<cmp-field>orderId</cmp-field>
<dbms-column>order_id</dbms-column>
</field-map>
<field-map>
<cmp-field>studentId</cmp-field>
<dbms-column>student_id</dbms-column>
</field-map>
<field-map>
<cmp-field>orderDate</cmp-field>
<dbms-column>order_date</dbms-column>
</field-map>
<field-map>
<cmp-field>status</cmp-field>
<dbms-column>status</dbms-column>
</field-map>
<field-map>
<cmp-field>amount</cmp-field>
<dbms-column>amount</dbms-column>
</field-map>
</table-map>
</weblogic-rdbms-bean>
<weblogic-rdbms-bean>
<ejb-name>OrderARSLineItemEJB</ejb-name>
<data-source-name>styejbDB</data-source-name>
<table-map>
<table-name>orderlineitems</table-name>
<field-map>
<cmp-field>orderLineItemId</cmp-field>
<dbms-column>orderLineItem_id</dbms-column>
</field-map>
<field-map>
<cmp-field>courseId</cmp-field>
<dbms-column>course_id</dbms-column>
</field-map>
<field-map>
<cmp-field>fee</cmp-field>
<dbms-column>fee</dbms-column>
</field-map>
</table-map>
</weblogic-rdbms-bean>
<weblogic-rdbms-relation>
<relation-name>Order-LineItems</relation-name>
<weblogic-relationship-role>
<relationship-role-name>
lineItem-belongsto-Order
</relationship-role-name>
<relationship-role-map>
<column-map>
<foreign-key-column>order_id</foreign-key-column>
<key-column> order_id </key-column>
</column-map>
</relationship-role-map>
<db-cascade-delete/>
</weblogic-relationship-role>
</weblogic-rdbms-relation>
</weblogic-rdbms-jar>

4-How to Develop Container-Managed-Relationships

FILE Client.java

import cmrex.ClientLineItem;
import cmrex.OrderARS;
import cmrex.OrderARSHome;

import java.util.*;
import javax.naming.*;
import javax.ejb.*;
public class Client {
public static void main(String[] args) {
print("Starting Client . . .\n");
Context initialContext = null;
OrderARSHome orderHome = null;
OrderARS order = null;
try {
print("Looking up the order home via JNDI.\n");
initialContext = new InitialContext();
Object object = initialContext.lookup("cmrex/OrderARS");
orderHome = (OrderARSHome)
javax.rmi.PortableRemoteObject.narrow(object,OrderARSHome.class);
object = (OrderARS)orderHome.create("1", "Submitted", 100);
order = (OrderARS)
javax.rmi.PortableRemoteObject.narrow(object,OrderARS.class);
String orderId = order.getOrderId();
print("Created a new order:" + orderId + " .\n");
print("Adding some line items to the order.\n");
order.addLineItem("1", 200);
order.addLineItem("2", 300);
order.addLineItem("3", 300);
print("Retrieving line items of the order.\n");
Collection collection = order.getOrderLineItems();
Iterator it = collection.iterator();
while (it.hasNext()) {
ClientLineItem item =(ClientLineItem)javax.rmi.PortableRemoteObject.narrow
(it.next(), ClientLineItem.class);
print("Item id:" + item.getOrderLineItemId() +
" Course id:" + item.getCourseId() +
" Fee:" + item.getFee()
);
}
print("Removing order:" + orderId + " .\n");
order.remove();
} catch ( Exception e) {
e.printStackTrace();
}
}
static void print(String s) {
System.out.println(s);
}
}

3-How to Develop Container-Managed-Relationships

FILE OrderARSLineItemLocalHome.java
package cmrex;

import javax.ejb.*;
import java.util.*;
public interface OrderARSLineItemLocalHome extends EJBLocalHome {
public OrderARSLineItemLocal create(String orderLineItemId,
String courseId, double fee) throws CreateException;
public OrderARSLineItemLocal findByPrimaryKey(String key)
throws FinderException;
}

FILE OrderARSLineItemLocal.java

package cmrex;

import weblogic.ejb.EJBLocalObject;

public interface OrderARSLineItemLocal extends javax.ejb.EJBLocalObject{
public String getOrderLineItemId();
public String getCourseId();
public void setCourseId(String courseId);
public double getFee();
public void setFee(double fee);
public OrderARSLocal getOrder();
public void setOrder(OrderARSLocal o);
}

FILE OrderARSLineItemEJB.java
package cmrex;

import javax.naming.*;
import javax.ejb.*;
import java.util.*;
public abstract class OrderARSLineItemEJB implements EntityBean {
protected EntityContext ctx;
/* get and set methods for cmp fields */
public OrderARSLineItemEJB() {}
public abstract String getOrderLineItemId();
public abstract void setOrderLineItemId(String id);
public abstract String getCourseId();
public abstract void setCourseId(String courseId);
public abstract double getFee();
public abstract void setFee(double fee);
/* get and set methods for relationship fields */
public abstract OrderARSLocal getOrder();
public abstract void setOrder(OrderARSLocal order);
/* Callback methods */
public void setEntityContext(EntityContext ctx) {
this.ctx = ctx;
}
public void unsetEntityContext() {
this.ctx = null;
}
public void ejbActivate() {}
public void ejbPassivate() {}
public void ejbStore() {}
public void ejbLoad() {}
public String ejbCreate(String orderLineItemId, String courseId,
double fee) throws CreateException {
setOrderLineItemId(orderLineItemId);
setCourseId(courseId);
setFee(fee);
print("Creating OrderLineItem id:" + orderLineItemId );
return null;
}
public void ejbPostCreate(String orderLineItemId, String courseId,
double fee) throws CreateException {}
public void ejbRemove() {
print("Removing OrderLineItem id:" + (String)ctx.getPrimaryKey() );
}
void print(String s) {
System.out.println(s);
}
}

FILE ClientLineItem
package cmrex;

public class ClientLineItem implements java.io.Serializable {
private String orderLineItemId;
private String courseId;
private double fee;
public ClientLineItem(String orderLineItemId,
String courseId, double fee) {
this.orderLineItemId = orderLineItemId;
this.courseId = courseId;
this.fee = fee;
}
public String getOrderLineItemId() {
return orderLineItemId ;
}
public double getFee() {
return fee;
}
public String getCourseId() {
return courseId;
}
}

2-How to Develop Container-Managed-Relationships

FILE OrderARSLocalHome.java
package cmrex;

import java.util.*;
import java.rmi.*;
import javax.ejb.*;
public interface OrderARSLocalHome extends EJBLocalHome {
/* Create methods */
public OrderARSLocal create(String studentId,
String status, double amount) throws CreateException;
/* Finder methods */
public OrderARSLocal findByPrimaryKey(String key)
throws FinderException;
}

FILE OrderARSLocal.java
package cmrex;

import java.util.*;
import java.rmi.*;
import javax.ejb.*;
public interface OrderARSLocal extends EJBLocalObject {
public String getOrderId();
public String getStudentId();
public void setStudentId(String studentId);
public double getAmount();
public void setAmount(double amount);
public java.sql.Timestamp getOrderDate();
public void setOrderDate(java.sql.Timestamp date);
public String getStatus();
public void setStatus(String status);
public void addLineItem(String courseId, double fee);
public Collection getOrderLineItems();
}
**********************************************************
FILE OrderARSEJB.java
package cmrex;

import java.util.*;
import java.io.*;
import java.rmi.*;
import javax.naming.*;
import javax.ejb.*;
public abstract class OrderARSEJB implements EntityBean {
protected EntityContext ctx;
/* get and set methods for cmp fields */
public abstract String getOrderId();
public abstract void setOrderId(String orderId);
public abstract String getStudentId();
public abstract void setStudentId(String studentid);
public abstract java.sql.Timestamp getOrderDate();
public abstract void setOrderDate(java.sql.Timestamp timestamp);
public abstract String getStatus();
public abstract void setStatus(String status);
public abstract double getAmount();
public abstract void setAmount(double amount);
/* get and set methods for relationship fields */
public abstract Collection getLineItems();
public abstract void setLineItems(Collection lineItems);
/* business methods */
public void addLineItem(String courseId, double fee) {
try {
Context ctx = new InitialContext();
OrderARSLineItemLocalHome home = (OrderARSLineItemLocalHome)
ctx.lookup("cmrex/OrderARSLineItemLocal");
String lineItemId = getUniqueId();
OrderARSLineItemLocal item =
home.create(lineItemId, courseId, fee) ;
getLineItems().add(item);
} catch(Exception e) {
throw new EJBException("Error adding line item:", e);
}
}
public Collection getOrderLineItems() {
Vector clientLineItems = new Vector();
Collection lineitems = getLineItems();
java.util.Iterator iterator = lineitems.iterator();
ClientLineItem item;
while (iterator.hasNext()) {
OrderARSLineItemLocal litem = (OrderARSLineItemLocal)iterator.next();
item = new ClientLineItem(litem.getOrderLineItemId(),
litem.getCourseId(), litem.getFee());
clientLineItems.add(item);
}
return clientLineItems;
}
/* Callback methods */
public void setEntityContext(EntityContext ctx) {
this.ctx = ctx;
}
public void unsetEntityContext() {
this.ctx = null;
}
public void ejbActivate() {}
public void ejbPassivate() {}
public void ejbStore() {}
public void ejbLoad() {}
public void ejbRemove() throws RemoveException {
print("Removing Order id:" + (String)ctx.getPrimaryKey() );
}
public String ejbCreate(String studentId,
String status, double amount) throws CreateException {
String orderId = getUniqueId();
setOrderId(orderId);
setStudentId(studentId);
setStatus(status);
setAmount(amount);
setOrderDate(new java.sql.Timestamp(System.currentTimeMillis()));
print("Creating Order id:" + orderId );
return null;
}
public void ejbPostCreate(String studentId,
String courseId, double amount) throws CreateException {}
String getUniqueId(){
return new Long(System.currentTimeMillis()).toString();
}
void print(String s) {
System.out.println(s);
}
}

1-How to Develop Container-Managed-Relationships

This article is about how I managed to build CMR Entity Beans using the Developing Container-Managed Relationships example of tinptB ‘s Blog: EJB in 21 Days: http://ejbvn.wordpress.com/
I appreciate her excellent English, which makes a soothing effect while trying to break through difficulties.

TINPTB’s work for the 12th Day misses some deployment descriptor scripts which she indicated with “. . . “ .
There also the name problem related to ‘order’ which is actually a key word and gets mixed. Jndi.properties is also missing in this example. Without any further aloboration, follows my solution below full and completely working with: Jdeveloper 11g(only the client not the deployment), WebLogic10.3, wlfullclient5, apache-ant-1.7.1 and mysql-essential-5.1.30-win32, mysql-connector-java-5.0.8 and Toad for MySQL 4.1 Freeware.

FILE OrderARSHome.java
package cmrex;

import java.util.*;
import java.rmi.*;
import javax.ejb.*;
public interface OrderARSHome extends EJBHome {
/* Create methods */
public OrderARS create(String studentId,
String status, double amount) throws CreateException, RemoteException;
/* Finder methods */
public OrderARS findByPrimaryKey(String key)
throws FinderException, RemoteException;
}

FILE OrderARS.java
package cmrex;

import java.util.*;
import java.rmi.*;
import javax.ejb.*;
public interface OrderARS extends EJBObject{
public String getOrderId()
throws RemoteException;
public String getStudentId()
throws RemoteException;
public void setStudentId(String studentId)
throws RemoteException;
public double getAmount()
throws RemoteException;
public void setAmount(double amount)
throws RemoteException;
public java.sql.Timestamp getOrderDate()
throws RemoteException;
public void setOrderDate(java.sql.Timestamp date)
throws RemoteException;
public String getStatus()
throws RemoteException;
public void setStatus(String status)
throws RemoteException;
public void addLineItem(String courseId, double fee)
throws RemoteException;
public Collection getOrderLineItems()
throws RemoteException;
}

Thursday 7 May 2009

SIMPLE AND COMPLETE DATA SOURCE EXAMPLE WITH WEBLOGIC

Please refer to ‘SIMPLE AND COMPLETE DATA SOURCE EXAMPLE’ at
http://tekne-techne.blogspot.com/2009/04/1-simple-and-complete-data-source.html
where I have created a simple httpServlet names Dstest and used the context.xml to access to the MySQL database from Apache Tomcat application server.

This time, I used the same httpservlets but changed the web.xml and added weblogic.xml, I also used
The datasource definition and its JNDI reference that I had created at
http://tekne-techne.blogspot.com/2009/05/5-how-to-develop-container-managed.html
You can find the jndi.properties at
http://tekne-techne.blogspot.com/2009/05/6-how-to-develop-container-managed.html

Here are web.xml and weblogic.xml files:

FILE web.xml
<?xml version = '1.0' encoding = 'windows-1254'?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">

<display-name>
Test ARS data source
</display-name>

<servlet>
<servlet-name>RequestDisplay</servlet-name>
<servlet-class>dsweb.RequestDisplay</servlet-class>
</servlet>
<servlet>
<servlet-name>DStest</servlet-name>
<servlet-class>dsweb.DStest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RequestDisplay</servlet-name>
<url-pattern>/RequestDisplay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DStest</servlet-name>
<url-pattern>/DStest</url-pattern>
</servlet-mapping>

<resource-ref>
<res-ref-name>jdbc/MySQLDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

<!--welcome-file-list>
<welcome-file>Welcome.html</welcome-file>
</welcome-file-list-->
</web-app>

FILE weblogic.xml
<?xml version='1.0' encoding='UTF-8'?>
<weblogic-web-app
xmlns="http://www.bea.com/ns/weblogic/weblogic-web-app"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-web-app
http://www.bea.com/ns/weblogic/weblogic-web-app/1.0/weblogic-web-app.xsd">

<!--!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web Application 10.0//EN"
"http://www.bea.com/servers/wls810/dtd/weblogic810-web-jar.dtd"-->
<session-descriptor></session-descriptor>
<jsp-descriptor></jsp-descriptor>
<container-descriptor></container-descriptor>
<context-root>/</context-root>
<servlet-descriptor>
<servlet-name>RequestDisplay</servlet-name>
</servlet-descriptor>
<resource-description>
<res-ref-name>jdbc/MySQLDB</res-ref-name>
<jndi-name>styejbDB</jndi-name>
</resource-description>
</weblogic-web-app>

This works, if it does not please do not hesitate to contact me at arsaral [at] yahoo.com
with your relevant data.

Wednesday 6 May 2009

6-How to Develop Container-Managed-Persistence Entity Beans

JNDI, WLST deploy related commands, ANT build.xml

FILE jndi.properties
java.naming.factory.initial=weblogic.jndi.WLInitialContextFactory
java.naming.factory.url.pkgs=weblogic.jndi.factories:weblogic.corba.j2ee.naming.url:weblogic.corba.client.naming
java.naming.provider.url=t3://localhost:7101
java.naming.security.principal=weblogic
java.naming.security.credentials=weblogic

WLST deploy related commands
connect('weblogic','weblogic','t3://localhost:7101')
deploy("CMPent","C:/CMPentity/deploy/CMPent.jar" ,"DefaultServer",securityModel="Advanced", block="true")

FILE build.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="EJB3 Tutorial" basedir="." default="deploy">

<property name="deploy.dir" value="C:/CMPentity/deploy" />
<property name="sourcedir" value="${basedir}/src"/>
<property name="targetdir" value="${basedir}/build"/>
<property name="librarydir" value="${basedir}/lib"/>

<path id="libraries">
<fileset dir="${librarydir}">
<include name="*.jar"/>
</fileset>
</path>

<target name="clean">
<delete dir="${targetdir}"/>
<mkdir dir="${targetdir}"/>
</target>

<target name="compile" depends="copy-resources">
<javac srcdir="${sourcedir}"
destdir="${targetdir}"
classpathref="libraries"
debug="on">

</javac>
</target>
<target name="copy-resources">
<copy todir="${targetdir}">
<fileset dir="${sourcedir}">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>

<target name="deploy" description="JARs the Task" depends="clean,copy-resources,compile">
<jar destfile="${deploy.dir}/CMPent.jar">
<metainf dir="${sourcedir}/META-INF" />
<fileset dir="${targetdir}">
<include name="**/*.class" />
</fileset>
</jar>
</target>

<target name="undeploy" description="Undeploy jar from server">
<delete file="${deploy.dir}/CMPent.jar" />
</target>

<target name="run" depends="compile">
<java classname="Client" classpathref="libraries">
<classpath path="${targetdir}"/>
<jvmarg value="-Djava.library.path=./lib"/>
</java>
</target>
</project>


5-How to Develop Container-Managed-Persistence Entity Beans

MySQL DDL, WLST Data source definition commands, WebLogic system config.xml files.

SCRIPT MySQL DDL for the orders table in the ‘testars’ database
create table orders (order_id varchar(64),
student_id varchar(64),
order_date Date,
status varchar(64),
amount DOUBLE PRECISION(12,2));

SCRIPT WLST Data Source definition commands
edit()
# Change these names as necessary
dsname="myJDBCDataSource"
server="DefaultServer"
cd("Servers/"+server)
target=cmo
cd("../..")
startEdit()
# start creation
print 'Creating JDBCSystemResource with name '+dsname
jdbcSR = create(dsname,"JDBCSystemResource")
theJDBCResource = jdbcSR.getJDBCResource()
theJDBCResource.setName("myJDBCDataSource")

connectionPoolParams = theJDBCResource.getJDBCConnectionPoolParams()
connectionPoolParams.setConnectionReserveTimeoutSeconds(25)
connectionPoolParams.setMaxCapacity(100)
connectionPoolParams.setTestTableName("SYSTABLES")
dsParams = theJDBCResource.getJDBCDataSourceParams()
dsParams.addJNDIName("styejbDB")

driverParams = theJDBCResource.getJDBCDriverParams()
driverParams.setUrl("jdbc:mysql://localhost:3306/testars")
driverParams.setDriverName("com.mysql.jdbc.Driver")

# driverParams.setUrl("jdbc:oracle:thin:@my-oracle-server:my-oracle-server-port:my-oracle-sid")
# driverParams.setDriverName("oracle.jdbc.driver.OracleDriver")
driverParams.setPassword("3391309")
# driverParams.setLoginDelaySeconds(60)
driverProperties = driverParams.getProperties()
proper0 = driverProperties.createProperty("user")
#proper.setName("user")
proper0.setValue("root")
proper1 = driverProperties.createProperty("DatabaseName")
#proper1.setName("DatabaseName")
proper1.setValue("jdbc:mysql://localhost:3306/testars")
jdbcSR.addTarget(target)
save()
activate(block="true")
print 'Done configuring the data source'

FILE WebLogic Default Server config file at C:\oracle\Middleware\jdeveloper\system\system11.1.1.0.31.51.88\DefaultDomain\config
The above script places it at the very bottom otomatically as:

<jdbc-system-resource>
<name>myJDBCDataSource</name>
<target>DefaultServer</target>
<descriptor-file-name>jdbc/myJDBCDataSource-9572-jdbc.xml</descriptor-file-name>
</jdbc-system-resource>
</domain>

And creates the related XXX-jdbc.xml file at
C:\oracle\Middleware\jdeveloper\system\system11.1.1.0.31.51.88\DefaultDomain\config\jdbc

FILE myJDBCDataSource-9572-jdbc.xml
<?xml version='1.0' encoding='UTF-8'?>
<jdbc-data-source xmlns="http://www.bea.com/ns/weblogic/jdbc-data-source" xmlns:sec="http://www.bea.com/ns/weblogic/90/security" xmlns:wls="http://www.bea.com/ns/weblogic/90/security/wls" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/jdbc-data-source http://www.bea.com/ns/weblogic/jdbc-data-source/1.0/jdbc-data-source.xsd">
<name>myJDBCDataSource</name>
<jdbc-driver-params>
<url>jdbc:mysql://localhost:3306/testars</url>
<driver-name>com.mysql.jdbc.Driver</driver-name>
<properties>
<property>
<name>user</name>
<value>root</value>
</property>
<property>
<name>DatabaseName</name>
<value>jdbc:mysql://localhost:3306/testars</value>
</property>
</properties>
<password-encrypted>{3DES}K0c09YjvYiI=</password-encrypted>
</jdbc-driver-params>
<jdbc-connection-pool-params>
<max-capacity>100</max-capacity>
<connection-reserve-timeout-seconds>25</connection-reserve-timeout-seconds>
<test-table-name>SYSTABLES</test-table-name>
</jdbc-connection-pool-params>
<jdbc-data-source-params>
<jndi-name>styejbDB</jndi-name>
</jdbc-data-source-params>
</jdbc-data-source>

4-How to Develop Container-Managed-Persistence Entity Beans

Deployment Descriptors

FILE ejb-jar.xml
<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC
'-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN'
'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>

<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>OrderARSEJB</ejb-name>
<home>cmpex.OrderARSHome</home>
<remote>cmpex.OrderARS</remote>
<ejb-class>cmpex.OrderARSEJB</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>OrderARS</abstract-schema-name>
<cmp-field>
<field-name>orderId</field-name>
</cmp-field>
<cmp-field>
<field-name>studentId</field-name>
</cmp-field>
<cmp-field>
<field-name>orderDate</field-name>
</cmp-field>
<cmp-field>
<field-name>status</field-name>
</cmp-field>
<cmp-field>
<field-name>amount</field-name>
</cmp-field>
<primkey-field>orderId</primkey-field>
<query>
<query-method>
<method-name>findByStatus</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>
<![CDATA[SELECT OBJECT(o) FROM OrderARS AS o
WHERE o.status = ?1]]>
</ejb-ql>
</query>
<query>
<query-method>
<method-name>ejbSelectAllOrderAmounts</method-name>
<method-params>
</method-params>
</query-method>
<ejb-ql>
<![CDATA[SELECT o.amount FROM OrderARS AS o
WHERE o.orderId IS NOT NULL]]>
</ejb-ql>
</query>
</entity>
</enterprise-beans>
</ejb-jar>

FILE weblogic-ejb.jar
<?xml version="1.0"?>
<!DOCTYPE weblogic-ejb-jar PUBLIC
'-//BEA Systems, Inc.//DTD WebLogic 7.0.0 EJB//EN'
'http://www.bea.com/servers/wls700/dtd/weblogic-ejb-jar.dtd'>

<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>OrderARSEJB</ejb-name>
<entity-descriptor>

<persistence>
<persistence-use>
<type-identifier>WebLogic_CMP_RDBMS</type-identifier>
<type-version>6.0</type-version>
<type-storage>META-INF/weblogic-cmp-rdbms-jar.xml</type-storage>
</persistence-use>
</persistence>

</entity-descriptor>
<jndi-name>cmpex/OrderARS</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>

FILE weblogic-rdbms-jar.xml
<!DOCTYPE weblogic-rdbms-jar PUBLIC
'-//BEA Systems, Inc.//DTD WebLogic 7.0.0 EJB RDBMS Persistence//EN'
'http://www.bea.com/servers/wls700/dtd/weblogic-rdbms20-persistence-700.dtd'>
<weblogic-rdbms-jar>
<weblogic-rdbms-bean>
<ejb-name>OrderARSEJB</ejb-name>
<data-source-name>styejbDB</data-source-name>
<table-map>
<table-name>orders</table-name>
<field-map>
<cmp-field>orderId</cmp-field>
<dbms-column>order_id</dbms-column>
</field-map>
<field-map>
<cmp-field>studentId</cmp-field>
<dbms-column>student_id</dbms-column>
</field-map>
<field-map>
<cmp-field>orderDate</cmp-field>
<dbms-column>order_date</dbms-column>
</field-map>
<field-map>
<cmp-field>status</cmp-field>
<dbms-column>status</dbms-column>
</field-map>
<field-map>
<cmp-field>amount</cmp-field>
<dbms-column>amount</dbms-column>
</field-map>
</table-map>
</weblogic-rdbms-bean>
</weblogic-rdbms-jar>

3-How to Develop Container-Managed-Persistence Entity Beans

Client

FILE Client.java
import cmpex.*;
import java.util.*;
import javax.naming.*;
import javax.ejb.*;

public class Client {
public static void main(String[] args) {
print("Starting Client . . .\n");
Context initialContext = null;
OrderARSHome orderHome = null;
OrderARS order = null;
try {
print("Looking up the order home via JNDI.\n");
initialContext = new InitialContext();
Object object = initialContext.lookup("cmpex/OrderARS");
orderHome =
(OrderARSHome)javax.rmi.PortableRemoteObject.narrow(object,
OrderARSHome.class);
order = (OrderARS)orderHome.create("1", "Submitted", 100);
String orderId = order.getOrderId();
print("Created a new order:" + orderId + " .\n");
print("Locating the order " + orderId +
" using findByPrimaryKey method.\n");

order = orderHome.findByPrimaryKey(orderId);
print("Locating all orders with status Submitted " +
" using findByStatus method.\n");
Collection col = orderHome.findByStatus("Submitted");
Enumeration orders = Collections.enumeration(col);

while (orders.hasMoreElements()) {
order = (OrderARS)orders.nextElement();
print("Order id:" + order.getOrderId());
}

print("Finding the total amount of all orders using \n" +
" getTotalAmountOfAllOrders home method.\n");
double totalAmount = orderHome.getTotalAmountOfAllOrders();
print("Total amount:" + totalAmount);
} catch (Exception e) {
e.printStackTrace();
}
}

static void print(String s) {
System.out.println(s);
}
}

2-How to Develop Container-Managed-Persistence Entity Beans

CMP Entity Bean files:

FILE: OrderARSHome.java
package cmpex;

import java.util.*;
import java.rmi.*;
import javax.ejb.*;

public interface OrderARSHome extends EJBHome {
/* Create methods */
public OrderARS create(String studentId,
String status, double amount) throws CreateException, RemoteException;
/* Finder methods */
public OrderARS findByPrimaryKey(String key)
throws FinderException, RemoteException;
public Collection findByStatus(String status)
throws FinderException, RemoteException;
/* Home methods */
public double getTotalAmountOfAllOrders()
throws FinderException, RemoteException;
}

FILE OrderARS.java
package cmpex;

import java.rmi.*;
import javax.ejb.*;

public interface OrderARS extends EJBObject {
public String getOrderId()
throws RemoteException;
public String getStudentId()
throws RemoteException;
public void setStudentId(String studentId)
throws RemoteException;
public double getAmount()
throws RemoteException;
public void setAmount(double amount)
throws RemoteException;
public java.sql.Timestamp getOrderDate()
throws RemoteException;
public void setOrderDate(java.sql.Timestamp date)
throws RemoteException;
public String getStatus()
throws RemoteException;
public void setStatus(String status)
throws RemoteException;
}

FILE OrderARSEJB.java
package cmpex;

import java.util.*;
import java.io.*;
import java.rmi.*;
import javax.naming.*;
import javax.ejb.*;

public abstract class OrderARSEJB implements EntityBean
{
protected EntityContext ctx;
public abstract String getOrderId();
public abstract void setOrderId(String orderId);
public abstract String getStudentId();
public abstract void setStudentId(String studentid);
public abstract java.sql.Timestamp getOrderDate();
public abstract void setOrderDate(java.sql.Timestamp timestamp);
public abstract String getStatus();
public abstract void setStatus(String status);
public abstract double getAmount();
public abstract void setAmount(double amount);
/* Callback methods */
public void setEntityContext(EntityContext ctx) {
print("setEntityContext called");
this.ctx = ctx;
}
public void unsetEntityContext() {
print("unsetEntityContext called.\n");
this.ctx = null;
}
public void ejbActivate() {
print("ejbActivate() called.\n");
}
public void ejbPassivate() {
print("ejbPassivate() called.\n");
}
public void ejbStore() {
print("ejbStore() called.\n");
}
public void ejbLoad() {
print("ejbLoad() called.\n");
}
public void ejbRemove() throws RemoveException {
print("ejbRemove() called.\n");
}
public String ejbCreate( String studentId,
String status, double amount) throws CreateException {
print("ejbCreate() called.\n");
String orderId = getUniqueId();
setOrderId(orderId);
setStudentId(studentId);
setStatus(status);
setAmount(amount);
setOrderDate(new java.sql.Timestamp(System.currentTimeMillis()));
return null;
}
public void ejbPostCreate(String studentId,
String courseId, double amount) throws CreateException {
print("ejbPostCreate() called.\n");
}
/* Home methods */
public double ejbHomeGetTotalAmountOfAllOrders()
throws FinderException {
double totalAmount = 0.0;
Collection col = ejbSelectAllOrderAmounts();
Enumeration amounts=Collections.enumeration(col);
while( amounts.hasMoreElements() ) {
Double amount= (Double)amounts.nextElement();
totalAmount += amount.doubleValue();
}
return totalAmount;
}
/* select methods. */
public abstract Collection ejbSelectAllOrderAmounts()
throws FinderException ;

void print(String s) {
System.out.println(s);
}
String getUniqueId(){
return new Long(System.currentTimeMillis()).toString();
}
}

1-How to Develop Container-Managed-Persistence Entity Beans

This article is about how I managed to build CMP Entity Beans using the Developing Container-Managed Persistence Entity Beans example of tinptB ‘s Blog: EJB in 21 Days: http://ejbvn.wordpress.com/
I appreciate her excellent English, which makes a soothing effect while trying to break through difficulties.

The difference of my work to TINPTB’s is first my work is complete and contains everything necessary to work.
TINPTB’s mission is more about teaching EJB’s thus she concentrates on providing the concise source necessary for creating them. He also provides necessary deployment descriptor scripts for both WebLogic and JBOSS. At this point her work begins to get questionable due to the different versions etc…

My solution works on Jdeveloper 11g(only the client not the deployment), WebLogic10.3, wlfullclient5, apache-ant-1.7.1 and mysql-essential-5.1.30-win32, mysql-connector-java-5.0.8 and Toad for MySQL 4.1 Freeware.

The first difficulty I had was the name used namely order is actually considered a key word by WebLogic 10.3,
Thus I had to change the CMP Entity Bean to XXXARS, ARS being the initials of my name.

Second, TINPTB does not need tomention that there has to be a jndi.properties file somewhere. He may be using the WebLogic console or some other tool instead…???

1- I created/copied the OrderXXX files as given in EJB in 21 Days. I had to change the library name(cmpex).
I also put the ejb-jar.xml, weblogic-ejb-jar.xml, weblogic-cmp-rdbms-jar.xml files into src/META-INF directory. I put the Client.java and jndi.properties also in the src directory. So, the directory structure is:
BMPex
src
Bmpex ..........................META-INF ...........Client.java ......jndi.properties
OrderHomeARS.java ....ejb-jar.xml
OrderARS.java ..............weblogic-ejb-jar.xml
OrderARSEJB.java .......weblogic-cmp-rdbms-jar.xml

At the same level with src lies:
Lib Build Deploy build.xml
wlfullclient5.jar

But also, in your weblogic domain’s lib directory, by the way I use DefaultServer;
C:\oracle\Middleware\jdeveloper\system\system11.1.1.0.31.51.88\DefaultDomain\lib
should include
mysql-connector-java-5.0.8-bin

2- I changes all names ‘order’ to ‘orderARS’. I changed ‘ch11’ lib names to ‘cmpex’. Most important,
There is a small discrepancy in the definition of
<weblogic-rdbms-jar>
<weblogic-rdbms-bean>
<ejb-name>OrderARSEJB</ejb-name>
<data-source-name>styejbDB</data-source-name>
If I give data-source-name above it asks for the JNDI name. So, I entered the JNDI name there.
3- I deployed with WLST as my WebLogic console does not work (or exist at all for some mysterious reason).

connect('weblogic','weblogic','t3://localhost:7101')

deploy("CMPent","C:/CMPentity/deploy/CMPent.jar" "DefaultServer",securityModel="Advanced", block="true")

Here, the library CMPEntity is the place where I used a build.xml file with Ant to compile and create the CMPent.jar. I also used ANT RUN command to run the client here. You may find this build file towards the end of this BLOG entries series.

If something goes wrong about the data source definition or ejb’s make sure that the JNDI tree has corresponding entries. For that, you can use
help(‘trees’)
jndi()
help(‘jndi’)
and so on…