import com.redprairie.moca.MocaResults; import com.redprairie.moca.MocaType; import com.redprairie.moca.MocaContext; import java.util.*; import groovy.text.*; import groovy.xml.XmlUtil; import freemarker.template.*; import wslite.rest.*; import com.redprairie.moca.SimpleResults; import wslite.http.auth.HTTPBasicAuthorization; import wslite.http.HTTPResponse; import javax.xml.parsers.SAXParserFactory; import com.redprairie.moca.util.MocaUtils; public class FreemarkerUtil { private static FreemarkerUtil instance; private static Configuration cfg; private FreemarkerUtil() { } public static FreemarkerUtil getInstance() { if (instance == null) { MocaContext ctx = MocaUtils.currentContext(); String template_root = (String) ctx.getVariable("TEMPLATE_DIRECTORY"); cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setDirectoryForTemplateLoading(new File((String)template_root)); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); } return instance; } Configuration getCfg() { return cfg; } } class MocaResultBuilder extends BuilderSupport { def Stack<SimpleResults> results =new Stack() public MocaResultBuilder() { } public SimpleResults getResults() { return results.peek(); } @Override public void setParent(Object parent, Object child) { } @Override public void nodeCompleted(Object parent, Object node) { if (node=='results' && !results.isEmpty() && results.size()>1) { results.pop(); } } @Override public Object createNode(Object name) { return createNode(name, null, null); } @Override public Object createNode(Object name, Object value) { return createNode(name, null, value); } @Override public Object createNode(Object name, Map attrs) { return createNode(name, attrs, null); } @Override public Object createNode(Object name, Map attrs, Object value) { SimpleResults currentset if (!results.isEmpty()) { currentset = results.peek(); } if (name=="results") { SimpleResults newset= new SimpleResults(); if (currentset!=null) { currentset.setResultsValue(value, newset); } results.push(newset); } else if (name=="column") { MocaType typ = MocaType.STRING if (attrs["type"] == "results") { typ = MocaType.RESULTS } currentset.addColumn(attrs["name"], typ) } else if (name=="row") { currentset.addRow(); } else if (currentset) { currentset.setStringValue(name,value); } return name } } private List getBinding(MocaResults input) { def rbinding = [] int j=0; if (input!=null) { input.reset(); while (input.hasNext()) { input.next() def row = [:] for (def i=0; i< input.getColumnCount(); i++) { if (input.getColumnType(i)==MocaType.RESULTS) { row.put(input.getColumnName(i) ,getBinding(input.getResults(i))) } else { row.put(input.getColumnName(i), input.getValue(i)) } } rbinding.add(row); } } return rbinding } private String getArgument(MocaContext context, String name, String dfltValue) { def result = dfltValue if (context.getStackVariable(name)!=null) { result = context.getStackVariable(name).asString() } else { def args = context.getArgs() for (a in args) { if (a.getName().equals(name)) { result = a.getValue() break } } } context.logDebug("Argument " + name + ":" + result) return result; } private String getRequest(String fileName, MocaResults inputset) { def inputbind =getBinding(inputset); def docbind = ["doc" : inputbind]; freemarker.template.Template ftl = FreemarkerUtil.getInstance().getCfg().getTemplate(fileName); StringWriter sw = new StringWriter(); ftl.process(docbind, sw); return sw.toString(); } private Object parseXmlContent(String content, boolean fail) { Object msg; try { msg = new XmlParser().parseText(content); } catch (Exception e) { msg = content; if (fail) { throw e; } } return msg; } private String serialize(Object data) { def result=data?.toString(); if (data instanceof groovy.util.Node) { result = XmlUtil.serialize(data); } return result; } SimpleResults outputSet = new SimpleResults(); outputSet.addColumn("ack_status_cd", MocaType.STRING); outputSet.addColumn("ack_status_text", MocaType.STRING); outputSet.addColumn("OUTPUTSET", MocaType.RESULTS); outputSet.addRow(); try { // get inputset resultset MocaResults inputset = moca.getVariable("INPUTSET"); if (inputset==null && moca.getStackVariable("INPUTSET")!=null) { inputset= moca.getStackVariable("INPUTSET").asType(MocaType.RESULTS); } assert inputset!=null : "INPUTSET needs to be provided" // get WS arguments def url = getArgument(moca,"REST_URL", ""); assert url!="" : "REST_URL argument needs to be provided" def restTemplate = getArgument(moca,"REST_TEMPLATE", ""); assert restTemplate!="" : "REST_TEMPLATE argument needs to be provided" def formparam = getArgument(moca, "REST_FORM_PARAM" ,"") def extractMap = getArgument(moca,"EXTRACT_MAP", ""); assert extractMap!="" : "EXTRACT_MAP argument needs to be provided" // check proxy settings def proxyHost = getArgument(moca,"PROXY_HOST", "") def proxyPort = getArgument(moca,"PROXY_PORT", "") def Proxy proxy = Proxy.NO_PROXY if (proxyHost.length() > 0 && proxyPort.length()>0) { proxy= new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort))) moca.logDebug("Proxy set to ${proxyHost} and ${proxyPort}") } def username = getArgument(moca, "USERNAME","") def password = getArgument(moca, "PASSWORD", "") // create REST client def client = new RESTClient(url) client.httpClient.sslTrustAllCerts = true if (username!="") { client.authorization = new HTTPBasicAuthorization(username, password) } // build the request def request; if (restTemplate!="PASSTHROUGH") { moca.logDebug("Create request from template and binding") request = getRequest(restTemplate, inputset) } else { inputset.reset(); if (inputset.hasNext()) { inputset.next(); request = inputset.getString("REQUEST") } else { throw new Exception("No request found for passthrough"); } } if (formparam!="") { URLParametersCodec encoder = new URLParametersCodec(); request = encoder.encode(["${formparam}":request]); } moca.logDebug("Request: ${request}") // send the request moca.logDebug("Sending request") wslite.rest.Response resp = client.post(proxy:proxy, accept: (ContentType.XML.getContentTypeList() + ContentType.TEXT.getContentTypeList()+ ContentType.ANY.getContentTypeList()).join(","), connectTimeout:10000, readTimeout:60000, followRedirects:false, useCaches:false ) { type "${(formparam!="") ? "application/x-www-form-urlencoded" : "text/xml"}" charset "UTF-8" bytes request } response = parseXmlContent(resp.text, extractMap!="PASSTHROUGH"); def respTxt = serialize(response); moca.logInfo("Sent request successfully") moca.logDebug("Response: ${respTxt}") // process the result if (extractMap!="PASSTHROUGH") { // map the reponse to MocaResult, if mapping specified moca.logDebug("Extracting resultset from Rest response") resultBuilder = new MocaResultBuilder() Binding binding=new Binding(); binding.setVariable("resultBuilder",this.resultBuilder); binding.setVariable("response",this.response); GroovyShell shell=new GroovyShell(binding); res=shell.evaluate(new File(extractMap)); if (!(res instanceof SimpleResults)) { throw new RuntimeException("SimpleResults value expected out of map: " + extractMap); } moca.logDebug("Extracted resultset ${getBinding(res)}") outputSet = res; } else { SimpleResults responseSet = new SimpleResults(); responseSet.addColumn("RESPONSE", MocaType.STRING); responseSet.addRow(); responseSet.setStringValue("RESPONSE", respTxt); outputSet.setStringValue("ack_status_cd", "OK") outputSet.setStringValue("ack_status_text", "") outputSet.setResultsValue("OUTPUTSET",responseSet) } } catch(AssertionError ae) { outputSet.setStringValue("ack_status_cd", "NOK") outputSet.setStringValue("ack_status_text", ae.toString()) moca.logError("Assertion error:" + ae.toString()) } catch (RESTClientException sce) { outputSet.setStringValue("ack_status_cd", "NOK") outputSet.setStringValue("ack_status_text", sce.toString()) moca.logError("REST Client Error:" + sce.toString()) } catch(Exception e) { outputSet.setStringValue("ack_status_cd", "NOK") outputSet.setStringValue("ack_status_text", e.toString()) moca.logError("Internal error:" + e.toString()) } return outputSet;
Write, Run & Share Groovy code online using OneCompiler's Groovy online compiler for free. It's one of the robust, feature-rich online compilers for Groovy language, running the latest Groovy version 2.6. Getting started with the OneCompiler's Groovy editor is easy and fast. The editor shows sample boilerplate code when you choose language as Groovy and start coding.
OneCompiler's Groovy online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample Groovy program which takes name as input and prints hello message with your name.
def name = System.in.newReader().readLine()
println "Hello " + name
Groovy is an object-oriented programming language based on java. Apache Groovy is a dynamic and agile language which is similar to Python, Ruby, Smalltalk etc.
Data type | Description | Range |
---|---|---|
String | To represent text literals | NA |
char | To represent single character literal | NA |
int | To represent whole numbers | -2,147,483,648 to 2,147,483,647 |
short | To represent short numbers | -32,768 to 32,767 |
long | To represent long numbers | -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 |
double | To represent 64 bit floating point numbers | 4.94065645841246544e-324d to 1.79769313486231570e+308d |
float | To represent 32 bit floating point numbers | 1.40129846432481707e-45 to 3.40282346638528860e+38 |
byte | To represent byte value | -128 to 127 |
boolean | To represent boolean values either true or false | True or False |
You can define variables in two ways
data-type variable-name;
[or]
def variable-name;
0.upto(n) {println "$it"}
or
n.times{println "$it"}
where n is the number of loops and 0 specifies the starting index
When ever you want to perform a set of operations based on a condition or set of conditions, then If / Nested-If / If-Else is used.
if(conditional-expression) {
// code
} else {
// code
}
Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.
switch(conditional-expression) {
case value1:
// code
break; // optional
case value2:
// code
break; // optional
...
default:
//code to be executed when all the above cases are not matched;
}
List allows you to store ordered collection of data values.
def mylist = [1,2,3,4,5];
List Methods | Description |
---|---|
size() | To find size of elements |
sort() | To sort the elements |
add() | To append new value at the end |
contains() | Returns true if this List contains requested value. |
get() | Returns the element of the list at the definite position |
pop() | To remove the last item from the List |
isEmpty() | Returns true if List contains no elements |
minus() | This allows you to exclude few specified elements from the elements of the original |
plus() | This allows you to add few specified elements to the elements of the original |
remove() | To remove the element present at the specific position |
reverse() | To reverse the elements of the original List and creates new list |