Sunday, January 26, 2014

Java Code

1. Reverse a String:

/**
 *
 */
package perform;

/**
 * @author Sai Saripalli
 *
 */
public class ReverseString {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

String str= "abcedf";
int lastIndex = str.length() -1;
char[] cha= str.toCharArray();
//System.out.println(cha.length);

for(int i=0; i<=lastIndex/2; i++){
cha = swap(cha, i, lastIndex-i);
}

for(int i=0;i<cha.length;i++)
System.out.println(cha[i]);
}
 System.out.println(String.valueOf(cha));

public static char[] swap(char[] cha, int x, int y){
char z= cha[x];
cha[x]=cha[y];
cha[y]= z;
return cha;
}

}

Monday, October 14, 2013

Get started with Maven

Create Maven web project
$mvn archetype: generate -DgroupId=com.mycompany.app -DartifactId=my-webapp -DarchetypeArtifactId=maven-archetype-webapp
Overview of POM.XML :
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <!-- The Basics -->
  <groupId>...</groupId>
  <artifactId>...</artifactId>
  <version>...</version>
  <packaging>...</packaging>
  <dependencies>...</dependencies>
  <parent>...</parent>
  <dependencyManagement>...</dependencyManagement>
  <modules>...</modules>
  <properties>...</properties>

  <!-- Build Settings -->
  <build>...</build>
  <reporting>...</reporting>

  <!-- More Project Information -->
  <name>...</name>
  <description>...</description>
  <url>...</url>
  <inceptionYear>...</inceptionYear>
  <licenses>...</licenses>
  <organization>...</organization>
  <developers>...</developers>
  <contributors>...</contributors>

  <!-- Environment Settings -->
  <issueManagement>...</issueManagement>
  <ciManagement>...</ciManagement>
  <mailingLists>...</mailingLists>
  <scm>...</scm>
  <prerequisites>...</prerequisites>
  <repositories>...</repositories>
  <pluginRepositories>...</pluginRepositories>
  <distributionManagement>...</distributionManagement>
  <profiles>...</profiles>
</project>

What is groupId in maven ?
groupId identifies a particular project uniquely across all projects, so we should follow an naming convention. A very simple and commonly used way of doing this is to use reverse of your domain,

A good way of maintaining the integrity of groupId is to use the project structure. In case the project is consists of multiple modules than every module should append an identifier to the parent groupId. i.e. com.beingjavaguys.maven, com.beingjava guys. Spring, com.beingjavaguys.struts .. etc.
What is artifactId in maven?
ArtifactId is the name of war file without version, if you are creating it by yourself you are free to took any name of your choice in lower case and without any strange symbol. But if this is a third party jar than we have to take the name of jar as suggested by it’s distribution.

What is archetype in maven?
Archetype is a Maven project templating toolkit which tells the maven the type of project we are going to create. Archetype enables the maven to create a template project of user’s choice so that the user can get the project up and running instantly.
“archetype: generate” generates a new project from provided archetype or update the actual project if using a partial archetype. Maven provides a number of predefined archetypes, see more from
.

What is archetype ArtifactId in maven?
While creating a new project we provide the archetype. ArtifactId that informs maven about what archetype to use to create the initial structure of the project. Maven looks it up from the archetype Catalog and works accordingly. E.g. If we want to create a simple web-app project we specify -DarchetypeArtifactId=maven-archetype-webapp.
Maven java docs:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-source-plugin</artifactId>
  <executions>
    <execution>
      <id>attach-sources</id>
      <goals>
        <goal>jar</goal>
      </goals>
    </execution>
  </executions>               
</plugin>

         <plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-javadoc-plugin</artifactId>
  <executions>
    <execution>
      <id>attach-javadocs</id>
      <goals>
        <goal>jar</goal>
      </goals>
    </execution>
  </executions>
</plugin>
To download and attach java Doc from command line
     mvn eclipse:eclipse -DdownloadSources=true  -DdownloadJavadocs=true

Directory Structure:
<!-- Directory Structure -->
             <directory>${project.basedir}/target</directory>
              <outputDirectory>${project.build.directory}/classes</outputDirectory>
              <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
              <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
              <finalName>SpringMVCDemo</finalName>
             <!-- TODO: MNG-3731 maven-plugin-tools-api < 2.4.4 expect this to be relative... -->
              <scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
              <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
             <resources>
                   <resource>
                        <directory>${project.basedir}/src/main/resources</directory>
                    </resource>
              </resources>
              <testResources>
                    <testResource>
                          <directory>${project.basedir}/src/test/resources</directory>
                     </testResource>
              </testResources>

              <!-- Maven Tomcat -->
              <plugin>
                     <groupId>org.apache.tomcat.maven</groupId>
                      <artifactId>tomcat7-maven-plugin</artifactId>
                       <version>${tomcat7-maven-version}</version>
                        <configuration>
                             <url>http://localhost:8080/manager/text</url>
                              <server>TomcatServer</server>
                         </configuration>
                </plugin>

Inheritance and Polymorphism


Quick Snapshot:

  • It is concept of making class use the properties and methods of another class while adding its own functionality.
  • It provides software re-usability.
  • Provides extensibility without disturbing existing features.
  • In java the keyword extends is used to establish the relationship between superclass and subclass to have inheritance. 
  • When you design with inheritance, you put common code in a class and then tell other more specific classes that the common (more abstract) class is their superclass. 
  • When one class inherits from another, the subclass inherits from the superclass.
  •  In Java, we say that the subclass extends the superclass. 
  • An inheritance relationship means that the subclass inherits the members of the superclass. 
  • When we say “members of a class” we mean the instance variables and methods.
  • super  keyword is used to access immediate super class shadowed variables. super.super is not valid.

Overriding and Polymorphism  

public class TestAnimals {
public static void main (String [] args) {
          Animal a = new Animal();
          Animal b = new Horse(); //Animal ref, but a Horse object
          a.eat(); // Runs the Animal version of eat()
         b.eat(); // Runs the Horse version of eat()
      }
}
class Animal {
     public void eat() {
         System.out.println("Generic Animal Eating Generically");
    }
}
class Horse extends Animal {
    public void eat() {
            System.out.println("Horse eating hay, oats, "+ "and horse treats");
    }
     public void buck() { }
}

In the preceding code, the test class uses an Animal reference to invoke a method
on a Horse object. Remember, the compiler will allow only methods in class Animal
to be invoked when using a reference to an Animal. The following would not be
legal given the preceding code:
Animal c = new Horse();
c.buck(); // Can't invoke buck(); // Animal class doesn't have that method 

 The rules for overriding a method are as follows:

  • The argument list must exactly match that of the overridden method. If they don't match, you can end up with an overloaded method you didn't intend.
  • The return type must be the same as, or a subtype of, the return type declared in the original overridden method in the superclass. (More on this in a few pages when we discuss covariant returns.)
  • The access level can't be more restrictive than the overridden method's.
  • The access level CAN be less restrictive than that of the overridden method.
  • Instance methods can be overridden only if they are inherited by the subclass.
  • A subclass within the same package as the instance's superclass can override any superclass method that is not marked private or final. A subclass in a different package can override only those non-final methods marked public or protected (since protected methods are inherited by the subclass).
  • The overriding method CAN throw any unchecked (runtime) exception, regardless of whether the overridden method declares the exception
  • The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException.
 Example:        
class A {
   public void foo() throws IOException {..}
}

class B extends A {
   @Override
   public void foo() throws SocketException {..} // allowed

   @Override
   public void foo() throws SQLException {..} // NOT allowed
}
SocketException extends IOException, but SQLException does not.
  •  The overriding method can throw narrower or fewer exceptions. Just because an overridden method "takes risks" doesn't mean that the overriding subclass' exception takes the same risks. Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of what the overridden method declares.
  • You cannot override a method marked final.
  • You cannot override a method marked static. We'll look at an example in a few pages when we discuss static methods in more detail.
  • If a method can't be inherited, you cannot override it. Remember that overriding implies that you're reimplementing a method you inherited! For example, the following code is not legal, and even if you added an eat() method to Horse, it wouldn't be an override of Animal's eat() method. 

Important Note

If a method is overridden but you use a polymorphic (supertype) reference to refer to the subtype object with the overriding method, the compiler assumes you’re calling the supertype version of the method. If the supertype version declares a checked exception, but the overriding subtype method does not, the compiler still thinks you are calling a method that declares an exception Let’s take a look at an example:
class Animal {
public void eat() throws Exception {
// throws an Exception
}
}
class Dog2 extends Animal {
public void eat() { /* no Exceptions */}
public static void main(String [] args) {
Animal a = new Dog2();
Dog2 d = new Dog2();
d.eat(); // ok
a.eat(); // compiler error -
// unreported exception
}
}
This code will not compile because of the Exception declared on the Animal eat() method. This happens even though, at runtime, the eat() method used would be the Dog version, which does not declare the exception.  

Reason:

At compile time, the compiler doesn't know if the 'a' reference is referring to a Dog2 object or an Animal object. This will not be determined until runtime. Since the reference type of 'a' is Animal, the compiler assumes that the a.eat() method invocation is on an Animal object. The main() method must either throw an Exception exception object in its method declaration or it must 'catch' an Exception exception object when invoking the a.eat() method. That is it must 'Duck or Catch' the exception thrown by the Animal class a.eat() method. The compiler doesn't know that the Dog2 eat() method is invoked polymorphically, because this happens at runtime. The compiler only knows that the a.eat() method is invoked on an Animal reference at compile time. The compiler enforces the 'Duck or Catch' requirement for exception handling.  

Solution:

 class Animal {
        public void eat() throws Exception {
            // throws an Exception
        }
}
class Dog2 extends Animal {
          public void eat() { // no Exceptions declared  }
         public static void main (String [] args) throws Exception {
                Animal a = new Dog2();
                Dog2 d = new Dog2();
               d.eat();        // ok
               a.eat();        // no compiler error -
}


Random Snippets in Core Java

                       
 1. The ?: operator in java

    if (a>b)
          val=a;
    else
          val=b;
The above can be written as val = (a>b) ? a: b
Note: the types you are comparing and the types you're assigning must be same e.g if a and b are int (a>b) then val must be int

Tuesday, October 8, 2013

Java Interfaces


Inner Interfaces:
Declaring an interface inside another interface. We can take Entry interface declared in Map interface as an example.

One example of inner interface used in java standard library is java.util.Map and Java.util.Map.Entry. Here java.util.Map is used also as a namespace. Entry does not belong to the global scope, which means there are many other entities that are Entries and are not necessary Map’s entries. This indicates that Entry represents entries related to the Map.
 
Sample Code:
public interface Map {
 interface Entry{
  int getKey();
 }
 
 void clear();
}
 
Why Use Inner Interface?
There are several compelling reasons for using inner interface:
  • It is a way of logically grouping interfaces that are only used in one place.
  • It increases encapsulation.
  • Nested interfaces can lead to more readable and maintainable code
 

Wednesday, July 24, 2013

Java Standalone JMS-JNDI Application

How to Connect to ActiveMQ
1. create jndi properties file
2. load the jndi properties file and read the JMS JNDI connection attributes
3. Instantiate the connection and send a request through a Producer Application
4. Consume messages using Consumer Application.

The Following below application takes an xml and xsd as input, performs validation on a logic and places the messages in a JMS Queue. The consumer application consumes the messages and writes them to a folder location in the path of the given xml leaf nodes.

1. JNDI Properties File
#ActiveMQ Connection Settings
# contextFactory
java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory

# use the following property to configure the default connector
java.naming.provider.url = vm://localhost

# use the following property to specify the JNDI name the connection factory
# should appear as. 
#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry
connectionFactoryNames = queueConnectionFactory
# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
queue.sai = FOO_BAR

#org.apache.activemq.ActiveMQConnectionFactory=myQueueConnectionFactory
# register some topics in JNDI using the form
# topic.[jndiName] = [physicalName]
#topic.MyTopic = example.MyTopic


2. JNDI Lookup Java Class

public class JndiLookup {

    private static Properties jndiProperties = null;
    private static Context ctx = null;
    private static Logger LOG = LoggerFactory.getLogger(JndiLookup.class);
    private static final JndiLookup jndiLookUp = new JndiLookup();

    private JndiLookup() {
        
    }

    public static JndiLookup getInstance() {
        return jndiLookUp;
    }
       
    public void loadProperties() throws Exception {
        try {
            jndiProperties = new Properties();
            LOG.info("Loading properties file");
            loadFromResourceBundle();
        } catch (final Exception ex) {
            throw ex;
        }
    }

    private void loadFromResourceBundle() throws Exception {
        String key = null;
        String value = null;
        ResourceBundle rb = ResourceBundle.getBundle(LoadConstants.jndi_properties);

        Enumeration enum1 = rb.getKeys();
        while (enum1.hasMoreElements()) {
            key = enum1.nextElement().toString();
            value = rb.getString(key);
            LOG.info("Key: " + key + "Value :" + value);
            // LOG.info(value);
            jndiProperties.put(key, value);
        }
    }

    public void connectToJNDI() throws javax.naming.NamingException {

        // jndiProperties was loaded from PropertiesManagement.properties
        ctx = new InitialContext(jndiProperties);
       
        LOG.info("Connected to Provider URL " + ctx.getEnvironment().get(Context.PROVIDER_URL));
        LOG.info("Connected to INITIAL CONTEXT Factory " +             ctx.getEnvironment().get(Context.INITIAL_CONTEXT_FACTORY));
        
    }

    public QueueConnectionFactory lookupQueueConnectionFactory() throws   javax.naming.NamingException {

        Enumeration enum1=jndiProperties.keys();
        while (enum1.hasMoreElements()) {
           String key = enum1.nextElement().toString();
           String value = (String) jndiProperties.get(key);
            LOG.info(" Key: " + key + " Value :" + value);
    }
        LOG.info("Key in lookupQueueConnectionFactory " + jndiProperties.get("java.naming.factory.initial").toString());
        return (QueueConnectionFactory) ctx.lookup("queueConnectionFactory");

    }

    public Queue lookupQueue() throws javax.naming.NamingException {
        return (Queue) ctx.lookup("sai");
    }
    
    public String getUserName() throws javax.naming.NamingException{
        return ctx.lookup("username").toString();
    }
    
    public String getPassword() throws javax.naming.NamingException{
        return ctx.lookup("password").toString();
    }
}

3. ProducerImpl.java

public class ProducerImpl {

    private static Logger LOG = LoggerFactory.getLogger(ProducerImpl.class);

    private static QueueConnectionFactory queueConnectionFactory = null;
    private static QueueSession queueSession = null;
    private static QueueConnection queueConnection = null;
    private static MessageProducer producer = null;
    private static Queue queue;
    private static TextMessage message;
    private static File xsdFile;
    private static File xmlFile;

    /**
     * Default Constructor
     */
    public ProducerImpl() {
        DOMConfigurator.configure(LoadConstants.SLF4JPATH);
        xsdFile = new File(ProducerImpl.class.getResource(LoadConstants.INPUT_XSD).getFile());
        xmlFile = new File(ProducerImpl.class.getResource(LoadConstants.INPUT_XML).getFile());
    }

    public static void main(String[] args) throws Throwable {
        // TODO Auto-generated method stub
        // send message
         ProducerImpl producerImpl = new ProducerImpl();
         producerImpl.produceMessages();
    }

    /**
     * This method will send messages to Queue only if given xmlfile is valid.
     * else it logs the invalid xml message and closes the queue connection.
     * 
     * @throws Throwable
     */
    public void produceMessages() throws Throwable {
        try {
            if (DotPathUtil.getNewInstance().validate(xmlFile, xsdFile)) {
                String xmlString = DotPathUtil.convertXMLFileToString(xmlFile);

                // Get the Connection using JNDI
                getConnection();

                // create queue session using JNDI
                queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

                // get queue name using JNDI lookup
                queue = JndiLookup.getInstance().lookupQueue();

                LOG.info("sending valid xml message.....");

                // create the producer
                producer = queueSession.createProducer(queue);

                // create the message
                message = queueSession.createTextMessage(xmlString);

                // send the message
                producer.send(message);
                LOG.info("valid xml message sent.....");

            } else {
                // else log the invalid message
                LOG.info("Logging the Invalid Message");
                String xmlString = DotPathUtil.convertXMLFileToString(xmlFile);
                // print the invalid message
                LOG.info(xmlString);
            }
            xmlFile = null;
            xsdFile = null;

            LOG.info("Program Ended");

        } catch (Exception e) {

            e.printStackTrace();
        } finally {
            if (queueSession != null && queueConnection != null) {
                queueSession.close();
                queueConnection.close();
            }
        }
    }

    /**
     * This method creates the connection using the JNDI lookup.
     * 
     * @throws Throwable
     */
    public static void getConnection() throws Throwable {
        try {
            JndiLookup.getInstance().loadProperties();
            JndiLookup.getInstance().connectToJNDI();
            queueConnectionFactory = JndiLookup.getInstance().lookupQueueConnectionFactory();
            //queueConnection = queueConnectionFactory.createQueueConnection(JndiLookup.getInstance().getPassword(),JndiLookup.getInstance().getPassword());
            queueConnection = queueConnectionFactory.createQueueConnection();
        } catch (final Throwable ex) {
            throw ex;
        }
    }
}


3. ConsumerApplication

public class ConsumerImpl{

    private static Logger LOG = LoggerFactory.getLogger(ConsumerImpl.class);
    private static QueueReceiver queueReceiver = null;
    private static QueueSession queueSession = null;
    private static QueueConnection queueConnection = null;
    private static QueueConnectionFactory queueConnectionFactory = null;
    private static TextMessage message=null;
    private static File xsdFile=null;

    public ConsumerImpl() {
        DOMConfigurator.configure(LoadConstants.SLF4JPATH);
        xsdFile = new File(ConsumerImpl.class.getResource(LoadConstants.INPUT_XSD).getFile());
    }

    /**
     * This method consumes the
     * 
     * @throws JMSException
     */
    public void consumeMessage() throws JMSException {
        try {
            JndiLookup.getInstance().loadProperties();
            JndiLookup.getInstance().connectToJNDI();
            queueConnectionFactory = JndiLookup.getInstance().lookupQueueConnectionFactory();

            queueConnection = queueConnectionFactory.createQueueConnection();
            queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

            queueReceiver = queueSession.createReceiver(JndiLookup.getInstance().lookupQueue());
            LOG.info("QUEUE Obtained" + queueReceiver.getQueue().getQueueName());
            queueConnection.start();

            while (true) {
                Message m = queueReceiver.receive(1);
                if (m != null) {
                    if (m instanceof TextMessage) {
                        message = (TextMessage) m;
                        LOG.info("Consuming message: " + message.getText());
                        if (DotPathUtil.getNewInstance().validate(message.getText(), xsdFile))
                            DotPathUtil.createFile(message.getText(), xsdFile);
                    } else {
                        break;
                    }
                }
            }
            xsdFile = null;
            LOG.info("Program Ended");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            queueReceiver.close();
            queueSession.close();
            queueConnection.close();
        }
    }
}

4. Utility Java DotPath Class which performs validation of given XML. This java class is common utility class which performs validation for placing the messages in the queue and also peforming XML validation after consuming messsages from the queue.

public class DotPathUtil implements DotPath {

    private static Logger LOG = LoggerFactory.getLogger(DotPathUtil.class);
    private static String root = System.getProperty("user.dir") + "\\";
    private static final DotPathUtil dotPathUtil = new DotPathUtil();
    private static StringBuilder sb = new StringBuilder();
    private static ArrayList<StringBuilder> al = new ArrayList<StringBuilder>();

    private DotPathUtil() {

    }

    public static void createFile(String str, File xsdFile) throws FileNotFoundException, XPathExpressionException, SAXException, IOException, ParserConfigurationException, JMSException {

        boolean createdDir = false;
        FileOutputStream fop = null;

        try {
            getPaths(str);
            LOG.info("reading the xml: " + str);
            Format timestamp = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.Z");
            for (int i = 0; i < al.size(); i++) {
                File directory = new File(al.get(i).toString());
                if (!directory.exists()) {
                    createdDir = directory.mkdirs();
                    if (createdDir)
                        LOG.info("Directory created " + directory.getAbsolutePath());
                    LOG.info("Creating File in newly created directory");
                    // fw = new FileWriter(directory + "\\"+
                    // timestamp.format(new Date()) + ".txt");
                    fop = new FileOutputStream(directory + "\\" + timestamp.format(new Date()) + ".txt");

                    byte[] stringContentInBytes = str.getBytes();
                    /*
                     * br = new BufferedReader(new FileReader(str)); String inp;
                     * while ((inp = br.readLine()) != null)
                     */
                    // fw.write(stringContentInBytes + "\n");
                    fop.write(stringContentInBytes);
                    fop.flush();
                    fop.close();
                    LOG.info("File Written successfully at: " + directory.getAbsolutePath());
                } else {
                    LOG.info("Creating File in already existing directory");
                    fop = new FileOutputStream(directory + "\\" + timestamp.format(new Date()) + ".txt");
                    byte[] stringContentInBytes = str.getBytes();
                    fop.write(stringContentInBytes);
                    fop.flush();
                    fop.close();
                    LOG.info("File Written successfully at: " + directory.getAbsolutePath());
                }
            }
            LOG.info("Files Written successfully");
            //sb=new StringBuilder();
        } catch (SAXException | ParserConfigurationException | IOException | JMSException e) {
            e.printStackTrace();
        } finally {
            if(fop!=null)
              fop.close();
        }
    }

    public static InputStream getInputStream(String str) throws JMSException {

        InputStream inputStream = new ByteArrayInputStream(str.getBytes());
        return inputStream;
    }

    public static void getPaths(String str) throws FileNotFoundException, SAXException, IOException, ParserConfigurationException, JMSException {
        // StringBuilder sb = new StringBuilder();
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(getInputStream(str));
        // LOG.info(document.getDocumentElement());
        if(sb!=null)
            sb=new StringBuilder();
        getChildPath(document.getChildNodes());
        

        // return sb.toString();
    }

    public static void getChildPath(NodeList nodeList){
        
        //for(int j=0;j<nodeList.getLength();j++)
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node currentNode = nodeList.item(i);
            System.out.println("CurrentNode name: "+ currentNode);
            if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
                if (currentNode.getNodeName().trim().equalsIgnoreCase("root"))
                { 
                    System.out.println(sb);
                    sb.append(root);
                }
                else{ 
                    if(!currentNode.hasChildNodes()){
                        StringBuilder sb1= new StringBuilder();                
                        al.add(sb1.append(sb+ currentNode.getNodeName() +"\\") );
                        System.out.println("In Leaf Node " +sb1);
                    }
                    else{
                        
                        sb.append(currentNode.getNodeName() + "\\");
                        System.out.println(sb);
                    } 
                }    
                    
                getChildPath(currentNode.getChildNodes());
            }
        }
    }

    public static String getPath(String str) throws FileNotFoundException, SAXException, IOException, ParserConfigurationException, XPathExpressionException, JMSException {
        StringBuilder sb = new StringBuilder();
        try {
            LOG.info("in getPath >" + str + "<");
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(getInputStream(str));
            NodeList nl = document.getChildNodes();
            LOG.info("Childs :" + nl.getLength());
            for (int i = 0; i < nl.getLength(); i++) {
                Node n = nl.item(i);
                if (n.getNodeType() == Node.ELEMENT_NODE) {
                    if (n.getNodeName().trim().equalsIgnoreCase("root"))
                        sb.append(root + "\\");
                    else
                        sb.append(n.getNodeName() + "\\");
                    nl = n.getChildNodes();
                    i = -1;
                }
            }

            // return sb.toString();
        } catch (SAXException | ParserConfigurationException | IOException | JMSException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    @Override
    public boolean validate(String str, File xsdFile) {

        boolean isValid = false;

        try {
            // Create source objects for XML and XSD files
            Source xmlSource = new StreamSource(DotPathUtil.getInputStream(str));
            Source xsdSource = new StreamSource(xsdFile);

            // Create SchemaFactory using XSD file
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(xsdSource);

            // Validator will use xsd file for validating the XML file
            Validator validator = schema.newValidator();

            // Validate the DOM tree.
            validator.validate(xmlSource);

            isValid = true;

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (isValid == true)
            LOG.info("Document is valid!");
        else
            LOG.info("Document is NOT valid!");

        return isValid;
    }

    @Override
    public boolean validate(File xmlFile, File xsdFile) {
        // TODO Auto-generated method stub
        boolean isValid = false;

        try {
            // Create source objects for XML and XSD files
            Source xmlSource = new StreamSource(xmlFile);
            Source xsdSource = new StreamSource(xsdFile);
            // Create SchemaFactory using XSD file
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(xsdSource);

            // Validator will use xsd file for validating the XML file
            Validator validator = schema.newValidator();

            // Validate the DOM tree.
            validator.validate(xmlSource);
            isValid = true;

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (isValid == true)
            LOG.info("Document is valid!");
        else
            LOG.info("Document is NOT valid!");

        return isValid;
    }

    public static String convertXMLFileToString(File xmlFile) throws SAXException, ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException, IOException {
        try {
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new FileInputStream(xmlFile));
            StringWriter stw = new StringWriter();
            Transformer serializer = TransformerFactory.newInstance().newTransformer();
            serializer.transform(new DOMSource(document), new StreamResult(stw));
            return stw.toString();
        } catch (SAXException | ParserConfigurationException | TransformerFactoryConfigurationError | IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static DotPathUtil getNewInstance() {
        return dotPathUtil;
    }

}