Java Volatile Keyword Working concept | what use of Volatile keyword in Multithreading

When a shared variable is  accessed by multiple threads , think about volatile keyword  .  When a field  is accessed by multiple threads , one thread’s changes to the field should be  visible to another thread. How it is possible ?.     The following tutorial covers about

  1. What volatile keyword indicates ?
   2. Why volatile keyword is required?
   3. When to use volatile modifier?
   4. How volatile works in java?  .

1. What volatile keyword indicates ?
  The volatile keyword indicates that a field can be  be modified by multiple threads that are executing simultaneously.  If a field is declared as volatile,  then the Java Memory Model  (JMM 133 , from java 5 )   ensures that all threads see a consistent value for the variable.

2. Why volatile keyword is required?

      Some of the following  reasons exist for  why the changes of a field  made by  one thread  is not communicated to another thread immediately  (i.e any thread  does not see the  most up-to-date value of  the field at any time)
               :
 a) Reordering of statements : Compiler optimizations are very important on modern platforms.  Instructions are  reordered by the compiler  to achieve maximum performance .   Due to this , instructions are  frequently not executed in the order it was written. At the same time , system needs to  maintain  as-if-serial semantics for individual threads. This works well in a single-threaded environment. i.e when a single thread executes, the result will appear as if all of the actions performed by that thread occur in the order they appear in the original program. But when multiple thread involves , the statement reordering done for a single thread  may be  out of order for other threads  which causes surprising results. Similarly  Processor and  caches  are allowed to reorder.

b) Thread may keep values in  local registers instead of shared memory whenever possible . So threads may see different values for shared variables.

c) On multiprocessor architectures, each processor may have own local caches to store shared variables  that are out of sync with main memory .

 One  solution to the above problem is Synchronization . Synchronization ensures both
    1. Visibility .  (any thread  sees the  most up-to-date value of  the field at any time)
    2. Mutual exclusion  (prevents methods / block of statements  from being executed concurrently)  . For more on synchronization , you can visit my earlier tutorial , Synchronization in java

 Another solution will be volatile modifier   It ensures the visibilty  of a  field  between threads i.e  any thread that reads the variable will see the last  written value   and it does not perform mutual exclusion  ie. it allows  methods /  block of codes to  be executed simultaneously by two or more threads.

3. When to use volatile modifier
                     
Some of the examples given below will give you clear  idea about when to use volatile
Example 1




class Reorder1 {

static   int value = 0;

static  boolean flag;



static   void one() {

    value = 100;

    flag = true;



       }



static void two() {

    if ( flag == true )

     System.out.println("Value " + value);



       }
In the above code , compiler is free to  reorder of statements as given below  as  statements value = 100; , flag = true; have  no dependency.



static   void one() {

    flag = true;

    value = 100;

 }

When the above code is executed by a single thread , calling  one() & two() methods  will give the output 100. When multiple threads execute the above methods simultaneously , the result may go wrong. When one thread execute the line flag=true , and another thread executes  the line
                       if ( flag == true )
                       System.out.println("Value " + value);
Now the result will be 0 .   One solution is to synchronize the above methods .   It  prevents method one and method two from being executed concurrently and also prevents reordering. Another solution is to declare  the field flag as   volatile   . Volatile read and write operations  can not be reordered with each other or  with respect to nonvolatile variable accesses

Example 2



 public static  PrimaryKeyGenerator getInstance()

   {

            if (instance == null)

       {

        synchronized(PrimaryKeyGenerator.class)

         {

           if (instance == null) 

             {

             instance = new PrimaryKeyGenerator();

               }

           }

        }

         return instance;      } 

The  above code is called double-checked locking idiom which implements singleton pattern suitable for  multithreaded environment and  also supports lazy initialization by  avoiding the overhead of synchronization.  But the above code does not work as expected due to  the reordering of  the  initialization of instance and the write to the instance field by the compiler . Suppose two threads execute the above code simultaneously .  The first thread  writes to instance variable first then  the object is constructed.  In the meantime , the second thread reads the instance field which is not null  before the first thread  finishes the construction of object.  So the second thread returns the incomplete object of  PrimaryKeyGenerator . We can fix  this problem with  Double-Checked Locking by declaring the instance field  volatile,  which prevents  reordering.

Example 3



class  WorkerOwnerThread

{

 // field is accessed by multiple threads.

 private static boolean  stopSignal;



  private static  void  doWork()

    {

        while (!stopSignal)

        {

           Thread t = Thread.currentThread(); 

           System.out.println(t.getName()+ ": I will work until i get STOP signal from my Owner...");

        }

         System.out.println("I got Stop signal . I stop my work");

    }



   private static   void stopWork()

    {

       stopSignal = true;

       Thread t = Thread.currentThread(); 

       System.out.println("Stop signal from " + t.getName()  );

    }

 

 

public static void main(String[] args) throws InterruptedException {



Thread workerThread = new Thread(new Runnable() {

      public void run() {

             doWork();    }

       });

workerThread.setName("Worker");

workerThread.start();



//Main thread

Thread.sleep(100);

stopWork();

}

}

The above code is another example for  when to use volatile modifier.  Two threads  Worker thread and Main thread are involved.  Worker thread starts and running continousely until it gets stop signal from the main thread.  This situation is a common use case for volatile.

  Under the new memory model (from JLS7), when one thread  writes to a volatile variable V, and thread B reads from V, any variable values that were visible to A at the time that V was written are guaranteed now to be visible to B. Here stopSignal is volatile variable. The changes made by the main thread to the stopSignal variable is communicated to Worker thread immediately.

 In the above code , if we synchronize  both methods doWork() and stopWork() instead of using volatile variable , if the worker thread starts first , then it  never stops . As synchronization performs mutual exclusion , when  the worker thread starts first  , the main thread never gets chance to update  stopSignal = true.  So declaring the stopSignal field as volatile is the  good solution.


4. How volatile works in java?

                                             1. The reads and writes of volatile fields  is made directly to main memory, instead of  to registers or the local processor cache.  This ensures that all the threads see the the most  recent written  value of  the field at all times        
               2. Fields that are declared volatile are not subject to compiler optimizations. ie. the reads and writes of volatile variables  can  not be reordered  with each other or  with respect to nonvolatile variable accesses.  A write to a volatile field happens-before every subsequent read of that same volatile.


Some of the key points about volatile keyword 

1. The volatile modifier is applied  to a field that is accessed by multiple threads without using the lock

2. Writes and reads of long and double variables declared as volatile are always atomic

2. The volatile keyword can not be applied to local variable

3.  final variable can not be a volatile.

4.  volatile modifier performs no mutual exclusion

5. Object variable declared as  volatile can be null .

6.  Reads and writes operations of volatile variables can not be reordered with each other  respect to each other or with respect to nonvolatile variable accesses

7. A write to a volatile field happens before every subsequent read of that same volatile

    Note : volatile is not the alternative to synchronization .

You can visit my another post for Difference between volatile and synchronized keyword 

How to create XML in java using DOM parser | XML with Java


This tutorial covers about how to create a XML file using DOM Parser in Java and also covers that how to indent an XML using java . XML is made up of Elements . You can visit my earlier tutorial for more on XML and How to traverse / parse an XML . DOM allows a developer to create objects like root , child elements , comments and text nodes, etc . Document interface have the factory methods to create these objects. Elements are represented by Element interface , can have other elements , text, attributes . Document and Element interface inherit Node interface which is the primary datatype for the DOM.

Some of the methods of Document & Element interface to create XML are as follows .
1. createElement(String tagName) : creates an element using the tagname in the document.
2. createComment(String data) : to create comment node of the given string
3. createTextNode(String data) : to create a Text node of the given string.
4. setAttribute(java.lang.String name, java.lang.String value) : method of Element that adds a new attribute to the element.
5. appendChild(Node newChild) : method of Element inherited from Node which is used to add the child element node

The following is the sample e-mail in XML format .
  <?xml version="1.0" encoding="utf-8" standalone="no"?><email>   <!--Sample XML format of Email -->   <subject>Message from TechLabs</subject>   <from>j2eeforum@rediffmail.com</from>   <fromdisplay>TechLabs</fromdisplay>   <receipients>      <receipient role="to">         <email-id>vkj@xyz.com</email-id>         <display>VKJ</display>      </receipient>   </receipients>   <bodytext>Hope this URL will help you to learn about  how to create XML using DOM.</a></bodytext>   <signature>Administrator</signature></email>

 Steps to create an XML using DOM . There are no fixed steps to create XML. I have used the following steps to create the above Email XML.
1. Create a Document to put DOM tree
2. Create the root element of the document . Add attribute and comments of root element if required
3. Create child element of the root element, and add attribute and comments of child
4. Add text node to the child elements
5. Create a Transformer to transform a source tree from the memory into a result which may be DOMResult , SAXResult or StreamResult. StreamResult is constructed from a file , string writer , outputstream , etc..

To indent of an XML , the following statements are used using the transformer object.
transformer.setOutputProperty(OutputKeys.INDENT, "yes");transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");   
 Java 5 transformer may not give the expected result with the indenting request due to bugs in Java 5.

You will get the clear idea when you create the above Email XML with the following code.
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

public class CreateDomXml {
public static void main (String args[]) {
createDomXml();
}

public static void createDomXml() {
try {
//to create document to put DOM tree.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();

//to create root element email
Element root = doc.createElement("email");
doc.appendChild(root);

//to create comment
Comment comment = doc.createComment("Sample XML format of Email ");
root.appendChild(comment);

Element subject = doc.createElement("subject");
root.appendChild(subject);

Text subText = doc.createTextNode("Message from TechLabs");
subject.appendChild(subText);

//to create child element from and text node of that element
Element from = doc.createElement("from");
root.appendChild(from);
Text fromText = doc.createTextNode("j2eeforum@rediffmail.com");
from.appendChild(fromText);

Element fromdisplay = doc.createElement("fromdisplay");
root.appendChild(fromdisplay);
Text fromdisplayText = doc.createTextNode("TechLabs");
fromdisplay.appendChild(fromdisplayText);

Element receipients = doc.createElement("receipients");
root.appendChild(receipients);

Element receipient = doc.createElement("receipient");
receipients.appendChild(receipient);
receipient.setAttribute("role", "to"); // to create attribute with value

Element email_id = doc.createElement("email-id");
receipient.appendChild(email_id);
Text emailidText= doc.createTextNode("vkj@xyz.com");
email_id.appendChild(emailidText);

Element disp = doc.createElement("display");
receipient.appendChild(disp);
Text dispText= doc.createTextNode("VKJ");
disp.appendChild(dispText);

Element bodytext = doc.createElement("bodytext");
root.appendChild(bodytext);
Text bodytextText = doc.createTextNode("Hope this URL will help you to learn about how to create XML using DOM.");
bodytext.appendChild(bodytextText);

Element sign= doc.createElement("signature");
root.appendChild(sign);
Text signText = doc.createTextNode("Administrator");
sign.appendChild(signText);

//to create transformer
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");

//to include the xml declaration line <?xml version="1.0" encoding="utf-8" standalone="no"?>
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");

//for indent of XML
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");

// to write into a file
// String fileName= "D://as2/jf6/email1.xml";
// StreamResult result = new StreamResult(new File(fileName));

DOMSource source = new DOMSource(doc);

//to write as a string
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
transformer.transform(source, result);
//System.out.println("XML file saved " + fileName);

String xmlString = sw.toString();
System.out.println("Email XML \n\n " + xmlString);

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

Implements MD5 hashing for Encryption and Decryption in c# | Use of MD5 in WCF

MD5 (Message-Digest algorithm 5) is a most popular Cryptographic Hash Function which is 128 bit encryption algorithm . This is way One-Way Encryption.

1. Client Side Encryption > here we have use Rondom number so that every time password will travel with different
    so that no can track or guess

      static string sltChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        static  string password = "";
        private static string cryptoKey = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        private static void Validate(string Crew3Ltr, string SeriveName)
        {
            password = "aBcc@T1234k";
            bool value = false;
            string key = "";
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            string serverToken = Encrypt(password);
     
            char ch;
            for (int i = 0; i < 10; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            string randon = builder.ToString();
            string testKey2 = Hash(randon);
            string teststr = sltChar;
            cryptoKey = testKey2;
            string test = Encrypt(password);
             cryptoKey = sltChar;
            string test1 = Encrypt(test);
           string decPass = Decrypt(test1);
           cryptoKey = testKey2;
          // string decPass = Decrypt(test1);
           string decPass1 = Decrypt(decPass);
           // string test = Encrypt(password, testKey2);
            //string test1=Encrypt(test,sltChar);
            key = test1 + "|" + testKey2;
            DataDownloadClient obj = new DataDownloadClient();
            value = obj.ValidateUser(Crew3Ltr, key);
            bool value1 = value;
        
        }
    

        private static string Hash(string ToHash)
        {
           Encoder enc = System.Text.Encoding.ASCII.GetEncoder();
            byte[] data = new byte[ToHash.Length];
            enc.GetBytes(ToHash.ToCharArray(), 0, ToHash.Length, data, 0, true);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(data);
            return BitConverter.ToString(result).Replace("-", "").ToLower();
        }
        // The Initialization Vector for the DES encryption routine
        private static readonly byte[] IV =
            new byte[8] { 240, 3, 45, 29, 0, 76, 173, 59 };

        public static string Encrypt(string s)
        {
            if (s == null || s.Length == 0) return string.Empty;

            string result = string.Empty;

            try
            {
                byte[] buffer = Encoding.ASCII.GetBytes(s);
               TripleDESCryptoServiceProvider des =new TripleDESCryptoServiceProvider();
               MD5CryptoServiceProvider MD5 =new MD5CryptoServiceProvider();
               des.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(cryptoKey));
               des.IV = IV;
                result = Convert.ToBase64String(
                    des.CreateEncryptor().TransformFinalBlock(
                        buffer, 0, buffer.Length));
            }
            catch
            {
                throw;
            }

            return result;
        }

        /// <summary>
        /// Decrypts provided string parameter
        /// </summary>
        public static string Decrypt(string s)
        {
            if (s == null || s.Length == 0) return string.Empty;
           string result = string.Empty;
           try
            {
               byte[] buffer = Convert.FromBase64String(s);
               TripleDESCryptoServiceProvider des =new TripleDESCryptoServiceProvider();
               MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
               des.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(cryptoKey));
               des.IV = IV;
               result = Encoding.ASCII.GetString(
                    des.CreateDecryptor().TransformFinalBlock(
                    buffer, 0, buffer.Length));
            }
            catch
            {
                throw;
            }

            return result;
        }
   

2. Server Side Code for Decryption

string cryptoKey = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        string ServerSideToken = "lzzS4UuOgLnSvrgOgsGw/w==";
        private static readonly byte[] IV =new byte[8] { 240, 3, 45, 29, 0, 76, 173, 59 };
        public bool ValidateUser(string st, string key)
        {
            string tokenValue = "";
            string tokenValue1 = "";
            string serverToken = "";
            bool value = false;
            string[] HashArray;
             HashArray = key.Split('|');
             tokenValue = HashArray[0];
             tokenValue1 = HashArray[1];
             serverToken = Decrypt(ServerSideToken);
            string getToken = Decrypt(tokenValue);
            cryptoKey = tokenValue1;
            string clientToken = Decrypt(getToken);
            if (serverToken.Equals(clientToken))
            {
                value = true;
            }
            cryptoKey = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
                return value;
        }
     
       private string Decrypt(string s )
        {
            if (s == null || s.Length == 0) return string.Empty;
            string result = string.Empty;
            try
            {
                byte[] buffer = Convert.FromBase64String(s);
                TripleDESCryptoServiceProvider des =new TripleDESCryptoServiceProvider();
                MD5CryptoServiceProvider MD5 =new MD5CryptoServiceProvider();
                des.Key =MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(cryptoKey));
                des.IV = IV;
                result = Encoding.ASCII.GetString(des.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length));
            }
            catch
            {
                throw;
            }

            return result;
        }

traverse / parse a XML file in Java with DOM Parser example code . XML document / file Parsing using recursion

XML - a Markup Language which defines structured and platform-independent data that can be exchanged between different applications and platforms. Both XML and Java technology helps for developing Web services and applications that access Web services. Extensible Markup Language (XML) also supports Unicode encoding . Such things made XML to become such a great and popular technology very quckly. . As XML is used every where , it is very important for java developers to read / access / parse XML document in java programming.
To work with XML in Java and XML Parser, Developer needs to have basic knowledge of XML document. It is necessary to know the terms like tags, elements, attributes and nodes of XML document for parsing the XML.
Tags : tag is the text between the left (<) and right (>) angle brackets . Starting tags are represented as <tagname> and ending tags are represented as </tagname>
Elements : An element is the starting tag, the ending tag, and tags in between them. Elements have children that may be other elements, text nodes, or a combination of both. Example for elements in the below sample books xml are <book>, <title>, <author> , <year> are elements.
Attributes : XML elements can have attributes which provide additional information about an element. eg. <book id=“954”> , id is as attribute
Nodes : Everything in an XML document is a node. Elements are only one type of node. We can call the whole document as document node , each XML element as element node , the text in the XML elements as text node , Every attribute as attribute node , Comments as comment node . In the below books xml document , books is the root node , which has two book nodes , whereas each book node has three nodes such as title , author and year and each of them have text node.

The following is the sample XML document to represent the Books details.

 <?xml version="1.0" encoding="UTF-8"?><books><book id=“954”> 
       <title>Effective Java</title> 
       <author>Joshua Bloch</author> 
       <year> 2009 </year></book><book id=“777”> 
           <title>Effective Java</title> 
           <author>Scott Meyers</author>
           <year> 2010 </year>
       </book></books>
Tree Representation of above XML Books

Another sample XML document to represent the Employee details with Salary
    <EmpDetails>         <Employee>             <Name>ABC</Name>             <Designation>ABC</Designation>             <Scale>50000-200000</Scale>             <Salary>                   <Basic>121199.00</Basic>                   <HRA>20000.00</HRA>                   <TA>10000.00</TA>              </Salary>           </Employee>           <Employee>              <Name>XYZ</Name>              <Designation>ABC</Designation>              <Scale>12100-100000</Scale>              <Salary>                    <Basic>21199.00</Basic>                    <HRA>2000.00</HRA>                    <TA>1000.00</TA>              </Salary>           </Employee>       </EmpDetails>

XML parser checks syntax . XML document can have an optional Document Type Definition (DTD), called Schema which defines the XML document structure. If the XML document adheres to the structure of the DTD , then it is valid .

Now let us see how to access and use an XML document through the Java programming language. Two ways are there
1. Through parsers using the API Java API for XML Processing (JAXP)
two parsers are provided with the above API .
i) Simple API for XML (SAX)
ii) Document Object Model (DOM).
2. Through the new API Java Architecture for XML Binding (JAXB).
3. Using JDOM an open-source API
4. Using Apache Xerces

In our tutorial , we are going to parse the above books and Employees XML files using DOM Parser.
Java developers can make use of DOM parser in an application through the JAXP API . DOM parser creates a tree of objects that represents the data in the whole document and puts the tree in memory. Now the program can traverse the tree , to access / modify the data.

Steps to Parse XML file using DOM Parser

1.Create a document factory for DOM methods to obtain a parser that produces DOM object trees from XML documents.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); which creates a new factory instance.

 2. Create document builder to obtain DOM Document instances from an XML document.
DocumentBuilder db = dbf.newDocumentBuilder(); which creates a new instance of a DocumentBuilder . XML can be parsed using the instance of this class.

3. Get the DOM Document object by parsing the content of the given XML file as an XML document
Document dom = db.parse(books); which returns DOM object where books is an XML file. Other input sources accepted by parse method are InputStreams, Files, URLs, and SAX InputSources.

4. Access / manipulate the XML document using various methods

Some of the useful methods to get nodelist , elements , node , node value , etc ...

To get the node list of all the elements from the document by giving the tag name .
NodeList nodes = dom.getElementsByTagName("book"); where book is the tag name. Nodes are returned by traversing Document tree by preorder traversal

To get the single node item from the above nodelist . The items in the NodeList are accessible through index, starting from 0.
Node node = nodes.item(index);

To get the element node of the given node .
Element element = (Element) node;

To get all child nodes of the above element for a particular tag
NodeList nodes = element.getElementsByTagName("title").item(0).getChildNodes(); - where title is the tag.

To get the children of root node .
Element root = doc.getDocumentElement(); // gets the root node.
NodeList children = root.getChildNodes(); // returns the children of root.

To get at node information , getNodeName() , getNodeValue() can be used .

Tree struture can be traversed using recursion easily . The following code traverses the entire Book XML document and prints all node names and values if exisit using recursion . This code can traverse any XML.
    import java.io.File;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.*;public class DOMParser1 {public static void main(String args[]) {try {File books = new File("books.xml");DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();Document doc = dBuilder.parse(books);doc.getDocumentElement().normalize();Element root = doc.getDocumentElement();  // gets the root element bookxml_traverse_DOM(root);} catch (Exception ex) {    ex.printStackTrace();}}private static void  bookxml_traverse_DOM(Node element)   {      System.out.println(element.getNodeName()+" = "+element.getNodeValue());         for (Node child = element.getFirstChild(); child != null;  child = child.getNextSibling())      {                     bookxml_traverse_DOM(child);                    } }}

The following code (partly) can be used to find the value (text node) of the tags title , author , year of books.xml
    NodeList bookNodes = doc.getElementsByTagName("book"); // all book nodesfor (int i = 0; i < bookNodes.getLength(); i++) {    Node bookNode = bookNodes.item(i);  if (bookNode.getNodeType() == Node.ELEMENT_NODE) {          Element element = (Element) bookNode;              System.out.println("Book Title: " + getTextNode("title", element));          System.out.println("Author Name: " + getTextNode("author", element));          System.out.println("Year of Publishing: " + getTextNode("year", element));            }     } getTextNode methodprivate static String getTextNode(String tag, Element element) {NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();Node node = (Node) nodes.item(0);return node.getNodeValue();  // returns the only one text node value. }
 Output:

Now let us parse the above Employees XML and calculate the Total salary of each employee without using recursion .
    import java.io.File;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import java.io.*;import org.w3c.dom.*;public class employees_DOM {   public static void main(String[] args) {         try{     File employees = new File("emp.xml");     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();     DocumentBuilder db = dbf.newDocumentBuilder();     Document doc = db.parse(employees);     doc.getDocumentElement().normalize();         // get all the employee nodes         NodeList employeeNodeList = doc.getElementsByTagName("Employee");         for(int i=0; i<employeeNodeList.getLength(); i++) { double total_salary=0.0;             Node employeeNode = employeeNodeList.item(i); // one employee node at a time    NodeList employeeChildNodeList = employeeNode.getChildNodes();    // all child nodes of employee node                        for(int j=0; j<employeeChildNodeList.getLength(); j++) {                                   Node employeeChildNode = employeeChildNodeList.item(j);   //Name , Designation , Scale ,Salary ....                                     if (employeeChildNode.getNodeType() == Node.ELEMENT_NODE) {                 String employeeChildNodeName=employeeChildNode.getNodeName();                  Node employeeTextNode = employeeChildNode.getFirstChild();//the only text node                 int no_of_childs=employeeChildNode.getChildNodes().getLength();    // no of childs inside name  child , designation , ..., salary  . salary has more than one child nodes.                 if (no_of_childs==1)                  System.out.println( employeeChildNodeName + "  = " +employeeTextNode.getNodeValue().trim());   else    {   // samething for salary  node    NodeList salaryChildNodeList = employeeChildNode.getChildNodes();   // all child nodes of salary node         for(int k=0; k<salaryChildNodeList.getLength(); k++) {                                      Node salaryChildNode = salaryChildNodeList.item(k); //  to get  basic , hra, ta ...                                        if (salaryChildNode.getNodeType() == Node.ELEMENT_NODE) {                    String salaryChildNodeName=salaryChildNode.getNodeName();                     Node salaryTextNode = salaryChildNode.getFirstChild(); //the only text node                       System.out.println( salaryChildNodeName + "  = " + salaryTextNode.getNodeValue().trim());      total_salary=total_salary + Double.parseDouble(salaryTextNode.getNodeValue().trim());      }      }      }      }              }   System.out.println("Total Salary = " + total_salary + "\n");           }      }  catch (Exception e) {e.printStackTrace(System.err);}       }}
 Output:

Some of the imporatnt uses of XML :
XML is used everywhere , some of the example are given below
 1. XML plays big role in Webservice through messaging. XML and Web services architecture allows applications written in different languages on different platforms to exchange information with each other in a standards-based way.
2. XML helps to create interactive pages that allows the customer to customize those pages which can be translated to XHTML using XSL stylesheet. With XML,the data is stored once and can be rendered for different viewers with different style based on the style sheet which is processed by XSLT ( Extensible Style Language Transformation ).
3. Ajax helps to communicate with server applications with the help of XML
4. Many configuration files used by Application Server , Framework are xml .
 5. XML helps to keep the data separated from your HTML

Java Interface Concepts and core use of interface in Java

Interface in java is core part of its programming language despite that many programmers thinks Java Interface as an advanced concept and refrain using interfaces from early in programming career. At very basic level  interface  in java is a keyword  but same time it is an object oriented term to define contractsand abstraction , This contract is followed by any implementation of Interface in Java. Since multiple inheritance is not allowed in Java,  interfaceis only way to implement multiple inheritance at Type level. In this Java tutorial we will see What is an interface in Java, How and where to use interface in Java and some important points related to interface in Java.

Key Points about Interface in Java

1. Interface in java is declared using keyword interface and it represent a Type like any Class in Java. a reference variable of type interface can point to any implementation of that interface in Java. Its also a good design principle to "program for interfaces than implementation" because when you use interface to declare reference variable, method return type or method argument you are flexible enough to accept any future implementation of that interface which could be much better and high performance alternative of current implementation. similarly calling any method on interface doesn't tie you with any particular implementation and you can leverage  benefit of better or improved implementation over time.

2) All variables declared inside interface is implicitly public final variable or constants. which brings a useful case of using Interface for declaring Constants. We have used both Class and interface for storing application wide constants and advantage of using Interface was that you can implement interface and can directly access constants without referring them with class name which was the case earlier when Class is used for storing Constants. Though after introduction of static imports in Java 5 this approach doesn't offer any benefit over Class approach.

3) All methods declared inside Java Interfaces are implicitly public and abstract, even if you don't use public or abstract keyword. you can not define any concrete method in interface. That's why interface is used to define contracts in terms of variables and methods and you can rely on its implementation for performing job.

4) In Java its legal for an interface to extend multiple interfaces. for example following code will run without any compilation error:

interface Session extends Serializable, Clonnable{ }

here Session interface in Java is also a Serializable and Clonnable. This is not true for Class and one Class can only extend at most another Class. In Java one Class can implement multiple interfaces. They are required to provide implementation of all methods declared inside interface or they can declare themselves as abstract class.

Example of interface in Java

Java standard library itself has many inbuilt interfaces like Serializable, Clonnable, Runnable or Callable interface in Java.  Declaring interface is easy but making it correct in first attempt is hard but if you are in business of designing API then you need to get it right in first attempt because its not possible to modify interface once it released without breaking all its implementation. here is an example of declaring interface in Java :

 interface SessionIDCreator extendsSerializable, Cloneable{
        String TYPE = "AUTOMATIC";
        int createSessionId();
    }
 
    class SerialSessionIDCreator implements SessionIDCreator{

        private int lastSessionId;
       

 @Override
         publicint createSessionId() {
            return lastSessionId++;
        }
    
    }

In above example of interface in Java, SessionIDCreator is an interface while SerialSessionIDCreator is a implementation of interface. @Override annotation can be used on interface method from Java 6 onwards, so always try to use it. Its one of those coding practice which should be in your code review checklist.

When to use interface in Java

Interface is best choice for Type declaration or defining contract between multiple parties. If multiple programmer are working in different module of project they still use each others API by defining interface and not waiting for actual implementation to be ready. This brings us lot of flexibility and speed in terms of coding and development. Use of Interface also ensures best practices like "programming for interfaces than implementation" and results in more flexible and maintainable code. Though interface in Java is not the only one who provides higher level abstraction, you can also use abstract class but choosing between Interface in Java and abstract class is a skill. Difference between Interface in Java and abstract class in java is also a very popular java interview question.

That's it for now on Interfacein Java, specifics of Java interface and How and when to use Interface in Java.  Interface is key to write flexible and maintainable code. If you are not yet using interface in your code than start thinking in terms of interfaces and use it as much possible. You will learn more about interfaces when you start using design patterns. many design patterns like decorator pattern, Factory method pattern  or Observer design pattern  makes very good use of Java interfaces.

Convert String into Int data type and finally convert into DateTime for Compare two dates in C#

Hi
I have two string value and i want to convert into DATETIME so that , i can do difference between them
like below

string a= 07032011 12:50
string b= 07032011 23:40

DateTime aa = new DateTime(int.Parse(a.Substring(4, 4)), int.Parse(a.Substring(2, 2)),
                                         int.Parse(a.Substring(0, 2)), int.Parse(a.Substring(9, 2)), int.Parse(a.Substring(12, 2)),

                                         00);
            DateTime bb = new DateTime(int.Parse(b.Substring(4, 4)), int.Parse(b.Substring(2, 2)),
                                         int.Parse(b.Substring(0, 2)), int.Parse(b.Substring(9, 2)), int.Parse(b.Substring(12, 2)),

                                         00);
    TimeSpan cc = aa - bb;

ind day= cc.days;
int hour= cc.hours;
int minutes= cc.minutes;

UNix Shell script for Oracle database access through Putty

In Latest R&D for Oracle database which is on Unix plateform. Our Team Member access it through Putty below important script for that

1. go to SqlPlus*

  > sqlplus "/as sysdba"

2) to show all user


> show users

3) to all database
>
4) create tablespace

create tablespace ts_something
  logging
  datafile '/dbf1/ts_sth.dbf' 
  size 32m 
  autoextend on 
  next 32m maxsize 2048m
  extent management local;