Dec 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>



Oct 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,


Jul 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

Jul 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

Feb 27, 2017

Modifying/Creating Excel files using data from CSV - JMETER

                          Hello guys, this post is to discuss how to write a bean shell code to generate excel files based upon a template file. I faced this issue when the requirement is like we have to generate multiple excel files with few cell's data modified in it.


Manual method: It requires more time as we have to copy and paste it. This method is suitable if the excel generation is one time and also if the requirement is very few excel files.

Example Scenario:

                 Generate 2 excel files using the template file "Sample.xlsx". These two excel files should contain data from input.csv file at first cell and third cell in the first row and at the first cell in the second row as shown below.
Template excel file


                Before proceeding further we need the POI jar files which can be found here and you will be redirected to Apache website.
                                                                 
Apache website


            Extract the jar files into JMeter's library folder in our case we are adding all POI jar files. It is up to you whether to add all the jars or to choose the required one.
                                                                 
Reqiured Jar Files

Word of caution:
After adding the jar files we have to restart/reopen JMeter to get the jar files included

           Now let us open the JMeter and add the following components as shown in the following snapshot.

JMeter


Use of each component is stated below,
  1. Loop controller: This component will help us to apply loop. In our case, it will be useful for generating "n" number of files.
  2. Counter: To increment the value and pass it to the bean shell.
  3. CSV Data Set config: To retrieve the values from CSV file and store them in JMeter variables.
  4. Bean shell sampler: Where we can code to write into excel file
Now let us create a CSV file having data in it as shown below,
CSV file with data

Specify the path of the input file into CSV data set config along with three variables as we are having three columns having values in it.
CSV data config in Jmeter

In counter specify the limits and give a variable name as shown below,
JMeter Test Plan
                               In this counter, I have given reference name(JMeter's variable) as 'filenum' which will be passed into bean shell code.

Now add the following code into bean shell sampler,
//Importing the jar files 
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;

//The following string represents the value from CSV
String v1=vars.get("va1");
String v2=vars.get("va2");
String v3=vars.get("va3");

//extracting the loop count to give the file name
String filenumber=vars.get("filenum");
//Creating an object with the file linked to it
FileInputStream excelFile = new FileInputStream("E:\\blog\\sample.xlsx");
//create a workbook object to excelfile
XSSFWorkbook workbook = new XSSFWorkbook(excelFile);
//Getting the sheet 0
XSSFSheet sheet = workbook.getSheetAt(0);
//accessing first row
XSSFRow row = sheet.getRow(0);
//accessing the first cell
Cell a1 = row.getCell(0);
a1.setCellValue(v1);
Cell a2=row.getCell(2);
a2.setCellValue(v2);
XSSFRow row1 = sheet.getRow(1);
Cell a3 = row1.getCell(0);
a3.setCellValue(v3);
FileOutputStream out = new FileOutputStream(
new File("E:\\blog\\sample"+filenumber+".xlsx"));
workbook.write(out);
out.close();

Beanshell program in JMeter
Word of caution:
             Before executing close the excel files which are open so that execution will not fail.

Now after executing it we get two files generated into the folder,
View Result Tree component in JMeterFile Explorer
 Now we can see that the excel file is contains data from CSV at specified cells.
                 -file: Sample1

Generated Excel file 1

                 -file: Sample2
Generated Excel file 2



Feb 13, 2017

What's Your Name?

You are given the firstname and lastname of a person on two different lines. Your task is to read them and print the following:
Hello firstname lastname! You just delved into python.
Input Format
The first line contains the first name, and the second line contains the last name.
Constraints
The length of the first and last name ≤ .
Output Format
Print the output as mentioned above.
Sample Input
Guido
Rossum
Sample Output
Hello Guido Rossum! You just delved into python.
Explanation
The input read by the program is stored as a string data type. A string is a collection of characters.
My Python 2.0 Code:
s=raw_input()
s2=raw_input()
print ("Hello ")+ s,s2+("! You just delved into python." )

Converting String into List-Python

     In this tutorial I will share you how to convert a input string into list containing each character.
In python 3 we have combined function that is input() for reading any type of input.Consider the following example
                       >>> invalue=input()
                       1234567789
                       >>> print(type(invalue))
                       <class 'str'>
                        >>> print(invalue)
                       1234567789
              Here we are using the input() function to read the string and store the value into the variable invalue. Now in order to convert this string into list we use the list() as given below

                        >>> inlist=list(invalue)
                        >>> print(type(inlist))

                        <class 'list'>
                        >>> print(inlist)
                       ['1', '2', '3', '4', '5', '6', '7', '7', '8', '9']
             From the above example we can see that the string can be converted into list using list().

Code To Convert Excel to Base64 -Jmeter

 Consider a scenario as follow like
                                1.Click on Upload button
                                2.Select the excel file to upload
                                3.Click upload
              We can record it and can correlate, but what if the excel file which is getting uploaded is converting into base64 and then getting uploaded. If this is the case we can write a simple bean shell code to convert that file into base64 string and save it into Jmeter Variable.

Below is the code for this conversion:
import java.io.*;
import org.apache.commons.codec.binary.Base64;

BufferedReader infile = new BufferedReader(new FileReader("--FileName with Extension--"));
String br;
String v1="";

/*Looping till the end of the file*/
while((br=infile.readLine())!=null)
{
/*Converting each byte to relevant base64 format */
byte[] encryptedUid = Base64.encodeBase64(br.getBytes());

/*Appending the converted base64 string */
v1=v1+new String(encryptedUid);
}

/*saving the string v1 into Jmeter variable genStringValue */
vars.put("genStringValue",v1);


Below are snapshots of the working code in Jmeter:

1.Excel file which has to be converted into base64 format


Sample Excel file to base 64

2. Jmeter Script having Bean shell code for converting the excel file into base64
JMeter Beanshell code
3.Below picture shows the Jmeter variables in which genStringValue consists of base64 format of the excel file
Excel in form of base64

Jan 31, 2017

Arrays - DS:An array is a type of data structure that stores elements of the same type in a contiguous block of memory

An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, , of size , each memory location has some unique index, (where ), that can be referenced as (you may also see it written as ).
Given an array, , of integers, print each element in reverse order as a single line of space-separated integers.
Note: If you've already solved our C++ domain's Arrays Introduction challenge, you may want to skip this.
Input Format
The first line contains an integer, (the number of integers in ).
The second line contains space-separated integers describing .
Constraints


Output Format
Print all integers in in reverse order as a single line of space-separated integers.
Sample Input
4
1 4 3 2
Sample Output
2 3 4 1
 
 
My Code in C:
 
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int n,j=0; 
    int arr_i;
    scanf("%d",&n);
    int *arr = malloc(sizeof(int) * n);
    int *rarr=malloc(sizeof(int) * n);
    for( arr_i = 0; arr_i < n; arr_i++){
       scanf("%d",&arr[arr_i]);
    }
    for(arr_i = n-1; arr_i >= 0; arr_i--){
       rarr[j]=arr[arr_i];
        printf("%d ",arr[arr_i]);
        j++;
    }
    return 0;
}