Saturday, 19 November 2011

EJB use third party libraries

Assume the EJB project (containing the session bean, entity bean) is named ‘ejb3-jpa’, the EAR project is named ‘ejb3-ear’

An EJB session bean needs to use a third party library (e.g. Log4j)

import org.apache.log4j.Logger;

@Stateless(name="stateless")
@Local(Session.class)
public class StatelessSessionBean implements Session {

    private int result;
    private Logger logger = Logger.getLogger(StatelessSessionBean.class);
    
    @Override
    public void add() {
        logger.info("add");
        result++;
    }

    @Override
    public int get() {
        return result;
    }
}

Without any more changes, we will get a NoClassDefFoundError:

Caused by: java.lang.NoClassDefFoundError: org/apache/log4j/Logger
at session.StatelessSessionBean.<init>(StatelessSessionBean.java:13)

This is because the dependent jar file (Log4j.jar) won’t be automatically deployed to the server. So we need to manually add the dependent jar file to the EAR project.

Right click on ‘ejb3-ear’, and click on ‘Properties’



Click on ‘Add External JARs’



Add the ‘Log4j.jar’ file into the Java EE modules list

In ‘ejb3-jpa’ project, open the MANIFEST.MF file under META-INF



Enter the Log4j jar name following the Class-Path:

Manifest-Version: 1.0
Class-Path: log4j-1.2.14.jar

Now the StatelessSessionBean class is able to find the Log4j classes it is dependent on.

Appendix

Class loading rule

Friday, 18 November 2011

Access environment properties in EJB3

Create a stateless session bean

@Stateless(name="personBean")
@Local(PersonManager.class)
public class PersonManagerBean implements PersonManager {

    @PersistenceContext(unitName="unit")
    private EntityManager em;
    
    @Resource
    private String defaultName;
    
    @Override
    public void save(Person person) {
        em.persist(new Person(defaultName));
    }
}

The defaultName is to be injected

In ejb-jar.xml

<enterprise-beans>
    <session>
        <ejb-name>personBean</ejb-name>
        <env-entry>
            <env-entry-name>
                session.PersonManagerBean/defaultName
            </env-entry-name>
            <env-entry-type>java.lang.String</env-entry-type>
            <env-entry-value>Tom</env-entry-value>
        </env-entry>
    </session>
</enterprise-beans>

Now the defaultName is initialised with the value ‘Tom’.

The xml equivalence of @Resource annotation:

<enterprise-beans>
    <session>
        <ejb-name>personBean</ejb-name>
        <env-entry>
            <env-entry-name>
                session.PersonManagerBean/defaultName
            </env-entry-name>
            <env-entry-type>java.lang.String</env-entry-type>
            <env-entry-value>Tom</env-entry-value>
            <injection-target>
                <injection-target-class>
                    session.PersonManagerBean
                </injection-target-class>
                <injection-target-name>
                    defaultName
                </injection-target-name>
            </injection-target>
        </env-entry>
    </session>
</enterprise-beans> 

Thursday, 17 November 2011

Credit Card Validation --- Luhn Check

/**
 * Checks if the value is a valid credit card number
 * @param value a string
 * @return true if the value is a valid credit card number
 */
public static boolean isValid(String value){
    return luhnCheck(value.replaceAll("\\D", "")); //remove non-digits
}
 
 /**
 * Checks if a cardNumber passes LUHN check
 * @param cardNumber A string contains only digits
 * @return true if the cardNumber passes LUHN check
 */
private static boolean luhnCheck(String cardNumber){
    int sum=0;
    for (int i=cardNumber.length()-1; i>=0; i-=2){
    sum+=Integer.parseInt(cardNumber.substring(i, i+1));
        if (i>0){
            int d=2*Integer.parseInt(cardNumber.substring(i-1, i));
            if (d>9) d-=9;
            sum+=d;
        }
    }
    return sum%10==0;
}

Configure JMS Resources and create Message Driven Bean in Websphere 7 (Step 8 and 9)

Step 8: Publish a Topic JMS message

Similar to step 4, omit the steps for context lookup, use dependency injection only.

8.1 Access the JMS resources in EJB

In ibm-ejb-jar-bnd.xml under META-INF

<session name="jmsService">
    <resource-ref name="jms/MyTopicConnectionFactory" 
        binding-name="jms/TopicConnectionFactory">
    </resource-ref>
    <message-destination-ref name="jms/MyTopic" 
            binding-name="jms/Topic"/>
</session> 

Note: The binding-name attribute of <resource-ref> and <message-destination-ref> element should match the jndi name specified in Step 6 and Step 7.

Create a stateless session bean

@Stateless(name = "jmsService")
@Local(JMSService.class)
public class JMSServiceBean implements JMSService {

    @Resource(name = "jms/MyTopicConnectionFactory")
    private TopicConnectionFactory tcf;

    @Resource(name = "jms/MyTopic")
    private Topic topic;
    

    @Override
    public void broadcast() {
        try {
            TopicConnection connection = tcf.createTopicConnection();
            TopicSession session 
                = connection.createTopicSession
                (false, TopicSession.AUTO_ACKNOWLEDGE);
            TopicPublisher publisher 
                = session.createPublisher(topic);
            TextMessage message = session.createTextMessage();
            message.setText("This is a broadcast");
            publisher.send(message);
        } catch (JMSException e) {
            throw new EJBException(e);
        }
        System.out.println("Broadcasted");
    }
}

Note: the name attribute of @Resource annotation should match name attribute of <resource-ref> and <message-destination-ref> element respectively in ibm-ejb-jar-bnd.xml, not the binding-name attribute.

Write a servlet to test

public class JMSTopicPublishServlet extends HttpServlet {

    @EJB(beanName="jmsService")
    private JMSService jmsService;
    
    protected void doGet(HttpServletRequest req, 
            HttpServletResponse resp)
            throws ServletException, IOException {
        jmsService.broadcast();
    }
} 

Result

[26/08/11 15:18:00:625 EST] 0000008f SystemOut O Broadcasted

8.2 Access the JMS resources in servlet

In ibm-web-bnd.xml under WEB-INF

<resource-ref name="jms/MyTopicConnectionFactory" 
        binding-name="jms/TopicConnectionFactory">
</resource-ref>
<message-destination-ref name="jms/MyTopic" 
            binding-name="jms/Topic"/>

Note: The binding-name attribute of <resource-ref> and <message-destination-ref> element should match the jndi name specified in Step 6 and Step 7.

Write a servlet to test

public class JMSTopicPublishServlet extends HttpServlet {
    
    @Resource(name = "jms/MyTopicConnectionFactory")
    private TopicConnectionFactory tcf;

    @Resource(name = "jms/MyTopic")
    private Topic topic;
    
    protected void doGet(HttpServletRequest req, 
            HttpServletResponse resp)
            throws ServletException, IOException {
        try {
            TopicConnection connection = tcf.createTopicConnection();
            TopicSession session 
                = connection.createTopicSession
                (false, TopicSession.AUTO_ACKNOWLEDGE);
            TopicPublisher publisher 
                = session.createPublisher(topic);
            TextMessage message = session.createTextMessage();
            message.setText("This is a broadcast");
            publisher.send(message);
        } catch (JMSException e) {
            throw new EJBException(e);
        }
        System.out.println("Broadcasted");
    }
} 

Result

[26/08/11 15:23:36:218 EST] 0000008f SystemOut O Broadcasted

Step 9: Create Topic Message Driven Beans

9.1 Create a Topic Activation Specification

Similar to 5.1



Type TopicActSpec for Name
jms/TopicActSpec for JNDI name
Select Topic as Destination type
Type jms/Topic for Destination JNDI name
Select InternalJMS as Bus name

Click ‘OK’ and save the changes.

9.2 Create two Topic Message Driven Beans

@MessageDriven(name="topicMessageDrivenBean1")
public class TopicMessageDrivenBean1 implements MessageListener {

    @Override
    public void onMessage(Message message) {
        try {
                    TextMessage txtMessage = (TextMessage) message;
                    System.out.println(txtMessage.getText()
                        + " processed by bean 1");
            } catch (JMSException ex) {
                throw new EJBException(ex);
            }
    }
}

@MessageDriven(name="topicMessageDrivenBean2")
public class TopicMessageDrivenBean2 implements MessageListener {

    @Override
    public void onMessage(Message message) {
        try {
                    TextMessage txtMessage = (TextMessage) message;
                    System.out.println(txtMessage.getText()
                            + " processed by bean 2");
            } catch (JMSException ex) {
                throw new EJBException(ex);
            }
    }
}

In ibm-ejb-jar-bnd.xml under META-INF

<message-driven name="topicMessageDrivenBean1">
    <jca-adapter activation-spec-binding-name="jms/TopicActSpec"/>
</message-driven>
<message-driven name="topicMessageDrivenBean2">
    <jca-adapter activation-spec-binding-name="jms/TopicActSpec"/>
</message-driven>

Test the servlet created in step 8 and check the result

[26/08/11 15:23:36:218 EST] 0000008f SystemOut O Broadcasted
[26/08/11 15:23:36:218 EST] 000000a3 SystemOut O This is a broadcast processed by bean 2
[26/08/11 15:23:36:218 EST] 000000a6 SystemOut O This is a broadcast processed by bean 1

Saturday, 12 November 2011

Configure JMS Resources and create Message Driven Bean in Websphere 7 (Step 6 and 7)

Step 6: Create a JMS Topic connection factory

Similar to step 2



Type TopicConnection for Name
jms/TopicConnectionFactory for JNDI name

Select InternalJMS as Bus name

Click ‘OK’ and save the changes

Step 7: Create a JMS Topic destination

Similar to step 3




Type Topic for name
jms/Topic for JNDI name
Select InternalJMS as Bus name
Type q for topic space identifier

Click ‘OK’ and save the changes

Configure JMS Resources and create Message Driven Bean in Websphere 7 (Step 5)

Step 5: Create a Queue Message Driven Bean

5.1 Create a Queue Activation Specification

Log into Websphere Application Server 7 Admin Console

Resources -> JMS -> Activation specifications



Click on ‘New’ button



Click on ‘OK’ button


Type QueueActSpec for Name
jms/QueueActSpec for JNDI name
Select Queue as Destination type
Type jms/Queue for Destination JNDI name
Select InternalJMS as Bus name

Click on ‘OK’ button (not shown in the screenshot)



Click on ‘Save’ link.

5.2 Create a queue message driven bean

@MessageDriven(name="queueMessageDrivenBean")
public class QueueMessageDrivenBean 
    implements MessageListener {

    @Override
    public void onMessage(Message message) {
        try {
            TextMessage txtMessage = (TextMessage) message;
            System.out.println(txtMessage.getText()
                    + " processed....Orz");
        } catch (JMSException ex) {
            throw new EJBException(ex);
        }
    }
}

In ibm-ejb-jar-bnd.xml

<message-driven name="queueMessageDrivenBean">
    <jca-adapter activation-spec-binding-name="jms/QueueActSpec"/>
</message-driven>

Test the servlet created in step 4 and check the result

[26/08/11 11:11:33:812 EST] 0000008f SystemOut O Message Sent
[26/08/11 11:11:33:812 EST] 000000a4 SystemOut O Hello World processed....Orz

Binding another message driven bean to the same queue destination won’t cause exceptions, but only one message driven bean is able to process the message.

Friday, 11 November 2011

Configure JMS Resources and create Message Driven Bean in Websphere 7 (Step 4)

Step 4: Send a queue JMS message

4.1 Access the JMS resources in EJB

4.1.1 Access the JMS resources through Context Lookup

In ibm-ejb-jar-bnd.xml under META-INF


<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar-bnd
        xmlns="http://websphere.ibm.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee 
        http://websphere.ibm.com/xml/ns/javaee/ibm-ejb-jar-bnd_1_0.xsd"
        version="1.0">
    <session name="jmsService">
        <resource-ref name="jms/MyQueueConnectionFactory" 
            binding-name="jms/QueueConnectionFactory">
        </resource-ref>
        <message-destination-ref name="jms/MyQueue" 
            binding-name="jms/Queue"/>
    </session>
</ejb-jar-bnd>

Note: The binding-name attribute of <resource-ref> and <message-destination-ref> element should match the jndi name specified in Step 2 and Step 3.

In ejb-jar.xml under META-INF

<session>
    <ejb-name>jmsService</ejb-name>
    <resource-ref>
        <res-ref-name>jms/MyQueueConnectionFactory</res-ref-name>
            <res-type>javax.jms.QueueConnectionFactory</res-type>
            <res-auth>Container</res-auth>
            <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>
    <message-destination-ref>
        <message-destination-ref-name>
            jms/MyQueue
        </message-destination-ref-name>
        <message-destination-type>
            javax.jms.Queue
        </message-destination-type>
        <message-destination-usage>
            ConsumesProduces
        </message-destination-usage>
        <message-destination-link>
            jms/Queue
        </message-destination-link>
    </message-destination-ref>
</session> 

Note: The value of <res-ref-name> and <message-destination-ref-name> (jms/MyQueueConnectionFactory and jms/MyQueue) should match the name attribute of < resource-ref> and <message-destination-ref> element respectively in ibm-ejb-jar-bnd.xml.

Create a stateless session bean

@Stateless(name="jmsService")
@Local(JMSService.class)
public class JMSServiceBean implements JMSService {

    @Override
    public void sendMessage() {
        try{
            Context ctx = new InitialContext();
            QueueConnectionFactory cf = 
                (QueueConnectionFactory)
                ctx.lookup
                ("java:comp/env/jms/MyQueueConnectionFactory");
            Queue dest = 
                (Queue)ctx.lookup("java:comp/env/jms/MyQueue");
            QueueConnection connection = cf.createQueueConnection();
            QueueSession session = 
                connection.createQueueSession
                (false, javax.jms.Session.AUTO_ACKNOWLEDGE);
            QueueSender queueSender = session.createSender(dest);
            TextMessage message = session.createTextMessage();
            message.setText("Hello World");
            queueSender.send(message);
            System.out.println("Message Sent");
        }catch (Exception e) {
            throw new EJBException(e);
        }
    }
}

Note: The lookup string (jms/MyQueueConnectionFactory and jms/MyQueue) should match the value of <res-ref-name> and <message-destination-ref-name> element respectively in ejb-jar.xml.

4.1.2 Access the JMS resources through Dependency Injection

In ibm-ejb-jar-bnd.xml under META-INF, same as 4.1.1

<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar-bnd
        xmlns="http://websphere.ibm.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee 
        http://websphere.ibm.com/xml/ns/javaee/ibm-ejb-jar-bnd_1_0.xsd"
        version="1.0">
    <session name="jmsService">
        <resource-ref name="jms/MyQueueConnectionFactory" 
            binding-name="jms/QueueConnectionFactory">
        </resource-ref>
        <message-destination-ref name="jms/MyQueue" 
            binding-name="jms/Queue"/>
    </session>
</ejb-jar-bnd>

Note: The binding-name attribute of and element should match the jndi name specified in Step 2 and Step 3.

No changes needed in ejb-jar.xml

Create a stateless session bean


@Stateless(name = "jmsService")
@Local(JMSService.class)
public class JMSServiceBean implements JMSService {

    @Resource(name = "jms/MyQueueConnectionFactory")
    private QueueConnectionFactory qcf;

    @Resource(name = "jms/MyQueue")
    private Queue queue;

    @Override
    public void sendMessage() {
        try {
            QueueConnection connection = qcf.createQueueConnection();
            QueueSession session 
                = connection.createQueueSession(false,
                    QueueSession.AUTO_ACKNOWLEDGE);
            QueueSender queueSender = session.createSender(queue);
            TextMessage message = session.createTextMessage();
            message.setText("Hello World");
            queueSender.send(message);
        } catch (JMSException e) {
            throw new EJBException(e);
        }
        System.out.println("Message Sent");
    } 
}

Note: the name attribute of @Resource annotation should match name attribute of <resource-ref> and <message-destination-ref> element, not the binding-name attribute.

4.1.3 Write a servlet to test

public class JMSSenderServlet extends HttpServlet {

    @EJB(beanName="jmsService")
    private JMSService jmsService;
    
    @Override
    protected void doGet(HttpServletRequest req, 
            HttpServletResponse resp)
            throws ServletException, IOException {
        jmsService.sendMessage();
    }
}

The result:

[25/08/11 14:07:40:109 EST] 0000001a SystemOut O Message Sent

4.2 Access the JMS resources in servlet

4.2.1 Access the JMS resources through Context Lookup

In ibm-web-bnd.xml under WEB-INFO


<?xml version="1.0" encoding="UTF-8"?>
<web-bnd 
    xmlns="http://websphere.ibm.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee 
    http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd"
    version="1.0">

    <virtual-host name="default_host" />
    <resource-ref name="jms/ConnectionFactory" 
            binding-name="jms/QueueConnectionFactory" />
    <message-destination-ref name="jms/Queue" 
            binding-name="jms/Queue"/>
</web-bnd>

Note: The binding-name attribute of <resource-ref> and <message-destination-ref> element should match the jndi name specified in Step 2 and Step 3.

In web.xml under WEB-INFO

<resource-ref>
    <res-ref-name>jms/MyQueueConnectionFactory</res-ref-name>
        <res-type>javax.jms.QueueConnectionFactory</res-type>
        <res-auth>Container</res-auth>
        <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
    
<message-destination-ref>
    <message-destination-ref-name>
        jms/MyQueue
    </message-destination-ref-name>
    <message-destination-type>
        javax.jms.Queue
    </message-destination-type>
    <message-destination-usage>
        ConsumesProduces
    </message-destination-usage>
</message-destination-ref>

Note: The value of <res-ref-name> and <message-destination-ref-name> (jms/MyQueueConnectionFactory and jms/MyQueue) should match the name attribute of < resource-ref> and <message-destination-ref> element respectively in ibm-web-bnd.xml.

Create the servlet

public class JMSQueueSenderServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest req, 
            HttpServletResponse resp)
            throws ServletException, IOException {
        
        try{
            Context ctx = new InitialContext();
            QueueConnectionFactory qcf = 
                (QueueConnectionFactory)
                ctx.lookup
                ("java:comp/env/jms/MyQueueConnectionFactory");
            Queue queue = 
                (Queue)ctx.lookup("java:comp/env/jms/MyQueue");
            QueueConnection connection = qcf.createQueueConnection();
            QueueSession session = 
                connection.createQueueSession
                (false, QueueSession.AUTO_ACKNOWLEDGE);
            QueueSender queueSender = session.createSender(queue);
            TextMessage message = session.createTextMessage();
            message.setText("Hello World");
            queueSender.send(message);
            System.out.println("Message Sent");
        }catch (Exception e) {
            throw new EJBException(e);
        }
    }
}

4.2.2 Access the JMS resources through Dependency Injection

In ibm-web-bnd.xml under META-INF, same as 4.2.1

<?xml version="1.0" encoding="UTF-8"?>
<web-bnd 
    xmlns="http://websphere.ibm.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee 
    http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd"
    version="1.0">

    <virtual-host name="default_host" />
    <resource-ref name="jms/ConnectionFactory" 
            binding-name="jms/QueueConnectionFactory" />
    <message-destination-ref name="jms/Queue" 
            binding-name="jms/Queue"/>
</web-bnd>

No changes in web.xml

Create the servlet

public class JMSQueueSenderServlet extends HttpServlet {

    @Resource(name = "jms/MyQueueConnectionFactory")
    private QueueConnectionFactory qcf;
    
    @Resource(name = "jms/MyQueue")
    private Queue queue;
    
    protected void doGet(HttpServletRequest req, 
            HttpServletResponse resp)
            throws ServletException, IOException {
        try {
            QueueConnection connection = qcf.createQueueConnection();
            QueueSession session 
                = connection.createQueueSession(false,
                    QueueSession.AUTO_ACKNOWLEDGE);
            QueueSender queueSender = session.createSender(queue);
            TextMessage message = session.createTextMessage();
            message.setText("Hello World");
            queueSender.send(message);
        } catch (JMSException e) {
            throw new EJBException(e);
        }
        System.out.println("Message Sent");
    }

}

Note: the name attribute of @Resource annotation should match name attribute of <resource-ref> and <message-destination-ref> element respectively in ibm-web-bnd.xml, not the binding-name attribute.

The result:

[25/08/11 14:20:55:218 EST] 00000020 SystemOut O Message Sent