Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, April 2, 2015

Avoiding XPathParser.initXPath(...) infinite loop in Apache Xalan XSLT

An explicit mention of the problem and solution mention in this link: http://marc.info/?l=xalan-j-users&m=104758138708998.

During XSLT transformation using org.apache.xalan.processor.TransformerFactoryImpl, org.apache.xpath.compiler.XPathParser.initXPath() goes into infinite loop if the XLS file is invalid.

The solution is to set an error listener on the TransformerFactory and rethrow the exception from the listener.

Sample Code:
    String xslFilePath = "/path/to/xsl/file";
    String inputXmlPath = "/path/to/input/xml";
    String outputXmlPath = "/path/to/input/xml";
    TransformerFactory factory = new org.apache.xalan.processor.TransformerFactoryImpl()
    factory.setErrorListener(new ErrorListener() {
        public void warning(TransformerException exception) throws TransformerException {
            throw exception;
        }
        public void fatalError(TransformerException exception) throws TransformerException {
            throw exception;
        }
        public void error(TransformerException exception) throws TransformerException {
            throw exception;
        }
    });

    /*
     * TransformerFactory factory = TransformerFactory.newInstance();
     * uses org.apache.xalan.xsltc.trax.TransformerFactoryImpl which doensn't
     * have the infinite loop problem.
     */

    StreamSource xslStream = new StreamSource(xslFilePath);
    Transformer transformer = factory.newTransformer(xslStream);
    StreamSource in = new StreamSource(inputXmlPath);
    StreamResult out = new StreamResult(outputXmlPath);
    HashMap context = new HashMap();
    // set context values into map
    transformer.setParameter("context", context);
    transformer.transform(in, out);

Wednesday, October 2, 2013

Remote debugging Java programs using jdb

The command line tool jdb can be a quick and convenient option to  debug Java programs, particularly in environments where using an IDE will be an overhead or slow.

This can be used for any Java application like those running a main method, web applications, etc.

Steps:

Enable remote debugging for the Java application by adding the following JVM parameter

-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n

The jdb tool can be invoked on the same machine as the running Java program or a remote machine that can access this machine.

jdb -connect com.sun.jdi.SocketAttach:hostname=hostname,port=8000



Refer https://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html for more details.

Saturday, September 28, 2013

Remote debugging Java applications using Eclipse IDE

Java applications can be debugged by attaching its source to a remotely IDE following a client-server approach. The running Java application is considered as server and the IDE with source attached is considered as client.

Server (Java application)
The application to be debugged should be started with the following JVM argument for Java 5.0 and beyond.
-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n

The debugger listens to the port 8000.

Executing java -agentlib:jdwp=help on the command prompt shows the help and list of options.

For pre Java 5.0, the server should be started with
-Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000, suspend=n

Client (Eclipse IDE)
  1. Click the Debug Configurations in the Debug button menu.
  2. In Debug Configurations window, right click Remote Java Application and click New.
  3. Give an appropriate name for the remote debug configuration.
  4. The Connection Type should be Standard (Socket Attach)
  5. Enter the Host on which the Java application is running.
  6. Enter the Port which was used as addresss= while starting the Java application.
  7. In the Source tab select a project or source jar.
  8. Click Apply to save the settings.
  9. Set appropriate break points in the source and start debugging by clicking on Debug in the Debug Configurations window.

Thursday, May 13, 2010

Embedded Jetty Server

A simple utility class to embed Jetty web server:
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.FilterMapping;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public enum WebContainer {
INSTANCE;
private Server server;

public void startServer(String resourceBase, String contextPath, int port) {
try {
server = new Server(port);
ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SESSIONS);
handler.setContextPath(contextPath);
handler.setResourceBase(resourceBase);
server.setHandler(handler);
////////////////////////////////////////////////////////
// add servlet context init params using the following
// handler.getServletContext().setInitParameter(, );
////////////////////////////////////////////////////////

////////////////////////////////////////////////////////
// add event listeners using
// handler.addEventListener();
////////////////////////////////////////////////////////

////////////////////////////////////////////////////////
// add filters using
// handler.addFilter(, , );
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
// add servlets using
// handler.addServlet(, );
////////////////////////////////////////////////////////
server.start();
server.join();
} catch(Exception e) {
e.printStackTrace();
}
}

public void stopServer() {
try {
server.stop();
} catch(Exception e) {
e.printStackTrace();
}
}
}

Use WebContainer.INSTANCE.startServer(...); and WebContainer.INSTANCE.stopServer(); to start and stop the server respectively.

Thursday, April 29, 2010

Implementing a simple deterministic rule engine

The following is my experience of implementing a simple deterministic rule engine (if at all it can be called such) in JavaScript using Mozilla Rhino. This was part of the enterprise platform we are building in our company. We tried using Rete based JBoss Drools earlier but felt that a simpler deterministic rule engine would better suit our purpose.

The need for such a thing was due to various reasons:-
i) Rete based stateful rule engine was an overkill for our use case
ii) The non deterministic and asynchronous nature of Rete based rule engines makes debugging and testing very difficult (as pointed out by Martin Fowler)
iii) Most of the rules in our case were of the nature of validations or calculations which makes Rete an overkill
iv) A tailor made custom rule engine gives more flexibility and power
v) Our consumers (product developers) were not at ease with the programming style of traditional rule based approach


The approach went something like this:-
i) Enable server side scripting in JavaScript using Mozilla's Rhino engine
ii) Capture rules as metadata in the form of JavaScript statements (majority of them will be of the form if condition then action)
iii) Expose domain objects and other relevant APIs into the rule scripts at well defined lifecycle phases of entities (CREATE, UPDATE, DELETE, etc.)
iv) Execute the rule scripts within the context of domain objects and relevant APIs during the life cycle of domain objects (typically CRUD phases)
v) We also support a MANUAL context wherein developers can set relevant domain objects explicitly and invoke the rule engine

Handling Spring ApplicationContext events in Spring DM based OSGi environment

Listening for and handling Spring ApplicationContext events in a Spring DM setup needs needs two steps:

1) Implement a class for the interface org.springframework.osgi.context.event.OsgiBundleApplicationContextListener
import org.osgi.framework.Bundle;
import org.springframework.context.ApplicationContext;
import org.springframework.osgi.context.event.OsgiBundleApplicationContextEvent;
import org.springframework.osgi.context.event.OsgiBundleApplicationContextListener;
import org.springframework.osgi.context.event.OsgiBundleContextClosedEvent;
import org.springframework.osgi.context.event.OsgiBundleContextRefreshedEvent;

public class BundleApplicationContextTracker implements OsgiBundleApplicationContextListener {
public void onOsgiApplicationEvent(OsgiBundleApplicationContextEvent event) {
if(event instanceof OsgiBundleContextRefreshedEvent) {
// handle bundle start
} else if(event instanceof OsgiBundleContextClosedEvent) {
// handle bundle close
}
}
}

2) Expose the above class as an OSGi service by putting the following entries in Spring beans-config.xml

<beans:bean id="bundleContextTracker" class="org.mypackage.BundleApplicationContextTracker" scope="singleton"/>
<osgi:service id="bundleContextTrackerOSGi" ref="bundleContextTracker" interface="org.springframework.osgi.context.event.OsgiBundleApplicationContextListener"/>

Thursday, February 25, 2010

Controlling setup order for Spring DM applications

A quick and easy way to control the order in which Spring DM applications come up is using cardinality property in service imports.

Assume we have two applications app1 and app2 running in a single OSGi container and using Spring DM. Suppose we want app2 wait till app1 is initialized by Spring DM, we could do the following.
i) Export a service with appropriate interfaces / filters from app1.
For example:-
<osgi:service id="dependencyOSGi" ref="applicationDependency" interface="com.test.ApplicationDependency">
<osgi:service-properties><<entry key="application" value="app1-1.4.0.0"/></osgi:service-properties>
</osgi:service>

ii) Imported the above service in app2 with a cardinality 1..1. The cardinality marks the service dependency as mandatory and causes Spring DM to delay the setup of app2 till the dependency is met (i.e. app1 is up an running).

<osgi:reference id="dependencyApp1OSGi" interface="com.test.ApplicationDependency" filter="(application=app1-1.4.0.0)" cardinality="1..1"/>

Wednesday, February 24, 2010

Customozing Spring's Routing Datasource

Changing the data source of your application dynamically at runtime is a very desirable feature for complex enterprise applications and frameworks. If you are using Spring, one of the viable options is Spring's AbstractRoutingDataSource, which allows dynamic data sources based on a lookup key. It uses the well known Decorator pattern to provide a javax.sql.DataSource instance dynamically.

The following article by Mark Fisher from Spring team clearly explains how to go about it:
http://blog.springsource.com/2007/01/23/dynamic-datasource-routing/

The default usage of Spring's AbstractRoutingDataSource is something as follows:
i) You have a set of data sources among which you want to switch dynamically.
ii) You have a well known dynamic key that can pick the right data source for you.

But what if you want to change the set of data sources themselves dynamically? The default usage of AbstractRoutingDataSource won't allow this. After digging into Spring code for some time I found that the following piece of code can do the job.

public class RoutingDataSource extends AbstractRoutingDataSource {
private Map targetDataSources = new HashMap();
public void setTargetDataSources(Map targetDataSources) {
this.targetDataSources = targetDataSources;
}

@Override
protected DataSource determineTargetDataSource() {
Object lookupKey = determineCurrentLookupKey();
DataSource dataSource = (DataSource)this.targetDataSources.get(lookupKey);
if (dataSource == null) {
throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
}
return dataSource;
}

@Override
protected Object determineCurrentLookupKey() {
return /*a lookup key that can pick the actual datasource from the Map*/;
}

@Override
public void afterPropertiesSet() {
// do nothing
// overridden to avoid datasource validation error by Spring
}
}

Monday, January 11, 2010

Javascript on Java

This post illustrates two versions of a simple Java helper class that enables scripting on Java. Its assumed that the reader is aware of the basics of running JavaScript on Java.

The first version uses "Mozilla's Rhino Engine" directly, the second uses the more standard "Java 6" scripting interface (JSR-223).

Using "Mozilla's Rhino Engine" directly:-
import java.util.HashMap;
import java.util.Map;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

/**
* High level wrapper to Mozilla Rhino Engine.
*/
public class ScriptSession {
private Map scopeObjects = new HashMap();

public void put(String key, Object value) {
scopeObjects.put(key, value);
}

public Object execute(String script) {
Object result = null;
try {
Context ctx = Context.enter();
Scriptable scope = ctx.initStandardObjects();
for(String key : scopeObjects.keySet()) {
scope.put(key, scope, scopeObjects.get(key));
}
result = ctx.evaluateString(scope, script, "embedded_script", 1, null);
} catch(Exception e) {
e.printStackTrace();
} finally {
Context.exit();
}
return result;
}

public static ScriptSession createInstance() {
return new ScriptSession();
}
}


Using Java 6 standard interface:-
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
* High level wrapper to JDK 6 scripting API.
*/
public class ScriptSession {
private ScriptEngine engine;

private ScriptSession() {
ScriptEngineManager factory = new ScriptEngineManager();
engine = factory.getEngineByName("JavaScript");
}

public void put(String key, Object value) {
engine.put(key, value);
}

public Object execute(String script) {
Object result = null;
try {
result = engine.eval(script);
} catch(Exception e) {
e.printStackTrace();
}
return result;
}

public static ScriptSession createInstance() {
return new ScriptSession();
}
}


Usage:-
ScriptSession ss = ScriptSession.createInstance();
// put all the context objects you want using
// session.put("", );
Object result = ss.execute("javascript as text");

Inside JavaScript you can access all your context objects the same way you would access Java objects.