Friday, June 29, 2012

Introduction To RDF (Resource Description Framework)

Mr. Goni On RDF (Resource Description Framework)

  • RDF is a language for representing information about resources in the World Wide Web
  • RDF is a standard model for data interchange on web ,more elegantly and intelligently
  • The Resource Description Framework (RDF) is a family of World Wide Web Consortium (W3C) specifications
  • Originally Designed as a metadata data model
  • Prime intention of RDF is to represent meta data about the resource in the web
  • One of the major focus of RDF (Resource Description Framework) is the data represented using RDF will be used by different application rather then only representation purpose . This capability will leverage next generation developer to work with data more conveniently

        
                Tony Benn
                Wikipedia
                
                     
                          Tony Benn  
                     
                
        



Reference :


The processing instruction target matching "[xX][mM][lL]" is not allowed

This message is related to xml directly.This is actually related to xml parsing .Technically id  SAX Parse exception occur then we will see this message . This exception will occur if there is any black space of line in the very beginning of the xml message , means before the line bellow :

                   <?xml version = "1.0" encoding = "utf-8" ?>  

Simple problem , simple solution just remove the black line or space in start of xml message .

Things Fall Apart by Chinua Achebe

By Chinua Achebe - Anchor Books (1959) 

Rise and fall , ups and down even head and tail are some true factors of human race.Recently i read these 
specific book with great interest. I am an analytical reader .
The story of this books is round in a time when people of different villages (as described in the book) are 
fighting and keeping there hope alive round the year and even round there life time with spectacular 
custom and natural rituals in different occasion.

                                                    

Tuesday, June 26, 2012

EJB (Enterprise Java Beans) Introduction

Mr . Goni on EJB (Enterprise Java Beans)

  • Enterprise beans an JEE components that implements EJB
  • EJB run in EJB container
    • JEE server
    • EJB Container
    • Web container
    • Application client container
    • Applet container
  • EJB is a server side component
  • Written in the pure java programming language
  • Encapsulates the business logic of an application
  • Types of EJB(Enterprise Java Beans)
    • Session Bean
    • Message Driven
    • Note : Entity beans have been replaced by Java Persistence API entities.
  • When we need EJB
    • If we need to scale our application and handle growing number of user
    • To distribute application in different machines
    • If we need to be sure about data integrity
    • flexible access of shared objects
    • In case of thin client implementation we can use EJB
    • When portability issue arise we will choose EJB as our implementation technology without re thinking

Saturday, June 23, 2012

StAX API in JAVA to Work With XML Info-Set



Streaming API for XML (StAX) is an API to process XML documents. As official documents of StAX

The StAX project was spearheaded by BEA with support from Sun Microsystems, and the JSR 173 specification passed the Java Community Process final approval ballot in March, 2004 (http://jcp.org/en/jsr/detail?id=173). The primary goal of the StAX API is to give "parsing control to the programmer by exposing a simple iterator based API. This allows the programmer to ask for the next event (pull the event) and allows state to be stored in procedural fashion." StAX was created to address limitations in the two most prevalent parsing APIs, SAX and DOM.

--StAX is a pull API
--StAX has bi directional support means it can do both XML reading and writing .

Streaming Vs DOM


There are two models of programming to work with XML infosets : document streaming and document object model (DOM)
In DOM based processing , in memory objects are created to represent entire document as a trree while processing the xml document. Obviously there are memory and processing issues involved with these . If XML document is smaller then we can ignore these issue but if document getting larger then we need to re think about DOM based solution. Though DOM based API gives developer programmatic flexibility but gives some memory and processing overhead.
On the other hand streaming refer to a programming model where xml document are processd serially and in application run time and often from dynamic sources whose contents are not precisely known beforehand. Moreover, stream-based parsers can start generating output immediately, and infoset elements can be discarded and garbage collected immediately after they are used. While providing a smaller memory footprint, reduced processor requirements, and higher performance in certain situations, the primary trade-off with stream processing is that you can only see the infoset state at one location at a time in the document. You are essentially limited to the "cardboard tube" view of a document, the implication being that you need to know what processing you want to do before reading the XML document.
Streaming models for XML processing are particularly useful when your application has strict memory limitations, as with a cellphone running J2ME, or when your application needs to simultaneously process several requests, as with an application server. In fact, it can be argued that the majority of XML business logic can benefit from stream processing, and does not require the in-memory maintenance of entire DOM trees.

Pull Vs Push Style API


In case of pull type programming model application need explicit call to read data from xml info-set means pulling from xml infoset .

But, in case of push parsing model parser API push the data to application when encounter any element in xml infoset.

Pull Parsing Has Some Advantages Over Push Model :

---client has control on application thread
--lees code writing
--can handle multiple documents at ones in a single thread
--StAX parser has filtering capabilities to ignore unwanted elements in xml infoset
--support xml views of non xml data

Reference

http://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/SJSXP2.html



Sample StAX Code To Write XML Document

public void generateXML ()  {

  String generatedXMLAsString = "";

  try {
   XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
   ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
   XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(byteArrayOutputStream);


   xmlStreamWriter.writeStartDocument();
   xmlStreamWriter.writeCharacters("\n\n");

   xmlStreamWriter.writeStartElement("rootElement");
   xmlStreamWriter.writeNamespace("", "http://wwww.example.com/hello");
   xmlStreamWriter.writeCharacters("\n");

   xmlStreamWriter.writeStartElement("childElement");
   xmlStreamWriter.writeCharacters("hello");
   xmlStreamWriter.writeEndElement();
   xmlStreamWriter.writeCharacters("\n");

   xmlStreamWriter.writeEndElement();

   xmlStreamWriter.writeEndDocument();
   xmlStreamWriter.close();

   generatedXMLAsString = new String(byteArrayOutputStream.toString());

   System.out.println(generatedXMLAsString);

   byteArrayOutputStream.close();
  } catch (Exception e) {
   System.out.println(e.getMessage());
  }
 }

Generated XML


hello


Thursday, June 07, 2012

REST with Java (JAX-RS) using Jersey in five minutes


Simple Root Resource Class :
package com.hello.demo;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;


@Path("/hello")
public class Hello  {

 @POST
 @Path("/test")
 @Consumes(MediaType.TEXT_XML)
 @Produces(MediaType.TEXT_XML)
 public String consumeTest (String requestMessage) {
   return requestMessage;
    
 } 
}


Testing this service using Simple REST Client found as chrome extension :
That's it. Try and enjoy.

Wednesday, June 06, 2012

Generate JAVA File from XSD using XJC Tool (JAXB)

Hello world xsd file :






     

 
  
      

 
 

 
  
   
   
   
   
  

 
  
   
   
   
  



Then Initiate the command from command line : Generated class files are :
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 
// See http://java.sun.com/xml/jaxb 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2012.06.06 at 11:37:48 AM ALMT 
//


package com.helloworld;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;


/**
 * 

Java class for anonymous complex type. * *

The following schema fragment specifies the expected content contained within this class. * *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="hackername" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="hackercode" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="expcode" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 * 
* * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "hackername", "hackercode", "expcode" }) @XmlRootElement(name = "Hacker") public class Hacker { @XmlElement(required = true) protected String hackername; @XmlElement(required = true) protected String hackercode; @XmlElement(required = true) protected String expcode; /** * Gets the value of the hackername property. * * @return * possible object is * {@link String } * */ public String getHackername() { return hackername; } /** * Sets the value of the hackername property. * * @param value * allowed object is * {@link String } * */ public void setHackername(String value) { this.hackername = value; } /** * Gets the value of the hackercode property. * * @return * possible object is * {@link String } * */ public String getHackercode() { return hackercode; } /** * Sets the value of the hackercode property. * * @param value * allowed object is * {@link String } * */ public void setHackercode(String value) { this.hackercode = value; } /** * Gets the value of the expcode property. * * @return * possible object is * {@link String } * */ public String getExpcode() { return expcode; } /** * Sets the value of the expcode property. * * @param value * allowed object is * {@link String } * */ public void setExpcode(String value) { this.expcode = value; } }
And :
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 
// See http://java.sun.com/xml/jaxb 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2012.06.06 at 11:37:48 AM ALMT 
//


package com.helloworld;

import javax.xml.bind.annotation.XmlRegistry;


/**
 * This object contains factory methods for each 
 * Java content interface and Java element interface 
 * generated in the com.helloworld package. 
 * 

An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.helloworld * */ public ObjectFactory() { } /** * Create an instance of {@link Hacker } * */ public Hacker createHacker() { return new Hacker(); } }

And final one :
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 
// See http://java.sun.com/xml/jaxb 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2012.06.06 at 11:37:48 AM ALMT 
//

@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.helloworld.com", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.helloworld;




Sunday, June 03, 2012

Introduction to XML Path Language (XPATH)

XPath is a W3C recommendation.
XPath is a language to navigate through different parts of xml document,designed to be used bu both XSLT and XPointer.
Simple way to use XPath with java .

The XML file need to read : hello.xml



Asraful
24
Male



Rid
22
Male



Tina
19
Female


And , Hear is the java code to read the file named : hello.xml
package com.thinktank.rnd.se.pattern.xml;


import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

public class XMLReadWrite {
    public static void main(String args[]) throws Exception {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

        documentBuilderFactory.setNamespaceAware(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        Document document = documentBuilder.parse("hello.xml");

        XPath xPath = XPathFactory.newInstance().newXPath();

        XPathExpression expr = xPath.compile("//person/*/text()");

        Object result = expr.evaluate(document, XPathConstants.NODESET);

        NodeList nodes = (NodeList) result;

        for (int i = 0; i < nodes.getLength(); i++) {
            System.out.println(nodes.item(i).getNodeValue());
        }

    }

}

Finally Output of the code :

Asraful
24
Male
Rid
22
Male
Tina
19
Female