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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); |
With this information, all you need to do is craft and execute the proper Process
:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} | |
} |
Using the Azure Storage Explorer I was easily able to enqueue messages to execute my webjob which is triggered by the queue: