Gurmeet
Gurmeet

Reputation: 3314

Execute .jar file in .net core on Openshift container platform

net core application which internally calls a java (.jar) file using .net Process class. I have used cmd.exe to run .jar file along with parameters. I have deployed this application on Openshift Container Platform. But as openshift is running on Linux, so cmd.exe is not available. Below is code in .net core to execute jar file.

            Process cmd = new Process();
            cmd.StartInfo.UseShellExecute = false;
            cmd.StartInfo.WorkingDirectory = Common.JarWorkingDir;
            cmd.StartInfo.FileName = "cmd.exe";
            cmd.StartInfo.Arguments = "/K java -jar " + string.Format("{0} {1}", '"' + Common.JarFilePath + '"', '"' + sourceCodePath + '"');
            cmd.StartInfo.CreateNoWindow = true;
            cmd.StartInfo.RedirectStandardInput = true;
            cmd.Start();
            cmd.StandardInput.WriteLine("exit");
            cmd.StandardInput.Flush();
            cmd.WaitForExit();

So Jar file is unable to execute. Any alternative to execute this jar with .net on OpenShift. Please help.

Upvotes: 2

Views: 1399

Answers (1)

omajid
omajid

Reputation: 15223

OpenShift is essentially Kubernetes running Linux containers. In other words, your code should act as if it is running on Linux.

Instead of cmd.exe, use bash (or, sh, or really, whatever shell is pre-installed in your container):

Process cmd = new Process();
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.WorkingDirectory = Common.JarWorkingDir;
cmd.StartInfo.FileName = "bash";
cmd.StartInfo.Arguments = "-c 'java -jar " + string.Format("{0} {1}", '"' + Common.JarFilePath + '"', '"' + sourceCodePath + '"'');
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.RedirectStandardInput = true;
cmd.Start();
cmd.StandardInput.WriteLine("exit");
cmd.StandardInput.Flush();
cmd.WaitForExit();

You can maybe even remove some of the lines. CreateNoWindow, for example, is not required because .NET Core does not create windows on Linux at all.

If you have no shell expressions, perhaps you can even get things to be simpler and simplify from this:

cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.FileName = "bash";
cmd.StartInfo.Arguments = "-c 'java -jar " + string.Format("{0} {1}", '"' + Common.JarFilePath + '"', '"' + sourceCodePath + '"'');

to something like this:

cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.FileName = "java";
cmd.StartInfo.Arguments = $"-jar \"{Common.JarFilePath}\" \"{sourceCodePath}\"";

Oh, and watch out for the quoting in your Arguments variable. If you wrap the entire command after -c with single quotes, you should be fine, but if you are doing something trickier - if Common.JarFilePath isn't a simple file name - it may not work so well. Definitely test and tweak that. Maybe consider EscapeAndConcatenate.

Upvotes: 3

Related Questions