MuleSoft Creating Custom Component/Connector
Using MuleSoft Palette and the Anypoint IDE (along with some Java code), we'll show you how to customize your MuleSoft applications.
Join the DZone community and get the full member experience.
Join For Free
1.0 Overview
This tutorial will walk a user through creating a custom Mule component where you can use it via Mule Palette (in Anypoint IDE) during design time. In this article, I will show you how to create the connector install it into your Anypoint IDE. I will also demonstrate how you can use it in later Mule projects. Besides that, I will also go through the necessary Maven settings and repository installation that needs to be in place for projects to start using it.
2.0 Creating the Custom Mule Component/Connector
Step 1 is creating an Anypoint Connector Project (as depicted in Figure 2.0a).
Figure 2.0a
Choose SDK Based and click on Next Button (as depicted in Figure 2.0b).
Figure 2.0b
Now key in the desired connector name here. For demonstration sake, I will just use my name (depicted in Figure 2.0c) and click Finish.
Figure 2.0c
3.0 Modifying the Connector Code
Once the connector is created, you will notice that you have two Java class being created (depicted in Figure 3.0a).
Figure 3.0a
The first connector class is where you implement your desired functionalities. The second class, the connector Java class, is where you capture all the necessary configurations that you might need for your connector class.
Include the following imports in your Connector java file.
import java.io.IOException;
import org.mule.api.annotations.Config;
import org.mule.api.annotations.Connector;
import org.mule.api.annotations.Processor;
import org.mule.api.MuleEvent;
import org.mule.api.MuleException;
import org.mule.api.MuleMessage;
import org.mule.api.annotations.Config;
import org.mule.api.annotations.Connector;
import org.mule.api.annotations.Processor;
import org.mule.api.annotations.lifecycle.OnException;
import org.mule.api.lifecycle.InitialisationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.mule.modules.kian.config.ConnectorConfig;
Add the logger so that custom connectors would be able to log its data onto the Mule log.
Logger log = LoggerFactory.getLogger(KianConnector.class);
Now modify the Java code from the first code block below to the second one depicted below.
@Processor
public String greet(String friend) {
/*
* MESSAGE PROCESSOR CODE GOES HERE
*/
return config.getGreeting() + " " + friend + ". " + config.getReply();
}
@Processor
public MuleEvent doSomething(final MuleEvent event, MuleMessage muleMessage)
throws InitialisationException, IOException, NullPointerException, MuleException {
try{
String corelationId = event.getMessage().getCorrelationId(); //check
log.info(String.format("corelationId: %s", corelationId));
int correlationGroupSize = event.getMessage().getCorrelationGroupSize();
log.info(String.format("correlationGroupSize: %s", correlationGroupSize));
int correlationSequence = event.getMessage().getCorrelationSequence();
log.info(String.format("correlationSequence: %s", correlationSequence));
String encoding = event.getMessage().getEncoding(); // check
log.info(String.format("encoding: %s", encoding));
Object OriginalPayload = event.getMessage().getOriginalPayload();
log.info(String.format("OriginalPayload: %s", OriginalPayload));
String messageRootId = event.getMessage().getMessageRootId(); // check
log.info(String.format("messageRootId: %s", messageRootId));
Object error = event.getMessage().getExceptionPayload(); // check
log.info(String.format("error: %s", error));
String payload = event.getMessage().getPayloadAsString();// check
log.info(String.format("Payload: %s", payload));
}catch(Exception ex){
log.error("Error Encountered from custom component ",ex);
}
return event;
}
The last return line is important - if you return a string or anything else besides an event it will overwrite any payload that passes through your connectors. If this is not what you want then you should return an event instead.
Now after all of this is done, the next thing you need to do is to build/compile the application and install it into your IDE so that you can use it in your Mule application.
4.0 Installing Mule in Your IDE
After you have done all the steps in section 3.0 now you are ready to install your custom component/connector to be used in a regular Mule application.
As depicted in Figure 4.0a, you need to right-click on the custom connector project, go to Anypoint Connector, expand the sub-menu, and click on “Install or Update.”
Figure 4.0a
Once it is successfully installed into your IDE you will get the following prompt:
If you don't get this prompt, then it would mean that you have compilation errors, you need to dig into the compilation errors to check what is wrong in your code.
5.0 Implementing Custom Components Into a Mule App
In this section, I will demonstrate how you can implement the previously built connector into a Mule application.
Go to File > New > Mule Project as depicted in Figure 5.0a.
Figure 5.0a
Now create a sample HTTP project with Maven enabled (it is important to have it Maven enabled because I want to show you how dependencies are created when you start using the custom component):
After creating the Mule application, we will now drag and drop the custom component from the Mule Palette across to the Mule configuration canvas (Figure 5.0c). If you search for “Kian” from the Mule Palette you will find it. Now drag it across the canvas and drop it beside the HTTP connector.
Figure 5.0c
If you look at your connector configuration screen, you will see two basic settings. The first one is the Connector Configuration and the second one is the Operation settings (as depicted in Figure 5.0d):
Figure 5.0d
Now if you observe closely enough, under Operations you will see that “Do something” actually coincides with the method name of our previously written connector class (Figure 5.0e).
Figure 5.0e
And if you go into the Connector Configuration of the custom component, you will see three text boxes, the first one being the name of the connector, and the two other text boxes under “General” tabs are Greeting and Reply (depicted in Figure 5.0f).
Figure 5.0f
Now if you contrast the two settings against the ConnectorConfig
Java class in our custom component you will see that Mule actually creates a text box to capture each configurable property that we have coded into this class (Figure 5.0g).
Figure 5.0g
Now let's move on to testing the Mule application with the new connector as part of its implementation, fire up the Mule application by starting it in the IDE. Launch postman, and key in the following JSON as part of the payload to post to the Mule app (Figure 5.0h).
{
"frequencyTimeUnit": "SECONDS",
"frequency": "120"
}
Figure 5.0h
Now if you move on back to the IDE, you will see that the implementation to log something is actually working because your IDE console will print out the following logs:
You will see your payload being printed in the console and together with all its related data.
6.0 Uninstalling the Custom Component/Connector
In order to modify the custom connector, you will need to first uninstall it from the IDE. There are many ways you can uninstall the custom connector, here I will only show you how to do it via the Custom Connector project.
Right-click on the project, go to “Anypoint Connector,” and then click on Uninstall (as depicted in Figure 6.0a).
Figure 6.0a
Once you'v esuccessfully uninstalled it, you will see a pop-up dialog box from your IDE as depicted in Figure 6.0b.
Figure 6.0b
If you click OK, your IDE will restart to reflect the changes.
7.0 Noticing the Impact of Uninstalling the Custom Component
If you have successfully uninstalled your connector from the IDE, it doesn't mean that it will remove it from the projects that it is dependant upon. If you go back to the Mule App in which you have implemented the custom connector you will notice that the Connector is now greyed out, what this means is that the IDE doesn't recognize the connector (Figure 7.0a).
Figure 7.0a
The second thing you will notice is that you can no longer find the custom connector in your IDE’s Mule Palette.
The third thing you will notice is that your Mule project's Maven dependency file (your Mule app’s pom.xml file) will still contain entries for the custom connector (ie Figure 7.0b and Figure 7.0c).
Figure 7.0b
Figure 7.0c
If you decide that you no longer want to use the custom component in your Mule projects you need to remove them manually.
8.0 Modifying the Custom Component
After uninstalling the custom component from the previous section, let's make further modifications on it to print out the connector settings.
Go back to the Connector class and change the operations method to the following code.
@Processor
public MuleEvent doSomething(final MuleEvent event, MuleMessage muleMessage)
throws InitialisationException, IOException, NullPointerException, MuleException {
try{
String corelationId = event.getMessage().getCorrelationId(); //check
log.info(String.format("corelationId: %s", corelationId));
int correlationGroupSize = event.getMessage().getCorrelationGroupSize();
log.info(String.format("correlationGroupSize: %s", correlationGroupSize));
int correlationSequence = event.getMessage().getCorrelationSequence();
log.info(String.format("correlationSequence: %s", correlationSequence));
String encoding = event.getMessage().getEncoding(); // check
log.info(String.format("encoding: %s", encoding));
Object OriginalPayload = event.getMessage().getOriginalPayload();
log.info(String.format("OriginalPayload: %s", OriginalPayload));
String messageRootId = event.getMessage().getMessageRootId(); // check
log.info(String.format("messageRootId: %s", messageRootId));
Object error = event.getMessage().getExceptionPayload(); // check
log.info(String.format("error: %s", error));
String payload = event.getMessage().getPayloadAsString();// check
log.info(String.format("Payload: %s", payload));
log.info(String.format("Connector Settings (Greeting): %s", config.getGreeting()));
log.info(String.format("Connector Settings (Reply): %s", config.getReply()));
}catch(Exception ex){
log.error("Error Encountered from custom component ",ex);
}
return event;
}
Now carry out the same action to install the components (refer to the previous sections on how to install the component).
If you face any issues with reinstalling the connector, you just need to close the IDE manually, remove the target folder, and open up the IDE to do the installation again.
Now if you run Postman again, with the same settings from the previous section, you will see that you have added two log entries from your connectors (as depicted in Figure 8.0a).
Figure 8.0a
And you will see the following logs in your IDE console (as depicted in Figure 8.0b).
Figure 8.0b
9.0 Conclusion
When you build custom components/connectors you need to ensure that they are built to be stable, otherwise, it will affect the stability of your whole Mule application. You will also need to devise a sufficient testing strategy on the Mule application so that no unstable versions of it will be released to production for use. You will also need to decide if you want your custom components to carry out their operations in Asynchronous or Synchronous mode (by default all connectors implementations are carried out in Synchronously) If you want it to be otherwise, you have to programmatically code in the async feature. Code for this tutorial can be obtained from the following link. https://github.com/kianting/CustomConnectorTutorial
Opinions expressed by DZone contributors are their own.
Comments