Wednesday 27 March 2013

JDK6 Collection New Features ArrayDeque, LinkedBlockingDeque, ConcurrentSkipListSet and ConcurrentSkipListMap Example

Deque and ArrayDeque

/*Deque interface defines some methods that access the element at both ends. Which means that

  by the methods of this interface we can add and remove the elements at both ends.
 
  ArrayDeque is a class that implements Deque.It can perform faster than Stack when used as a stack and 
 
  faster than LinkedList when used as a queue.

 */

package com.gaurav.jdk6newfeatures;


import java.util.ArrayDeque;

import java.util.Iterator;


public class ArrayDequeExample

{

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String arg[])

            {

                           ArrayDeque arrayDeque = new ArrayDeque();

                        //Inserting elements using various methods of ArrayDeque

                           arrayDeque.add("Samsung");

                           arrayDeque.addFirst("Sony");

                           arrayDeque.offerFirst("Micromax"); 

                           arrayDeque.offerLast("LG");

                        Iterator it = arrayDeque.iterator();

                        while(it.hasNext())

                        {

                                    System.out.println(it.next());

                        } 
                       

                        System.out.println("Retrieving First Element :" + arrayDeque.peekFirst());

                        System.out.println("Retrieving Last Element :" + arrayDeque.peekLast());

                        System.out.println("Removing First  Element :" + arrayDeque.pollFirst());

                        System.out.println("Removing Last  Element :" + arrayDeque.pollLast());

                        //Traversal in Reverse order

                        System.out.println("Remaining Elements :");

                        Iterator it1 = arrayDeque.descendingIterator();

                        while(it1.hasNext())

                        {

                                    System.out.println(it1.next());

                        }                    

            }

}


/*
Remember : 

 1. peekFirst() method retrieves first element from the ArrayDeque.

 2. peekLast() method retrieves last element from the ArrayDeque.

 3. pollFirst() method removes first element from the ArrayDeque. 

 4. pollLast() method removes last element from the ArrayDeque.
*/


BlockingDeque and LinkedBlockingDeque

/*
A BlockingDeque is similar to Deque and provides additional functionality.

When we tries to insert an element in a BlockingDeque, which is already full,

it can wait till the space become available for inserting an element. We can also

specify the wait time period limit.

BlockingDeque methods are available in four flavor:-

    Method throws exception
    Method returns special value
    Method that blocks(Waits indefinitely for space to be available)
    Method that times out(Waits for a given time period for space to be available)
*/

package com.gaurav.jdk6newfeatures;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

public class LinkedBlockingDequeExample implements Runnable{
   
    @SuppressWarnings("rawtypes")
   
    BlockingDeque blockingDeque = new LinkedBlockingDeque(1);
    volatile boolean flag = true;
   
    @SuppressWarnings("unchecked")
    public void run()
    {
        try
        {
            /*First thread once enters into the block it modifies
              instance variable flag to false and prevents second
              thread to enter into the block */
             if(flag)
            {
                flag = false;
                Thread.sleep(3000);//Makes the Thread to sleep for 3 seconds
                System.out.println("Removing the element - "+blockingDeque.peek());
                blockingDeque.poll();//Removing an element from collection
            }
            else
            {
                System.out.println("Waiting ");   
                /*This method makes to wait till the first thread removes an elements*/
                blockingDeque.put("Kumar");
                System.out.println("Inserted element - "+blockingDeque.peek());   
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
   
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws Exception
    {
        LinkedBlockingDequeExample linkedBlockingDequeExample = new LinkedBlockingDequeExample();
        linkedBlockingDequeExample.blockingDeque.offer("Gaurav");
        System.out.println("Inserted the element - "+linkedBlockingDequeExample.blockingDeque.peek());   
        Thread threadObj1 = new Thread(linkedBlockingDequeExample);
        threadObj1.start();
        Thread threadObj2 = new Thread(linkedBlockingDequeExample);
        threadObj2.start();       
    }
}

NavigableSet and ConcurrentSkipListSet


/* NavigableSet extends SortedSet and is implemented by TreeSet and concurrentSkipListSet (a new class in Java collection).

   ConcurrentSkipListSet is one of the class that implements NavigableSet and it is used to return the closest matches of elements.
  
   It includes methods to return iterators in ascending and descending orders, as well as methods that return a sorted or navigable set
  
   for a special portion of data.

 */

package com.gaurav.jdk6newfeatures;

import java.util.Iterator;
import java.util.NavigableSet;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

public class ConcurrentSkipListSetExample

{

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args)

    {

        System.out.println("Example of Navigable Set");

        NavigableSet navigableSet = new ConcurrentSkipListSet();

        navigableSet.add("30");

        navigableSet.add("90");

        navigableSet.add("20");

        navigableSet.add("10");

        navigableSet.add("80");

        navigableSet.add("70");

        Iterator iterator = navigableSet.iterator(); // Returns an iterator over the
                                                // elements in navigable set, in
                                                // ascending order.

        System.out.print("In ascending order :");

        while (iterator.hasNext())

        { // Ascending order list

            System.out.print(iterator.next() + " ");

        }

        System.out.println(); // Descending order list

        System.out.println("In descending order : " + navigableSet.descendingSet()
                + "\n");

        System.out.println("Remove element: " + navigableSet.pollLast());

        // After removing the last element, now get navigable set

        System.out.println("Now navigable set: " + navigableSet.descendingSet());

        ConcurrentSkipListSet<Integer> conSkipListSet = new ConcurrentSkipListSet<Integer>();

        conSkipListSet.add(40);
        conSkipListSet.add(35);
        conSkipListSet.add(25);
        conSkipListSet.add(55);
        System.out.println("Elements in the collections are");

        for (Integer i : conSkipListSet) {
            System.out.println(i);
        }

        /* Retrieve immediate element less than or equal to the given element */
        System.out.println("Floor    " + conSkipListSet.floor(28));

        /* Retrieve immediate element greater than or equal to the given element */
        System.out.println("Ceiling  " + conSkipListSet.ceiling(20));

        /* Retrieve immediate element less than the given element */
        System.out.println("Lower    " + conSkipListSet.lower(30));

        /* Retrieve immediate element greater than the given element */

        System.out.println("heigher  " + conSkipListSet.higher(40));
        System.out.println("Head Elements ");
        Set<Integer> cslsHeadView = conSkipListSet.headSet(35);

        // HeadSet will exclude the given element

        for (Integer i : cslsHeadView) {
            System.out.println(i);
        }
        Set<Integer> cslsTailView = conSkipListSet.tailSet(35);

        // TailSet will include the given element

        System.out.println("Tail Elements");
        for (Integer i : cslsTailView) {
            System.out.println(i);
        }

    }

}


/*
  Remember :
  
  Data insertion is possible in NavigableSet using the "add()" method.
 
  NavigableSet provides the facility for retrieving the data in ascending and descending order.
 
  The "descendingSet()" method returns the data from the NavigableSet in descending order.
 
  We can use "pollFirst()" method to remove the element from the set at first position and " pollLast()" method to remove
 
  element from NavigableSet at last position.
 */


NaviagableMap and ConcurrentSkipListMap


/* NaviagableMap is similar to NaviagableSet. In NavigableSet, methods use to return values, but in NaviagableMap methods
  
   used to return the key,value pair.ConcurrentSkipListMap is the one of the class which implements NaviagableMap.
*/
package com.gaurav.jdk6newfeatures;

import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.SortedMap;
import java.util.concurrent.ConcurrentSkipListMap;

public class ConcurrentSkipListMapExample {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] arg)

    {

        System.out.println("Example of Navigable Map ");

        NavigableMap navmap = new ConcurrentSkipListMap();

        navmap.put(1, "January");

        navmap.put(2, "February");

        navmap.put(3, "March");

        navmap.put(4, "April");

        navmap.put(5, "May");

        navmap.put(6, "June");

       
        System.out.println("Data in the navigable map: "
                + navmap.descendingMap() + "\n");

        // Retrieving first data

        System.out.println("First data: " + navmap.firstEntry() + "\n");

        // Retrieving last data

        System.out.print("Last data: " + navmap.lastEntry() + "\n");

        // Retrieving the nearest less than or equal to the given key

        System.out.println("Nearest less than or equal to the given key: "
                + navmap.floorEntry(5) + "\n");

        // Retrieving the greatest key strictly less than the given key

        System.out
                .println("Retrieving the greatest key strictly less than the given key: "
                        + navmap.lowerEntry(3));

        // Retrieving a key - value associated with the least key strictly greater than the given key
       
        System.out
                .println("Retriving data from navigable map greater than the given key:    "
                        + navmap.higherEntry(5) + "\n");

        // Removing first entry

        System.out.println("Removing First: " + navmap.pollFirstEntry());

        // Removing last entry

        System.out.println("Removing Last: " + navmap.pollLastEntry() + "\n");

        // Displaying all data

        System.out.println("Now data: " + navmap.descendingMap());

       
        NavigableMap navigableMap = new ConcurrentSkipListMap();
       
        navigableMap.put(1,"First");
        navigableMap.put(2,"Second");
        navigableMap.put(3,"Third");
        navigableMap.put(4,"Fourth");
        navigableMap.put(5,"Fifth");
        navigableMap.put(6,"Sixth");
       
        /* It Retrieves the key - value pair immediately lesser than the given key */
        Map.Entry ae = navigableMap.lowerEntry(5);
       
        /* Map.Entry is a Static interface nested inside Map
           interface,It is used to hold key and value */
       
        System.out.println("Key - " + ae.getKey());
        System.out.println("Value - "+    ae.getValue());
       
        /* Retrieves key - value pairs equal to and greater then the given key */
       
        SortedMap sortedMap = navigableMap.tailMap(3);
       
        Set<Integer> s = sortedMap.keySet();
       
        System.out.println("Tail elements are:-");
        for(Integer i:s)
        {
            System.out.println("Key - "+ i + "Value - "+ sortedMap.get(i));
            }
        }
    }


/*
 Remember : 

  1. lowerEntry() method retrieves less than the givenkey (or) null.
 
  2. floorEntry() method retrieves less than or equal to the givenkey (or) null.

  3. headMap() method retrieves all elements less than the givenkey. 

  4. tailMap() method retrieves all elements greater than or equal to the givenkey.
 */

Saturday 23 March 2013

Steps for Creating a Soap WebService mock project Using soapUI


Creating a soap web service mock project using soapUI

Steps for creating mock project

  1. Open Soapui and select New SoapUI project.
  2. A popup will appear like below:-





    3.  Fill the Required details as below after targeting the WSDL file path.






    StudService.wsdl File Content:-

    <?xml version="1.0" encoding="UTF-8" standalone="no"?><wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:sch="http://localhost:7070/gaurav/springws/ContractFirstStudentService" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://localhost:7070/gaurav/springws/ContractFirstStudentService" targetNamespace="http://localhost:7070/gaurav/springws/ContractFirstStudentService">
      <wsdl:types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://localhost:7070/gaurav/springws/ContractFirstStudentService">

                <element name="studentRequest">
                            <complexType>
                                        <sequence>
                                                    <element name="id" type="string"/>
                                        </sequence>
                            </complexType>
                </element>
                <element name="studentResponse">
                            <complexType>
                                        <sequence>
                                        <element name="studentdetails" type="tns:studentdetails"/>
                                        </sequence>
                            </complexType>
                </element>
                <complexType name="studentdetails">
                            <sequence>
                                        <element name="name" type="string"/>
                                        <element name="total" type="string"/>
                                        <element name="address" type="tns:address"/>
                                       
                            </sequence>
                </complexType>
                <complexType name="address">
                            <sequence>
                                       
                                        <element name="flatNo" type="string"/>
                                        <element name="street" type="string"/>
                                        <element name="city" type="string"/>
                                        <element name="state" type="string"/>
                                        <element name="pin" type="string"/>
                            </sequence>
                </complexType>
    </schema>
      </wsdl:types>
      <wsdl:message name="studentRequest">
        <wsdl:part element="tns:studentRequest" name="studentRequest"/>
      </wsdl:message>
      <wsdl:message name="studentResponse">
        <wsdl:part element="tns:studentResponse" name="studentResponse"/>
      </wsdl:message>
      <wsdl:portType name="StudService">
        <wsdl:operation name="student">
          <wsdl:input message="tns:studentRequest" name="studentRequest"/>
          <wsdl:output message="tns:studentResponse" name="studentResponse"/>
        </wsdl:operation>
      </wsdl:portType>
      <wsdl:binding name="StudServiceSoap11" type="tns:StudService">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="student">
          <soap:operation soapAction=""/>
          <wsdl:input name="studentRequest">
            <soap:body use="literal"/>
          </wsdl:input>
          <wsdl:output name="studentResponse">
            <soap:body use="literal"/>
          </wsdl:output>
        </wsdl:operation>
      </wsdl:binding>
      <wsdl:service name="StudServiceService">
        <wsdl:port binding="tns:StudServiceSoap11" name="StudServiceSoap11">
          <soap:address location="http://localhost:7070/ContractFirstStudentService/services"/>
        </wsdl:port>
      </wsdl:service>
    </wsdl:definitions>


    4)      After browsing the wsdl file path in Initial WSDL/WADL option
                Check mark the Create sample Requests and Create TestSuite options.
    5)  After clicking on OK below popup will appear.


     

6) Click on OK, again a popup will appear, which is as follows:-

7)   Click on OK.

8)      Now Project will appear as below:-  



9)      Select the project StudentSoapUIWebServiceMocking and right click on it:-



10)  Select the option New MockService. After selection a popup will appear as below :-



11)   Fill this text box with any name like below and click on OK.  


12)   Right Click on StudentMockService and select the option New MockOperation


 

13)   A popup will appear like below, Click on OK.



14) Right Click on student operation and select New MockResponse option.




15)   Provide the Mock Response names as per the requirement, I kept the names like SuccessMockResponse and FailureMockResponse.

16)  Double click on the student operation, A window will be opened like below-
                               Select dispatch type as Script, as by default it is SEQUENCE



17) Write the groovy script as per the Response presentation like below:- 



import groovy.util.XmlSlurper

            def parsedContent = new XmlSlurper().parseText(mockRequest.requestContent)

            //dispatch based on request student id
           
            def studId = parsedContent.Body.studentRequest.id.toString()
           
            def responseToUse = "";

            log.info "studId is->"+studId

            if (studId.equals("0") || studId.equals("")) {
                        responseToUse = "FailureMockResponse"
            }

            else{
                         responseToUse = "SuccessMockResponse"
                        }
            return responseToUse
                       
  18) The Screen will appear as below:-



19) Fill the Required details in the Success and Failure mock responses as per the 

                   response representation. 


Success Mock Response is as below:-

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:con="http://localhost:7070/gaurav/springws/ContractFirstStudentService">
   <soapenv:Header/>
   <soapenv:Body>
      <con:studentResponse>
         <con:studentdetails>
            <con:name>Gaurav</con:name>
            <con:total>1000</con:total>
            <con:address>
               <con:flatNo>FLAT No-XXX</con:flatNo>
               <con:street>DENIZEN COMPLEX</con:street>
               <con:city>HYDERABAD</con:city>
               <con:state>ANDHRA PRADESH</con:state>
               <con:pin>500034</con:pin>
            </con:address>
         </con:studentdetails>
      </con:studentResponse>
   </soapenv:Body>
</soapenv:Envelope>

            Failure Mock response is as below:-
           
            <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:con="http://localhost:7070/gaurav/springws/ContractFirstStudentService">
   <soapenv:Header/>
   <soapenv:Body>
      <con:studentResponse>
         <con:studentdetails>
            <con:name>INVALID NAME</con:name>
            <con:total>NOT FOUND</con:total>
            <con:address>
               <con:flatNo>N/A</con:flatNo>
               <con:street>N/A</con:street>
               <con:city>N/A</con:city>
               <con:state>N/A</con:state>
               <con:pin>N/A</con:pin>
            </con:address>
         </con:studentdetails>
      </con:studentResponse>
   </soapenv:Body>
</soapenv:Envelope>

20) Right Click on StudentMockService and select option Show MockService  Editor .                 A window will appear like below:-



21)  From the above window, Select the option Sets options for this MockService. In the appeared dialog box fill the reuired details like below:-


Note:- We can place any path and port-number(empty portnumber not using by any                                   services).
   
22)  Double click on the student request and select edit current endpoint in Address bar.   

            http://<hostname>:<MockService Running PortNumber>/path declared in mockservice     above.




23)  Send the reuired parameters in student request, here I need to send student id and I am sending student id as – 5 as per the groovy script if i will send student id as – 5 or any number then i should get success mock response or if i will send student id as – 0 or blank then i should get fail mock response.

24)   Start the StudentMockService on the specified port and endpoint by clicking on Green Button.


25) After Sending the student request proper success mock response will appear as  below:-

                          


26)  After Sending the student request for fail, mock response will appear as below:-   



27)  When student id is sent as blank in student request, we will get fail mock response:-