[Schmitzm-commits] r2400 - in trunk: schmitzm-core/src/main/java/de/schmitzm/io schmitzm-core/src/main/resources/de/schmitzm/io/resource schmitzm-hibernate/src/main/java/de/schmitzm/db/hibernate

scm-commit at wald.intevation.org scm-commit at wald.intevation.org
Sat Mar 29 02:33:55 CET 2014


Author: mojays
Date: 2014-03-29 02:33:55 +0100 (Sat, 29 Mar 2014)
New Revision: 2400

Added:
   trunk/schmitzm-core/src/main/resources/de/schmitzm/io/resource/Elevate-x64.exe
   trunk/schmitzm-core/src/main/resources/de/schmitzm/io/resource/Elevate-x86.exe
Modified:
   trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtil.java
   trunk/schmitzm-hibernate/src/main/java/de/schmitzm/db/hibernate/HibernateApplication.java
Log:
IOUtil: method execCmdAsAdmin(.) to run a Windows shell script "as administrator" (using elevate.exe)
IOUtil: methods to check, start and stop a Windows OS service
HibernateApplication: methods to check and ensure that the database service is running (currently only for Windows OS)

Modified: trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtil.java
===================================================================
--- trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtil.java	2014-02-10 18:10:44 UTC (rev 2399)
+++ trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtil.java	2014-03-29 01:33:55 UTC (rev 2400)
@@ -3006,20 +3006,144 @@
 	  Process process= Runtime.getRuntime().exec(script);
 	  String output = convertStreamToString(process.getInputStream());
 	  return output;
+	}
+	
+
+    /**
+     * Executes a Windows (shell) script via {@link Runtime#exec(String[]) Runtime.exec("cmd.exe", "/c", ...)}
+     * and returns the process output as string.
+     * @return {@code null} if program is not running on Windows OS 
+     */
+	public static String execCmd(String... script) throws IOException {
+	  if (!SystemUtils.IS_OS_WINDOWS)
+	    return null;
+	  String[] cmdScript = new String[script.length+2];
+	  cmdScript[0] = "cmd.exe";
+	  cmdScript[1] = "/c";
+	  for (int i=0; i<script.length; i++)
+	    cmdScript[i+2] = script[i];
+	  return exec(cmdScript);
+	}
+	
+    /**
+     * Executes a Windows (shell) script "as administrator" (using 'elevate.exe') via
+     * {@link Runtime#exec(String[]) Runtime.exec("cmd.exe", "/c", "elevate.exe", ...)}
+     * and returns the process output as string.
+     * @return {@code null} if program is not running on Windows OS 
+     */
+    public static String execCmdAsAdmin(String... script) throws IOException {
+      if (!SystemUtils.IS_OS_WINDOWS)
+        return null;
+      File elevateFile = checkElevateAvailable();
+      if ( elevateFile == null )
+        throw new IOException("Command can not be executed as administrator. elevate.exe not available!");
+      String[] elevateScript = new String[script.length+1];
+      elevateScript[0] = elevateFile.getAbsolutePath();
+      for (int i=0; i<script.length; i++)
+        elevateScript[i+1] = script[i];
+      return execCmd(elevateScript);
+    }
+
+    /**
+     * Only for Windows OS. Checks whether the 'elevate.exe' (which is used to execute commands
+     * "as administrator") is available in user temp directory. If not the 'elevate.exe' is
+     * copied from resource path to temp directory. 
+     * @return the existing 'elevate.exe' file in temp directory or {@code null} if 'elevate.exe'
+     *         is not available or program in not running on Windows OS   
+     */
+    public static File checkElevateAvailable() throws IOException {
+      if ( !SystemUtils.IS_OS_WINDOWS )
+        return null;
+      File localFile = new File(getTempDir(), "Elevate.exe");
+      if ( localFile.exists() )
+        return localFile;
+      
+      String elevateFileName = "Elevate-x86.exe"; // TODO: u.U. fuer 64-bit-System Elevate-x64.exe verwenden
+      URL elevateURL = IOUtil.class.getResource("resource/"+elevateFileName);
+      // Datei in lokales Verzeichnis kopieren
+      FileUtils.copyURLToFile(elevateURL, localFile);
+      if ( !localFile.exists() )
+        return null;
+      return localFile;
+    }
+    
+	/**
+	 * Checks whether a Windows service is running.
+	 * @param serviceName service name
+	 * @return {@code false} if program is not running on Windows OS
+	 */
+	public static boolean isWindowsServiceRunning(String serviceName) throws IOException {
+	  if ( StringUtils.isBlank(serviceName) || !SystemUtils.IS_OS_WINDOWS )
+	    return( false );
 	  
-//      String APP_SERVICE_NAME = "postgresql-x64-9.1";
-//      String SERVICE_NAME = "postgresql-x64-9.1";
-//      String[] scriptCheck = {"cmd.exe", "/c", "sc", "query", APP_SERVICE_NAME, "|", "find", "/C", "\"RUNNING\""};//to check whether service is running or not
-//
-//      String[] scriptStart = {"cmd.exe", "/c", "sc", "start", SERVICE_NAME};//to start service
-//
-//      String[] scriptStop = {"cmd.exe", "/c", "sc", "stop", SERVICE_NAME};//to stop service
-//      String  res = IOUtil.exec(scriptCheck);
-//      System.out.println(res);
-//      if ( "0".equals(res.trim()) ) {
-//        res = IOUtil.exec(scriptStart);
-//        System.out.println(res);
-//      }
+	  String[] scriptCheck = {"sc", "query", serviceName, "|", "find", "/C", "\"RUNNING\""};
+	  String   res = IOUtil.execCmd(scriptCheck);
+      LOGGER.debug("check service '"+serviceName+"': "+res);
+      return "1".equals(res.trim());
+	}
+
+	/**
+	 * Stops a Windows service. Does nothing if program is not running on
+	 * Windows OS.
+     * @param serviceName service name
+	 * @return {@code true} only if service was stopped successfully or {@code false} if
+	 *         service was not running or program is not running on Windows OS.
+	 */
+	public static boolean stopWindowsService(String serviceName) throws IOException {
+	  if ( StringUtils.isBlank(serviceName) || !SystemUtils.IS_OS_WINDOWS )
+	    return( false );
+	  if ( !isWindowsServiceRunning(serviceName) )
+	    return false;
+	  // stop service
+	  String[] scriptStop = {"sc", "stop", serviceName};
+      String   res = IOUtil.execCmdAsAdmin(scriptStop);
+      LOGGER.debug("stop service '"+serviceName+"': "+res);
+//    return "".equals(res.trim());
+      // Check whether service is not running anymore, but... give the OS
+      // some seconds for the stopping process...
+      try {
+        Thread.sleep(2000);
+      } catch (InterruptedException e) {
+      }
+      return !isWindowsServiceRunning(serviceName);
 	  
-	}	
+	}
+
+    /**
+     * (Re)Starts a Windows service. Does nothing if program is not running on
+     * Windows OS.
+     * @param serviceName service name
+     * @param restart     indicates whether an already running service is restarted
+     * @return {@code true} only if service was (re)started successfully or {@code false} if
+     *         service was already running and restart flag was not set or if program
+     *         is not running on Windows OS.
+     */
+	public static boolean startWindowsService(String serviceName, boolean restart) throws IOException {
+      if ( StringUtils.isBlank(serviceName) || !SystemUtils.IS_OS_WINDOWS )
+        return( false );
+      // if service is already running, do nothing or stop service first (if
+      // restart flag is set)
+      if ( isWindowsServiceRunning(serviceName) ) {
+        if ( !restart )
+          return false;
+        stopWindowsService(serviceName);
+      }
+      // start service
+//    String[] scriptStart = {"sc", "start", serviceName}; // --> PERMISSION DENIED
+//    String[] scriptStart = {"runas.exe", "/user:administrator", "\"sc start "+serviceName+"\""}; // --> ASKS FOR PASSWORD
+//    String   res = IOUtil.execCmd(scriptStart);
+      String[] scriptStart = {"sc", "start", serviceName};
+      String   res = IOUtil.execCmdAsAdmin(scriptStart);
+      LOGGER.debug("start service '"+serviceName+"': "+res);
+//      return "".equals(res.trim());
+      // Check whether service is running now, but... give the OS
+      // some seconds for the starting process...
+      try {
+        Thread.sleep(2000);
+      } catch (InterruptedException e) {
+      }
+      return isWindowsServiceRunning(serviceName);
+	}
+
+
 }

Added: trunk/schmitzm-core/src/main/resources/de/schmitzm/io/resource/Elevate-x64.exe
===================================================================
(Binary files differ)


Property changes on: trunk/schmitzm-core/src/main/resources/de/schmitzm/io/resource/Elevate-x64.exe
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: trunk/schmitzm-core/src/main/resources/de/schmitzm/io/resource/Elevate-x86.exe
===================================================================
(Binary files differ)


Property changes on: trunk/schmitzm-core/src/main/resources/de/schmitzm/io/resource/Elevate-x86.exe
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Modified: trunk/schmitzm-hibernate/src/main/java/de/schmitzm/db/hibernate/HibernateApplication.java
===================================================================
--- trunk/schmitzm-hibernate/src/main/java/de/schmitzm/db/hibernate/HibernateApplication.java	2014-02-10 18:10:44 UTC (rev 2399)
+++ trunk/schmitzm-hibernate/src/main/java/de/schmitzm/db/hibernate/HibernateApplication.java	2014-03-29 01:33:55 UTC (rev 2400)
@@ -30,11 +30,16 @@
 package de.schmitzm.db.hibernate;
 
 import java.awt.Frame;
+import java.io.IOException;
 
 import javax.swing.JOptionPane;
 
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang.SystemUtils;
+
 import de.schmitzm.db.hibernate.gui.GUIUtil;
 import de.schmitzm.db.hibernate.gui.event.DatabaseUpdateEmitter;
+import de.schmitzm.io.IOUtil;
 import de.schmitzm.swing.Disposable;
 import de.schmitzm.swing.ExceptionDialog;
 import de.schmitzm.swing.SwingUtil;
@@ -168,7 +173,41 @@
       return ret;
   }
 
+  
   /**
+   * Ensures that the given database (Postgres) service is running.
+   * <b>Method only works on Windows OS and does nothing if program is not
+   * running on Windows OS. If not running on Windows OS the method always
+   * returns {@code true} because we expect that the service is running!</b>
+   * @param serviceName name of database service
+   * @return {@code true} if service was started or is already running; {@code false} if
+   *         service could not be started
+   */
+  public boolean checkDatabaseServiceRunning(String serviceName) throws IOException {
+    if ( isDatabaseServiceRunning(serviceName) )
+      return true;
+    return IOUtil.startWindowsService(serviceName, false);
+  }
+  
+  /**
+   * Checks whether the given database (Postgres) service is running.
+   * <b>Method only works on Windows OS and does nothing if program is not
+   * running on Windows OS. If not running on Windows OS the method always
+   * returns {@code true} because we expect that the service is running!</b>
+   * @param serviceName name of database service
+   * @return {@code true} if service is already running; {@code false} otherwise.
+   */
+  public boolean isDatabaseServiceRunning(String serviceName) throws IOException {
+    if ( !SystemUtils.IS_OS_WINDOWS )
+      return true; // expect that the service is running!
+    if ( StringUtils.isBlank(serviceName) )
+      return true; // no service specified -> we expect that the appropriate service is running!
+    if ( IOUtil.isWindowsServiceRunning(serviceName) )
+      return true;
+    return false;
+  }
+
+  /**
    * Creates a connection to the database, so that {@link #getSession()} returns an open session.
    * Does nothing if a connection already exists.
    * @return {@code false} if no new connection is established



More information about the Schmitzm-commits mailing list