Sunday, February 26, 2012

Start ANTLR project with Maven

http://www.antlr.org/wiki/display/ANTLR3/Building+ANTLR+Projects+with+Maven

http://www.eclipse.org/m2e/
Download m2e
http://www.eclipse.org/m2e/download/





dave@dave antlr-maven]$ mvn archetype:generate -B -DarchetypeGroupId=org.antlr
-DarchetypeArtifactId=antlr3-maven-archetype
-DarchetypeVersion=3.3-1
-DgroupId=dave.antlr
-DartifactId=java-tree-walker
-Dversion=1.0
-Dpackage=dave.antlr
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:2.1:generate (default-cli) @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:2.1:generate (default-cli) @ standalone-pom <<<
[INFO]
[INFO] --- maven-archetype-plugin:2.1:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Batch mode
[INFO] Archetype repository missing. Using the one from [org.antlr:antlr3-maven-archetype:3.4] found in catalog remote
Downloading: http://repo1.maven.org/maven2/org/antlr/antlr3-maven-archetype/3.3-1/antlr3-maven-archetype-3.3-1.jar
Downloaded: http://repo1.maven.org/maven2/org/antlr/antlr3-maven-archetype/3.3-1/antlr3-maven-archetype-3.3-1.jar (11 KB at 34.4 KB/sec)
Downloading: http://repo1.maven.org/maven2/org/antlr/antlr3-maven-archetype/3.3-1/antlr3-maven-archetype-3.3-1.pom
Downloaded: http://repo1.maven.org/maven2/org/antlr/antlr3-maven-archetype/3.3-1/antlr3-maven-archetype-3.3-1.pom (3 KB at 6.0 KB/sec)
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Archetype: antlr3-maven-archetype:3.3-1
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: davedave@dave antlr-maven]$ mvn archetype:generate -B -DarchetypeGroupId=org.antlr -DarchetypeArtifactId=antlr3-maven-archetype -DarchetypeVersion=3.3-1 -DgroupId=dave.antlr -DartifactId=java-tree-walker -Dversion=1.0 -Dpackage=dave.antlr
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:2.1:generate (default-cli) @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:2.1:generate (default-cli) @ standalone-pom <<<
[INFO]
[INFO] --- maven-archetype-plugin:2.1:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Batch mode
[INFO] Archetype repository missing. Using the one from [org.antlr:antlr3-maven-archetype:3.4] found in catalog remote
Downloading: http://repo1.maven.org/maven2/org/antlr/antlr3-maven-archetype/3.3-1/antlr3-maven-archetype-3.3-1.jar
Downloaded: http://repo1.maven.org/maven2/org/antlr/antlr3-maven-archetype/3.3-1/antlr3-maven-archetype-3.3-1.jar (11 KB at 34.4 KB/sec)
Downloading: http://repo1.maven.org/maven2/org/antlr/antlr3-maven-archetype/3.3-1/antlr3-maven-archetype-3.3-1.pom
Downloaded: http://repo1.maven.org/maven2/org/antlr/antlr3-maven-archetype/3.3-1/antlr3-maven-archetype-3.3-1.pom (3 KB at 6.0 KB/sec)
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Archetype: antlr3-maven-archetype:3.3-1
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: dave.antlr
[INFO] Parameter: artifactId, Value: java-tree-walker
[INFO] Parameter: version, Value: 1.0
[INFO] Parameter: package, Value: dave.antlr
[INFO] Parameter: packageInPathFormat, Value: dave/antlr
[INFO] Parameter: package, Value: dave.antlr
[INFO] Parameter: version, Value: 1.0
[INFO] Parameter: groupId, Value: dave.antlr
[INFO] Parameter: artifactId, Value: java-tree-walker
[INFO] project created from Archetype in dir: /usr/app/project/antlr-maven/java-tree-walker
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.303s
[INFO] Finished at: Sun Feb 26 10:40:25 CET 2012
[INFO] Final Memory: 7M/17M
[INFO] ------------------------------------------------------------------------



[dave@dave java-tree-walker]$ cat >dave.dmo
Keyser Soze ;
2 + 3;



java -jar target/java-tree-walker-1.0-jar-with-dependencies.jar dave.dmo

java -jar target/java-tree-walker-1.0-jar-with-dependencies.jar -dot dave.dmo




Monday, February 20, 2012

Tree traversal

http://en.wikipedia.org/wiki/Tree_traversal
http://en.wikipedia.org/wiki/Breadth-first_search
http://en.wikipedia.org/wiki/Depth-first_search

Tree traversal in various languages
http://rosettacode.org/wiki/Tree_traversal#Java

Algorithms
http://algs4.cs.princeton.edu/home/
Graphs
http://algs4.cs.princeton.edu/40graphs/
Directed Graphs

http://algs4.cs.princeton.edu/42directed/

Java Data Structure: A Generic Tree

http://sujitpal.blogspot.com/2006/05/java-data-structure-generic-tree.html


Generic Node
public class Node<T> {

public T data;
public List<Node<T>> children;
public List<Node<T>> parents;


Non-generic node
package dave;

/**
* Non-generic subclass of Node<String>
*/
public class DaveNode extends Node<String> {
public DaveNode() {
super();
}
}



Walk using stack
 /**
*
* @param element
* @return set of all nodes
*/
public List<Node<T>> walk(Node<T> element){

List<Node<T>> out = new ArrayList<Node<T>>();

Queue<Node<T>> q = new LinkedList<Node<T>>();
q.add(element);

while(!q.isEmpty()){
Node<T> x = q.poll();
out.add(x);

for(Node<T> child : x.getChildren()){
q.add(child);
}
}

return out;

}


Walk from bottom up
  /**
*
* @param element
* @return set of all upper nodes
*/
public Collection<Node<T>> pathBottomUp(Node<T> element){

Set<Node<T>> out = new LinkedHashSet<Node<T>>();

Queue<Node<T>> q = new LinkedList<Node<T>>();
q.add(element);

while(!q.isEmpty()){
Node<T> x = q.poll();
out.add(x);

for(Node<T> parent : x.getParents()){
q.add(parent);
}
}

return out;

}


Construct tree
package dave;


public class WalkTree {

public static void main(String[] args) {

DaveTree daveTree = new DaveTree();

DaveNode daveNode = getDaveNode("1");

DaveNode daveNode11 = getDaveNode("1.1");
DaveNode daveNode12 = getDaveNode("1.2");
DaveNode daveNode13 = getDaveNode("1.3");

DaveNode daveNode131 = getDaveNode("1.3.1");
DaveNode daveNode132 = getDaveNode("1.3.2");

daveNode.addChild(daveNode11);
daveNode.addChild(daveNode12);
daveNode.addChild(daveNode13);

daveNode12.addChild(daveNode131);

daveNode13.addChild(daveNode131);
daveNode13.addChild(daveNode132);


daveTree.setRootElement(daveNode);

System.out.println(daveTree.toList());

Node<String> root = daveTree.getRootElement();

System.out.println("walk:" + daveTree.walk(root));

System.out.println("pathBottomUp:" +daveTree.pathBottomUp(daveNode131));

}

private static DaveNode getDaveNode(String profileName){

DaveNode daveNode = new DaveNode();

daveNode.setData(profileName);

return daveNode;

}

}



Program output
[{1,[1.1,1.2,1.3]}, {1.1,[]}, {1.2,[1.3.1]}, {1.3.1,[]}, {1.3,[1.3.1,1.3.2]}, {1.3.1,[]}, {1.3.2,[]}]
walk:[{1,[1.1,1.2,1.3]}, {1.1,[]}, {1.2,[1.3.1]}, {1.3,[1.3.1,1.3.2]}, {1.3.1,[]}, {1.3.1,[]}, {1.3.2,[]}]
pathBottomUp:[{1.3.1,[]}, {1.2,[1.3.1]}, {1.3,[1.3.1,1.3.2]}, {1,[1.1,1.2,1.3]}]

Friday, January 6, 2012

Weblogic auto login with boot properties file

Weblogic requires JVM property -Dweblogic.system.BootIdentityFile to locate boot.properties file
How a Server Uses a Boot Identity File at Startup
http://docs.oracle.com/cd/E14571_01/web.1111/e13708/overview.htm#START132


# create boot properties file
${DOMAIN_HOME}/bin/createBootProperties.sh

#use boot.properties from AdminServer dir - this is necessary for weblogic.Admin to run without password
JAVA_OPTIONS="${JAVA_OPTIONS} -Dweblogic.system.BootIdentityFile=${DOMAIN_HOME}/servers/${SERVER_NAME}/security/boot.properties"

# add trust key store
SSL_ARGS="${JAVA_OPTIONS} -Dweblogic.security.SSL.trustedCAKeyStore=/weblogic/weblogic10.3/wlserver_10.3/server/lib/DemoTrust.jks -Dweblogic.security.SSL
.ignoreHostnameVerification=true"

# check if admin server is not already running
echo "Checking if admin server is not already running..."
${JAVA_HOME}/bin/java ${SSL_ARGS} weblogic.Admin -url t3s://localhost:7001 PING



Without JVM property attempt to call Weblogic without password returns following error

WebLogic server requires a valid username and password for the command that you are trying to execute. Please try again


Password and username can be encrypted by weblogic.security.Encrypt which is using domain key /app/domains/base_domain/security/SerializedSystemIni.dat
http://docs.oracle.com/cd/E21764_01/web.1111/e13749/utils.htm#ADMRF142
http://docs.oracle.com/cd/E13222_01/wls/docs92/admin_ref/utils.html#wp1209592

#!/bin/bash

WL_HOME=/app/weblogic122/wlserver_12.1
DOMAIN_HOME=/app/domains/base_domain

. $WL_HOME/server/bin/setWLSEnv.sh

BOOT_PROPERTIES_DIR=$DOMAIN_HOME/servers/AdminServer/security
BOOT_PROPERTIES_FILE=$BOOT_PROPERTIES_DIR/boot.properties

mkdir -p $BOOT_PROPERTIES_DIR

printf "username=" > $BOOT_PROPERTIES_FILE
java -Dweblogic.RootDirectory=/app/domains/base_domain weblogic.security.Encrypt weblogic >> $BOOT_PROPERTIES_FILE
printf "password=" >> $BOOT_PROPERTIES_FILE
java -Dweblogic.RootDirectory=/app/domains/base_domain weblogic.security.Encrypt weblogic123 >> $BOOT_PROPERTIES_FILE


[dave@dave java]$ more /app/domains/base_domain/servers/AdminServer/security/boot.properties 
username={AES}DG3YOrSwfkK0YrxUM+4cMf+wF91eYhhHpF4wFbsydp0=
password={AES}pkaZZGMqSWQwFEMJSj+FO0aY9LatGJTkz4CZ0Un5v64=




Domain Configuration Files
http://docs.oracle.com/cd/E14571_01/web.1111/e13716/config_files.htm#i1091725
servers/server-name/security
This directory holds security-related files that can be or must be different for each Oracle WebLogic Server instance. The file boot.properties is an example of a file that resides here because it can differ from one server to the next. This directory also maintains files related to SSL keys.

Monday, December 26, 2011

Functional x Imperative ?

http://rosettacode.org/wiki/Roman_numerals/Decode#Java

[dave@dave lisp]$ clisp 
i
. i i i I i i i i ooooo o ooooooo ooooo ooooo
I I I I I I I I I 8 8 8 8 8 o 8 8
I I \ `+' / I I 8 8 8 8 8 8
I \ `-+-' / I 8 8 8 ooooo 8oooo
\ `-__|__-' / 8 8 8 8 8
`--___|___--' 8 o 8 8 o 8 8
| ooooo 8oooooo ooo8ooo ooooo 8
--------+--------

Welcome to GNU CLISP 2.49 (2010-07-07) <http://clisp.cons.org/>




Code ( taken from Object Oriented Common Lisp )
defun roman-to-decimal  (num-list)
(if ( endp num-list)
0
(+ (or
(and (cdr num-list)
(< (numeral-to-decimal (car num-list))
(numeral-to-decimal (cadr num-list)))
(- (numeral-to-decimal (car num-list))))
(numeral-to-decimal (car num-list)))
(roman-to-decimal (cdr num-list)))))

(load "roman-to-decimal.lisp")

[7]> (roman-to-decimal '(M C M L X I X ))
1969
[8]> (trace roman-to-decimal)
;; Tracing function ROMAN-TO-DECIMAL.
(ROMAN-TO-DECIMAL)
[9]> (roman-to-decimal '(M C M L X I X ))
1. Trace: (ROMAN-TO-DECIMAL '(M C M L X I X))
2. Trace: (ROMAN-TO-DECIMAL '(C M L X I X))
3. Trace: (ROMAN-TO-DECIMAL '(M L X I X))
4. Trace: (ROMAN-TO-DECIMAL '(L X I X))
5. Trace: (ROMAN-TO-DECIMAL '(X I X))
6. Trace: (ROMAN-TO-DECIMAL '(I X))
7. Trace: (ROMAN-TO-DECIMAL '(X))
8. Trace: (ROMAN-TO-DECIMAL 'NIL)
8. Trace: ROMAN-TO-DECIMAL ==> 0
7. Trace: ROMAN-TO-DECIMAL ==> 10
6. Trace: ROMAN-TO-DECIMAL ==> 9
5. Trace: ROMAN-TO-DECIMAL ==> 19
4. Trace: ROMAN-TO-DECIMAL ==> 69
3. Trace: ROMAN-TO-DECIMAL ==> 1069
2. Trace: ROMAN-TO-DECIMAL ==> 969
1. Trace: ROMAN-TO-DECIMAL ==> 1969
1969



Haskell
http://www.haskell.org/haskellwiki/Roman_numerals#More-than-one_liner
http://www.cs.york.ac.uk/ftpdir/pub/haskell/contrib/Roman.hs
[dave@dave haskell]$ ghci
GHCi, version 6.12.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package ffi-1.0 ... linking ... done.
Prelude> :l Roman.hs
[1 of 1] Compiling Main ( Roman.hs, interpreted )
Ok, modules loaded: Main.
*Main> fromRoman "MCMLXIX"
1969




Simple Java implementation
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RomanToDecimal {

public static Map<String, Integer> romanNumberMap = new HashMap<String, Integer>();
static {
// ( (I 1) (V 5) (X 10) (L 50) (C 100) (D 500) (M 1000)))
romanNumberMap.put("I", 1);
romanNumberMap.put("V", 5);
romanNumberMap.put("X", 10);
romanNumberMap.put("L", 50);
romanNumberMap.put("C", 100);
romanNumberMap.put("D", 500);
romanNumberMap.put("M", 1000);
}

public static void main(String[] args) {

roman2dec("IV");

roman2dec("LXIV");

roman2dec("XCVIII");

roman2dec("MCMLXIX");

}

private static int roman2dec(String roman) {

int out = 0;

List<Integer> list = new ArrayList<Integer>();

for (int i = 0; i < roman.length(); i++) {
list.add(romanNumberMap.get(String.valueOf(roman.charAt(i))));
}

System.out.println("list=" + list);

while (list.size() > 0) {
if ((list.size() > 1) && (list.get(0) < list.get(1))) {
out -= list.remove(0);
} else {
out += list.remove(0);
}
System.out.println(" list=" + list + " out=" + out);
}

System.out.println("roman=" + roman + " dec=" + out);

return out;

}

}



list=[1, 5]
list=[5] out=-1
list=[] out=4
roman=IV dec=4
list=[50, 10, 1, 5]
list=[10, 1, 5] out=50
list=[1, 5] out=60
list=[5] out=59
list=[] out=64
roman=LXIV dec=64
list=[10, 100, 5, 1, 1, 1]
list=[100, 5, 1, 1, 1] out=-10
list=[5, 1, 1, 1] out=90
list=[1, 1, 1] out=95
list=[1, 1] out=96
list=[1] out=97
list=[] out=98
roman=XCVIII dec=98
list=[1000, 100, 1000, 50, 10, 1, 10]
list=[100, 1000, 50, 10, 1, 10] out=1000
list=[1000, 50, 10, 1, 10] out=900
list=[50, 10, 1, 10] out=1900
list=[10, 1, 10] out=1950
list=[1, 10] out=1960
list=[10] out=1959
list=[] out=1969
roman=MCMLXIX dec=1969

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();

}

}