import com.eviware.soapui.impl.wsdl.teststeps.*

def list = []
list.add(jsessionid)
def headers = testStep.testRequest.requestHeaders
headers["Cookie"] = list
testStep.testRequest.requestHeaders = headers
log.info testStep.testRequest.requestHeaders["Cookie"]
package com.mugil.first
import jxl.*
import jxl.write.*


class ExcelUtils {
	public static void main(String[] args)
	{
		writeExcel()
		readExcel()
	}
	
	static def writeExcel()
	{
		WritableWorkbook workbook = Workbook.createWorkbook(new File("d:\\output.xls"))
		WritableSheet sheet = workbook.createSheet("Worksheet1", 0)		 
		
		for(int i=0;i<3;i++)
		{
			for(int j=0;j<5;j++)
			{
				Label label = new Label(i, j, i+","+j);
				sheet.addCell(label);
			}
		}		
		
		workbook.write()
		workbook.close()	
		
	}
	
	static def readExcel()
	{
		Workbook workbook1 = Workbook.getWorkbook(new File("d:\\output.xls"))
		Sheet sheet1 = workbook1.getSheet(0)
		Cell a1 = sheet1.getCell(0,2) 
		Cell b2 = sheet1.getCell(2,2) 
		Cell c2 = sheet1.getCell(2,1)
		
		println a1.getContents();
		println b2.getContents();
		println c2.getContents();		
		
		workbook1.close()
	}
}

What def Keyword Does?
def is a replacement for a type name. In variable definitions it is used to indicate that you don’t care about the type. In variable definitions it is mandatory to either provide a type name explicitly or to use “def” in replacement. This is needed to make variable definitions detectable for the Groovy parser.You can think of def as an alias of Object and you will understand it in an instant.

def name = "Stephanie"
println name.toUpperCase() // no cast required

while you would need an explicit cast in the Java version

Object name = "Stephanie";
System.out.println(((String) name).toUpperCase());

Omitting the “def” keyword puts the variable in the bindings for the current script and groovy treats it (mostly) like a globally scoped variable:

x = 1
assert x == 1
assert this.binding.getVariable("x") == 1

Using the def keyword instead does not put the variable in the scripts bindings:

def y = 2
assert y == 2
try {
    this.binding.getVariable("y") 
} catch (groovy.lang.MissingPropertyException e) {
    println "error caught"
} 

Prints: “error caught”

If you define a method in your script, it won’t have access to the variables that are created with “def” in the body of the main script as they aren’t in scope:

x = 1
def y = 2

public bar() {
    assert x == 1

    try {
        assert y == 2
    } catch (groovy.lang.MissingPropertyException e) {
        println "error caught"
    }
}

bar()

prints “error caught”

The “y” variable isn’t in scope inside the function. “x” is in scope as groovy will check the bindings of the current script for the variable.

JARs to be added

  • poi-3.8.jar
  • poi-examples-3.8.jar
  • poi-excelant-3.8.jar
  • poi-ooxml-3.8.jar
  • poi-ooxml-schemas-3.8.jar
  • poi-scratchpad-3.8.jar
  • dom4j-1.6.1.jar

Reading Excel Sheet

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
 
class ExcelReader {
  
  def readData() {
        def path = "D:\\Test.xlsx";
        InputStream inputStream = new FileInputStream(path);
        Workbook workbook = WorkbookFactory.create(inputStream);
        Sheet sheet = workbook.getSheetAt(0);
                      
        Iterator rowIterator = sheet.rowIterator();
        rowIterator.next()
        Row row;                       
        def rowsData = []
        while(rowIterator.hasNext()) {
             row = rowIterator.next()
             def rowIndex = row.getRowNum()
             def colIndex;
             def rowData = []
             for (Cell cell : row) {
                 colIndex = cell.getColumnIndex()
                  rowData[colIndex] = cell.getRichStringCellValue().getString();
             }                    
             rowsData << rowData
         }
         rowsData
  }
 }
 
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def myTestCase = context.testCase
 
ExcelReader excelReader = new ExcelReader();
List rows = excelReader.readData();
def d = []
Iterator i = rows.iterator();
while( i.hasNext()){
         d = i.next();
         myTestCase.setPropertyValue("From", d[0])
         myTestCase.setPropertyValue("To", d[1])       
         testRunner.runTestStepByName( "ConversionRate")
}

Below are the code sample which shows how to carry out basic tasks in Jython.The Files should be shared as .py extension if your are using eclipse.To know abount configuring jython in eclipse follow the
Link

Printing a Message in Console

  print 1 + 1
  print "Hello" + " World "
  print "Hello Jython "
  print "Jython ", "Scripting"

Simple Jython Function that Takes Argument and Print Values

def displayName(x):
 print x 
 
displayName("Mugil")

Jython Function which Calculates the Factorial of a Number

def factorial(x):
 if x<=1 : 
  return 1    
 return x * factorial(x-1)
 
print factorial(3)

Function which compares Two Strings in If Condition

def compareName(FirstName, LastName):
 if FirstName == LastName:
  print "They are Equal"
 else:
  print "They are Not Equal"  
   
   
compareName("Jython", "Jython")

Conditional Operators
Function which Perform AND, OR and Not Ops

def BoolOps(pOne, pTwo): 
 if pOne and pTwo:
  print "They are Equal"
 else:
  print "They are Not Equal" 
  
BoolOps(1,0)

Jython Conditional Operators

Jython Supports Three Numeric Values as Below

  • Integers
  • Long
  • Floating Point

Array from Delimited String and Looping through It

Names = "A, B, C, D, E"

arrNames = Names.split(",")

for x in range(len(arrNames)):
 print arrNames[x]

Array Function

Names = "A,B,C,D,E,F,G,H,I,J,K,L,M"

arrNames = Names.split(",")

#B
print arrNames[1]

#['B']
print arrNames[1:2]

#['B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M']
print arrNames[1:]

#['A', 'B', 'C', 'D', 'E', 'F']
print arrNames[:6]

#['B', 'C', 'D', 'E']
print arrNames[1:5]

#['H', 'I', 'J']
print arrNames[-6:-3]

#['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M']
print arrNames[:]

#['A', 'C', 'E', 'G', 'I', 'K', 'M']
print arrNames[::2]

Concatenating Two Arrays together

Names1 = "A,B,C"
Names2 = "D, E, F"

arrNames1 = Names1.split(",")
arrNames2 = Names2.split(",")

arrNames = arrNames1 + arrNames2

for i in range(len(arrNames)):
 print arrNames[i]

import jarray
import java
myArray = jarray.array(["mugil", "Vannan"], java.lang.Object)

rc.logMessage(str(len(myArray)))

for value in myArray:
 rc.logMessage(value)

For Character

myArray = jarray.array(["m", "V"], "c")

For Integer

import jarray
import java
myArray = jarray.array([1,2,3,4,5,6], java.lang.Integer)

rc.logMessage(str(len(myArray)))

for value in myArray:
 rc.logMessage(str(value))

I am having single column in excel sheet which I want to replicate in Jython scripting and place it in adjacent column.The Content of the Column is as in the Pic below

from jxl import *
from jxl.write import *
from java.io import File
workbook = Workbook.getWorkbook(File("$(TargetFolder)\Book2.xls"))
targetWorkbook = Workbook.createWorkbook(File("$(TargetFolder)\Book2.xls"),
workbook)
sheet = targetWorkbook.getSheet(0)
columnIndex = 0

rowCount = sheet.getRows()

for i in range(rowCount):
 row = sheet.getRow(i)
 content = row[columnIndex].getContents()
 rc.logMessage("Content -> " + content)    
 wc = sheet.getWritableCell(1,i)
 newLabel = Label(1,i, content)
 sheet.addCell(newLabel)
 
targetWorkbook.write() 
targetWorkbook.close()
workbook.close()

Before running Script
null

After running Script
null