DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How to Introduce a New API Quickly Using Micronaut
  • Spring Boot GoT: Game of Trace!
  • Data Pipeline Techniques in Action
  • Javac and Java Katas, Part 2: Module Path

Trending

  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • SaaS in an Enterprise - An Implementation Roadmap
  • Go 1.24+ Native FIPS Support for Easier Compliance
  • Software Delivery at Scale: Centralized Jenkins Pipeline for Optimal Efficiency
  1. DZone
  2. Coding
  3. Languages
  4. Executing Shell Scripts From Mule

Executing Shell Scripts From Mule

Learn how to execute shell scripts from Mule with a custom Java component so you can perform tasks directly, rather than using wrapper components.

By 
Deepak Kushwaha user avatar
Deepak Kushwaha
·
Aug. 18, 17 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
11.0K Views

Join the DZone community and get the full member experience.

Join For Free

Sometimes it is better to perform a task directly with the help of the OS rather than using wrapper components. For example, if we just want to move a file from one directory to another without any transformation, we can avoid loading the file into the memory and can move the file directly using a shell script.

Objective: Executing shell scripts from a Mule custom Java component.

In this tutorial, I'll pass the filename from HTTP Post to the flow, and later, my custom Java component will execute the shell script command to move the file.

Steps

1. Create a flow by adding an HTTP Listener and do the basic configuration.

   <flow name="fileMoverFlow">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/moveFile" allowedMethods="POST" doc:name="HTTP"/>
    </flow>

2. Now create a .sh (or any extension) file and put your commands into it. You can dynamically pass values into this script file using a template component. For example: you can pass the file name to this script by putting #[payload] in the script, then parsing it through a template component.

I created a file, the content of which is

mv /input/#[payload] /output/

As you can see, this script has an MEL expression in it. To populate values through MEL expressions, we ll pass this script through the template.

Now the flow will become

  <flow name="fileMoverFlow">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/moveFile" allowedMethods="POST" doc:name="HTTP"/>
        <parse-template location="scripts/fileMover.sh" doc:name="Parse Template"/>
    </flow>

3. Now, I create a Java Class which will get shell script commands as a string input and will execute them.



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractMessageTransformer;

public class ScriptExecuter extends AbstractMessageTransformer {

@Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
// this is your script in a string
String script = (String) message.getPayload();

List<String> commandList = new ArrayList<>();
commandList.add("/bin/sh");

ProcessBuilder builder = new ProcessBuilder(commandList);

builder.redirectErrorStream(true);
Process shell;
try {
shell = builder.start();

try (OutputStream commands = shell.getOutputStream()) {
commands.write(script.getBytes());
}

// read the outcome
try (BufferedReader reader = new BufferedReader(new InputStreamReader(shell.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}

// check the exit code
int exitCode = shell.waitFor();
System.out.println("EXIT CODE: " + exitCode);

} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Success";
}

}

 4. Now, place a Groovy component and call the script executer class to run your script.

Th final flow is as follows:

    <flow name="fileMoverFlow">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/moveFile" allowedMethods="POST" doc:name="HTTP"/>
        <parse-template location="scripts/fileMover.sh" doc:name="Parse Template"/>
        <set-payload value="#[payload:java.lang.String]" doc:name="Set Payload"/>
        <custom-transformer class="com.test.ScriptExecuter" doc:name="Execute Script"/>
    </flow>
shell

Opinions expressed by DZone contributors are their own.

Related

  • How to Introduce a New API Quickly Using Micronaut
  • Spring Boot GoT: Game of Trace!
  • Data Pipeline Techniques in Action
  • Javac and Java Katas, Part 2: Module Path

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!