Contact Us 1-800-596-4880

Annotation Reference

DevKit is compatible only with Studio 6 and Mule 3. To build Mule 4 connectors, see the Mule SDK documentation.

This document lists MuleSoft DevKit core Java Annotations.

Category Summary

Category Annotations

Newest Annotations

General

@Category @Configurable @Connector @Expr @ExpressionEnricher @ExpressionEvaluator @ExpressionLanguage @Filter @Icons @Ignore @Mime @Module @Paged @Processor @Source @Transformer @TransformerResolver

Argument Passing

@InboundHeaders @InvocationHeaders @Literal @OutboundHeaders @Payload @SessionHeaders

Connection Management

@Connect @ConnectionIdentifier @ConnectionManagement @ConnectionStrategy @Disconnect @InvalidateConnectionOn @ReconnectOn @ValidateConnection

DataSense

@MetaDataCategory @MetaDataKeyParam @MetaDataKeyRetriever @MetaDataOutputRetriever @MetaDataRetriever @MetaDataScope @NoMetaData @Query @QueryPart @QueryTranslator

Display

@FriendlyName @Password @Path @Placement @Summary @Text

Exception Management

@OnException @Handler @Handle

Lifecycle

@Dispose @Initialise @Start @Stop

Authentication

@HTTPBasicAuth

OAuth

@OAuth @OAuth2 @OAuthAccessToken @OAuthAccessTokenIdentifier @OAuthAccessTokenSecret @OAuthAuthorizationParameter @OAuthCallbackParameter @OAuthConsumerKey @OAuthConsumerSecret @OAuthInvalidateAccessTokenOn @OAuthPostAuthorization @OAuthProtected @OAuthScope

Parameters

@ConnectionKey @Default @Email @ExceptionPayload @MetaDataStaticKey @Optional @RefOnly

REST

@BinaryParam @RestCall @RestExceptionOn @RestHeaderParam @RestHttpClient @RestPostParam @RestQueryParam @RestTimeout @RestUriParam

@BinaryParam

Category: REST
Mule Version: 3.5 and newer

Specifies if a payload is a binary type.

@Category

Category: General
Mule Version: 3.5 and newer

Anypoint Studio and the doclet use the @Category annotation to organize message processors. You can use @Category annotation at class definition level (Connector or Module) to select in which category you want your extension to be listed:

@Connector(name = "ldap", schemaVersion = "3.6",
  friendlyName="LDAP", minMuleVersion="3.6",
  description="The LDAP connector connects to an
    LDAP server and performs LDAP operations")
@Category(name = "org.mule.tooling.category.core",
  description = "Components")
  public class LDAPConnector
    {
      ...
    }

Notes:

  • You can only add the connector to one of the existing Studio categories (this means you cannot define your own category)

  • The values for name and description attributes of @Category can only have these values:

    • Endpoints: org.mule.tooling.category.endpoints

    • Scopes: org.mule.tooling.category.scopes

    • Components: org.mule.tooling.category.core

    • Transformers: org.mule.tooling.category.transformers

    • Filters: org.mule.tooling.category.filters

    • Flow Control: org.mule.tooling.category.flowControl

    • Error Handling: org.mule.tooling.ui.modules.core.exceptions

    • Cloud Connectors (DEFAULT): org.mule.tooling.category.cloudconnector

    • Miscellaneous: org.mule.tooling.ui.modules.core.miscellaneous

    • Security: org.mule.tooling.category.security

You can use the following to specify the permitted categories:

import org.mule.api.annotations.Category;
@Category(name = "org.mule.tooling.category.endpoints", description = "Endpoints")
@Category(name = "org.mule.tooling.category.scopes", description = "Scopes")
@Category(name = "org.mule.tooling.category.core", description = "Components")
@Category(name = "org.mule.tooling.category.transformers", description = "Transformers")
@Category(name = "org.mule.tooling.category.filters", description = "Filters")
@Category(name = "org.mule.tooling.category.flowControl", description = "Flow Control")
@Category(name = "org.mule.tooling.ui.modules.core.exceptions", description = "Error Handling")
@Category(name = "org.mule.tooling.category.cloudconnector", description = "Cloud Connectors")
@Category(name = "org.mule.tooling.ui.modules.core.miscellaneous", description = "Miscellaneous")
@Category(name = "org.mule.tooling.category.security", description = "Security")

@Configurable

Category: General
Mule Version: 3.5 and newer

Mule 3.7 Note: @Configurable is no longer supported for use with @Connector. This change deprecates @Configurable fields that are defined in @Connector or @Module and encourages you move those fields to @Config.

Marks a field inside a @Connector as being configurable. The @Configurable annotation signals the generator to create a property configurable for each instance of your connector through XML syntax or a connector configuration dialog box. In addition to the @Configurable annotation, you need at least one public get and set function.

@Configurable
 private String url;

 public String getUrl() {
      return url;
 }

 public void setUrl(String url) {
      this.url = url;
 }

@Configuration

Category: Connection Management
Mule Version: 3.6 and newer

Indicates a class without a connection management strategy; that is, without a pooling profile or the ability to reconnect. Provides a generic strategy for global elements without any connection management.

Using this annotation, a connector or module can configure different parameters at a global element level using @Configurable when there is no need for authentication and/or connection management.

@Configuration
public class GenericStrategy{

    @Configurable
    private String myConfigurable
    ...
}

Notes:

  • The @Configuration strategy does not have any connection management tabs for a pooling profile or reconnection, and a connection group is not created by default.

  • All configurables go into the General group by default.

  • Define your own group and/or use connectivity testing.

@Connect

Category: Connection Management
Mule Version: 3.5 and newer

Marks a method inside a @Connector scope as responsible for creating a connection.

This method can have several parameters and can contain annotations such as @ConnectionKey or @Password. The @Connect annotation guarantees that the method is called before calling any message processor.

This method designates which method inside an @Connector class is responsible for creating a connection to the target. The @Connect method is called automatically by Mule when the connector starts up, or if the connection to the API has been lost and must be reestablished. When this method finishes, if authentication is successful, the connector instance is ready to make requests to the API.

A method annotated with @Connect must:

  • Be public

  • Throw org.mule.api.ConnectionException (and no other exceptions)

  • Have a void return type

  • If automatic connection management for username and password authentication is used, have exactly one method annotated @Connect; otherwise compilation fails

  • The parameters cannot be of primitive type such as int, bool, short, etc.

Example 1:

@Connect
public void connect(@ConnectionKey String username, String password) throws   ConnectionException { ... }

Example 2:

@Connect
public void connect(@ConnectionKey String username, String password)
throws ConnectionException
{
   ConnectorConfig config = new ConnectorConfig();
   config.setUsername(username);
   config.setPassword(password);
   try
   {
      connection = com.mycompany.ws.Connector.newConnection(config);
   }
   catch (com.mycompany.ws.ConnectionException e)
   {
      throw new org.mule.api.ConnectionException(ConnectionExceptionCode.UNKNOWN, null, e.getMessage(), e);
   }
}

The parameters required by this method are the credentials needed for authentication, in this case username and password. Since this method is annotated with @Connect , Anypoint DevKit makes these parameters available both in the configuration element for this connector (as occurs with @Configurable fields), as well as in the message processor whenever it is dragged into a flow. Specified credentials override those that are set in the configuration element.

@ConnectionIdentifier

Category: Connection Management
Mule Version: 3.5 and newer

Marks a method inside a @Connector as responsible for identifying the connection.

A method annotated with @ConnectionIdentifier must:

  • Be public

  • Not be static

  • Not take arguments

  • Return java.lang.String

A @Connector class that uses connection management for basic authentication must have exactly one method annotated @ConnectionIdentifier; otherwise compilation fails.

The connector’s connection manager calls the method annotated with @ConnectionIdentifier for debugging purposes.

This annotation must be used on a non-static method without arguments and must return a String that contains the connection identifier representation.

The following example code returns the connection SessionId as an identifier (if available). The SessionHeader object in this case contains header information about the current connection to the API, including the session ID.

@ConnectionIdentifier
   public String connectionId() {
    if (connection != null){
     return connection.getSessionHeader().getSessionId();
    } else {
     return null;
    }
   }

@ConnectionKey

Category: Parameters
Mule Version: 3.5 and newer

Marks a parameter inside the connect method as part of the key for the connector lookup. This only can be used as part of the @Connect method.

@Connect(strategy=ConnectStrategy.SINGLE_INSTANCE)
public void connect(@ConnectionKey String username, @Password String password)
throws ConnectionException { ... }

@ConnectionManagement

Category: Connection Management
Mule Version: 3.6 and newer

Indicates a class that defines a connection strategy for basic username and password authentication.

Examples

@ConnectionManagement(friendlyName = "Connection Management type Strategy",
     configElementName="config-type")
public class ConnectionManagementStrategy implements StrategyCommonInterface {

    MyDummyService service;

    public ConnectionManagementStrategy(){
        service = new MyDummyService();
    }

    @TestConnectivity
    @Connect
    public void connect(@ConnectionKey String username, @Password String password)
        throws ConnectionException {
        Boolean result = service.connectService(username, password);
        if(result == false){
            throw new ConnectionException(null, "Invalid Username or password",
              "Please review Username or Password values");
        }
    }

The following example is for connectors with connection management and connectivity testing.

@ConnectionManagement
public class BasicAuthConnectionStrategy{
  @Connect
  @TestConnectivity //(active=true) default
  //Connection management methods
}

The following example is for connectors with connection management and no connectivity testing:

@ConnectionManagement
public class BasicAuthConnectionStrategy{
  @Connect
  @TestConnectivity //(active=true) default
  //Connection management methods
}

Indicates a connector strategy class. See @ConnectionStrategy for more examples.

@ConnectionStrategy

Category: Authentication
Mule Version: 3.6 and newer

Indicates a connection strategy class for a connection. The class is defined by the new @ConnectionManagement annotation, the new @Configuration annotation, the new @HTTPBasicAuth annotation or the existing @OAuth2 annotation. In previous Mule versions, a connection strategy could only be added by inheritance, which made coding more difficult and caused extensibility problems when new DevKit features appeared. The new connection strategy features solve these issues.

Example with @OAuth2

@Connector
public class MyConnector {

    @ConnectionStrategy
    private OAuth2Strategy connection;

    @Processor
    public void doSomething(){
        connection.getClient().doSomething();
    }
}
@OAuth2(friendlyName="oauth2", configElementName="oauth2", ...)
public class OAuth2Strategy implements BaseConnectionStrategy {

    @Override
    public Client getClient(){
        return this.client;
    }

    /**
     * Your application's client identifier (consumer key in Remote Access Detail).
     */
    @OAuthConsumerKey
    private String consumerKey;

    /**
     * Your application's client secret (consumer secret in Remote Access Detail).
     */
    @OAuthConsumerSecret
    private String consumerSecret;

    @OAuthAccessToken
    private String accessToken;

    @OAuthPostAuthorization
    public void postAuthorize() {...}

    ...
}

Example with @ConnectionManagement

@Connector
public class MyConnector {

    @ConnectionStrategy
    private ConnectionManagementStrategy connection;

    @Processor
    public void doSomething(){
        connection.getClient().doSomething();
    }
}
@ConnectionManagement(friendlyName="ConnectionManagement", configElementName="connection-management")
public class ConnectionManagementStrategy implements BaseConnectionStrategy {

    @Override
    public Client getClient(){
        return this.client;
    }

    @Connect
    public void connect(...){
        this.client = new Client(...);
    }

    @Disconnect
    public void disconnect() {...}

    @ValidateConnection
    public boolean isConnected() {...}

    @ConnectorIdentifier
    public String getIdentifier() {...}

}

Multiple Connection Strategies

Each of the connection strategies above extends the BaseConnectionStrategy interface.

public interface BaseConnectionStrategy{
    private Client client;

    Client getClient();
}

The @ConnectorStrategy field type is the common interface.

@Connector
public class MyConnector {


    @ConnectionStrategy
    private BaseConnectionStrategy connection;

    @Processor
    public void doSomething(){
        connection.getClient().doSomething();
    }
    ...
}

Now you can choose at design time which connection type is your Connector going to use.

Screen+Shot+2014-12-30+at+1.06.11+PM

here is an example of a multiple strategies connector in github.

Compatibility

@Connect parameters cannot be overridden from the @Processor call.

For this case, the @ConnectionManagement component in the DevKit lets you add the @Connect parameters as optional parameters for the @Processor blocks by annotating the @ConnetionStrategy with @OverrideAtProcessors. This way you can override an attribute directly from the @Processor call.

The @OverrideAtProcessor annotation is deprecated in Mule 3.6 and newer and exists just for backward compatibility.

Execution Time: Connector Pooling

The simplest way is to maintain current DevKit connector’s architecture and continue having a pool of connectors per each configuration. Use the following example:

<my-connector:connection-management name="connection-management" username="mule" password="mulemanishere"/>
<my-connector:oauth name="oauth2" consumerkey="..." consumerSecret="..." />

<flow>
  <my-connector:do-something config-ref="basic"/>
</flow>

Behind the two elements :basic-auth and :oauth are two different pools for MyConnector classes configured to be injected with BasicStrategy and OAuthStrategy instances respectively. This could be accomplished by using generics on MyConnector<Strategy>. The flowchart for the execution on this alternative is presented below.

  1. Spring Bean injection from :basic-auth element to MyConnectorPool<BasicStrategy> bean object.

  2. Spring Bean injection from :do-something to DoSomethingMessageProcessor (with a reference to the MyConnectorPool).

  3. Later on the DoSomethingMessageProcessor.doProcess() call. A MyConnector instance is taken from the MyConnectorPool<ConnectionManagement> containing a ConnectionManagement connection already connected. If there’s none, a new one is created.

@Connector

Category: General
Mule Version: 3.5 and newer

Defines a class that exports its functionality as a Mule connector. When you first create an Anypoint Connector Project in Studio, Maven generates a scaffold @Connector class for you. Creating a connector assumes that you enhance this class to enable your code to access a target resource.

This class-level annotation identifies a Java class as a Cloud Connector.

@Connector restrictions:

  • Do not apply to an interface

  • Do not apply to final classes

  • Apply only to a public class

  • Cannot have a typed parameter (no generics)

  • A class with @Connector must contain exactly one method annotated with @Connect

  • A class with @Connector must contain exactly one method annotated with @Disconnect

@Connector(name = "hello", schemaVersion = "1.0", friendlyName = "Hello", minMuleVersion = "3.6")
public class HelloConnector {
  ...
}

@Connector parameters:

Annotation Type Element Description Required? Default Value

name

The name of the connector. This value must be a simple string, with no spaces.

schemaVersion

The version of the schema as generated by the DevKit.

1.0-SNAPSHOT

friendlyName

This is the human-readable name of the connector. It can contain spaces. Mule uses it only to label the connector in the Studio Palette.

description

A longer string describing the connector and its operation. Mule Studio displays the description as a tool tip.

namespace

The namespace of the connector.

http://www.mulesoft.org/schema/mule/name

schemaLocation

The location of the schema file that writes to the spring.schemas file.

http://www.mulesoft.org/schema/mule/name/schemaVersion/mule-name.xsd

and

http://www.mulesoft.org/schema/mule/name/current/mule-name.xsd

minMuleVersion

The minimum Mule version with which the connector can be used. Mule checks the version at runtime and throws an error if versions are incompatible.

Latest stable Mule runtime release

@Default

Category: Parameters
Mule Version: 3.5 and newer

Specifies a default value to a @Configurable field or a @Processor or @Source parameter.

@Configurable
@Default("mule")
private String type;

Or:

@Processor
public abstract String listAnimals(@Default("mule") String type) throws IOException;

@Disconnect

Category: Connection Management
Mule Version: 3.5 and newer

Marks a method inside a @Connector class that is responsible for disposing the connection. Called by the connector’s connection manager when the connector is shut down or a connection terminates.

A method annotated with @Disconnect must:

  • Be public

  • Take no input parameters

  • Have a void return type

If connection management (username and password) is used for authentication, the @Connector class must have exactly one annotated @Disconnect method; otherwise compilation fails.

In 3.6 and newer, the @Disconnect method only supports RuntimeException, any other exception causes a failure in a connector’s compilation:

@Connector(...)
public myConnector(){
    ...
    @Disconnect
    public void disconnect() throws RuntimeException{
        ...
    }
    ...
}

This method is invoked as part of the maintenance of the Connection Pool. The pool is configured with a maximum idle time value.

When a connection lies in the pool without use for more than the configured time, then the method annotated with @Disconnect is invoked and subsequently the @Connect method. Also, when the @InvalidateConnectionOn annotation is used on a method to catch Exceptions, then the @Disconnect method likewise is invoked with the subsequent reconnect.

@Disconnect
public void disconnect() {
   if (connection != null)
   {
      try
         {
         connection.logout();
         }
      catch (ConnectionException e)
         {
         e.printStackTrace();
         }
      finally
         {
         connection = null;
         }
   }
}

@Dispose

Category: LifeCycle
Mule Version: 3.5 and newer

Mark a method to be disposed during a method’s org.mule.lifecycle.Disposable phase.

@Dispose
public void mydispose()  {
    if ( this.sessionId != null ) {
        serviceProvider.dispose(sessionId);
    }
}

Note: dispose is a reserved word that cannot be used as the method’s name.

@Email

Category: Parameters
Mule Version: 3.5 and newer

Specifies a default email pattern.

@ExceptionPayload

Category: Parameters
Mule Version: 3.5 and newer

Specifies the payload for an exception.

@Processor
public Object returnExceptionPayload(@ExceptionPayload Object payload) {
    return payload;
}

@Expr

Category: General
Mule Version: 3.5 and newer

Binds a parameter in a @Processor method to an expression.

Binding a parameter to an expression works similar to @Payload in the sense that the user of the module won’t be able to alter the expression or the value of the parameter from the XML. A binding is hardcoded and the user cannot change it.

The following example maps the myFlowVarXXX parameter to the result of the expression flowVars['xxx']:

@Processor
public String myProcessor(@Expr("flowVars['xxx']")
   String myFlowVarXXX) {
     ...
   }

@ExpressionEnricher

Category: General
Mule Version: 3.5 and newer

Marks a method inside an @ExpressionLanguage as the responsible for enriching mule messages based on an expression.

The following example shows how to use the @ExpressionEnricher annotation to set the payload (which is expected to be a map) in the enrich() method using the “map-payload” expression language:

@ExpressionLanguage(name = "map-payload")
public class MapPayloadExpressionLanguage {
    @ExpressionEnricher
    public void enrich() {
        ...
    }
}

@ExpressionEvaluator

Category: General
Mule Version: 3.5 and newer

Marks a method inside an @ExpressionLanguage annotation as being responsible for evaluating expressions.

@ExpressionLanguage(name = "expr")
public class ExprExpressionLanguage {
    @ExpressionEvaluator
    public Object evaluate() {
        ...
    }
}

@ExpressionLanguage

Category: General
Mule Version: 3.5 and newer

Defines a class that exports its functionality as a Mule Expression Language.

@ExpressionLanguage restrictions on which types are valid:

  • Cannot be an interface

  • Must be public

  • Cannot have a typed parameter (no generics)

@ExpressionLanguage(name = "expr")
public class ExprExpressionLanguage {
    @ExpressionEvaluator
    public Object evaluate() {
        ...
    }
}

@Filter

Category: General
Mule Version: 3.5 and newer

Marks a method inside a @Connector as a callable from within a Mule flow that filters a message. Each parameter on this method is featured as an attribute on the Mule XML invocation.

By adding this annotation to a method inside @Connector, a filter is created which may be used from within a Mule flow to filter messages based on implementation of this method.

@Filter
    public boolean shouldFilter() throws Exception {
        ...
   }

@FriendlyName

Category: Display
Mule Version: 3.5 and newer

Gives a short name to an annotated element. If a value is not specified, the name is inferred from the annotated element’s name.

Use this annotation to instance variables and method parameters to provide a way to override the default inferred nickname for a @Configurable variable or a @Processor, @Source, @Transformer method parameter. Provide a parameter if annotated with this.

Example:

@FriendlyName("Consumer Key")
private String consumerKey;
// Alternate: Declare in a method's arguments:
  public abstract String getByTypeAndName(
  @RestQueryParam("name") @FriendlyName("name") String uname)
      throws IOException;

Another example illustrates how the friendlyName appears in the Anypoint Studio connector list:

@Connector(name="barn", schemaVersion="1.0", friendlyName="Barn", minMuleVersion="3.6")
public class BarnConnector
{
    ...
}

The example Barn connector appears in Anypoint Studio’s list of connectors as:

friendlyName-screenshot

@Handle

Category: Exception Management
Mule Version: 3.6 and newer

Indicates a method for handling and describing exceptions. There is one @Handle per @Handler class.

Use with @Handler:

@Handler
public class GenericHandler
{
   @Inject                    //optional
   FooConnector fooConnector; //optional

   @Handle
   public void customHandler (Exception e) throws Exception
   {
      // Analyze the stack within "e"...
      throw new MyDescriptiveException(e);
   }

   public void setFooConnector(Foo foo)
   {
      this.fooConnector=foo;
   }
}

The @Handle method can return two results:

  • RECONNECT - Retry the operation if the @Processor has @ReconnectOn, and the @Handle throws an exception of that kind.

  • FAIL - Fail the operation by throwing an exception that does not belongs to the @ReconnectOn, or the processors don’t support reconnection.

Note: If a method annotated with @Handle does not throw an exception during its execution, the original exception are re-thrown.

@Handler

Category: Exception Management
Mule Version: 3.6 and newer

Indicates a class that handles an exception. Use with @OnException and @Handle.

@OnException (handler=GenericHandler.class)
@Connector (name = "foo", friendlyName = "Foo")
{
   @Processor
   public void someOp (...)
   {
      ...
   }
   @OnException (handler=CustomHandler.class)
   @Processor
   public void anotherOp ()
   {
      ...
   }
}

The constraints for the @Handler class are:

  • Must be public

  • Must be annotated with @Handler

  • Must have an empty constructor

  • Might have an @Inject parameter with the same type of the connector

  • Must have an method annotated with @Handle

    • The annotated method with @Handle must receive an Exception as parameter

    • The annotated method must return void

    • The annotated method must be declared with throws Exception

See also: @OnException @Handle

@HTTPBasicAuth

Category: Authentication
Mule Version: 3.6 and newer

Indicates an implementation of RFC-2617 "HTTP Authentication: Basic and Digest Access Authentication".

@HTTPBasicAuth(headerName = "Authorization", prefix="Basic ", friendlyName="Http Basic Auth")
public class HTTPBasicAuthStrategy implements BaseConnectionStrategy {
   ...

   @Configurable
   @BasicAuthUsername
   private String username;

   @Configurable
   @BasicAuthPassword
   private String password;
}

Usage:

  • Username and password are combined into a string "username:password".

  • The resulting string is then encoded using the RFC-2045 MIME variant of Base64.

  • Default value for the header param name: "Authorization", and default value for prefix param: "Basic "

  • The value of the header param and the prefix param can be changed by user.

  • Support for empty passwords, example: Stripe.

  • @BasicAuthUsername is only valid under @HTTPBasicAuth.

  • @BasicAuthPassword is only valid if @BasicAuthUsername exists and vice versa.

  • This only works for @RestCall connectors.

The JIRAs API expects an Authorization header with content "Basic " followed by the encoded string. For example, the string "fred:fred" encodes to "ZnJlZDpmcmVk" in base64, so make the request as follows.

curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" "http://<url>"

@Icons

Category: General
Mule Version: 3.5 and newer

Custom palette and flow editor icons.

Use this annotation on the connector class to override the default location of one or more of the required icons. The path needs to be relative to the /src/main/java directory.

@Icons(connectorLarge="barn-icon-large.png", connectorSmall="barn-icon-small.png")
@Connector(name="barn", schemaVersion="1.0", friendlyName="Barn", minMuleVersion="3.6")
public class BarnConnector
{
   ...
}

@Ignore

Category: General
Mule Version: 3.5 and newer

Ignores a field inside a complex object.

public class MyComplexType
{
    private String color;

    @Ignore
    private String description;
}

@Processor
public void receiveAComplexType(MyComplexType myComplexType) {
    ...
}

@InboundHeaders

Category: Argument Passing
Mule Version: 3.5 and newer

Passes inbound headers.

@Processor
public String getInboundHeaders(@InboundHeaders("myHeader") String myHeader) { ... }

@Initialise

Category: LifeCycle
Mule Version: 3.5 and newer

Mark a method to be initialized during a method’s org.mule.lifecycle.Initialisable phase.

@Initialise
public void initialize() {
    if ( this.sessionId != null ) {
        serviceProvider.initialise(sessionId);
    }
}

Note: initialise is a reserved word that cannot be used as the method’s name.

See also: @Dispose @Start @Stop

@InvalidateConnectionOn

Category: Connection Management
Mule version: 3.5 and newer

Used on a method to catch Exceptions - deprecated use @ReconnectOn instead.

@Processor
@InvalidateConnectionOn(exception=AnimalException.class)
public Animal getAnimal (String id ) {
    ...
}

@InvocationHeaders

Category: Argument Passing
Mule Version: 3.5 and newer

Passes invocation headers. This can be a single header, a comma-separated list of header names, an asterisk '*' to denote all headers, or a comma-separated list of wildcard expressions. By default, if a named header is not present, an exception is thrown. However, if the header name is defined with the '?' post fix, it is marked as optional.

@Processor
public String getInvocationHeaders(@InvocationHeaders("myHeader")
String myHeader) {
    ...
}

@Literal

Category: Parameters
Mule Version: 3.6 and newer

Specifies Mule Expression Language (MEL) as a method parameter without the DevKit resolving the expression. You can use any MEL code with this annotation.

Problem

Given the following Processor method:

public void enrich(Object source, String targetExpression)

Given the following Mule XML:

<mymodule:enrich targetExpression="#[variable:myexpr]" ... />

The enrich method receives the result of evaluating the following expression:

#[variable:myexpr]

And not this String:

[variable:myexpr]

This is because DevKit’s generated code tries to automatically resolve the expression.

Solution

The @Literal annotation flags a method parameter so that its value coming from Mule XML does not get resolved if it’s a Mule expression:

public void enrich(Object source, @Literal String targetExpression)

In this case, expression evaluation does not apply to the value of the targetExpression parameter.

Also, this annotation can be used for Lists of Strings, where each element is passed without evaluating the expression. For example:

public void enrich(Object source, @Literal List<String> targetExpressions)

@MetaDataCategory

Category: DataSense
Mule Version: 3.5 and newer

Describes a grouping DataSense concrete class, which returns the types and descriptions of any of those types.

Mule 3.6 and newer supports @MetaDataCategory both in @Module and @Connector annotations.

Use to annotate a class that groups methods used for providing metadata about a connector using DataSense.

@MetaDataCategory
public class MyCategory {
    ...
}

@MetaDataKeyParam

Category: DataSense
Mule Version: 3.5 and newer

Marks a parameter inside @Processor as the key for a metadata lookup.

public Object create(@MetaDataKeyParam String entityType, @Default("#[payload]") Object entityData) {
    ...
}

@MetaDataKeyRetriever

Category: DataSense
Mule Version: 3.5 and newer

Use to annotate a method that is responsible to return a service’s entities names.

Given the functionality of this annotation, the return type of this Java method must be a List<MetaDataKey>.

The entities returned from this method are from a query after a detailed description obtained using @MetaDataRetriever.

Use this annotation inside an @Connector context or inside an @MetaDataCategory.

@MetaDataKeyRetriever
   public List<MetaDataKey> getMetaDataKeys() throws Exception {
       ...
   }

@MetaDataOutputRetriever

Category: DataSense
Mule Version: 3.5 and newer

Marks a method as a describer for @MetaData for output scenarios, for a given @MetaDataKey.

@MetaDataOutputRetriever
public MetaData getMetaDataOutputRestImplCategory(MetaDataKey key) throws Exception {
    checkProperConnectorInjection();
    return new DefaultMetaData(resolveOutputMetaDataModel(key));
    ...
}

@MetaDataRetriever

Category: DataSense
Mule Version: 3.5 and newer

The method annotated with @MetaDataRetriever describes the metadata for the received metadata key parameter.

Uses the list of metadata keys retrieved by @MetadataKeyRetriever to retrieve the entity composition of each entity Type.

@MetaDataRetriever
public MetaData getMetadata(MetaDataKey key) {
    ...
}

@MetaDataScope

Category: DataSense
Mule Version: 3.5 and newer

@MetaDataScope(DefaultCategory.class)
@Connector(name = "my-connector", minMuleVersion = "3.6")
public class MyConnector {
    ...
}

@MetaDataStaticKey

Category: Parameters
Mule Version: 3.5 and newer

Defines the specific MetaData type of the annotated value. When applied to a @Processor it affects (by default) just the Output, otherwise it affects the field parameter.

@Processor
@MetaDataStaticKey(type = "CLIENT")
public Map<String, Object> getClient(String id) {
    return createClientObject();
}

@Mime

Category: General
Mule Version: 3.5 and newer

Generates the appropriate message header.

@Processor
@Mime("application/json")
public String search(String keyword) {
    ...
}

@Module

Category: General
Mule Version: 3.5 and newer

Defines a class that exports its functionality as a Mule module.

The class level annotation @Module indicates that a Java class needs to be processed by the DevKit Annotation Processing Tool and considered as a Mule Module.

@Module cannot be applied to:

  • Interfaces

  • Final classes

  • Parameterized classes

  • Non-public classes

@Module(name="animal-search", schemaVersion="3.6.1")
public class AnimalSearchModule {
    ...
}

@NoMetaData

Category: DataSense
Mule Version: 3.5 and newer

Marks a @Processor to avoid discovering metadata with @MetaDataRetriever and @MetaDataKeyRetriever mechanism.

@OAuth

Category: OAuth
Mule Version: 3.5 and newer

Annotates connectors that uses the OAuth 1.0a protocol for authentication.

@Connector(name = "myconnector", friendlyName = "MyConnector")
@OAuth(requestTokenUrl = "https://example.com/uas/oauth/requestToken",
accessTokenUrl = "https://example.com/uas/oauth/accessToken",
authorizationUrl = "https://example.com/uas/oauth/authorize")
public class MyConnector {
    ...
}

@OAuth2

Category: OAuth
Mule Version: 3.5 and newer

Annotates connectors that uses the OAuth 2 protocol for authentication.

@Connector(name = "oauth2connector")
@OAuth2(authorizationUrl = "http://someUrl", accessTokenUrl = "http://someOtherUrl")
public class MyConnector {
    ...
}

@OAuthAccessToken

Category: OAuth
Mule Version: 3.3 and newer

Holds an access token. When an @Processor method is invoked, an OAuth access token is set in case the Resource Owner already authorized the Consumer; otherwise the method isn’t invoked and the Resource Owner is redirected to the OAuth or OAuth2 authorization URL depending on the class level annotation used.

Note: This annotation is only supported for class fields.

A class annotated with @OAuth or @OAuth2 needs to have exactly one field annotated with @OAuthAccessToken.

The field must be of type String.

@OAuthAccessToken private String accessToken;

@OAuthAccessTokenIdentifier

Category: OAuth
Mule Version: 3.5 and newer

Marks a method as responsible for identifying the user of an access token. The method is called by a connector’s access token manager. This identification is used as a key to store access tokens.

@OAuthAccessTokenIdentifier
public String getUserId() {
    return api.getUserId(myAccessToken);
}

@OAuthAccessTokenSecret

Category: OAuth
Mule Version: 3.5 and newer

Holds an access token secret.

@OAuthAccessTokenSecret private String accessTokenSecret;

@OAuthAuthorizationParameter

Category: OAuth
Mule Version: 3.5 and newer

Appends an authorization parameter to authorize a URL.

@OAuthAuthorizationParameter(name = "xxx", type = xxx, description = "xxx")

@OAuthCallbackParameter

Category: OAuth
Mule Version: 3.5 and newer

Identifies the module attribute that represent each parameter on the service OAuth response.

@OAuthCallbackParameter(expression = "#[json:instance_url]")
private String instanceId;

@OAuthConsumerKey

Category: OAuth
Mule Version: 3.5 and newer

Holds an OAuth consumer key. This field must contain the OAuth Consumer Key as provided by the Service Provider and described in the OAuth specification.

@Configurable @OAuthConsumerKey private String consumerKey;

@OAuthConsumerSecret

Category: OAuth
Mule Version: 3.5 and newer

Holds an OAuth consumer secret. This field must contain the OAuth Consumer Key as provided by the Service Provider and described in the OAuth specification.

@Configurable @OAuthConsumerSecret private String consumerSecret;

@OAuthInvalidateAccessTokenOn

Category: OAuth
Mule Version: 3.5 and newer

Marks a method which automatically refreshes the tokens.

Note: This annotation is deprecated. Use @ReconnectOn instead.

@Processor
@OAuthInvalidateAccessTokenOn(exception = RuntimeException.class)
public void processor() {
    ...
}

@OAuthPostAuthorization

Category: OAuth
Mule Version: 3.5 and newer

Marks a method inside OAuth as the responsible for setting up the connector after OAuth completes.

@OAuthPostAuthorization
public void postAuthorize() throws ConnectionException, MalformedURLException, AsyncApiException {
    ...
}

@OAuthProtected

Category: OAuth
Mule Version: 3.5 and newer

Marks a method inside a Connector as requiring an OAuth access token. Such a method fails to execute while the connector is not authorized. Therefore, forcing the OAuth to happen first.

@OAuthProtected
@Processor
public void logInfo() {
   logger.info(String.format("OAuthAccessToken=%s", getAccessToken()));
   logger.info(String.format("OAuthAccessTokenSecret=%s", getAccessTokenSecret()));
}

@OAuthScope

Category: OAuth
Mule Version: 3.5 and newer

Indicates that access to the Protected Resources must be restricted in scope. A field annotated with @OAuthScope must be present and contain a String indicating the desired scope.

@Configurable
@OAuthScope
@Optional
@Default("")
private String scope;

@OnException

Category: Exception Handling
Mule Version: 3.6 and newer

There are cases where, for unexpected scenarios, a connector can improve its user experience by centralizing exception handling in one or more methods.

Those cases arise when an exception thrown by the external API contains information that causes:

  • RECONNECT - Retry an operation

  • FAIL - Fail an operation

Prior to Mule version 3.6, DevKit provided only a mechanism for retrying the current operation, when a concrete and expected exception was raised using @InvalidateConnectionOn or @ReconnectOn. This required adding custom try {} catch (){} code for every @Processor and analyzing the stack.

In Mule version 3.6 and newer, the @OnException mechanism reduces a connector’s code, as well as improves the granularity of the code so that you can define a concrete handler for different processors. @OnException identifies a handler. Use @Handler to designate an exception handling class, and use @Handle to identify the exception handling method.

Example:

@OnException (handler=GenericHandler.class)
@Connector ( name = "foo", friendlyName = "Foo" )
{
   @Processor
   public void someOp (...)
   {
      ...
   }
   @OnException (handler=CustomHandler.class)
   @Processor
   public void anotherOp ()
   {
      ...
   }
}

See also: @Handle @Handler

@Optional

Category: Parameters
Mule Version: 3.5 and newer

Marks a @Configurable field or a @Processor or @Source parameters as optional.

@Configurable
@Optional
String path;

@OutboundHeaders

Category: Argument Passing
Mule Version: 3.5 and newer

Used to pass outbound headers.

@Processor
public void outboundHeaders(@OutboundHeaders
Map<String, Object> outboundHeaders) {
    ...
}

@Paged

Category: General
Mule Version: 3.5 and newer

Marks a method inside a @Connector as an operation that returns a paged result set. Methods annotated with this interface must also be annotated with @Processor and must return an instance of @ProviderAwarePagingDelegate.

@Processor
@Paged
public ProviderAwarePagingDelegate paginationTestOperation (String ble, PagingConfiguration pagingConfiguration) throws WrongParameterConfiguredException {
    ...
}

@Password

Category: Display
Mule Version: 3.5 and newer

Identifies a field or method parameter as being a password, or more generally as a variable which contains data that cannot be displayed as plain text.

@Connect
public void connect(@ConnectionKey String username,
  @Password String password)
        throws ConnectionException {
     ...
}

The following shows how the password appears in the Global Element Properties:

password screenshot

@Path

Category: Display
Mule Version: 3.5 and newer

Identifies a field or method parameter as being a path to a file. This displays a window at Studio to choose a file from the filesystem.

@Configurable
@Path
String path;

@Payload

Category: Argument Passing
Mule Version: 3.5 and newer

Marks arguments to receive the payload.

@Processor
public String setPayload(@Payload String payload) {
    ...
}

@Placement

Category: Display
Mule Version: 3.5 and newer

Defines the placement of a configurable attribute in the Anypoint Studio configuration.

Use this annotation to instance variables and method parameters. It accepts the following parameters:

  • order — The relative order of the annotated element within its group. If the value provided is duplicated then the order of these elements is arbitrarily defined. Value is relative; an element with order 10 has higher precedence than an element with value 25.

  • group — A logical way to display one or more variables together. If you do not specify a group, then Mule assumes a default group. To place multiple elements in the same group, assign the same values to them for this attribute.

  • tab — A logical way to group annotated elements together. This attribute specifies the name of the tab in which to display the annotated element. If no tab is specified, then Mule assumes a default tab. To display multiple parameters in the same the tab, assign the same values to them for this attribute.

@Configurable
@Placement(group = "Basic Settings", order = 1)
private String consumerKey;

The following code creates the General > Basic Settings for Consumer Key and Consumer Secret settings:

@Configurable
@Placement(group = "Basic Settings", order = 1)
@FriendlyName("Consumer Key")
private String consumerKey;

@Configurable
@Placement(group = "Basic Settings", order = 3)
@FriendlyName("Consumer Secret")
@Summary("consumer secret for authentication")
private String consumerSecret;

The generated screen is:

placement 1 screenshot

This code creates the Advanced Settings > Application Name setting under the General Information section:

@Configurable
@Placement(tab="Advanced Settings", group = "General Information", order = 2)
@Summary("the application name")
@FriendlyName("Application Name")
private String applicationName;

The generated screen is:

placement 2 screenshot

@Processor

Category: General
Mule Version: 3.5 and newer

Marks a method as an operation in a connector. A @Processor method generates a general purpose message processor. The parameters for this annotation are optional. The friendlyName lets you specify the display name for the Operation.

@Processor(friendlyName="OperationName", name="SchemaName")
 public String putInBarn(String animal) {
     return animal + " has been placed in the barn";
 }

@Query

Category: DataSense
Mule Version: 3.5 and newer

Supports easy query building by using DataSense Query Language (DSQL). Define @Query within an @Connector scope.

@Processor
public void setQuery(@Query DsglQuery query) {
    ...
}

@QueryPart

Category: DataSense
Mule Version: 3.5 and newer

Used in advanced @Query scenarios.

@QueryTranslator

Category: DataSense
Mule Version: 3.5 and newer

Translates a DSQL query into a native one.

@QueryTranslator
public String toNativeQuery(DsqlQuery query){
    SimpleSyntaxVisitor visitor = new SimpleSyntaxVisitor();
    query.accept(visitor);
    return visitor.dsqlQuery();
}

@ReconnectOn

Category: Connection Management
Mule Version: 3.5 and newer

This annotation is used for exception handling related to connections. It can be used at a class level (annotated with the @Connector annotation) or at a method level (annotated with @Processor annotation) . If the Connector or Processor throws an exception of this class, @ReconnectOn automatically invalidates the connection. @ReconnectOn receives a list containing the classes of the exceptions to be caught (see below for an example). When an exception occurs, `@ReconnectOn’s behavior is based on the configured reconnection strategy.

Used to invalidate connections. You can attach this annotation to any method annotated with @Processor. If the Processor or Source throws an exception that matches any of the exceptions specified in the @ReconnectOn annotation, the connection is invalidated.

@Processor
@ReconnectOn(exceptions = {InvalidSessionFault.class, PasswordChangedException.class})
public void myOperation(@Optional String source,
                        @Optional Object destination) throws InvalidSessionFault, PasswordChangedException, InvalidParameterException
{
    /**
    * CODE FOR MY OPERATION
    */
}

@RefOnly

Category: Parameters
Mule Version: 3.5 and newer

Marks a @Configurable field or a @Processor parameter as being passed by reference only.

@RequiresEntitlement

Checks to see if a @Module or @Processor requires an Enterprise license with a particular entitlement. Works at connector level. Enterprise only.

@RequiresEntitlement(name="peoplesoft")
@Connector
public class SuperConnector(){
 .....
}

@RequiresEnterpriseLicense

Checks to see if a @Module or @Processor requires an Enterprise license. The license can be an evaluation license or not. Works at connector level. Enterprise only.

@RequiresEnterpriseLicense
@Connector
public class SuperConnector(){
 .....
}

@RestCall

Category: REST
Mule Version: 3.5 and newer

Used with the @Processor annotation. Indicates that upon invocation, the processor makes a RESTful request.

DevKit provides a set of annotations to simplify working with RESTful APIs. These annotations handle all necessary operations, generating each REST call, and incorporating each REST call parameter.

Required arguments:

  • uri: URI of the REST resource to query

  • method: HTTP method to use

The generated code creates the URI based on the arguments passed to the @RestCall annotation, and makes a request using the verb specified by the method parameter of @RestCall.

@Processor
@RestCall(uri = "{url}/list", method = org.mule.api.annotations.rest.HttpMethod.GET)
public abstract String showAll() throws IOException;

Optional arguments:

  • contentType: The content-type of the response from this method call.

    @Processor
    @RestCall(uri = "{url}/list", method = HttpMethod.POST, contentType = "application/json")
  • exceptions: A list of exceptions to throw, configured by pairing an exception type and an expression which is evaluated.

    @Processor
    @RestCall(uri = "{url}/list", method = HttpMethod.POST, contentType = "application/json", exceptions = {@RestExceptionOn(expression="#[message.inboundProperties['http.status'] != 200]", exception = AnimalNotFoundException.class)})

    In this case, the @RestExceptionOn annotation is used to throw an exception on a specified criteria. In the example above, if the HTTP status is not 200, an exception is thrown.

@RestExceptionOn

Category: REST
Mule Version: 3.5 and newer

Throws an exception on specified criteria.

@Processor
@RestCall(uri = "{url}/animals", method = HttpMethod.GET, exceptions = {@RestExceptionOn(expression="#[message.inboundProperties['http.status'] != 200]", exception = AnimalNotFoundException.class)})
public abstract List<Animal> listAnimals(@RestQueryParam("type") String type) throws IOException;

@RestHeaderParam

Category: REST
Mule Version: 3.5 and newer

Allows you to insert custom headers in the HTTP request. When using this annotation, you must specify the name of the header to include in the call. As with the @RestURIParam annotation, you can apply this annotation to @Processor methods arguments or to connector fields marked @Configurable.

When annotating a specific configurable variable using the @RestHeaderParam, the variable is present in all HTTP requests.

@Configurable
@RestHeaderParam(value = "emptyHeaderField", ignoreIfEmpty = true)
private String emptyHeaderField;

When you use the @RestHeaderParam on a specific argument in a method, the header is only included if the method is called.

@Processor
@RestCall(uri = "{url}/create", method = org.mule.api.annotations.rest.HttpMethod.POST)
public abstract String create( @RestHeaderParam("age")
int age)
throws IOException;

@RestHttpClient

Category: REST
Mule Version: 3.5 and newer

An annotation to mark the HttpClient the module uses. This way, you avoid creating multiple clients and have the opportunity to perform your own calls or to configure the HttpClient to fulfill special needs:

@RestHttpClient
HttpClient client = new HttpClient();

@RestPostParam

Category: REST
Mule Version: 3.5 and newer

Allows you to set parameters in the body of POST method calls. Define the POST method with @RestCall and set its parameters with @RestPostParam.

You can apply this annotation to @Processor method arguments or to connector fields marked @Configurable. DevKit ensures that you apply this annotation only to POST methods.

Processor methods annotated with @RestPostParam cannot use a non-annotated argument or a @Payload annotated argument.

For example:

@Processor
@RestCall(uri = "{url}/form", method = HttpMethod.POST)
public abstract String addAnimal(@RestPostParam("type") String type) throws IOException;

Another way is to annotate an @Configurable variable with @RestPostParam as follows:

@Configurable
@RestPostParam("category")
private String category;

@Processor
@RestCall(uri = "http://localhost:8089/product/", method = HttpMethod.POST)
  public abstract Result createProduct(String name) throws IOException;

@RestQueryParam

Category: REST
Mule Version: 3.5 and newer

Specifies URI query parameters, which are appended to the path of the URI after a ? or & symbol. You can apply this annotation to @Processor method arguments or to connector fields marked @Configurable. This enables you to use dynamically-generated arguments as query parameters.

Required argument: String representation of the name of the parameter to append.

@Processor
@RestCall(uri = "{url}/listName", method = org.mule.api.annotations.rest.HttpMethod.GET)
public abstract String getByType(
@RestQueryParam("type") String type)
throws IOException;

When the getByType message processor is called with mule as a parameter, the resultant call would be: http://localhost:8089/animals?type=mule

@RestTimeout

Category: REST
Mule Version: 3.5 and newer

Specifies a timeout for the rest call. This annotation can be attached to a @RestCall to optionally specify a timeout in milliseconds for the rest call. If the rest call exceeds the specified time, a RuntimeException is going to be thrown, unless an exception is specified for the timeout.

@Processor
@RestTimeout(timeout = 1, exception = TimeoutException.class)
@RestCall(uri = "{url}/list/timeout", method = HttpMethod.GET)
public abstract String listAnimalsTimeout() throws IOException;

@RestUriParam

Category: REST
Mule Version: 3.5 and newer

Allows you to dynamically generate URIs by inserting parameters which are annotated with the @RestUriParam annotation.

You can use the @RestUriParam annotation, as well as other related annotations, on @Processor method arguments or @Configurable fields of the connector.

When generating the request call, DevKit includes a non-annotated argument and an argument annotated with @Payload as the body of the call.

When applying annotations to @Processor methods, specify a placeholder in the URI by surrounding the placeholder with curly braces, for example ` {type}. `

You can apply @RestUriParam to @Processor methods arguments as follows:

@Processor
@RestCall(uri = "{url}/create/{type}", method = org.mule.api.annotations.rest.HttpMethod.POST)
public abstract String create(@RestUriParam("type") String type)  throws IOException;

Another way is to annotate the @Configurable variable with @RestUriParam as follows:

@Configurable
@RestUriParam("url")
@Default("http://localhost:8089")
private String url;

@Processor
@RestCall(uri = "{url}/listType", method =    org.mule.api.annotations.rest.HttpMethod.GET)
  public abstract String getByType(@RestQueryParam("type") String type)
   throws IOException;

The next example replaces the path:

@RestCall(uri = "http://myservice.com/{path}", method = HttpMethod.HEAD)

Reference the path argument:

...
Public abstract String setPath(@RestURIParam String path ...

@SessionHeaders

Category: Argument Passing
Mule Version: 3.5 and newer

Marks a method parameter that passes in one or more received headers.

This annotation value can define a single header, a comma-separated list of header names, an asterisk '' to denote all headers, or a comma-separated list of wildcard expressions such as MULE_, X-*. By default, if a named header is not present on the current message, an exception is thrown. However, if the header name is defined with the '?' post fix, it’s marked as optional.

When defining multiple header names or using wildcards, this parameter can be a Map or List. If a Map is used, the header name and value are passed. If List is used, just the header values are used.

If a single header name is defined, the header type can be used as the parameter type, though List or Map can be used too.

The Inbound headers collection is immutable, so the headers Map or List passed in are also immutable. Attempting to write to the Map or List results in an UnsupportedOperationException.

@Source

Category: General
Mule Version: 3.5 and newer

Marks a method inside a @Connector as a callable from within a Mule flow and capable of generating Mule events.

This annotation marks a method inside a Module as callable from within a Mule flow and capable of generating Mule events. Each marked method has an org.mule.api.source.MessageSource generated. The method must receive a SourceCallback as one of its arguments. It does not matter which parameter it is as long it is there.

@Source
public void subscribeTopic(String topic, final SourceCallback callback) {
  getBayeuxClient().subscribe(topic, new ClientSessionChannel.MessageListener() {
    @Override
    public void onMessage(ClientSessionChannel channel, Message message) {
      try {
        callback.process(message.getData());
      } catch (Exception e) {
        LOGGER.error(e);
      }
    }
  });
}

Invoke this method as follows:

<flow name="myFlow">
  <sfdc:subscribe-topic topic="/someTopic"/>
  <logger level="INFO" message="#[payload]"/>
  ...
</flow>

This flow subscribes to a topic and when an update appears, invokes the logger message processor.

@Start

Category: LifeCycle
Mule Version: 3.5 and newer

Mark a method to be started during a method’s org.mule.lifecycle.Startable phase.

@Start
public void mystart() {
     this.sessionId = serviceProvider.login(username, password);
}

Note: start is a reserved word that cannot be used as the method’s name.

@Stop

Category: LifeCycle
Mule Version: 3.5 and newer

Mark a method to be stopped during a method’s org.mule.lifecycle.Stoppable phase.

@Stop
public void mystop() {
    if ( this.sessionId != null ) {
       serviceProvider.logout(sessionId);
    }
}

Note: stop is a reserved word that cannot be used as the method’s name.

@Summary

Category: Display
Mule Version: 3.5 and newer

Adds display information to a field or parameter. Use this annotation to instance variables and method parameters to provide a way to override the default inferred description for a @Configurable variable or a @Processor, @Source, @Transformer method parameter.

@Processor
@Summary("This processor puts an animal in the barn")
public String putInBarn(String animal)
{
    return animal + "has been placed in the barn";
}

@TestConnectivity

Category: Connection Management
Mule Version: 3.6 and newer

Indicates a class for testing connection connectivity. @TestConnectivity makes a connector simpler and helps build better connection strategies. Note: For Mule 3.6, see Mule 3.6 Usage.

Mule 3.7 Update

When implementing a @ConnectionManagement strategy, sometimes is necessary to separate the validation or test of the credentials and the whole configuration from the connection itself. This is the case, for example, if the testing of the configuration adds an unnecessary overhead to the actual connection mechanism.

With this improvement, the developer has the freedom to implement two different methods, one exclusively for testing and validation, and the other focused only in the actual connection.

Instead of annotating the @Connect method also with @TestConnectivity, now there are two methods, each with one of the annotations, for example:

@TestConnectivity
public void testConnect(String username, String password, String url, String optionalConnectionParam)
           throws ConnectionException
{
    if (StringUtils.isBlank(username) || StringUtils.isBlank(password)){
        throw new ConnectionException(ConnectionExceptionCode.INCORRECT_CREDENTIALS,
                 "001", "Username or Password is blank");
    }

    if ( !StringUtils.isBlank(optionalConnectionParam) && !validParams(optionalConnectionParam)){
        throw new ConnectionException(ConnectionExceptionCode.INCORRECT_CREDENTIALS,
                "002", "Given connection parameters are not valid for this connection");
    }
    UrlValidator urlValidator = new UrlValidator();
    if ( !urlValidator.isValid(url)){
        throw new ConnectionException(ConnectionExceptionCode.UNKNOWN_HOST, "003", "Url is not valid");
    }
    Result result = new ServiceClient(username, password).test(url);
    if ( !result.success()){
        throw new ConnectionException(result.cause(), result.code(), result.message());
    }
}
@Connect
public void connect(@ConnectionKey String username, @Password String password,
                                @Optional @Default("http://www.mulesoft.org") String url,
                                @Optional String optionalConnectionParam)
    throws ConnectionException
{
    ServiceClient client = new ServiceClient(username, password);
    try {
        client.connect(url, optionalConnectionParams);
    } catch (ServiceConnectionException e) {
        throw new ConnectionException(getExceptionCode(e.getCause()), e.getCode(), e.getMessage(), e);
    }
}

Restrictions:

  • Only one method can be annotated with @TestConnectivity.

  • The method annotated with @TestConnectivity must have the exact same parameters the @Connect methods, in the same order.

  • Method should declare throws ConnectionException.

Mule 3.6 Usage

The following example is for connectors with connection management and connectivity testing:

@ConnectionManagement
public class BasicAuthConnectionStrategy{
  @Connect
  @TestConnectivity //(active=true) default
  //Connection management methods
}

The following example is for connectors with connection management and no connectivity testing:

@ConnectionManagement
public class BasicAuthConnectionStrategy{
  @Connect
  @TestConnectivity(active=false)
  //Connection management methods
}

The following example is for connectors without connection management and connectivity testing:

@Configuration
public class BasicConnectionStrategy{
  @TestConnectivity//(active=true) default
  public void myCustomMethodForTestingConnectivity() throws ConnectionException{
    //code that uses @Configurable
    ..
    if ("something went wrong"){
      throw new ConnectionException(
         ConnectionExceptionCode.CANNOT_REACH,
         "what your API has returned, if it did..",
         "some meaningful stuff about your API")
    }
    ...
    //if we manage to get here, it means that the connection was
    // successful, hence, no need to return a boolean
  }
}

The @TestConnectivity method must:

  • Receive zero parameters. This constraint does not applies for the @Connect method when being annotated with @TestConnectivity.

  • Throw org.mule.api.ConnectionException.

  • Be public and not static.

  • Not contain any state, use only @Configurable (or the @Connect parameters, if that was the annotated method).

  • Work in a @Connector without connection manager (as test connectivity scenario is covered in the @Connect method).

@Text

Category: Display
Mule Version: 3.5 and newer

Identifies a parameter as being large text input. This marker generates a child element instead of an attribute for the schema generation, but it also uses a text area instead of a text field in the Anypoint Studio dialog generation.

@Transformer

Category: General
Mule Version: 3.5 and newer

Marks a method as a Transformer of data-types or as data formats in the context of the connector.

This annotation identifies a method that becomes a Mule transformer.

@Transformer(sourceTypes = { Object[].class })
public static List transformArrayToList(@Payload Object[] payload)

@TransformerResolver

Category: General
Mule Version: 3.5 and newer

Finds transformers that match a criteria in the registry. Implementations of this interface use some or all of the information passed in to discover a matching transformer.

Register implementations of this interface with the registry before an implementation can be picked up. Typically this is done using registry-bootstrap.properties.

@TransformerResolver
public static org.mule.api.transformer.Transformer
  transformerResolver(DataType source, DataType result,
  MuleContext muleContext) throws Exception {
    if(source.getType().equals(Book.class) &&
      result.getType().equals(String.class)) {
        BookToString bookToString = new BookToString();
        muleContext.getRegistry().
          applyProcessorsAndLifecycle(bookToString);
        return bookToString;
   }
      return null;
}

@UserDefinedMetaData

Mule version: 3.7 and newer

Provides Anypoint Studio users a MetaData tab to enable changing metadata propagation information.

If a @Processor is annotated with @UserDefinedMetaData (which is not mandatory when using TransformingValue), then it should also add a custom attribute to the editors.xml file. That attribute helps Studio users change the metadata of the given processor in later usages if needed.

When enabled, an end user of Studio should see that every @Processor annotated with @UserDefinedMetaData a tab in the UI that enables a user to change the information for MetaData propagation (look for the MetaData tab ).

One use of @UserDefinedMetaData is to define a MIME type for content returned by a connector’s target resource.

For example:

@Processor
@UserDefinedMetaData
public TransformingValue<InputStream, DataType<InputStream>>

//The object represents the Java class of the DataType's type class
getFileFromSystem(String filePathBleh) {
    DataType<InputStream> dataType = DataTypeFactory.create(InputStream.class, MimeTypes.APPLICATION_XML);
    dataType.setEncoding(StandardCharsets.UTF_8.name());
    return new DefaultTranformingValue("CREATE YOUR STREAM HERE", dataType);
}

@ValidateConnection

Category: Connection Management
Mule Version: 3.5 and newer

Validates a connection prior to each invocation of the operations exposed by the @Processor annotation.

This method is called by Mule to check whether the connection is actually open or not.

A method annotated with @ValidateConnection must:

  • Be public

  • Take no input parameters

  • Return boolean or java.lang.Boolean

Only one method on a @Connector class can be annotated with @ValidateConnection.

The following example determines whether a connection is active. The code simply checks if the connection parameter is null. A different implementation may be required for other connectors, depending on the protocol.

@ValidateConnection
public boolean isConnected() {
    return connection != null;
}

@WsdlProvider

Mule version: 3.7 and newer

Created by default for a SOAP connector. The @WsdlProvider class resides in src/main/java > org.mule.modules.<connector_name>.config. This class contains annotations for @WsdlServiceRetriever and @WsdlServiceEndpoint. The retriever annotation retrieves the full set of WSDL files. The service endpoint annotation provides a way to resolve endpoints across the one or more WSDLs.

package org.mule.modules.demoflow.config;

import org.mule.api.annotations.Configurable;
import org.mule.api.annotations.components.WsdlProvider;
import org.mule.api.annotations.ws.WsdlServiceEndpoint;
import org.mule.api.annotations.ws.WsdlServiceRetriever;
import org.mule.devkit.api.ws.definition.DefaultServiceDefinition;
import org.mule.devkit.api.ws.definition.ServiceDefinition;
import org.mule.api.annotations.param.Default;

@WsdlProvider(friendlyName = "Configuration")
public class ConnectorConfig {

    @Configurable
    @Default("MyWsdl")
    private String endpoint;

    @WsdlServiceRetriever
    public ServiceDefinition getServiceDefinition() {
           return new DefaultServiceDefinition(
                "MyWsdl");
    }

    @WsdlServiceEndpoint
    public String getServiceEndpoint(ServiceDefinition definition) {
         return endpoint;
    }

    public String getEndpoint() {
        return endpoint;
    }
    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }
}

@WsdlServiceEndpoint

Mule version: 3.7 and newer

Created by default in a SOAP connector to resolve endpoints across one or more WSDL files.

See @WsdlProvider for an example.

@WsdlServiceRetriever

Mule version: 3.7 and newer

Created by default in a SOAP connector to retrieve WSDL content from one or more WSDL files.

See @WsdlProvider for an example.