-
Notifications
You must be signed in to change notification settings - Fork 82
script templates
Metl comes with a set of templates available for use within a script component. These templates demonstrate a broad set of capabilities of several common integration scenarios. They can be expanded and built upon to accomplish various tasks that may not be as easily accomplished using core components.
-
Create filename parameter - Create a parameter to hold a generated filename
-
Forward entity once - Forwards an Entity message only one time
-
Generate entity data message - Creates several Entity objects with Attributes
-
Set email variables - Builds various email fields as parameters such as subject line, body, to
-
Track number of records - Gets the number of records in a message
-
Upload input data as file to web server - Demonstrates how to read incoming messages and post this data to a file on a web server
-
Use jdbc to get id - Demonstrates use of custom Methods and jdbc to update attribute data
-
Use script context with entity iterator - Creates a list of attribute values and forwards this as a parameter
Creates a filename using the current date-time as part of the name and sets this value in a parameter called filename.property that can be referenced in subsequent components such as a Text File Writer.
Date date = new Date(); String dateTime = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(date); fileName = 'MyFile_' + dateTime + '.txt'; forwardMessageWithParameters(['filename.property':fileName]);
Checks if an Entity message has already been sent during the process of a previous message. Demonstrates the use of the scriptContext variable provided by Script Helper.
if (inputMessage instanceof EntityDataMessage) { def datas = inputMessage.getPayload() for (EntityData data: datas) { def id = new Integer(getAttributeValue("SOME_ENTITY", "SOME_ATTRIBUTE", data)) def alreadySent = scriptContext.get(id) if (alreadySent == null) { scriptContext.put(itemId, Boolean.TRUE) callback.sendEntityDataMessage(null, [data]); } } }
Creates new EntityData objects and forwards these as entity messages. This template demonstrates the setting of Entity Attribute values and how to forward these using the Script Helper function sendEntityDataMessage().
def list = [] for (int i = 0; i < 10; i++) { def data = new EntityData() putAttributeValue("NOTE", "ID", data, i) putAttributeValue("NOTE", "NOTE", data, "Note #${i}") list += data } sendEntityDataMessage(list)
Uses existing flow parameters to populate new email related parameters such as a dynamic subject and body. This template could be expanded with content from the example in Use script context with entity iterator to also include details from the Entity data in an email body that will be forwarded to a subsequent Email component where it could refer to the email_body $(email_body) parameter when defining the email component properties.
if (!unitOfWorkBoundaryReached) { // only execute this if there is a normal message passed in and not just a control message String flowName = context.flowParameters['_flowName']; String envr = context.flowParameters['_agentName']; String host = context.flowParameters['_host']; subject = "Email Subject line can include where run: " + host + " - agent: " + envr; email_to = context.flowParameters['email_to']; // this refers to a Flow Parameter set in the General Settings, could be a data element passed in as well body = '''\ <br/> Example Email body <h2> Some Heading </h2> <br/> Some detailed message generated by Metl Flow: $(_flowName). '''; body = FormatUtils.replaceTokens(body, context.getFlowParameters(), true); info("Email to: " + email_to); info("Email subject: " + subject); info("Email body: " + body); params = [email_subject:subject, email_body:body, email_to:email_to]; forwardMessageWithParameters(params); }
Demonstrates the basic use of script variables and how to get the number of data rows in an input message. This could be used to cause some action such as an update of a job status table.
if (inputMessage instanceof ContentMessage) { recordCount += inputMessage.getPayload().size(); } // in the onSuccess() method: // Do something with results like update a job status table
Shows how to read input data (sample assumes xml string) and then looks up resource settings to execute the post of a file containing the input data to an Http server. Demonstrates how to reference resource settings as well as the use of Imports.
if (!unitOfWorkBoundaryReached) { // assumes the input message is an xml string that is to be saved to a file and uploaded String xml = inputMessage.getPayload().get(0); // file_dir would be the directory (path) (set in flow settings) and xmlFileName (generated as a header parameter in separate script) // is the name to where the file will be created before sending String fileName = context.flowParameters['file_dir'] + '/' + inputMessage.getHeader().get("xmlFileName")+ '.xml'; info("Filename is " + fileName); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(resource.getResourceRuntimeSettings().get("url")); // gets the url value from the Http resource MultipartEntity entity = new MultipartEntity(); entity.addPart("Filedata", new ByteArrayBody(xml.getBytes("UTF-8"), fileName)); httpPost.setEntity(entity); httpClient.execute(httpPost); callback.sendControlMessage(); }
This template shows how to use jdbc within a script to pull data to update an attribute value that is passed to the next component. It illustrates the scenario where a database table needs to be updated if the lookup value exists otherwise a new id needs to be generated and a new row inserted. This fills in the Entity object with the details an RDBMS Writer needs in order to write the data.
... // get the id corresponding to my lookup value or else get an id one larger than the max if the record doesn't exist try { id = getJdbcTemplate().queryForObject("select max(ID_FIELD) from MY_TABLE where LOOKUP_FIELD = '" + lookupValue + "'", Integer.class); } catch (EmptyResultDataAccessException) { id = getJdbcTemplate().queryForObject("select max(ID_FIELD) + 1 from MY_TABLE", Integer.class); } ...
Uses the scriptContext variable provided by Script Helper to hold a list of values that are the data attributes from the rows received in the input message. The template shows how to navigate an Entity and its Attributes to get specific or all data elements from an entity data message. Then how to only send the result once a Unit of Work boundary is reached.
String allCombinedList = scriptContext.get("combinedList"); int localMsgCount = scriptContext.get("msgCount"); if (!(inputMessage instanceof ControlMessage)) { localMsgCount++; Model inputModel = flowStep.getComponent().getInputModel(); // make sure we have a valid inputModel and then get the model Entity and ids of the Attributes for that Entity if (inputModel != null) { ModelEntity myEntity = inputModel.getEntityByName("Entity_Name"); ModelAttrib myAttr1Attribute = testEntity.getModelAttributeByName("Attribute1_Name"); ModelAttrib myAttr2Attribute = testEntity.getModelAttributeByName("Attribute2_Name"); List<EntityData> list = inputMessage.getPayload(); entityDataIterator = list.iterator(); // walk through all the entity data objects getting the attributes from each row using the attribute id found above while (entityDataIterator.hasNext()) { EntityData data = entityDataIterator.next(); String attr1 = (String) data.get(myAttr1Attribute.getId()); String attr2 = (String) data.get(myAttr2Attribute.getId()); // build our combined list of attr2 data values allCombinedList += '<some_tag>' + attr1 + ':' + attr2 + '</some_tag>'; } } info("Combined List msg(" + localMsgCount + ") : " + allCombinedList); // put the updated values back in the scriptContext for reference with next message(s) scriptContext.put("combinedList", allCombinedList); scriptContext.put("msgCount", localMsgCount); } // Only forward one message when the unit of work boundary was reached with the combined set of values if (unitOfWorkBoundaryReached) { info("Processed " + localMsgCount + " messages"); info("Combined data: " + allCombinedList); params = [combined_list:allCombinedList]; forwardMessageWithParameters(params); }