Monday, 21 November 2011

EJB Security configuration in Glassfish 3.1

Assume the MySQL data source has been set up. (If not, check Configure MySQL datasource in Glassfish 3.1)

The JNDI name is jdbc/mysql

Start Glassfish, go to Admin Console, http://localhost:4848

Configurations -> server-config -> Security -> Realms


Click on 'New' button

Name: jdbcRealm
Class Name: Select com.sun.enterprise.security.auth.realm.jdbc.JDBCRealm
JAAS Context: jdbcRealm
JNDI: jdbc/mysql
User Table: T_USER
User Name Column: username
Password Column: password
Group Table: T_GROUP
Group Name Column: groupname
Digest Algorithm: none


 

In the MySQL data source, create two tables: T_USER and T_GROUP

CREATE TABLE T_USER (
  `username` VARCHAR(30) NOT NULL,
  `password` VARCHAR(30) NOT NULL,
  PRIMARY KEY (`username`)
)

CREATE TABLE T_GROUP (
  `username` VARCHAR(30) NOT NULL,
  `groupname` VARCHAR(30) NOT NULL,
  PRIMARY KEY (`username`)
)

Insert data

insert into T_USER values (‘sun’, ‘123’);
insert into T_USER values (‘ming’, ‘456’);
insert into T_GROUP values (‘sun’, ‘adminGroup’);
insert into T_GROUP values (‘ming’, ‘userGroup’);

Create a stateless session bean

@Stateless(name="securityManager")
@Local(SecurityManager.class)

public class SecurityManagerBean implements SecurityManager {

    @Resource
    private EJBContext context;
    
    @RolesAllowed({"admin"})
    public void save() {
        System.out.println("User: "
                +context.getCallerPrincipal().getName());
        System.out.println("Save");
    }

}

Create a servlet

public class SecurityServlet extends HttpServlet {

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

Edit web.xml under WEB-INF

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    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">
    <security-role>
        <role-name>user</role-name>
    </security-role>
    
    <security-role>
        <role-name>admin</role-name>
    </security-role>
    
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>all resources</web-resource-name>
            <url-pattern>/se</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
            <http-method>HEAD</http-method>
        </web-resource-collection>
        <auth-constraint>
            <role-name>user</role-name>
            <role-name>admin</role-name>
        </auth-constraint>
        <user-data-constraint>
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>
    
    <login-config>
        <auth-method>BASIC</auth-method>
           <realm-name>jdbcRealm</realm-name>
    </login-config>

    <servlet>
        <servlet-name>se</servlet-name>
        <servlet-class>web.SecurityServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>se</servlet-name>
        <url-pattern>/se</url-pattern>
    </servlet-mapping>
</web-app> 

Note: The value of <realm-name> (jdbcRealm) must match the Name field in Admin Console.


Edit sun-web.xml under WEB-INF

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 8.1
Servlet 2.5//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_2_5-0.dtd">

<sun-web-app>
    <security-role-mapping>
       <role-name>user</role-name>
       <group-name>userGroup</group-name>
    </security-role-mapping>

    <security-role-mapping>
       <role-name>admin</role-name>
       <group-name>adminGroup</group-name>
    </security-role-mapping>
</sun-web-app>


Note: The value of <role-name> must match the value of <role-name> under <security-role> in web.xml. The value of <group-name> must match the value of groupname column in T_GROUP table.

Test the servlet

http://localhost:8080/security-web/se


The console prints

User: sun
Saved


Close and open the browser again, login with the user 'ming'

The console prints

javax.ejb.EJBAccessException

Then try to login with an nonexistent user

The console prints

java.lang.SecurityException

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.