Commit c3ae8c12 authored by Benedikt Kleinmeier's avatar Benedikt Kleinmeier Committed by dlehm

Encapsulated logic to parse CLI arguments into new class "VadereArgumentParser"

This new class is used by:

  - VadereApplication
  - VadereConsole
  - PostVisualization

Now, all Vadere applications have a unified interface to pass arguments on command line.

Watch out: The method "VadereConsole.addSubCommandsToParser()" should be moved to "VadereArgumentParser".
parent 1ae05e2b
package org.vadere.gui.postvisualization;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import org.vadere.gui.components.utils.Messages;
import org.vadere.gui.postvisualization.view.PostvisualizationWindow;
import org.vadere.gui.projectview.VadereApplication;
import org.vadere.util.io.VadereArgumentParser;
import org.vadere.util.logging.Logger;
import org.vadere.util.logging.StdOutErrLog;
public class PostVisualisation {
// TODO: Move logic to read/write config file to "VadereConfig.java".
private static Logger logger = Logger.getLogger(PostVisualisation.class);
public static void main(String[] args) {
StdOutErrLog.addStdOutErrToLog();
logger.info("starting post visualization ...");
// load settings
logger.info("preferences started");
// start main gui
logger.info("starting Vadere PostVisualization...");
VadereArgumentParser vadereArgumentParser = new VadereArgumentParser();
ArgumentParser argumentParser = vadereArgumentParser.getArgumentParser();
try {
vadereArgumentParser.parseArgsAndProcessOptions(args);
} catch (UnsatisfiedLinkError linkError) {
System.err.println("[LWJGL]: " + linkError.getMessage());
} catch (ArgumentParserException e) {
argumentParser.handleError(e);
System.exit(1);
} catch (Exception e) {
System.err.println("Cannot start vadere: " + e.getMessage());
e.printStackTrace();
System.exit(1);
}
Messages.loadLanguageFromPreferences(VadereApplication.class);
PostvisualizationWindow.start();
logger.info("post visualization started");
}
}
......@@ -42,9 +42,6 @@ import java.util.Optional;
/**
* Main Window of the new post visualization.
*
* @Version 1.0
*
*/
public class PostvisualizationWindow extends JPanel implements Observer, DropTargetListener {
private static final long serialVersionUID = -8177132133860336295L;
......
package org.vadere.gui.projectview;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import org.vadere.gui.components.utils.Messages;
import org.vadere.gui.projectview.view.ProjectView;
import org.vadere.util.config.VadereConfig;
import org.vadere.util.io.VadereArgumentParser;
import org.vadere.util.logging.Logger;
import org.vadere.util.logging.StdOutErrLog;
......@@ -20,10 +22,24 @@ public class VadereApplication {
StdOutErrLog.addStdOutErrToLog();
logger.info("starting Vadere GUI...");
// set locale
VadereArgumentParser vadereArgumentParser = new VadereArgumentParser();
ArgumentParser argumentParser = vadereArgumentParser.getArgumentParser();
try {
vadereArgumentParser.parseArgsAndProcessOptions(args);
} catch (UnsatisfiedLinkError linkError) {
System.err.println("[LWJGL]: " + linkError.getMessage());
} catch (ArgumentParserException e) {
argumentParser.handleError(e);
System.exit(1);
} catch (Exception e) {
System.err.println("Cannot start vadere: " + e.getMessage());
e.printStackTrace();
System.exit(1);
}
Messages.loadLanguageFromPreferences(VadereApplication.class);
// start main gui
ProjectView.start();
}
......
......@@ -158,12 +158,5 @@
<artifactId>meshing</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>net.sourceforge.argparse4j</groupId>
<artifactId>argparse4j</artifactId>
<version>0.4.3</version>
</dependency>
</dependencies>
</project>
This source diff could not be displayed because it is too large. You can view the blob instead.
package org.vadere.simulator.entrypoints.cmd;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import net.sourceforge.argparse4j.inf.Subparsers;
import net.sourceforge.argparse4j.inf.*;
import org.vadere.simulator.entrypoints.Version;
import org.vadere.simulator.entrypoints.cmd.commands.MigrationSubCommand;
import org.vadere.simulator.entrypoints.cmd.commands.ProjectRunSubCommand;
import org.vadere.simulator.entrypoints.cmd.commands.ScenarioRunSubCommand;
import org.vadere.simulator.entrypoints.cmd.commands.SuqSubCommand;
import org.vadere.simulator.utils.scenariochecker.ScenarioChecker;
import org.vadere.util.io.VadereArgumentParser;
import org.vadere.util.logging.Logger;
import org.vadere.util.logging.StdOutErrLog;
import java.util.Arrays;
/**
* Provides the possibility to start Vadere in console mode.
* Do not use Logging in this Class! The Logging framework needs information generated here
......@@ -29,62 +21,32 @@ public class VadereConsole {
public static void main(String[] args) {
Logger.setMainArguments(args);
// rimea_01_pathway_gnm1.scenario rimea_04_flow_gnm1_050_h.scenario
// String[] tmp = {"project-run", "-p", "/home/lphex/hm.d/vadere/VadereModelTests/TestOSM_Group_calibration"};
// args = tmp;
ArgumentParser parser = createArgumentParser();
VadereArgumentParser vadereArgumentParser = new VadereArgumentParser();
ArgumentParser argumentParser = vadereArgumentParser.getArgumentParser();
addSubCommandsToParser(argumentParser);
try {
//if (!CLUtils.isOpenCLSupported()) {
// System.out.println("Warning: OpenCL acceleration disabled, since no OpenCL support could be found!");
//}
Namespace ns = parser.parseArgs(args);
Namespace ns = vadereArgumentParser.parseArgsAndProcessOptions(args);
SubCommandRunner sRunner = ns.get("func");
StdOutErrLog.addStdOutErrToLog();
sRunner.run(ns, parser);
sRunner.run(ns, argumentParser);
} catch (UnsatisfiedLinkError linkError) {
System.err.println("[LWJGL]: " + linkError.getMessage());
} catch (ArgumentParserException e) {
parser.handleError(e);
argumentParser.handleError(e);
System.exit(1);
} catch (Exception e) {
System.err.println("topographyError in command:" + e.getMessage());
System.err.println("Cannot start vadere-console: " + e.getMessage());
e.printStackTrace();
System.exit(1);
}
}
private static ArgumentParser createArgumentParser() {
ArgumentParser parser = ArgumentParsers.newArgumentParser("Vadere")
.defaultHelp(true)
.description("Runs the VADERE pedestrian simulator.");
addOptionsToParser(parser);
addSubCommandsToParser(parser);
return parser;
}
private static void addOptionsToParser(ArgumentParser parser) {
// no action required call to Logger.setMainArguments(args) already configured Logger.
parser.addArgument("--loglevel")
.required(false)
.type(String.class)
.dest("loglevel")
.choices("OFF", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE", "ALL")
.setDefault("INFO")
.help("Set Log Level.");
// no action required call to Logger.setMainArguments(args) already configured Logger.
parser.addArgument("--logname")
.required(false)
.type(String.class)
.dest("logname")
.help("Write log to given file.");
}
// TODO: Move this method to "VadereArgumentParser".
private static void addSubCommandsToParser(ArgumentParser parser) {
Subparsers subparsers = parser.addSubparsers()
.title("subcommands")
......@@ -94,7 +56,7 @@ public class VadereConsole {
// Run Project
Subparser projectRun = subparsers
.addParser(SubCommand.PROJECT_RUN.getCmdName())
.help("This command uses a VADERE project and runs selected scenario.")
.help("This command uses a Vadere project and runs selected scenario.")
.setDefault("func", new ProjectRunSubCommand());
projectRun.addArgument("--project-dir", "-p")
.required(true)
......
......@@ -71,6 +71,11 @@
<classifier>${lwjgl.natives}</classifier>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.argparse4j</groupId>
<artifactId>argparse4j</artifactId>
<version>0.4.3</version>
</dependency>
</dependencies>
<!-- end generated by lwjgl -->
<profiles>
......@@ -102,4 +107,4 @@
</properties>
</profile>
</profiles>
</project>
\ No newline at end of file
</project>
......@@ -10,13 +10,11 @@ import org.apache.commons.configuration2.ex.ConfigurationException;
import org.vadere.util.logging.Logger;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
......@@ -42,14 +40,15 @@ public class VadereConfig {
// Static Variables
private static final Logger LOGGER = Logger.getLogger(VadereConfig.class);
private static final String CONFIG_FILENAME = "vadere.conf";
private static final String HOME_DIR = System.getProperty("user.home");
private static final String CONFIG_DIR = ".config";
private static final String DEFAULT_HOME_DIR = System.getProperty("user.home");
private static final String DEFAULT_CONFIG_DIR = ".config";
private static final Path PATH_TO_CONFIG_DIR = Path.of(HOME_DIR, CONFIG_DIR);
private static final Path PATH_TO_CONFIG = Path.of(HOME_DIR, CONFIG_DIR, CONFIG_FILENAME);
// Both variables must not be "final" so that we are able
// to inject another config file from CLI argument "--config-file myconfig.conf".
private static String CONFIG_FILENAME = "vadere.conf";
private static Path CONFIG_PATH = Path.of(DEFAULT_HOME_DIR, DEFAULT_CONFIG_DIR, CONFIG_FILENAME);
private static VadereConfig SINGLETON_INSTANCE = new VadereConfig();
private static VadereConfig SINGLETON_INSTANCE;
// Variables
private FileBasedConfiguration vadereConfig;
......@@ -58,10 +57,13 @@ public class VadereConfig {
private VadereConfig() {
createDefaultConfigIfNonExisting();
// If Vadere was started like "vadere-console.jar --config-file here.txt", search in current working directory.
String basePath = (CONFIG_PATH.getParent() == null) ? System.getProperty("user.dir") : CONFIG_PATH.getParent().toString() ;
PropertiesBuilderParameters propertiesParams = new Parameters()
.properties()
.setFileName(CONFIG_FILENAME)
.setBasePath(PATH_TO_CONFIG.getParent().toString());
.setBasePath(basePath);
FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
......@@ -71,26 +73,26 @@ public class VadereConfig {
try {
vadereConfig = builder.getConfiguration();
} catch (ConfigurationException ex) {
LOGGER.error(String.format("Error while reading config file \"%s\": %s", PATH_TO_CONFIG.toString(), ex.getMessage()));
LOGGER.error(String.format("Error while reading config file \"%s\": %s", CONFIG_PATH.toString(), ex.getMessage()));
LOGGER.info("Create and use default config");
}
}
private void createDefaultConfigIfNonExisting() {
try { // Ensure that config directory exists.
Files.createDirectories(PATH_TO_CONFIG_DIR);
Files.createDirectories(Path.of(DEFAULT_HOME_DIR, DEFAULT_CONFIG_DIR));
} catch (IOException ex) {
LOGGER.error(String.format("Cannot create directory: %s", PATH_TO_CONFIG));
LOGGER.error(String.format("Cannot create directory: %s", Path.of(DEFAULT_HOME_DIR, DEFAULT_CONFIG_DIR)));
}
if (Files.exists(PATH_TO_CONFIG) == false) {
if (Files.exists(CONFIG_PATH) == false) {
Map<String, String> defaultConfig = getDefaultConfig();
try {
LOGGER.info(String.format("Writing default config file: %s", PATH_TO_CONFIG));
LOGGER.info(String.format("Writing default config file: %s", CONFIG_PATH));
Files.write(
PATH_TO_CONFIG,
CONFIG_PATH,
defaultConfig
.entrySet()
.stream()
......@@ -98,12 +100,23 @@ public class VadereConfig {
.sorted(String::compareTo)
.collect(Collectors.toList()));
} catch (IOException e) {
LOGGER.error(String.format("Error while writing default config file \"%s\": %s", PATH_TO_CONFIG.toString(), e.getMessage()));
LOGGER.error(String.format("Error while writing default config file \"%s\": %s", CONFIG_PATH, e.getMessage()));
}
}
}
// Static Getters
// Static Setters
/**
* With this setter one can inject a different config file instead of using "~/.config/vadere.conf".
*
* @param configPath Path to config file.
*/
public static void setConfigPath(String configPath) {
CONFIG_PATH = Path.of(configPath);
CONFIG_FILENAME = CONFIG_PATH.getFileName().toString();
}
// Static Setters
/**
* Use Apache Common Configuration API on the returned object to retrieve Vadere's config options.
*
......@@ -112,6 +125,10 @@ public class VadereConfig {
* @return A Configuration object from Apache Common Configuration library.
*/
public static Configuration getConfig() {
if (SINGLETON_INSTANCE == null) {
SINGLETON_INSTANCE = new VadereConfig();
}
return SINGLETON_INSTANCE.vadereConfig;
}
......
package org.vadere.util.io;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
import org.vadere.util.config.VadereConfig;
/**
* This class provides the functionality to parse command line arguments
* and should be used by all Vadere end-user applications, i.e.:
*
* - VadereApplication
* - VadereConsole
* - PostVisualizationWindow
*/
public class VadereArgumentParser {
// Variables
public ArgumentParser argumentParser;
// Constructors
public VadereArgumentParser() {
argumentParser = ArgumentParsers.newArgumentParser("Vadere")
.defaultHelp(true)
.description("Runs the Vadere pedestrian simulator.");
addOptionsToParser(argumentParser);
}
// Getters
public ArgumentParser getArgumentParser() {
return argumentParser;
}
// Methods
public Namespace parseArgsAndProcessOptions(String[] args) throws ArgumentParserException {
Namespace namespace = argumentParser.parseArgs(args);
String configFile = namespace.getString("configfile");
if (configFile != null) {
VadereConfig.setConfigPath(configFile);
}
return namespace;
}
private void addOptionsToParser(ArgumentParser parser) {
parser.addArgument("--loglevel")
.required(false)
.type(String.class)
.dest("loglevel")
.choices("OFF", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE", "ALL")
.setDefault("INFO")
.help("Set Log Level.");
parser.addArgument("--logname")
.required(false)
.type(String.class)
.dest("logname")
.help("Write log to given file.");
parser.addArgument("--config-file")
.required(false)
.type(String.class)
.dest("configfile")
.help("Use given config file instead of the default config file.");
}
}
......@@ -52,8 +52,8 @@ public class BundleManager {
}
public void setLanguage(Class<?> clazz){
String language = VadereConfig.getConfig().getString("language", null);
Locale locale =defaultLocale;
String language = VadereConfig.getConfig().getString("Messages.language", null);
Locale locale = defaultLocale;
if (language != null) {
switch (language) {
case "de":
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment