Sunday, November 6, 2011

Java EE6 - POJO injection

Simplest Possible POJO Injection Example With Java EE 6
http://www.adam-bien.com/roller/abien/entry/simplest_possible_pojo_injection_example

Annotation Type Inject

http://download.oracle.com/javaee/6/api/javax/inject/Inject.html


Contexts and Dependency Injection for the Java EE Platform

http://www.oracle.com/technetwork/articles/javaee/javaee6overview-141808.html#webbeans



TestInject class
package testinject;

import javax.ejb.EJB;
import javax.inject.Named;

import testejb.BackendBeanLocal;
import testservice.MasterDataCacheLocal;

@Named("TestInject")
public class TestInject {


public TestInject(){
System.out.println("TestInject : constructor");
}

@EJB
MasterDataCacheLocal masterDataCache;

@EJB
BackendBeanLocal service;

public void callService(){

if(masterDataCache.get("dave") == null){
masterDataCache.store("dave","dave");
}

System.out.println("TestInject: callService" );
service.runService();

}

}



Inject POJO in Test Servlet
  @Inject
TestInject testInject;

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

out.println("testInject.callService()<br>");
testInject.callService();






This file is necessary to force to injection
/testWEB/WebContent/WEB-INF/beans.xml
http://download.oracle.com/javaee/6/tutorial/doc/gjbnz.html

</beans>




TestServlet

package testWEB;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.ejb.EJB;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import testinject.TestInject;
import testservice.TestServiceLocal;

/**
* Servlet implementation class TestServlet
*/
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
// TODO Auto-generated constructor stub
}

@EJB TestServiceLocal service;

@Inject
TestInject testInject;

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
res.setContentType("text/html");

HttpSession session = req.getSession(true);

String heading;
Integer accessCount = new Integer(0);
if (session.isNew()) {
heading = "Welcome, Newcomer";
} else {
heading = "Welcome Back";
Integer oldAccessCount = (Integer) session
.getAttribute("accessCount");
if (oldAccessCount != null) {
accessCount = new Integer(oldAccessCount.intValue() + 1);
}
}
session.setAttribute("accessCount", accessCount);

out.println("service.callService()<br>");
service.callService();

out.println("testInject.callService()<br>");
testInject.callService();

out.println("<H1>This is a password protected resource</H1>");
out.println("<PRE>");
out.println("User Name: " + req.getRemoteUser());
String name = (req.getUserPrincipal() == null) ? null : req
.getUserPrincipal().getName();
out.println("Principal Name: " + name);
out.println("Authentication Type: " + req.getAuthType());
out.println("Is a Manager: " + req.isUserInRole("AppRole"));
out.println("</PRE>");
out.println(
"<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" +
"<H2>Update Servlet!!! Information on Your Session:</H2>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD70\">\n" +
" <TH>Info Type<TH>Value\n" +
"<TR>\n" +
" <TD>ID\n" +
" <TD>" + session.getId() + "\n" +
"<TR>\n" +
" <TD>Creation Time is\n" +
" <TD>" + new Date(session.getCreationTime()) + "\n" +
"<TR>\n" +
" <TD>Time of Last Access\n" +
" <TD>" + new Date(session.getLastAccessedTime()) + "\n" +
"<TR>\n" +
" <TD>Number of Previous Accesses\n" +
" <TD>" + accessCount + "\n" +
"</TABLE>\n");
out.println("</BODY></HTML>");


}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}







Application Server log

[#|2011-11-06T22:49:45.979+0100|INFO|glassfish3.1.1|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=17;_ThreadName=Thread-2;|WEB0671: Loading application [testEAR#testWEB.war] at [testWEB]|#]

[#|2011-11-06T22:49:46.002+0100|INFO|glassfish3.1.1|javax.enterprise.system.tools.admin.org.glassfish.deployment.admin|_ThreadID=17;_ThreadName=Thread-2;|testEAR was successfully deployed in 911 milliseconds.|#]

[#|2011-11-06T22:50:30.394+0100|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=24;_ThreadName=Thread-2;|TestInject : constructor|#]

[#|2011-11-06T22:50:30.401+0100|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=24;_ThreadName=Thread-2;|principal=dave|#]

[#|2011-11-06T22:50:30.404+0100|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=24;_ThreadName=Thread-2;|MasterDataCache.initCache|#]

[#|2011-11-06T22:50:30.409+0100|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=24;_ThreadName=Thread-2;|MasterDataCache.get dave|#]

[#|2011-11-06T22:50:30.411+0100|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=24;_ThreadName=Thread-2;|TestService: masterDataCache.store|#]

[#|2011-11-06T22:50:30.413+0100|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=24;_ThreadName=Thread-2;|MasterDataCache.store dave|#]

[#|2011-11-06T22:50:30.413+0100|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=24;_ThreadName=Thread-2;|TestService: callService|#]

[#|2011-11-06T22:50:30.415+0100|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=24;_ThreadName=Thread-2;|BackendBean: runService|#]

[#|2011-11-06T22:50:30.417+0100|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=24;_ThreadName=Thread-2;|MasterDataCache.get dave|#]

[#|2011-11-06T22:50:30.417+0100|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=24;_ThreadName=Thread-2;|TestInject: callService|#]

[#|2011-11-06T22:50:30.418+0100|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=24;_ThreadName=Thread-2;|BackendBean: runService|#]

EJB 3.1 Singleton example

Simplest Possible EJB 3.1 Singleton - Injected Into Servlet 3.0, WAR Deployment
http://www.adam-bien.com/roller/abien/entry/simplest_possible_ejb_3_14

Java EE6 Tutorial : A Singleton Session Bean Example: counter
http://download.oracle.com/javaee/6/tutorial/doc/gipvi.html

A singleton session bean is instantiated once per application and exists for the lifecycle of the application. Singleton session beans are designed for circumstances in which a single enterprise bean instance is shared across and concurrently accessed by clients.

Singleton bean - implements cache

package testservice;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;


/**
* Session Bean implementation class MasterDataCache
*/
@javax.ejb.Singleton
public class MasterDataCache implements MasterDataCacheLocal {

private Map cache;

@PostConstruct
public void initCache() {
System.out.println("MasterDataCache.initCache");
this.cache = new HashMap();
}

public Object get(String key) {
System.out.println("MasterDataCache.get " + key);
return this.cache.get(key);
}

public void store(String key, Object value) {
System.out.println("MasterDataCache.store " + key);
this.cache.put(key, value);
}

}




TestService Session Bean
package testservice;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.EJBContext;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;

import testejb.BackendBeanLocal;

/**
* Session Bean implementation class TestService
*/
@Stateless
public class TestService implements TestServiceRemote, TestServiceLocal {

@EJB
MasterDataCacheLocal masterDataCache;

@EJB
BackendBeanLocal service;

@Resource SessionContext sessionContext;

public void callService(){

System.out.println("principal=" + sessionContext.getCallerPrincipal());

if(masterDataCache.get("dave") == null){
System.out.println("TestService: masterDataCache.store" );
masterDataCache.store("dave","dave");
} else {
System.out.println("TestService: masterDataCache get" );
}

System.out.println("TestService: callService" );
service.runService();

}

}

Security in Glassfish 3.1 ( Java EE 6)

Introduction to Security in the Java EE Platform
http://download.oracle.com/docs/cd/E19798-01/821-1841/6nmq2cpig/index.html
Getting Started Securing Web Applications
http://download.oracle.com/docs/cd/E19798-01/821-1841/bncas/index.html

In EJB caller principal can be obtained from injected SessionContext using
@Resource SessionContext sessionContext;


    System.out.println("principal=" + sessionContext.getCallerPrincipal());




web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>testWEB</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<security-constraint>
<web-resource-collection>
<web-resource-name>TestServlet</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>AppRole</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>default</realm-name>
</login-config>
<security-role>
<role-name>AppRole</role-name>
</security-role>
</web-app>


sun-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Servlet 2.5//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_2_5-0.dtd">
<sun-web-app error-url="">
<context-root>/testWEB</context-root>
<security-role-mapping>
<role-name>AppRole</role-name>
<principal-name>dave</principal-name>
</security-role-mapping>

<security-role-mapping>
<role-name>AppRole</role-name>
<group-name>AppGroup</group-name>
</security-role-mapping>
<class-loader delegate="true"/>
<jsp-config>
<property name="keepgenerated" value="true">
<description>Keep a copy of the generated servlet class java code.</description>
</property>
</jsp-config>

</sun-web-app>


Add user dave in group AppGroup using server console.
Group AppGroup must be mapped to security role AppRole defined in descriptors.