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

}

}

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.