I am trying to start a windows service in java using this
public static void main(String[] args) throws IOException {
String startCom = "net start";
String startProc = "\"C:/Program Files/Common Files/Apple/Mobile Device Support/bin/AppleMobileDeviceService.exe\"";
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(startCom + startProc);
System.out.println("Starting It");
}
It runs with no exceptions but does not start the service. What Am I doing wrong?
Try to figure out what the registered service name is, and use that instead of the full executable. For example:
net start "Adobe Acrobat Update Service"
You can find out the service name by by running net start on a command window (which prints a list of all registered services) or by finding the service in the Services control panel by clicking the Start button, typing services.msc, and pressing Enter. If the service name is cryptic, you can right-click the service in the Services control panel and click Properties to confirm the executable for that service.
You probably need to execute the command with escalated privileges. You can either do this by disabling UAC (not recommended), by launching javaw.exe with elevated privileges when you start your program, or by using a utility like Elevate.exe to execute any privileged commands.
If you're having trouble getting Runtime.exec to do your bidding, try using ProcessBuilder instead.
Lastly, it's a good idea to always read the contents of STDOUT and STDERR (from Process.getOutputStream() and Process.getErrorStream()). They might contain diagnostic information; but even more importantly, if the buffers fill up while the Process is still outputting to them, the Process will hang.
Try this code:
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd start /c C:/Program Files/Common Files/Apple/Mobile Device Support/bin/AppleMobileDeviceService.exe");
System.out.println("Starting It");
It looks like your main() exits, so your service will die. In this case, you need to install the service using
sc create "servicename" binpath="path",
and then start it with
sc start "servicename.
That is, a service .exe still needs to be installed as a Windows service.
Related
I have a Talend job that will open an Excel file when certain conditions are met. The Excel file has lots of VBA in it to read from SQL Server and create a document. I can run the Talend job successfully when running from Open Studio. I am now trying to schedule the job in Windows Task Scheduler that will run the Talend job every 5min to open the Excel file.
I tried using a tJava component to use the Desktop class to open the file, but that did not work.
Desktop dt = Desktop.getDesktop();
dt.open(new File("C:/Users/<username>/<filepath info>/TEST.xlsm"));
Now, I'm trying to use a tSystem component with the following command:
"cmd.exe /c start excel \"C:/Users/<username>/<filepath info>/TEST.xlsm\""
I believe it does not work due to the fact that when scheduled, it becomes a background process that has no reference to a desktop or cmd that it can run the command on. How can I open my Excel file from a background job using Java?
If using the start command and the path of the file to be started contains a space then you must specified a title to the start command.
import java.io.IOException;
class StartExcel {
public static void main(String args[])
throws IOException
{
String fileName = "c:\\temp\\xls\\test2.xls";
String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName};
Runtime.getRuntime().exec(commands);
}
}
It's feature.
I'm trying to execute a batch file and get the error code from it in Windows 7 Enterprise 64-bit.
My batch file is c:\test.cmd and contains a single line:-
exit 1
My code for executing the batch file is:-
public static void main(String[] args) throws Exception {
Process process = new ProcessBuilder("c:\\test.cmd").start();
System.out.println(process.waitFor());
}
The output is zero. If I try with:-
new String[] {"cmd", "/c", "c:\\test.cmd"}
the result is again zero.
There doesn't seem to be much magic to the ProcessBuilder API that I'm missing. Can anyone see where my code is going wrong?
Shouldn't I be able to capture the exit code of the batch file?
I think there is something wrong (or different) with my PC. The Apache Commons Exec project source code I downloaded failed unit tests when capturing return codes. Looks to be unsolvable on my PC and haven't found a workaround.
I have a Java application.
The application has a setting that decides whether or not the application starts at startup.
Currently, I have it this by placing/removing a shortcut in the StartUp items folder.
However, I am wondering if there is a better way to handle this behaviour.
EDIT
Yes, it's Windows. Sorry for not clearing that before.
The application has an UI where the user may trigger actions, also the application runs a few tasks in the background periodically while running.
#Peter, how could I change the registry with code from within the application? Is that approach compatible with all versions of Windows?
Below is a small example snippet of how it can be done from inside your application
static final String REG_ADD_CMD = "cmd /c reg add \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\" /v \"{0}\" /d \"{1}\" /t REG_EXPAND_SZ";
private void exec(String[] args) throws Exception
{
if (args.length != 2)
throw new IllegalArgumentException("\n\nUsage: java SetEnv {key} {value}\n\n");
String key = args[0];
String value = args[1];
String cmdLine = MessageFormat.format(REG_ADD_CMD, new Object[] { key, value });
Runtime.getRuntime().exec(cmdLine);
}
I'm pretty sure this will work with all versions of Windows since they all use the same Startup\Run registry entry.
Hope that helps! :)
Credit
On Windows I have used open source Java Service Wrapper to make our application as window service which you can setup automatic at startup.
What you need to do is to download latest wrapper.exe and create wrapper.config file put all the configuration like Main class any VM arument other parameters in defined standards and create a window service by this exe
Use the Registry to start your program at the startup and then it will be shown in the list provided by msconfig commnd through Run.
Use this registry path
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
I have build a Java command line application which consists of several moduls. So when you start the application via the command line, you have to pass one parameter and its options like this for example:
cmd-> java -jar application -startModul1 option1 folderPath
OR
cmd-> java -jar application -startModul5 500 folderPath 1222
Currently I have to start each modul by starting the application and passing the requested parameter+options. For now thats finde but later, when I have lets say 20 modules, I want to generate a proccess chain with several moduls started one after the other.
For example at the end I could start both modules from the example above with just one command.
cmd-> java -jar application -startAllModules option1 500 folderPath 1222
Is there a framework, where I can generate such a proccess chain with existing command line modules? This should not be NOTHING programatically because I want to have some sort of xml-file or whatever, where I just configure a process chain and where I can select the modules and its parameters that should be run with one command.
Have you thought of turning your program into an interpreter?
I think that parsing your command line, understanding what simple commands it must execute (from the xml you want to use) and launching them is enough.
How to launch them?
Process p = Runtime.exec(String[] cmdarray)
where cmdarray will have each of the words of the command:
{"java", "-jar", "application", "-startModul1", "option1", "folderPath"}
and
p.waitFor();
if you want this thread to wait until launched command ends.
Update: non concurrent
The later was in case you want to run several independent processes in parallel. One for command you need.
In case you only need to execute them one after the another there's a more simply way. When the main realizes it must execute multi modules, it calls itself with the appropiate arguments.
public static void main(String[] args) throws Exception {
// parse params
if (it's a multi module command line) {
for (each module you have to execute) {
main(new String[] {"-startModule1", ..., ...}); // call myself with different args
}
}
else {
// execute what you've been asked for
}
}
I have a python compiled script (script.pyc , I haven't the .py file)that work well from my windows command prompt, and I want to execute it from my Java's application.
I tried to use runtime() method :
Runtime runtime = Runtime.getRuntime();
runtime.exec(new String[] {"C:\\toto\\tools\\script.pyc" ,"arg","arg2" });
but I get an error :
Exception in thread "main" java.io.IOException: Cannot run program "C:\Nuance\VoCon Hybrid\SDK_v4_3\tools\clctodict.pyc": CreateProcess error=193, %1 n?est pas une application Win32 valid
The script work well in my terminal ("arg" is a txt file, "arg2" is the output name, and the script does its job without any problem).
I also try to launch my script with getDesktop() :
File fie = new File("C:\\toto\\tools\\script.pyc" ,"arg","arg2");
Desktop.getDesktop().open(fie);
There is no problem, but I can't add argument, so I can just see a terminal windows opening during a few second before disappearing instantly.
I have also tried to use JPython, without success too (maybe we can't use methode "execfile" on a .pyc????)
You can do something like
Process p = Runtime.getRuntime().exec(new String[]{"python.exe" ... other args)
Then you can invoke p.waitFor() to wait for the end of the process and p.exitValue() to test if the program exited successfully.
You can also get the output stream via p.getOutputStream() to retrieve the text printed by your python script
Please refer to the class documentation for further information : http://docs.oracle.com/javase/6/docs/api/java/lang/Process.html
Just like you need a jvm to run a .class, you need a python interpreter to run a .pyc.
Try something like:
runtime.exec(new String[] {"c:\\Python26\\bin\\python.exe", "C:\\toto\\tools\\script.pyc" ,"arg","arg2" });