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.
- Add the Script action from the Custom Actions group in Actions Library to the Actions flow.
- Copy a code sample from this page and insert it into the Script area within the Script action.
- Create the input-output variables used in the script in the Recorder Variables tab.
warning
If you have more than one custom script in the recording, you need to define a different method for each action, e.g., 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
note
The code sample has been shared by ivan.swiegers on the Community Forum. For more information, refer to this forum topic.
Variables (name – type):
failcheck1– Booleanfailcheck2– Booleanfailcheck3– Booleanfailcheck4– Booleanfailcheck5– Booleanfinalfailcheck– 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
note
The code sample has been shared by Bonnero on the Community Forum. For more information, refer to this forum topic.
This custom script is an example that does a comparison of arithmetic operations. You could also perform other operations, e.g. 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 – type):
condition1– Numbercondition2– Numbercondition3– Numberboolean_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
note
The code sample has been shared by tinwy on the Community Forum. For more information, refer to this forum topic.
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 regexpmatcher[0][1]refers to the first capture in the matchmatcher[0][2]refers to the second capture in this match
Variables (name – type):
original_str– Stringresult_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
note
The code sample has been shared by tinwy on the Community Forum. For more information, refer to this forum topic.
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 – type):
date1– DateTimedate2– DateTime
Modify day in date
@CustomScriptAction(
input = ['date1'],
output = 'date1'
)
def customScript() {
date1 = date1.minus(java.time.Duration.ofDays(1))
}
Modify month in date
@CustomScriptAction(
input = ['date1'],
output = 'date2'
)
def customScript() {
date2 = date1.plus(java.time.Period.ofMonths(1))
}
Download file from remote server
Variables (name – type – default value):
web_url– String – https://rpa-tutorial.s3.amazonaws.com/trainings/Tickers.xlsxlocal_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 – 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/tabs
These custom scripts can be applied to both desktop and web automation scenarios when switching between the windows/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
note
The code sample has been shared by Bonnero on the Community Forum. For more information, refer to this forum topic.
Variables (name – type):
data_table– Tablerow_pointer– Numbercol_pointer– Numbercell_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 – default value):
a– Number – 4result– 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
note
The code sample has been shared by alasbleis on the Community Forum. For more information, refer to this forum topic.
Currently, Intelligent Automation Cloud does not support 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 (variant 1 - recommended)
There are several ways to find dates in Java, but we recommend this option which uses the java.time library classes.
Variables (name – type):
last_date– DateTime
import java.time.*
@CustomScriptAction(
output = 'last_date'
)
def FindLastDate() {
ZonedDateTime zonedDateTime = RDateTime.now().asZonedDateTime();
boolean isLeapYear = Year.isLeap(zonedDateTime.getYear());
ZonedDateTime zdt2 = ZonedDateTime.now().minusMonths(1)
RDateTime.of(zdt2.withDayOfMonth(zdt2.getMonth().length(isLeapYear)));
}
Find last date of previous month (variant 2)
Variables (name – type):
last_date– DateTime
@CustomScriptAction(
output = 'last_date'
)
def customScript() {
def calendar = Calendar.getInstance();
def year = calendar.get(Calendar.YEAR);
def month = calendar.get(Calendar.MONTH);
def date = calendar.get(Calendar.DAY_OF_MONTH);
def timezone = calendar.getTimeZone().getID();
calendar.set(year, month-1, date);
def maxday = calendar.getActualMaximum(calendar.DAY_OF_MONTH);
def last_date = RDateTime.of(year,month,maxday,0,0,0,timezone);
}
Web Automation
Standard browser navigation
Variables (name – type - default value):
web_url_one– String – https://wikipedia.orgweb_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 – default value):
web_url– String – https://automationacademy.comcontent– 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
note
The code sample has been shared by stuti.verma on the Community Forum. For more information, refer to this forum topic.
Variables (name – type – default value):
web_url– String – https://automationacademy.comresponse_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 – default value):
link_text– String – Link Testoption_value– String – AFRselect_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 – type):
url– Stringcode– String
@CustomScriptAction(
input = ['url'],
output = 'code'
)
def customScript() {
def status_code = url.toURL().openConnection().responseCode
code = RNumber.of(status_code)
}
Assertions
Variables (name – type – default value):
element_id– String – #continentelement_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 – default value):
question– String – Do you like Groovy?answer– String – Yes/Nouser_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 – 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 – type):
text– Stringname– String
@CustomScriptAction(
input = ['text'],
output = 'name'
)
def customScript() {
name = RString.of($("[CLASS:DataItem; TEXT:${text}]").getAttribute('Name'))
}
Find last modified file
Variables (name – type):
folder– Stringfile_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
note
The code sample has been shared by shagivara on the Community Forum. For more information, refer to this forum topic.
Variables (name – type – default value):
file1– String – path to the file to be renamedfile2– 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
note
The code sample has been shared by ShawnLi on the Community Forum. For more information, refer to this forum topic.
Variables (name – type – 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 – 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 – default value):
sheet_index– Number – the index of the sheet which you want to getsheet_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", "")
}