Sunday, July 31, 2011

ssh connect to host port 22 connection refused

I got this message while trying to ssh into my VMWare Ubuntu 10.4:

ssh connect to host xxx port 22 connection refused

I do this:

sudo apt-get update
sudo apt-get install openssh-server

and.... it works again! cool!

I get the same message with the Oracle VirtualBox Linux: here is a suggested solution

it works!

OSB and Log4J

Objective: enable custom logging from OSB with Log4J

in C:\Oracle\Middleware\Oracle_OSB1\lib\external\log4j_1.2.8.jar you find the libraries

OSB Logger code:

package com.acme.osb;

public class OSBLogger {
 static java.util.logging.Logger loggerJava = java.util.logging.Logger.getLogger(OSBLogger.class.getName());
 static org.apache.log4j.Logger loggerLog4j = org.apache.log4j.Logger.getLogger(OSBLogger.class.getName());
 public static String logMessage(String message) {
  String messageout = "the message is " + message;
  loggerJava.log(java.util.logging.Level.SEVERE, messageout);
  loggerLog4j.debug("log4j" + messageout);
  return messageout;
 public static String reloadConfiguration(String configFilename) throws Exception {
  String messageout = "reloading configuration from " + configFilename;
  URL url = Thread.currentThread().getContextClassLoader().getResource(configFilename);
  if (url == null) {
   throw new IllegalArgumentException("unable to locate resource " + configFilename);
  String file = url.getFile();
  System.out.println("file=" + file);
  BufferedReader in = new BufferedReader(new FileReader(file));
  String text = "";
  while (in.ready()) {
   text = in.readLine();
  System.out.println("done reloading");
  return messageout;

Extra configuration:

put your log4j.xml file in $DOMAIN_HOME/config/osb
(another example here)

Log4j 1.2.13 source here

"The hierarchy will be reset before configuration when log4j.reset=true is present in the properties file. " but this is available only for log4j 1.2.15

This great post on logging best practices


My conclusion: configureAndWatch doesn't simply work. I am fed up investigating on this issue. Probably upgrading to the latest version of log4j would help.

I had to add an extra logger:

<logger name="org.apache.commons" additivity="false">
<level value="WARN"/>
<appender-ref ref="FILEAPACHE"/>

to avoid my own log file being cluttered by org.apache.commons messages (no clue why they end up in my own com.acme.osb logger).

Appendix: custom xpath definitions:

<?xml version="1.0" encoding="UTF-8"?>
<xpf:xpathFunctions xmlns:xpf="">
    <xpf:category id="logMessage">
            <xpf:method>java.lang.String logMessage(java.lang.String)</xpf:method>
            <xpf:method>java.lang.String reloadConfiguration(java.lang.String)</xpf:method>

Best XML editor

I have used Altova XML Spy, but it's not free
I hear good things about Oxygen - also not free

I have been recommended Komodo Edit

I will start using it from today.

Eclipse XML Buddy plugin is so-and-so

Also Eclipse WTP is

As reported in the comments, a star also for  Liquid XML editor ( )

Friday, July 29, 2011

ubuntu on vmware: network is unreachable

Crap, yesterday my Ubuntu 10.4 on VMPlayer was working ALMOST filne,
today I get "network is unreachable" whenever I ping anything.
My VM is set to use NAT.

I do:

cat /etc/network/interfaces

auto lo
iface lo inet loopback

hey, where is eth0?

Here some example, so I "chmod 777" and I add to the file:

auto eth0
iface eth0 inet dhcp

and I
sudo /etc/init.d/networking restart
(it takes a while)

(same can be done with the menu Preferences/Network)

This seems to take care of some issues.

OSB find which Proxy Service is being invoked

I am a bit unsure how better to identify the Message Flow which is currently being executed;
The $inbound variable is:

<con:endpoint name="ProxyService$pierreTests$identifyFlow$identifyFlowPS" xmlns:con="">

so, if you use the name attribute of inbound you have this Xquery:

xquery version "1.0" encoding "Cp1252";
(:: pragma  parameter="$anyType1" type="xs:anyType" ::)

declare namespace xf = "";
declare namespace con = "";
declare namespace tran = "";

declare function xf:getEndpointFromInbound($inbound1 as element())
    as xs:string {
       let $myendpoint := $inbound1/./@name
       fn:tokenize($myendpoint, '\$')[last()]

declare variable $inbound1 as element() external;



This method is far better than using the transport/uri, since the latter is present only in HTTP Proxies, while the inbound/@name is present in ALL proxies.

Thursday, July 28, 2011

Oracle Service Bus Configuration Jar Build and Export reloaded

After a lot of tears shed (see here for my previous post)
I have come up with my own version of the OSBExportFromWorkspace tool.

It is really primitive, especially for the way it parses XSDs and WSDLs, but I have successfully used on my project and it worked - besides it's blazing fast and makes no use of external libraries (esp. NO USE OF ECLIPSE-bleah).

Here goes the link to the code.

Of course there are no comments in the code :o) and it's the good old monolithic-all_in_one procedural coding style

WSDL parser reloaded

Here a previous post on the topic

Here the WSDL 1.1 Schema:

Import it into a Eclipse Web Service project (it has all the facets needed for JAXB)
and generate JAXB classes (I use org.example.wsdl package)

Trying to unmarshal a WSDL, I get a

java.lang.ClassCastException: javax.xml.bind.JAXBElement

(see here)

so I choose a better API for Unmarshaller (don(t try to understand; just make it work)

And.... here is the WSDLParser!

In reality as you start working with TDefinitions you realize that it's quite difficult to extract the information you need, because the schema is VERY abstract.

As usual, simple things made complicated by academics.

Wednesday, July 27, 2011

How to tell if Oracle XE is running on your box

you should have these processes running on your box:

/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/bin/tnslsnr LISTENER -inherit

and if you do
netstat -an | grep 1521
you should get:

tcp 0 0* LISTEN

Tuesday, July 26, 2011

Mysterious new Threads in WebLogic




for a quick intro to Diagnostic Framework, read here and more in details here

process reaper

for some explanation on this thread, read here

OSB Read Timeout and Connection Timeout, stuck threads

This morning the server was hanging (even sbconsole was not responding) and the automated tests were stuck since little after midnight. Maybe something has happened around midnight on that box.

Since I would much rather have a request fail than hanging forever, I have reviewed all the timeouts associated with my Business Services.

There are 2 parameters:

HTTP Transport Configuration:

Read Timeout (30s default)
"Enter the read timeout interval in seconds.
A zero (0) value indicates no timeout."

Connection Timeout (0=disabled by default)
"Enter the connection timeout interval in seconds. If the timeout expires before the connection can be established, Oracle Service Bus raises a connection error."

see here the Oracle OSB doc.

My threads were stuck waiting for a Response from a Web Service... I wonder why the "Read Timeout" didn't trigger a fault.

This was the complete stacktrace for the stuck thread:
(I see a similar problem reported here)

"[STUCK] ExecuteThread: '30' for queue: 'weblogic.kernel.Default (self-tuning)'" - Thread t@141
   java.lang.Thread.State: WAITING
 at java.lang.Object.wait(Native Method)
 - waiting on <6f34d9fb> (a java.lang.Object)
 at java.lang.Object.wait(
 at stages.transform.runtime.WsCalloutRuntimeStep$WsCalloutDispatcher.dispatch(
 at stages.transform.runtime.WsCalloutRuntimeStep.processMessage(
 at sun.reflect.GeneratedMethodAccessor655.invoke(Unknown Source)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(
 at java.lang.reflect.Method.invoke(
 at $Proxy106.sendMessageAsync(Unknown Source)
 at stages.routing.runtime.DynamicRouteRuntimeStep.processMessage(
 at sun.reflect.GeneratedMethodAccessor655.invoke(Unknown Source)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(
 at java.lang.reflect.Method.invoke(
 at $Proxy106.sendMessageAsync(Unknown Source)
 at stages.routing.runtime.RouteRuntimeStep.processMessage(
 at weblogic.servlet.FutureResponseServlet.service(
 at javax.servlet.http.HttpServlet.service(
 at weblogic.servlet.internal.StubSecurityHelper$
 at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(
 at weblogic.servlet.internal.ServletStubImpl.execute(
 at weblogic.servlet.internal.ServletStubImpl.execute(
 at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(
 at weblogic.servlet.internal.WebAppServletContext$
 at weblogic.servlet.internal.WebAppServletContext.securedExecute(
 at weblogic.servlet.internal.WebAppServletContext.execute(

Monday, July 25, 2011

Oracle Service Bus Configuration Jar Build and Export

I was wondering how to generate a sbconfig.jar - yes I know there is a ALSBConfigurationMBean API here but it works only if the projects are deployed in OSB, not if they exist in the OEPE workspace.

so while running an Export operation of my projects defined in Eclipse I took this beautiful stacktrace (thank you, VisualVM):

at ZwWaitForSingleObject+21()@0x770BF8C1
    at RtlIntegerToUnicodeString+523()@0x770D8CB8
    at block_for_safepoint+163(safepoint.c:872+10)@0x0232ABA4
    at tsCheckTransitToJava+19(execution.c:236+19)@0x02330944
    at java/util/zip/ZipFile.getEntry(ILjava/lang/String;Z)I(Native Method)
    at java/util/zip/ZipFile.getEntry(
    at org/eclipse/osgi/baseadaptor/bundlefile/ZipBundleFile.getZipEntry(
    at org/eclipse/osgi/baseadaptor/bundlefile/ZipBundleFile.getEntry(
    ^-- Holding lock: org/eclipse/osgi/baseadaptor/bundlefile/ZipBundleFile@0x1193ADF8[thin lock]
    at org/eclipse/osgi/baseadaptor/loader/ClasspathManager.findClassImpl(
    at org/eclipse/osgi/baseadaptor/loader/ClasspathManager.findLocalClassImpl(
    at org/eclipse/osgi/baseadaptor/loader/ClasspathManager.findLocalClass_LockClassLoader(
    ^-- Holding lock: org/eclipse/osgi/internal/baseadaptor/DefaultClassLoader@0x118AF488[recursive]
    at org/eclipse/osgi/baseadaptor/loader/ClasspathManager.findLocalClass(
    at org/eclipse/osgi/internal/baseadaptor/DefaultClassLoader.findLocalClass(
    at org/eclipse/osgi/internal/loader/BundleLoader.findLocalClass(
    at org/eclipse/osgi/internal/loader/BundleLoader.findClassInternal(
    at org/eclipse/osgi/internal/loader/BundleLoader.findClass(
    at org/eclipse/osgi/internal/loader/BundleLoader.findClass(
    at org/eclipse/osgi/internal/baseadaptor/DefaultClassLoader.loadClass(
    at java/lang/ClassLoader.loadClass(
    at jrockit/vm/Classes.loadClassInternal(
    ^-- Holding lock: org/eclipse/osgi/internal/baseadaptor/DefaultClassLoader@0x118AF488[thin lock]
    at jrockit/vm/RNI.c2java(IIIII)V(Native Method)
    at jrockit/vm/RNI.initializeClass(I)V(Native Method)
    at com/bea/wli/sb/resources/alertdestination/AlertDestinationTypeDef.getPersistedValueRepresentation(
    at com/bea/wli/config/persistence/BinaryIndexedFile.getValueRepresentation(
    at com/bea/wli/config/persistence/BinaryIndexedFile.readData(
    at com/bea/wli/config/component/impl/DataCache.evaluateKey(
    at com/bea/wli/config/component/impl/DataCache.evaluateKey(
    at com/bea/wli/config/component/impl/LazyValueCache$DataCacheEntry.evaluate(
    at com/bea/wli/config/component/impl/LazyValue.getValue(
    at com/bea/wli/config/component/impl/DataCache.getValue(
    at com/bea/wli/config/component/impl/ComponentTypeImpl.getValue(
    at com/bea/wli/config/impl/ConfigContextImpl.getResourceData(
    at com/bea/wli/config/importexport/ConfigJar$CanonicalForm.(
    at com/bea/wli/config/task/impl/ExportTask._execute(
    at com/bea/wli/config/task/impl/ExportTask._execute(
    at com/bea/wli/config/task/impl/SessionedTask$1.execute(
    at com/bea/wli/config/transaction/TransactionalTask._doExecute(
    at com/bea/wli/config/transaction/TransactionalTask._doExecuteWithRetry(
    at com/bea/wli/config/transaction/TransactionalTask.doExecute(
    at com/bea/wli/config/task/impl/SessionedTask.doExecute(
    at com/bea/wli/config/task/impl/SessionedTask.doExecute(
    at com/bea/wli/config/task/impl/ExportTask.exportProjectLevel(
    at com/bea/wli/config/mbeans/Config.exportProjects(
    at com/bea/alsb/core/internal/repositories/jar/ConfigFactory.createForProjects(Ljava/util/Collection;Z)[B(Unknown Source)
    at com/bea/alsb/ui/repositories/jar/ConfigJarContentViewer.createJar()[B(Unknown Source)
    at com/bea/alsb/ui/repositories/jar/JarContextWizardPage.createContext()Lcom/bea/alsb/core/repositories/jar/IWorkspaceConfigRepository$IWorkspaceRepositoryContext;(Unknown Source)
    at com/bea/alsb/ui/repositories/jar/JarExportWizard.performFinish()Z(Unknown Source)
    at org/eclipse/jface/wizard/WizardDialog.finishPressed(
    at org/eclipse/jface/wizard/WizardDialog.buttonPressed(
    at org/eclipse/jface/dialogs/Dialog$2.widgetSelected(
    at org/eclipse/swt/widgets/TypedListener.handleEvent(
    at org/eclipse/swt/widgets/EventTable.sendEvent(
    at org/eclipse/swt/widgets/Widget.sendEvent(
    at org/eclipse/swt/widgets/Display.runDeferredEvents(
    at org/eclipse/swt/widgets/Display.readAndDispatch(
    at org/eclipse/jface/window/Window.runEventLoop(
    at org/eclipse/jface/window/
    at org/eclipse/ui/internal/navigator/wizards/
    at org/eclipse/jface/action/Action.runWithEvent(
    at org/eclipse/jface/action/ActionContributionItem.handleWidgetSelection(
    at org/eclipse/jface/action/ActionContributionItem.access$2(
    at org/eclipse/jface/action/ActionContributionItem$5.handleEvent(
    at org/eclipse/swt/widgets/EventTable.sendEvent(
    at org/eclipse/swt/widgets/Widget.sendEvent(
    at org/eclipse/swt/widgets/Display.runDeferredEvents(
    at org/eclipse/swt/widgets/Display.readAndDispatch(
    at org/eclipse/ui/internal/Workbench.runEventLoop(
    at org/eclipse/ui/internal/Workbench.runUI(
    at org/eclipse/ui/internal/Workbench.access$4(
    at org/eclipse/ui/internal/Workbench$
    at org/eclipse/core/databinding/observable/Realm.runWithDefault(
    at org/eclipse/ui/internal/Workbench.createAndRunWorkbench(
    at org/eclipse/ui/PlatformUI.createAndRunWorkbench(
    at org/eclipse/ui/internal/ide/application/IDEApplication.start(
    at org/eclipse/equinox/internal/app/
    at org/eclipse/core/runtime/internal/adaptor/EclipseAppLauncher.runApplication(
    at org/eclipse/core/runtime/internal/adaptor/EclipseAppLauncher.start(
    at org/eclipse/core/runtime/adaptor/
    at org/eclipse/core/runtime/adaptor/
    at jrockit/vm/RNI.c2java(IIIII)V(Native Method)
    at jrockit/vm/Reflect.invokeMethod(Ljava/lang/Object;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;(Native Method)
    at sun/reflect/NativeMethodAccessorImpl.invoke0(Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;(Native Method)
    at sun/reflect/NativeMethodAccessorImpl.invoke(
    at sun/reflect/DelegatingMethodAccessorImpl.invoke(
    at java/lang/reflect/Method.invoke(
    at org/eclipse/equinox/launcher/Main.invokeFramework(
    at org/eclipse/equinox/launcher/Main.basicRun(
    at org/eclipse/equinox/launcher/
    at org/eclipse/equinox/launcher/Main.main(
    at jrockit/vm/RNI.c2java(IIIII)V(Native Method)
    -- end of trace

Everything seems to start from com.bea.alsb.ui.repositories.jar.JarExportWizard, which is part of the alsbui.jar (eclipse plugin).

in fact I am trying to generate a sbconfig.jar file directly from the SVN content of the OSB artifacts, without having to do a manual export from Eclipse of from the OSB Web Console....

Anyway here the solution... see the exportFromWorkspace target which uses the com.bea.alsb.core.ConfigExport class... which is documented here ... great job, Edwin.

With the PS3, in the build.xml replace:


and make sure you DO NOT DELETE your .metadata in the WORKING COPY workspace - otherwise you have to reconstruct it again!

Problem is, the machine where you do the exportFromWorkspace must have OEPE installed - which is normally not part of the server installation for a non-dev environment...

Just to recap, I am reporting the file and the ant task here:



#properties for workspace export

# export properties  
# specify a project or use None  
#export.customFile = c:/temp/cust.xml  
# import properties  
# specify a project or use None  

and the build.xml

<?xml version="1.0" encoding="windows-1252" ?>
<project name="ConfigExport">

   <property file="./"/>

   <property name="eclipse.home" value="${fmw.home}/oepe_11gR1PS3"/>
   <property name="weblogic.home" value="${fmw.home}/wlserver_10.3"/>
   <property name="metadata.dir" value="${workspace.dir}/.metadata"/>
   <property name="osb.home" value="${fmw.home}/Oracle_OSB1"/>

   <property name="domain.export.script" value="" />
   <property name="domain.import.script" value="" />

   <target name="exportFromWorkspace">
      <!--delete failonerror="false" includeemptydirs="true"
      <java dir="${eclipse.home}"
            fork="true" failonerror="true" maxmemory="768m">
         <jvmarg line="-XX:MaxPermSize=256m"/>   
         <arg line="-data ${workspace.dir}"/>
         <arg line="-application com.bea.alsb.core.ConfigExport"/>
         <arg line="-configProject ${config.project}"/>
         <arg line="-configJar ${config.jar}"/>
         <arg line="-configSubProjects ${config.subprojects}"/>
         <arg line="-includeDependencies ${config.includeDependencies}"/>
         <sysproperty key="weblogic.home" value="${weblogic.home}"/>
         <sysproperty key="osb.home" value="${osb.home}"/>
         <sysproperty key="osgi.bundlefile.limit" value="500"/>
         <sysproperty key="harvester.home" value="${osb.home}/harvester"/>
         <sysproperty key="" value="en_US"/>
         <sysproperty key="sun.lang.ClassLoader.allowArraySyntax" value="true"/>

and it works like magic, even without deleting the .metadata directory...

thank you soooo much Edwin!!!

Incidentally, an attempt to run the task WITHOUT Eclipse (removing the "dir" parameter and providing the JAR as a local copy) aborted with this message:

!SESSION Tue Jul 26 11:47:56 CEST 2011 -----------------------------------------
!ENTRY org.eclipse.equinox.launcher 4 0 2011-07-26 11:47:56.430
!MESSAGE Exception launching the Eclipse Platform:
java.lang.RuntimeException: Could not find framework
 at org.eclipse.equinox.launcher.Main.getBootPath(
 at org.eclipse.equinox.launcher.Main.basicRun(
 at org.eclipse.equinox.launcher.Main.main(

Conversely, if you copy your workspace and OEPE from your Windows machine to your Linux hudson build server, you might get this:

org.eclipse.equinox.p2.core.ProvisionException: No repository found at file:/opt/app/bla/mumble/oepe_11gR1PS3/C:/Oracle4/Middleware/Oracle_OSB1/eclipse120

try adding an extra / at the end of your workspace.dir variable in

and if you get

java.lang.RuntimeException: Application "com.bea.alsb.core.ConfigExport" could not be found in the registry

then edit
to point it to your right value (/opt/app/bla/mumble/Oracle_OSB1/eclipse120/)

and make sure the $ORACLE_HOME/Oracle_OSB1/eclipse120/ directory exists with all the plugins

PS for 10.3.5, use

property name="eclipse.home" value="${fmw.home}/oepe_11gR1PS4"



wlst execfile sys.argv


fails with a exceptions.IndexError because the does a


and nothing is specified for sys.argv[1]



doesn't work
IOError: File not found - (No such file or directory)


execfile('', '')

it gives me a
sequence subscript must be integer or slice

(god only knows what it is trying to do)

All in all, it seems that the only way to pass parameters to a script is by invoking it directly from the command line (java weblogic.WLST
or using the Ant equivalent.

It could be worse... it could be raining...

Sunday, July 24, 2011

A good manager has to be tactful

Saturday, July 23, 2011

Managing Thread Pools

I have copied and run a sample program as from here

Here is the source code:

and here the ExecutorService

particularly valuable are the isTerminated() and awaitTermination(long timeout, TimeUnit unit) methods.

Fantastic also the possibilily to submit a task and monitor its execution with a Future object.

There is also an API to schedule a task in the future, without having to use a java.util.Timer or a framework like Quartz:

Anyway using a ThreadPoolExecutor is far superior to allocating and managing directly Threads yourself (never again a new Thread(this) !)

In praise of Far Manager

I personally hate Windows Explorer - it's very unsafe (you can't disable the drag and drop, which is a major source of trouble) and buggish. It lacks even the fundamental feature of displaying 2 directories side by side.

The almost first thing I do when I have a new computer is to install Far Manager

with its WinSCP plugin.
For those who have used Norton Commander in the old DOS days, it's basically the same.

The WinSCP plugin lets you seamlessly connect to a remote system through SSH and operate as it was a local filesystem - it even acts as a terminal.

Some love Total Commander, my experience still favours Far Manager.

Initiation to GitHub

I was feeling very ignorant because I have never used Git.

Here instructions on how to setup a GitHub client

First I educate myself on Git here.
It's conceptually very clear.

I install Git For Windows and follow the tutorial to check in a README file.
Things go smoothly, the only funny thing is that "commit" doesn't actually push data to the GIT server, you must issue "git push origin master" to see changes reflected in the GIT Web Console.

So now I got my GIT initiation and I can boast about it :o)

Wednesday, July 20, 2011 MBean class bla does not implement DynamicMBean, neither follows the Standard MBean conventions MBean class com.acme.osb.CachesService does not implement DynamicMBean, neither follows the Standard MBean conventions ( Class com.acme.osb.CachesService is not a JMX compliant Standard MBean) nor the MXBean conventions ( com.acme.osb.CachesService: Class com.acme.osb.CachesService is not a JMX compliant MXBean)
at com.sun.jmx.mbeanserver.Introspector.checkCompliance(
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(
at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(

"A standard MBean is defined by writing a Java interface called SomethingMBean and a Java class called Something that implements that interface. "

Stupid me, I had an implementation CachesService but the Interface was called CachesServiceIF... I have renamed it to CachesServiceMBean and everything works!

Throwing exceptions in XQuery - fn:error()

Generating proper error messages is the foundation for a well maintainable application.

One should embed proper assertions in XQuery, using fn:error()

See chapter 3 in here

A (dummy)example is here:

xquery version "1.0" encoding "Cp1252";
(:: pragma parameter="$anyType1" type="xs:anyType" ::)
(:: pragma type="xs:anyType" ::)

declare namespace xf = "";

declare function xf:raiseTest($anyType1 as element(*))
as element(*) {
if ($anyType1/id/text() = 23) then
fn:error(xs:QName('localnameblablabla'), '23 is not a good id')

declare variable $anyType1 as element(*) external;


and you test it with


In OSB only the xs:QName($someString) constructor is supported, and the someString must be the localname (don't use a style, it will raise an exception)
although the normal QName constructor supports all possible variations:,%20java.lang.String,%20java.lang.String%29

Your error handler will receive a fault:

weblogic.xml.query.exceptions.XQueryUserException: line 1, column 1: localnameblablabla: 23 is not a good id:

<con:fault xmlns:con="">
OSB Assign action failed updating variable "bla": weblogic.xml.query.exceptions.XQueryUserException: line 1, column 1: localnameblablabla: 23 is not a good id

How to tell which flavour of Linux I am running

When you telnet, you get it all:

login as: a087
Host: blahost
Company: ACME
Environment: PRODUCTION
Location: Block

In case of problems, contact

*---------------------------------------*'s password:
Last login: Tue Jul 19 17:20:14 2011 from
Welcome to blahost.
This system is managed by Puppet 2.6.7.

Running Red Hat Enterprise Linux Server release 5.6 (Tikanga).

also, uname -a tells you a lot:

Linux blahost 2.6.18-238.1.1.el5 #1 SMP Tue Jan 4 13:32:19 EST 2011 x86_64 x86_64 x86_64 GNU/Linux

and in case of RedHat

cat /etc/redhat-release
Red Hat Enterprise Linux Server release 5.6 (Tikanga)

otherwise just do
ls /etc/*release

Tuesday, July 19, 2011

This is just too funny

sorry but I have to post it

and these code comments are really hilarious

and read also there

this one is pure poetry:

* For the brave souls who get this far: You are the chosen ones,
* the valiant knights of programming who toil away, without rest,
* fixing our most awful code. To you, true saviors, kings of men,
* I say this: never gonna give you up, never gonna let you down,
* never gonna run around and desert you. Never gonna make you cry,
* never gonna say goodbye. Never gonna tell a lie and hurt you.

A mini-framework for Performance Monitoring

Minimalistic set of 3 classes:

import java.util.Collection;

public class PerformanceMeasurement {
 RecordByTypeContainer recordByTypeContainer = new RecordByTypeContainer();

 public void record(String type, long elapsed) {
  RecordByType recordByType = recordByTypeContainer.getRecordByType(type);

 public long averageExecutionTime() {
  long sum = 0;
  for (RecordByType recordByType : recordByTypeContainer.getAllRecordByType()) {
   sum += recordByType.averageExecutionTime();
  return recordByTypeContainer.size() > 0 ? sum / recordByTypeContainer.size() : 0;

 public Collection getRecordByTypes() {
  return recordByTypeContainer.getAllRecordByType();

 public void reset() {
  for (RecordByType recordByType : recordByTypeContainer.getAllRecordByType()) {


import java.util.Collections;
import java.util.List;
import java.util.ArrayList;

public class RecordByType {
 private String type;
 private List measurements = Collections.synchronizedList(new ArrayList());

 public RecordByType(String type) {
  this.type = type;

 public synchronized void addEntry(long elapsed) {

 public long averageExecutionTime() {
  long result = 0;
  synchronized (measurements) {
   for (Long item : measurements) {
    result += item;

  return measurements.size() > 0 ? result / measurements.size() : 0;

 public int numberOfRecordsAboveThreshold(long i) {
  int count = 0;
  synchronized (measurements) {
   for (Long item : measurements) {
    if (item > i)
  return count;

 public synchronized void clear() {

 public String getType() {
  return type;

 public void setType(String type) {
  this.type = type;


import java.util.Collection;
import java.util.HashMap;

public class RecordByTypeContainer extends HashMap {

 public RecordByType getRecordByType(String type) {
  RecordByType result = get(type);
  if (result == null) {
   result = new RecordByType(type);
   this.put(type, result);
  return result;
 public Collection getAllRecordByType() {
  return values();


How to use it:

// create tooling
static final PerformanceMeasurement performanceMeasurement = new PerformanceMeasurement();

// reset to a know state

// do all the tests each of which records the elapsed type

long now = System.currentTimeMillis();
long elapsed = (System.currentTimeMillis() - now);
performanceMeasurement.record("TEST_TYPE", elapsed);

// print stats or do asserts

assertTrue("global averageExecutionTime", performanceMeasurement.averageExecutionTime() < 1600);

for (RecordByType recordByType : performanceMeasurement.getRecordByTypes()) {
 assertTrue("individual averageExecutionTime for type "  + recordByType.getType(), recordByType.averageExecutionTime() < 1600);

 assertTrue("execution threshold  for type " + recordByType.getType(), recordByType.numberOfRecordsAboveThreshold(2000) < 10);

Works like magic!

JMS Resources using JMX

here the original code

here the same code after some fixes is a great site for WebLogic users... check out also

OutOfMemoryError running Ant from Hudson

java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(
at java.util.concurrent.ThreadPoolExecutor.addIfUnderCorePoolSize(
at java.util.concurrent.ThreadPoolExecutor.execute(

Increasing Hudson heap will do no good, since Hudson runs Ant tasks in a separate JVM (I think!).

Rather define

export ANT_OPTS="-Xmx1024m -Xms1024m"

and ant_exec_debug=true

In any case - after a lot of tears and pain - we discovered by running "free" that the Unix box memory was simply totally occupied by running processes.... :o(

Java doesn't differentiate between an OutOfMemory caused by hitting the Heap limit imposed by the -Xms and -Xmx flags, and one caused by hitting physical limits of the host.

Sun JVM heap dump on OutOfMemory

-XX:+HeapDumpOnOutOfMemoryError does the job!!!!

better to add also -XX:HeapDumpPath=/your/path/to/heapdump/dir

(it should be a dir, not a file)

Ad the end of, put:

if [[ "${SERVER_NAME}" == *as ]]
MEM_ARGS="-Xms1g -Xmx1g -XX:MaxPermSize=512m"
MEM_ARGS="-Xms2g -Xmx2g -XX:MaxPermSize=768m"

MEM_ARGS="${MEM_ARGS} -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${DOMAIN_HOME} -Xloggc:/opt/var/log/weblogic/server/${SERVER_NAME}gc.log"

(this loggc option has the disadvantage that gc of multiple servers ends up in the same file... it can be improved... )

More on Oracle Service Bus Split Join

Unsurprisingly Split Join use some BPEL constructs:


and bpel:flow to implement the parallel execution of branches

In fact I can't wait to see the BPEL engine of SOA Suite seamlessly merged into the Oracle Service Bus.

Funny thing is that a SplitJoin is defined only for 1 operation on a target service, but the Business Service you originate from it exposes ALL operations n the WSDL. If by mistake you invoke the wrong operation, you get:

The invocation resulted in an error: Split-Join is configured for operation "bla" but received request for operation "mumble". Make sure the correct operation is selected in route, publish or service callout actions in the proxy message Split-Join..

And unlike in the traditional OSB where you can access a uninitialized variable without getting any error, in BPEL if you forget to assign a value to response you get

[BEA-2031518] Variable 'response' is being referenced before it has been initialized with a value.

OSB Split Join.... Split !Join! Sit!

"Split-Join allows you to send message requests to multiple services concurrently"

This is a Split-Join Halloween dog

The official documentation:


Designing a split join documentation

What is a Mediator Pattern :

I have done a quick minimalistic example to test the parallel execution:

simply import the sbconfig.jar, test/debug the BS, enter whatever you want in input, and watch the 3 parallel log statements being executed in no particular order


I do an xsd:import

xsd:import namespace="" schemaLocation="bla.xsd"

and bla.xsd doesn't define a namespace for its elements.

No way. I get an error

Imported schema has a target namespace "null" that does not match the specified ""

If you specify a namespace, Eclipse complains that it's different from the one used in bla.xsd.
If you leave it empty, "", still it complains. If you omit the namespace="" clause, again it complains. I have tried xsd:nil, no way.

The only way is to use

xsd:include schemaLocation="bla.xsd"


xsd:import xsi:noNamespaceSchemaLocation="bla.xsd"

Monday, July 18, 2011


I have created an attribute

private List measurements = new ArrayList();

and I keep getting an exception:

java.lang.ArrayIndexOutOfBoundsException: 10
at java.util.ArrayList.add(

whenever I do

public void addEntry(long elapsed) {

In fact, ArrayList constructor does:

public ArrayList() {

and its "add" method verifies that there is enough capacity:

public boolean add(E e) {
ensureCapacity(size + 1);
elementData[size++] = e;
return true;

it is self evident that this code is not thread safe.... so if you plan to use an ArrayList in a concurrent scenario, you better synchronize here and there...
otherwise use

List list = Collections.synchronizedList(new ArrayList());

BPM and VirtualBox

I am reading the book "Getting Started with Oracle BPM Suite 11gR1"

For the tutorials, they point you to this page:

Download VirtualBox from here
or here

(in my case, VirtualBox-4.0.12-72916-Win.exe)

Download the VB image as shown here

it's a HUGE download, each file is 1GB...

Then download the Sales Quote Demo.

When importing the appliance into VirtualBox, I get VERR_VD_VMDK_INVALID_HEADER vbox-oel5u4-soabpm-11gr1ps2-bp1-root.vmdk

Being an idiot, at first I swear against Oracle.... then I check all the MD5 fact the vbox-oel5u4-soabpm-11gr1ps2bp1-root.vmdk checksum was wrong.... redownload it again.... the second time around it works!

Importing appliance in VBOX takes forever... 37 minutes.... zzzz...

Once started, it gives me an error about the USB controller.... I disable USB and start again.

Virtual Box captures mouse and keyboard, they say that I should use the "host key" = H0JRE CTRL, no clue what this means.... I panic and finally manage to uncapture by hitting every possible combination of keys.

I get a "memory for crash kernel (0x0 to 0x0) not within permissible range"

I discover that I should "enable IO APIC if you want to run a 64-bit guest"

This is really depressing.

I enable the blessed "IO APIC" in the VM options, and restart.
This time it seems to start.

I get this other message:

I think I can survive to this one.

Login as oracle with password as oracle

and.... lo and behold, I am in!

Sunday, July 17, 2011

What is new in Java 7

basically, nothing noticeable.
To get something really useful, like CLOSURES, you will have to wait for Java 8

Friday, July 15, 2011

Where is Java more popular?

these are the pageviews of my blog (my guess is that almost only people working with Java end up on this blog)

United States
United Kingdom

By far most pageview on this blog are from USA, then India. I am surprised by Brasil, my guess is that soon Brasil will outreach most EU nations.


I am glad to see that Urbanists have minted a word to describe the sense of horror and squalor you have while walking in some streets of Bruxelles:

If you go to any other Belgian city, you feel the beauty, the poetry and harmony of the pristine medieval settings.

Here in Bruxelles in the 1960-1970 they covered everything with concrete. Attila would not have done a better job at making sure no grass grows here.

This is Brussels at its best: concrete, grey, dirt, squalor, desert.

I have heard that Amsterdam was about to follow the same destiny, with bulldozers knocking down 400 years old quarters to replace them with concrete blocks and parking lots; but the Dutch people rioted against the speculators, and after many clashes with Police the speculators had to abandon their plans. Kudos, Dutchmen!

The result is that Amsterdam is one of the main tourist destinations in Europe, while Bruxelles is a city where only students and immigrants live, record-high crime and curfew after 7pm. Most Belgians come here only to work, and commute back to a better place to live.

OSB and the Test Message Pattern

I want to be able to treat differently "test" messages from "normal" messages, so as to be able to monitor my application without disrupting the normal business.

Headers are very good at this.

In my test Java client:

HttpPost httppost = new HttpPost(FACADE_URL);
httppost.addHeader("ORIGIN", "TEST");

In my Facade Proxy Service, enable "get all headers".

log $inbound:

        text/plain; charset=ISO-8859-1
        Apache-HttpClient/4.1.1 (java 1.5)

The problem is how to propagate the headers to other Proxies (http or local).

Use "Set Transport Headers for outbound Destination" with the option "Pass all Headers through Pipeline" to copy the headers to the destination.
When you route to a LOCAL Proxy Service, the header changes slightly, it uses xsi:type="loc:LocalRequestHeaders" instead of xsi:type="http:HttpRequestHeaders" :


You can extract the header with


see here for a discussion on the topic, and here for OSB documentation.

Thursday, July 14, 2011

Hudson Fun Plugins

I have installed the following plugins, just for fun:

Hudson Speaks! Plugin!+Plugin (first, you must go to the /configure page and test if your server supports sound... unfortunately it doesn't support remote notification on another server...)

Hudson Sounds plugin

Radiator View Plugin

To enable the Radiator View, click on myViews and add a view of type "Radiator"
(even if you are blind you will see if your build failed)

For sound and tray monitoring, you can still use the CruiseControl trick:

"An alternative to this is to use the CCTray app that comes with CruiseControl.NET and have it monitor your Hudson server. You can set this up on a shared machine or on individual developer machines. To have CCTray monitor Hudson, set it up to monitor a custom URL that looks like http://hudsonserver:hudsonport/hudsonpath/cc.xml

Basically, appending cc.xml to almost any Hudson URL (project, view, etc.) will return an XML document that CCTray can parse. You can then use CCTray to play .wav files, speak, or even control X10 devices.

CCTray is available at"

I will do it first thing tomorrow...

Hudson integration with JUnit

my ANT build.xml :






Once I configure Hudson with a valid ANT installation, running the test produces a
junitreport under the /home/a087/.hudson (hudson's home dir)

In fact the "Publish JUnit test result report " Hudson option accepts the parameter
"Test report XMLs" with the notation **/reports/*.xml relative to the /home/a087/.hudson directory! (it took some time to figure out)

The TESTS-TestSuites.xml file produced contains aggregate info on all the tests run:





And it happily appears on the "Test Result" tab

If you get
Fingerprinting not enabled on this build. Test aggregation requires fingerprinting

in Post-build Actions, enable "Record fingerprints of files to track usage "
and enter **/reports/*.xml in "Files to fingerprint"

More on TESTS-TestSuites.xml and JUnitReport

Hudson Tray Application failing with "multiple points" NumberFormatException

java.lang.NumberFormatException: multiple points
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Float.parseFloat(Unknown Source)
at org.hudson.trayapp.model.Server.isHudsonBuild173orGreater(

If anybody has a clue, please help.

I was trying to install it from the Hudson Update Center...

Here it says that you must be logged in in order to make Hudson Tray Application work.... =:o(

I had to "Enable security" in Hudson configuration, "Hudson's own user database"

At this point I login and.... I still get the exception :o(((

Here is a preview of what I would get if only it was working.

When I click on the link to Issue Tracker I get a "404" at

very depressing.... one hour wasted...

OSB Custom XPath: XQuery expression validation failed: {err}FONS0003: : prefix not defined in static context

I have created a Custom XPath function, and the entry in osb-built-in.xml is:

            Fills the TSScache with all elements, using Id as a key
            java.lang.String initTSSArray(java.lang.String, [Lorg.apache.xmlbeans.XmlObject;)

When using the new XPath function, I have to precede it with the Namespace prefix generated by OSB :


Problem is, in Eclipse this nisnx is not defined. So I add nisnx as a static prefix in the Proxy Workflow, and next thing I get is:

XQuery expression validation failed: {err}XQ0017: unknown function (or number of arguments (0) is wrong)

The problem now is how to register the custom function in Eclipse.

I will find out one day....

The official documentation says nothing on the topic:

It turns out that, if Eclipse is installed in

you must copy the XML and JAR file to

at this point Eclipse will recognize the Custom XPath functions (after restart and clean).

My problem was that I had deployed the JAR and XML only to my remote installation, not to the local OSB installation. So Eclipse could not see the definition of the XPath Functions.

see also:

and watch this cool video

Wednesday, July 13, 2011

JMS: delete (remove) all messages from a JMS Queue

public static final String WEBLOGIC_JMS_XA_CONNECTION_FACTORY = "weblogic/jms/XAConnectionFactory";

 public static Context createInitialContext() throws NamingException {
  Hashtable ht = new Hashtable();
  ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
  ht.put(Context.PROVIDER_URL, "t3://");     
  Context ctx = new InitialContext(ht);
  return ctx;

 public void init(String jndiname) throws Exception {
  // get the initial context
  Context ctx = createInitialContext();
  // lookup the queue object
  queue = (Queue) ctx.lookup(jndiname);
  // lookup the queue connection factory
  queueConnFactory = (QueueConnectionFactory) ctx.lookup(WEBLOGIC_JMS_XA_CONNECTION_FACTORY);
  // create a queue connection
  queueConn = queueConnFactory.createQueueConnection();
  // create a queue session
  queueSession = queueConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
  // create a queue browser
  queueBrowser = queueSession.createBrowser(queue);
  // start the connection

 public void deleteAllMessagesFromQueue(String jndiname) throws Exception {
    MessageConsumer consumer = queueSession.createConsumer(queue);
    Message message = null;
    do {
        message = consumer.receiveNoWait();
     if (message != null) message.acknowledge();
    while (message != null);

150 thousand visits to this blog!

Jack Daniels - 150th Birthday Flag

To celebrate, I will send a (small) bottle of Jack Daniels to the first person to put a comment on this post - please provide your mailing address (actually, I would rather send you the money, you buy it and drink it to my health)

Eclipse: generate JAXB classes: Please insure that a JAXB implementation is available ....

The classpath for this project does not appear to contain the necessary libraries to proceed with class generation. Please insure that a JAXB implementation is available on the classpath.

What you need is available in a Web Services project:

Quote of the Day

If you really want to do something, you'll find a way. If you don't, you'll find an excuse.

Tuesday, July 12, 2011

XmlObject, XmlCursor and how to replace XPath with "hardcoded" queries

I was under the impression that a given XPath search was too slow, so I implemented the same search in Java.

It's not that difficult.
The main tools are:

a XmlCursor:

XmlCursor cursor = xmlObject.newCursor();

moving to first element inside a node:


moving to a child identified by its QName:

static QName qnameLongNames = new QName("", "LongNames");
boolean found1 = cursor.toChild(qnameLongNames);

eventually using an index if there are multiple elements with same QName:

int count = 0;
boolean found1 = cursor.toChild(qnameLongNames, count);

saving a cursor for later use:

cursor.push(); some other navigation with the cursor....

get the text of an element:


move to adjacent sibling:


With this, you can achieve a lot, and at amazing speed.

Monday, July 11, 2011

IT and the Gulag Archipelago

"Don't ever be the first to stop applauding!"

I am reading The Gulag Archipelago, the book is a bit boring but rich in anecdotes which have some parallel in real life.

Here goes the quote from The Gulag Archipelago:

Here is one vignette from those years as it actually occurred. A district Party conference was under way in Moscow Province. It was presided over by a new secretary of the District Party Committee, replacing one recently arrested. At the conclusion of the conference, a tribute to Comrade Stalin was called for.
Of course, everyone stood up (just as everyone had leaped to his feet during the conference at every mention of his name). The small hall echoed with "stormy applause, rising to an ovation." For three minutes, four minutes, five minutes, the "stormy applause, rising to an ovation," continued. But palms were getting sore and raised arms were already aching. And the older people were panting from exhaustion. It was becoming insufferably silly even to those who really adored Stalin. However, who would dare be the first to stop? The secretary of the District Party Committee could have done it. He was standing on the platform, and it was he who had just called for the ovation. But he was a newcomer. He had taken the place of a man who'd been arrested. He was afraid! After all, NKVD men were standing in the hall applauding and watching to see who quit first! And in that obscure, small hall, unknown to the Leader, the applause went on - six, seven, eight minutes! They were done for! Their goose was cooked! They couldn't stop now till they collapsed with heart attacks! At the rear of the hall, which was crowded, they could of course cheat a bit, clap less frequently, less vigorously, not so eagerly-but up there with the presidium where everyone could see them? The director of the local paper factory, an independent and strong-minded man, stood with the presidium.

Aware of all the falsity and all the impossibility of the situation, he still kept on applauding! Nine minutes! Ten! In anguish he watched the secretary of the District Party Committee, but the latter dared not stop. Insanity! To the last man! With make- believe enthusiasm on their faces, looking at each other with faint hope, the district leaders were just going to go on and on applauding till they fell where they stood, till they were carried out of the hall on stretchers! And even then those who were left would not falter. . . .Then, after eleven minutes, the director of the paper factory assumed a businesslike expression and sat down in his seat. And, oh, a miracle took place! Where had the universal, uninhibited, indescribable enthusiasm gone? To a man, everyone else stopped dead and sat down. They had been saved! The squirrel had been smart enough to jump off his revolving

That, however, was how they discovered who the independent people were. And that was how they went about eliminating them. That same night the factory director was arrested. They easily pasted ten years on him on the pretext of something quite different. But after he had signed Form 206, the final document of the interrogation, his interrogator reminded him:
"Don't ever be the first to stop applauding!"

Now that's what Darwin's natural selection is. And that's also how to grind people down with stupidity.

IT Consulting companies in Denmark and Sweden

Please allow me to list here some IT consulting companies operating in Denmark:

this one to advertise yourself as a freelancer:

and Sweden:

Denmark and Sweden offer excellent salaries and working conditions,
the only blocker being the language and the weather in winter ...
I was in Copenhagen in March and the lakes were covered with ice.... brrrrr....
but in summer it's the Garden of Earthly Delight

Managing concurrent R/W access to a single resource

I have a cache which can be reloaded by client threads.
The problem is to avoid having 2 (or 20!) threads reloading it at the same time.

The solution is pretty simple:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


private static final Lock lock = new ReentrantLock();

public static boolean acquireLock() throws InterruptedException {
return lock.tryLock(TIMEOUT_FOR_LOCK, TimeUnit.SECONDS);

public static String releaseLock() {
return "OK";

And I have exposed these 2 functions as custom XPaths.

In my pipeline, I acquire the lock, then check again if the cache still needs to be reloaded (it might have been reloaded while trying to acquire the lock!)...

VERY important:

a) remember to release the lock, under all circumstances (i.e. do it also in error handler)
b) don't put your acquireLock in a synchronized method, otherwise a deadlock is guaranteed

There might be a case where a thread acquires the lock and then dies without executing the error handler... in this case, the lock will NEVER be released.
I still must think about this scenario, very unlikely but you never know...

Oracle books at Packtpub

"To celebrate the publication of its 50th Oracle book, Packt is offering a series of attractive discounts on all Oracle books.

Buy any Oracle print book and get 20% off
Buy any Oracle eBook and get 30% off"

They ask to spread the word, which I gladly do.

XQuery, convert a dateTime into a date

Stealing almost all the code from I managed to convert a dateTime into a date (dateTimeToDate)...

guys, this is insane...

declare namespace functx = "";

declare function functx:repeat-string
( $stringToRepeat as xs:string? ,
$count as xs:integer ) as xs:string {

string-join((for $i in 1 to $count return $stringToRepeat),
} ;

declare function functx:pad-integer-to-length
( $integerToPad as xs:integer? ,
$length as xs:integer ) as xs:string {

if ($length < string-length(string($integerToPad))) then error(xs:QName('functx:Integer_Longer_Than_Length')) else concat (functx:repeat-string( '0',$length - string-length(string($integerToPad))), string($integerToPad)) } ; declare function functx:date ( $year as xs:integer , $month as xs:integer , $day as xs:integer) as xs:date { xs:date( concat( functx:pad-integer-to-length(xs:integer($year),4),'-', functx:pad-integer-to-length(xs:integer($month),2),'-', functx:pad-integer-to-length(xs:integer($day),2))) } ; declare function functx:dateTimeToDate($dateTime1 as xs:dateTime) as xs:date {
functx:date(fn:year-from-dateTime($dateTime1), fn:month-from-dateTime($dateTime1), fn:day-from-dateTime($dateTime1))

There is this alternative way, slightly simpler :o)


(thanks David for the suggestion, it helps a lot!)

Organizational Charts

I don't know it's true, but I love making fun of Microsoft

(reblogged from )

Optional Attributes in XQuery

I have to return some optional attributes in a XQuery.
There are too many of them, so I cannot return a separate XML for each case. Things have to be done dynamically.

This post explains how:

It works like a charm! Yet I wish there was a simpler fact there is, just use Groovy XmlBuilder :o)

Thursday, July 7, 2011

OSB, side effects of caching Xqueries

One instance of "com.bea.wli.config.derivedcache.DerivedCache" loaded by "sun.misc.Launcher$AppClassLoader @ 0x7812ef450" occupies 1,090,992,792 (72.62%) bytes. The memory is accumulated in one instance of "weblogic.xml.query.xdbcimpl.XQueryPreparedStatementImpl" loaded by "sun.misc.Launcher$AppClassLoader @ 0x7812ef450".

apparently, OSB internally "precompiles" and caches XQuery, which sound pretty reasonable for performance issues.

The side effect is that, if your XQuery is nothing but a huge XML, the format by which this XML is saved in memory is very inefficient.

Our XQuery was simply returning a 10k elements XML, each element being 1K, so a total of 10M on file.

This XQuery ends up taking 1GB of memory, and the performance of my server drops dramatically because very less RAM is available afterwards.

If took a heap dump and Eclipse MAT to discover that.

I think in future we will do a Java Callout returning the content of a file, and converting it to XmlObject with fn-bea:inlinedXML() - that should not put anything in a Cache!

updates: in the custom XPath I read a xml file (. path is relative to user.dir = domain home), using XmlObject.parse(File), and returing XmlObject to OSB.... it works very well without any caching side effect.

This inspires me an interesting pattern: in my Mock Service, I use the unique ID of the request to identify a specific XML file on disk (eg id=408 retrieves file train408.xml). This will enable us to easily serve different data for different IDs.

OSB encoding in XQuery

All the XQuery files in $domain/osb/config/core are stored in UFT-8 encoding:

?xml version="1.0" encoding="UFT-8"?

When you edit the XQuery through the OSB console, the application will take care of encoding weird characters (â, é, ü...) into a sequence of bytes (3 bytes, I guess).

If you have to edit manually the XQuery, and deploy it directly, YOU are responsible to encode the file.

The simplest option is to use Notepad++ and do Encode/Convert to UTF-8

If you deploy the XQuery with improper encoding, the server will not even start and throw horrible UTF8Decoder exceptions (!!!!).

Another alternative for encoding could be using the "file" Linux utility, but I haven't tested this.

Wednesday, July 6, 2011

OSB executing XQuery defined in an external file

Let's admit it, support for reusability of XQuery code is EXTREMELY limited in OSB.
One has to play some trick.

One of them is using custom XPath function - defined in Java - and read and execute dynamically a XQuery, binding parameters dynamically.


This is the Java code:

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

import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;

static String BASE_DIR = "/path/to/config/osb/";

public static XmlObject trainWithParams(XmlObject[] parameters, String[] name) throws Exception {
String xquery = readFile(BASE_DIR + "train.xq"); 
XmlOptions options = new XmlOptions();
// see
Map map = new HashMap();
for (int i = 0; i < name.length; i++) {
   map.put(name[i], parameters[i]);
  return runXQuery(xquery, options)[0];

private static XmlObject[] runXQuery(String xquery, XmlOptions options) {
  XmlObject xmlObject = XmlObject.Factory.newInstance();
  XmlObject[] results = xmlObject.execQuery(xquery, options);
  return results;

private static String readFile(String fFileName) throws Exception {
  StringBuilder text = new StringBuilder();
  String NL = System.getProperty("line.separator");
  Scanner scanner = new Scanner(new FileInputStream(fFileName));
  try {
   while (scanner.hasNextLine()){
    text.append(scanner.nextLine() + NL);
  return text.toString(); 

This is the entry in the osb-built-in.xml

Run a XQuery function returning XmlObject, passing many parameters
org.apache.xmlbeans.XmlObject trainWithParams([Lorg.apache.xmlbeans.XmlObject;, [Ljava.lang.String;)

and this is how to invoke it from any XQuery context in OSB:

return acmxk:trainWithParams(($Train), ('Train'))

You can chain multiple parameters:

return acmxk:trainWithParams(($Train, $Bus), ('Train', 'Bus'))

Of course you can pass the Xquery file name in the call itself, by adding an extra parameter to the signature.

I am not sure if the XQuery will be recompiled every time, or it the XQuery engine keeps a cache. This mechanism exists in SQL engines, perhaps it's there also in XQuery engines.

Also I don't know if this compiled statement caching is in place for all XQuery defined in OSB.