BassemE/mulesoft-documentation-embeddings huggingface dataset:
substringAfterLast | MuleSoft Documentation
# substringAfterLast
## substringAfterLast(text: String, separator: String): String
Gets the substring after the last occurrence of a separator. The separator is not returned.
_Introduced in DataWeave version 2.2.0._
### Parameters
Name | Description  
---|---  
The input string.  
`separator` | String to search for.  
### Example
This example shows how `substringAfterLast` behaves with different inputs and sizes.
#### Source
```
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
 "a": substringAfterLast(null, "'"),
 "b": substringAfterLast("", "-"),
 "c": substringAfterLast("abc", "b"),
 "d": substringAfterLast("abcba", "b"),
 "e": substringAfterLast("abc", "d"),
 "f": substringAfterLast("abc", "")
}
```

#### Output
```
{
 "a": null,
 "b": "",
 "c": "c",
 "d": "a",
 "e": "",
 "f": null
}
```

## substringAfterLast(text: Null, separator: String): Null
Helper function that enables `substringAfterLast` to work with a `null` value.
_Introduced in DataWeave version 2.2.0._
Troubleshooting Flex Gateway | MuleSoft Documentation
# Troubleshooting Flex Gateway
When you perform Anypoint Flex Gateway tasks, you might encounter issues or receive error messages. These topics help you resolve these issues:
## Troubleshooting Managed Flex Gateway
  * Troubleshooting Managed Flex Gateway Creation
  * Troubleshooting Managed Gateway Maintenance


## Troubleshooting Self-Managed Flex Gateway
  * Troubleshooting Self-Managed Gateway with Debug Logs
  * Troubleshooting Registration Issues
  * Troubleshooting Linux Permissions
  * Troubleshooting Platform Connections
  * Troubleshooting Self-Managed Gateway Logging Issues
  * Troubleshooting Linux Services
  * Troubleshooting with the CLI
  * Troubleshooting Request Connection
  * Troubleshooting Docker Command Issues
  * Troubleshooting Helm Command Issues
Accelerator Setup Guide | MuleSoft Documentation
# Accelerator Setup Guide
This page provides guidance on configuring the various systems and products required to implement the use cases provided by this solution.
## Service Accounts
Service accounts are needed for the applications below, with the versions used during Accelerator development noted:
  * Salesforce B2C Commerce (Version 20.6, Compatibility Mode 19.10)
  * Salesforce Marketing Cloud (April 2021)
  * Salesforce (Spring '21)
  * SAP (ECC 7.5)


Additional resources used:
  * Global Data Management System (GDM) - MariaDB used as GDM
  * Order Management System (OMS) - Apache OFBiz used as OMS
  * Product Information Management (PIM) - Oracle 11g used as PIM


## Required Configuration
In addition to configuring individual applications to suit your target deployment environment, the following will be required to implement the use cases described:
  * B2C Commerce Configuration: Open Commerce and Salesforce Commerce API access in addition to deployment and configuration of the B2C Commerce Sync Cartridge.
  * Salesforce Configuration: Addition of custom fields and enabling Person Accounts (details can be found here) in addition to creating a push topic on Account object with appropriate filters.
  * Salesforce Marketing Cloud: A custom Data Extension will need to be created along with an Installed Package to make API requests.
  * SAP Configuration: Deployment of the custom SAP BAPI code required.


## Optional Configuration
The accelerator includes some additional common components, which can be configured to suit your needs. These are all optional:
  * Configurable properties in the common core library
  * Notification APIs for sending error notifications via email, SMS or Slack
  * Common scheduler for executing jobs on a schedule


Please refer to the Accelerators Common Services documentation for more details on configuring optional components.
## See Also
  *   * MuleSoft Accelerator for Retail
Reviewing API Manager Mule API Analytics Charts Usage | MuleSoft Documentation
# Reviewing API Manager Mule API Analytics Charts Usage
Mule API Analytics provides a summary in chart form of requests, top apps, and latency for 1 hour, 3 hours, 1 day, 7 days, or 1 month. This data is available for 30 days. To view the Mule API Analytics chart, in API Manager, click the instance name of a deployed API.
**Note:** To view Mule API Analytics charts, users need `View APIs Configuration` permission. See To Set Permissions.
## Reviewing Requests Summary Chart
The requests summary chart lists the total number of requests to your API instance by the duration you choose. The chart shows the HTTP status codes specified by W3C. For example:
Graph lines are provided for:
  * Green - Successful requests that returned a status code from 1xx to 3xx.
  * Dark Gray - Client failed requests that returned a status code of 4xx.
  * Blue - Server failed requests that returned a status code of 5xx.


## Reviewing Top Apps Summary Chart
The top apps summary chart lists the number of requests made to the API instance by each application for the top 5 applications calling that API instance. Each color represents one of the top 5 applications accessing the API. The y-axis plots the number of calls made to the API instance.
The graph lists the number of requests over the duration you select, for example:
## Reviewing Latency Summary Chart
The latency summary chart lists the average API latency for the period selected. The higher the latency, the lower the performance. The y-axis in the chart lists the average latency in milliseconds (ms).
The following example shows that the worst average performance in the one-hour period was at 8:30 am.
## Including Policy Violations in Charts
**Note:** Users must have the `View Policies` permission set to view policies or edit a Policy Violation alert.
Enable or disable the tracking of policy violations by checking the Include Policy Violations checkbox on an Mule API Analytics chart screen. The chart shows traffic rejected, or not rejected, by a policy.
## See Also
  *
Using XA Transactions in Database Connector | MuleSoft Documentation
# Using XA Transactions in Database Connector
Anypoint Connector for Database (Database Connector) provides the option to use Extended Architecture Transactions (XA Transactions) when you enable the **Use XA Transactions** field in the Database Connector global configuration.
## Before You Begin
Before getting started, ensure that you have an understanding of XA Transactions
## Use XA Transactions
You can enable the **Use XA Transactions** field in the database global connector configuration for the **Derby Connection** , **Generic Connection** , **Microsoft SQL Server Connection** , **MySQL Connection** , and **Oracle Connection**. For a **Data Source Reference Connection** , refer to the Configure a Data Source Reference Connection When in XA Transaction Mode topic.
When you enable **Use XA Transactions** the connection pooling is created as well.   
---  
The following example shows how to configure **Use XA Transactions** for the **MySQL Connection** in Anypoint Studio:
  1. In Studio, navigate to the **Global Elements** tab.
  2. Click **Create**.
  3. In the search bar, type `database`.
  4. Select **Database Config**.
  5. Click **OK**.
  6. In the **Global Element Properties** window, select **MySQL Connection** in the **Connection** field.
  7. Select the **Transactions** tab.
  8. Select **Use XA Transactions** , which indicates that the created data source must support XA transactions. Note that the implementation creates an Enhydra XADatasource.
  9. Configure other required database configurations in the **General** and **Advanced** tabs.
  10. Click **OK**.


In the **Configuration XML** editor window, the configuration looks like this:
```
<db:config name="Database_Config" doc:name="Database Config" >
		<db:derby-connection useXaTransactions="true" />
	</db:config>
```

## See Also
  * Configuring the Bitronix Transaction Manager
Viewing Key Metrics in API Manager for Managed Flex Gateway | MuleSoft Documentation
# Viewing Key Metrics in API Manager for Managed Flex Gateway
API Manager and Anypoint Monitoring collect metrics on active Flex Gateway API instances. You can view charts related to these metrics and filter the data by date.
The metrics available in API Manager are considered **Key Metrics** and are described here. **Key Metrics** are available with all Anypoint Platform subscriptions. For additional Flex Gateway API metrics not included in the **Key Metrics** section, use Anypoint Monitoring (Anypoint Integration Advanced package or Titanium subscriptions only). You can navigate to Anypoint Monitoring by clicking **Anypoint Monitoring** from Anypoint Platform.
The **Mule API Analytics** tab in API Manager is currently not available for Flex Gateway APIs. Use the **Key Metrics** or the additional metrics in Anypoint Monitoring.  
---  
## Key Metrics
  1. Log in to Anypoint Platform.
  2. In the navigation bar or the Anypoint Platform page, click **API Manager**. The **API Administration** page appears, showing a list of APIs that are available in your organization.
  3. Click the API instance. The **API Summary** page appears, showing general information and the status of the API instance.
To see an API instance in Anypoint Monitoring, from the **Key Metrics** section click **View more metrics in Anypoint Monitoring dashboard** or navigate to Anypoint Monitoring directly.


The **Key Metrics** section shows four charts. If charts do not appear for your API instance, refresh your browser.
## Understanding Key Metrics
The **Key Metrics** section of the API summary contains the following charts: 

Total Requests
    
Sum of requests in the selected time period for the given API.
Data is aggregated in one minute increments. 

Total Policy Violations
    
Sum of requests that return policy violations.
Data is aggregated in one minute increments. 

Total Errors
    
Sum of HTTP response codes that occur in the selected time period. The response codes counted in this metric are 400, 401, 402, 403, 404, 405, 408, 409, 410, 411, 412, 413, 415, 416, 417, 420, 422, 429, 500, 502, 503, 504, 504, 510, and 511.
Data is aggregated in one minute increments. In the chart, HTTP response codes are abbreviated as 4xx and 5xx. 

Average Response Time
    
Average response time of requests in the selected time period for the given API.
Data is aggregated in one minute increments.
## Setting the Time Period for Key Metrics
You can view the data points collected for the last given period of time (such as the last 5 or 30 minutes) or over a given date and time range. Use the drop-down in the calendar icon to select the time period to display.
## See Also
  * Viewing Managed Flex Gateway Metrics
  * Using Built-in API Dashboards
Aggregators Module XML and Maven Support | MuleSoft Documentation
# Aggregators Module XML and Maven Support
Although you can manually code a Mule app in XML, it is more efficient to use Anypoint Studio.
If you manually code a Mule runtime engine (Mule) app in XML, either from the Anypoint Studio XML editor or from a text editor, you can get access to the connector in your app by adding reference statements to both your XML Mule flow and the Apache Maven `pom.xml` file.
When you add the connector in Studio, Studio automatically populates the XML code with the connector’s namespace and schema location. It also adds a dependency to the `pom.xml` file.
## Add a Namespace for the Connector
Paste the following code inside the `<mule>` tag of the header of your configuration XML:
```
http://www.mulesoft.org/schema/mule/<connector>
http://www.mulesoft.org/schema/mule/<connector>/current/mule-<connector>.xsd
```

This example shows how the namespace statements are placed in the `<mule>` XML block:
```
<mule xmlns:aggregators="http://www.mulesoft.org/schema/mule/aggregators"
	xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core"
	xmlns:http="http://www.mulesoft.org/schema/mule/http"
	xmlns:file="http://www.mulesoft.org/schema/mule/file"
	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/file
	http://www.mulesoft.org/schema/mule/file/current/mule-file.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/aggregators
	http://www.mulesoft.org/schema/mule/aggregators/current/mule-aggregators.xsd">
```

## Add a POM File Dependency
The Apache Maven `pom.xml` file generated by Anypoint Studio contains dependencies for a Mule app. If you code a Mule app manually, include this XML snippet in your `pom.xml` file to enable access to this connector:
```
<dependency>
 <groupId>org.mule.modules</groupId>
 <artifactId>mule-aggregators-module</artifactId>
 <version>x.x.x</version>
 <classifier>mule-plugin</classifier>
</dependency>
```

Replace `x.x.x` with the version that corresponds to the connector you are using.
To obtain the most up-to-date `pom.xml` file information:
  1. Go to Anypoint Exchange.
  2. In Exchange, click **Login** and supply your Anypoint Platform username and password.
  3. In Exchange, search for `aggregators`.
  4. Select the connector.
  5. Click **Dependency Snippets** near the upper right of the screen.


## Next Step
After completing your namespace and `pom.xml` file, you can try the Examples
## See Also
  * Introduction to Anypoint Connectors
  * MuleSoft Help Center
Work With Throwables | MuleSoft Documentation
# Work With Throwables
The Java module exposes useful DataWeave functions for throwable instances. (In Java, a throwable is a `throw` statement.)
These functions have been available since DataWeave version 1.2.0.
## Check for a Cause
You can check if a throwable was caused by a certain type of exception using the `isCausedBy` function. This is especially useful when adding logic to error handlers.
```
package com.me;
public class TaxCalculator {
	public Double calculateTax(Double price) {
		if (price == null) {
			throw new NullPointerException("Must provide a value for price");
		}
		if (price < 0) {
			throw new IllegalArgumentException("Price must be a non-negative value, but was: " + price);
		}
		return price * 0.21;
	}
}
```

The `calculateTax(Double price)` method declares the `IllegalArgumentException` and `NullPointerException` exceptions.
The next code example lists part of a flow that throws an error during the execution of the `invoke` operation.
To check which of the Java exceptions occurred during the failed invocation of the `calculateTax(Double price)` method, use the `isCausedBy` function in the error handler to add different logic for each of the cases.
```
<java:new class="com.me.TaxCalculator"
	constructor="TaxCalculator()"
	target="taxCalculator"/>
<java:invoke instance="#[vars.taxCalculator]"
	class="com.me.TaxCalculator"
	method="calculateTax(Double)">
  <java:args>#[{price: payload.price}]</java:args>
</java:invoke>
<error-handler>
  <on-error-continue
  	when="#[Java::isCausedBy(error.cause, 'java.lang.IllegalArgumentException')]">
    <set-payload value="Negative prices are not allowed."/>
  </on-error-continue>
  <on-error-continue
  	type="#[Java::isCausedBy(error.cause, 'java.lang.NullPointerException')]">
    <set-payload value="There is no price."/>
  </on-error-continue>
</error-handler>
```

## Obtain a Root Cause
The `getRootCause` function obtains the root cause of a throwable, disregarding any exception wrapping.
In the next example, all tax calculation errors are handled by the `FailureHandler` class, which has the `handle(Throwable)` method that takes the root cause of the throwable. To make that possible, the `getRootCause` function can be used to pass the root cause as an argument to the `handle(Throwable)` method.
```
<java:new class="com.me.TaxCalculator"
 constructor="TaxCalculator()"
 target="taxCalculator"/>
<java:invoke instance="#[vars.taxCalculator]"
 class="com.me.TaxCalculator"
 method="calculateTax(Double)">
  <java:args>#[{price: payload.price}]</java:args>
</java:invoke>
<error-handler>
  <on-error-continue>
   <java:invoke-static
   	class="com.me.FailureHandler"
	method="handle(Throwable)">
     <java:args>#[{cause: Java::getRootCause(error.cause)}]</java:args>
   </java:invoke-static>
  </on-error-continue>
</error-handler>
```

## See Also
  *
Microsoft OneDrive Connector 1.1 | MuleSoft Documentation
# Microsoft OneDrive Connector 1.1
Anypoint Connector for Microsoft OneDrive (OneDrive Connector) enables you to access Microsoft Graph APIs to provide a unified programmability model that you can use to access the tremendous amount of data in Microsoft 365, Windows 10, and Enterprise Mobility + Security.
For compatibility information and fixed issues, see the Microsoft OneDrive Connector Release Notes.
## Before You Begin
To use this connector, you must be familiar with:
  * Microsoft Graph API 1.0
  * Anypoint Connectors
  * Mule runtime engine (Mule)
  * Elements and global elements in a Mule flow
  * Creating a Mule app using Anypoint Studio (Studio)


Before creating an app, you must have:
  * Credentials to access the target resource
  * Anypoint Studio version 7.3.5 or later


## Common Use Cases for the Connector
Some common use cases for OneDrive Connector include:
  * Sales Operations
    * When a sales contract comes in through the Salesforce CRM system, upload the contract to OneDrive and collaboratively review the contract with the Deal Desk. You can assign approval tasks to notify the contract owner when a contract is approved or rejected.
    * When a new budget proposal or customer invoice is generated, upload the documents to OneDrive and collaborate with the accounting team for their review. You can assign tasks to notify the invoice owner when an invoice is approved or rejected.
    * When an opportunity is closed (won), create a folder structure in OneDrive based on a predefined template.
  * Employee onboarding and offboarding
    * When new employees start their jobs, existing resources can be shared with them via OneDrive.
    * Create a new folder in OneDrive and share it with the new employee so they can upload documents to it.
    * After an employee leaves the company, all documents used or uploaded can be moved or deleted (GDPR).
  * Health care Share sensitive patient data with the departments that are allowed to access the information by using OneDrive to share the files, and allow access to the relevant parties.


## Authentication Types
OneDrive Connector uses the following authentication methods:
  * OAuth 2.0 authorization code grant connection type, which is used in applications that are installed on a device to gain access to protected resources.
  * OAuth 2.0 client credentials grant, which uses the identity of the application to access web-hosted resources.


## See Also
  * Introduction to Anypoint Connectors
  * Use Exchange to Discover Connectors, Templates, and Examples
  * Microsoft OneDrive Connector Reference
  * MuleSoft Help Center
Assert Expression | MuleSoft Documentation
# Assert Expression
Anypoint Code Builder 
Anypoint Studio 
The Assert Expression processor allows you evaluate a Dataweave expression that asserts the state of a Mule Event’s content. This processor can be used to validate the Mule Event after the production code runs, using the DataWeave Assertions Library.
For example, to assert that a payload is equal to a certain value, you can configure the Assert-Expression processor using the equalTo() matcher.
```
<munit-tools:assert>
  <munit-tools:that>#[ import * from dw::test::Asserts ---
    payload must equalTo('example') ]
  </munit-tools:that>
</munit-tools:assert>
```

## Perform Complex Assertions
The DW assertions library allows you to assert the state of the Mule Event’s content in a deeper way.
```
<munit-tools:assert>
  <munit-tools:that>#[ import * from dw::test::Asserts ---
    vars.attributes must [beObject(), $.statusCode must equalTo(200), $.method must equalTo('GET')] ]
  </munit-tools:that>
</munit-tools:assert>
```

## Create your own Matcher
To create your own matcher, you can add DW files to your `src/test/resources` folder. For example, a file called `MyMatcher.dwl` with the following content:
```
import * from dw::test::Asserts
fun beEven(): Matcher<Number> =
   (actual:Number) -> do {
     var matchesEven = (actual mod 2) == 0
     ---
     {
       matches: matchesEven,
       description: {expected: " to be an even number.", actual: write(actual) as String}
     }
   }
```

And then use it in your Assert-Expression processor:
```
<munit-tools:assert>
  <munit-tools:that>#[ import * from dw::test::Asserts ---
    payload must MyMatcher::beEven() ]
  </munit-tools:that>
</munit-tools:assert>
```

If this assertion fails, the processor throws a `java.lang.AssertionError`.
Matchers from the `dw::test::Asserts` library are not compatible with the `MunitTools` matchers. You can’t use `dw::test::Asserts` with the Assert-That processor, and you can’t use `MunitTools` matchers with the Assert-Expression processor.  
---
Publishing Managed Gateway and Connected Mode APIs | MuleSoft Documentation
# Publishing Managed Gateway and Connected Mode APIs
For Managed Flex Gateway or Flex Gateway running in Connected Mode, use **API Manager** to publish both API instances with a single upstream service, API instances with multiple upstream services, MCP server instances, and A2A server instances.
For more information, see:
  * Adding a Flex Gateway API Instance
  * Adding a Flex Gateway MCP Server Instance
  * Adding a Flex Gateway A2A Server Instance


Additionally, you can publish a simple API with Getting Started with Managed Flex Gateway on CloudHub 2.0 or Getting Started with Self-Managed Flex Gateway in Connected Mode.
## See Also
  * Flex Gateway Overview
Creating Private Locations | MuleSoft Documentation
# Creating Private Locations
A private location is a Mule application that runs in an environment in CloudHub 1.0 or Cloudhub 2.0. You can run tests against APIs that are accessible only within the private location. The private location environment might have an Anypoint VPC associated with it. You can create multiple private locations in a single instance of Anypoint VPC.
You can create a private location when you:
  *   * Add a schedule to a monitor
  * Modify a schedule in a monitor


This procedure explains how to create a private location when you modify a schedule.
For information about private locations and their uses, see Monitoring the Endpoints of Private APIs.
## Before You Begin
  * Ensure that your Anypoint Platform organization has a subscription to Anypoint Virtual Private Cloud.
  * Ensure that you have the following permission set in Access Management:
    * **Runtime Manager > Create Applications**


An Anypoint Platform administrator for your organization grants permission. See Manage Permissions.
## Create a Private Location
To create a private location:
  1. When creating a test or schedule, click the field under **Select location** and select **Create new location**.
  2. Name the location.
The name can be up to 255 characters, and can include spaces and special characters.
  3. Select the environment for the tests.
  4. Select the deployment target.
  5. Complete the creation of the test or schedule. By default, it uses a 0.2 vCores replica size.


If your deployment target is set to any variant of CloudHub 2.0, a connected app is created automatically.   
---  
+ While API Functional Monitoring is registering the private location, the status indicator is yellow. After the location is successfully registered, the status indicator is green.
+ . If the status indicator is red: .. Navigate to Runtime Manager and restart the application/worker cloudhub application. .. Check the logs for the application/worker cloudhub application to troubleshoot the issue.
## What to Do Next
You can now run tests from the private location, either by adding a schedule that uses the location or by modifying an existing schedule to use it.
## See Also
  *   *   * Modifying Schedules
  *   * Virtual Private Cloud
Add API Instances | MuleSoft Documentation
# Add API Instances
  * Adding a Mule Gateway API Instance Use Mule Gateway if you have APIs on Mule Runtime that need an API gateway to manage, observe, and secure your APIs.
  * Adding a Flex Gateway API Instance Use Flex Gateway for any APIs that need a flexible and performant API gateway that works with distributed and microservices environments and fits into your CI/CD environments.
  * Adding a Flex Gateway MCP Server Instance Use Flex Gateway to protect MCP servers that need a flexible and performant gateway that works with distributed and microservices environments and fits into your CI/CD environments.
  * Adding a Flex Gateway A2A Server Instance Use Flex Gateway for any A2A servers that need a flexible and performant gateway that works with distributed and microservices environments and fits into your CI/CD environments.
Tree Types (dw::util::Tree) | MuleSoft Documentation
# Tree Types (dw::util::Tree)
Type | Definition | Description  
---|---|---  
`type Path = Array<PathElement>` |  Type that consists of an array of `PathElement` values that identify the location of a node in a tree. An example is `[{kind: OBJECT_TYPE, selector: "user", namespace: null}, {kind: ATTRIBUTE_TYPE, selector: "name", namespace: null}] as Path`. _Introduced in DataWeave version 2.2.2._  
PathElement |  `type PathElement = {| kind: "Object" | "Attribute" | "Array", selector: String | Number, namespace: Namespace | Null |}` |  Type that represents a selection of a node in a path. An example is `{kind: ARRAY_TYPE, selector: "name", namespace: null} as PathElement`. _Introduced in DataWeave version 2.2.2._
pluralize | MuleSoft Documentation
# pluralize
## pluralize(text: String): String
Pluralizes a singular string.
If the input is already plural (for example, "boxes"), the output will match the input.
### Parameters
Name | Description  
---|---  
The string to pluralize.  
### Example
This example pluralizes the input string "box" to return "boxes".
#### Source
```
%dw 2.0
import * from dw::core::Strings
output application/json
---
 { "pluralize" : pluralize("box") }
```

#### Output
```
{ "pluralize" : "boxes" }
```

## pluralize(text: Null): Null
Helper function that enables `pluralize` to work with a `null` value.
toTime | MuleSoft Documentation
# toTime
## toTime(str: String, formatters: Array<Formatter>): Time
Transforms a `String` value into a `Time` value using the first `Formatter` that matches with the given value to transform.
_Introduced in DataWeave version 2.5.0._
### Parameters
Name | Type | Description  
---|---|---  
The `String` value to transform into a `Time` value.  
`formatters` | Array<Formatter> | The `array` of formatting to use on the `Time` value.  
### Example
This example shows how `toTime` behaves with different inputs. It produces output in the `application/dw` format.
#### Source
```
%dw 2.0
import * from dw::util::Coercions
import * from dw::Runtime
output application/dw
---
{
 a: toTime("13:44:12.283-08:00", [{format: "HH:mm:ss.xxx"}, {format: "HH:mm:ss.nxxx"}]),
 b: try(() -> toTime("13:44:12.283-08:00", [{format: "HH:mm:ss.xxx"}]).error.message
}
```

#### Output
```
{
 a: |13:44:12.000000283-08:00| as Time {format: "HH:mm:ss.nxxx"},
 b: "Could not find a valid formatter for '13:44:12.283-08:00'"
}
```

## toTime(str: String, format: String | Null = null, locale: String | Null = null): Time
Transforms a `String` value into a `Time` value and accepts a format and locale.
_Introduced in DataWeave version 2.4.0._
### Parameters
Name | Description  
---|---  
The `String` value to transform into a `Time` value.  
The formatting to use on the `Time` value. A `null` value has no effect on the `Time` value. This parameter accepts Java character patterns based on ISO-8601. A `Time` value, such as `10:15:30.000000`, has the format `HH:mm:ss.nxxx`.  
Optional ISO 3166 country code to use, such as `US`, `AR`, or `ES`. A `null` or absent value uses your JVM default.  
### Example
This example shows how `toTime` behaves with different inputs. It produces output in the `application/dw` format.
#### Source
```
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
  a: toTime("23:57:59Z"),
  b: toTime("13:44:12.283-08:00","HH:mm:ss.nxxx")
}
```

#### Output
```
{
 a: |23:57:59Z|,
 b: |13:44:12.000000283-08:00| as Time {format: "HH:mm:ss.nxxx"}
}
```
Anypoint Custom Metrics Connector | MuleSoft Documentation
# Anypoint Custom Metrics Connector
Anypoint Custom Metrics Connector enables you to send operational and business metric values that you define from an application to Anypoint Monitoring, where the metrics can be visualized in real time using custom dashboards.
Once the metrics are in a custom dashboard, you can filter and group the metrics along the included dimensions. You can include multiple custom and built-in metrics in a single dashboard visualization.
This connector is available only if your organization has the Anypoint Integration Advanced package or a Titanium subscription to Anypoint Platform. For more information, see the Pricing and Packaging documentation.
For an example of how to use the Anypoint Custom Metrics connector in an end-to-end flow, see Custom Metrics.
## See Also
  * Custom Metrics Connector Reference
  * Anypoint Monitoring Release Notes
  *
A2A Personally Identifiable Information (PII) Detector Policy | MuleSoft Documentation
# A2A Personally Identifiable Information (PII) Detector Policy
**Policy Name** | A2A PII Detector Policy  
---|---  
Detects personally identifiable information (PII) in requests sent to the agent  
**First Flex Gateway version available**  
**Returned Status Codes**  
This policy supports Agent2Agent Protocol (A2A) versions v0.2.3 and earlier. To learn more about A2A versions, see A2A Releases.   
---  
## Summary
The A2A PII Detector policy detects personally identifiable information (PII) in requests sent to the agent. If PII is detected, you can either log or block the request. A policy violation is always reported if PII is detected.
## Configuring Policy Parameters
### Flex Gateway Local Mode
The A2A PII Detector policy isn’t supported in Local Mode.
### Managed Flex Gateway and Flex Gateway Connected Mode
When you apply the policy to your API instance from the UI, the following parameters are displayed:
Element | Description  
---|---  
Array that defines the types of PII to detect. You can select multiple PII types. Supported values are `Email`, `US SSN`, `Credit Card`, `Phone Number`. For more information, see PII Types.  
Action to take when PII is detected. Supported values are `Log` or `Block`.  
### PII Types
When you configure an A2A PII Detector policy, you can choose which types of PII to detect.
The following table describes the type of PII this policy can detect:
PII Type | Description  
---|---  
Standard email addresses such as `User.Name+tag@example.com`  
United States Social Security Numbers (SSNs) in the standard format: `XXX-XX-XXXX` where each `X` is a digit. For example: `123-45-6789`.  
Credit Card |  Credit card numbers in the form of four groups of four digits, separated by optional spaces or hyphens. Examples: `1234-5678-9012-3456`, `1234 5678 9012 3456`, or `1234567890123456`.  
Phone Number |  United States phone numbers in various formats, with or without country code, parentheses, spaces, hyphens, or dots. Examples: `123-456-7890`, `(123) 456-7890`, `123.456.7890`, `+1 123 456 7890`, or `1234567890`.
Gathering Setup Information for SSO | MuleSoft Documentation
# Gathering Setup Information for SSO
Use these sections to gather the information you’ll need to set up SSO.
You might need to collaborate with your security team or other team members if you don’t have access to this information. For more information, see User Roles for Configuring SSO.
## Username Assignment Strategy for a Shared Identity
If an identity provider is configured for your Anypoint Platform organization, review the username assignment strategy because it can be different for the portal and Anypoint Platform users.
To have a single identity between the portal and Anypoint Platform, the format for the username assignment must be the same. If the username strategy doesn’t match, reconcile the username format by adding attributes for `anypoint_idp_id` and `anypoint_username`. Then, map this information to the Anypoint Platform identity provider that you are using for SSO.
For more information about adding custom claims when the identity provider is already configured but not in the required format, see _Required Claims and Attributes for SSO_.
## Required Claims and Attributes for SSO
Be aware of API Experience Hub requirements for claims or attributes when creating a new application for the portal in the identity provider.
Configuring the required user claims in the identity provider ensures that the user information is mapped correctly to Salesforce and Anypoint Platform users.
The **AEHPortalRegistrationHandler** requires specific user information from the identity provider to create or update a user. The registration handler uses required claims to extract user information. This table lists the required information and which claims the information is extracted from. If more than one claim exists for the same value, the registration handler looks for the first expected claim in the order it appears in the table:
Field | Expected Claims  
---|---  
First Name | given_name, first_name, firstname, and firstName  
Last Name | family_name, last_name, lastname, and lastName  
email, email_address, and emailAddress  
Username | preferred_username, federation_identifier, email, sub, and NameId  
To configure SSO when the identity provider is already configured for Anypoint Platform, use this information:
Field | Description | Expected Values  
---|---|---  
Anypoint Idp Id |  Map identities to the specific identity provider in Anypoint Platform. |  anypoint_idp_id  
Anypoint Username |  Explicitly specify the Anypoint Platform user if the user’s identity exists in Anypoint Platform, but the username is different than the Salesforce user. |  anypoint_username  
If the required information is not in the supported format, create a new custom attribute or claim with the supported format. For information, see the documentation for the identity provider.
## See Also
  * User Roles for Configuring SSO
  *
Payments Modernization Demo Setup Guide | MuleSoft Documentation
# Payments Modernization Demo Setup Guide
This guide provides instructions for setting up all the components required to run the Payments Modernization use case demo.
## Summary
  * A Docker runtime will be required to deploy containers needed by the solution
  * A generic core banking system will be used as the primary system of record
  * Moov.io containers will be used to simulate the processing of ACH and Fedwire messages
  * A third-party Java library will be used to simulate the processing of SWIFT messages
  * A custom process will be used to simulate incoming payment confirmations
  * A Payments Front-end Web UI has been built to demonstrate the functionality implemented by this use case
  * MultiChain Wallet Node is used to support processing of BlockChain Transactions


## Setup
This guide sets up a demo environment with the supported backend services used by the provided API implementations. When these APIs are adopted by a MuleSoft customer, it is expected that the customer will replace these example backend services with their preferred services.
The following containerized services are deployed on docker. For demo purposes, it is recommended to deploy all containers on a single Docker node.
  * moov.io ACH service
  * moov.io Fedwire service
  *   * Blockchain based on MultiChain


The Payments Front-end Web UI can also be run locally, outside of a container, by following the instructions provided in its README file.
**Payments Front-end Web UI recommended setup:**
  1. Install Docker and its dependencies on the server of your choice.
  2. Configure the Payments Front-end Web UI by modifying the following properties in the .env file:
     * `REACT_APP_PAYMENTS_WEBUI_EXP_API_ENDPOINT` should point to an instance of the Payments Web UI Experience API
     * `REACT_APP_PAYMENTS_WEBUI_EXP_API_WEBSOCKET_ENDPOINT` should point to an instance of the Payments Web UI Experience API
  3. Build the docker image by running its docker-build.sh script.
  4. Start the docker container by running the docker-run.sh script on the machine running the Docker server, or use a Docker administration UI to manage the containers.
  5. Update `https.cors.allow-url` property in the Payments Web UI Experience API with the Payments Front-end Web UI endpoint to allow CORS.


**Moov.io recommended setup:**
The moov.io images are provided pre-built as-is. They can be started on the Docker server by using the included docker-run.sh scripts.
**MultiChain setup:**
To run the MultiChain node as a docker container, perform the following steps:
  1. Use the Dockerfile from the scripts folder in the Blockchain System API to build the MultiChain image.
  2. Run the `docker-run.sh` script to deploy the container and setup network ports. Run `docker-exec.sh` to create MultiChain and configure the json-rpc service to interact with the MultiChain container.


## See Also
  *   * MuleSoft Accelerator for Financial Services
countBy | MuleSoft Documentation
# countBy
## countBy<T>(@StreamCapable array: Array<T>, matchingFunction: (T) -> Boolean): Number
Counts the elements in an array that return `true` when the matching function is applied to the value of each element.
### Parameters
Name | Description  
---|---  
The input array that contains elements to match.  
`matchingFunction` | A function to apply to elements in the input array.  
### Example
This example counts the number of elements in the input array ([1, 2, 3, 4]) that return `true` when the function `(($ mod 2) == 0)` is applied their values. In this case, the values of _two_ of the elements, both `2` and `4`, match because `2 mod 2 == 0` and `4 mod 2 == 0`. As a consequence, the `countBy` function returns `2`. Note that `mod` returns the modulus of the operands.
#### Source
```
%dw 2.0
import * from dw::core::Arrays
output application/json
---
{ "countBy" : [1, 2, 3, 4] countBy (($ mod 2) == 0) }
```

#### Output
```
{ "countBy": 2 }
```

## countBy(array: Null, matchingFunction: (Nothing) -> Any): Null
Helper function that enables `countBy` to work with a `null` value.
_Introduced in DataWeave version 2.4.0._
Enable Flow Sources | MuleSoft Documentation
# Enable Flow Sources
Anypoint Code Builder 
Anypoint Studio 
The `Enable Flow Sources` element within the MUnit test instructs MUnit which flow sources to load and execute for the test.
By default, MUnit doesn’t start any of the event sources (flow sources such as triggers and listeners). You must configure which flow sources must start for your tests.
Assume that your application has a flow with an HTTP listener that returns a specific payload:
```
<http:listener-config name="HTTP_Listener_config">
  <http:listener-connection host="localhost" port="1234"/>
</http:listener-config>
<flow name="http-example-flow">
  <http:listener path="/" config-ref="HTTP_Listener_config"/>
  <set-payload value="#['Hello World!']" mimeType="text/plain"/>
</flow>
```

For MUnit to invoke that listener, enable the `http-example-flow` in your `enable-flow-source` property within your MUnit test:
```
<http:request-config name="HTTP_Request_config">
  <http:request-connection host="localhost" port="1234"/>
</http:request-config>
<munit:test name="http-example-test">
  <munit:enable-flow-sources>
    <munit:enable-flow-source value="http-example-flow"/>
  </munit:enable-flow-sources>
  <munit:execution>
    <http:request method="GET" path="/" config-ref="HTTP_Request_config"/>
  </munit:execution>
  <munit:validation>
    <munit-tools:assert-that expression="#[payload]"
                 is="#[MunitTools::equalTo('Hello World!')]"/>
  </munit:validation>
</munit:test>
```

If the `http-example-flow` value isn’t listed as an enabled flow source, your MUnit test fails because it can’t initialize the HTTP listener configuration.
MUnit starts flow sources at the beginning of the test and stops them at the end of the test. Flow sources aren’t executed during the before-suite/before-test, nor during the after-test/after-suite. See Before/After scopes for additional information.
Binary Format | MuleSoft Documentation
# Binary Format
MIME type: `application/octet-stream`
ID: `binary`
The Binary data format handles binary content, such as an image or PDF. Such content is represented as a `Binary` type.
Note that Binary content is stored into RAM memory.
## Configuration Properties
DataWeave supports the following configuration properties for this format.
### Reader Properties
There are no reader properties for this format.
### Writer Properties
This format accepts properties that provide instructions for writing output data.
Parameter | Type | Default | Description  
---|---|---|---  
`bufferSize` |  Size of the buffer writer, in bytes. The value must be greater than `8`.  
Generates the output as a data stream when set to `true`, and defers the script’s execution until the generated content is consumed. Valid values are `true` or `false`.  
## Supported MIME Types
This format supports the following MIME types.
`application/octet-stream`  
---  
`application/x-binary`
Configuring Application Alerts | MuleSoft Documentation
# Configuring Application Alerts
_Alerts_ indicate whether an app is behaving as expected. You can create alerts in Runtime Manager for applications deployed to CloudHub 2.0.
You can also create basic alerts in Anypoint Monitoring that focus on application metrics such as message count and CPU utilization. See the Anypoint Monitoring documentation for more guidance on creating basic alerts.
## Rate Limits on Alerts
Anypoint Platform enforces rate limits that determine how often an alert is triggered and prevent excessive emails from being sent. The rate limit is one alert notification email sent every 2.5 seconds per organization.
This limit is enforced by a combination of organization, environment, alert (name or ID), and application.
## Before You Begin
  * Ensure that your default environment (defined in your profile) has Read Application permissions.


## Create a Custom Alert
In Runtime Manager, bind the custom notification to an alert:
  1. From Anypoint Platform, select **Runtime Manager**.
  2. In the navigation menu, click **Alerts**.
  3. Click the blue plus icon (**+**) to create a new alert.
  4. In the **Create an Alert** page, configure your custom alert and click **Submit** : 

Name
    
Enter a meaningful name for the custom alert. 

Severity level
    
Select the severity level to apply to the alert:
     * **Critical** 

Source
    
Select **Applications** for the alert source. 

Application type
    
Select **CloudHub 2.0 and RTF Applications**. 

Applications
    
Select the application that contains the flow that you configured to trigger a custom alert. 

Condition
    
Select one of the following:
     * Deployment success: An app deploys and runs
     * Deployment failure: An app cannot deploy. Note that this condition is triggered only for failures and not when the app is stuck in a deployment loop. 

Subject
    
Enter the subject line to include in the notification email. 

Message
    
Enter the custom message to include in the notification. 

Recipients
    
Enter the email addresses for notification recipients.
You can use variables in the alert **Subject** and **Message** fields. For information about using variables in alerts, see Alert Variables.


When you trigger the alert, the specified recipients receive an email with the custom message you added to the app.
## See Also
  * Setting Up Basic Alerts in Anypoint Monitoring
Synchronous Versus Asynchronous Aggregations | MuleSoft Documentation
# Synchronous Versus Asynchronous Aggregations
An aggregation is complete based on a new element added to the list, as when a max size is specified, or because some timeout or time period is complete. This is important because the type of aggregation determines which chain of components to execute with the list of elements. There are two kinds of triggers for an aggregation completion: synchronous and asynchronous.
Each time counter associated with an aggregator starts counting from the moment the first message of a group arrives. Once the aggregation is complete, the counter resets and waits for the next element to arrive. For single-group aggregators (time-based and size-based aggregators scopes), there is only one time counter, but for the group-based aggregator, there is one counter per group.   
---  
## Synchronous Aggregations
For aggregations completed because a new element arrives (Sync), at least one of the following things occur:
  * If the aggregator scope is configured with an **Aggregation complete** route, the components inside that route execute with the payload being the list of aggregated elements.
  * If the aggregator scope has a referenced **Aggregator listener** , the flow to which that listener belongs executes with the payload being the list of aggregated elements.


## Asynchronous Aggregations
For aggregations completed because a time period ended or a timeout was reached (Async), the only thing that can happen is that if the aggregator scope has a referenced **Aggregator listener** and the listener accepts timed-out aggregations, the flow to which that listener belongs executes the list of aggregated elements as the payload.
## Placement of Processing Logic for Mule Apps Using Aggregators
When you create a Mule app that uses aggregators, place the processing logic as follows:
  * If the aggregation depends on time, add the processing logic in a different flow with an **Aggregation listener** as a source.
  * If the aggregation depends on a size being reached, add the processing logic in the **Aggregation complete** route.
  * If the aggregation depends on both time and size:
    * Add the main logic in a subflow with no source. The **Is aggregation complete** attribute shows how the aggregation ended.
    * Add a **Flow reference** component to the main logic flow in the **Aggregation complete** route. If the subflow is executed by this flow reference, then the **Is aggregation complete** attribute is `true`.
    * Add another flow with an **Aggregation listener** that listens to the aggregator and accepts timed-out groups. Follow the listener with a **Flow reference** component that calls the main logic subflow. In this case, the **Is aggregation complete** attribute is `false`.


## See Also
  * Aggregators Module Reference
  * MuleSoft Help Center
Reviewing Mule API Analytics Event Forwarding | MuleSoft Documentation
# Reviewing Mule API Analytics Event Forwarding
Sometimes you need to forward the Mule API Analytics events to a third-party system. An example of this could be integrating with ELK or other analytics system.
There are three ways to export events:
  * Use the API Analytics Report API to pull the data. One consideration with this method is that the API has limit on the number and frequency of events that can be reported. Additionally, events may have delays of up to 10 minutes from the time the event is generated to the moment it is available for query.
  * Forward Mule API Analytics events from the Gateway to configured HTTP endpoint. To configure this on CloudHub, configure the `anypoint.platform.analytics_base_uri` gateway property from the Settings tab of Runtime Manager.
Setting this property configures the base URL where the events are posted.


In the example shown above, the events are published to `http://<your-address-here>/v2/analytics/events` using the POST method and GZIP for compression.
The disadvantage of this approach is that events are not published to Anypoint Platform and neither Mule API Analytics nor API Manager display information about API calls.
  * Use Runtime Manager to Export Data to External Analytics Tools


## See Also
  * Reviewing Analytics Event API