Getting XML elements as Key Value Map java

Get XML values as key value pair in Java

This simple java class would help to get values of the xml format as key and value map in java.

It has some limitation on the xml that you would be using, yet it would be a ground step for building other.

package helpers;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 *
 * Simple XML Class -
 * This XML Class is a simple helper only for specific case. Originally developed to get
 * key and value of flat xml.
 * Feel free to use this piece of code as you like with/out permission - if possible mention this site.
 * I am not responsible for any consequences that would result after using this piece of code.
 *
 * @author http://gullele.com
 */
public class XMLHelper {
	private DocumentBuilderFactory documentBuilderFactory;
	private DocumentBuilder documentBuilder;

	public XMLHelper(){
		try{
			this.documentBuilderFactory = DocumentBuilderFactory.newInstance();
			this.documentBuilder = this.documentBuilderFactory.newDocumentBuilder();
		}
		catch(ParserConfigurationException pce){
			//log error
		}
	}

	//Simple test
	public static void main(String argv[]) {
		XMLHelper xmlHelper = new XMLHelper();
		  try {
			  String xmlDoc = "<?xml version="1.0"?><flatFields><java>6.0</java><xml>yes</xml><tags>given tags</tags><doc /><multipleRow /></flatFields>";
			  Document doc = xmlHelper.getDocumentBuilder().parse(
					  xmlHelper.getInputStream(xmlDoc)
			  );
			  doc.getDocumentElement().normalize();
			  NodeList nodeLst = doc.getDocumentElement().getChildNodes();
			  Map elemen = xmlHelper.getElementKeyValue(nodeLst);
			  Iterator it = elemen.entrySet().iterator();
			  while (it.hasNext()) {
				  Map.Entry pairs = (Map.Entry)it.next();
				  	System.out.println(pairs.getKey() + " = " + pairs.getValue());
			  }
			} catch (SAXParseException e) {
			   //log error
			} catch (SAXException e) {
				   //log error
			} catch (IOException e) {
				   //log error
			}
	}

	/**
	 * Provides NodeList from the given Document object by the tagName
	 * @param Document - doc
	 * @param tagname
	 * @return NodeList
	 */
	public NodeList getNodeListByTag(Document doc, String tagname){
		NodeList nodeList = null;
		if (doc !=null && !tagname.isEmpty()){
			nodeList = doc.getElementsByTagName(tagname);
		}
		return nodeList;
	}

	/**
	 *
	 * @param nodeList
	 * @return Map
	 */
	public Map getElementKeyValue(NodeList nodeList){
		Map elements = new HashMap();
		if (nodeList!=null && nodeList.getLength()>0 ){
			for(int i=0 ; i < nodeList.getLength() ; i++){
				Node node = nodeList.item(i); //Take the node from the list
				NodeList valueNode = node.getChildNodes(); // get the children of the node
		        String value = (valueNode.item(0)!=null) ? valueNode.item(0).getNodeValue() : "";
		        elements.put(node.getNodeName(), value);
			}
		}
		return elements;
	}

	/**
	 * Returns InputString given string
	 * @param string
	 * @return InputStream
	 */
	public InputStream getInputStream(String string){
		InputStream inputStream = null;
		if (!string.isEmpty()){
			try{
				inputStream = new ByteArrayInputStream(string.getBytes("UTF-8"));
			}
			catch(UnsupportedEncodingException uee){
			}
		}
		return inputStream;
	}

	/**
	 * Setters and getters
	 * @return
	 */
	public DocumentBuilderFactory getDocumentBuilderFactory() {
		return documentBuilderFactory;
	}
	public void setDocumentBuilderFactory(
			DocumentBuilderFactory documentBuilderFactory) {
		this.documentBuilderFactory = documentBuilderFactory;
	}
	public DocumentBuilder getDocumentBuilder() {
		return documentBuilder;
	}
	public void setDocumentBuilder(DocumentBuilder documentBuilder) {
		this.documentBuilder = documentBuilder;
	}
}

An output for the test main method would be:
tags = given tags
doc =
multipleRow =
xml = yes
java = 6.0

Also Recommended for You

See how to handle unicode in database with java here

Find the longest palindrome sequence from given characters

Can you find pairs that makes K complementary from the array?

Convering String to inputStream java

There are a number of places where string would be needed to be changed to InputStream object. For example the Dom parser would expect an InputStream for the creation of its DocumentBuilder

Here is the simple yet powerful single line doing the task!!

inputStream = new ByteArrayInputStream(string.getBytes("UTF-8"));

find specific string from files in unix and show files

This would select and print on the terminal.
Say you want to examine gullele.wordpress.com from all index.html files that are residing in some directory and sub directory
then:
find . -name ‘index.html’ -exec ‘gullele.wordpress.com’ {} ; -print
would list all index.html files with the given content inside them.

find and filter in jQuery when and how to use

Thanks to JQuery, handling javascript has never been easy. Bigger things while working on the client side would be querying the DOM for specific components. Among the tremendously many options, I would discuss the find and filter.
For illustration of the discussion let’s have the following example HTML:

<div class="upper"><p>Upper text goes here</p><div>
<div class="upper"><p>Another <b>Upper text goes</b> here</p><div>
<div class="middle"><p>middle <b>text goes</b> here</p><div>
<div class="lower">lower <b>text goes</b> here<div>
<div class="lower"><p>still another lower <i>text goes</i> here</p><div>

Using Filter

Filter would provide all the given components which are screened by the given condition. the query:
jQuery(‘div’).filter(‘.upper’) would provide two elements of div that have class upper on them. so alert(jQuery(‘div’).filter(‘.upper’).length) would alert two. Changing the class to middle and lower would result one and two respectively.

Using Find

Find, like the filter would provide elements and unlike filter, it would apply filtering on the children of the given component. Here is an example

jQuery('div').find('p').addClass('border-it');

This query would select the ‘p’ tag under every div element and would apply the class ‘border-it’ to the ‘p’ element only. Which means, it would iterate on the given condition on the parent component.

Finding all the bolds and underlining them would be:

jQuery('div').find('p').find('b').css('text-decoration', 'underline');

Also, this can be done ins succinct way as:

jQuery('div p b').css('text-decoration','underline');

How about if we want to select both the parent and the selected child:

In this case the handy method andSelf() would be there. Say if we want to border only the bold text and that of the enclosing div, we would have:

jQuery('div').find('p').find('b').andSelf().css('border', '1px black solid');

Regular expression for file and directory listing

I guess ls is a laudable command in the Linux world – the fact that everything is a file, we exploit it in a daily manner.
One usage of the a helpful command on ls is grep for listing regex’d listing.
here is the the simplest command that can list all the files/directories with that start with ‘pe’
First we would be on the directory we want the listing, then we would pipe the listing to grep!

ls | grep "^pe.*"

Even

ls | grep "^pe" 

would result the same.
One that contains pe would be

ls | grep "pe"

and the one that ends with pe would be

ls | grep "pe$"

Further reading Ubunutu help on grep

Adding PECL package in Ubuntu

I remember once enjoying PECL (PHP Extension Community Library)on my machine flourishingly. All of the sudden, I was not able find it – here is how I find out.
Trying to play with the new MongoDb, I had to install the driver from the the repository as

sudo pecl install mongo

This time I got the wrong message of not having the pecl. It was easy though – just

sudo apt-get install php5-dev

As the PECL can be found inside it.
I have read some blogs complaining this one not working and passing the problem through installing the PEAR pachage – WHICH EVER IS EASIER.
Happy PECLing..

Adding Path to Environment in Ubuntu

After adding some software or programing language or whatever to ubuntu, mostly using the non-synaptic method, our command line would crave for the new terms ;).
Here is how to add the new path to the environment
Lets use how to add the tomcat app server after we install it using the tar file.

1. Open the terminal : Application->Accessories->Terminal
2. use your favorite text editor to open /etc/environment in my case I would use view as vi /etc/environment
3. add the path on new line as CATALINA_HOME=”path/to/catalina”
4. save and exit!!
In most cases, the current shell would not see the effect and you may want to open another tab for that or you can use the export command

if we are appending to the existing path variable, we can use the export command as
export PATH = ${PATH}:/path/to/new/location – here the ${PATH} would maintain the existing path information and the colon would be the separator for the paths

Server sent unexpected return value (405 Method Not Allowed) in response to MKCOL request error in svn

The error pops up when trying to commit to the repository.

This SVN error happens when trying to add the directory/file to the repository while the directory is already existing.

It can happen when one of the coworker creates a directory and commits and the other one tries the same task [svn add directory/file] without updating from trunk first.

Solution

A couple of options are there for this.

1. Update to the repository and deal with the conflicts if there are any.
2. if the created directory is assumed to be redundant, delete the directory and recommit it.

Also: Checkout how to identify changes in SVN

Could not open Hibernate Session for transaction

This problem happens when the connection to the database is disconnected or was not created at all by the application, but pool assumes connection is established.
Remedy for this could be checking credential to the database [username, password, host, port] and also checking the connection object before proceeding to database tasks like reading or updating.