Uday's Blog

February 26, 2010

Retrieving a nodes having max and min values using XPath

Filed under: Technical — ugoud @ 12:34 pm

I was wondering on how to retrieve a xml node which conatains maximum value among a set of nodes. Initially I was thinking to write a Java programme to pass the XML and write logic to retrieve a node containing maximum value. But I found a quicker way of doing it using XPath.

Sample data and example XPath are:


<data>
	<message>
		<value>1</value>
	</message>
	<message>
		<value>3</value>
	</message>
	<message>
		<value>5</value>
	</message>
	<message>
		<value>2</value>
	</message>
	<message>
		<value>4</value>
	</message>
</data>


In order to retrieve message node with value “5” which is maximum, I can use the following XPath (Remember that this is a string comparison)


//data/message[not(value <= preceding-sibling::message/value) and not(value <= following-sibling::message/value)]

In order to retrieve message node with value “1” which is minimum, I can use the following XPath (Remember that this is a string comparison)


//data/message[not(value >= preceding-sibling::message/value) and not(value >= following-sibling::message/value)]

Send message using JMS

Filed under: Technical — ugoud @ 12:09 pm

import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.jms.*;

public class SimpleJMSConnect {
public static void main(String[] args) throws NamingException {
	Properties props = new Properties();
	props.setProperty(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.fscontext.RefFSContextFactory");
	props.setProperty(Context.PROVIDER_URL,"file://E:/JNDI");

    Context jndiContext = null;
    ConnectionFactory connectionFactory = null;
    String connectionFactoryName = null;
    String destinationName = null;
    Destination destination = null;
    Connection connection = null;
    Session session = null;
    MessageProducer producer = null;


    if (args.length != 2) {
        System.out.println("Usage: java SimpleJMSConnect  ");
        System.exit(1);
    }
    connectionFactoryName = args[0];
    destinationName = args[1];
    System.out.println("Destination name is " + destinationName);

    /*
     * Create a JNDI API InitialContext object
     */
    try {
        jndiContext = new InitialContext(props);
    } catch (NamingException e) {
    	System.out.println("Could not create JNDI API context: " + e.toString());
        System.exit(1);
    }

    /*
     * Look up connection factory and destination.
     */
    try {
        connectionFactory = (ConnectionFactory)jndiContext.lookup(connectionFactoryName);
        destination = (Destination)jndiContext.lookup(destinationName);
    } catch (NamingException e) {
    	System.out.println("JNDI API lookup failed: " + e);
        System.exit(1);
    }
    try {
        connection = connectionFactory.createConnection();

        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(destination);
        TextMessage message = session.createTextMessage();
        message.setText("Simple Text message");
        System.out.println("Sending message: " + message.getText());
        producer.send(message);
        /*
         * Send a non-text control message indicating end of messages.
         */
        producer.send(session.createMessage());
    } catch (JMSException e) {
    	System.out.println("Exception occurred: " + e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }

}
}

Create JNDI bindings for WMQ

Filed under: Technical — ugoud @ 12:05 pm

The page describes about how to create jndi bindings files Websphere MQ.

The environment used to describe is as follows:

OS : Windows XP SP3
Websphere MQ: V6.0
Java: 1.6

Once Websphere MQ refered as WMQ from here onwards is installed navigate to the WMQ installation folder from command prompt.
Navigate to <WMQ Install location>\bin and execute the following commands

Create a queue manager

 crtmqm -q JMS_QUEUE_MANAGER

Start queue manager

 strmqm JMS_QUEUE_MANAGER

Open mq command line environment

runmqsc

Define a local queue in mq command line

define qlocal(JMS_QUEUE)
end

Create a configuration file with contents

INITIAL_CONTEXT_FACTORY=com.sun.jndi.fscontext.RefFSContextFactory
PROVIDER_URL=file:
SECURITY_AUTHENTICATION=none

Navigate to <WMQ Install location>\Java\bin

Open JMSAdmin tool

 JMSAdmin.bat -v -cfg 

The above command opens JMSAdmin tool environment

Define JMS bindings for Connection factory by executing

define qcf(jms/testJMSQCF) qmgr(JMS_QUEUE_MANAGER)

JNDI name for the Connection factory will be “jms/testJMSQCF”

Define JMS binding for Queue by executing

define q(jms/testJMSQ) qmgr(JMS_QUEUE_MANAGER) queue(JMS_QUEUE)
end

JNDI name for the Queue will be “jms/testJMSQ”

This will create a .bindings file at location specified in the configuration file.

February 17, 2010

Call Java from XSLT

Filed under: Technical — ugoud @ 3:55 pm

Sometimes it will be useful to call Java static functions from XSLT (esp Date functions). One can easily achieve this, if the xslt engine is running in Java environment. The following shows how to achieve it.



<xsl:element name="DateAsString">
    <xsl:value-of select="CALENDAR:toString()" xmlns:CALENDAR="java.util.Calendar"></xsl:value-of>
</xsl:element>
    


    


February 12, 2010

XML Transformation

Filed under: Technical — ugoud @ 2:10 pm

Sample xml transformation using XSLT 1.0


import java.io.File;
import java.io.StringBufferInputStream;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class XMLTransform {
    public void transform(String xmlFilePath, String xsltFilePath, String destFilePath)
	    throws TransformerException {
	if (null == xmlFilePath || null == xsltFilePath) {
	    System.err.println("One of xml file or xslt file can not be null.");
	    return;
	}

	TransformerFactory transformerFactory = TransformerFactory
		.newInstance();
	Transformer transformer = transformerFactory
		.newTransformer(new StreamSource(new File(xsltFilePath)));
	transformer.transform(new StreamSource(new File(xmlFilePath)),
		new StreamResult(new File(destFilePath)));

    }

    public void transformXML(String xmlData, String xsltFilePath, String destFilePath)
	    throws TransformerException {
	if (null == xmlData || null == xsltFilePath) {
	    System.err.println("One of xml file or xslt file can not be null.");
	    return;
	}

	TransformerFactory transformerFactory = TransformerFactory
		.newInstance();
	Transformer transformer = transformerFactory
		.newTransformer(new StreamSource(new StringBufferInputStream(xmlData)));
	transformer.transform(new StreamSource(new File(xmlData)),
		new StreamResult(new File(destFilePath)));

    }

    public void transformFilesInDir(String xmlDirectory, String xsltFilePath)
	    throws TransformerException {
	File f = new File(xmlDirectory);
	if (f.isFile()) {
	    transform(xmlDirectory, xsltFilePath, xmlDirectory+"-transformed.xml");
	    return;
	} else if (f.isDirectory()) {
	    File[] files = f.listFiles();
	    for (File file : files) {
		if (file.isFile()) {
		    transform(file.getAbsolutePath(), xsltFilePath, file.getAbsolutePath()+"-transformed.xml");
		}
	    }
	} else
	    throw new IllegalArgumentException("[" + xmlDirectory
		    + "]-should be a file or directory.");

    }

    public static void main(String[] args) throws TransformerException {
	if (null == args || 2 > args.length) {
	    System.err
		    .println("Usage: XMLTransform  [directory|file] [xsltfile]");
	}

	XMLTransform transformer = new XMLTransform();
	transformer.transformFilesInDir(args[0], args[1]);

    }
}

Blog at WordPress.com.