Sunday, December 17, 2017

Java Code to process Soap Request

 Hi guys, welcome to my blog. This post contains a sample java code to send soap request with XML post body. Recently in our project, we got a different requirement that we need to send soap request using Java code. For this example demo, I am using sample request available on this website.

In this example below are the details which I am going to use.

URL - www.dneonline.com/calculator.asmx
POST Body-
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <Add xmlns="http://tempuri.org/">
      <intA>1</intA>
      <intB>2</intB>
    </Add>
  </soap:Body>
</soap:Envelope>

Headers-
Content-Type:text/xml; charset=utf-8
Content-Length:length
SOAPAction:"http://tempuri.org/Add"

Below is the Java code for sending the above request,


package com.srikanth.SoapRequestExample;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class SoapRequest {
  
  public static void main(String a[]){
   try {
    int a1=3;
    int b=4;
    String requestXML="<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><Add xmlns=\"http://tempuri.org/\"><intA>"+a1+"</intA><intB>"+b+"</intB></Add> </soap:Body></soap:Envelope>";
    
    //We are creating and instance for URL class which is pointing to our specified url path
    URL url = new URL("http://www.dneonline.com/calculator.asmx");
    
    //Now we are opening the url connection  using the URLConnection class
    URLConnection connection = url.openConnection();
    
    //Converting the connection HTTP
    //If you want to convert to HTTPS use HttpsURLConnection
    HttpURLConnection httpConn = (HttpURLConnection) connection;
    
    //Below are the statements that gives the header details for the url connection
    httpConn.setRequestProperty("Content-Length", "length");
    httpConn.setRequestProperty("Content-Type","text/xml");
    httpConn.setRequestProperty("SOAPAction","http://tempuri.org/Add");
    httpConn.setRequestMethod("POST");
    
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);

    //Sending the post body to the http connection
    OutputStreamWriter out=new OutputStreamWriter(httpConn.getOutputStream());
    out.write(requestXML);
    out.close();
    
    InputStream newIP=httpConn.getInputStream(); 
    String temp;
    String tempResponse = "";
    String responseXML;
    
    // Read the response and write it to standard out.
    InputStreamReader isr = new InputStreamReader(newIP);
    BufferedReader br = new BufferedReader(isr);
    
    
    // Create a string using response from web services
    while ((temp = br.readLine()) != null) {
     tempResponse = tempResponse + temp;
     
    }
    responseXML = tempResponse;
    System.out.println(responseXML);
    //this.outputResponse=responseXML;
    br.close();
    isr.close();
    
    }
   catch (java.net.MalformedURLException e) {
    System.out.println("Error in postRequest(): Secure Service Required");
    e.printStackTrace();
   
   } catch (Exception e) {
    System.out.println("Error in postRequest(): " + e.getMessage());
    }
   
  }
  
}

      Most of the explanation for the above code is given in form of comments.

Note: We need to use a try-catch block to capture the exception as the URLConnection/ HttpURLConnection will throw an exception.


After successful execution, we can see the following result in the console.

Outut Response Body:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <AddResponse
            xmlns="http://tempuri.org/">
            <AddResult>7</AddResult>
        </AddResponse>
    </soap:Body>
</soap:Envelope>



Sunday, October 1, 2017

Saving the JMeter Recording

In this tutorial, we are going to discuss on how to save the recording of the JMeter so that it would be easy for comparison of post body and for doing the parameterization and correlation.
        Note: This setup has to be done before starting the recording.

STEPS:
1.Create your test plan and add the View Results Tree element under the HTTP(S) Test Script Recorder as shown in below snapshot
JMeter Test plan

2.Now if you observe carefully we have a configure option on the right side of the View Results Tree element as shown in below snapshot.

3.When we click on that tab we can see that it gives multiple options to select according to which it will record and also save.
4.Here we can see the Save as XMl option which is the main option. The tricky part which I have observed is if we first select the Save as XML option and then give the path for saving the XML the Save as XML option will not be selected instead we have to do in reverse that is first we have to give the path and then we have to select the Save as XML option.
Below is the snapshot for your reference,


Thursday, July 20, 2017

Python - Problem 1

Question:
Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included).The numbers obtained should be printed in a comma-separated sequence on a single line.Below is the solution code with the explanation.

Code:
l=[]

#starting with loop which will iterate from i1 to i2.Here we are using the Range function available in Python.
for i in range(2000,3201):
    #always becareful with the indent spaces.now we are in the loop.
    ##variable 'i' will be iterated every time and will contain value from 2000 to 3200for every iteration.
    if(i%7==0) and (i%5 != 0):
        #we are appending the satisifed value to the list 'l', but before appending we are converting the value to str for the next usage.
        l.append(str(i))
    #Here we are printing the list.join is used for combining the str values in a list with the specified seperator.
    #in our case the seperator is ',' 
print(','.join(l))
print("total numbers:",len(l))

Output:
     The above code is having hard coded values with a range from 2000 to 3200.Below is the output of the above code.
output of python code
Let us make some changes to above code so that it will accept different inputs and also with a check that the lower limit value does not exceed higher limit value.
Below is the modified code,

Modified Code:


import time
i1=int(input())
i2=int(input())

start_time = time.time()
l=[]

#starting with loop which will iterate from i1 to i2.Here we are using the Range function available in Python.
if(i1<i2):
    for i in range(i1 ,i2 ):

        #always be careful with the indent spaces.now we are in the loop.
        #variable 'i' will be iterated every time and will contain a value from i1 to i2 for every iteration.

        if(i%7==0) and (i%5 != 0):
            #we are appending the satisifed value to the list 'l', but before appending we are converting the value to str for the next usage.
            l.append(str(i))

    #Here we are printing the list.join is used for combining the str values in a list with the specified seperator.
    #in our case the seperator is ',' 
    print(','.join(l))
    print("total numbers:",len(l))

else:
    print("value 1 should be less than value 2")
print("---seconds---", (time.time() - start_time))

Output:
       The above code will produce the following output.
Python modified code problem 1 output

Wednesday, July 19, 2017

Python-Printing the list elements on one line with comma separated

                This blog post is about printing the string values present in the list into a single line separated by a comma.

Input: [‘1’,’2’,’3’]
Output: 1, 2, 3

Code:
      #let us take a list with the elements ‘s’,’t’,’r’,’i’,’n’,’g’
      l=[‘s’,’t’,’r’,’i’,’n’,’g’]
      # now this is converted to our required format using the join function and
      # Below is the implementation

      print(‘,’.join(l))

Output:
                s,t,r,i,n,g