Execute a Java process in a .Net Azure WebJob

I recently had the need to execute a .jar file from within an Azure WebJob built with C#. I found a few resources that showed how to upload a .zip file, for instance, and have that run  a .bat file as a job. Or, how to create a Java web app. But my webjob needed to do more than just run a .jar, and I didn’t have the time to get up to speed on Java and the Azure Storage SDK for Java. As the Google let me down, here I demonstrate the solution.

It turns out there is indeed a JRE available and you can run java.exe. You can either give it a class name that contains a main entry point, or give it a .jar, exactly a you would do from the command line. The first thing I had to do was determine how to locate java.exe. I made a dump of environment variables and saw that JAVA_HOME was defined.

Capture

StringBuilder sb = new StringBuilder();
foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
{
sb.AppendFormat("{0} : {1}", de.Key.ToString(), de.Value.ToString()).AppendLine();
}
Console.WriteLine(sb.ToString());

view raw
EnvVariableDump.cs
hosted with ❤ by GitHub

With this information, all you need to do is craft and execute the proper Process:

using Microsoft.Azure.WebJobs;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace TestWebjob
{
public class Functions
{
// This function will get triggered/executed when a new message is written
// on an Azure Queue called queue.
public static void ProcessQueueMessage([QueueTrigger("webjobtestq")] string message, TextWriter log)
{
try
{
var javaHome = Environment.GetEnvironmentVariable("JAVA_HOME");
ProcessStartInfo psi = new ProcessStartInfo(javaHome + "\\bin\\java", string.Concat(" -jar .\\App_Data\\AzureWebjobJar.jar ", message))
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true
};
Process javaProcess = Process.Start(psi);
string theOutput = javaProcess.StandardOutput.ReadToEnd();
javaProcess.WaitForExit();
//code to craft email of output omitted
}
catch (Exception ex)
{
//code to craft email of exception omitted
}
}
}
}

view raw
WebJobJar.cs
hosted with ❤ by GitHub

Using the Azure Storage Explorer I was easily able to enqueue messages to execute my webjob which is triggered by the queue:

Capture

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s