Monday, 26 January 2015

Resolving "The markup in the document following the root element must be well-formed" Exception

Background

In last post we say how we can efficiently parse an XML file using DocumentBuilder -


But as we had concluded that post saying we cannot parse an XML file with multiple root elements. Hence in this post we will see how we can achieve that.

To The Code....

Let say now our data.xml file looks like the following - 

<data key="name" value="John"></data>
<data key="age" value="23"></data>
<data key="sex" value="male"></data>

That is no root element (or rather 3 root elements). If we run the previous code here we will get following Exception -

[Fatal Error] data.xml:2:2: The markup in the document following the root element must be well-formed.
Exception in thread "main" org.xml.sax.SAXParseException; systemId: file:/C:/Users/athakur/newJavaWorkspace/XMLParserDemo/data.xml; lineNumber: 2; columnNumber: 2; The markup in the document following the root element must be well-formed.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
    at XMLParser.main(XMLParser.java:24)


Now lets see how can we tackle this. In this case we will take help of java.io.SequenceInputStream.


import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;

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.NodeList;
import org.xml.sax.SAXException;

/**
 * 
 * @author athakur
 *
 */
public class XMLParser {
    
    public static void main(String args[]) throws IOException, ParserConfigurationException, SAXException
    {
        File file = new File("data.xml");
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Enumeration<InputStream> streams = Collections.enumeration(
                Arrays.asList(new InputStream[] {
                    new ByteArrayInputStream("<ROOT>".getBytes()),
                    new FileInputStream(file),
                    new ByteArrayInputStream("</ROOT>".getBytes()),
                }));

        SequenceInputStream sequenceStream = new SequenceInputStream(streams);
        Document doc = db.parse(sequenceStream);
        NodeList nodes = doc.getElementsByTagName("data");
        for ( int i = 0; i < nodes.getLength(); i++) 
        {
            Element element = (Element) nodes.item(i);
            String key = element.getAttribute("key");
            String value = element.getAttribute("value");    
            System.out.println("Key : " + key + " || Value : " + value);
        }
    }
}
 

and life is good again! Output is -

Key : name || Value : John
Key : age || Value : 23
Key : sex || Value : male 



Related Links

Parsing XML files in Java using javax.xml.parsers.DocumentBuilder

Background

If you want to read xml files and process tag and attributes then there is a smarter way to do it than just reading the file line by line. That is exactly what we are going to see in this post.

To the Code.....

Assume we have the following data.xml file in the root directory of the project with following contents - 

<ROOT>
    <data key="name" value="John"></data>
    <data key="age" value="23"></data>
    <data key="sex" value="male"></data>
</ROOT>


Our goal is to parse this file and print key and value in an efficient manner. We do it the following way - 

import java.io.File;
import java.io.IOException;

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.NodeList;
import org.xml.sax.SAXException;

/**
 * 
 * @author athakur
 *
 */
public class XMLParser {
    
    public static void main(String args[]) throws IOException, ParserConfigurationException, SAXException
    {
        File file = new File("data.xml");
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = db.parse(file);
        NodeList nodes = doc.getElementsByTagName("data");
        for ( int i = 0; i < nodes.getLength(); i++) 
        {
            Element element = (Element) nodes.item(i);
            String key = element.getAttribute("key");
            String value = element.getAttribute("value");    
            System.out.println("Key : " + key + " || Value : " + value);
        }
    }
}

and the output is as expected - 

Key : name || Value : John
Key : age || Value : 23
Key : sex || Value : male

Easy... wasn't it? Using DocumentBuilder makes parsing xml files easy.

NOTE : The XML file should have only one root element and can have multiple child elements. If this is not satisfied you will get following Exception

org.xml.sax.SAXParseException: The markup in the document following the root element must be well-formed.

In case of such cases (multiple root elements) how can we parse the XML? I have explained the same in separate post (See Related Links section below)



Related Links



Saturday, 24 January 2015

Getting started with IBM Bluemix

Background

A while ago I had written a post explaining difference between SaaS, PaaS and IaaS.

In PaaS if you see examples IBM Bluemix is one of the PaaS solutions. In this post we will explore it in detail. Bluemix is powered by Cloud Foundry open source project which itself is a PaaS solution.

For more details on why you should use IBM bluemix, what are the benefits you can refer to following slideshare PPT -


Getting Started

You can sign in into Bluemix portal with following URL - 

You will need an IBM ID for the same. If you don't have you can create one. Once you login you should see following dashboard section -


 Once you have the Dashboard you are all set to create and deploy App of your own. Go ahead and Click on Create An App.

Creating an App

  • Click on Create An App



  • You will be prompted to choose what type of App are you creating ? Is it a web app or a mobile App? For this demo tutorial lets select web app.
  • Next on selecting WEB you will get options to select from various runtimes like Java, NodeJS etc...


  •  For this demo I am choosing NodeJS as it will be easier to demonstrate final outputs. Choose SDK for Node js and click continue.
  • You will then be asked to enter App Name. This will for unique root to your Application. So if some name is already taken you have to give another one (just like domain names :) )


  •  Put some name. I had put DemoWebApp but unfortunately it was taken. So I have put it as DemoTestWebApp. We will see it is next screenshots. Anyway click on finish and your template App should be created, built and deployed.



  • Let see how it looks like, shall we?

See the Route field in above screenshot? That is unique url that points to your App. Go ahead click on it or copy paste it in the URL of your favorite browser. You should see following -


  •  Yeah we create our template App...big deal? What the fun unless we modify it and give it our flavor :)

Modifying and deploying your own code

If you see start coding section under dashboard you should see various methods in which you can build your code.

  •  Yes it provides seamless integration with GIT. Fell free to try out any/all methods. For this demo I am going to use the CF (Cloud foundry) CLI(command line interface). This section gives you list of exact steps that you need to do for creating a local copy of code, changing it and deploying it. But will  re do them for better understanding -

    • Download and install CF CLI from here. I am using Windows. You can choose installer which suits your requirement.... Debian, Redhat, Mac OS X, Windows etc.
    • To verify that it is correctly installed you can simple type cf -v in your command line and it should print you the version. For me it gives -

      C:\Users\athakur>cf -v
      cf version 6.9.0-620f841-2015-01-20T18:01:40+00:00
    • Next Download the template code. Link to it should be in the same CF CLI section of  Start coding section. Go ahead and download the zip file (DemoTestWebApp.zip in my case) and extract it.
    • Lets make some changes to the code now. Example code makes use of Jade Node template engine. The pages that are rendered are in views folder of extracted folder.
    • I have changed some line of code in body.jade file.  For the changes that I made and how can we deploy these changes see following screenshots - 

body.jade File Content

//- body.jade
//- This file provides the HTML body part.


body
  table
    tr
      td(style= "width:30%;" )
        img(src="/images/newapp-icon.png")
      td
        h1 Welcome to Bluemix!
        p This is a demo web app created with <span class = "blue">NodeJS Starter Application</span> by <span class = "blue">Aniket Thakur</span>. Happy Coding!



Now lets deploy our code -

  • Navigate to App directoru ->  cd C:\Users\athakur\Sources\WebTestAppDemo
  • Next connect to bluemix -> cf api https://api.ng.bluemix.net 
  • Login -> cf login -u yourUserName
  • Setup target -> cf target -o yourOrganization -s yourSpace
  • Finally push your code -> cf push DemoTestWebApp 

Finally you should see something like -


1 of 1 instances running

App started


OK

App DemoTestWebApp was started using this command `node app.js`

Showing health and status for app DemoTestWebApp in org *********** / space at
hakur as *************...
OK

requested state: started
instances: 1/1
usage: 128M x 1 instances
urls: demotestwebapp.mybluemix.net
last uploaded: Sun Jan 25 06:28:12 +0000 2015

     state     since                    cpu    memory          disk
#0   running   2015-01-25 11:59:01 AM   0.0%   18.1M of 128M   35.9M of 1G



This means your code is deployed and your app is restarted. All you have to do now is revisit your App URL and test out the changes.


  Lastly I would say it always fun to try new technologies. So do give this a try. It will surely make your life easier (it terms of app deployment and maintenance ofcourse :) )


Related Links

Understanding SOA (Service Oriented Architecture)

Background



Lets say you are designing a system to process stock rates that you receive from stock exchange. Lets say you develop a web application that expects a JSON object. Maybe in further processing down the workflow some other format is expected. To integrate various such services and inter communicate in platform independent way SOA is used. SOA suites provides easy way to integrate such services.



SOA and ESB

SOA is service oriented architecture. In SOA services are decoupled and can interact with each other irrespective of the service type. Meaning a particular service can be platform or protocol specific but SOA enables such services to interact and exchange data. This data is essentially exchanged via ESB (Enterprise service bus) which forms the backbone of any SOA architecture.

Let me go ahead and give specific example to help understand this better. One way ESB could be implemented us by using JMS servers and using XML/XSD as means of transferring data between various services. So various service will register or connect to these JMS servers and exchange data using XML format. Generally SOA suite comes bundles with so called adapters that help transforming messages to and from format understood by service and XML.

For example consider shares trading system. Messages from stock exchange come in FIX protocol. You may have build an application that expects JSON. To make these both systems work you will use SOA - FIX Adapter will convert FIX message to XML, then this xml will be transferred to JSON Adapter over ESB which will then convert to JSON as required by your system endpoint.

Note : I have mentioned XML as it is platform independent message format. It is in fact SOAP (Simple Object access Protocol) that is used to transfer messages. SOAP is a standardized xml with already defined and recognized specifications.

Finally hoping following picture makes it very clear.




Related Links

Friday, 23 January 2015

Difference between SaaS, PaaS and IaaS explained

Background

When decision is made that the business you are trying to create depends on cloud services you need to choose between one of the following deployment models - 
  • IaaS (Infrastructure as a Service)
  • PaaS (Platform as a Service)
  • SaaS (Software as a Service)

Simply speaking following diagram should tell you what each model represents -


Lets discuss in details about each of the cloud models  -

 SaaS (Software as a Service)

SaaS is the simplest cloud service model that serves the end users. All end users have to do is log into the cloud service from a client (typically a browser) and start using the service - Excellent example here would be GMail . All you do is log into your gmail account and send/receive mails.

Target Audience : End Users

Benefits : It saves you the trouble of creating and maintaining software's by yourself. I gave Gmail as an example for SaaS above. Now think you are starting your own business/company and you need to communicate via emails.  If you start from scratch you will have to have your own mail server, configuration and most importantly it's maintenance . SaaS lets you delegate this to 3rd party (SaaS vendors) - Gmail in our example. 

Working : SaaS generally works on Subscription model. You pay for the duration of time you are using the services. Some SaaS based companies may give out free trials for some trial period or give some basic features for free to end users to try out. For example Gmail - if you exceed the space quota available you have to pay for the extra space.

Example : Look around you -  the services that you use in day to day life. Gmail, Salesforce, DropBox, Cisco WebEx, Google Forms, Google Docs, Microsoft 365 etc.





PaaS (Platform as a Service)


PaaS comes at a level lower than SaaS. PaaS allows you to deploy your code without bothering about underlying runtime ,operating system or server infrastructure. Best example here would be - Google App Engine . You choose what programming language suits your business model - Java, NodeJs, PHP ... , write code and deploy it on the PaaS provider. 

Target Audience : Developers

Benefits : It saves you the trouble of owning and maintaining servers (data centers), operating systems on it, runtimes needed to build and deploy your application etc. PaaS delegates these infrastructure requirements to 3rd party (PaaS vendors) - Google App Engine in our example.Also you don't have to worry about scaling and performance. 

Working : So lets say you have written a code for the service you want to provide but dont want to bear the additional cost of purchasing and maintaining infrastructure required to build and deploy your code. So you go to a PaaS vendor and deploy your code there. Again this is pay as you use model. You will have some memory space / RAM  allotted to you for free. As your application scales, your customer base increases you will have to pay for that. Best thing about this is that you don't have to pay unless your requirements exceed the ones provided by the PaaS vendor.

Example :Unless you are a developer I don't expect you to know these but here are some example - Google App EngineCloud Foundry, Heroku, IBM Bluemix, Red Hat’s OpenShift.



 IaaS (Infrastructure as a Service)

This is the lowest level of cloud services that are provided. This saves you the trouble of actually buying and maintaining server infrastructure. In this you get servers from IaaS vendor. You choose your own OS, your runtimes, your application code etc (Refer to topmost picture to visualize).  Famous example of this is AWS (Amazon web services).


Target Audience : Typically IT Admins

Benefits : It saves you the overhead of maintaining hardware infrastructure. You directly get the servers from IaaS vendor.

Working : This generally works using virtual environments. IaaS vendor will have data centers each having multiple servers. Each server will have multiple virtual machines running on them and each IaaS customer will get such a virtual machine. You can then decide what OS you prefer, what runtimes you need etc. Note  as a IaaS customer you will get the experience of a full server + OS stack. You will never know that it infact is virtual environments. How this actually works will of-course depend on the vendor. As far as AWS goes you can try it out for one year without any charges with specified data limits. After a year you will be charged.

Example :Examples for IaaS vendors are AWS, HPCloud, CloudSigma etc.


Summary

 To summarize each of these cloud models have their own uses, So choose according to your business model.


t> UA-39527780-1 back to top