Professional Documents
Culture Documents
Follow: @fadevrel
Read: blogs.oracle.com/fadevrel
Watch: youtube.com/FADeveloperRelations
Discuss: bit.ly/fadevrelforum
Contents
Introduction .............................................................................................................................................. 5
ADF: Dates................................................................................................................................................. 6
2
Web Services: Creating a findCriteria payload ....................................................................................... 11
Web Services: using the findAttribute element and processing the response ...................................... 12
Web Services: More on the findAttribute element and parsing responses ........................................... 13
3
Security: More VO Query for Person Resources Roles ........................................................................... 21
4
Introduction
This document provides examples of using Groovy code to achieve a range of common goals during
developing customisations in Oracle Sales Cloud using Application Composer.
The sample code here is not certified or supported by Oracle; it is intended for educational or testing
purposes only.
For further assistance in using Groovy and Application Composer please consult the following
recommended resources:
5
ADF: Dates
In addition to the items on the Release 9 Supported Functions list (in the Groovy Scripting Reference
Guide):
def newDate = adf.currentDate or adf.currentDateTime
6
def val = adf.userSession.userData.SomeKey
The internal ADF session object and its variables can be accessed, although details on intended use and
a list of attributes is not available at this time. Here is a usage example:
String var = session.getVariable("EmailSent");
if(var != 'Y') //Nothing is set on the session
{
someAPIToSendEmail();
session.putVariable("EmailSent","Y");
}
else if(var == "Y")
{
//Do nothing but reset the session variable value
session.putVariable("EmailSent",null); }
}
Release 9 introduces a whitelist of supported functions (here) to prevent destabilizing the environment. The range
of usable functions is reasonably broad, including standard API’s under java.lang, java.util and java.sql along with
many Groovy and Oracle packages such as many under oracle.jbo and oracle.adf.
If you have a requirement for using other common utility API’s under the java or groovy packages then please log
this with Oracle Support along with your use-case so we can consider potential additions.
8
UI Handling Data: Change Case
Converting strings to all uppercase. The lowercase() function also exists
def str1 = UniqueNameAlias
setAttribute("UniqueNameAlias",uppercase(str1))
2) If the string is not a number, below will throw an exception you can catch.
def isItNumber = TextField_c.isNumber()
9
def url = new URL("http://www.dummy.com/myServ/api/v1/1234")
org.apache.http.impl.client.DefaultHttpClient httpClient = new
org.apache.http.impl.client.DefaultHttpClient()
org.apache.http.client.methods.HttpGet getRequest= new
org.apache.http.client.methods.HttpGet(url);
getRequest.addHeader("Accept", "application/xml");
getRequest.addHeader("Authorization", "Basic " + authString);
org.apache.http.HttpResponse response = httpClient.execute(getRequest);
def status = response.getStatusLine().getStatusCode();
def returnMessage = ""
def customerName = ""
if (status>= 300) {
throw new org.apache.http.client.ClientProtocolException("Unexpected response status: " +
status)}
org.apache.http.HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
returnMessage= org.apache.http.util.EntityUtils.toString(responseEntity);
}
def customers = new XmlParser().parseText(returnMessage)
customerName = "Customer Name: " + customers.details.name.text()
return customerName
def findCriteria =
[
filter:
[
group:
[
[
item:
[
[
attribute :'Deptno',
operator :'=',
value :[[item:30]]
],
[
attribute :'Comm',
operator :'>',
value :[[item:300]]
],
[
upperCaseCompare :true,
attribute :'Job',
operator :'STARTSWITH',
value :[[item:'sales']]
]
]
]
]
]
]
def findControl = [ ]
def emps = adf.webServices.EmployeesService.findEmployees(findCriteria, findControl)
for (emp in emps) {
println(emp)
}
11
InteractionTypeCode: 'PHONE CALL',
DirectionCode:'OUTBOUND',
MediaItemId:1,
// InteractionAssociation:[ InteractionAssociationId:23456779,
InteractionId:23456779,
AssociatedObjectUid:300000014128636,
AssociatedObjectCode:'LEAD',
ActionCode:'CREATED']]
newint = adf.webServices.Interaction.createInteraction(newint)
}
Web Services: using the findAttribute element and processing the response
println('***** Find appointments (Opportunity - Object Functions) START ***** ' + now());
def today1 = today();
def targetDate1 = today1 + 3;
println('Today : ' + today1);
println('Target Date : ' + targetDate1);
def findCriteria =
[
fetchStart: 0,
fetchSize: -1,
excludeAttribute: false,
filter:
[
conjunction: 'And',
group:
[[
conjunction: 'And',
upperCaseCompare: false,
item:
[[
conjunction: 'And',
upperCaseCompare: false,
attribute: 'PlannedStartDt',
operator: 'AFTER',
value:
[[
item: targetDate1,
]],
]],
]],
],
findAttribute:
12
[
[item: 'ActivityId'],
[item: 'ActivityName'],
[item: 'ActivityDescription'],
[item: 'PlannedStartDt'],
[item: 'PlannedEndDt']
]
]
def findControl =
[
retrieveAllTranslations :false,
]
try
{
def appointments = adf.webServices.ActivityAppointmentService.findAppointment(findCriteria,
findControl);
for (appointment in appointments)
{
println('ActivityId : ' + appointment.get('ActivityId'));
println('ActivityName : ' + appointment.get('ActivityName'));
println('ActivityDescription : ' + appointment.get('ActivityDescription'));
println('PlannedStartDt : ' + appointment.get('PlannedStartDt'));
println('PlannedEndDt : ' + appointment.get('PlannedEndDt'));
}
}
catch(ex)
{
//println('ERROR : ' + ex.getClass().getName() + ' Message:' + ex.getMessage());
println('ERROR : ' + ex.getMessage());
}
println('***** Find appointments (Opportunity - Object Functions) END ***** ' + now());
13
],
findAttribute:
[
[item: 'LeadId'],
[item: 'Description'],
]
]
def findControl =
[
retrieveAllTranslations :false,
]
14
def findControl = []
def custs = adf.webServices.CustomerDataService.findSalesAccount(findCriteria, findControl)
println(custs)
def output = custs.toString()
def trn = output.indexOf(", PostalCode=")
def finx = trn + 10
def repo = output.substring(finx)
println(repo)
Reference your child objects using a collection name, specified upon its creation. This example
uses is CollateralCollection collection name for the Collateral child custom object.
double result = 0;
def iterator = CollateralCollection__c
if (iterator != null) {
while (iterator.hasNext()) {
// define a variable to hold the child (Collateral) in the iterator
def child = rs.next();
result += ((Number)child.Amount__c).doubleValue()
}
15
}
return new BigDecimal(result);
Here is a usage example of the same, calling O_INT_ApplyFilter as the global function name.
try{
def searchParams = [:]
searchParams.put('PartyId', OrganizationProfile_c.PartyId)
def salesAccountVO = newView('SalesAccountVO')
adf.util.O_INT_ApplyFilter(salesAccountVO, searchParams)
salesAccountVO.executeQuery()
if (salesAccountVO.hasNext()) {
return salesAccountVO.next()
}
16
}catch (e){
def message = adf.util.O_INT_GetLogMsg('0086', 'Cannot find the Sales Account by searching
Account PartyId')
throw new oracle.jbo.ValidationException(message)
}
17
Inserting VO Rows: Interactions
Following is an example of Groovy Script that you can write on “Before Update in Database” trigger, to
create an Interaction when the Opportunity status is set to Won. From Release 9 the API changed to the
Activities service.
if(isAttributeChanged('StatusCode') && nvl(StatusCode,'') == 'WON') {
def interVO = newView('InteractionVO')
def newinter = interVO.createRow()
newinter.setAttribute('InteractionDescription', 'Interaction description goes here..')
newinter.setAttribute('InteractionStartDate', today())
interVO.insertRow(newinter)
def interassocVO = newinter.InteractionAssociation
def newinterassoc = interassocVO.createRow()
newinterassoc.setAttribute("AssociatedObjectCode", "OPPORTUNITY")
newinterassoc.setAttribute("AssociatedObjectUid", OptyId)
interassocVO.insertRow(newinterassoc)
}
Another example using an interaction.
def opptyUpdatedName = Name
def opptyOwnerId = OwnerResourcePartyId
def voInteraction = newView('InteractionVO')
def voIntAssociation = newView('InteractionAssociationVO')
//createInt.setAttribute('Subject_c', interactionName)
createInt.setAttribute('InteractionStartDate', currentDateTime)
createInt.setAttribute('InteractionEndDate', currentDateTime)
createInt.setAttribute('OwnerId',opptyOwnerId)
createInt.setAttribute('CustomerId',TargetPartyId)
createIntAssc.setAttribute('AssociatedObjectUid',OptyId )
createIntAssc.setAttribute('AssociatedObjectCode','OPPORTUNITY')
voInteraction.setAttribute('voInteraction.voIntAssociation',createIntAssc)
voInteraction.insertRow(createInt)
getDetails()
getErrorCode()
getErrorParameters()
getLocalizedMessage()
getMessage()
19
Error Handling: ValidationException
Example of using the ValidationException manually.
if (ApprovalStatus__c != 'DRAFT')
{
setAttribute("ApprovalStatus__c","DRAFT")
}
else
{
throw new
oracle.jbo.ValidationException(adf.object.hints.ApprovalStatus__c.label +
"Approval cannot be submitted as this record already in an approval pending
status")
}
20
Security: More VO Query for Person Resources Roles
Another example of looking up roles.
def vo = newView('Resource');
def vc = vo.createViewCriteria()
def vcr = vc.createRow()
def vci1 = vcr.ensureCriteriaItem('PartyId')
vci1.setOperator('=')
vci1.setValue(adf.util.getUserPartyId())
vc.insertRow(vcr)
vo.appendViewCriteria(vc)
vo.executeQuery()
if(vo.hasNext()) {
def r = vo.next()
def x = r?.Roles.toString()
if (x == 'Operation Executive' || x == 'Operation Supervisor' || x == 'Country Operation
Manager' || x == 'Operation Supervisor' || x == 'Sales Administrator') {
return true
}
else {
return false
}
}
else {
return false
}
21