Google is providing OAuth Service. You can implement Google Login on your website so that user doesn't need to remember another password for your website. You will also get worthy email addresses to connect with users. Get Google GSON Java Library to handle JSON responses.

OAuth 2.0 Flow

  1. User will click on Auth login link
  2. Google Auth server will show permission screen to user
  3. Once user accepts to the scope, It will send code to App Server ( Redirect URI)
  4. Once we got code, get access token by using client secret id
  5. Access User's Information using that access token 

Get OAuth 2.0  Credentials from Google developer console 

  1. Go to Google Developer Console
  2. Create Project and Open that project
  3. Go to API & Auth > Credentials > Create New Client ID. Here one new dialog box will open and show some options. Now select web application, Give you website URL (example: http://demo.sodhanalibrary.com) in JavaScript origins and Give redirect URL (example: http://demo.sodhanalibrary.com/oauth2callback). Now click on Create Client ID button.
  4. Now you can see your client id and client secret id.

Form the URL

Now we need to create a button with Auth URL. Syntax of the URL is
https://accounts.google.com/o/oauth2/auth?[parameters]

Some important Query Paramenters

  1. client_id: Which you got at Google developer console
  2. response_id: For web application response_id is code
  3. redirect_uri: Redirect URI which you given at Google developer console
  4. scope: to get profile info give profile as scope, to get email address give email as scope
  5. approval_prompt: (force or auto) If it is force, user must accept to your scope or else it will be optional.

The Auth URL get Users Email Address

 https://accounts.google.com/o/oauth2/auth?
 scope=email&
 redirect_uri=http://demo.sodhanalibrary.com/oauth2callback&
 response_type=code&
 client_id=your application client id&
 approval_prompt=force

Get Access Token 

Once user click on above link, It will ask for User's permission to provide information to your site. Once user click on accept it will redirect to Your APP Redirect URI?code=[some code here]. Here you will get code value at server side. So you need to access this from Java or PHP or any other server side language. 

Get Code Value and format Parameters

String code = request.getParameter("code");
String urlParameters = "code="
                    + code
                    + "&client_id=Your app client id"
                    + "&client_secret=Your app secret id"
                    + "&redirect_uri=http://demo.sodhanalibrary.com/oauth2callback"
                    + "&grant_type=authorization_code";
Now we have to send that code with client id and secret id to https://accounts.google.com/o/oauth2/token

Java code to post parameters

URL url = new URL("https://accounts.google.com/o/oauth2/token");
URLConnection urlConn = url.openConnection();
urlConn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(
urlConn.getOutputStream());
writer.write(urlParameters);
writer.flush();

Extract Access Token

After posting above parameters to Google Auth URL, we will get response which contains Access Token. Now extract that access token from that response.
JsonObject json = (JsonObject)new JsonParser().parse(line1);
String access_token = json.get("access_token").getAsString();

Get User Info

Now we have access token so we can get user info.
url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token="+ access_token);
urlConn = url.openConnection();
outputString = "";
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
        outputString += line;
}
In the above code outputString contains the User Info

User info in JSON format

  {
    "id":"user id here",
    "email":"email here",
    "name":"name here",
    "given_name":"given name here", 
    "family_name":"family name here"  
  }

POJO Class to handle JSON rensponse

public class GooglePojo {
    String id;
    String email;
    boolean verified_email;
    String name;
    String given_name;
    String family_name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isVerified_email() {
        return verified_email;
    }

    public void setVerified_email(boolean verified_email) {
        this.verified_email = verified_email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGiven_name() {
        return given_name;
    }

    public void setGiven_name(String given_name) {
        this.given_name = given_name;
    }

    public String getFamily_name() {
        return family_name;
    }

    public void setFamily_name(String family_name) {
        this.family_name = family_name;
    }

    @Override
    public String toString() {
        return "GooglePojo [id=" + id + ", email=" + email
                + ", verified_email=" + verified_email + ", name=" + name
                + ", given_name=" + given_name + ", family_name=" + family_name
                + "]";
    }
}

Whole Servlet Code 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class Oauth2callback extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public Oauth2callback() {
        super();
        
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        
        System.out.println("entering doGet");
        try {
            // get code
            String code = request.getParameter("code");
            // format parameters to post
            String urlParameters = "code="
                    + code
                    + "&client_id=Your App Client ID"
                    + "&client_secret=Your App secret client ID"
                    + "&redirect_uri=Your App Redirect URL"
                    + "&grant_type=authorization_code";
            
            //post parameters
            URL url = new URL("https://accounts.google.com/o/oauth2/token");
            URLConnection urlConn = url.openConnection();
            urlConn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(
                    urlConn.getOutputStream());
            writer.write(urlParameters);
            writer.flush();
            
            //get output in outputString 
            String line, outputString = "";
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    urlConn.getInputStream()));
            while ((line = reader.readLine()) != null) {
                outputString += line;
            }
            System.out.println(outputString);
            
            //get Access Token 
            JsonObject json = (JsonObject)new JsonParser().parse(outputString);
            String access_token = json.get("access_token").getAsString();
            System.out.println(access_token);

            //get User Info 
            url = new URL(
                    "https://www.googleapis.com/oauth2/v1/userinfo?access_token="
                            + access_token);
            urlConn = url.openConnection();
            outputString = "";
            reader = new BufferedReader(new InputStreamReader(
                    urlConn.getInputStream()));
            while ((line = reader.readLine()) != null) {
                outputString += line;
            }
            System.out.println(outputString);
            
            // Convert JSON response into Pojo class
            GooglePojo data = new Gson().fromJson(outputString, GooglePojo.class);
            System.out.println(data);
            writer.close();
            reader.close();
            
        } catch (MalformedURLException e) {
            System.out.println( e);
        } catch (ProtocolException e) {
            System.out.println( e);
        } catch (IOException e) {
            System.out.println( e);
        }
        System.out.println("leaving doGet");
    }

}
Read More
Recently I got a situation to create 20 similar type of HTML files which differs in only content. Then I got this idea make this automate. Here you can find Java program which is able to create HTML files based on a template.

Make your template ready

Here in template you can observe the title, body tags. These elements have template words title and message. These were specified in ${...} for easy replacement
<html>
  <head>
    <title>${title}</title>
  </head>
  <body>
    ${message}
  </body>
</html>

Get TemplateMatcher

To use TemplateMatcher, you need to have jlibs-core jar in build-path. You can download this jar from https://code.google.com/p/jlibs/downloads/list. Read more about TemplateMatcher at http://blog.sodhanalibrary.com/2014/09/format-html-styled-email-using-java.html

Java Code

Algorithm of this below program is very simple.
  1. Read template file content
  2. Replace template words with new words
  3. Write the generated content into new file
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import jlibs.core.util.regex.TemplateMatcher;

public class TemplateFiles {
    
   
   static public String getContents(File aFile) {
        //...checks on aFile are elided
        StringBuilder contents = new StringBuilder();
        
        try {
          //use buffering, reading one line at a time
          //FileReader always assumes default encoding is OK!
          BufferedReader input =  new BufferedReader(new FileReader(aFile));
          try {
            String line = null; //not declared within while loop
            /*
            * readLine is a bit quirky :
            * it returns the content of a line MINUS the newline.
            * it returns null only for the END of the stream.
            * it returns an empty String if two newlines appear in a row.
            */
            while (( line = input.readLine()) != null){
              contents.append(line);
              contents.append(System.getProperty("line.separator"));
            }
          }
          finally {
            input.close();
          }
        }
        catch (IOException ex){
          ex.printStackTrace();
        }
        
        return contents.toString();
      }

      /**
      * Change the contents of text file in its entirety, overwriting any
      * existing text.
      *
      * This style of implementation throws all exceptions to the caller.
      *
      * @param aFile is an existing file which can be written to.
      * @throws IllegalArgumentException if param does not comply.
      * @throws FileNotFoundException if the file does not exist.
      * @throws IOException if problem encountered during write.
      */
      static public void setContents(File aFile, String aContents)
                                     throws FileNotFoundException, IOException {
        if (aFile == null) {
          throw new IllegalArgumentException("File should not be null.");
        }
        if (!aFile.exists()) {
            aFile.createNewFile();
        }
        if (!aFile.isFile()) {
          throw new IllegalArgumentException("Should not be a directory: " + aFile);
        }
        if (!aFile.canWrite()) {
          throw new IllegalArgumentException("File cannot be written: " + aFile);
        }
        

        //use buffering
        Writer output = new BufferedWriter(new FileWriter(aFile));
        try {
          //FileWriter always assumes default encoding is OK!
          output.write( aContents );
        }
        finally {
          output.close();
        }
      }

      /** Simple test harness.   */
      public static void main (String args[]) throws IOException {
        
        // template file
        File templateFile = new File("C:\\template.html");
        // file to be created
        File distFile = new File("C:\\template1.html"); 
        
        // get content of template file
        String template = getContents(templateFile);
       
        // set template fields 
        Map<String, String> vars = new HashMap<String, String>();
        vars.put("title", "srinivas");
        vars.put("body", "21");

        // Match and replace template words     
        TemplateMatcher matcher = new TemplateMatcher("${", "}");
        setContents(distFile, matcher.replace(template, vars));
      }
   
}
Read More
If you want find 9th character or 19th line in a text, how will you do ?. You can do this manually or by using editors. Here I am going to implement this functionality with jQuery. I have created one simple online tool by using this program.

Algorithm

  1. Get text, character or line position
  2. Enclose every character by span element with id attribute as "char"+(char number)
  3. Enclose every paragraph by div element with id attribute as "line"+(line number)
  4. If it is character number then  highlight element with id "char"+(number) element by assigning new css
  5. If it is line number then  highlight element with id "line"+(number) element by assigning new css

jQuery Code

function hilightPosition(text, number, charOrLine) {
      var len = text.length + 1;
      var res = '';
      var j=2;
      res += '<div id="line1">';
      for(var i=1;i<=len;i++) {
        if(text.charAt(i-1) == '\n') {
          // Adding line id
          res += '</div><div id="line'+j+'">';
          j++;
        }
        // Adding char id
        res += '<span id="char'+i+'">'+text.charAt(i-1)+'</span>';
      }
      res += '</div>';
      
      // Display text
      $("#result").html(res);
      
      // Check whether we have to hilight line or character
      if(charOrLine == 'line'){
        // Highlight line id
        $("#line"+number).attr("style","border:2px solid #0000ff;");
      } else {
        // Highlight char id
        $("#char"+number).attr("style","border:2px solid #0000ff;");
      } 
}
Read More
How much one URL went viral ? It is based on the shares of that URL on social networking websites. How to get those share counts ?...Here in this tutorial I am going to explain how to get those share count.

Twitter

Get URL
Output
{"count":11,"url":"http:\/\/pojo.sodhanalibrary.com\/"}
Implementation with Java
String url ="https://cdn.api.twitter.com/1/urls/count.json?url=http://pojo.sodhanalibrary.com"; 
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);

// Send request
System.out.println("\nSending 'GET' request to URL : " + url);
BufferedReader in = new BufferedReader(
       new InputStreamReader(con.getInputStream()));
String outputLine;

// reading output from Request
StringBuffer response = new StringBuffer(); 
while ((outputLine = in.readLine()) != null) {
   response.append(outputLine);
}
in.close();

Facebook

Get URL
Output
{
   "id": "http://pojo.sodhanalibrary.com",
   "shares": 27
}
Implementation with Java
String url ="http://graph.facebook.com/?id=http://pojo.sodhanalibrary.com"; 
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);

// Send request
System.out.println("\nSending 'GET' request to URL : " + url);
BufferedReader in = new BufferedReader(
       new InputStreamReader(con.getInputStream()));
String outputLine;

// reading output from Request
StringBuffer response = new StringBuffer(); 
while ((outputLine = in.readLine()) != null) {
   response.append(outputLine);
}
in.close();

System.out.println(response.toString());

Pinterest

Get URL
Output
receiveCount({"url":"http://pojo.sodhanalibrary.com","count":0})
Implementation with Java
String url ="http://api.pinterest.com/v1/urls/count.json?url=http://pojo.sodhanalibrary.com"; 
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);

// Send request
System.out.println("\nSending 'GET' request to URL : " + url);
BufferedReader in = new BufferedReader(
       new InputStreamReader(con.getInputStream()));
String outputLine;

// reading output from Request
StringBuffer response = new StringBuffer(); 
while ((outputLine = in.readLine()) != null) {
   response.append(outputLine);
}
in.close();
System.out.println(response.toString());

Linkedin

Get URL
Output
IN.Tags.Share.handleCount({"count":0,"fCnt":"0","fCntPlusOne":"1","url":"http:\/\/pojo.sodhanalibrary.com"});
Implementation with Java
String url ="http://www.linkedin.com/countserv/count/share?url=http://pojo.sodhanalibrary.com"; 
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);

// Send request
System.out.println("\nSending 'GET' request to URL : " + url);
BufferedReader in = new BufferedReader(
       new InputStreamReader(con.getInputStream()));
String outputLine;

// reading output from Request
StringBuffer response = new StringBuffer(); 
while ((outputLine = in.readLine()) != null) {
   response.append(outputLine);
}
in.close();
System.out.println(response.toString());
Read More
This tutorial teaches how to read and differentiate different type of XML Nodes.
There are 3 important XML data parts.
  1. Element - Elements have tags. In above example bookstore, book, title, author are elements
  2. Attribute - These are attributes for Elements. In above example category is attribute.
  3. Text - Simple text surrounded by tags

Program Flow :

  1. Read ROOT Element as Node
  2. If it is Text, go to 3rd step else go to 4th step.
  3. print text value
  4. If it is Element, print all attributes and list children and send them to 2nd step

XML Node Types :

Node Node Type Named Constant
Element 1 ELEMENT_NODE
Attribute 2 ATTRIBUTE_NODE
Text 3 TEXT_NODE

JavaScript Code :

Here you can find JavaScript source code parse XML. In below code you can find some individual functions. Those are explained below
readNode : It will parse all type of XML nodes
trimSpace : This function removes all unwanted space from the XML
loadXMLDoc : This function is for loading XML document 
var parseXml;

var res = '';

if (window.DOMParser) {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    parseXml = function() { return null; }
}


var xmlDoc = parseXml(trimSpace(loadXMLDoc("books.xml")));

x=xmlDoc.documentElement;

readNode(x);

document.getElementById("result").innerHTML = res;

function readNode(node) {
    res+=" <br/>";
    res+=" (nodetype: " + node.nodeType + ") ";
    if(node.nodeType == 1) {
        res+="Nodename: " + node.nodeName;
        var y=node.childNodes;
        for(var i=0;i<y.length;i++)
        {
            readNode(y[i]); 
        }
    } else if(node.nodeType == 2) {
        res+="Nodename: " + node.nodeName;
    } else if(node.nodeType == 3) {
        res+="Nodevalue: " + node.textContent+ "";
    }
    res+=" <br/>";
}

function trimSpace(val) {
    var lines = val.split('\n');
    var out='';
    for(var i = 0;i < lines.length;i++){
        out += lines[i].trim();
    }
    return out;
}

function loadXMLDoc(file) {
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET",file,false);
    xmlhttp.send();

    return xmlhttp.responseText;
}

Read More
This tutorial is purely on programming SOAP Web Services with JAVA. First of I will give a sample case study. Then I will implement the same. By reading this article, You can learn the implementation of SOAP web services with JAVA. You need to have Tomcat server configured Eclipse.

What is SOAP :

SOAP stands for Simple Object Access Protocol. We can send messages by using this Protocol. SOAP is based on XML, so it is independent of programming platform.
SOAP Message Syntax :
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Header>
...
</soap:Header>

<soap:Body>
...
  <soap:Fault>
  ...
  </soap:Fault>
</soap:Body>

</soap:Envelope>
SOAP Body contains message
SOAP Header contains data other than message (Authentication info, Login User ID...etc)
SOAP Fault contains reason for failure.

Case Study :

This project is for maintaining Employee information. We have to convert below Case Study into Web Service project. 
  1. Create Employee Class
  2. Create EmployeeService Class with methods createEmployee(String id, String name, String email), deleteEmployee(String id), selectEmployees()
  3. Create one global HashMap to maintain Employee Info.
  4. createEmployee is for creating employees, This method takes Employee object as input and returns String
  5. deleteEmployee is for deleting employees, This method takes Employee ID (String) as input and returns String
  6. selectEmployees is for reading all employee info. This method returns List of Employee details

Annotations :

@WebService Annotation

@WebService(
        portName = "EmployeePort",
        serviceName = "EmployeeService",
        targetNamespace = "http://blog.sodhanalibrary.com/wsdl",
        endpointInterface = "com.services.EmplyeeInterface"
)
This annotation is for java class which works as Sevice
portName - specifies wsdl:port
serviceName - specifies Service Name
targetNamespace - specifies Namespace for WSDL
endpointInterface - java interface class which Service class implements

@WebMethod Annotation

This annotation is for method in service class which implements functionality
action - specifies SOAP action
operationName - specifies soap:operation
exclude - exclude the method from Web Service
@WebMethod(action="create",
           operationName="createEmployee",
           exclude=false
          )

@WebParam Annotation

This annotation is for defining request parameters. 
@WebParam(name = "i") int i

Setup Apache Axis2

Apache Axis 2 is Web Service engine which supports SOAP messages.

Axis2 Preferences

  1. Download the Axis 2 binary distribution (here)
  2. Extract it
  3. Enter Eclipse and go to Window > Preferences > Web Services > Axis2 Preferences
  4. In the Axis2 runtime location field, points to your Axis2 installation directory (the one you created in step 2)
  5. Click Apply
  6. Close Preferences and try again

Server and Runtime

  1. Enter Eclipse and go to Window > Preferences Web Services Server and Runtime
  2. In the Web Service runtime field, points to your Axis2 installation directory (the one you created in step 2)
  3. Click Apply
  4. Close Preferences and try again

Setup Chrome / Firefox  SOAP Web Service Testing Plugin

Install Wizdler in chrome. You can find this plugin here
or
Install SOA Client for Firefox. You can find this plugin here

Implementation 

Create New Dynamic Web Project SimpleSoapExample in Eclipse
Create com.services java package
Create Employee Pojo Class
package com.services;

public class Employee {
    String id;
    String name;
    String email;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

Create EmployeeList Pojo class like below
Here I have used Employee Array because JAX-RPC doesn't support any collections. This class is for showing list of Employees
package com.services;

public class EmployeeList {
    private Employee[] employeeList;
    private int count;

    public Employee[] getEmployeeList() {
        return employeeList;
    }

    public void setEmployeeList(Employee[] employeeList) {
        this.employeeList = employeeList;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }   
}
Create below EmployeeService class in the com.services package
This is Service class. We can access methods in this class through SOAP web service
package com.services;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

@WebService(
        portName = "EmployeePort",
        serviceName = "EmployeeService",
        targetNamespace = "http://blog.sodhanalibrary.com/wsdl"
)
public class EmployeeService {
    private static HashMap<String,Employee> empData = new HashMap<String,Employee>();
    

    @WebMethod(action="create",
            operationName="createEmployee",
            exclude=false)
    @WebResult(targetNamespace = "http://blog.sodhanalibrary.com/wsdl")
    public String createEmp(@WebParam(name = "id") String id,@WebParam(name = "name") String name,@WebParam(name = "email") String email ) {
        Employee emp = new Employee();
        emp.setId(id);
        emp.setEmail(email);
        emp.setName(name);
        empData.put(emp.getId(), emp);
        return "success";
    }
    
    @WebMethod(action="delete",
            operationName="deleteEmployee",
            exclude=false)
    @WebResult(targetNamespace = "http://blog.sodhanalibrary.com/wsdl")
    public String deleteEmp(String empID) {
        empData.remove(empID);
        return "success";
    }
    
    @WebMethod(action="read",
            operationName="readEmployee",
            exclude=false)
    @WebResult(targetNamespace = "http://blog.sodhanalibrary.com/wsdl")
    public EmployeeList readEmp() {
        EmployeeList empListPojo = new EmployeeList();
        Set<Entry<String, Employee>> eset = empData.entrySet();
        int i=0;
        Employee[] empList = new Employee[empData.size()]; 
        for(Entry<String, Employee> en : eset) {
            empList[i] = en.getValue();
            i++;
        }
        empListPojo.setEmployeeList(empList);
        empListPojo.setCount(empData.size());
        return empListPojo;
    }    
}

Generate web service 

Right click on the project, click on New > Web Service. Make web service configuration as like below.
Click on Browse and select EmployeeService class
Then click Finish

Test the Service 

Add the project to tomcat and start the server. Open http://localhost:8080/SimpleSoapExample/services/EmployeeService?wsdl in chrome / firefox browser. Then you can see the SOAP Service testing plugin icon like below. 

Click on those links and test respective web services.

SOAP UI Eclipse Plugin 

Install plugin

Download SOAP UI Eclipse plugin from here.
Click on Help > Install New Software > Add
Enter "SOAP UI" in the name field.
Click on Archive.. and select downloaded eclipse plugin archive file

Create New SOAP UI Project

Click on Window > Open Perspective > Other > soapUI
Right click on Projects > New soapUI Project
Enter "http://localhost:8080/SimpleSoapExample/services/EmployeeService?wsdl" in the Initial WSDL/WADL
Click on OK

Test the web service

Now it will show all web methods to test (createEmployee, deleteEmployee, readEmployee).

Read More
In this article I am going to explain how to read JSON with JavaScript. The basic part of the JSON is JsonElement. There are 4 types JSON elements.
  1. Json Object : Surrounded with curly braces and have child JSON elements
  2. Json Primitive Element : It contains field name and it's value
  3. Json Array Element : It contains field name and array of JSON elements.
  4. Json Null Element : It contains nothing 

Program Flow

Program flow for JSON reading is shown in the below diagram. 
  1. If element is JSON Object then iterate it into field names and JSON elements and process those JSON elements. 
  2. If element is JSON Array then iterate it into JSON elements and process those JSON elements.
  3. If element is JSON Primitive then print its value as String




JavaScript Code :

In the below example there are 4 JSON input strings, First 3 are normal JSON String, Fourth-one is Array.
checkIt - Is for to check the Object Type
readObject - Is for reading JSON Object
readArray - Is for reading JSON Array

   var object = {
        "age":23,
        "name":"srinivas",
        "blog":"http://blog.sodhanalibrary.com",
        "messages":["msg1","msg2","msg3"] 
    };

    var arrayConstructor = [].constructor;
    var objectConstructor = {}.constructor;

    var html='';

    checkIt(object);

    function checkIt(object) {
      if (object === null) {
        html += "\n\nnull \n";
      }
      else if (object === undefined) {
          html += "\n\nundefined \n";
      }
      else if (object.constructor === arrayConstructor) {
          html += "\n\nArray :: \n";
          readArray(object);
      }
      else if (object.constructor === objectConstructor) {
          readObject(object);
      }
      else {
         html += "\n\nPrimitive Datatype :: \n";
         html += object;
      }
    }
             

    function readObject(myobj) {
      html += "\n\nObject :: \n";
      html += myobj;
      for (key in myobj) {
        if (myobj.hasOwnProperty(key)) {
            html += "\n\nKey Value Pair :: \n";
            html += key + " = " + myobj[key];
            checkIt(myobj[key]);
        }
      }  
    }

    function readArray(myobj) {
      var n = myobj.length;
      html += myobj;
      for(var i=0;i<n;i++) {
        checkIt(myobj[i]);
        html += myobj[i];
      }
    }
    document.getElementById("jsonObject").innerHTML = html;

Read More

Search This Blog

Loading...

Blogroll

Srinivas Dasari
find me on facebook
follow me on twitter

Follow this blog by Email

Popular Posts