[Schmitzm-commits] r2180 - in trunk/schmitzm-core/src/main/java/de/schmitzm: io lang swing

scm-commit at wald.intevation.org scm-commit at wald.intevation.org
Sun Dec 23 15:11:01 CET 2012


Author: mojays
Date: 2012-12-23 15:11:01 +0100 (Sun, 23 Dec 2012)
New Revision: 2180

Modified:
   trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtil.java
   trunk/schmitzm-core/src/main/java/de/schmitzm/lang/LangUtil.java
   trunk/schmitzm-core/src/main/java/de/schmitzm/swing/SwingUtil.java
Log:
IOUtil.determineCommandLineParametersIndex(.), .removeCommandLineParametersFromCommand(.), .getCommandLineParametersFromCommand(.): methods to determine/remove command line arguments from command
IOUtil.createApplicationStartCommand(.) create complete command to (re)start the running application from command line
IOUtil.getApplicationMainClass(): determine the initial starting class of running application
SwingUtil.STARTING_CLASS: holds the initial starting class of running application (even if starting thread already has terminated)
LangUtil.getLastStackTraceClasses(.): handle "depth < 0" (complete stack trace)



Modified: trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtil.java
===================================================================
--- trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtil.java	2012-12-22 23:18:09 UTC (rev 2179)
+++ trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtil.java	2012-12-23 14:11:01 UTC (rev 2180)
@@ -78,12 +78,14 @@
 import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.lang.SystemUtils;
+import org.apache.log4j.Level;
 import org.apache.log4j.Logger;
 
 import de.schmitzm.console.CharacterDevice;
 import de.schmitzm.console.ConsoleDevice;
 import de.schmitzm.console.TextDevice;
 import de.schmitzm.lang.LangUtil;
+import de.schmitzm.swing.SwingUtil;
 
 /**
  * Diese Klasse stellt statische Methoden fuer die Ein/Ausgabe zur Verfuegung.
@@ -95,7 +97,9 @@
  */
 public class IOUtil {
 	private static Logger LOGGER = Logger.getLogger(IOUtil.class.getName());
-
+	static {
+	  LangUtil.initializeDefaultLogger(Level.DEBUG, null);
+	}
 	/**
 	 * Liefert den Index des Dateinames, an der die Dateinamen-Erweiterung
 	 * (inkl. Punkt) beginnt.
@@ -2222,22 +2226,203 @@
       return file;
 	}
 	
+	
+    /**
+     * Returns all command line arguments from command.
+     */
+    public static String getCommandLineParametersFromCommand(String commandStr) {
+      int idx = determineCommandLineParametersIndex(commandStr);
+      return idx > 0 ? commandStr.substring(idx).trim() : "";
+    }
+
+    /**
+     * Removes all command line arguments from command.
+     */
+    public static String removeCommandLineParametersFromCommand(String commandStr) {
+      int idx = determineCommandLineParametersIndex(commandStr);
+      return idx > 0 ? commandStr.substring(0, idx).trim() : commandStr;
+    }
+    
 	/**
-	 * Returns the command (incl. path) the runnding application (JAR, EXE, etc.)
-	 * was started by. 
+	 * Determines the index in a command, where the command line arguments 
+	 * begin.
+	 * @return -1 if command does not contain command line arguments
 	 */
-	public static String getApplicationCommand() {
-	  String startCommand = System.getProperty("sun.java.command");
-	  // TODO: Remove Command line arguments from startCommand
+	public static int determineCommandLineParametersIndex(String commandStr) {
+	  // Because command and command line parameters can not be separated
+	  // simply by first occurrence of white space (windows paths can contain
+	  // spaces in folder names!), we successively cut the command at the
+	  // last white space occurrence and check whether an existing file
+	  // oder class results...
+	  int i = commandStr.length(); // start with complete command string   
+	  do {
+	    commandStr = commandStr.substring(0, i);
+        try {
+          // Try to create file from string and check whether
+          // it exists
+          if ( new File(commandStr).exists() )
+            return i;
+        } catch (Exception e) {
+          // File can not be created
+        }
 
-	  // if application was started by "java ..." the system property only
-	  // contains the jar file!
-	  // -> extend command by "javaw" and application path 
-	  if ( startCommand.toLowerCase().endsWith("jar") )
-	    startCommand = "javaw "+getApplicationDirectory().getAbsolutePath() + File.separatorChar + startCommand;
+        try {
+          // Maybe command does not represent a file, but a class
+          // from classpath, so we also check this
+	      Class.forName(commandStr);
+	      return i;
+	    } catch (Exception e) {
+	      // Class can not be created
+        }
+
+	    i = commandStr.lastIndexOf(' ');
+	  } while (i > 0);
+	    
+	  // No existing file or class available
+	  return -1;
+	}
+	
+    /**
+     * Returns starting class (with {@code main(.)}-method of the running application.
+     */
+    public static Class getApplicationMainClass() {
+      // if main class already determined, use it
+      if ( SwingUtil.STARTING_CLASS != null )
+        return SwingUtil.STARTING_CLASS;
+      try {
+        String mainClassName = getApplicationMainClassName();
+        return mainClassName != null ? Class.forName(mainClassName) : null;
+      } catch (ClassNotFoundException err) {
+        // Should definitly not occur!!
+        throw new RuntimeException(err);
+      }
+    }
+
+    /**
+     * Returns starting class (with {@code main(.)}-method of the running application.
+     */
+    public static String getApplicationMainClassName() {
+      // if main class already determined, use it
+      if ( SwingUtil.STARTING_CLASS != null )
+        return SwingUtil.STARTING_CLASS.getName();
+      // determine main method from running threads
+      for (Thread t : Thread.getAllStackTraces().keySet()) {
+        for (StackTraceElement ste : t.getStackTrace()) {
+//          System.out.println(t.getName()+"; "+ste.getClassName()+"; "+ste.getFileName()+"; "+ste.getMethodName());
+          if ( "main".equals(ste.getMethodName()) )
+            return ste.getClassName();
+        } 
+      }
+      // no main method (anymore) for no running thread
+      // -> starting class can not be determined anymore :-(
+      return null;
+    }
+
+    /**
+     * Returns the start command from system properties ("sun.java.command"). 
+     */
+    public static String getApplicationCommand() {
+      String startCommand = System.getProperty("sun.java.command");
+      return startCommand;
+    }
+    
+    /**
+     * Reconstructs the complete command line command (incl. path, java call, etc.) to (re)run
+     * the running application (JAR, EXE, etc.) from command line.
+     */
+    public static String createApplicationStartCommand(boolean inclParams) {
+      return createApplicationStartCommand(inclParams, null);
+    }
+
+    /**
+	 * Reconstructs the complete command line command (incl. path, java call, etc.) to (re)run
+	 * the running application (JAR, EXE, etc.) from command line.
+	 * @param inclParams indicates whether the start parameters of the running application should
+	 *                   be included in created command
+	 * @param javaPrg java programm (e.g. "java" or "javaw") added to start command when application
+	 *                was started from JAR or classpath (if {@code null}, "javaw" is used)
+	 */
+	public static String createApplicationStartCommand(boolean inclParams, String javaPrg) {
+	  if ( javaPrg == null )
+	    javaPrg = "javaw";
+	  javaPrg = javaPrg.trim();
+      // if application was started on Windows OS surround java command
+      // with quotation marks
+      if ( SystemUtils.IS_OS_WINDOWS && javaPrg.indexOf(' ')>0 && !javaPrg.startsWith("\"") )
+        javaPrg = "\""+javaPrg+"\"";
+
+      // determine command from system property
+	  String startCommand = getApplicationCommand();
+//	  LOGGER.debug("Command: "+startCommand);
+	  // Cases:
+	  // a) application run from Windows EXE
+	  //    -> startCommand contains the complete path, e.g.
+	  //       "C:\MyApps\MyApp.exe -param1 param2"
+	  // b) application run from JAR
+      //    -> startCommand only contains the jar name, only with relative path, e.g.
+	  //       if called from C:\:
+      //       "MyApps\MyApp.jar -param1 param2"
+      // c) application run from class path (e.g. Eclipse)
+      //    -> startCommand only contains the main class, without path, e.g.
+      //       "com.me.apps.MyApp -param1 param2"
 	  
+	  // determine parameters from command
+	  String params = "";
+	  String startCommandWithoutParams = startCommand;
+	  int idx = determineCommandLineParametersIndex(startCommand);
+	  if ( idx > 0 ) {
+	    params = startCommand.substring(idx).trim();
+	    startCommandWithoutParams = startCommand.substring(0,idx).trim();
+	  }
+//      LOGGER.debug("Command without params: "+startCommandWithoutParams);
+//      LOGGER.debug("Parameter: "+params);
+	  
+      // determine starting class
+	  String mainClassName = getApplicationMainClassName();
+	  
+	  boolean startedFromJAR        = startCommandWithoutParams.toLowerCase().endsWith(".jar");
+      boolean startedFromClasspath  = startCommandWithoutParams.toLowerCase().endsWith(mainClassName);
+      boolean startedFromExecutable = !startedFromJAR && !startedFromClasspath;
+	  
+	  // if application was started from JAR file the system property only
+	  // contains the jar file (with relative path)!
+	  // -> extend command by application path 
+	  if ( startedFromJAR ) {
+// Problem, when startCommandWithParams alreads is absolut path!
+//	    startCommandWithoutParams = getApplicationDirectory().getAbsolutePath() + File.separatorChar + startCommandWithoutParams;
+	    // using "File" object automatically handles the case that
+	    // startCommandWithoutParams already is absolut path!
+	    startCommandWithoutParams = new File(startCommandWithoutParams).getAbsolutePath();
+	  }
+	  // if application was started from JAR, remove the possible
+	  // main class information from parameters because this is part
+	  // of the start command and no real command line parameter for the
+	  // application
+      if ( startedFromJAR && params.startsWith(mainClassName) )
+        params = params.substring(mainClassName.length()).trim();
+	  // if application was started on Windows OS surround command
+	  // with quotation marks
+	  if ( !startedFromClasspath && SystemUtils.IS_OS_WINDOWS &&
+	      startCommandWithoutParams.indexOf(' ')>0 && !startCommandWithoutParams.startsWith("\"") )
+	    startCommandWithoutParams = "\""+startCommandWithoutParams+"\"";
+      // if application was started from jar file or class path extend command
+	  // by "javaw" (and "-jar")   
+	  if ( startedFromClasspath || startedFromJAR ) {
+	    String javaCommand = javaPrg;
+	    if ( startedFromJAR )
+	      javaCommand += " -jar";
+        startCommandWithoutParams = javaCommand + " "+startCommandWithoutParams;
+	  }
+      // if application was started from jar file add also the main class for
+	  // the case the main class is not included in MANIFEST file
+      if ( startedFromJAR ) 
+        startCommandWithoutParams += " " + mainClassName;
+
+      // Return complete start command (with parameters) 
+      startCommand = startCommandWithoutParams;
+      if ( inclParams )
+        startCommand += " " + params;
+//      LOGGER.debug("Start command: "+startCommand);
 	  return startCommand;
 	}
-	
-
 }

Modified: trunk/schmitzm-core/src/main/java/de/schmitzm/lang/LangUtil.java
===================================================================
--- trunk/schmitzm-core/src/main/java/de/schmitzm/lang/LangUtil.java	2012-12-22 23:18:09 UTC (rev 2179)
+++ trunk/schmitzm-core/src/main/java/de/schmitzm/lang/LangUtil.java	2012-12-23 14:11:01 UTC (rev 2180)
@@ -2008,7 +2008,8 @@
 	 * @param stackTrace
 	 *            stack trace to explore
 	 * @param depth
-	 *            maximum count of classes, which are explored in the stack trace
+	 *            maximum count of classes, which are explored in the stack trace (-1 for complete 
+	 *            stack trace)
 	 */
 	public static String[] getLastStackTraceClasses(StackTraceElement[] stackTrace, int depth) {
 		Vector<String> lastClasses = new Vector<String>();
@@ -2016,7 +2017,7 @@
 			String className = st.getClassName();
 			if (!lastClasses.contains(className))
 				lastClasses.add(className);
-			if (lastClasses.size() >= depth)
+			if (depth > 0 && lastClasses.size() >= depth)
 				break;
 		}
 		return lastClasses.toArray(new String[0]);

Modified: trunk/schmitzm-core/src/main/java/de/schmitzm/swing/SwingUtil.java
===================================================================
--- trunk/schmitzm-core/src/main/java/de/schmitzm/swing/SwingUtil.java	2012-12-22 23:18:09 UTC (rev 2179)
+++ trunk/schmitzm-core/src/main/java/de/schmitzm/swing/SwingUtil.java	2012-12-23 14:11:01 UTC (rev 2180)
@@ -157,6 +157,16 @@
  * @version 1.1
  */
 public class SwingUtil {
+    /** Even if the initial application thread already has terminated, this field should
+     *  hold the {@link Class} (with the main method) which started the (swing) application.<br>
+     *  <b>Note:</b> This field expects (hopes!) that {@link SwingUtil} class is referenced
+     *  in any case before the initial thread terminates. "Normally" this should be the case,
+     *  because {@link SwingUtil} is a very common class for SCHMITZM projects, which is
+     *  referenced very often, especially during main frame initialization.  
+     */
+    public static final Class STARTING_CLASS = IOUtil.getApplicationMainClass();
+  
+  
 	private static final Logger LOGGER = Logger.getLogger(SwingUtil.class
 			.getClass().getName());
 



More information about the Schmitzm-commits mailing list