Advertisement
Guest User

restarter

a guest
Jul 7th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1.  
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.lang.management.ManagementFactory;
  5. import java.util.List;
  6.  
  7. public class Restarter {
  8. /**
  9. * Sun property pointing the main class and its arguments.
  10. * Might not be defined on non Hotspot VM implementations.
  11. */
  12. public static final String SUN_JAVA_COMMAND = "sun.java.command";
  13.  
  14. /**
  15. * Restart the current Java application
  16. * @param runBeforeRestart some custom code to be run before restarting
  17. * @throws IOException
  18. */
  19. public static void restartApplication(Runnable runBeforeRestart) throws IOException {
  20. try {
  21. // java binary
  22. String java = System.getProperty("java.home") + "/bin/java";
  23. // vm arguments
  24. List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
  25. StringBuffer vmArgsOneLine = new StringBuffer();
  26. for (String arg : vmArguments) {
  27. // if it's the agent argument : we ignore it otherwise the
  28. // address of the old application and the new one will be in conflict
  29. if (!arg.contains("-agentlib")) {
  30. vmArgsOneLine.append(arg);
  31. vmArgsOneLine.append(" ");
  32. }
  33. }
  34. // init the command to execute, add the vm args
  35. final StringBuffer cmd = new StringBuffer("\"" + java + "\" " + vmArgsOneLine);
  36.  
  37. // program main and program arguments
  38. String[] mainCommand = System.getProperty(SUN_JAVA_COMMAND).split(" ");
  39. // program main is a jar
  40. if (mainCommand[0].endsWith(".jar")) {
  41. // if it's a jar, add -jar mainJar
  42. cmd.append("-jar " + new File(mainCommand[0]).getPath());
  43. } else {
  44. // else it's a .class, add the classpath and mainClass
  45. cmd.append("-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0]);
  46. }
  47. // finally add program arguments
  48. for (int i = 1; i < mainCommand.length; i++) {
  49. cmd.append(" ");
  50. cmd.append(mainCommand[i]);
  51. }
  52. // execute the command in a shutdown hook, to be sure that all the
  53. // resources have been disposed before restarting the application
  54. Runtime.getRuntime().addShutdownHook(new Thread() {
  55. @Override
  56. public void run() {
  57. try {
  58. Runtime.getRuntime().exec(cmd.toString());
  59. } catch (IOException e) {
  60. e.printStackTrace();
  61. }
  62. }
  63. });
  64. if (runBeforeRestart!= null) {
  65. runBeforeRestart.run();
  66. }
  67. System.exit(0);
  68. } catch (Exception e) {
  69. throw new IOException("Error while trying to restart the application", e);
  70. }
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement