RPA, BOTS, AI and API

In today’s competitive markets, industries face many challenges in order to remain successful. These include staying ahead of the competition, understanding customers need and preferences, and providing a high level of service that will make customers happy.

Here are few challenges for current industries

  1. Resolve customer issues ASAP
  2. Collect and qualify customer information
  3. Easily connect to business process
  4. Enable business new features quickly.

In current business requirements 90% of organizations see increased demand for automation from business teams, due to that 95% of IT leaders are prioritizing automation. 

Automation is a critical component of digital transformation and business success. Robotic Process Automation (RPA) bots are at the forefront of this revolution, providing businesses with an automated solution to optimize their processes while improving customer experiences. RPA bots can be used in many areas such as data entry, document processing and workflow management; they automate repetitive tasks that would otherwise take up valuable resources from human employees. This automation not only increases efficiency but also reduces costs associated with manual labor, allowing companies to focus on more pressing issues like innovation or collaboration between departments. By utilizing intelligent bots powered by artificial intelligence (AI), companies can further streamline operations and provide customers with immediate feedback on requests or inquiries in real time without manual intervention from employees. Additionally, natural language processing (NLP) capabilities allow chatbots used in websites or apps to respond quickly and accurately when communicating with customers.

Using NLP, Bots can decipher specific sentences or words customers type and associate them to an intent. NLP provides insights by analyzing past chat transcripts to identify common customer utterances or phrases (such as order status, account information, password reset, logging an issue, etc.) that the Bot can use to take action. A predictive model for bots to understand intent and take action called intent model. The intent model is made up of intents and utterances.

APIs , NLP and AI are the essential components for Bots. Once an intent model from NLP identifies action then Bots call APIs. APIs help to execute tasks from the backend system for Bots. Suppose if users are looking for order status from bots and APIs are not responding on time it will fail the whole Bots purpose. So APIs are one of the key components for Bots.

APIs streamline Bots tasks and automated any process/tasks for any team. Bots and APIs empower business and IT teams to collaborate with ease and break silos in every step of their automation journey. Enable end-to-end automation at scale Reuse and compose RPA securely.

API Security

API is a key component of digital transformation. API is the interface of your legacy and SAAS data. The goal of APIs is to facilitate the transfer and enablement  of data between your system and external users. APIs are typically available through public networks like the internet to communicate to external users and expose your data into the public domain.

Since your data is exposed into the public domain through APIs, It can lead to a data breach. APIs can be broken and expose sensitive personal as well as company data. An insecure API can be an easy target for hackers to gain access to your system and network. Rise of IOT devices and usage of APIs by these IOT devices, APIs are now more vulnerable. 

According to owasp, these are 10 main API vulnerabilities.

  1. Broken Object Level Authorization – Expose endpoints that handle object identifiers, creating a wide attack surface Level Access Control issue.
  2. Broken User Authentication – Authentication mechanisms are implemented incorrectly.
  3. Excessive Data Exposure – Developers  expose all object properties without considering their individual sensitivity
  4. Lack of Resources & Rate Limiting – APIs do not impose any restrictions on the size or number of resources that can be requested by the client/user, lead to Denial of Service (DoS) attack on APIs
  5. Broken Function Level Authorization Complex access control policies with different hierarchies lead to authorization flaws.
  6. Mass Assignment – Without proper properties filtering based on an allowlist, usually leads to Mass Assignment.
  7. Security Misconfiguration – Misconfiguration or lack of Security configuration  is commonly a result of insecure APIs
  8. SQL Injection SQL Injection occurs when untrusted data is sent to an interpreter as part of a command or query.
  9. Improper Assets Management – APIs tend to expose more endpoints than traditional web applications lead to improper expose APIs.
  10. Insufficient Logging & Monitoring – Insufficient logging and monitoring fail to find your vulnerability and broken integration.

How to mitigate API security risk?

  • API supports secure sockets layer (SSL), transport layer security (TLS), and Hypertext Transfer Protocol Secure (HTTPS) protocols, which provide security by encrypting data during the transfer process.
  • Apply Basic Auth minimum with API or  if you want to more secure your API then enable 2 way authentication through OAuth framework . 
  • Apply Authorization on each API resource to more control on API security through external Identity and access management provider (IAM).
  • Use encryption and signatures to all your API exposed personal and organizational sensitive data.
  • Apply API throttling through API manager to control number of user access per API (Rate Limiting).
  • Implement best practice of exception handling on your APIs to hide all your internal server and database information to mitigate SQL injection security risk.
  • Use Service Mesh to manage different layers of API management and control.
  • Audit your APIs and remove all unused API from your API catalog.
  • Add proper logging, Monitoring and Alerting on your APIs to keep track of your APIs activity.

Conclusion: APIs are a critical part of modern AI, mobile, SaaS, IOT and web applications. APIs Security should be the main focus on strategies and solutions to mitigate the unique vulnerabilities and security risks .

Covid 19 :Digital Transformation

Digital Transformation

The coronavirus (COVID-19) outbreak is one of the worst pandemic in recent history. This pandemic is affecting almost every person in the world. This pandemic is changing our living style, working style and also affecting our society.

This pandemic crisis raised a number of unique challenges among small and enterprise businesses. Organizations are navigating the business and facing unique operational challenges and delivering their product to their customers during the pandemic. 

During this COVID-19 pandemic crisis here are few business challenges 

  • Resource Management 
  • Client Management 
  • Digital/online transformation 
  • Employee Remote work management

In this pandemic crisis API is playing a pivotal role to help their customers to migrate their business into digital through digital transformation solutions. API is playing a pivotal role to expedite digital transformation. API is also providing a platform  and solution for crisis management during this pandemic.

Here is API solution for business

  • Make decisions — APIs are creating open platforms that expose critical COVID and organization data to enable organization proper management and tracking.These API enable data are helping to create dashboard and AI model. These dashboard and AI models help organizations to  take decision or forecast their future strategy.
  • Respond and deliveries — Tracking and Management APIs are  enabling organizations to respond quickly for any crisis and deliver their product on time.This helps any organization to expand their business and digitalize their legacy system & assets.
  • Return to work — APIs, templates and connectors are helping to unlock employee data. Organizations are integrating with ERP systems through APIs and unlocking their employee and resources data during pandemic. It is also facilitating/helping their employees to return their work during pandemic time either remote or onsite.
  • Simplify delivery — Enabling APIs, templates and micro-services are helping to simplify and  improve their business process during pandemic.This is also helping to enable new innovation within organization and opening new business opportunity.

Covid 19 is also expediting digital transformation in healthcare. It is reshaping the way humans interact with technology in healthcare and Public Health Agencies  or Federal Regulators. COVID-19 is also pushing healthcare organizations to embrace the idea of digital health and intelligent data integration as a tool. “Contact tracing” during pandemics is only possible through enablement of APIs. Federal and state governments are getting “contact tracing” patient data through API and using this data to trace down the source of pandemic.

API is also enabling pharmaceutical industries to deliver medicine fast and on time. It is also helping to manage and track medicine dose and availability. 

Conclusion: Covid is disrupting whole industries and pushing companies to digital transform their process forever.

Mulesoft Performance Tunning

API Performance Tunning
  1. Keep the application synchronous if possible. Synchronous flows avoid serialization/deserialization of messages sent through VM queues, do not cause context switches, and do not cause contention when messages move across thread pools.
  1. Store as little as possible in variables. The vars are serialized and deserialized every time a message crosses an endpoint, even if it is a VM endpoint. This will impact performance overhead in direct proportion to the size of variables and the number of endpoints. 
  1. Use Dataweave Java payloads whenever possible. The usage of a canonical data model is recommended for projects that deal with data (mapping, transformation etc.). It is also recommended to create them in Java objects as dataweave whenever possible, as this provides the fastest format to access fields and change information and to convert to other formats.
  1. Encourage dataweave  languages. For better performance, use Dataweave for simple data extraction from messages, and Java components with dataweave for everything else. 
  1. Use flow references instead of VM endpoints. To communicate between flows internally within an application, use flow references instead of VM endpoints. The VM connector, even though it is an in-memory protocol, emulates transport semantics that serialize and deserialize parts of your messages, most notably the vars. This makes it slower than a flow reference, which just injects messages into the referenced flow with no intermediate steps. Please note that in some cases the usage of VM endpoints is preferred (see the chapter on reliability patterns). For example, a Mule cluster can load balance applications that use VM endpoints by deferring execution to another, available node in the cluster.
  1. Cache aggressively. Take advantage of Mule’s caching scope when making requests to external resources like Web services or databases. Also consider caching reusable assets such as security tokens or ephemeral API keys and cookies. Mule’s Notification subsystem can additionally be used to “warm up” a cache when Mule starts. For example, consider doing this for situations where an initial cache miss is not acceptable.
  1. Configure message processors and endpoints at the global level. Some connectors allow you to configure some parameters at both the global and the endpoint/message processor level. We recommend placing the configuration at a global level to avoid repeated initialization of resources. 
  1. Avoid creating a large volume of business events. Business events incur performance overhead in Mule and in platform when platform’s internal event buffer overflows. Thus, avoid using either default flow level business events or a large volume of custom business events in a high message volume project.
  1. Consider using message compression. For communicating between Mule applications over the network consider using Mule’s compression processors to compress/decompress the message payloads before they hit the wire if their sizes are large.
  1. Consider using VM queues instead of an external message broker. VM queues are fast and have some guaranteed delivery semantics in a cluster. Consider using these instead of going out to an external messaging broker for inter-application Mule communication.
  1. Use the async scope when appropriate. If a flow is performing processing on a message that is neither modifying the message nor changing how it is routed, then it could be wrapped in an async block. This will cause the processing to occur in a different thread and will avoid adding unnecessary overhead to processing the message.
  2. Use connection pooling for connectors because the performance cost of establishing a connection to another data source, such as a database, is relatively high.
  3. Optimize your logging within your mule flows. Too much logging will slow down your process and too less logging will hard to debug.
  4. Encryption and decryption of data is very costly. Whenever your Mule application really needs then apply encryption/decryption on your data.

APIs Integration with IOT and CRM improves Customer Service

APIs integration helping IOT and CRM to enable better customer experience

IOT (Internet of things) is revolutionizing our lives. As per Gartner report by 2025 IOT market will expand a 58-billion-dollar opportunity. It is affecting all parts of our life. In our pandemic era we found more use of IOT device to maintain social distancing.

IOT is also one of the main disruptive technologies in our businesses. It is affecting all business domain including healthcare, retail, automotive, security.

There are wide range of IOT benefits in business.

  • Enhanced productivity
  • Better customer experience
  • Cost-effectiveness

CRM system is keeping all your customer relationship like data, notes, metrics and more – in one place. CRM is helping small business to take off all burden from the IT management team by automating the business process. It is also helping employee to keep the focus on the critical business areas.

API is helping to integrate these two unrelated systems. APIs are enabling this system to optimize process and streamline whole business process. API is the main communication channel to build robust process and keeping real time update to these systems. APIs are allowing to build context-based application with IOT and CRM to interact with the physical world.

Now here are few areas where IOT is helping CRM system with help of APIs to optimize business process.

  1. Optimize customer service – Before your customer finds any error in your service/product you proactively acting on error and fixing those error. This will help to build relationship with customer.
  2. Increase sales – With help of IOT and CRM system you are finding untouched opportunity and using those opportunity to increase your sale.
  3. Personalize customer experience – You are analyzing data provided by IOT and CRM system and building user based predictive model to enable personalize experience to user.
  4. Customer retention – CRM provide customer data and relationship. IOT data providing customer behavior. This will help any business to personalize and target marketing for their customer.
  5. Omnichannel instore experience – IOT and CRM is helping business to enable 360 omnichannel customer experience. This process will help and suggest the products which the customer might purchase.

APIs  integration with IOT and CRM helping business to enable higher degree of personalization, target marketing, optimize price model, higher revenue and enhance customer satisfaction.

Anypoint Platform: External (OKTA) Identity Management

Anypoint Platform acts as a client provider by default, but you can also configure external client providers to authorize client applications. As an API owner, you can apply an OAuth 2.0 policy to authorize client applications that try to access your API. You need an OAuth 2.0 provider to use an OAuth 2.0 policy. You can configure more than one client provider and associate the client providers with different environments. If you configure multiple client providers after you have already created environments, you can associate the new client providers with the environment. 

MuleSoft supports client management by identity providers that implement the OpenID Connect Dynamic Client Registration open standard. MuleSoft explicitly verifies support in Anypoint Platform for Salesforce, Okta, and OpenAM v14 Dynamic Client Registration. The following table contains examples of the URLs you need to supply, depending on your provider, during registration.

URL NameOkta Example URLOpenAM Example URLSalesforce Example URL
Base https://example.okta.com/oauth2/v1 https://example.com/openam/oauth2 https://example.salesforce.com/services/oauth2
Client Registration {BASE URL}/clients {BASE URL}/connect/register {BASE URL}/register
Authorize {BASE URL}/authorize {BASE URL}/authorize {BASE URL}/authorize
Token {BASE URL}/token {BASE URL}/access_token {BASE URL}/token
Token Introspection {BASE URL}/introspect {BASE URL}/introspect {BASE URL}/introspect
URL Name Okta Example URL OpenAM Example URL Salesforce Example URL

Steps to Create External Client Provider

  • Log in to Anypoint Platform using an account that has the organization administrator role.
  • In Anypoint Platform, click Access Management.
  • In the menu on the left, click Client Providers.

  • Click Add Client Provider, and then select OpenID Connect Dynamic Client Registration.
    The Add OIDC client provider page appears.
  • After obtaining values from your identity provider’s configuration, complete the following required fields in each section:
    • Dynamic Client Registration
      • Issuer: URL that the OpenID provider asserts is its trusted issuer.
      • Client Registration URL: The URL to dynamically register client applications as a client application for your identity provider.
      • Authorization Header
        • For Okta, this value is SSWS ${api_token}, where api_token is an API token created through Okta.
        • For ForgeRock, this value is Bearer ${api_token}, where api_token is an API token created through ForgeRock.
        • For Salesforce, this value is Bearer ${api_token}, where api_token is an API token created through Salesforce. In Advanced Settings you can also select:
      • Disable server certificate validation: Disables server certificate validation if your OpenID client management instance presents a self-signed certificate, or one signed by an internal certificate authority.
      • Enable client deletion in Anypoint Platform: Enables deletion of clients created with this integration.
      • Enable client deletion and updates in IdP: To use this option, you must also select the Enable client deletion in Anypoint Platform option.
    • Token Introspection Client
      • Client ID: The client ID for an existing client in your IdP capable of introspection of all tokens from all clients.
        • For Okta, this value should be a “Confidential” client.
        • For ForgeRock, this value should be a “Confidential” client.
        • For Salesforce, this value should be a “Confidential” client.
      • Client Secret: The client secret that corresponds to the client ID.
    • OpenID Connect Authorization URLs
      • Authorize URL: The URL where the user authenticates and grants OpenID Connect client applications access to the user’s identity.
      • Token URL: The URL that provides the user’s identity, encoded in a secure JSON Web Token.
      • Token Introspection URL: endpoint that returns metadata about the access token, including expiration and token active state.

Mule 4: Consume a SOAP Webservice

The Web Service Consumer is an existing connector in Mule 4 that you can configure to point to a SOAP based web service. Webservice consumer call webservice hosted elsewhere as WSDL SOAP services and get response. This connector simplified process and encapsulated all the feature to consume SOAP based webservice. When no connector is available specific to any product (like Service-Now, Workday etc.), which is hosted as SOAP based webservice then this webservice consumer Connector enables any services to consume.

The main feature of this connector is

  • Consuming DOC Literal Web services.
  • SOAP multipart messages.
  • SOAP Headers.
  • DataSense support for SOAP Headers, SOAP Body, and Attachment.
  • Embedded DataWeave transformations inside the operation.
  • Support and Unified experience for SOAP with attachments and MTOM handling.
  • Custom HTTP configuration as transport (runtime and design time).
  • Web Service Security (WS Security) support.

Connector Configuration- In this section we define connector configuration to communicate with SOAP based webservice end point. By default, connector uses a simple non protected HTTP configuration to send all outgoing SOAP message.  In connector configuration you can select your SOAP version from drop down  and provide WSDL location. Connector extract and populates Service, Port and webservice endpoint address from WSDL file.

But if you are using secure endpoint address with HTTPS you need to configure custom Transportation Configuration for HTTPS.

These are the steps to enable your secure HTTPS endpoint.

  • Create jks file with keytool command
 keytool -keystore clientkeystore.jks -genkey -alias client 
  • Download certificate from WSDL HTTPS endpoint and add this certificate in your JKS file with below command
keytool -importcert -file certificate.cer -keystore clientkeystore.jks -alias "Alias"
  • Now configure TLS Context for Webservice consumer connector.
<tls:context name="TLS_Context" doc:name="TLS Context" doc:id="f634b824-2695-4d5f-8789-7a309b1511cb" >
           <tls:trust-store path="certificate/clientkeystore.jks" password="xxxxxx" type="jks" />
     </tls:context>
  • Now configure HTTP Request configuration for HTTPS endpoint.
<http:request-config name="HTTPS_Request_configuration" doc:name="HTTPS Request configuration" doc:id="02db1fd9-9f04-4eae-83cf-df43effd25d2">
           <http:request-connection protocol="HTTPS" host="service.vanrish.com" port="443" tlsContext="TLS_Context">
     	   </http:request-connection>
	</http:request-config>

  • If TLS and HTTPS configuration configured then you can select HTTP request configuration from Webservice consumer
<wsc:config name="BookService_Web_Service_Consumer_Config" doc:name="Book Web Service Consumer Config" doc:id="59fd0d73-f90d-4cf0-9855-c008307067a2" >
 <wsc:connection wsdlLocation="wsdl\bookservice.wsdl" service="BookService" port="BookServicePort" address="https://service.vanrish.com:443/service/BookService">
  <wsc:custom-transport-configuration >
    <wsc:http-transport-configuration requesterConfig="HTTPS_Request_configuration"/>
  </wsc:custom-transport-configuration>
 </wsc:connection>
</wsc:config>

Connector Parameter- If connector configuration is configured properly, your operation parameters are available from WSDL as drop down options.

In Message section there are three parameters available

  1. Body – The Body is main part of the SOAP message. The body element accepts embedded DataWeave scripts as values so that you can construct the XML request without having a side effect on the message or having to use multiple components to create the request.
  2. Headers – The headers element contains application-specific information (like authentication, payment, and so on) about the SOAP message . This elements accepts embedded DataWeave scripts as values.
  3. Attachment – The attachments element enables you to bind attachments to the SOAP message. This element also accepts embedded DataWeave scripts as values.

Since you configured custom HTTPS connector for your webservice consumer Connector you can configure Transport Configuration. In Transport header section you can select “Edit inline” and add all your header parameters in line

<wsc:consume doc:name="Consume" doc:id="ca5a1247-7cf6-4c7f-a442-b6fd037c13c9" config-ref="BookService_Web_Service_Consumer_Config" operation="AddBook">
       <wsc:transport-headers >
          <wsc:transport-header key="SOAPAction" value="AddBook" />
          <wsc:transport-header key="Content-Type" value="text/xml; charset=UTF-8" />
          <wsc:transport-header key="Authorization" value="${book.authorization}" />
       </wsc:transport-headers>
 </wsc:consume>

Here is webservice consumer flow diagram

Code for this flow

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core"
	xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:tls="http://www.mulesoft.org/schema/mule/tls"
	xmlns:wsc="http://www.mulesoft.org/schema/mule/wsc"
	xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/wsc http://www.mulesoft.org/schema/mule/wsc/current/mule-wsc.xsd
http://www.mulesoft.org/schema/mule/tls http://www.mulesoft.org/schema/mule/tls/current/mule-tls.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd">
	
	<wsc:config name="BookService_Web_Service_Consumer_Config" doc:name="Book Web Service Consumer Config" doc:id="59fd0d73-f90d-4cf0-9855-c008307067a2" >
            <wsc:connection wsdlLocation="wsdl\bookservice.wsdl" service="BookService" port="BookServicePort" address="https://service.vanrish.com:443/service/BookService">
	            <wsc:custom-transport-configuration >
					<wsc:http-transport-configuration requesterConfig="HTTPS_Request_configuration" />
				</wsc:custom-transport-configuration>
            </wsc:connection>
     </wsc:config>

	<tls:context name="TLS_Context" doc:name="TLS Context" doc:id="f634b824-2695-4d5f-8789-7a309b1511cb" >
           <tls:trust-store path="certificate/clientkeystore.jks" password="changeit" type="jks" />
     </tls:context>

    <http:request-config name="HTTPS_Request_configuration" doc:name="HTTPS Request configuration" doc:id="02db1fd9-9f04-4eae-83cf-df43effd25d2">
           <http:request-connection protocol="HTTPS" host="service.vanrish.com" port="443" tlsContext="TLS_Context">
     	   </http:request-connection>
	</http:request-config>

	<sub-flow name="addbook-ServiceSub_Flow" doc:id="511f0969-0b7d-4b7e-a113-60ef03e97648" >
             <logger level="INFO" doc:name="Logger" doc:id="e6bd0106-e512-4fdd-97cf-1dbd77e1e0e7" message="Entering into AddBook flow"/>
                             <ee:transform doc:name="Transform Message" doc:id="06cc17de-86a9-4c53-a2f4-167d9561bed9" >
                                           <ee:message >
                                                          <ee:set-payload ><![CDATA[%dw 2.0
 output application/xml skipNullOn="everywhere"
 ns n0  https://www.service.vanrish.com/BookService/
  ---
   n0#AddBook:
         {
                 n0#Book : {
                 	ID: payload.id,
                 	Title : payload.title,
                 	Author : payload.author
                 }
         }]]></ee:set-payload>
                                           </ee:message>
                             </ee:transform>
                             <logger level="INFO" doc:name="Logger" doc:id="ce84f628-7b38-4d2d-b5e3-9fdded2c9289" message="soap request --> #[payload]"/>
                             
<wsc:consume doc:name="Consume" doc:id="ca5a1247-7cf6-4c7f-a442-b6fd037c13c9" config-ref="BookService_Web_Service_Consumer_Config" operation="AddBook">
                                           <wsc:transport-headers >
                                                          <wsc:transport-header key="SOAPAction" value="AddBook" />
                                                          <wsc:transport-header key="Content-Type" value="text/xml; charset=UTF-8" />
                                                          <wsc:transport-header key="Authorization" value="${book.authorization}" />
                                           </wsc:transport-headers>
                             </wsc:consume>
                             <logger level="INFO" doc:name="Logger" doc:id="680d69e0-2b01-480c-afe7-660ca22b2f9f" message="AddBook Output-->#[payload]"/>
                             <ee:transform doc:name="Transform Message" doc:id="72d26561-107a-4c6e-a7d4-85bd18e0d316" >
                                           <ee:message >
                                                          <ee:set-payload ><![CDATA[%dw 2.0
ns ns0 https://www.service.vanrish.com/BookService/
 

output application/json skipNullOn="everywhere"
---
payload.body.ns0#AddBookResponse]]></ee:set-payload>
                                           </ee:message>
                             </ee:transform>
                             <logger level="INFO" doc:name="Logger" doc:id="ea517185-efa4-4bf2-a03f-e8bd4d308e80" message="Output AddBook --> #[payload]"/>
              </sub-flow>
</mule>

Mulesoft 4: Using Java in Dataweave 2.0

Mule 4 introduces DataWeave 2.0 as the default expression language replacing Mule Expression Language (MEL). DataWeave 2.0 is tightly integrated with the Mule 4 runtime engine, which runs the scripts and expressions in your Mule application.

Since Dataweave 2.0 is default expression language for Mule 4, Dataweave can use almost all place within your Mule application. So, In some use-case Dataweave needs to call java method or instantiate java class to execute java complex business logic.

In my previous blog I explained usage of java within Mulesoft flow. In this blog I am explaining usage of java within Dataweave 2.0.

There are 2 ways we can use java within Dataweave code

  1. Calling java method
  2. Instantiate Java class
1. Calling java method There is restriction with Dataweave when calling to java. you can only call Static methods via DataWeave (methods that belong to a Java class, not methods that belong to a specific instance of a class). Before making a method call from java class, you must import the class.

Here is Dataweave code

In dataweave this method can use multiple way

Import only method instead of the whole class:

%dw 2.0
import java!com::vanrish::AppUtils:: encode
output application/json
---
{
encode:encode("mystring" as String)
}

import and call it in a single line:

%dw 2.0
output application/json
---

    encode: java!com::vanrish::AppUtils:: encode ("mystring" as String)
}
2. Instantiate Java class Dataweave allows to instantiate a new object of any java class but you can’t call its instance method through dataweave. You can refer it as variables.

%dw 2.0
import java!com::vanrish::AppUtils
output application/json
---
{
     value: AppUtils::new().data
}

AppUtils.java

package com.vanrish;

import sun.misc.BASE64Encoder;
/**
 * @author rajnish
 */
public class AppUtils{
	public static final BASE64Encoder encoder = new BASE64Encoder();
        private String data;
	
	/**
	 * @param plainString
	 * @return
	 */
	public static String encode(String plainString)
	{
		String encodedString = encoder.encodeBuffer(plainString.getBytes());
		return encodedString;
	}

/**
	 * @param dataStr
	 * @return
	 */
	public String getData(String dataStr)
	{
              data = dataStr+" : test";
              return  data;
	}
}

MuleSoft 4: Using Java in Mule Flow

MuleSoft is a lightweight integration and API platform that allows you to connect anything anywhere and enable your data through API. Mule evolved from java and spring framework. MuleSoft supports multiple language although all Mule module are developed in java.

 Since Mule evolved from java it has capability to use direct java class and method in Mule flow. This capability gives flexibility to Mule developer to use java for complex business logic.

There are several ways you can use java within Mule. Here are some of Java modules available to use within MuleSoft application

There are 4 java modules are available in MuleSoft flow

  1. New
  2. Invoke
  3. Invoke static
  4. Validate type

To explain all these components and uses in Mule flow I created Utils.java and AppUtils.java classes

1. New – AppUtils.java class instantiation can be achieved by calling constructor of this class through MuleSoft New component within Mule flow.

AppUtils java class defined 2 contractors, So Mule constructor properties for NEW component is showing 2 options.

New module without parameter

<java:new doc:name="Instantiate appUtils" doc:id="22ddcb7e-82ed-40f8-bc11-b779ceedd1a1"
constructor="AppUtils()" class="com.vanrish.AppUtils" target="appInst">
</java:new>

New module with parameter

<java:new doc:name="Instantiate appUtils" doc:id="22ddcb7e-82ed-40f8-bc11-b779ceedd1a1"
constructor="AppUtils(String)" class="com.vanrish.AppUtils" target="appInst">
<java:args ><![CDATA[#[{paramVal:"Hello world}]]]>
</java:new>

In above code, Instance of AppUtils class is created and placed into the “appInst”  target variables to reuse same instance in Mule flow.

New module
2. InvokeIn new java module we instantiate AppUtils.java class and placed into “appInst” variable. Now to use this variable set Invoke module and call one of method define in AppUtils.java class. In AppUtils.java class, there is one non static method “generateRandomNumber” defined with String parameter. In example we call this method through Invoke module.
<java:invoke doc:name="Invoke" doc:id="9348e2cf-87fe-4ff7-958c-f430d0421702"
instance="#[vars.appInst]" class="com.vanrish.AppUtils" method="generateRandomNumber(String)">
<java:args ><![CDATA[
#[{numVal:”100”}]]]></java:args>
</java:invoke>
Invoke module
3. Invoke staticInvoke static java module enable mule flow to call java static method. This is one of the easy ways to call any java method in Mule flow.

Mule code is calling to java static method

<java:invoke-static doc:name="Invoke static" doc:id="bc3e110c-d970-47ef-891e-93fb3ffb61bd" 
class="com.vanrish.AppUtils" method="encode(String)">
<java:args ><![CDATA[#[{plainString:"mystringval"}]]]></java:args>
</java:invoke-static>
Invoke-static module
4. Validate typeValidate type java module use instance of method from java. This module accepts “Accept subtypes” parameter which indicates if the operation should accept all subclasses of a class. By default it acceptSubtypes=“true” which means it will accept all sub class of main class but if it will set as false acceptSubtypes=“false” then during execution the operation throws an error (JAVA:WRONG_INSTANCE_CLASS)
<java:validate-type doc:name="Validate type" doc:id="288c791c-50eb-4be0-b924-56481dfdc023"
class="com.vanrish.Utils" instance="#[vars.appInst]" acceptSubtypes="false"/>
Validate-type module

Java in Mule flow diagram

java in Mule flow

Utils.java

package com.vanrish;

public class Utils{
	
}

AppUtils.java

package com.vanrish;
import java.util.Random;
import sun.misc.BASE64Encoder;
/**
 * @author rajnish
 */
public class AppUtils extends Utils {
	public static final BASE64Encoder encoder = new BASE64Encoder();
	//Constructor without Parameter
	public AppUtils(){
		System.out.println("Constructor with no parameter");
	}
	//Constructor with Parameter
  public AppUtils(String paramVal){
		System.out.println("Constructor with parameter value="+paramVal);
	}
	/**
	 * @param String
	 * @return
	 */
	public  String generateRandomNumber(String numVal) {
		Integer numNoRange = null;
		  Random rand = new Random();
		  if(numVal !=null) {
			  numNoRange = rand.nextInt(new Integer(numVal));
		  }else {
		   numNoRange = rand.nextInt();
		  }
	    return numNoRange.toString();
	}
	/**
	 * @param plainString
	 * @return
	 */
	public static String encode(String plainString)
	{
		String encodedString = encoder.encodeBuffer(plainString.getBytes());
		return encodedString;
	}
}

Mulesoft Code

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:java="http://www.mulesoft.org/schema/mule/java" xmlns:db="http://www.mulesoft.org/schema/mule/db"
xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core"
xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd
http://www.mulesoft.org/schema/mule/hl7 http://www.mulesoft.org/schema/mule/hl7/current/mule-hl7.xsd
http://www.mulesoft.org/schema/mule/db
http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd
http://www.mulesoft.org/schema/mule/java http://www.mulesoft.org/schema/mule/java/current/mule-java.xsd"> <http:listener-config name="HTTP_Listener_config" doc:name="HTTP Listener config" doc:id="af3ce281-bf68-4c7b-83fb-52b2d2506677" > <http:listener-connection host="0.0.0.0" port="8081" /> </http:listener-config> <flow name="helloworldFlow" doc:id="a13826dc-67a1-4cda-8133-bc16a59ddba2" > <http:listener doc:name="Listener" doc:id="82522c77-5c33-4003-820a-7a04b51c3001" config-ref="HTTP_Listener_config" path="helloworld"/> <logger level="INFO" doc:name="Logger" doc:id="b40bc107-1ab5-4a3f-8f20-d7dfb63e5acb" message="entering flow"/> <java:new doc:name="Instantiate appUtils" doc:id="c1854580-f4d4-4e5c-a34d-7ca185152d02" constructor="AppUtils(String)" class="com.vanrish.AppUtils" target="appInst" > <java:args ><! [CDATA[#[{ paramVal:"Hello world" }]]]></java:args> </java:new> <java:invoke doc:name="Invoke" doc:id="9348e2cf-87fe-4ff7-958c-f430d0421702" instance="#[vars.appInst]" class="com.vanrish.AppUtils" method="generateRandomNumber(String)"> <java:args ><![CDATA[#[{ numVal:null }]]]></java:args> </java:invoke> <java:invoke-static doc:name="Invoke static" doc:id="bc3e110c-d970-47ef-891e-93fb3ffb61bd" class="com.vanrish.AppUtils" method="encode(String)"> <java:args ><![CDATA[#[{ plainString:"mystringval" }]]]></java:args> </java:invoke-static> <java:validate-type doc:name="Validate type" doc:id="288c791c-50eb-4be0-b924-56481dfdc023" class="com.vanrish.Utils" instance="#[vars.appInst]"/> <set-payload value="Success" doc:name="Set Payload" doc:id="8b6c9c0b-07c8-4e17-b649-2c24d4da8bea" /> </flow> </mule>

MuleSoft: Cloudhub vCores Usage Optimization

Mulesoft Connect 2019 was wrapped last month in North america. These connects are one of the premier conferences for API led connectivity and digital transformation.These conference brought more content for developers, architects, and business executives across different business domain. At MuleSoft CONNECT plethora of market experts, and business executives including industry’s CEO/CTO,  discussed their Mulesoft experience and democratization of innovation.

During these conferences, I got an opportunity to talk to some business executives about their Mulesoft experiences and challenges.

One of the biggest challenges is to optimize Mulesoft vCore in cloudhub to keep their project in budget. 

Here are few steps in Mulesoft application to keep vCore usage low and project in budget.

1. API Optimization — As per Mulesoft best practices, Mulesoft suggest API led connectivity to expose data to application within or outside of your organization through reusable and purposeful APIs.

The APIs used in an API-led approach to connectivity falls  into three categories:

  • Experience APIs
  • Process APIs 
  • System APIs

When you are working on API led connectivity, do we really need all three layers of APIs every time?

No, It is not necessary to implement all three layers of APIs every time.

API Layers

Here are some of API layers use-case to save vCores usage and optimize APIs led connectivity.

  • Experience APIs — Experience API is similar to process APIs but unlike Process APIs, Experience APIs are more specifically tied to a unique business context, and project data formats, interaction timings, or protocols into a specific channel and context. These  APIs simplifies your front end data, based on different GUI. For example if you are working on PC website or Mobile website, we display data based on user experience, so we need different APIs to show these data, but if your application needs  only data irrespective of user experience we can skip Experience APIs and application can work only on Process APIs or System APIs. This will save some vCores and keep project in budget.
  • Process APIs — Process APIs, if you are working on complex business logic based on different organization department then you can incorporate all these business specific data in process layer and expose these data through process APIs. But if APIs are not incorporating any complex business logic and most of datas are processing through System APIs then in this use-case you can skip Process APIs and expose your data through System APIs. In this way you can save some vCore and keep your project within budget.

2. Salesforce Platform Events Integration – Salesforce integration with Mulesoft is one of the very common integration use-cases. In the old days  Salesforce synced their data through polling. Poll run couple of time in whole day and sync data between different salesforce org. Since this is polling process, it is not easy to predict the volume of data flowing through Mulesoft application during a certain period of time. So in this case, we go with higher mulesoft vCore to avoid any memory leak. 

Salesforce introduced “Platform Events”   the Salesforce Enterprise Messaging Platform on June 2017. After introduction of “Platform Event”,  integration of Mulesoft and salesforce has become very easy. “Platform Event” enterprise messaging service is event based. So any update for any create Object within salesforce generates event and sends payload to salesforce messaging queue. Mulesoft-Salesforce connector read these payload for data sync from Salesforce messaging queue FIFO based. Since this integration is event based, so as soon as Mulesoft receives event from “Platform event” it is processes Platform event message. So any time we have no large set of data to process. In this integration then we can go for lower vCore and execute project within budget. 

3. Batch Process Optimization — Mulesoft allows to process messages in batch. Mule batch process provides a construct for asynchronous processing larger-than-memory data sets that can split into individual records. Mulesoft batch extracting, transforming and loading (ETL) information into a target system like hadoop.

               Mulesoft needs large memory/vCore to run large sets of data in batch process.   These Mulesoft batch process runs max once or twice a day . These Mulesoft batch  hold large number of vCore idle rest of day without any active usage. You can optimize vCore usage and reduce your batching processing cost by following these two steps.

  • Reuse vCore by deploying multiple batch process applications — As you know, batch run certain time of day once or twice. Suppose one batch application is running every midnight and other batch application is running every morning . Both your batch application is taking 1 vCore. So both applications consuming  total 2 vCore.

If you are configuring any CI/CD process like Jenkin/Code build to deploy your batch application into cloud then it is very easy to manage your process to reuse your vCore. Your can configure you CI/CD process to build your application and deploy your application into cloud when you want to run batch. Once batch is done then you un-deploy your application and deploy next batch application on same memory. In this way you can keep reusing your vCore memory and keep your project within budget.

  • Deploy Batch application in on-premise Mulesoft server — As we all know Batch process is simple and easy to maintain application in most to their use-case. In this case it is very easy to maintain on-premise Mulesoft server and deploy your batch application without much worry about vCore usage.

Link:

Salesforce Platform Event Mulesoft Integration : https://www.vanrish.com/blog/2018/10/01/mulesoft-salesforce-platform-events-integration/