Skip to main content
Version: 10.3.1

Code samples

We have put together some examples of custom scripts that you can use in your recordings.

tip

To learn more about using code in your actions, refer to Script as custom action.

How to use a code sample?

When adding a custom script in your recording, proceed as follows.

  1. Add a Script action from the Script as custom action group in Actions library to the Actions flow.
  2. Copy a code sample from this page and insert it into the Script area within the Script action.
  3. Create the input-output variables used in the script in the Recorder Variables tab.

If you have more than one custom script in the recording, you need to define a different method for each action, for example, CustomScriptAction1 in the example below. The name of the class has to start with a letter.

@CustomScriptAction(
input = ['my_timezone'],
output = 'resdate'
)

def CustomScriptAction1() {

def now = new Date()
resdate=RDateTime.fromRepresentation(now.format("yyyy-MM-dd HH:mm:ss", TimeZone.getTimeZone("${my_timezone}")), "yyyy-MM-dd HH:mm:ss;en-US;${my_timezone}")

}

Work with logical operators

Multiple If conditions

Variables (name and type):

  • failcheck1: Boolean
  • failcheck2: Boolean
  • failcheck3: Boolean
  • failcheck4: Boolean
  • failcheck5: Boolean
  • finalfailcheck: Boolean
@CustomScriptAction(
input = ['failcheck1','failcheck2','failcheck3','failcheck4','failcheck5'],
output = 'finalfailcheck'
)

def customScript() {

if( (failcheck1) == (RBoolean.fromCanonical('true')) || (failcheck2) == (RBoolean.fromCanonical('true'))
|| (failcheck3) == (RBoolean.fromCanonical('true')) || (failcheck4) == (RBoolean.fromCanonical('true'))
|| (failcheck5) == (RBoolean.fromCanonical('true'))) {

finalfailcheck = RBoolean.fromCanonical('true')

} else {

finalfailcheck = RBoolean.fromCanonical('false')
}

}

Compare more than one variable in If-Else condition

This custom script is an example that does a comparison of arithmetic operations. You could also perform other operations, for example, compare text, regexp, etc., and make as many logical operations as you want. The script outputs true if ALL conditions are true.Otherwise, it outputs false.

Variables (name and type):

  • condition1: Number
  • condition2: Number
  • condition3: Number
  • boolean_result: Boolean
@CustomScriptAction(
input = ['condition1', 'condition2', 'condition3'],
output = 'boolean_result'
)

def customScript() {

def c1 = RNumber.of(condition1)
def c2 = RNumber.of(condition2)
def c3 = RNumber.of(condition3)


if(
(c1 < c2) && // "&&" is the logical operator AND
(c2 <c3) && // This structure allows you avoid nested "IF" statements in recorder
(c2*c3 < 10) // by using one BOOLEAN result in one IF branch.
){

def boolean_result = RBoolean.of(true)

} else{

def boolean_result = RBoolean.of(false)
}

}

Work with strings

Use regexp to create substring

The matcher object depends on the number of capturing groups inside the regexp that was used. For example, if you have three capturing groups denoted by the brackets ( … ):

  • matcher[0][0] refers to everything that matched the regexp.
  • matcher[0][1] refers to the first capture in the match.
  • matcher[0][2] refers to the second capture in this match.

Variables (name and type):

  • original_str: String
  • result_str: String
@CustomScriptAction(
input = ['original_str'],
output = 'result_str'
)

def regexSubstring() {
def regex = /(\d\d\d\d)-(\d\d)(-\d\d[a-zA-Z])?/
def matcher = (original_str =~ /$regex/)
result_str = RString.of(matcher[0][0])
}

Get file name from path

import org.apache.commons.io.FilenameUtils

@CustomScriptAction(
input = ['input_str'],
outout = 'output_str'
)

def getFileNameFromPath() {
output_str = RString.of(FilenameUtils.getBaseName(input_str.toString()))
}

Miscellaneous

Modify time period

To generate the date based on today's date, you can either modify the number of days or the number of months.

Variables (name and type):

  • date1: DateTime
  • date2: DateTime

Modify day in date

@CustomScriptAction(
input = ['date1'],
output = 'date1'
)
def customeScript() {
date1 = date1.minus(java.time.Duration.ofDays(1))
}

Modify month in date

@CustomScriptAction(
input = ['date1'],
output = 'date2'
)
def customeScript() {
date2 = date1.plus(java.time.Period.ofMonths(1))
}

Download file from remote server

Variables (name, type, and default value):

  • web_url: String, https://rpa-tutorial.s3.amazonaws.com/trainings/Tickers.xlsx
  • local_file_link: String
@CustomScriptAction(
input = ['web_url'],
output = 'local_file_link'
)

def customScript() {
def link = downloadFileOnAgent(web_url.toString())
local_file_link = RString.of(link)
}

Select text and copy to clipboard

Variables (name, type, and default value):

  • form_url: String, https://rpa-tutorial.s3.amazonaws.com/trainings/iframe/form.html
@CustomScriptAction(
input = ['form_url']
)

def customScript() {
openAndFocus('notepad.exe', 3000, 250)
sendKeys('New line')
selectAllTextAndCopy()

openIE(form_url.toString())
$(byXpath('//div[8]/input')).pressCtrlV()
}

Click with some keyboard combination pressed

@CustomScriptAction

def customScript() {

// selecting multiple elements by SHIFT + DOWN
sendKeys(Keys.chord(Keys.COMMAND, 'e'))
keyboard().pressKey(Keys.SHIFT)
sendKeys(Keys.DOWN, Keys.DOWN)
keyboard().releaseKey(Keys.SHIFT)

}

Switch between windows and tabs

These custom scripts can be applied to both desktop and web automation scenarios when switching between the windows and tabs.

Switch to last window

@CustomScriptAction(
)

def customScript() {
driver().switchToLastWindow()
}

Switch to next window

@CustomScriptAction(
)

def customScript() {
switchToNextWindow()
}

Switch to previous window

@CustomScriptAction(
)

def customScript() {
switchToPrevWindow()
}

Get table data based on index

Variables (name and type):

  • data_table: Table
  • row_pointer: Number
  • col_pointer: Number
  • cell_value: String
@CustomScriptAction(
input = ['data_table','row_pointer','col_pointer'],
output = 'cell_value'
)
def customScript() {
def cell_value = data_table.get(row_pointer,col_pointer)
}

Apply math functions and equations

Variables (name, type, and default value):

  • a: Number; 4
  • result: Number; 0
@CustomScriptAction(
input = ['a'],
output = 'result'
)

def customScript() {
def b = RNumber.of(Math.min(12.123, 12.456))
def c = RNumber.of(Math.pow(2, 3))
result = a + b + c + Math.abs(-5.6) + Math.sqrt(4)
}

Color image detection

This custom script works as a workaround returning the color under the mouse as (r,g,b,a) (int value between 0 and 255). You can easily change it to return the color at a desired location of the screen. At the final step, compare the color with the targeted one and click on the object (a regular mouse click) if the condition is fulfilled.

import java.awt.Robot
import java.awt.image.BufferedImage
import java.awt.Rectangle
import java.awt.PointerInfo
import java.awt.MouseInfo
import java.awt.Point
import java.awt.Color
import java.io.File
import javax.imageio.ImageIO
@CustomScriptAction(
output = 'color_string'
)

def customScript() {
//Get mouse position
Point mousePos = MouseInfo.getPointerInfo().getLocation();

//Take a screenshot to be able to access pixel value
Robot r = new Robot();
Rectangle rect = new Rectangle((int)mousePos.x,(int)mousePos.y,1,1)
BufferedImage im = r.createScreenCapture(rect);

//Get the color of the screenshot. In that case we want the color at mousePos hence the coordinates (0,0) of the image
//Change this to your desired location if you don't want the color under the mouse
Color rgb_color = new Color(im.getRGB(0,0));

//Convert the rgb int color to red,green,blue,alpha
int red = rgb_color.getRed();
int green = rgb_color.getGreen();
int blue = rgb_color.getBlue();
int alpha = rgb_color.getAlpha();

//Store the result as a string to return multiple variable
String color = "("+red+","+green+","+blue+","+alpha+")";

//You can use this to save the screenshot taken for debugging purpose
//File outputfile = new File("PATH_TO_SAVE_FOR_DEBUG/test_wf_im.jpg");
//ImageIO.write(im, "jpg", outputfile);

//return the color as a string
color_string = RString.of(color)
}

Find last date of previous month

Variables (name and type):

  • last_date: DateTime
import java.time.*

@CustomScriptAction(
output = 'last_date'
)

def customScript() {

ZonedDateTime zonedDateTime = RDateTime.now().asZonedDateTime();
boolean isLeapYear = Year.isLeap(zonedDateTime.getYear());
RDateTime.of(zonedDateTime.withDayOfMonth(ZonedDateTime.now().minusMonths(1).getMonth().length(isLeapYear)));
}

Web automation

Standard browser navigation

Variables (name, type, and default value):

  • web_url_one: String; https://wikipedia.org
  • web_url_two: String; https://automationacademy.com/
  • page_headings: String
@CustomScriptAction(
input = ['web_url_one', 'web_url_two'],
output = 'page_headings'
)

def customScript() {
openIE(web_url_one.toString())
driver().navigate().to(web_url_two.toString())
back()
forward()
refresh()
def headings = $$(byXpath('//h2')).getTexts().join(',')
page_headings = RString.of(headings)
}

Send GET request to any URL

Variables (name, type, and default value):

  • web_url: String; https://automationacademy.com
  • content: String
@CustomScriptAction(
input = ['web_url'],
output = 'content'
)

def customScript() {
def html = web_url.toURL().text
content = RString.of(html)
}

Send GET request and parse response

Variables (name, type, and default value):

  • web_url: String; https://automationacademy.com
  • response_of_url: String
 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@CustomScriptAction(
input = ['web_url'],
output = 'response_of_url'
)

def customScript() {
URL obj = new URL(String.valueOf(web_url));
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responsecode = con.getResponseCode();
if (responsecode == HttpURLConnection.HTTP_OK) {
BufferedReader in1 = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in1.readLine()) != null) {
response.append(inputLine);
}
in1.close();

response_of_url = RString.of(response.toString());

} else {
response_of_url = RString.of("GET request not worked");
}
}

Hover over element on web page

@CustomScriptAction(

)

def customScript() {
$(byXpath('your-xpath-for-menu-item')).hover()
}

Use element selectors other than XPath to click

Variables (name, type, and default value):

  • link_text: String; Link Test
  • option_value: String; AFR
  • select_id: String; #continents
@CustomScriptAction(
input = ['link_text', 'option_value', 'select_id'])

def customScript() {
openIE('https://rpa-tutorial.s3.amazonaws.com/trainings/iframe/form.html')
$(byLinkText(link_text.toString())).click()
sleep(3000)
back()

// Select specific option by its value in dropdown selected by its id
$(select_id.toString()).selectOptionByValue(option_value.toString())
sleep(3000)
}

Check web page on HTTP status code

Variables (name and type):

  • url: String
  • code: String
@CustomScriptAction(
input = ['url'],
output = 'code'
)

def customScript() {
def status_code = url.toURL().openConnection().responseCode
code = RNumber.of(status_code)
}

Assertions

Variables (name, type, and default value):

  • element_id: String; #continent
  • element_class: String; .container__small
@CustomScriptAction(
input = ['element_id', 'element_class']
)

def customScript() {
$(element_id.toString()).should(APPEAR)

// Wait until element with a specific class appears on the page
$(element_class.toString()).waitUntil(EXIST)
}

Execute custom JavaScript

Variables (name, type, and default value):

  • question: String; Do you like Groovy?
  • answer: String; Yes or No
  • user_choice: String
@CustomScriptAction(
input = ['question', 'answer'],
output = 'user_choice'
)

def customScript() {
openIE('https://wikipedia.org')
def choice = executeJavaScript("return prompt(arguments[0], arguments[1])", question as String, answer as String)
user_choice = RString.of(choice)
}

Desktop automation

Get object value

Variables (name and type):

  • variable_name: String
@CustomScriptAction(
output = 'variable_name'
)
def customScript() {
variable_name = RString.of($("object_selector").getText())
}

Get Excel cell coordinates based on cell text

Variables (name and type):

  • text: String
  • name: String
@CustomScriptAction(
input = ['text'],
output = 'name'
)

def customScript() {

name = RString.of($("[CLASS:DataItem; TEXT:${text}]").getAttribute('Name'))

}

Find last modified file

Variables (name and type):

  • folder: String
  • file_name: String
@CustomScriptAction(
input = ['folder'],
output = 'file_name'
)

def customScript() {

def File[] files = new File(folder.toString()).listFiles()
Date dt = new Date(0);

for (File file : files) {
if (file.isFile())
{
Date date = new Date(file.lastModified());

if (date.after(dt))
{
dt = date;
file_name = RString.of(file.getName().toString());
}
}
}
}

Rename files

Variables (name, type, and default value):

  • file1: String; path to the file to be renamed
  • file2: String; path to the renamed file
import java.io.File;

@CustomScriptAction(
input = ['file1', 'file2']
)

def customScript() {

def original_file = new File (file1.toString())
def new_file = new File (file2.toString())
original_file.renameTo(new_file);
}

Get user desktop path

Variables (name, type, and default value):

  • result_str: String; path to the desktop folder
@CustomScriptAction(
output = 'result_str'
)
def customScript() {
def String desktop_path = System.properties.'user.home' + "\\Desktop"
result_str = RString.of(desktop_path)
}

Get local computer name

Variables (name, type, and default value):

  • computer_name: String; name of user local PC
import java.net.InetAddress

@CustomScriptAction(
output = 'computer_name'
)
def FindComputerName() {
def localhost = InetAddress.getLocalHost()
computer_name = RString.of(localhost.getHostName().toString())
}

Get Excel sheet name

Variables (name, type, and default value):

  • sheet_index: Number; the index of the sheet which you want to get
  • sheet_name: String
@CustomScriptAction(
input = ['sheet_index'],
output = 'sheet_name'
)

def customScript() {

sheet_name = RString.of($("[CLASS:TabItem;INSTANCE:${sheet_index}]").getAttribute('Text'))
sheet_name = sheet_name.replaceIgnoreCase("Sheet tab", "")
}