Java.exe does not open with Process.start - java

I have an application that needs to be opened with Java.exe . when i try to open the application with Command prompt with the following arguments
C:\MyworkingFolder\>start java -MyParamters ->This works and the application is launched
But when i use the same in my c# code
var pInfo = new ProcessStartInfo
{
FileName = "Java",
WorkingDirectory = "MyworkingFolder",
Arguments = -MyParamters
};
Process monitorProcess = Process.Start(pInfo);
This code part does not work. All that i get is a window that shows OpenWith

The application now works fine.. I have given the full path for Java "C:\ProgramData\Oracle\Java\javapath\java.exe" and it works now.

Related

how to run a powershell script as a windows service from inside a Java program?

I have the following code that runs a windows service from inside Java.The code uses JInterop Java library, JInterop is a pure Java COM client for windows COM server. More details of JIntop are available here [http://fishi.devtail.io/weblog/2015/01/21/pure-java-dcom-bridge-j-interop/]
String cmdFile = "service.bat";
results = wbemServices_dispatch.callMethodA(
"Get", new Object[]{ new JIString("Win32_Process"),
new Integer(0), JIVariant.OPTIONAL_PARAM()});
IJIDispatch wbemObjectSet_dispatch = (IJIDispatch)JIObjectFactory.narrowObject(
(results[0]).getObjectAsComObject());
results = wbemObjectSet_dispatch.callMethodA("Create",
new Object[]{ new JIString(targetFilePrefix + cmdFile),
JIVariant.OPTIONAL_PARAM(),
JIVariant.OPTIONAL_PARAM()});
Is it possible to run a powershell file(.ps1) as a service in the same manner as above using the same library, or in some other way.
You can create a batch file which, in-turns, can trigger a powershell script like this:
#echo off
Powershell.exe set-executionpolicy remotesigned -File C:\folder\MyScript.ps1
pause
Save it as "Trigger_ps.bat"
Then you can use the sc command to create a windows service by mentioning this batch file path like this:
SC CREATE PS_Trigger_Service Displayname= "PS_Trigger_Service" binpath= "C:\folder\Trigger_ps.bat" start= auto
This should solve your purpose.

Problems With Spaces In Path In System.Diagnostics.Process parameters

First let me say that this question is not a duplicate of Use Process.Start with parameters AND spaces in path. I am using the System.Diagnostics.Process to start a cmd.exe window and then running java in that window. Except I want the java command to be run based on their installed Java path, as the PATH environment variable is unreliable and doesn't seem to get set very often when Java is installed. So I replaced the "java" in my arguments for the Process with the actual Java path, but now I'm getting this error:
'C:\Program' is not recognized as an internal or external command,
operable program or batch file.
Clearly this is because there are spaces in the name, but I am properly quoting the path and using escape characters to create those quotes. Here is the code used to run the cmd.exe:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
//startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
if (chbPath.Checked) startInfo.Arguments = "/C \"" + javaPath + "\\bin\\java.exe\" -Djava.library.path=\"lib\\natives-win\" -jar SecondDimension.jar " + chbWindowed.Checked.ToString();
else startInfo.Arguments = "/C java -Djava.library.path=\"lib\\natives-win\" -jar SecondDimension.jar " + chbWindowed.Checked.ToString();
process.StartInfo = startInfo;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.Start();
this.Visible = false;
process.WaitForExit();
Console.WriteLine(process.StandardError.ReadToEnd());
Application.Exit();
If chbPath.Checked = false, it runs the command with the java command set with PATH. Which works fine for me, but doesn't for people who haven't ever tried to run java from the command line. But when I check chbPath, then I get the error listed above. Can anyone help with this? This is really annoying and I should have been done with this hours ago, but of course a SPACE....a SINGLE SPACE is stopping me from progressing....ARGHHH!!!
Edit:
Also here is the code for my path finder, which I pulled off another post here:
String javaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment";
using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(javaKey))
{
String currentVersion = baseKey.GetValue("CurrentVersion").ToString();
using (var homeKey = baseKey.OpenSubKey(currentVersion))
return homeKey.GetValue("JavaHome").ToString();
}
First you could use the property ProcessStartInfo.WorkingDirectory to set the working folder for the Java process, then, because your program is in a different directory you need to change the path to this program.
You could set an Environment variable and use that variable to complete the path to the program or directly include the name of the program in the environment variable
Environment.SetEnvironmentVariable("JAVA_PRG", #"d:\temp"); // Whatever
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WorkingDirectory = Path.Combine(javaPath, "bin");
startInfo.FileName = "cmd.exe";
if (chbPath.Checked)
startInfo.Arguments = "/C java.exe .... -jar %JAVA_PRG%\SecondDimension.jar ";
Ok, so I was able to fix it. Apparently I don't need to run a cmd window to run the java command, because using diagnostics.process to start a progarm this way always creates a console window. So I just changed the GetJavaInstallationPath() code to return the path to the actual java executable, and then just set StartInfo.FileName = GetJavaInstallationPath(); which pretty much solved all my problems. This way the working directory stays in the game's directory and I still get the console window I wanted. So I guess I was trying too hard. :) Here's the fixed code:
private void btnLaunch_Click(object sender, EventArgs e)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = GetJavaInstallationPath();
startInfo.Arguments = "-Djava.library.path=\"lib\\natives-win\" -jar SecondDimension.jar " + chbWindowed.Checked.ToString();
process.StartInfo = startInfo;
process.Start();
this.Visible = false;
process.WaitForExit();
Application.Exit();
}

Run external app by userinput

So I'm creating a Java program and I want to make it so that you can ask it to open a program.
But, here's the catch, I want the program it opens to be taken from the user input, right now I'm trying to change this
try{Process p = Runtime.getRuntime().exec("notepad.exe");}
catch(Exception e1){}
Into something that opens a program that you asked it to open.
Here's an example of what I want:
User: Can you open chrome?
Program: Of course, here you go!
chrome opens
Could anyone tell me how I would be able to do this?
You can do it in two ways:
1.By Using Runtime:
Runtime.getRuntime().exec(...)
So, for example, on Windows,
Runtime.getRuntime().exec("C:\application.exe -arg1 -arg2");
2.By Using ProcessBuilder:
ProcessBuilder b = new ProcessBuilder("C:\application.exe", "-arg1", "-arg2");
or alternatively
List<String> params = java.util.Arrays.asList("C:\application.exe", "-arg1", "-arg2");
ProcessBuilder b = new ProcessBuilder(params);
or
ProcessBuilder b = new ProcessBuilder("C:\application.exe -arg1 -arg2");
The difference between the two is :
Runtime.getRuntime().exec(...)
takes a single string and passes it directly to a shell or cmd.exe process. The ProcessBuilder constructors, on the other hand, take a varargs array of strings or a List of strings, where each string in the array or list is assumed to be an individual argument.
So,Runtime.getRuntime.exec() will pass the line C:\application.exe -arg1 -arg2 to cmd.exe, which runs a application.exe program with the two given arguments. However, ProcessBuilder method will fail, unless there happens to be a program whose name is application.exe -arg1 -arg2 in C:.
You can try it with like. Pass whole path of where you install chrome.
try{
Process p = Runtime.getRuntime().exec("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe");
}
catch(Exception e1){
}
When using exec, it is essentially the same as if you were using the command line on windows. Open Command Prompt, type open, and see if it gives details as to how it opens files. If not, find the opener. Usually when dealing with command line operations, there are multiple parameters that are required for opening files/applications. An example of this would be for opening the "TextEdit.app" application on a mac.
Process p = Runtime.getRuntime().exec("open -a TextEdit.app");
Terminal(for mac) would open the app using the -a flag, meaning "application." You could open a file doing:
Process p = Runtime.getRuntime().exec("open filename.file_ext -a TextEdit.app");
The second one will tell the computer to find the application named <app_name>.app and open the file filename.file_ext
I know this is not going to work for a windows machine, but it's only to show how to use the command line operations for opening files and applications. It should be similar for windows though.
Hope this helps

Alloy API resulting in java.lang.UnsatisfiedLinkError

I'm currently using the Alloy Analyzer API to build a program, and getting some peculiar behavior. Specifically, if I open a file and parse it (using CompUtil.parseEverything), then make a new Command and call TranslateAlloyToKodkod.execute_command on the parsed file and newly created command using MiniSat with UNSAT core, it runs fine. However, later in execution, my program parses a second input file (also using CompUtil.parseEverything), gets another world, makes a new command, and then I try to call TranslateAlloyToKodkod.execute_command again, it throws the following error:
ERROR: class edu.mit.csail.sdg.alloy4.ErrorFatal: The required JNI library cannot be found:
java.lang.UnsatisfiedLinkError: no minisatproverx5 in java.library.path
edu.mit.csail.sdg.alloy4compiler.translator.TranslateAlloyToKodkod.execute_command(TranslateAlloyToKodkod.java:390)
Does anyone have any idea why this is thrown the second time, but not the first?
To summarize, I have something similar to the following:
Module someWorld = CompUtil.parseEverything_fromFile(rep, null, "someFile.als");
//For the following, "sig" is a sig in someWorld.getAllReachableSigs();
Command command = sig.not();
A4Options options = new A4Options();
options.solver = A4Options.SatSolver.MiniSatProverJNI;
A4Solution ans =
TranslateAlloyToKodkod.execute_command(rep, someWorld, command, options);
//No thrown error
Module someOtherWorld = CompUtil.parseEverything_fromFile(rep, null, "someOtherFile.als");
//For the following, "sig" is a sig in someOtherWorld.getAllReachableSigs();
Command commandTwo = sig.not();
A4Solution ansTwo =
TranslateAlloyToKodkod.execute_command(rep, someOtherWorld, commandTwo, options);
//Thrown error above. Why?
I tried to reproduce this behavior, but I couldn't. If I don't add MiniSat binaries to the LD_LIBRARY_PATH environment variable, I get the exception you mentioned the very first time I invoke execute_command. After configuring LD_LIBRARY_PATH, the exception doesn't happen.
To configure LD_LIBRARY_PATH:
(1) if using Eclipse, you can right-click on one of your source folders, choose Build Path -> Configure Build Path, then on the "Source" tab make sure that "Native library location" points to a folder in which MiniSat binaries reside.
(2) if running from the shell, just add the path to a folder with MiniSat binaries to LD_LIBRARY_PATH, e.g., something like export LD_LIBRARY_PATH=alloy/extra/x86-linux:$LD_LIBRARY_PATH.
Here is the exact code that I was running, and everything worked
public static void main(String[] args) throws Exception {
A4Reporter rep = new A4Reporter();
A4Options options = new A4Options();
options.solver = A4Options.SatSolver.MiniSatProverJNI;
Module someWorld = CompUtil.parseEverything_fromFile(rep, null, "someFile.als");
Command command = someWorld.getAllCommands().get(0);
A4Solution ans = TranslateAlloyToKodkod.execute_command(rep, someWorld.getAllReachableSigs(), command, options);
System.out.println(ans);
Module someOtherWorld = CompUtil.parseEverything_fromFile(rep, null, "someOtherFile.als");
Command commandTwo = someOtherWorld.getAllCommands().get(0);
A4Solution ansTwo = TranslateAlloyToKodkod.execute_command(rep, someOtherWorld.getAllReachableSigs(), commandTwo, options);
System.out.println(ansTwo);
}
with "someFile.als" being
sig A {}
run { some A } for 4
and "someOtherFile.als"
sig A {}
run { no A } for 4
I use alloy4.2.jar as a library in my eclipse plugin project.
A4Reporter rep = new A4Reporter();
Module world = CompUtil.parseEverything_fromFile(rep, null, "civi.als");
A4Options options = new A4Options();
options.solver = A4Options.SatSolver.SAT4J;
options.skolemDepth = 1;
When I use SAT4J, the default solver, the problem mentioned here will not show up. But another exception comes out. The reason is that my civi.als file need Integer model, which located in alloy4.2.jar under the folder /models/util/. But when I run the application, it tries to find the file util/Integer.als directly. That causes the exception. Is it possible to fix that problem?
Besides, I also tried to put the alloy4.2.jar in eclipse plugin project and run my application as an eclipse application (running my application as a plugin). With the default solver, the application has no problem at all. But when I switch to MiniSatProverJNI, the problem mentioned here comes out (I have set the alloy4.2.jar as classpath).

Java program for changing the directory of command prompt

I have written a java program named Automate.java, in which the another java program named newsmail will be executed.
The problem i face here is, Automate.java is in Desktop location(should be in desktop only always due to some requirements) and newsmail is in /home/Admin/GATE521/LN_RB this location.
What must be done before the below code, such that the command prompt automatically goes to the required folder and executes the program.
String command = "java newsmail";
Process child = Runtime.getRuntime().exec(command);
You can use this exec() :
Process child = Runtime.getRuntime().exec(command, null, new File("/home/Admin/GATE521/LN_RB"));
Resources :
javadoc - Runtime.exec()
Use the new ProcessBuilder class, instead of Runtime.exec().
ProcessBuilder pb = new ProcessBuilder("java", "newsmail");
pb.directory("/home/Admin/GATE521/LN_RB");
pb.start();
You can even look at pb.environment() to change environment variables if necessary.

Categories

Resources