You are on page 1of 106

Guidewire Gosu

Gosu is Guidewire's programming language - Has elements of both procedural and object-oriented programming languages - Similar to JavaScript and Java

Gosu specifies runtime business logic that: - Executes fundamental application behavior - Manages complex business processes - Specifies dynamic client-side behavior

Where is Gosu used? (1)


Business rules - Execute fundamental application behavior, such as activity assignment Entity enhancements - Extend entity functionality with new methods, such as a new UpdateEmployees() method for ABCompany
Rules

Enhancements

Classes

Gosu classes - Create general purpose classes, such as logging utilities, plugins, and entities used to pass information to external applications

PCFs

Workflows

Where is Gosu used? (2)


PCFs - Specify user interface layout and dynamic behavior, such as "inspection date" field being visible only when "inspection needed" set to true Workflows - Executes processes whose execution is time-based, or triggered by events in external applications, or both - Currently, used only by PolicyCenter and BillingCenter base applications
Rules

Enhancements

Classes

PCFs

Workflows

The Gosu Tester


The Gosu Tester is a Studio component that lets you test

Gosu code without needing to trigger anything in the Guidewire application


- Typically requires connection to the server

Connecting Studio to the server

1. Click the

"Disconnected" button
2. Enter login

information for super user


3. Click Log In

Starting the Gosu Tester

Working with the Gosu Tester


Click "Run" to execute code - Runtime Output tab results retained until you click "Clear" print statement prints strings and variable values
- Syntax:

print ( Strings_and/or_variables )

Clears Runtime Output tab

Gosu case sensitivity

Guidewire recommends that you write Gosu code as if

Gosu were case-sensitive


Case-insensitive code will compile, but: - It will compile and run more slowly - Studio syntax checking will warn you of improper case usage

Future versions may require code to be case-sensitive

Lesson outline
Guidewire Gosu overview Gosu statements Gosu objects Gosu subtypes Studio features for working with Gosu

Variables
Syntax to declare variables:

var variableName : datatype var variableName = initialValue


Syntax to set variable values:

variableName = newValue

Comments
Single-line comment // comment - CTRL + SHIFT + / toggles selected lines to have or not have single-line comments Multiple-line comment /* comment */

Statements
Statements in Gosu do not require a terminator to mark

end of statement
- Compiler determines end of statement based on syntax

statement

Conditions and comparison operators

Common comparison operators: - Equality: ==, != - Relational: >, <, >=, <= - Compound: AND (or &&), OR (or ||)

Concatenation operator
Concatenates two or more values into a single string Syntax: value + value

if/else statements
Syntax: if (condition)

statement_or_{block} else

statement_or_{block}

Ternary operator
Similar to if-else, but can

only return expressions


- It cannot execute

statements
Typically used in PCF

files where if-else statements are cumbersome


Syntax:

condition ? returnValueIfTrue : returnValueIfFalse

Gosu method libraries


Available in all base applications Syntax to reference method: - gw.api.util.DateUtil.FunctionName(arguments) - gw.api.util.StringUtil.FunctionName(arguments) - gw.api.util.Math.FunctionName(arguments)

Commonly used library methods

Lesson outline
Guidewire Gosu overview Gosu statements Gosu objects Gosu subtypes Studio features for working with Gosu

Objects
Syntax to create new variable:

var objectName = new datatype()


Syntax to set variable to given object:

objectName = someOtherObject objectName = entityName(objectID)

Working with simple value fields


Syntax to reference object fields: objectName.fieldName

Working with foreign key fields


Foreign key fields can be used to reference objects related

to given object
Syntax: objectName.fkeyFieldName.fieldName

Working with object methods


Objects have methods that can be referenced in Gosu Syntax: objectName.methodName(arguments)

- Although code shown above is valid, it cannot be executed in

Gosu Tester because object is in read-only bundle

Determining if field value has changed


Syntax: objectName.isFieldChanged("field")
- Returns true if field named in input string has changed

since it was read from database

Retrieving original field value


Syntax: objectName.getOriginalValue("field")
- Returns value read from database

Lesson outline
Guidewire Gosu overview Gosu statements Gosu objects Gosu subtypes Studio features for working with Gosu

Subtyped entities
Guidewire entities
ABContact

may have subtypes


- Each subtype

AssignedUser EmailAddress

inherits the properties and methods of all their supertypes - Subtypes typically have their own properties and/or methods

ABPerson

FirstName LastName

ABPerson Vendor AttorneyLicense ABAttorney AttorneySpecialty

ABDoctor

DoctorSpecialty MedicalLicense

Dot notation and subtyped objects


var JLee : ABContact run-time memory

ABContact
JLee
Name: James Lee EmailAddress: null Subtype: ABDoctor FirstName: James Gender: male LastName: Lee MedicalLicense: AB3244

ABContact fields

(JLee as ABDoctor)

ABPerson fields ABDoctor fields

Server infers structure

of object based on datatype as specified in PCF file

(next object)

Directly referencing subtype fields


When working with an object of given subtype, you can

directly reference only fields and methods at or above that subtype


- You cannot directly reference fields or methods below that

subtype

Indirectly referencing subtype fields


When working with an object of given subtype, you can

indirectly reference fields and methods below that subtype by indicating child subtype where field is declared
Syntax: ( object as childSubtype ).fieldOrMethod

Testing an object's type: subtype field


Subtype field identifies object's subtype - Syntax: object.Subtype

Testing an object's type: typeis


typeis returns true if object is of given subtype, either

directly or indirectly
- Syntax: ( object typeis Subtype )

Lesson outline
Guidewire Gosu overview Gosu statements Gosu objects Gosu subtypes Studio features for working with Gosu

Syntax checker
Most Studio components that work with Gosu include a

syntax checker
- Green square indicates code is well-formed

- Red square indicates code has syntax error - One or more horizontal bars indicate lines with syntax errors - Mouse over horizontal bar to display popup with more details

Code completion features


Dot completion - Enter dot (.) after object name - Studio opens popup which lists its fields and methods - List is filtered as you type SmartHelp - Light-bulb icon indicates SmartHelp available for current line - Click icon for a list of choices CTRL + Space and CTRL + / open a selection popup to

help you complete a partial expression or value

Gosu API Reference

Gosu API Reference

documents each entity, its fields, and its methods


You can display help for given method by clicking in name and pressing F1

Array length
Syntax:

array.length

Arrays and loops


Gosu for loops used for iteration through objects in arrays Syntax:

for (currentObject in objectSet) { // statements that process currentObject }

Adding index variable to for loops


Syntax: for (currentObject in objectSet index indexVar)

Testing for existence of element


Syntax: hasMatch(\var -> var.property == condition) Returns a Boolean value

Finding first element of given criteria


firstWhere is array method that uses block as input

parameter
Syntax:

array.firstWhere( \ Var -> conditionUsingVar)

"\" rendered as "" "->" rendered as ""

Finding all elements of given criteria


where is array method that also uses block as input

parameter
Syntax:

array.where( \ Var -> conditionUsingVar)

Adding object to array


Syntax: parentObject.addToArrayName(objectToAdd)

parentObject.removeFromArrayName(objectToRemove)

Gosu queries
A Gosu query is an object associated with a specific entity

that stores a database query and its results


- Gosu queries are useful when code must work with a set of

objects that does not exist as an array, such as "all contact notes created by this user"

Objects used when querying database


table condition 1 condition 2

table Coverage

query object

results object

Query object stores

criteria of query, such as:


- Which entity to query - What restrictions (where

Results object stores results and related info:


How many results? If necessary, how should

clauses) to apply

they be ordered?

Steps to execute a basic query


1. Create the query object Accomplished using the make() method 2. Create the results object Accomplished using the select() method 3. Process the results of the query as needed

Step 1: Create the query object


Syntax:

var queryObj = gw.api.database.Query.make(EntityToQuery)

Step 2: Create the results object


Syntax:

var resultsObj = queryObj.select()

Step 3: Process results of query as needed


You can use a for loop to iterate through the result set as if

it were an array

Viewing approximation of SQL query


Syntax: queryObj.toString() - Actual SQL may vary based on actual RDBMS

Lesson outline
Gosu query basics Working with queries Working with result sets

Restricting queries
Query objects have methods that add restrictions to query - Typically, they become SQL where clause

Restricting queries: compare method


Syntax:

queryObj.compare("field", operator, value)


- Field and value must be strings

- Valid operators include: - Equals - NotEquals - LessThan - LessThanOrEquals - GreaterThan - GreaterThanOrEquals

Specifying value in compare method


For NULL, integer, or boolean values, do not use quotes For strings, use quotes For datetime and typekey, use quotes and cast object

Multiple restrictions ANDed together


Query can have as many restrictions as needed - Restrictions are inherently ANDed together

Multiple restrictions ORed together


Syntax:

queryObj.or( \ placeholder -> { placeholder.criteria placeholder.criteria // add as many criteria as needed })

Additional restriction options


Gosu Reference Guide contains complete list of all options

for restricting queries, including restrictions that make use of:


- between and Ranges
- startsWith - contains

Lesson outline
Gosu query basics Working with queries Working with result sets

Getting size of results


Syntax: resultsObj.Count - Value will vary if number of rows in database that meet query's criteria changes

Sorting results
Sorting methods use blocks as input parameters - Syntax: resultsObj.orderBy( \ row -> row.FieldName) resultsObj.orderByDescending( \ row -> row.FieldName )

Querying when only one result is expected


Syntax:

queryObj.select().AtMostOneRow
- If single item exists, method returns that single row

- If no item exists, method returns null


- If multiple items exist, method throws exception

Business rules
A business rule is Gosu code that: - Accomplishes some task for given entity, and - Executes when specific event occurs to instance of that entity TrainingApp Example - ABContact pre-update rules
- Execute actions required by change to an ABContact, such as:
- Creating history entry to record change of assigned user - Setting a company's Primary Contact to null if the original Primary

Contact no longer works for the company


- Triggered when ABContact object is created or modified

Examples from Guidewire applications


PolicyCenter: account validation rules - Verifies that account is valid before committing it to database - Triggered when account is created or modified BillingCenter: activity escalation rules - Escalates activity that is open for too long - Triggered when activity is open past its escalation date ClaimCenter: claim assignment rules - Assigns given claim to a group and user - Triggered when claim is created or needs reassignment

Business rule structure


Consists of name, condition, and action - Condition code must resolve to true or false - Action code executed only if condition is true

if

{ }

then

Business rule hierarchy


Three levels (from highest to lowest) - Rule set categories - Rule sets - Rules (which may be multi-leveled if child rules are present)

Hierarchy: rule set categories


A rule set

category is a collection of rules that have common highlevel business purpose


- Studio uses rule

set categories to group similar rules together

Hierarchy: rule sets


A rule set is a

collection of rules that are attached to the same entity and share the same trigger
- For example,

ABContact Preupdate rule set is attached to ABContact and triggers when any ABContact is created or modified

Hierarchy: business rules


A business rule is

a set of one or more lines of code that typically executes one logical action
Rules can have

child rules
- If parent

condition is true, parent action is executed and then child rules are executed

Rule names
Guidewire recommends rules naming convention be

used, such as CodeNumber Purpose, where:


- Code is a 4-character code related to rule set name - Number is a 4-digit unique number - Purpose identifies purpose of rule

Lesson outline
Business rules overview Rules-specific Gosu Working with rules Debugging rules

Root entity
Every rule set has "root entity" - Identifies entity with which rule set is associated Every rule has access to object that triggered rule set - Object has same name as root entity

"aBContact" is ABContact object which triggered rule set

Normal flow of execution

When triggering event occurs: - Rules executed in order listed in Studio - If rule has child rules and parent rule condition is true, parent action executed first, then child rules executed - All rules in rule set executed unless explicit "exit" encountered

Two logical types of rule sets


"Execute all" - All rules in rule set executed - Example: validation rules
- All validation conditions are checked,

regardless of how many are true

"Exit after first action" rule sets - When first true condition is found, action taken and rule set is exited - Example: assignment rules
- Once one assignment is made, rule set

should be exited to prevent later rules from reassigning object

Exiting a rule set


Typically done only in rules in "exit after first action" rule

sets
- Syntax: actions.exit()

- Example:

Lesson outline
Business rules overview Rules-specific Gosu Working with rules Debugging rules

Rule set information

Selecting the rule set displays rule set description and lists

root entity

Rules in Studio
Resources Rule Set tab Rule tab

Select a rule set in Resources to display Rule Set tab

Select a rule in Rule Set tab to display Rule tab

Creating new rules

Right-click rule parent

Rule defaults to true condition with no action

Rule conditions and actions


Use rule condition to: - Indicate if rule action should be executed - Control whether or not child rules are executed

If rule should always be executed, set condition to true

Working with rules


Moving rules De/activating rules

Deleting and renaming rules

Deploying rule changes


If Dynamic Code Evolution Virtual Machine (DCEVM) is

installed, must press Alt + Shift + L


If DCEVM is not installed, must restart server DCEVM should only be used in development

environments, never in production environments

Lesson outline
Business rules overview Rules-specific Gosu Working with rules Debugging rules

Studio debugger
The Studio debugger is a set of tools that

shows how code managed by Studio is executed


- Helps you debug code that does not execute as expected
- Useful for determining how rules are being executed

Available for most code managed by Studio, including:

Rules Enhancements Classes

Setting breakpoints

A breakpoint indicates a place in code where execution

should be suspended
- Once suspended, you can step through code and observe: - Which code gets executed - Variable and object values

To add breakpoint, click in area immediately left of line

number

Starting the debugger


Breakpoints suspend execution only when debugger is

running
To start debugger, select

Server from Debugger menu


While debugger is running,

Debugger tab appears at bottom of Studio

Suspending execution
When application executes code

with breakpoint
- Execution is suspended

- Studio is automatically displayed

with current line in green - Frame tab shows current values of root and related objects

Stepping through code


"Step" tool lets you

execute one line at a time


- Next line to be

executed displays in green


After each line, you

can:
- View values in

Frame tab - Observe state of application

Watches
A watch is an expression

whose value you wish to observe


To add a watch: - On Watches tab, right-click and select Add Watch - Enter expression - Click OK - Expression is then listed in Watches tab, along with its value

Debugger panel buttons

Start or continue debugging Stop debugging Step to next statement after current execution point

Step into method call at current execution point Edit breakpoints


Mute breakpoints Open Gosu Tester Stop and close Debugger

Stopping debugger
To stop debugger, click either Stop button

Methods
A method is a set of statements that executes a logical unit

of work
function popupButtonText If flag entry's IsEditable boolean is true return "View/Edit" Otherwise, return "View"

Method syntax
Can take input parameters, return a result, or both Syntax:

function functionName (inputvar : datatype) : returnType { // code to execute method return returnValue

input parameter

return value

Methods with return values


All code paths must contain a return statement, or Gosu

gives error

Return value must be of the declared return type

What is return value if condition is false?

Methods with no return value


If method does not need to return a value: - Set return value to void - Do not include any return statements

Where can you declare Gosu methods?


PCFs - Method can be used only within that PCF - Discussed in this lesson

Enhancements - Method associated to given type (such as an entity) - Can only be used by instances of that type - Discussed in "Enhancements" lesson
Classes - Method associated with given class - If declared as static methods, can be used anywhere - Discussed in "Gosu Classes" lesson

Lesson outline
Overview of Gosu methods Creating PCF methods Common use cases for PCF methods

PCF methods
A PCF method is a method declared on a given PCF file's

Code tab
- Method can be called by properties of PCF file or its widgets

Lesson outline
Gosu methods Creating PCF methods Common use cases for PCF methods

Calling PCF methods


Methods can be referenced from location and widget

properties - Syntax: functionName (inputParameters)


Although any method can be referenced, the remainder of

this lesson focuses on PCF methods


Common use cases include method to execute when: - Given widget is clicked - Given widget is rendered - Given widget's value changes - Event occurs for a given location, such as:
- User navigates to that location - Data modifications in that location are committed

Use case 1: When widget is clicked

Action

attribute specifies code to execute when widget is clicked

Widget availability
An atomic widget's available property determines when the

widget can be clicked


available = true

available = false

Configuring widget availability

Widget is clickable only if available returns true - Default value is true - Checked only when action property is not null CurrentLocation.InEditMode can be used to control

availability based on edit mode of location


- Returns true if current location is in edit mode
- Returns false if current location is in read-only mode

Use case 2: Input or cell button label

Use case 3: When widget's value changes


Widgets can

execute code when their value changes in the application (prior to the value being saved)
- This is discussed

in detail in the "Server-Side Widget Behavior" lesson

onChange: set UnflagUser to current user set UnflagDate to current date

Use case 4
PCF methods can be called in

reaction to location events, such as navigating to location


After entering location, create "viewed this contact" history entry

Changing data in PCF methods


When PCF method changes data, those changes are not

automatically written to database


- If method is called while location is in edit mode, changes are

committed when user clicks "Update"


deletion of addresses committed when user clicks Update
- If method must change data while location is in read-only

mode, code must commit data manually

You might also like