Use java library from python (Python wrapper for java library) - java

I have a java library in jar form which can be used to extract data from files(excel,xml etc). As its in java, it can be used only in java applications. But i need the same library to be used for python projects as well.
I have tried py4j etc which takes the objects from jvm. But the library is not an executable and wont be 'run'. I have checked Jython but i need the library to be accessible from Python projects.
I have thought about using automated java to python translators, but i would take that as the last resort.
Please suggest some way i can accomplish this.

You can make a one class java program with a thread never ending until you send from Python a notification to do so.
This way the lib would be kept in memory and accessible from your Python program.
This class could be like this (add your needed lib import/init) :
public class TestPy {
private Thread thread;
public void die() {
synchronized (thread) {
thread.interrupt();
}
}
public TestPy() {
thread = new Thread(){
public void run() {
try {
while (!Thread.interrupted()) {
Thread.sleep(500);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
};
thread.start();
}
public static void main(String[] args) {
TestPy tp = new TestPy();
GatewayServer server = new GatewayServer(tp);
server.start();
}
}
You would have to launch the java program, use the lib, and then use the die() method to kill the java program in Python :
gateway = JavaGateway()
do your stuff here using the lib
tp = gateway.entry_point
tp.die()

You can write a simple command line Java program which calls the library and saves the results in a format you can read in Python, then you can call the program from Python using os.system.
Another option is to find Python libraries with equivalent functionality to the Java library: you can read excel, xml and other files in Python, that's not a problem.

I haven't learned how to create new instances of java class in a jar file by java constructors, but accidentally found that it's very easy to use any java static methods to access java objects in py2j.
step 1: download py4j zip file from https://pypi.python.org/pypi/py4j. "py4j0.10.0.jar" is in the zip file.
step 2: install py4j by
pip install 'D:\Downloads\py4j-0.10.0.zip'
step 3: add py4j0.10.0.jar as well as the_lib_you_use.jar (like owlapi-distribution-3.5.0.jar for the example below) to build path in your eclipse project
step 4: create AdditionApplication.java, and copy and paste the code of AdditionApplication.java at https://www.py4j.org/, and run Java application AdditionApplication.java
step 5: after running AdditoinApplication.java, test the example code in a python file:
if __name__ == '__main__':
pass
from py4j.java_gateway import JavaGateway
gateway = JavaGateway() # connect to the JVM
random = gateway.jvm.java.util.Random() # create a java.util.Random instance
number1 = random.nextInt(10) # call the Random.nextInt method
number2 = random.nextInt(10)
print(number1,number2)
(2, 7)
addition_app = gateway.entry_point # get the AdditionApplication instance
addition_app.addition(number1,number2) # call the addition method
Math = gateway.jvm.java.lang.Math
a = Math.max(4, 6);
print a
IRI = gateway.jvm.org.semanticweb.owlapi.model.IRI
abcIRI = IRI.create('fewf#fe')
print 'abcIRi = ' + str(abcIRI)
print 'abcIRI.getFragment() = ' + abcIRI.getFragment()
The result on console is :
(5, 0)
6
abcIRi = fewf#fe
abcIRI.getFragment() = fe

Related

pyspark: call a custom java function from pyspark. Do I need Java_Gateway?

I wrote the following MyPythonGateway.java so that I can call my custom java class from Python:
public class MyPythonGateway {
public String findMyNum(String input) {
return MyUtiltity.parse(input).getMyNum();
}
public static void main(String[] args) {
GatewayServer server = new GatewayServer(new MyPythonGateway());
server.start();
}
}
and here is how I used it in my Python code:
def main():
gateway = JavaGateway() # connect to the JVM
myObj = gateway.entry_point.findMyNum("1234 GOOD DAY")
print(myObj)
if __name__ == '__main__':
main()
Now I want to use MyPythonGateway.findMyNum() function from PySpark, not just a standalone python script. I did the following:
myNum = sparkcontext._jvm.myPackage.MyPythonGateway.findMyNum("1234 GOOD DAY")
print(myNum)
However, I got the following error:
... line 43, in main:
myNum = sparkcontext._jvm.myPackage.MyPythonGateway.findMyNum("1234 GOOD DAY")
File "/home/edamameQ/spark-1.5.2/python/lib/py4j-0.8.2.1-src.zip/py4j/java_gateway.py", line 726, in __getattr__
py4j.protocol.Py4JError: Trying to call a package.
So what did I miss here? I don't know if I should run a separate JavaApplication of MyPythonGateway to start a gateway server when using pyspark. Please advice. Thanks!
Below is exactly what I need:
input.map(f)
def f(row):
// call MyUtility.java
// x = MyUtility.parse(row).getMyNum()
// return x
What would be the best way to approach this? Thanks!
First of all the error you see usually means the class you're trying to use is not accessible. So most likely it is a CLASSPATH issue.
Regarding general idea there are two important issues:
you cannot access SparkContext inside an action or transformation so using PySpark gateway won't work (see How to use Java/Scala function from an action or a transformation? for some details)). If you want to use Py4J from the workers you'll have to start a separate gateways on each worker machine.
you really don't want to pass data between Python an JVM this way. Py4J is not designed for data intensive tasks.
In PySpark before start calling the method -
myNum = sparkcontext._jvm.myPackage.MyPythonGateway.findMyNum("1234 GOOD DAY")
you have to import MyPythonGateway java class as follows
java_import(sparkContext._jvm, "myPackage.MyPythonGateway")
myPythonGateway = spark.sparkContext._jvm.MyPythonGateway()
myPythonGateway.findMyNum("1234 GOOD DAY")
specify the jar containing myPackage.MyPythonGateway with --jars option in spark-submit
If input.map(f) has inputs as an RDD for example, this might work, since you can't access the JVM variable (attached to spark context) inside the executor for a map function of an RDD (and to my knowledge there is no equivalent for #transient lazy val in pyspark).
def pythonGatewayIterator(iterator):
results = []
jvm = py4j.java_gateway.JavaGateway().jvm
mygw = jvm.myPackage.MyPythonGateway()
for value in iterator:
results.append(mygw.findMyNum(value))
return results
inputs.mapPartitions(pythonGatewayIterator)
all you need to do is compile jar and add to pyspark classpath with --jars or --driver-class-path spark submit options. Then access class and method with below code-
sc._jvm.com.company.MyClass.func1()
where sc - spark context
Tested with Spark 2.3. Keep in mind, you can call JVM class method only from driver program and not executor.

Running a Python program in Java using Jython

I wrote a Python program that consists out of five .py script files.
I want to execute the main of those python scripts from within a Java Application.
What are my options to do so? Using the PythonInterpreter doesn't work, as for example the datetime module can't be loaded from Jython (and I don't want the user to determine his Python path for those dependencies to work).
I compiled the whole folder to .class files using Jython's compileall. Can I embed these .class files somehow to execute the main file from within my Java Application, or how should I proceed?
Have a look at the ProcessBuilder class in java: https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html.
The command used in the java constructor should be the same as what you would type in a command line. For example:
Process p = new ProcessBuilder("python", "myScript.py", "firstargument").start();
(the process builder does the same thing as the python subprocess module).
Have a look at running scripts through processbuilder
N.B. as for the Jython part of the question, if you go to the jython website (have a look at the FAQ section of their website www.jython.org). Check the entry "use jython from java".
I'm also interested in running Python code directly within Java, using Jython, and avoiding the need for an installed Python interpreter.
The article, 'Embedding Jython in Java Applications' explains how to reference an external *.py Python script, and pass it argument parameters, no installed Python interpreter necessary:
#pymodule.py - make this file accessible to your Java code
def square(value):
return value*value
This function can then be executed either by creating a string that
executes it, or by retrieving a pointer to the function and calling
its call method with the correct parameters:
//Java code implementing Jython and calling pymodule.py
import org.python.util.PythonInterpreter;
import org.python.core.*;
public class ImportExample {
public static void main(String [] args) throws PyException
{
PythonInterpreter pi = new PythonInterpreter();
pi.exec("from pymodule import square");
pi.set("integer", new PyInteger(42));
pi.exec("result = square(integer)");
pi.exec("print(result)");
PyInteger result = (PyInteger)pi.get("result");
System.out.println("result: "+ result.asInt());
PyFunction pf = (PyFunction)pi.get("square");
System.out.println(pf.__call__(new PyInteger(5)));
}
}
Jython's Maven/Gradle/etc dependency strings can be found at http://mvnrepository.com/artifact/org.python/jython-standalone/2.7.1
Jython JavaDoc
It is possible to load the other modules. You just need to specify the python path where your custom modules can be found. See the following test case and I am using the Python datatime/math modules inside my calling function (my_maths()) and I have multiple python files in the python.path which are imported by the main.py
#Test
public void testJython() {
Properties properties = System.getProperties();
properties.put("python.path", ".\\src\\test\\resources");
PythonInterpreter.initialize(System.getProperties(), properties, new String[0]);
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile(".\\src\\test\\resources\\main.py");
interpreter.set("id", 150); //set variable value
interpreter.exec("val = my_maths(id)"); //the calling function in main.py
Integer returnVal = (Integer) interpreter.eval("val").__tojava__(Integer.class);
System.out.println("return from python: " + returnVal);
}

Reading BSTR in JAVA through JACOB

I am trying to access a device through a COM object in a JAVA interface.
The particular call (as described by the manufacturer) is:
Name: ScanUSB
Parameters: [out] VARIANT* serialNumbers
Use: serialNumbers is a pointer to a VARIANT containing an array of BSTR.
The exact call doesn't matter, but I need to feed it a BSTR array through the Java interface. A VB demo for the COM interface simply does this with the commandlm_Co1.ScanUSB(snNum), with Dim snNum As Object = Nothing. The Items in snNum are then displayed in a dropdown menu.
I am trying to do this with JACOB, as I have had the most luck with communication. This is more or less what I am using:
import com.jacob.com.Variant;
import com.jacob.com.Dispatch;
public class JunoReader {
public JunoReader() {
Dispatch oOphirLink = new Dispatch("clsid:{--the id of the device here--}");
Variant snNum = new Variant();
Variant testing = Dispatch.call(oOphirLink,"ScanUSB", snNum);
println(testing);
}
}
When I run this, everything compiles properly and I can confirm that I am communicating with the device, but all I get back is the null Variant that I put in.
My question is: How can I feed a BSTR array to a COM object through a JAVA interface?
Thanks!
So, one month and zero free time later, I have an answer to my own question and that answer is "Use Python".
Python allows users to access COM objects with the comtypes module, effectively with a single command:
from comtypes.client import CreateObject
target_guid = CreateObject("{TARGET-COM-CLSID-HERE}")
This allows python to talk with whatever the COM object is, so there was none of the trouble that Java was giving me. The single line: target_guid.ScanUSB() produced (u'717610',), the serial number of the target device. Notice that Python has no trouble reading the Unicode produced by the COM object.
The second trick involves Python's COM server, generated with the win32com module. Because the COM servers can be registered to Windows, I don't have to worry about where the dll is located. All I need is the clsid. To build the python COM server, I followed the instructions for a "quick start to server side COM and Python". So what does it all look like?
Python code:
class OphirPyCOM:
_reg_clsid_ = "{PYTHON-COM-CLSID-HERE}"
_reg_desc_ = "Python COM server"
_reg_progid_ = "Python COM server"
_public_methods_ = [ 'Hello',
'ConnectOphir',
'ScanUSB', """More methods here"""
]
_public_attrs_ = ["""Some public attributes"""]
_readonly_attrs_ = ["""some read-only attributes"""]
def __init__(self):
"""some variables declared here"""
def Hello(self, who):
"""Verifies a connection"""
return "{PYTHON-COM-CLSID-HERE}" + str(who)
def ConnectOphir(self,clsid):
"""Connects to the target COM Object"""
from comtypes.client import CreateObject
self.target_guid = CreateObject(clsid)
return "OphirLMMeasurement object created."
def ScanUSB(self):
"""Communicates with the target device"""
self.connected_inst = self.target_guid.ScanUSB()
for i in range(0,len(self.connected_inst)):
self.inst_list.append(str(self.connected_inst[i]))
return self.inst_list
if __name__ == "__main__":
# use 'python com.py' to register the COM server
# use 'python com.py --unregister' to unregister it
print "Registering COM server..."
import win32com.server.register
win32com.server.register.UseCommandLine(OphirPyCOM)
We can run that with the command line and get it registered. Then we take the values over to Java with JACOB:
import com.jacob.com.Variant;
import com.jacob.com.Dispatch;
public class JunoReader {
String pyClsid = "{PYTHON-COM-CLSID-HERE}"; // This is where your python COM clsid goes
String opClsid = "{TARGET-COM-CLSID-HERE}"; // This is where your ultimate target clsid goes
public JunoReader() {
_pyClsid = "clsid:" + pyClsid
// This finds the COM object location:
Dispatch oOphirLink = new Dispatch(_pyClsid);
}
public String HandShake() {
String _talkBack = "is connected.";
Variant _handShake = Dispatch.call(oOphirLink,"Hello",_talkBack); // I am trying to look for the Juno...
return (_handShake.toString());
}
public String ConnectOphir() {
Variant _connectOphir = Dispatch.call(oOphirLink,"ConnectOphir", opClsid); // Connect to the target COM object
return (_connectOphir.toString());
}
public String ScanUSB() {
Variant _serialNumberList = Dispatch.call(oOphirLink,"ScanUSB"); // This scans the USB ports for devices
return (_serialNumberList.toString());
}
}
calling JunoReader.ScanUSB() produces: 717610, exactly like it is supposed to. Implementing the subsequent methods of the manufacturer dll allowed me to read data from this device into a Java applet. Problem solved.
A caveat: you may need to unregister the Python COM every time you change the change the source file and then re-register with a different clsid. Java was having a tough time establishing a connection to the updated code unless I used a new clsid every time I changed the file.
Why did I spend all this time typing this up? Because most of the advice related to reading native data types into Java involved some version of JNI and JNA. I spent weeks trying to get the tutorials to compile and didn't make any progress. On the other hand, I thought of this approach yesterday and can now communicate with my device through Java. The Python COM server provided a simple, straightforward way to interface Java with native applications. No UnsatisfiedLinkErrors, no Can't find librarys, no Classpath and JAVA_HOME issues. I didn't need to learn C or C++ and all the Python tutorials worked as described with no necessary modification.
To summarize, if you are having trouble reading native data types into Java, just set up a Python COM server and let Python's dynamic typing do the work for you.

Opening a TCL gui within Java code

I have a TCL file which uses Tcl's BWidget package that I've been using as a GUI for my program. I now want to be able to load up this GUI from a separate Java program. I've looked into Jacl and Swank, but they don't seem to do exactly what I want.
I've tried the following with Jacl but it's unable to evaluate the file. While debugging, I can see that it completes parsing my tcl file, but it throws an exception while parsing through the BWidget package tcl files. Here's my Java code:
Interp interp = new Interp();
try {
interp.evalFile("C:\\CTP\\Tcl\\LuxonCtp32.tcl");
} catch (TclException ex) {
int code = ex.getCompletionCode();
System.err.println("command returned bad error code: " + code);
} finally {
interp.dispose();
}
Any ideas on how I can accomplish what I want to do? Is it even possible?
Tcl itself can not display a GUI. It uses a plugin called Tk for that.
In the C reference implementation of Tcl you get Tk as well.
Tk has not been ported to Java, Tcl has.
You can not use Jacl to display Tk widgets, but TclBlend could do that, because TclBlend uses the C reference implementation of Tcl. That means that the user needs a working Tcl/Tk installation.
There are some problems with TclBlend and Tcl > 8.5 through, which result in a segfault.
IIRC you have to remove the conditional if around Tcl_FindNameOfExecutable in TclBlends C code (and compile it yourself).
Go to this site http://jtcl-project.github.io/jtcl/ and download now for the binary zip. Its a recent java tcl on github called Jtcl.
Unzip it and you will find a jar called jtcl-2.7.0.jar.
I am using Netbeans 8 my preference.
I add the jar into Project Library.
I create a java file called JTclHallo.java and this is the code.
package jtclhallo;
// import tcl.lang it belongs to jtcl-2.7.0 jar a must
import tcl.lang.*;
// Java wrapper to test JACL or JTCL.
public class JTclHallo {
public static void main(String []args) {
//Interp is a java class belonging to tcl.lang. Unrar the jtcl-2.7.0
Interp i = new Interp();
try {
//call your tcl file mine was swing.tcl from the E drive
i.eval("source E:/private/swing.tcl");
} catch (TclException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
For swing.tcl
package require java
set window [java::new javax.swing.JFrame]
$window setSize 600 400
$window setVisible true

How can I restart a Java application?

How can I restart a Java AWT application? I have a button to which I have attached an event handler. What code should I use to restart the application?
I want to do the same thing that Application.Restart() do in a C# application.
Of course it is possible to restart a Java application.
The following method shows a way to restart a Java application:
public void restartApplication()
{
final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
final File currentJar = new File(MyClassInTheJar.class.getProtectionDomain().getCodeSource().getLocation().toURI());
/* is it a jar file? */
if(!currentJar.getName().endsWith(".jar"))
return;
/* Build command: java -jar application.jar */
final ArrayList<String> command = new ArrayList<String>();
command.add(javaBin);
command.add("-jar");
command.add(currentJar.getPath());
final ProcessBuilder builder = new ProcessBuilder(command);
builder.start();
System.exit(0);
}
Basically it does the following:
Find the java executable (I used the java binary here, but that depends on your requirements)
Find the application (a jar in my case, using the MyClassInTheJar class to find the jar location itself)
Build a command to restart the jar (using the java binary in this case)
Execute it! (and thus terminating the current application and starting it again)
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
StringBuilder cmd = new StringBuilder();
cmd.append(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java ");
for (String jvmArg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
cmd.append(jvmArg + " ");
}
cmd.append("-cp ").append(ManagementFactory.getRuntimeMXBean().getClassPath()).append(" ");
cmd.append(Main.class.getName()).append(" ");
for (String arg : args) {
cmd.append(arg).append(" ");
}
Runtime.getRuntime().exec(cmd.toString());
System.exit(0);
}
}
Dedicated to all those who say it is impossible.
This program collects all information available to reconstruct the original commandline. Then, it launches it and since it is the very same command, your application starts a second time. Then we exit the original program, the child program remains running (even under Linux) and does the very same thing.
WARNING: If you run this, be aware that it never ends creating new processes, similar to a fork bomb.
Basically, you can't. At least not in a reliable way. However, you shouldn't need to.
The can't part
To restart a Java program, you need to restart the JVM. To restart the JVM you need to
Locate the java launcher that was used. You may try with System.getProperty("java.home") but there's no guarantee that this will actually point to the launcher that was used to launch your application. (The value returned may not point to the JRE used to launch the application or it could have been overridden by -Djava.home.)
You would presumably want to honor the original memory settings etc (-Xmx, -Xms, …) so you need to figure out which settings where used to start the first JVM. You could try using ManagementFactory.getRuntimeMXBean().getInputArguments() but there's no guarantee that this will reflect the settings used. This is even spelled out in the documentation of that method:
Typically, not all command-line options to the 'java' command are passed to the Java virtual machine. Thus, the returned input arguments may not include all command-line options.
If your program reads input from Standard.in the original stdin will be lost in the restart.
Lots of these tricks and hacks will fail in the presence of a SecurityManager.
The shouldn't need part
I recommend you to design your application so that it is easy to clean every thing up and after that create a new instance of your "main" class.
Many applications are designed to do nothing but create an instance in the main-method:
public class MainClass {
...
public static void main(String[] args) {
new MainClass().launch();
}
...
}
By using this pattern, it should be easy enough to do something like:
public class MainClass {
...
public static void main(String[] args) {
boolean restart;
do {
restart = new MainClass().launch();
} while (restart);
}
...
}
and let launch() return true if and only if the application was shut down in a way that it needs to be restarted.
Strictly speaking, a Java program cannot restart itself since to do so it must kill the JVM in which it is running and then start it again, but once the JVM is no longer running (killed) then no action can be taken.
You could do some tricks with custom classloaders to load, pack, and start the AWT components again but this will likely cause lots of headaches with regard to the GUI event loop.
Depending on how the application is launched, you could start the JVM in a wrapper script which contains a do/while loop, which continues while the JVM exits with a particular code, then the AWT app would have to call System.exit(RESTART_CODE). For example, in scripting pseudocode:
DO
# Launch the awt program
EXIT_CODE = # Get the exit code of the last process
WHILE (EXIT_CODE == RESTART_CODE)
The AWT app should exit the JVM with something other than the RESTART_CODE on "normal" termination which doesn't require restart.
Eclipse typically restarts after a plugin is installed. They do this using a wrapper eclipse.exe (launcher app) for windows. This application execs the core eclipse runner jar and if the eclipse java application terminates with a relaunch code, eclipse.exe restarts the workbench. You can build a similar bit of native code, shell script or another java code wrapper to achieve the restart.
Windows
public void restartApp(){
// This launches a new instance of application dirctly,
// remember to add some sleep to the start of the cmd file to make sure current instance is
// completely terminated, otherwise 2 instances of the application can overlap causing strange
// things:)
new ProcessBuilder("cmd","/c start /min c:/path/to/script/that/launches/my/application.cmd ^& exit").start();
System.exit(0);
}
/min to start script in minimized window
^& exit to close cmd window after finish
a sample cmd script could be
#echo off
rem add some sleep (e.g. 10 seconds) to allow the preceding application instance to release any open resources (like ports) and exit gracefully, otherwise the new instance could fail to start
sleep 10
set path=C:\someFolder\application_lib\libs;%path%
java -jar application.jar
sleep 10 sleep for 10 seconds
Just adding information which is not present in other answers.
If procfs /proc/self/cmdline is available
If you are running in an environment which provides procfs and therefore has the /proc file system available (which means this is not a portable solution), you can have Java read /proc/self/cmdline in order to restart itself, like this:
public static void restart() throws IOException {
new ProcessBuilder(getMyOwnCmdLine()).inheritIO().start();
}
public static String[] getMyOwnCmdLine() throws IOException {
return readFirstLine("/proc/self/cmdline").split("\u0000");
}
public static String readFirstLine(final String filename) throws IOException {
try (final BufferedReader in = new BufferedReader(new FileReader(filename))) {
return in.readLine();
}
}
On systems with /proc/self/cmdline available, this probably is the most elegant way of how to "restart" the current Java process from Java. No JNI involved, and no guessing of paths and stuff required. This will also take care of all JVM options passed to the java binary. The command line will be exactly identical to the one of the current JVM process.
Many UNIX systems including GNU/Linux (including Android) nowadays have procfs However on some like FreeBSD, it is deprecated and being phased out. Mac OS X is an exception in the sense that it does not have procfs. Windows also does not have procfs. Cygwin has procfs but it's invisible to Java because it's only visible to applications using the Cygwin DLLs instead of Windows system calls, and Java is unaware of Cygwin.
Don't forget to use ProcessBuilder.inheritIO()
The default is that stdin / stdout / stderr (in Java called System.in / System.out / System.err) of the started Process are set to pipes which allow the currently running process to communicate with the newly started process. If you want to restart the current process, this is most likely not what you want. Instead you would want that stdin / stdout / stderr are the same as those of the current VM. This is called inherited. You can do so by calling inheritIO() of your ProcessBuilder instance.
Pitfall on Windows
A frequent use case of a restart() function is to restart the application after an update. The last time I tried this on Windows this was problematic. When overwrote the application's .jar file with the new version, the application started to misbehave and giving exceptions about the .jar file. I'm just telling, in case this is your use case. Back then I solved the issue by wrapping the application in a batch file and using a magic return value from System.exit() that I queried in the batch file and had the batch file restart the application instead.
Although this question is old and answered, I've stumbled across a problem with some of the solutions and decided to add my suggestion into the mix.
The problem with some of the solutions is that they build a single command string. This creates issues when some parameters contain spaces, especially java.home.
For example, on windows, the line
final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
Might return something like this:C:\Program Files\Java\jre7\bin\java
This string has to be wrapped in quotes or escaped due to the space in Program Files. Not a huge problem, but somewhat annoying and error prone, especially in cross platform applications.
Therefore my solution builds the command as an array of commands:
public static void restart(String[] args) {
ArrayList<String> commands = new ArrayList<String>(4 + jvmArgs.size() + args.length);
List<String> jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments();
// Java
commands.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java");
// Jvm arguments
for (String jvmArg : jvmArgs) {
commands.add(jvmArg);
}
// Classpath
commands.add("-cp");
commands.add(ManagementFactory.getRuntimeMXBean().getClassPath());
// Class to be executed
commands.add(BGAgent.class.getName());
// Command line arguments
for (String arg : args) {
commands.add(arg);
}
File workingDir = null; // Null working dir means that the child uses the same working directory
String[] env = null; // Null env means that the child uses the same environment
String[] commandArray = new String[commands.size()];
commandArray = commands.toArray(commandArray);
try {
Runtime.getRuntime().exec(commandArray, env, workingDir);
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}
If you realy need to restart your app, you could write a separate app the start it...
This page provides many different examples for different scenarios:
http://www.rgagnon.com/javadetails/java-0014.html
Similar to Yoda's 'improved' answer, but with further improvements (both functional, readability, and testability). It's now safe to run, and restarts for as as many times as the amount of program arguments given.
No accumulation of JAVA_TOOL_OPTIONS options.
Automatically finds main class.
Inherits current stdout/stderr.
public static void main(String[] args) throws Exception {
if (args.length == 0)
return;
else
args = Arrays.copyOf(args, args.length - 1);
List<String> command = new ArrayList<>(32);
appendJavaExecutable(command);
appendVMArgs(command);
appendClassPath(command);
appendEntryPoint(command);
appendArgs(command, args);
System.out.println(command);
try {
new ProcessBuilder(command).inheritIO().start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private static void appendJavaExecutable(List<String> cmd) {
cmd.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java");
}
private static void appendVMArgs(Collection<String> cmd) {
Collection<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
String javaToolOptions = System.getenv("JAVA_TOOL_OPTIONS");
if (javaToolOptions != null) {
Collection<String> javaToolOptionsList = Arrays.asList(javaToolOptions.split(" "));
vmArguments = new ArrayList<>(vmArguments);
vmArguments.removeAll(javaToolOptionsList);
}
cmd.addAll(vmArguments);
}
private static void appendClassPath(List<String> cmd) {
cmd.add("-cp");
cmd.add(ManagementFactory.getRuntimeMXBean().getClassPath());
}
private static void appendEntryPoint(List<String> cmd) {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
StackTraceElement stackTraceElement = stackTrace[stackTrace.length - 1];
String fullyQualifiedClass = stackTraceElement.getClassName();
String entryMethod = stackTraceElement.getMethodName();
if (!entryMethod.equals("main"))
throw new AssertionError("Entry point is not a 'main()': " + fullyQualifiedClass + '.' + entryMethod);
cmd.add(fullyQualifiedClass);
}
private static void appendArgs(List<String> cmd, String[] args) {
cmd.addAll(Arrays.asList(args));
}
V1.1 Bugfix: null pointer if JAVA_TOOL_OPTIONS is not set
Example:
$ java -cp Temp.jar Temp a b c d e
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a, b, c, d]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a, b, c]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a, b]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp]
$
I was researching the subject myself when came across this question.
Regardless of the fact that the answer is already accepted, I would still like to offer an alternative approach for completeness. Specifically, Apache Ant served as a very flexible solution.
Basically, everything boils down to an Ant script file with a single Java execution task (refer here and here) invoked from a Java code (see here). This Java code, which can be a method launch, could be a part of the application that needs to be restarted. The application needs to have a dependency on the Apache Ant library (jar).
Whenever application needs to be restarted, it should call method launch and exit the VM. The Ant java task should have options fork and spawn set to true.
Here is an example of an Ant script:
<project name="applaucher" default="launch" basedir=".">
<target name="launch">
<java classname="package.MasinClass" fork="true" spawn="true">
<jvmarg value="-splash:splash.jpg"/>
<jvmarg value="-D other VM params"/>
<classpath>
<pathelement location="lib-1.jar" />
...
<pathelement location="lib-n.jar" />
</classpath>
</java>
</target>
</project>
The code for the launch method may look something like this:
public final void launch(final String antScriptFile) {
/* configure Ant and execute the task */
final File buildFile = new File(antScriptFile);
final Project p = new Project();
p.setUserProperty("ant.file", buildFile.getAbsolutePath());
final DefaultLogger consoleLogger = new DefaultLogger();
consoleLogger.setErrorPrintStream(System.err);
consoleLogger.setOutputPrintStream(System.out);
consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
p.addBuildListener(consoleLogger);
try {
p.fireBuildStarted();
p.init();
final ProjectHelper helper = ProjectHelper.getProjectHelper();
p.addReference("ant.projectHelper", helper);
helper.parse(p, buildFile);
p.executeTarget(p.getDefaultTarget());
p.fireBuildFinished(null);
} catch (final BuildException e) {
p.fireBuildFinished(e);
}
/* exit the current VM */
System.exit(0);
}
A very convenient thing here is that the same script is used for initial application start up as well as for restarts.
Old question and all of that. But this is yet another way that offers some advantages.
On Windows, you could ask the task scheduler to start your app again for you. This has the advantage of waiting a specific amount of time before the app is restarted. You can go to task manager and delete the task and it stops repeating.
SimpleDateFormat hhmm = new SimpleDateFormat("kk:mm");
Calendar aCal = Calendar.getInstance();
aCal.add(Calendar.SECOND, 65);
String nextMinute = hhmm.format(aCal.getTime()); //Task Scheduler Doesn't accept seconds and won't do current minute.
String[] create = {"c:\\windows\\system32\\schtasks.exe", "/CREATE", "/F", "/TN", "RestartMyProg", "/SC", "ONCE", "/ST", nextMinute, "/TR", "java -jar c:\\my\\dev\\RestartTest.jar"};
Process proc = Runtime.getRuntime().exec(create, null, null);
System.out.println("Exit Now");
try {Thread.sleep(1000);} catch (Exception e){} // just so you can see it better
System.exit(0);
System.err.println("Someone is Restarting me...");
setVisible(false);
try {
Thread.sleep(600);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
setVisible(true);
I guess you don't really want to stop the application, but to "Restart" it. For that, you could use this and add your "Reset" before the sleep and after the invisible window.

Categories

Resources