Web Services in Java


In this tutorial we will see about Web Services in Java.


What are Web Services?


Web services are client and server applications that communicate over the World Wide Web's (WWW) HyperText Transfer Protocol (HTTP). As described by the World Wide Web Consortium (W3C), web services provide a standard means of interoperating between software applications running on a variety of platforms and frameworks. Web services are characterized by their great interoperability and extensibility, as well as their machine-processable descriptions, thanks to the use of XML. Web services can be combined in a loosely coupled way to achieve complex operations. Programs providing simple services can interact with each other to deliver sophisticated added-value services. By Oracle Docs.


Before Web Services?

Before Web Services introduced we were using RMI (Remote Method Invocation), CORBA etc., to communicate third part services and methods. With the release of JDK version 1.1, Java has its own, built-in native ORB, called RMI (Remote Method Invocation). Where CORBA is an integration technology, not a programming technology which used in Java to communicate between other languages like C, C++, Ada, COBOL etc., Instead of digging to RMI or other client/ server we will focus only on Web Services in this tutorial. 


Types of Web Services?

There are 2 tyes of Web Services,
1. SOAP based (Simple Object Access Protocol) Web Services 
2. RESTful Web Services 


SOAP Web Services (JAX-WS)

SOAP web services use XML messages that follow the Simple Object Access Protocol (SOAP) standard, an XML language defining a message architecture and message formats. Such systems often contain a machine-readable description of the operations offered by the service, written in the Web Services Description Language (WSDL), an XML language for defining interfaces syntactically. Basically Client and Server communication will be in XML standard formats which gives flexibility to use any platform (Java, .NET, etc.,) and to use any OS (Windows, Unix, etc.,). Generally Server can be in any language and client can be any language where communication will be in common XML formats and standards.


RESTful Web Services (JAX-RS)


JAX-RS provides the functionality for Representational State Transfer (RESTful) web services in Java. REST is well suited for basic, ad hoc integration scenarios. RESTful web services, often better integrated with HTTP than SOAP-based services are, do not require XML messages or WSDL service–API definitions as like SOAP. By Oracle Docs.


Difference between SOAP and RESTful

  • SOAP is a Object oriented and REST is a resource oriented.
  • In place of security SOAP supports SSL and WS-Security and REST supports only SSL.
  • As performance wise SOAP will be better than REST
  • SOAP doesn't support caching and REST supports.
  • SOAP is heavy in message size with WS specific markup. where as REST is lightweight and no extra XML markups added. 
  • SOAP supports text and binary encoding and REST supports only text encoding.
  • SOAP uses WSDL to describe the services which we have exposed and in REST there is no formal definition.
  • Complexity of SOAP uses frameworks to develop and on other side REST is very simple in development without any frameworks. 
  • Protocols supported in SOAP are HTTP, SMTP, JMS and REST supports only HTTP.


According to project needs development team need to decide whether they need to go with SOAP or REST. 






Update or Edit XML File using DOM Parser


In our earlier tutorial we have seen how to read XML file using DOM and SAX Parser. In this tutorial we will see how to edit or update XMl file using DOM parser. We have used below sample XML to update using DOM parser.

SAMPLE XML:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 
<organization>
 <employee mode="permanent">
  <name>John</name>
  <empid>1234</empid>
  <designation>SE</designation>
  <technology>Java</technology>
 </employee>
 <employee mode="contract">
  <name>David</name>
  <empid>4545</empid>
  <designation>Manager</designation>
  <technology>.NET</technology>
 </employee>
</organization>


XML AFTER UPDATE: 

<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 
<organization>
 <employee mode="permanent">
  <name>John</name> 
  <empid>1234</empid> 
  <designation>SE</designation> 
  <age>35</age> 
 </employee>
 <employee mode="permanent">
  <name>David</name> 
  <empid>4545</empid> 
  <designation>Senior Manager</designation> 
  <age>35</age> 
 </employee>
 <employee mode="permanent">
  <name>Steve</name> 
  <empid>5635</empid> 
  <designation>Lab Engineer</designation> 
  <age>38</age> 
 </employee>
</organization>


If we seen above XML we have modified such as
  • Deleting <technology> node from the XML
  • Updating attribute value from "contract" to "permanent" for 2nd employee
  • Updating <designation> node value from "Manager" to "Senior Manager"
  • Adding new <employee> element


Below example java code will be used to modify the XML as per given above. 


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

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

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

public class EditXML {
 
 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, TransformerException {
  editMyXML("D:\\document.xml");
 }
 
 public static void editMyXML(String file) throws ParserConfigurationException, SAXException, IOException, TransformerException{
  
  DocumentBuilderFactory builderFac = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = builderFac.newDocumentBuilder();
     Document doc = builder.parse(new File(file));

     System.out.println ("ROOT: " + doc.getDocumentElement().getNodeName());
        NodeList list = doc.getElementsByTagName("employee");
        System.out.println("No. Of Employees: " + list.getLength());
                
        for(int i= 0; i<list.getLength(); i++){
            Node node = list.item(i);
            if(node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element)node;
                String mode, name, empid, designation, technology;
                                
                mode = element.getAttribute("mode");
                
                NodeList nListName = element.getElementsByTagName("name");
                Element nElementName = (Element)nListName.item(0);
                NodeList tListName = nElementName.getChildNodes();
                name =((Node)tListName.item(0)).getNodeValue().trim();
                
                NodeList nListEmpId = element.getElementsByTagName("empid");
                Element nElementEmpId = (Element)nListEmpId.item(0);
                NodeList tListEmpId = nElementEmpId.getChildNodes();
                empid = ((Node)tListEmpId.item(0)).getNodeValue().trim();
                
                NodeList nListDesi = element.getElementsByTagName("designation");
                Element nElementDesi = (Element)nListDesi.item(0);
                NodeList tListDesi = nElementDesi.getChildNodes();
                designation = ((Node)tListDesi.item(0)).getNodeValue().trim();
                
                NodeList nListTech = element.getElementsByTagName("technology");
                Element nElementTech = (Element)nListTech.item(0);
                NodeList tListTech = nElementTech.getChildNodes();
                technology =((Node)tListTech.item(0)).getNodeValue().trim();
                
                // Updating only for 4545 (David) Employee
                if(empid.equals("4545")){
                 
                 // Updating MODE from "contract" to "Permanent"
                 node.getAttributes().getNamedItem("mode").setTextContent("permanent");
                 
                 // Updating Designation from "Manager" to "Senior Manager"
                 ((Node)tListDesi.item(0)).setTextContent("Senior Manager");
                }
                
                // Adding new Node called "age"
                Element nElementAge = doc.createElement("age");
                nElementAge.appendChild(doc.createTextNode("35"));
                element.appendChild(nElementAge);
                
                // Deleting "technology" Node
                element.removeChild(nElementTech);
            }
        }
        
        //Adding new employee
        addNewEmployee(doc, "permanent", "Steve", "5635", "Lab Engineer", "38");
        
        
        // Writing update XML file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
  Transformer transformer = transformerFactory.newTransformer();
  DOMSource source = new DOMSource(doc);
  StreamResult result = new StreamResult(new File("D:\\document.xml"));
  transformer.transform(source, result);
 }
 
 public static void addNewEmployee(Document doc, String mode, String name, String empId, String designation, String age){
  
  Element root = doc.getDocumentElement();
        
        Element element = doc.createElement("employee");
        root.appendChild(element);
        
  Attr attr = doc.createAttribute("mode");
  attr.setValue("permanent");
  element.setAttributeNode(attr);
  
  Element nElementName = doc.createElement("name");
        nElementName.appendChild(doc.createTextNode("Steve"));
        element.appendChild(nElementName);
        
        Element nElementEmpId = doc.createElement("empid");
        nElementEmpId.appendChild(doc.createTextNode("5635"));
        element.appendChild(nElementEmpId);
        
        Element nElementDesi = doc.createElement("designation");
        nElementDesi.appendChild(doc.createTextNode("Lab Engineer"));
        element.appendChild(nElementDesi);
  
  Element nElementAge = doc.createElement("age");
        nElementAge.appendChild(doc.createTextNode("38"));
        element.appendChild(nElementAge);
  } 
}








Java Interview Questions - 4



Java Interview Questions


In this tutorial we will see about few simple interview programming questions.

1. Sort 3 numbers without IF condition or looping.


public class Sort3No {
 public static void main(String[] args) {
  int x = 9;
  int y = 3;
  int z = 7;

  int first = Math.min(x, Math.min(y, z));
  int third = Math.max(x, Math.max(y, z));
  int second = x + y + z - first - third;

  System.out.println("SORTED NO's : " + first + ", " + second + ", "+ third);
 }
}


OUTPUT:

SORTED NO's : 3, 7, 9





2. Reverse the number without using String


public class ReverseNumber {
 
 public static void main(String[] args) {
  
  int number = 123456;

  int revNo = 0;
  while(number > 0){
   revNo = (10 * revNo) + (number % 10);
   number = number / 10;
  }
  
  System.out.println("REVERSED NO : "+revNo);
 }
}


OUTPUT:

REVERSED NO : 654321





3. Print first N Fibonacci numbers.


public class Fibonacci {

  public static void main(String[] args) { 
       int input = 10;
       int fib = 0,  val= 1;
       System.out.print("First "+input+" Fibonacci Numbers : ");
       for (int i = 0; i < input; i++) {
          fib = fib + val;
          val = fib - val;
          System.out.print(fib+", "); 
       }
  }
}


OUTPUT:

First 10 Fibonacci Numbers : 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 





4. Convert String to Date Object 


public class StringToDate {
 
 public static void main(String args[]) {
  try{
         String strDate = "23-5-2013";

         SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
         Date date = format.parse(strDate);
         System.out.println("DATE : "+date);
  }catch (ParseException e) {
   e.printStackTrace();
  }
    }
}


OUTPUT:

DATE : Thu May 23 00:00:00 IST 2013





5. Find entered date is valid or not


public class ValidDate {

 public static void main(String[] args) {

  int day = 29;
  int month = 2;
  int year = 1984;

  int[] leapYearDays = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  int[] nonLeapYearDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

  if (month >= 1 && month <= 12) {
   if (year % 4 == 0) {
    if (day >= 1 && day <= leapYearDays[month - 1]) {
     System.out.println("Valid Date...");
    } else {
     System.out.println("Invalid Date");
    }
   } else {
    if (day >= 1 && day <= nonLeapYearDays[month - 1]) {
     System.out.println("Valid Date...");
    } else {
     System.out.println("Invalid Date");
    }
   }
  } else {
   System.out.println("Invalid Date");
  }
 }
}


OUTPUT:

Valid Date...





6. Find the day of week by given date.


public class DayOfWeek {

 public static void main(String[] args) {

  int day = 23;
  int month = 5;
  int year = 2013;

  String days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

  int a = year - (14 - month) / 12;
  int x = a + a / 4 - a / 100 + a / 400;
  int b = month + 12 * ((14 - month) / 12) - 2;
  int c = (day + x + (31 * b) / 12) % 7;

  System.out.println(days[c]);
 }
}


OUTPUT:

Thursday





7. Print 5 random numbers between 2 numbers


public class PrintRandom {
 
 public static void main(String[] args) {
  
  int min = 100;
  int max = 200;
  
  for(int i=0;i<5;i++){
   int rand = new Random().nextInt(max);
   if(rand > min){
    System.out.println(rand);
   }else{
    i--;
   }
  }
 }
}


OUTPUT:

122
180
193
114
187





8. Replace character in a string without using Java API functions


public class ReplaceChar {

 public static void main(String[] args) {
  String str = "This document is the API specification for version 6 of the Java";
  System.out.println("INPUT              : "+str);
  str = replaceChar(str, 'Q', 'i'); // Change all 'i' to 'Q' 
  System.out.println("AFTER CHAR REPLACE : "+str);
 }
 
 public static String replaceChar(String str, char newChar, char oldChar){
  try{
   char[] charAry = str.toCharArray();
   for(int i=0;i<str.length();i++){
    if(charAry[i] == oldChar){
     charAry[i] = newChar;
    }
   }
   str = new String(charAry);
  }catch (Exception e) {
   e.printStackTrace();
  }
  return str;
 }
}


OUTPUT:

INPUT               : This document is the API specification for version 6 of the Java
AFTER CHAR REP: ThQs document Qs the API specQfQcatQon for versQon 6 of the Java





9. Write a Java program to find given number is odd or even without / or % operators. 


public class OddOrEven {
 
 public static void main(String[] args) {
  int no = 25;
  while(no>2){
   no -= 2;
  }
  if(no == 1){
   System.out.println("Given no. is Odd Number...");
  }else{
   System.out.println("Given no. is Even Number...");
  }
 }
}


OUTPUT:

Given no. is Odd Number...





10.  This is a simple mathematical calculation program. 
    
Example: Raj purchased the bag for Rs.2750 which includes 10% tax of bag price. So what will be the price of bag and tax amount?. Program should work for whatever be the amount as input.


public class CalculatePrice {
 
 public static void main(String[] args) {
  int price = 2750;
  float bagPrice = ((price/11f)*10f);
  float taxAmt = (price/11f);
  System.out.println("BAG PRICE   : "+bagPrice);
  System.out.println("TAX AMOUNT  : "+taxAmt);
  System.out.println("TOTAL PRICE : "+(bagPrice+taxAmt));
 }
}


OUTPUT:

BAG PRICE   : 2500.0
TAX AMOUNT  : 250.0
TOTAL PRICE : 2750.0