Find and replace the node/element value using xsl

Leave a comment

Below is the XSL source which will be useful for find and replace the node/element value inside the xml.

In the below example , i have tried looking out the two (2) node/element value.

<xsl:stylesheet version=”2.0″ xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”><xsl:processing-instruction name=”xml-u”>version=”1.0″</xsl:processing-instruction><xsl:output method=”html” omit-xml-declaration=”no” indent=”no”/><xsl:param name=”findName01″ select=””/><xsl:param name=”repName01″ select=””/><xsl:variable name=”f01″><xsl:value-of select=”$findName01″/></xsl:variable><xsl:param name=”findName02″ select=””/><xsl:param name=”repName02″ select=””/><xsl:variable name=”f02″><xsl:value-of select=”$findName02″/></xsl:variable><xsl:template match=”node()|@*”> <xsl:copy>  <xsl:apply-templates select=”node()|@*”/></xsl:copy></xsl:template><xsl:template match=”text()”><xsl:variable name=”nm”><xsl:value-of select=”.”/></xsl:variable><xsl:choose><xsl:when test=”contains ($nm,$f01)”><xsl:call-template name=”string-replace-all”><xsl:with-param name=”text” select=”$nm” /><xsl:with-param name=”replace” select=”$f01″ /><xsl:with-param name=”by” select=”$repName01″ /></xsl:call-template></xsl:when><xsl:when test=”contains ($nm,$f02)”><xsl:call-template name=”string-replace-all”><xsl:with-param name=”text” select=”$nm” /><xsl:with-param name=”replace” select=”$f02″ /><xsl:with-param name=”by” select=”$repName02″ /></xsl:call-template></xsl:when><xsl:otherwise><xsl:copy>  <xsl:apply-templates select=”node()|@*”/></xsl:copy> </xsl:otherwise></xsl:choose></xsl:template><xsl:template name=”string-replace-all”><xsl:param name=”text” /><xsl:param name=”replace” /><xsl:param name=”by” /><xsl:choose><xsl:when test=”contains($text, $replace)”><xsl:value-of select=”substring-before($text,$replace)” /><xsl:value-of select=”$by” /><xsl:call-template name=”string-replace-all”><xsl:with-param name=”text” select=”substring-after($text,$replace)” /><xsl:with-param name=”replace” select=”$replace” /><xsl:with-param name=”by” select=”$by” /> </xsl:call-template></xsl:when></xsl:choose></xsl:template></xsl:stylesheet>

njoy !

Sun jaxp factory class implementation path –

Leave a comment

Below are the details of JAXP factory implementation of  Sun JDK 1.5 includes the Xerces and Xalan  –
DocumentBuilderFactory ==> com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl.
SAXParserFactory ==> com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl.
TransformerFactory ==> com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.

Replacing node value using xslt

Leave a comment

One of the usecase which i have looked into recently is about replacing the whole (exact) node/element value with the new one. We can achieve this with the use of XSLT.

Below is the xlst sample which will find and replace the two of the node value(s) –

<xsl:stylesheet version=”2.0″ xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”&gt;
<xsl:output omit-xml-declaration=”yes” indent=”yes”/>
<xsl:param name=”findName01″ select=””/>
<xsl:param name=”repName01″ select=””/>
<xsl:variable name=”f01″><xsl:value-of select=”$findName01″/></xsl:variable>

<xsl:param name=”findName02″ select=””/>
<xsl:param name=”repName02″ select=””/>
<xsl:variable name=”f02″><xsl:value-of select=”$findName02″/></xsl:variable>

<xsl:template match=”node()|@*”>
<xsl:copy>  <xsl:apply-templates select=”node()|@*”/></xsl:copy>
</xsl:template>
<xsl:template match=”text()”>
<xsl:variable name=”nm”><xsl:value-of select=”.”/></xsl:variable>

<xsl:choose>
<xsl:when test=”$nm = $f01″>
<xsl:text><xsl:value-of select=”$repName01″/></xsl:text>
</xsl:when>
<xsl:when test=”$nm = $f02″>
<xsl:text><xsl:value-of select=”$repName02″/></xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:copy>  <xsl:apply-templates select=”node()|@*”/></xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>

Above params like –  “findName01” , “findName02”, “repName01” & “repName02” we can set through the code  that why i have kept that as empty in the xsl file.

Hope this will be useful for others who are looking for the similar solution(s).

Tree view of xml file

Leave a comment

Written one utility class which i believe will useful for others who are looking out for having a tree view of xml file . I have developed the same using swings.  This utility will also provide a drop down and search box which will be useful in searching or finding the selected or entered element /node . In case if the node is found it will highlight those node in tree and will expand only those nodes/element in a tree.

code :-

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XmlTreeView extends DefaultHandler {

private static final String _ROOT_NODE = “Viewer”;
private static final String _GROUP_NAME = “group”;
private static final String _USECASE_NAME = “usecase”;
private static final String _SCENARIO_NAME = “scenario”;
private static final String _AUTOMATION_TOOL_NAME = “automationtool”;
private static final String _FILTER_LABEL = “Filters :”;
private JTree _jTree;
private DefaultTreeModel _treeModel;
private DefaultMutableTreeNode _base;
private static XmlTreeView _treeViewer;
private JComboBox _automationToolBox;
private HashSet<String> _automationToolSet = new HashSet<String>();
Object selectedTool = null;
private JTextField _searchText;
private JButton _jbutton;

@Override
public void startElement(String uri, String localName, String tagName,
Attributes attr) throws SAXException {
if ((tagName.equals(_GROUP_NAME)) || (tagName.equals(_USECASE_NAME))
|| (tagName.equals(_SCENARIO_NAME))) {
DefaultMutableTreeNode currentAtt = null;
for (int i = 0; i < attr.getLength(); i++) {
if (attr.getLocalName(i)
.equalsIgnoreCase(_AUTOMATION_TOOL_NAME)) {
_automationToolSet.add(attr.getValue(i));
}
currentAtt = new DefaultMutableTreeNode(attr.getValue(i) + ” [”
+ tagName + “]”);
_base.add(currentAtt);
}
_base = currentAtt;
} else {
DefaultMutableTreeNode current = new DefaultMutableTreeNode(tagName);
// current.
_base.add(current);
_base = current;
for (int i = 0; i < attr.getLength(); i++) {
if (attr.getLocalName(i)
.equalsIgnoreCase(_AUTOMATION_TOOL_NAME)) {
_automationToolSet.add(attr.getValue(i));
}
System.out.println(attr.getQName(i));
DefaultMutableTreeNode currentAtt = new DefaultMutableTreeNode(attr.getLocalName(i) + “=” + attr.getValue(i));
_base.add(currentAtt);
}
}

}

@Override
public void startDocument() throws SAXException {
super.startDocument();
_base = new DefaultMutableTreeNode(_ROOT_NODE);
((DefaultTreeModel) _jTree.getModel()).setRoot(_base);
}

@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String s = new String(ch, start, length).trim();
if (!s.equals(“”)) {
DefaultMutableTreeNode current = new DefaultMutableTreeNode(“Descrioption : ” + s);
_base.add(current);

}
}

@Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
_base = (DefaultMutableTreeNode) _base.getParent();
}

@Override
public void endDocument() throws SAXException {
// Refresh JTree
((DefaultTreeModel) _jTree.getModel()).reload();
_expandRootNode(_jTree);
}

/**
* Method to start/launch the swing application.
* @param args.
*/

public static void main(String[] args) {
_treeViewer = new XmlTreeView();
_treeViewer.createUI(args);

}

/* private void _expandAll(JTree tree) {
int row = 0;
while (row < tree.getRowCount()) {
tree.expandRow(row);
row++;
}
}*/

private void _colapseAll(JTree tree) {
int row = tree.getRowCount() – 1;
while (row >= 0) {
tree.collapseRow(row);
row–;
}
}

private void _expandRootNode(JTree tree) {
int row = 0;
while (row < 2) {
tree.expandRow(row);
row++;
}
}

private void _xmlSetUp(File xmlFile) {
try {
SAXParserFactory fact = SAXParserFactory.newInstance();
SAXParser parser = fact.newSAXParser();
parser.parse(xmlFile, this);

} catch (Exception e) {

}
}

public void createUI(String[] args) {

//String filePath = args[0];
File file = new File(“D:\\demo\\input_mats.xml”);
_treeModel = new DefaultTreeModel(_base);
_jTree = new JTree(_treeModel);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
javax.swing.ToolTipManager.sharedInstance().registerComponent(_jTree);
} catch (Exception e1) {

}
// — start of components —
_jTree.setCellRenderer(new TreeRender());
JScrollPane scrollPane = new JScrollPane(_jTree);
JLabel lbl = new JLabel(_FILTER_LABEL);
_automationToolBox = new JComboBox();
_searchText = new JTextField();
_jbutton = new JButton(“search”);
JFrame windows = new JFrame();

windows.setTitle(“xml Tree viewer…”);
JPanel pnl = new JPanel();
pnl.setLayout(null);
_xmlSetUp(file);
// create a combo-box dynamically
_automationToolBox.addItem(_AUTOMATION_TOOL_NAME);
for (String x : _automationToolSet) {
_automationToolBox.addItem(x);
}

// Listener for combo-box
_automationToolBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectedTool = ((JComboBox) e.getSource()).getSelectedItem();
List<DefaultMutableTreeNode> nodeList = _searchNode(
_AUTOMATION_TOOL_NAME + “=” + selectedTool.toString(),
false);

if (nodeList.size() > 0) {
_colapseAll(_jTree);
TreePath[] paths = new TreePath[nodeList.size()];

for (int i = 0; i < nodeList.size(); i++) {
DefaultMutableTreeNode node = nodeList.get(i);
TreeNode[] nodes = _treeModel.getPathToRoot(node);
TreePath path = new TreePath(nodes);
_jTree.expandPath(path);
paths[i] = path;
}
_jTree.setSelectionPaths(paths);

} else {
System.out.println(“Node with string ” + selectedTool+ ” not found”);
}

}
});

//Listener for Button.
_jbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
List<DefaultMutableTreeNode> nodeList = _searchNode(
_searchText.getText(), true);
if (nodeList.size() > 0) {
_colapseAll(_jTree);
TreePath[] paths = new TreePath[nodeList.size()];

for (int i = 0; i < nodeList.size(); i++) {
DefaultMutableTreeNode node = nodeList.get(i);
TreeNode[] nodes = _treeModel.getPathToRoot(node);
TreePath path = new TreePath(nodes);
_jTree.expandPath(path);
paths[i] = path;
}
_jTree.setSelectionPaths(paths);

} else {
System.out.println(“Node with string ” + selectedTool
+ ” not found”);
}
}
});
// setting the bounds for the component.
lbl.setBounds(5, 10, 100, 30);
_automationToolBox.setBounds(50, 15, 110, 20);
_searchText.setBounds(180, 15, 150, 20);
_jbutton.setBounds(340, 15, 80, 20);
scrollPane.setBounds(0, 50, 500, 600);
// adding a component to panel.
pnl.add(lbl);
pnl.add(_automationToolBox);
pnl.add(_searchText);
pnl.add(_jbutton);
pnl.add(scrollPane);
// adding a panel to window
windows.add(pnl);
windows.setSize(520, 700);
windows.setVisible(true);
windows.setDefaultCloseOperation(windows.EXIT_ON_CLOSE);
}

private List<DefaultMutableTreeNode> _searchNode(String nodeStr, boolean isSearch) {
DefaultMutableTreeNode node = null;
List<DefaultMutableTreeNode> nodeList = new ArrayList<DefaultMutableTreeNode>();
Enumeration e = _base.breadthFirstEnumeration();
while (e.hasMoreElements()) {
node = (DefaultMutableTreeNode) e.nextElement();
if (!isSearch) {
if (nodeStr.equals(node.getUserObject().toString())) {
nodeList.add(node);

}
} else {
if (node.getUserObject().toString().toLowerCase()
.contains(nodeStr.toLowerCase())) {
nodeList.add(node);

}
}
}
return nodeList;
}

}

/**
* Custom Tree renderer class.
*
*/
class TreeRender extends DefaultTreeCellRenderer {

private static final long serialVersionUID = 1L;

public TreeRender() {

}

public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) super
.getTreeCellRendererComponent(tree, value, selected, expanded,
leaf, row, hasFocus);
renderer.setToolTipText(value.toString());

if (value.toString().contains(“[group]”)) {
renderer.setForeground(Color.BLUE);
Font font = new Font(“Verdana”, Font.BOLD, 11);
renderer.setFont(font);

} else if (value.toString().contains(“[usecase]”)) {
Color color = new Color(196, 18, 245);
renderer.setForeground(color);
Font font = new Font(“Verdana”, Font.BOLD, 11);
renderer.setFont(font);

} else if (value.toString().contains(“[scenario]”)) {
Color color = new Color(165, 96, 242);
renderer.setForeground(color);
Font font = new Font(“Verdana”, Font.BOLD, 11);
renderer.setFont(font);

} else {
Font font = new Font(“Verdana”, Font.PLAIN, 10);
renderer.setFont(font);
renderer.setForeground(Color.black);
}

return renderer;
}

}

njoy !

Solr – enterprise search platform

Leave a comment

It’s been long ,quite busy with the schedule and travel. In this post i would like to share by working experience with the solr. Hope it will be usefule for all those who are working on solr and facing some of challenges which i came across during the implementation.

how to check the class version?

Leave a comment

Its really interesting to know what is the version of class file.
Let’s say some time by having a class file we need to find the java version.
when we compile java it convert into byte code.In that
First 4 bytes CA FE BA BE is the signature of a Java Class file.
The next 2 bytes show the minor version number and then the
next 2 bytes show the major version number.

Convert the hexadecimal to decimal then verify with the below chart.

major minor Java version
45 3 1.0
45 3 1.1
46 0 1.2
47 0 1.3
48 0 1.4
49 0 1.5
50 0 1.6

Open the class file in Hex editor

if you have find difficulty in above procedure then write the java file to check the class version.

Method to check the class version:-
public void checkClassVersion(String classfile)
{
DataInputStream in = new DataInputStream
(new FileInputStream(filename));

int magic = in.readInt();
if(magic != 0xcafebabe) {
System.out.println(filename + ” is not a valid class!”);;
}
int minor = in.readUnsignedShort();
int major = in.readUnsignedShort();
System.out.println(filename + “:- ” + major + ” :- ” + minor);
in.close();

}

— Enjoy

some of links..

Leave a comment

– one of my client visit in india and he had capture snap.

Interesting about the static keywords in java

Leave a comment

Let us talk about some example say – we want an utility class which have a method which will return always random number, so it wouldn’t matter which instance of class is invoking this method. Here method job is to return the random number.

So why then, do we need an instance to invoke this method? Why not just tell the class itself to run this method.

So here what it means – the variable or method which is not be an instance-specific, there we should use the static keyword.

What it mean that we can use static method and variable without having the instance of class at all.

Now what it strikes it in my head, usually we use to invoke the method or variable of class with the use of (.) dot operator.

So all the non-static variable and method is get invoked with the class instance.

Can we invoke the static method or variable by the instance of class?

Yes, you can. But the rule’s is not changed here; it’s just the syntax trick to invoke the static method or variable with the instance of class, but the static members is not aware of the particular instance of class to invoke the members.

Compiler knows that the instance of which class, so it will run the static members with no concerns.

Bullets point(s):-

  • Static method cannot access an instance (non-static) variable.
  • Static method cannot access an instance (non-static) method.
  • Static method can access a static method and variable.

Here comes tricky one? Can we override the static method?

– NO, static method’s can’t be overridden. This does not mean that they can’t be redefined in subclass but redefining and overloading isn’t the same thing.

java crunch(S)

Leave a comment

About the java thoughts and lot more…

Thoughts on interface and abstract class

Leave a comment

Inteface

Let take an example – Shave trimmer that have an adapter which is used to connect it to power sockets.

Now let us take an ipod which uses the same adapter to connect it to power sockets. so here come two disimilar objects ( shave trimmer and ipod) that are allowed to use the same adaptar.Interface is like a guideline or making a contract between the class (shave trimmer and ipod) with the kind of adaptar. My making a adaptar as an interface we can implement the mechanism which is used to handle the voltage and power out put.

  • Basically used to provide the certain functionality to class with no matter what type of object is invoking.
  • All the class which implement this interface(adapter) all it knows it should support the type of voltage and power out put.

Abstract

Abstract class are purely used for inheritance.

Let take again an example of ipod – when the first version of ipod release it has the method of changing the song and display the song name on the screen and lot more other method which provide some functionality.

In that case Abstract class should have method where all the child ipod( new version ipod) should inherit .In that case all the new version of ipod default inherit the feature of change the song and display the song name methods.

But there may be chance that all the new version of ipod may have slightly changes in one of the method , but they all inherit the basic functionality from the base class.Now what makes this different from a regular base class is that its abstract meaning that all those child ipods that inherit from the original override the functionality.

Abstract classes are not meant to be directly instantiated, they are primarily used to inherit from. You can pull all the functionality common to all ipods out there in one basic class and then in each child class only override what is new to the child class (aka the improvements).

  • By creating an interface, you can move your implementation to any class that implements your interface.
  • By creating an abstract class, you can share implementation for all derived classes in one central place, and avoid lots of bad things like code duplication.

Older Entries